API reference
Compile a Cypher pattern over your PostgreSQL schema into one parameterized SELECT that returns the primary keys of one node type.
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",
),
],
)
q = shop.to_sql(
"MATCH (c:Customer) RETURN c",
)
print(q.params, q.columns)
Semantics, collation, limits and the full error catalog: api-semantics.
The Python API
Declare once
Node(label, *, table, key, properties=None)
| Parameter | Type |
|---|---|
label |
str |
table |
str |
key |
str | tuple |
properties |
mapping | None |
Edge(type, source, target, *, ...)
| Parameter | Type |
|---|---|
source_columns |
str | tuple | None |
target_columns |
str | tuple | None |
table |
str | None |
properties |
mapping | None |
key |
str | tuple | None |
Column(name, type)
| Parameter | Type |
|---|---|
name |
str |
type |
PropertyType |
Schema(*, nodes, edges=(), limits=Limits())
| Parameter | Type |
|---|---|
nodes |
iterable |
edges |
iterable |
limits |
Limits |
Limits(**bounds) — the seven fields and their defaults are in Limits.
Declare once, infer the rest. A Node names its table, primary key and queryable properties; a Column renames one ({"price": Column("price_cents", int)}). A key column does not need to be listed in properties to be selected or joined; list it when you want n.key in a predicate. An Edge names the columns that hold each end's key: source_columns alone is a foreign key in the target's table, target_columns alone the reverse, and both plus table a join table. Schema validates every declaration, copies it, and stays immutable.
Edge(key=...) names one edge row (default: the distinct source then target columns, so no edge matches twice); Edge.properties are columns of its table; a type may recur between different label pairs.
Schema- class
Node,Edge,Column- classes
NodeType,EdgeType- protocols
PropertyType- type alias
Limits- class
SQLQuery- frozen dataclass
TemplateLike- protocol
Cypher2SQLError- base exception
Schema is the only compiler: it accepts any objects with the read-only attributes of NodeType and EdgeType (structural typing.Protocols, so an ORM adapter can satisfy them), and Node/Edge are the shipped implementations. NodeType needs label, table, key and properties; EdgeType requires type, source, target, table, source_columns, target_columns, key and properties. PropertyType is the eight Python types a property may have: str, int, float, bool, decimal.Decimal, datetime.date, datetime.datetime and uuid.UUID. Limits bounds compilation of untrusted queries (details).
Schema.to_sql
schema.to_sql(cypher, params=None) -> SQLQuery
| Parameter | Type |
|---|---|
cypher |
str or TemplateLike |
params |
mapping or None |
to_sql is pure: it never opens a connection, and the same input always produces byte-identical SQL. params supplies $name values (extras are ignored); every value is bound, never placed in the SQL text. The result is the returned node's key set, each key once, and is unordered unless the query orders it. A $param must fit the declared property type, or ParameterError names the parameter and the type — never the value. A label/type selector is the one exception; see Selector parameters.
SQLQuery
| Attribute | Meaning |
|---|---|
sql |
one SELECT, no trailing semicolon, positional %s placeholders |
params |
one value per %s, in textual order |
columns |
the target node's key columns, in key order |
len(q.params) == q.sql.count("%s"), and sql is generated text, never caller input. Pass q.params even when empty: it runs with psycopg 3 conn.execute, psycopg 2 cur.execute, Django RawSQL and SQLAlchemy exec_driver_sql.
to_template() builds a PEP 750 Template from the same SQL and params, for nesting into a psycopg ≥ 3.3 t-string; it needs Python 3.14.
q = shop.to_sql(
"MATCH (c:Customer {country: $country}) RETURN c",
{"country": "FR"},
)
print(q.to_template().values, q.params)
Selector parameters
A $param may stand where a label or relationship type is written: (x:$kind) and -[:$rel]->. The selector is resolved against the Schema while compiling; the result is exactly the SQL for the named label or type, so prepare one statement per declared name. Only declared names are accepted, and one name per pattern element: a list raises UnsupportedCypherError. Property values remain ordinary %s parameters. A rejected selector value is echoed truncated to 63 bytes and escaped, so the error can name the declaration it should have been; it never enters SQL text.
template = "MATCH (x:$kind) RETURN x"
for kind in ("Customer", "Order"):
print(shop.to_sql(template, {"kind": kind}).sql)
Errors
Cypher2SQLError base of everything raised on purpose
├── SchemaError Schema(...) or a declaration (Node/Edge/Column/Limits) was rejected
└── QueryError to_sql(...) rejected a query; .reason .line .column .span .hint
├── CypherSyntaxError the text is not valid Cypher
├── CypherSemanticError unknown label, type, property or variable; ambiguity; misuse
├── UnsupportedCypherError valid Cypher that cypher2sql does not compile (writes, a returned optional variable, `WITH`/an aggregate inside `EXISTS`, ...)
├── ParameterError a $param is missing, has an unsupported property type, misfits its property or its IN list, or is a label/type selector naming an undeclared label/type (in that selector position a list or tuple raises UnsupportedCypherError)
└── LimitExceededError a Limits field was exceeded
QueryError attributes: reason: str (one line), line/column: int (1-based), span: tuple[int, int] (0-based [start, end) offsets into the query), hint: str | None. str(error) is the reason and position, the offending line with carets under the span, and the hint. The error catalog pins one representative trigger per documented message and covers every concrete exception type.
Feature parity with Neo4j
cypher2sql reads the same graph patterns as Neo4j but compiles them against a relational schema and returns keys, not records. The bands below separate what means the same, what is deliberately different, and what 0.1.0 refuses.
Supported (same meaning)
| Capability | Notes |
|---|---|
MATCH |
labels, relationship types, direction, property maps |
WHERE |
comparisons, AND/OR/XOR/NOT, IS [NOT] NULL, n:Label |
RETURN a node variable |
its key columns are selected; see the Output shape row under Different flavor |
EXISTS { ... }, pattern predicates |
correlated existence checks; the body is MATCH/WHERE (a trailing RETURN <literal> changes nothing), with no OPTIONAL MATCH, WITH or aggregation |
IN |
list literal or one list $param, Cypher NULL rules |
STARTS WITH, ENDS WITH, CONTAINS |
case-sensitive substring predicates, never LIKE |
DISTINCT |
deduplicates the key list |
| Null semantics | three-valued logic |
| Relationship uniqueness | one path never reuses a relationship row |
| Bounded variable-length | [*a..b], *n, *..b, *0..0 |
SKIP, LIMIT |
integer literal or $param, bound as %s::bigint |
$parameters |
values are bound, never SQL text |
Supported, different flavor
| Capability | Notes |
|---|---|
| Output shape | a primary-key set, not records |
| Schema | static Python declarations, no server-stored labels or introspection |
Untyped -- |
any declared edge, else the shortest inferred path (an extension) |
=~ |
PostgreSQL POSIX ARE, not Java |
| String comparison and ordering | code point via COLLATE "C" |
| Path depth and uniqueness | trail-based, bounded by max_path_length/open_path_length |
| Parameters | compile-time selectors for names, server parameters for values |
| t-string queries | str or a t-string on Python 3.14 |
WITH |
whole variables only |
OPTIONAL MATCH |
missing variables read as NULL, but cannot be returned |
ORDER BY |
the returned variable's keys only |
| Open-ended paths | need Limits(open_path_length=N) |
Not supported in 0.1.0
Each construct in the table below is valid Cypher that this compiler refuses with UnsupportedCypherError and a hint, never a bare syntax error; the alternative is usually one query away.
| You write | Why it cannot compile | Do this instead |
|---|---|---|
RETURN *, RETURN n.name, RETURN n, m, a relationship or a path |
the result is one node type's key set, not a projection | return the node variable alone; its key columns are selected for you |
RETURN count(*), RETURN sum(o.total) |
the result is a key set, not a number | return the node variable and count its keys around the SQL (len(rows), or SELECT count(*) FROM (...)) |
size(p.sku), date(), datetime(), duration() |
a function call builds a value, and temporal values are not part of the query language here | filter with comparisons, AND/OR/NOT, IS [NOT] NULL and pattern predicates; compare a stored temporal column with a value |
RETURN p[0], RETURN p[0..2] |
a key set has no elements or length | return the variable; read the pieces you need alongside its keys |
[x IN xs \| x], [(a)-->(b) \| b] |
it builds a value, and the result is keys | ask the question with a pattern predicate or EXISTS { MATCH ... } in WHERE, then return the variable |
a property, aggregate or function in WITH; WITH * |
WITH keeps exactly the whole variables you list |
name them: WITH a, b, and filter with WHERE |
ORDER BY, SKIP or LIMIT inside WITH |
the result is an unordered key set until RETURN orders and pages it |
filter with WHERE; order and page after RETURN |
ORDER BY o.name, ORDER BY o + 1, ORDER BY o, p |
the result is a key set, not a projection | order by the returned variable alone, e.g. ORDER BY o |
MATCH p = (…)->(), RETURN p |
a path is not a key set; path values are not supported in 0.1.0 | return the node variable; ask path questions with a pattern predicate or EXISTS { MATCH ... } |
CASE WHEN … THEN … ELSE … END |
the result is a key set, so there is no value to compute | filter with comparisons and AND/OR/NOT, or compute the CASE around the SQL |
{a: 1} as a value |
a map is not one of the declared property types, and the result is keys | compare one property at a time (n.a = 1), or query a JSON column in your own SQL |
UNWIND $rows AS row |
UNWIND emits rows, not one node type's keys |
filter a property with IN (a list literal or one list $param), or compile one query per value |
UNION, UNION ALL |
two result sets are not one key set | compile one query per pattern and union their keys in your own SQL |
CALL { ... }, CALL db.labels() |
procedures and subqueries change the row stream | compile the question as one pattern; run procedures with your own SQL |
FOREACH (x IN xs \| SET ...) |
writes are not compiled | run the write loop with your own SQL |
CREATE, MERGE, SET, DELETE, REMOVE |
the compiler reads one node type's keys: it never writes | run writes with your own SQL |
Multi-label nodes (n:A:B) are not in the catalog but are also refused: a second label raises CypherSemanticError naming the label, because each node has exactly one label here. Write one label per pattern element.
Different flavor
| Capability | What it does differently, why, and what to do |
|---|---|
| Output shape | Returns one row per primary-key tuple of the returned node, not records with properties. The SQL is one SELECT of keys and composes with your own SQL: filter with WHERE, then read the columns you need around the query. Cost: no RETURN n.name, count(*), CASE, map or list values. |
| Schema | Labels, types and properties live in your Python declarations, not in the database, and there is no server introspection. That is what keeps compilation pure and every identifier checked: change the declaration when the DDL changes. Cost: schema drift is yours to manage, and CALL db.labels() has no equivalent. |
Untyped -- |
Neo4j's -- is one relationship; here it first matches any declared edge joining the two endpoints, then falls back to the shortest declared path up to max_path_length (an extension). A relational schema often has no direct foreign key between the nodes you care about. Name the type for a single hop; the emitted SQL shows the path, and max_inferred_paths bounds ambiguous ones. |
=~ |
Patterns are PostgreSQL's native POSIX ARE, not Java regex: \d, \w, classes and alternation work, while Java-only constructs such as \Q…\E do not. PostgreSQL evaluates the pattern where the data is. Escape metacharacters with a backslash and test on PostgreSQL; a pattern it cannot parse raises InvalidRegularExpression at execution, never in the SQL text. |
| String comparison and ordering | Cypher specifies Unicode code-point order; cypher2sql pins it with COLLATE "C", so PostgreSQL's locale collation cannot change results. Neo4j's JVM implementation can differ outside the BMP for astral characters. Add a matching COLLATE "C" expression index or declare the column COLLATE "C"; otherwise a plain btree cannot serve the pinned comparison. |
| Path depth and uniqueness | One path never reuses a relationship row, as in Cypher; recursive walks carry the rows they read in a trail. Every path is finite: a bound is capped by max_path_length, and an open-ended * resolves to open_path_length before planning. Set open_path_length when you write */*a..; raise max_path_length for longer walks. Cost: a chain beyond the bound is cut silently, and two variable-length occurrences of one declared edge are refused. |
| Parameters | $kind/$rel are compile-time selectors resolved against the schema; only values stay server parameters. This keeps identifiers inside your declarations. Prepare one statement per label/type; a list of names is refused. A plan cache therefore sees one statement per shape, as it would for separate literal queries. |
| t-string queries | A query is a str with a params dict, or on Python ≥ 3.14 a t-string whose {expr} values are bound with no dict. t-strings keep values from being confused with query text, and to_template() lets the compiled SQL be nested in another t-string. Use $param on older Pythons; execute a template with psycopg ≥ 3.3. Cost: the t"..." syntax itself needs 3.14, and {x!r}/{x:>5} are refused. |
WITH |
WITH re-scopes and renames whole variables only, because the result is a key set and there is nothing to project. List the variables (WITH a, b, WITH a AS x) and filter with WHERE. Cost: no aggregation, property projection, WITH *, or ORDER BY/SKIP/LIMIT inside WITH. |
OPTIONAL MATCH |
It keeps required rows, and later predicates read the optional side as NULL, but a variable it introduces cannot be returned: a NULL row is not a key set. Return the required variable and test with IS NULL, a pattern predicate or EXISTS. Why: the result is one node type's key set. Cost: no RETURN b for an optional (a)-[:PLACED]->(b). |
ORDER BY |
Sorts by the returned variable's key columns, and DESC reverses all of them. Ordering a key set is well-defined, while ordering by a value would require returning it. Use ORDER BY o, then page after RETURN. Cost: no property, expression or multiple-variable ordering, and rows are non-deterministic without it. |
| Open-ended paths | * and *a.. are not unbounded: they resolve to Limits(open_path_length=N), because a walk that never stops is not a query. Set the limit and read the result as "reachable within N hops". Cost: longer chains are cut silently rather than returning every depth. |