API semantics
Back to the API reference. Collation, ordering, property types, t-strings, limits, and the full error catalog.
from cypher2sql import Edge, Node, Schema
customer = Node(
"Customer",
table="customer",
key="id",
properties={"country": str},
)
order = Node(
"Order",
table="order",
key="id",
)
shop = Schema(
nodes=[customer, order],
edges=[
Edge(
"PLACED",
customer,
order,
source_columns="customer_id",
),
],
)
Strings and collation
Cypher compares and orders strings by Unicode code point, never by your column's or database's collation. Every comparison that looks at characters pins that order with COLLATE "C".
| You write | How the strings are compared |
|---|---|
c.country = $x, <>, <, <=, >, >= |
code point, pinned with COLLATE "C" |
c.country IN $codes, IN ['FR', 'DE'] |
each element compared under COLLATE "C" |
STARTS WITH, ENDS WITH, CONTAINS |
PostgreSQL string functions on the pinned column |
=~ |
POSIX ARE, whole string, pinned |
| a pattern link | code point when either key column is declared str |
| a variable-length walk | state, endpoint and trail pinned for declared text keys |
A pattern link compares by code point when either of its key columns is declared a str property: one declared side pins the comparison, and a declared node key pins both sides. A column you do not declare has no declared type, so when nothing else pins it its own collation decides. A str property in a case-insensitive, ICU or nondeterministic collation therefore cannot change which rows match or the order keys return in: c.country = 'FR' matches FR and never fr.
A plain btree index on a non-C text column cannot serve country COLLATE "C" = %s. Keep those comparisons index-served with a matching expression index (CREATE INDEX customer_country_c ON customer (country COLLATE "C")) or declare the column COLLATE "C"; a pinned pattern link may need both sides indexed. See the collation trap.
Ordering and paging
ORDER BY v orders the returned variable's key columns in key order; a bare item is ascending, and DESC reverses every key column. The result is unordered unless the query says otherwise. ORDER BY on a property, another variable or an expression raises UnsupportedCypherError, because the result is a key set, not a projection. DISTINCT deduplicates the keys first, then the order and the page apply to that list.
SKIP and LIMIT take an integer literal or a $param, and either binds as one %s::bigint parameter. SKIP becomes OFFSET, LIMIT becomes FETCH FIRST … ROWS ONLY, and neither value enters the SQL text. LIMIT 0 returns no row. A negative or out-of-bigint literal is a CypherSyntaxError; a negative, oversized or non-int $param is a ParameterError naming the parameter and never its value.
q = shop.to_sql(
"MATCH (c:Customer)-[:PLACED]->(o:Order) RETURN o ORDER BY o DESC SKIP $skip LIMIT $limit",
{"skip": 10, "limit": 5},
)
print(q.sql)
print(q.params, q.columns)
SELECT n2."id"
FROM "order" AS n2
WHERE EXISTS (
SELECT 1
FROM "customer" AS n1
WHERE n2."customer_id" = n1."id"
)
ORDER BY n2."id" DESC
OFFSET %s::bigint
FETCH FIRST (%s::bigint) ROWS ONLY
(10, 5) ('id',)
OFFSET's cast needs no parentheses because it takes a full expression; FETCH FIRST takes only a c_expr, so its %s::bigint is parenthesised. Both clauses bind one %s::bigint.
Mixing property types
| Type | PostgreSQL type and binding |
|---|---|
str |
text |
int |
bigint; a finite fractional or out-of-int64 float value binds as numeric |
float |
double precision |
bool |
boolean |
decimal.Decimal |
numeric |
datetime.date |
date |
datetime.datetime |
timestamptz |
uuid.UUID |
uuid |
A $param must fit the property's type (and None always fits): a str with no NUL or surrogate; an int that is not bool and fits int64 (a finite float also fits); a float or fitting int for a float, including ±infinity and NaN as in Cypher; a bool; a fitting int, NaN or finite Decimal for a Decimal (≤ 131072 digits before the point and ≤ 16383 after — PostgreSQL's limits; no infinities); a date (not a datetime); a datetime (aware or naive, read in the session zone); or a UUID. A finite float compared with an int property binds as its exact int when integral and in int64, else a Decimal; an int compared with a float property binds its nearest float, and =/<> bind no placeholder when no double equals it. A $param for IN is a list/tuple of those values and binds as one array (%s::text[]); a scalar where a list is expected raises ParameterError.
A float property never compares with an int or Decimal property in 0.1.0: PostgreSQL rounds the pair through double precision, and no exact cast exists. Compare each property with a value, or store both in one exact numeric type. The error names the Cypher properties, even when their columns are renamed:
from cypher2sql import Column, Node, Schema, UnsupportedCypherError
product = Node(
"Product",
table="product",
key="sku",
properties={"price": Column("price_cents", int), "weight": Column("weight_grams", float)},
)
mixed_types = Schema(nodes=[product])
try:
mixed_types.to_sql("MATCH (p:Product) WHERE p.price = p.weight RETURN p")
except UnsupportedCypherError as error:
print(error)
print(mixed_types.to_sql("MATCH (p:Product) WHERE p.price = 900 AND p.weight = 0.9 RETURN p").sql)
cannot compare float property weight with int property price exactly (line 1, column 25)
MATCH (p:Product) WHERE p.price = p.weight RETURN p
^^^^^^^^^^^^^^^^^^
hint: PostgreSQL compares the pair through double precision, which rounds values that need more than 53 bits; compare each property with a value, or store both in columns of one exact numeric type (e.g. numeric)
SELECT n1."sku"
FROM "product" AS n1
WHERE n1."price_cents" = %s::bigint
AND n1."weight_grams" = %s::double precision
t-string queries
On Python ≥ 3.14 a query may be a t-string: a stdlib string.templatelib.Template, or any object satisfying the public TemplateLike protocol (.strings/.interpolations; structural, no import). Each interpolation becomes a bound parameter, text comes from .strings (never re-parsed from values), and the query takes no params. A $name left in template text is a ParameterError whose hint says use {name}. The structural object works on every version; only the t"..." syntax needs 3.14. An interpolation in a label, type, property-name or variable position is refused; a conversion (!r) or format spec (:>5) is refused at its position. Double literal braces ({{/}}) are text.
q = shop.to_sql("MATCH (c:Customer {country: $country}) RETURN c", {"country": "FR"})
print(q.params, q.columns)
country = "FR"
q = shop.to_sql(t"MATCH (c:Customer {{country: {country}}}) RETURN c")
print(q.params, q.columns)
Limits
| Field | Default and meaning |
|---|---|
max_query_length |
10_000; characters of Cypher text (a template's joined text plus interpolation slots) |
max_nesting |
32; depth of parentheses, NOTs, operators and subqueries |
max_pattern_size |
32; node + relationship patterns, summed over a join-tier [*a..b]; a recursive walk or an untyped bound is not charged |
max_path_length |
8; longest upper bound [*a..b], typed or untyped, and longest inferred untyped path |
max_inferred_paths |
32; shortest declared paths inferred for one untyped -- |
max_edge_branches |
32; declared-edge branches one untyped [*a..b] walk may union |
open_path_length |
None; depth an open-ended */*a.. resolves to; unset raises, and it must not exceed max_path_length |
The hint names the field to raise; raise it on the same Schema and the same query compiles:
from cypher2sql import LimitExceededError, Limits
nested_query = "MATCH (c:Customer) WHERE (((c.country = 'FR'))) RETURN c"
tight = Schema(nodes=[customer, order], limits=Limits(max_nesting=2))
try:
tight.to_sql(nested_query)
except LimitExceededError as error:
print(error)
roomier = Schema(nodes=[customer, order], limits=Limits(max_nesting=3))
print(roomier.to_sql(nested_query).sql)
nesting is deeper than max_nesting (2) (line 1, column 28)
MATCH (c:Customer) WHERE (((c.country = 'FR'))) RETURN c
^
hint: raise Limits(max_nesting=...) or simplify the parentheses
SELECT n1."id"
FROM "customer" AS n1
WHERE n1."country" COLLATE "C" = %s::text
Error catalog
Every message below is pinned by tests/test_error_catalog.py: the type, a stable case id (its pytest id), the hint shape (none, or a regular expression), and an example that also runs in the test suite. The examples share the schema declared at the top of this page.
| Type | Case | Hint | Example |
|---|---|---|---|
CypherSyntaxError |
expected-token |
none | shop.to_sql("MATCH (c:Customer RETURN c") |
CypherSemanticError |
unknown-label |
^did you mean :Customer\?$ |
shop.to_sql("MATCH (c:Custmer) RETURN c") |
CypherSemanticError |
unknown-property |
^did you mean country\?$ |
shop.to_sql("MATCH (c:Customer {countri: 'FR'}) RETURN c") |
CypherSemanticError |
unknown-variable |
^declare it in MATCH$ |
shop.to_sql("MATCH (c:Customer) RETURN x") |
CypherSemanticError |
ambiguous-node-type |
^add a label$ |
shop.to_sql("MATCH (c) RETURN c") |
CypherSemanticError |
unknown-relationship |
^relationship types: :PLACED$ |
edged.to_sql("MATCH (c:Customer)-[:LIKES]->(o:Order) RETURN c") |
UnsupportedCypherError |
unsupported-write |
^run writes with your own SQL$ |
shop.to_sql("CREATE (c:Customer {name: 'Ada'})") |
UnsupportedCypherError |
unsupported-order |
^the result is a key set: order by |
shop.to_sql("MATCH (c:Customer) RETURN c ORDER BY c.name") |
UnsupportedCypherError |
mixed-property-types |
^PostgreSQL compares the pair through double precision |
mixed.to_sql("MATCH (p:Product) WHERE p.price = p.weight RETURN p") |
ParameterError |
missing-parameter |
^pass it in params: to_sql |
shop.to_sql("MATCH (c:Customer {country: $country}) RETURN c") |
ParameterError |
parameter-type |
^pass a str with no NUL or surrogate$ |
shop.to_sql("MATCH (c:Customer {country: $country}) RETURN c", {"country": b"SECRET"}) |
ParameterError |
selector-unknown-label |
^labels: :Customer, :Order$ |
shop.to_sql("MATCH (c:$kind) RETURN c", {"kind": "Xyzzy"}) |
LimitExceededError |
query-too-long |
^raise Limits\(max_query_length=\.\.\.\) or send a shorter query$ |
limited.to_sql("MATCH (c:Customer) RETURN c") |
LimitExceededError |
nesting-too-deep |
^raise Limits\(max_nesting=\.\.\.\) or simplify the parentheses$ |
nested.to_sql("MATCH (c:Customer) WHERE (((c.name = 'x'))) RETURN c") |
LimitExceededError |
pattern-too-large |
^raise Limits\(max_pattern_size=\.\.\.\) or write a shorter pattern$ |
limited_pattern.to_sql("MATCH (c:Customer)-[:PLACED]->(o:Order) RETURN c") |
SchemaError |
edge-no-side |
none | Edge("PLACED", customer, order) |
SchemaError |
invalid-identifier |
none | Node("a" * 4096, table="t", key="id") |
SchemaError |
duplicate-label |
none | Schema(nodes=[customer, customer]) |
SchemaError |
limits-not-positive |
none | Limits(max_query_length=0) |
from cypher2sql import Column, Cypher2SQLError, Edge, Limits, Node, QueryError, Schema
def show_error(run):
try:
run()
except Cypher2SQLError as error:
reason = error.reason if isinstance(error, QueryError) else str(error)
print(f"{type(error).__name__}: {reason}")
show_error(lambda: shop.to_sql("MATCH (c:Customer RETURN c"))
show_error(lambda: shop.to_sql("MATCH (c:Custmer) RETURN c"))
show_error(lambda: shop.to_sql("MATCH (c:Customer {countri: 'FR'}) RETURN c"))
show_error(lambda: shop.to_sql("MATCH (c:Customer) RETURN x"))
show_error(lambda: shop.to_sql("MATCH (c) RETURN c"))
placed = Edge("PLACED", customer, order, source_columns="customer_id")
edged = Schema(nodes=[customer, order], edges=[placed])
show_error(lambda: edged.to_sql("MATCH (c:Customer)-[:LIKES]->(o:Order) RETURN c"))
show_error(lambda: shop.to_sql("CREATE (c:Customer {name: 'Ada'})"))
show_error(lambda: shop.to_sql("MATCH (c:Customer) RETURN c ORDER BY c.name"))
product = Node(
"Product",
table="product",
key="sku",
properties={"price": Column("price_cents", int), "weight": Column("weight_grams", float)},
)
mixed = Schema(nodes=[product])
show_error(lambda: mixed.to_sql("MATCH (p:Product) WHERE p.price = p.weight RETURN p"))
show_error(lambda: shop.to_sql("MATCH (c:Customer {country: $country}) RETURN c"))
show_error(lambda: shop.to_sql("MATCH (c:Customer {country: $country}) RETURN c", {"country": b"SECRET"}))
show_error(lambda: shop.to_sql("MATCH (c:$kind) RETURN c", {"kind": "Xyzzy"}))
limited = Schema(nodes=[customer, order], limits=Limits(max_query_length=10))
nested = Schema(nodes=[customer, order], limits=Limits(max_nesting=2))
limited_pattern = Schema(nodes=[customer, order], limits=Limits(max_pattern_size=1))
show_error(lambda: limited.to_sql("MATCH (c:Customer) RETURN c"))
show_error(lambda: nested.to_sql("MATCH (c:Customer) WHERE (((c.name = 'x'))) RETURN c"))
show_error(lambda: limited_pattern.to_sql("MATCH (c:Customer)-[:PLACED]->(o:Order) RETURN c"))
show_error(lambda: Edge("PLACED", customer, order))
show_error(lambda: Node("a" * 4096, table="t", key="id"))
show_error(lambda: Schema(nodes=[customer, customer]))
show_error(lambda: Limits(max_query_length=0))
from cypher2sql import ParameterError
try:
shop.to_sql("MATCH (c:Customer) RETURN c SKIP $skip", {"skip": -1})
except ParameterError as e:
print(e)
parameter $skip must be non-negative (line 1, column 34)
MATCH (c:Customer) RETURN c SKIP $skip
^^^^^
hint: a page value is zero or more
SchemaError messages start with the declaration (Schema, Node Customer, Edge PLACED (Customer -> Order), Column price or Limits). Every declared name in one is escaped and cut to the same 63-byte budget, and the whole message is one line of at most 200 characters. Node, Edge and Column raise it for: an edge naming neither side, both without table, or one plus table; column counts differing from the referenced key; an empty key, label or type; an unsupported property type; a table/column name that is empty, over 63 UTF-8 bytes, has NUL or %, or is not valid UTF-8 text; and a label or type name held to those same identifier rules. Schema re-checks it all and adds duplicate labels, a duplicate edge type between the same node types, an endpoint not in nodes, and a non-positive or missing limit (every Limits field, max_edge_branches included).