Skip to content

Design

Internals for contributors; the user contract is docs/tutorial.md + docs/api.md.

Pipeline

to_sql(str | TemplateLike) → parse → AST with spans → bind (+ Schema) → IR → plan → relational plan → emit → SQLQuery

to_sql accepts str | TemplateLike, where TemplateLike is the public @runtime_checkable protocol in _template.py over read-only .strings/.interpolations (never a static string.templatelib import; floor 3.12): each interpolation becomes one AST Param in source order. A real Template satisfies it structurally. Interpolations are a structural token list (strings plus Param indices), never a sentinel in the text and never joined values; errors render {expr}, never the value. Before the AST, the front-end checks len(.strings) == len(.interpolations) + 1 (else TypeError) and len(text) + interpolation count <= max_query_length (else LimitExceededError); values follow the $param rules.

Module Owns Never
__init__.py re-exports + __all__ logic
_schema.py, _limits.py Node, Edge, Column, Schema, protocols, Limits, validation, to_sql orchestration SQL text
_errors.py exceptions, caret formatting, "did you mean" (edit distance ≤ 3, ties by name; every name hint bounded by bounded_names within 63 bytes), escaped query line —
_template.py the public TemplateLike protocol (structural .strings/.interpolations, no templatelib import) tokens/SQL
_unsupported.py the canonical refused-construct table, its hints and the generated API table parsing
_lexer.py, _parser/ (_base, _grammar, _clauses), _ast.py text → AST, syntax errors, max_query_length, max_nesting schema lookups
_bind/ (_base, _values, _edges, _patterns, _build, _predicates, _binder, _names), _ir.py name resolution, type inference, param typing, semantic errors, max_pattern_size, max_edge_branches SQL text
_infer.py inferred untyped paths: label BFS distance, shortest-path DAG count and walk, max_path_length/max_inferred_paths diagnostics SQL text
_compare.py value-vs-value numeric comparison, fitting and folds SQL text
_plan/ (_nodes, _scopes, _uniqueness, _working, _groups, _rows, _planner) IR → relational plan: aliases, EXISTS groups, join order, predicate placement, WITH RECURSIVE walks SQL text
_emit.py plan → text + params; the only identifier quoting and %s producer decisions

Stages are pure functions over frozen, slotted dataclasses dispatched with match; a AND b AND c parses to n-ary nodes and every recursive descent is counted, so tree depth is ≤ max_nesting.

One stage, one module family. parse, bind and plan are packages whose __init__ re-exports the stage's entry point (parse / bind / plan, plus the plan's node types), while each member owns one part of that stage: in _parser, __init__ is the entry point (parse, which closes the operator-nesting budget), _base the parser state and token access (with the recursive-descent nesting guard), _grammar the patterns, expressions and EXISTS bodies, _clauses the clauses in order; in _bind, _base holds the binder state and schema lookups, _values property values, _edges path arithmetic, _patterns edge and label resolution, _build path → IR, _predicates conditions and EXISTS bodies, _binder clause order, _names the bounded name hints; in _plan, _nodes the plan dataclasses, _scopes the row-scope and reference queries over bound IR, _uniqueness the row-identity rules, _working the planner's shared element/unit types, _groups EXISTS groups, _rows aliases, uniqueness and projections, _planner the outer SELECT. Outside a family only its __init__ is imported (_schema calls parse/bind/plan, _emit reads plan nodes), so moving a member never crosses a stage boundary.

  • AST (_ast.py), each node has span: Span (0-based [start, end)): Query(clauses); Match(paths, where, optional), With(items, where, distinct) (WithItem(name, alias) is one whole variable, optionally renamed), Return(var, distinct, order: OrderItem | None, skip: Page | None, limit: Page | None) (OrderItem(var, direction: SortDirection) is the one returned variable and ASC/DESC; Page(keyword, value) holds an integer Lit or a Param, so a negative literal reaches the binder for its own refusal), Create(paths) (TCK fixtures only; binder rejects); Path(elements) of NodePat(var, labels, props) / RelPat(var, types, direction, length, props), where length is a Length(min, max, span) hop bound (max is None for an open-ended *a..); expressions Lit, Param, Var, Prop, Cmp, ListLit(items), In(left, items) (items is a ListLit or the Param holding the whole list), StringPredicate(op, left, right) (op is StringOp.STARTS_WITH | ENDS_WITH | CONTAINS), Regex(left, pattern), And, Or, Xor, Not, IsNull, HasLabel, PatternPredicate(path, span) and ExistsSubquery(clauses, span) (ExistsMatch(paths, where, span) is one [MATCH] paths [WHERE ...] clause of a subquery body; a trailing RETURN <literal> is parsed and dropped); other keywords → UnsupportedCypherError.
  • Bound IR (_ir.py): Bound(target, nodes, rels, inferred, recursive, trails, where: BExpr, values: tuple[object, ...]); BNode(id, node_type); BRel(id, edge_type, left, right, orientations ⊆ {forward, backward}, carrier, declared); BInferred(left, right, alternatives: tuple[BPath, ...]) is a relationship with no single declared edge of its own — an untyped --'s shortest declared paths, or a join-tier [*a..b]'s one chain per length (an empty chain is the zero-hop alternative); BRecursive(left, right, edge_type, min_depth, max_depth, base, steps) is one WITH RECURSIVE walk of one declared edge — the orientations its first hop and its later hops may take, and the deepest hop count that lands on the right endpoint; BUntypedRecursive(left, right, min_depth, max_depth, base, steps) is the same walk with no type, over BHop(tag, edge_type, orientation) values: tag names the declared edge (both orientations share it), base holds every hop leaving the left label at depth one, and steps every hop leaving a label the walk can stand on before its last hop, pruned to those that can still reach the right endpoint. BWalk = BRecursive | BUntypedRecursive; BTrail(rels, expansions, recursions) is one path's relationship occurrences — relationship uniqueness is per path, and two occurrences in one trail may not bind the same row; BScope(index, optional, nodes, rels, inferred, recursive, trails, properties, where) is one clause from the first OPTIONAL MATCH on that declares elements of its own; BExists(nodes, rels, inferred, recursive, trails, properties, where, refs, groups, number) is one pattern bound inside a predicate, never fetched: its own elements, what it reads from outside (refs are the outer column owners, relationship endpoints included; groups the optional scopes whose presence it names) and its bind-order number, which names its reach<i> walks; BExpr = Col(owner, column, pg_type), Value(index, pg_type), Const(TRUE | FALSE | NULL | NAN), Present(scope index), NaN(pg_type), Cmp, BArray(index, pg_type) (one caller list at values[index], cast to <pg_type>[]), BIn(column, values: BArray), BString(op: BStringOp, column, operand), BRegex(column, pattern: BValue), And, Or, Xor, Not, IsNull, Fold(guard, negated), NullWhen(guard, operand) (a pattern predicate over a missing optional variable), Exists(body); literals and $params are Values, n:Label is already Const, And/Or n-ary.
  • Plan (nodes in _plan/_nodes.py, planner in _plan/_planner.py): Select(columns, table, alias, where, laterals=(), walks=(), distinct=False, order=(), offset=None, limit=None). walks are its hoisted recursive walks, written before the SELECT so each is evaluated once per query. where is a conjunction of Conjunct = SqlExpr | Exists | AnyOf | Walk | WalkIn; Exists(group) is one correlated EXISTS, AnyOf the OR of alternative bodies, and Recursive (a typed CTE) and UntypedWalk (an untyped CTE over WalkHop branches) make up Walk = Recursive | UntypedWalk. WalkSource(cte, anchor_cte, alias, anchor, columns, walk) is one hoisted walk: the statement-level recursive entry cte, its non-recursive anchor_cte entry, the alias the walk's left and seed references give that anchor, the anchor's anchor group, the columns it projects, and the walk node the inline plan renders; WalkIn(source) is the target's semi-join into the endpoint set source.cte holds. Projection(name, expr) is one select-list expression and the key name it returns; OrderColumn(operand, descending) is one ORDER BY operand (the target's key columns in key order, a text key wrapped in Collate) and offset/limit are the bound page Placeholders. Join(table, alias, on), CrossJoin; SqlExpr = ColRef(alias, column), Placeholder(value_index, pg_type, array=False), operators, Bool, CaseNull(guard, value), AnyEq(column, values: Placeholder) (membership in one bound array), StringCall(op, column, operand), Regex(column, pattern, negated=False); grows (Optional) with no public change.

Schema model

  • Label ↔ node type ↔ one table. Zero or one label; (n:A:B) is a CypherSemanticError; labels, types and property names match exactly (case-sensitive). Each property has a Python type; fits means its cast type can represent it (api.md table). A misfit $param → ParameterError naming parameter and declared type; an out-of-range number literal → CypherSyntaxError; comparisons Cypher decides alone fold. Declared names follow the identifier rules in the security model and are never truncated to fit.
  • Uniform edge model: (table, source_columns → source.key, target_columns → target.key); an FK names one side, Edge resolves the other, and the planner reuses that node's alias; covers FK edges, join tables, FKs inside composite keys and self-references. Identity is (type, source label, target label); key (default source + target columns) identifies a row for uniqueness.
  • Type inference: declared candidates are constrained by direction to a fixpoint (≤ pattern size rounds); one candidate per element, else cannot tell which node type n is: :Customer or :Order with hint: add a label.
  • Reachability: a named type must resolve to exactly one declared edge between the endpoints (either direction when undirected), else CypherSemanticError. An untyped relationship between labeled endpoints asks the schema graph: a single declared edge joining them in the pattern's direction (either direction when undirected) wins, a deliberate extension of Cypher's single-relationship --; only when none joins them, a node-level BFS over labels follows the declared edges the same way (directed follows the arrow, undirected either), expanding each label once. Two label-level BFS runs, forward from the start and backward from the goal, give the shortest distance and the layered DAG every shortest path runs through; the "shortest path is longer than max_path_length" diagnostic is that distance alone, so no path is walked to report it. The shortest simple paths are counted exactly on the DAG by a dynamic program over its layers (a shortest path uses each label only at its BFS distance, and labels that reach no goal are skipped); the scan is linear in the layers and Python big ints keep the count exact, so the error names the exact number — until CPython's str(int) digit cap, where it names a 10**N bound instead. Above Limits.max_inferred_paths the binder raises LimitExceededError naming that limit and the count instead of truncating, because a dropped alternative would drop rows. Within the cap the paths are walked inside the same DAG: each path is at most max_path_length hops, the step table is schema-sized (one declare-order scan of the edges holds every label's steps, so the label BFS costs labels + edges, not a scan per label), and the walk expands at most one prefix per hop of each emitted path; the tie-break is shortest, then declaration order. Emit one EXISTS per inferred path and OR them (no UNION, no DISTINCT). No path at all → CypherSemanticError whose hint lists the FKs that would relate them; a shortest path longer than the limit → LimitExceededError naming max_path_length.

SQL emission

Two tiers. Hops 1..K (K = Limits.max_pattern_size, the join budget) are a join/EXISTS expansion, and a bounded [*a..b] whose summed hops fit max_pattern_size compiles to it — one alternative per length, each hop a join. Every length's hops are charged, not just the longest: the plan emits one EXISTS per length, so the budget is Σ(2k-1) over the lengths it allows (zero hops adding nothing). A bound whose own summed hops exceed K is compiled by the second tier and is not charged; the pattern's other elements still count, so a query can still exceed the budget with many declared elements or inferred alternatives.

The second tier is one WITH RECURSIVE walk per occurrence: an open-ended */*a.., which Limits.open_path_length resolves first (LimitExceededError when it is unset), any bounded [*a..b] whose hops are above K, and every untyped bound, which has no single declared edge to join. The walk is evaluated once per query, never once per candidate row, when its start is read from the same row scope the statement can compute alone — the common MATCH (x {..})-[*]->(target) shape: the statement opens with WITH RECURSIVE, whose non-recursive anchor1 AS NOT MATERIALIZED entry selects the start row's key (and the trail rows the path already read) and whose reach1 … AS MATERIALIZED entry computes the reachable identities. When the walk's right end is the returned node, the outer WHERE asks whether that node's key is in the endpoint set, so the number of candidate targets cannot multiply the walk's cost. A start bound by an earlier clause still hoists: MATCH (c:C) WITH c MATCH (c)-[*1..3]->(p:P) RETURN p opens with the same anchor and materialized entries. Two shapes stay inline, evaluated per candidate row: the returned node is the walk's own left end (MATCH (p:P)-[*1..3]->(q:Q) RETURN p), or the walk is written inside a pattern-predicate group (MATCH (c:C), (p:P) WHERE (c)-[*1..2]->(p) RETURN c); neither has a statement-level start row to precompute. A typed walk's CTE has one state row per edge row: its two end keys, which end the walk arrived at, and an array of the rows the path already read. Each step leaves the arrived node in an orientation its label allows; the trail comparison (a ROW(key) = ANY (trail) check) is relationship uniqueness, not cycle detection — it compares row identities, so every key column whose declared type is text is pinned to code points ((<col> COLLATE "C")) in the base seed, in the step and in the NOT (… = ANY (trail)) test, exactly as a string comparison is pinned. A key column with no declared text type keeps its own collation. An untyped walk has one state per node it stands on: the current node's label and key encoded as one text value (so keys of different node types can never collide), the hop count, and a trail of tag:key entries — the tag names the declared edge, and both orientations of one edge share it, because they read the same row. Its non-recursive term unions every declared edge the arrow allows that leaves the left label and can still reach the right label before the bound; its recursive term unions every such hop leaving a label the walk may stand on, joined on the current key. A step casts a frontier component back to its typed column only when every hop that can produce that identity — plus the left node's own key, when a hoisted depth-0 row can stand in the frontier — agrees on one producer type, the departing column's carried type equals it, and it is in _EXACT_CASTS (bigint, boolean, uuid, date, timestamptz, whose renderings are faithful keys). Otherwise the comparison is the pinned code-point text, with the edge column cast to text when it is not text: one value and another type's rendering of it can be different text ('01' against 1). Hops that cannot reach the target within the remaining depth are pruned at bind, so the union is the declared edge set the label graph leaves possible, not the whole schema. Cycle safety is the depth counter: a walk stops at open_path_length (or the bound), never by refusing to revisit a row, so cyclic data terminates and repeated nodes stay legal. Depth integers are validated, rejected above the configured bound, and INLINED, never strings from query text; values still travel only in params. Truncation at that depth is silent because a rewrite would change results; a requested bound above max_path_length raises. A *0..b bound ORs the zero-hop key equality with the walk when both ends are one node type — a hoisted walk puts the depth-0 state row inside its CTE instead — and *0..0 never emits one (both sides are the node itself): two ends of different node types are never one row, so that alternative would compare unrelated keys. A walk with no step to make — nothing leaves the end it arrives at, or the bound stops at the first hop — is that one base join as a plain EXISTS, so no recursive term is written for a step that cannot exist. A walk whose right end is the returned node is hoisted out of every row scope and matched to the target once through its endpoint set, whether its start is read from the same clause or an earlier one; a walk whose right end is not the returned node, or that is written inside a pattern-predicate group, stays inline and correlated, so it still composes in one pattern with inferred OR-of-EXISTS alternatives and join-tier expansions. The number of SELECT branches an untyped walk unions (its base hops plus its step hops) is capped by Limits.max_edge_branches, raising LimitExceededError before any SQL is written. Output is the pks of exactly one target type; SQL stays byte-identical for identical input. Known readability gap (#45): a walk's state values and trail tags are opaque in the emitted SQL — an identity is ARRAY[label, key…]::text and a trail tag is a declaration position, so a DBA cannot map either back to the schema without counting Schema.edges; correctness is unaffected.

Shape: the target's table is the only outer FROM, selecting its key columns; every other element is an EXISTS group (each key once, no DISTINCT, a semi-join). Elements linked other than through the target (relationship, WHERE conjunct, uniqueness check) share a group; groups are separate EXISTS; pieces linked only by predicates are CROSS JOINed. Relationship rows are compared once, where both aliases are visible: declared occurrences in their group, an expansion hop against the path's declared occurrences inside each alternative's EXISTS, and a recursive walk seeded with the row each declared occurrence actually binds — its own alias, or its single carrying end's row — which a hoisted walk reads through its anchor entry and an inline one through the enclosing subquery. Two inferred occurrences of one edge type in one path would need one row stream over the whole path, which is not built, so the binder refuses them rather than emitting two walks that could both read the same row.

Optional groups. A query with an OPTIONAL MATCH has several row scopes. The mandatory clauses before the first OPTIONAL MATCH form the pattern every row has; from that clause on, every clause that declares a node, relationship or path of its own is a scope (BScope) — optional for OPTIONAL MATCH, required for MATCH — and a later MATCH that only names earlier variables adds its predicates to the outer WHERE. The pattern's components and then the scopes, in clause order, each become one LEFT JOIN LATERAL (…) AS o<i> ON TRUE in the target's FROM. A clause can only name what earlier clauses declared, so clause order puts every scope after every scope it reads, and a scope renders all of its own relationships, expansions and walks itself: a path is never left for another scope to pick up, and a planner that cannot see an endpoint raises instead of dropping the path. A required body projects TRUE AS "found" and the outer WHERE requires that column, which keeps its semi-join meaning; an optional body projects found plus every column a later scope or predicate names, and a match that finds nothing contributes one all-NULL row instead of rejecting the outer row. A scope's property predicates and its own WHERE live in its body, so an optional one filters that expansion only; predicates outside it read its columns through three-valued logic. BPresent(i) names the presence of the bound scope at position i: TRUE when it matched, NULL when it did not, so a bare optional variable, IS [NOT] NULL on any node or relationship variable the clause declared (a variable-length one included) and b:Label use it, and a NOT keeps NULL as NULL while an inside-WHERE never becomes an outer null-rejecting predicate. It is emitted as o<k>."found", where k is that scope's position among the emitted groups (the pattern's components first, then one per surviving clause) — not i, which indexes the bound scopes. A clause naming an optional variable requires its scope to be present and reads the variable through the projected key columns; a scope whose every element an earlier scope declared (a relationship stored in a row already read, a walk between two bound variables) reads no row of its own and has no FROM. An empty interval (*2..1) in an OPTIONAL MATCH makes that scope its null row (WHERE FALSE). Relationship uniqueness holds between the occurrences of one clause only — a later MATCH may bind a relationship an earlier one bound — and a relationship variable named again in a later clause is refused (UnsupportedCypherError) rather than silently bound afresh. An optional scope nothing outside it reads is pruned before planning: it can neither filter nor project, so it adds no join and no DISTINCT. A surviving unit can turn one target row into several — a required one is a lateral join that may match many rows, and an optional one may too unless the outer WHERE pins it to its null row (o IS NULL) — so a plan with any such unit selects the keys DISTINCT. Keys are a set, so listing DISTINCT whenever a unit might multiply rows is always correct; it is left out only when no required unit survives and every optional one is pinned. A projected column is named <alias>:<column>, or <alias>#<k> when that would pass PostgreSQL's 63-byte identifier limit — a name with no :, so it never meets a real column's. This is one plan node in the existing tier: no new SQL tier, no new Limits field (max_pattern_size already counts every clause's elements). WITH scopes. A WITH is a variable-scope boundary, not a pattern clause: it creates no BScope and no plan node. The binder resolves each item against the names bound so far (one node or relationship variable, optionally renamed by AS), keeps exactly the projected names and drops the rest; a later reference to a dropped name is a CypherSemanticError (unknown variable ..., with a hint that WITH dropped it) whose span is the use. Cypher evaluates the clause's WHERE over the names it projects and the names still bound when it starts (the TCK's WithWhere7 rule), so the binder binds it against that union and then commits only the projected names. Its conjuncts join Bound.where, which the planner renders in the outer WHERE after every lateral: a real filter boundary, never a predicate folded into an optional body. Inside the body b IS NULL would filter the expansion's own rows, match nothing for every target and keep every outer row; the outer conjunct reads the scope's found column and keeps exactly the rows the optional side missed. No second emission tier and no new Bound field is needed: the filter is row-local, so applying it with the other outer conjuncts is equivalent to applying it before a later clause's lateral, and the null-pinning rule in _plan/_rows.py still sees the BIsNull(BPresent(i)) conjunct. WITH DISTINCT is accepted and changes nothing: the result is a key set already. Aggregation, function calls, property projections, WITH *, ORDER BY, SKIP and LIMIT inside WITH are parser refusals (UnsupportedCypherError with a hint), so nothing downstream has to reason about a projected value. Narrowing. The result is a key set, so a variable an OPTIONAL MATCH introduced cannot be the RETURN target, even when a later mandatory MATCH makes it present: the target's row is the outer FROM, and an optional scope cannot hang off the row it is the target of. The binder raises UnsupportedCypherError naming the variable and hints to return the variable the optional side hangs off. Returning a variable that a mandatory clause declared and an optional pattern merely used is fine.

  • Order inside a group: FROM the first non-target element in pattern order, then greedily JOIN the next linked element (ON = that link, new alias on the left). WHERE: links to the outer alias, inline property predicates in pattern order, then other conjuncts; target-only conjuncts stay in the outer WHERE, before EXISTS.
  • Aliases come from positions, never query text: n<i> = i-th node, r<i> = i-th edge needing its own alias, e<i> = the edge row a typed walk reads (its recursive walk, or the one hop it takes when nothing leaves the end it arrives at), e<i><j> = one declared-edge branch of an untyped walk, numbered from one across its base and step hops so no alias repeats, reach<i> = that walk's CTE (a typed walk's state columns are depth, src<i>, dst<i>, trail, plus at_target only when it may traverse either way; an untyped walk's are current, depth, trail, with step<i> naming its union of hop branches), and o<i> = one row scope's LEFT JOIN LATERAL group (the pattern's components first, then one per later clause in clause order); a walk inside a scope continues the query's walk numbering, so no reach<i> repeats. An edge stored in an end's own table reuses that end's alias, unless it is undirected between two different nodes and in a uniqueness check: either end's row may be the edge, so it gets its own r<i>. _schema.quote_ident always quotes table/column names (" doubled), even customer; only our own [ner][0-9]+/step[0-9]+/reach[0-9]+ aliases are bare.
  • Values are %s::<pg_type> placeholders appended while writing (textual order, len(params) == sql.count("%s")). Cast = the compared property's pg_type, else api.md's Python-type table (lists: %s::<type>[]); unfit values raise ParameterError first, with the hint "pass an int in int64 range or a float" for an int/float property and "pass an int or Decimal" for a Decimal property, which takes no float (a literal folds, a $param raises). Cypher's int and float are one domain for a value: an integral float inside int64 against an int property binds as that int and %s::bigint (exact and index-friendly), a finite fractional or out-of-int64 one as Decimal(value) (the double's exact binary value) and %s::numeric, so the bigint column is never rounded; NaN/±infinity fold with no placeholder. An int against a float property is written %s::double precision as float(value); an integer no double equals folds =/<> and orders against its neighbouring double. true/false/null are keywords.
  • Lists, strings, regex: IN over a property is col = ANY(%s::<type>[]) (col as the collated operand below when its declared type is str), one array placeholder, which gives Cypher's answer for NULL and an empty list for free: FALSE matches nothing and no element equal leaves NULL when the column or the list is NULL. An empty list literal is written FALSE; a list literal's elements the column can never equal (another type, NaN) are dropped, and if every one is, the cast is BFold(BIsNull(column)). A $param list is checked element by element before emission — an integral float inside int64 is an int for an int property, a float property takes an int only when a double equals it — and a misfit raises ParameterError naming the parameter and the declared type, never the value. An IN whose left side is not a property is folded in Python to TRUE/FALSE/NULL. STARTS WITH is starts_with((col COLLATE "C"), %s::text), CONTAINS is position(%s::text in (col COLLATE "C")) > 0, and ENDS WITH is right((col COLLATE "C"), length(%s::text)) = %s::text — PostgreSQL 15+ has starts_with but no ends_with (checked on 18), right inherits its input's "C" collation, and the needle is written twice, so it binds twice. =~ is (col COLLATE "C") ~ ('^(?:' || %s::text || ')$'), !~ when its immediate negation is a BNot, so the whole-string POSIX ARE match never depends on the pattern carrying anchors; neither it nor the string functions use LIKE, so %, _ and \ in a value are data. Every one of the four pins the text column with the one Collate node (the same one comparisons and ordering use), a column used as the needle included, and the bound value stays a bare %s::text, so the column's pin decides the comparison and no nondeterministic collation can change the answer. NULL on either side stays NULL; a non-string literal/property operand folds to NULL; a NUL/surrogate literal folds like another unrepresentable string and a $param raises ParameterError. A pattern whose unescaped parentheses are unbalanced, or that starts with a (?flags) group PostgreSQL could apply only outside the anchor wrapper, raises at bind (a $param names itself in a ParameterError, a literal in a CypherSemanticError); any other pattern PostgreSQL cannot parse raises the driver's InvalidRegularExpression at execute. A string predicate or =~ needs a property on the left, else UnsupportedCypherError.
  • Semantics: SQL's three-valued logic matches Cypher for AND/OR/NOT, IS NULL and comparisons (see folds, NaN); XOR is <>. In 0.1.0 every string comparison and ordering is code-point order. Every text column operand of =, <>, <, <=, >, >=, IN, STARTS WITH, ENDS WITH, CONTAINS and =~ is planned as a Collate (col COLLATE "C"), a column used as a string predicate's needle included; a text key declared as a str property is ordered through the same node, in both ORDER BY and its SELECT DISTINCT select-list twin. A bound value keeps its %s::text cast, because the explicit pin on the column decides the comparison. Neither the column's nor the database's collation can then change which keys come back or the order they come in. A non-text operand is never collated. An undirected same-type edge emits (fwd) OR (bwd); (a)-[r]->(a) links both ends; two patterns of one edge get (keys of r1) <> (keys of r2), once, in the group holding both rows (outer WHERE when both are the target's row). A float property never compares with an int or Decimal property in 0.1.0: PostgreSQL's common type for either pair is double precision, which rounds values that need more than 53 bits, and no exact float8→numeric cast exists (PostgreSQL rounds to 15 significant digits), so such a comparison raises UnsupportedCypherError at bind, naming both Cypher properties and the fix: compare each property with a value, or store both in columns of one exact numeric type (e.g. numeric) — a DDL change, since no cast is emitted for a property-vs-property comparison. Same-type numeric pairs and int/Decimal still compare exactly in PostgreSQL.
  • Folds (no placeholder), with N = OR of <col> IS NULL: a literal of another type has = → (N AND NULL) (false on non-null rows, NULL on a NULL row), <> → (NOT N OR NULL), ordering → plain NULL; a NaN value has =/ordering → (N AND NULL), <> → (NOT N OR NULL); a NUL/surrogate string has =/<> the same N-preserving false/true, ordering → UnsupportedCypherError; so NOT (c.country = 5) skips only Alan's NULL. A float value against an int property is not a type mismatch: it binds as an exact number (Values), and ±infinity there is beyond every int64, so ordering folds to its definite answer with only the null-ness kept (< +inf → (NOT N OR NULL), > +inf → (N AND NULL)); a float NaN against an int property folds as NaN does, and so does an int no double equals against a float property (=/<> only).
  • NaN (double precision/numeric): PostgreSQL makes NaN equal itself and above all numbers; Cypher makes comparisons FALSE (<> TRUE). A NaN $param/value has no placeholder (folds above). For a NaN column, col op v: =, <>, <, <= are right; >/>= must preserve NULL — add (v IS NULL OR col <> 'NaN'::<type>), or fold a NaN value per the Folds rule. Column vs column: =/ordering add AND (a <> 'NaN' OR b IS NULL) AND (b <> 'NaN' OR a IS NULL), <> adds OR (a = 'NaN' AND b IS NOT NULL) OR (b = 'NaN' AND a IS NOT NULL); these NULL cases stay NULL. 'NaN' is Const(NAN) text.
  • Ordering and paging: ORDER BY v orders by the target's key columns, in key order, and DESC sets the direction on every one of them (a composite key reverses as a whole). A text key is a Collate operand for both the ORDER BY and, under SELECT DISTINCT, the select list: PostgreSQL requires every distinct order expression to appear in the select list, and decorating only the order side would hide the column from that check. DISTINCT therefore dedupes the key list first, and the order and the page apply to that list. A key column declared as a str property is emitted COLLATE "C" — code-point order, the same rule a string ordering comparison follows — and a key column no property declares has no declared type, so its column's collation decides. SKIP/LIMIT are never inlined: each is one %s::bigint placeholder, in OFFSET then FETCH FIRST … ROWS ONLY (so params follows the query's own SKIP then LIMIT). PostgreSQL's FETCH FIRST grammar takes only a c_expr, which a cast is not, so that one placeholder is parenthesised; OFFSET takes a full expression and is not. A positive literal above 2^63-1 is refused at parse with CypherSyntaxError naming SKIP/LIMIT, a negative literal at bind, a non-int, negative or out-of-int64 $param raises ParameterError naming the parameter, and LIMIT 0 is a valid (empty) page — no Limits field is involved, because the bound is int64 itself. Without ORDER BY, a page is legal and PostgreSQL's row choice is not deterministic, which the docs state rather than hide.
  • Format: keywords upper case; one clause per line; AND continuation indented two spaces; an EXISTS ( body indented two more, ) aligned. Same input → byte-identical text (no set/dict dependence; schema order = declaration order).
Limit Enforced in Why
max_query_length before lexing; for a Template, before AST assembly (joined text + interpolation slots) bounds all later work
max_nesting parser (depth counter in every recursive rule) stack safety for every stage
max_pattern_size binder bounds joins, inference rounds and the join budget K; the declared pattern plus every hop of every length a join-tier expansion stands for (Σ(2k-1)), and every alternative's hops of an inferred untyped path, summed over the whole query. A bound whose own hops are over K is a recursive walk and is not charged; a non-zero untyped bound is one walk and is not charged either
max_path_length binder (_infer.py) the longest upper bound [*a..b] may name, typed or untyped, and the longest inferred untyped path between two labels (either arrow); a shortest path above it raises, naming the distance. A bound past it raises too, before the join budget, whichever tier would compile it
max_inferred_paths binder one untyped relationship's alternative cap (either arrow); the layer DP counts it exactly before any path is walked, and exceeding it raises because keeping only the first N would drop rows
max_edge_branches binder the declared-edge branches one untyped walk unions, a branch being one declared edge traversed one way and emitted as one SELECT: every base hop leaving the left label plus every step hop leaving a label the walk may stand on, pruned to those that can still reach the right endpoint. Exceeding it raises before any SQL is written, because dropping a branch would drop rows
open_path_length binder the depth an open-ended */*a.. resolves to, before inference or planning, typed or untyped; None raises LimitExceededError because a path that never stops is not a query, and a value above max_path_length is a SchemaError. An open-ended *a.. whose lower end exceeds the resolved depth raises LimitExceededError naming that depth, not an empty result. Truncation there is silent: a rewrite would change results

Security model

  1. Values (literals, $params, interpolations) only travel in params, checked to fit first; errors never include them and quote only the user's query line, escaped and capped at 120 chars. Names taken from the query — a selector's rejected value included — are echoed cut to 63 UTF-8 bytes with …; declared names are escaped and shown within the same hint budget (a long list ends with …). An unknown label, relationship type or property hint lists the declarations or, past 63 bytes, the size clause; a missing variable or parameter gets a static hint.
  2. Identifiers only come from NodeType/EdgeType, validated (non-empty; ≤ 63 bytes, never truncated into a collision; no NUL; no %) and quoted by one function.
  3. Query names are lookup keys only (unknown = compile error); suggestions come from the declared schema, so a Schema per audience scopes them; no eval/exec, no backtracking scanner.
  4. Outputs feed access control: real-PostgreSQL tests prove rows that must not match are excluded (nulls, direction, label, uniqueness, optionality); a multi-EXISTS test pins params order.

Executable docs

tests/test_docs.py runs docs/tutorial.md, docs/api.md, docs/performance.md and README.md, one fresh database and one shared Python namespace per document, one pytest item per block in order. - ```sql blocks run on the document's database via the harness's own autocommit connection; ```python blocks exec in the namespace, and PG* variables make the tutorial's connect real. - A block whose info string carries title="output" (text title="output") must equal the stdout of the preceding Python block (trailing whitespace stripped). Other languages are illustrative. - A fence's info string is one language plus attributes: a bare title="output", and any other attribute in a braced group (python {requires="py3.14"}). A bare second word, or a bare attribute the site build does not know, is a harness error, because the site build silently leaks such a fence and the lines after it as raw text. - A fence's info string may carry {requires="py3.14"} (language line python {requires="py3.14"}), parsed not decoration, combinable with <!-- pending: #N -->. On < 3.14 the harness skips the block and its output fence but prints a visible count line (skipped N blocks requiring python 3.14 (running X)); on ≥ 3.14 it executes it like any block, so a wrong block fails loudly. make check-py314 runs tests/test_docs.py on 3.14. - <!-- pending: #N --> directly above a Python fence marks it and its output unbuilt: it must still fail ("remove the marker" otherwise), and tracker.py set N done refuses while any remain.

TCK

The TCK assumes a schemaless graph and full projections; we return keys over a static schema. The corpus is 220 features, 3,897 scenario instances (1,615 declarations; outlines expand to 3,897); tests/tck/scope.toml answers for every instance. VISION records the live split of in, planned and out-of-scope instances — the one place those numbers are written — and make tck prints it. The adapter (tests/tck/) derives per scenario the schema a developer would declare and compares node identities.

  1. Read features with a purpose-built Gherkin reader; key = features/ path + title (#<row> for outlines).
  2. Build the graph from setup having executed: plain CREATE into nodes (id, labels, props) and relationships (id, type, src, dst, props) via the parser's Create AST; anything else (a named path, MERGE, parameters, a computed value) → setup-unsupported.
  3. Derive the schema: one node type per label (table = label, key id), _Unlabeled for label-less nodes; columns = property keys on the label or in the query, typed from values (none → text); one join-table edge (id, src, dst + properties, key="id") per (type, source, target label); query-only names get empty tables; multi-label nodes or mixed key types → schemaless-only; so is an untyped/undirected pattern that would infer a multi-hop path the TCK graph does not contain (the adapter never invents an edge).
  4. Run each scenario in a rolled-back transaction of one session database: create, insert, Schema.to_sql(query, parameters), execute.
  5. Compare identities: expected rows are node literals (expected null dropped; a returned NULL key fails) described by (labels, properties); one matching node is checked exactly; look-alikes (CREATE (), ()) must return a count in [1, min(look-alikes, expected)]; order and multiplicity are not checked (the product returns sets); unexpected descriptions fail.
  6. Errors: a compile-time error scenario passes only when both the TCK's expected error Type (mapped to our public class) and its Detail (mapped to a predicate on reason) match. Every TCK compile-time-error step names a detail, so there is no class-only path; see Compile-error expectations.

tests/tck/scope.toml (generated and maintained by tools/tck_scope.py):

[ratchet]
in_scope_floor = 56   # must equal the number of "in" entries; lowering it needs review
["clauses/match/Match1.feature"]
"[1] Match non-existent nodes returns empty" = "in"
"[2] Matching all nodes" = "planned"
Category Meaning Ever in scope?
in runs in make check and make tck, must pass —
planned needs a feature promised for 0.1.0 and expects rows; runs, and fails if it passes (promote it); reported on its own line, never as out-of-scope yes; planned rows remain at 0.1.0 and are promoted as slices land (the live split is in VISION)
write-query the query mutates (CREATE, MERGE, SET, DELETE, REMOVE) no
projection returns anything but one node variable (properties, relationships, paths, several columns) no
aggregation depends on aggregates (count, collect, …) not in 0.1.0
ordering-paging an ORDER BY, SKIP or LIMIT the compiler does not support: inside WITH, ordering by a property, another variable or an expression, or a page combined with an out-of-scope projection only when the query is otherwise in scope; query-level ORDER BY v, SKIP and LIMIT after RETURN compile, and the set comparison ignores order
unsupported-clause UNWIND, UNION, CALL, FOREACH, procedures and a named path (MATCH p = …) are not in 0.1.0. A second MATCH, OPTIONAL MATCH and WITH compile, so an error-expecting query using them is here only because its TCK detail is one we cannot reproduce (see Compile-error expectations); a query that also needs an out-of-scope feature (an aggregate, ordering, a write, an unsupported setup) lands in that category. Typed and untyped open-ended */*a.. are compiled, so they are not such constructs. A query that returns something other than one node variable is projection even when it also has one of those, e.g. MATCH (a)-[r*1..1]->(b) RETURN r no while the detail is unverifiable
unsupported-expression functions/operators outside our expression language that 0.1.0 does not promise (temporal, maps, CASE, comprehensions, type conversion, a label test on an already-bound variable inside a pattern predicate), and an error-expecting scenario on a promised form whose expected error is never reached (the construct is not compiled, or the binder reports a different compile-time error first). A row-returning query using one of the promised features is planned no while the construct is uncompiled
regex-dialect a =~ scenario whose expected answer only Java's regular-expression engine gives; PostgreSQL matches with POSIX ARE, which is a different dialect no; hand-set only, never emitted by the classifier
schemaless-only the graph or query has no static-schema equivalent (multi-label nodes, mixed property types, ambiguous or untyped unlabeled matches, runtime labels()/type()) no
runtime-error expects an error raised at run time no
setup-unsupported setup is not plain CREATE no

planned is a row-returning scenario whose feature is promised for 0.1.0 but not compiled yet — the remaining pattern forms; it runs, and must not pass. EXISTS { ... } and a pattern predicate in WHERE are compiled, so a query using them is classified by what it still needs: Pattern1 [1]–[6], [10] (*2), [19], [20] and [21], and ExistentialSubquery1–3 bind the predicate but match an unlabeled node or endpoint over several node types, which has no static-schema equivalent (schemaless-only), as does Pattern1 [13] (a relationship with four types); Pattern1 [12] and [14]–[18] return several columns (projection). A bounded [*a..b] (typed or untyped) and an open-ended */*a.. are compiled (join tier and WITH RECURSIVE respectively), so a bound is not itself a reason to stay planned: the planned rows that contain one need another construct, except Match4 [2] and Pattern1 [7]–[9]. Those are open-ended and the adapter derives Limits() with open_path_length unset, so the query raises the documented LimitExceededError before it can return rows — promoting them needs an adapter decision about that depth, not a compiler change. The OPTIONAL MATCH rows (Match7 [12]–[14], Match9 [8]) all stop at that same unset open_path_length, like Match4 [2], because each optional pattern has an open upper end. With a depth set, [13] compiles, [12]/[14] then resolve an unlabeled endpoint, and [8] stops at a <> b. MatchWhere4 [2] and WithWhere4 [2] put a label on an already-bound variable inside a pattern predicate ((b:MissingLabel) after (b:TheLabel)): openCypher reads that as a label test, while the binder refuses a different label as a conflicting second one (a CypherSemanticError), so the query needs a filter form 0.1.0 does not promise (unsupported-expression). An error-expecting scenario whose construct is not compiled, or whose class-and-detail pair we can never match, is out of scope in the category of what its query needs first, because the expected assertion is never reached: that is why the second-MATCH VariableTypeConflict scenarios are unsupported-clause while the row-returning ones compile and are classified by what they still need.

The classifier is a first-match ladder over one scenario, in this order: runtime-error, setup-unsupported, write-query, unsupported-clause (a clause keyword or a named path), schemaless-only, aggregation, ordering-paging, projection, unsupported-expression, planned. It reads the query with comments and string literals blanked, so RETURN 'CREATE' is not a write query. Its unsupported-clause rule sees the clause keywords listed above and a named path written directly after MATCH/OPTIONAL MATCH (MATCH p = …); a row whose single returned identifier is not a node is refined by hand in scope.toml, and the generator keeps a hand classification. The generator only ever emits planned and the never-categories; a human sets in, and only a human sets regex-dialect, because it records a dialect difference the classifier cannot see.

The 0.1.0 scope correction moved most planned rows to unsupported-clause (named paths, and error scenarios whose detail the runner cannot verify) and the rest to projection (a relationship or a computed value) or unsupported-expression (then-uncompiled pattern predicates and expressions). Separately, restricting a setup to plain CREATE moved some projection and schemaless-only rows to setup-unsupported. in and in_scope_floor were not lowered.

Ratchet: tests/tck/test_scope.py fails on a missing scenario, stale key, unknown category, or in_scope_floor ≠ the in count, so a coverage decrease is a visible, reviewed diff; make tck prints in-scope passing: N / N, out-of-scope: M (by category) on its first line, then planned: P (must not pass) and one category: count line per category other than planned, which runs and so is not out of scope.

Promotions are recorded here as they land. The list/string slice took the floor from 34 to 54 with expressions/string String8 [1]–[3], [6], [7], [9], String9 [1]–[3], [6], [7], [9], String10 [1]–[3], [6], [7], [9] and String11 [1]–[2] — 20 scenarios, all row-returning, so none needed a compile-error detail. Its =~ reclassification list is empty: String13 and String14 are empty feature stubs, so no scenario had to move to regex-dialect.

The query-level ordering/page slice took the floor from 54 to 56 with ReturnSkipLimit1 [4] (SKIP 0) and ReturnSkipLimit2 [3] (LIMIT 0), both row-returning, so neither needed a compile-error detail; the set comparison cannot see order, and these two pin syntax and the empty page rather than an ordering. Every other ordering-paging row stays out: most order by a property or an expression, page inside WITH, project a property or an aggregate, or expect a compile-time error whose detail (NonConstantExpression, NegativeIntegerArgument, InvalidArgumentType) the runner has no honest predicate for.

A scenario that expects a compile-time error is in or planned only when both its Type and its Detail are in the two tables below (test_every_running_error_expectation_is_verifiable covers both categories). Anything else can never pass and is out of scope, in the category of what its query needs before the error check is even reached — never planned.

Compile-error expectations

A Then a <Type> should be raised at compile time: <Detail> step asserts an error type and a detail code. We verify both, from two tables in tests/tck/_cases.py; a step without a detail is a runner error, and a scenario whose type or detail is absent from the tables is out of scope. Matching the class alone was the old rule and inflated the ratchet, so the floor was lowered from 172 to 12 as a correction, not a regression; later promotions (Match3 [20]–[21], and Pattern1 [10] #1–#14, whose pattern predicates now report the undefined variable itself) raised it to 34, and the list/string slice then took it to 54 (above). The floor's value and the reason for every moved scenario live in this section: scope.toml stays the canonical classification, and its header is generated from tests/tck/_scope.py, so hand-written reasons there would be lost on the next tck_scope.py run.

TCK Type the class we raise why it is the counterpart
SyntaxError CypherSyntaxError or CypherSemanticError the TCK's SyntaxError is every compile-time error that is not a type error; our finer split calls unparseable text a syntax error and unknown names a semantic one
TCK Detail predicate on reason why it is the counterpart
UndefinedVariable starts with unknown variable the binder's undefined-name rejection is that assertion

Only what a running scenario asserts is mapped. MissingParameter (the binder's missing parameter $name) and the TypeError scenarios are kept out of scope by a procedure setup, a projection, or an error raised at run time, so their mappings would be unreachable; a type or detail we do map is one the runner can actually reach.

A detail we do not reproduce keeps its scenarios out of planned as well as out of in: they could never pass, so the manifest records the category of the construct their query needs first. The UndefinedVariable predicate covers a bare name and a pattern predicate's names, so Pattern1 [10] #1–#14 are in; row #15 is unsupported-expression because its pattern names an undeclared label :C, which the binder reports before the undefined-variable check, even though the detail code is mapped.

The details we do not reproduce, and where their scenarios live:

detail codes category why we cannot verify them
VariableTypeConflict when the query uses a named path, a second MATCH, WITH or reuses a name across an untyped variable-length relationship; VariableAlreadyBound on a named path (including one written in a second MATCH or after WITH) unsupported-clause the clause construct is compiled but the assertion is not the TCK's: a second MATCH reusing a relationship name as a node (r) raises our own CypherSemanticError ("cannot tell which node type r is: …" or "variable r is already declared"), never VariableTypeConflict; a reused relationship variable raises UnsupportedCypherError ("relationship variable r is already bound in an earlier clause" or "… in this clause"), and a named path does not parse (CypherSyntaxError "expected '(', found 'p'"), so VariableAlreadyBound is unreachable. An untyped variable-length path compiles, so reusing its variable as a node (r) runs the node/relationship clash check and raises our own CypherSemanticError "variable r is already declared" — or, with open_path_length unset, the documented LimitExceededError first. A typed open-ended [r:T*] compiles the same way. None is the TCK's assertion
Same-pattern reuse of one name as a node and a relationship (MATCH ()-[r]-(r)), VariableTypeConflict schemaless-only; unsupported-clause when the pattern is an untyped open-ended variable-length one ([r*]) the unlabeled endpoints stop the binder at the derived schema (CypherSemanticError "no relationship connects :_Unlabeled and :_Unlabeled", or "cannot tell which node type …" when the graph has several labels); MATCH ()-[r*]-(r) now reaches the untyped walk's checks: LimitExceededError when open_path_length is unset, else CypherSemanticError "variable r is already declared" — never the TCK's VariableTypeConflict
InvalidArgumentType on a property of a named path (MATCH r = … WHERE r.name = …) unsupported-clause named paths and path-typed values are not supported, so it is rejected while parsing MATCH r = …
VariableTypeConflict on an untyped relationship between unlabeled nodes (directed ones included) schemaless-only the derived schema has no such edge; the binder rejects before the variable-reuse check
InvalidParameterUse on $param inside a node or relationship pattern; InvalidArgumentType on (n) alone as a condition; UndefinedVariable on a pattern predicate naming an undeclared label, and on a bare-identifier operand unsupported-expression none is a pattern predicate we compile: a $param is not a pattern element (CypherSyntaxError "expected ')'"/"expected ']'"), (n) alone is not a condition ("expected a condition"), a bare identifier is not a value ("expected a value"), and Pattern1 [10] #15's undeclared label :C is reported before its undefined variable
UnexpectedSyntax on a pattern expression in a WITH projection unsupported-expression WITH projects variables only, so a pattern there fails the parser ("expected a variable, found '('")
InvalidArgumentType on RETURN NOT <literal>; RelationshipUniquenessViolation when the query projects a relationship; ColumnNameConflict when it projects a computed value projection the query projects something other than one node variable
every other code (InvalidAggregation, IntegerOverflow, …) its feature's category the feature (aggregation, writes, ordering, …) is out of scope on its own

A scenario whose query needs an unimplemented construct fails loudly (UnsupportedCypherError for returning a variable an OPTIONAL MATCH introduced or for WITH inside EXISTS; CypherSemanticError for a pattern predicate naming a variable that is not bound or a relationship that does not connect its labels; CypherSyntaxError for a named path or <-; LimitExceededError for an open-ended bound, typed or untyped, while the adapter's open_path_length is unset), so it can never be mistaken for the expected error and promoted early.

Decisions

  1. Schema: protocols + reference classes + one validated Schema; uniform edge model; tuple keys; typed properties. Rejected: one class per table with class attributes (metaclass tricks).
  2. Entry point: to_sql(cypher: str | TemplateLike, params), target = the RETURN variable; not target=. Template acceptance is additive; SQLQuery.to_template() (Python ≥ 3.14) rebuilds the emitted text as a Template with one Interpolation per bound parameter, and SQLQuery.sql stays str: schema-derived text, not a literal, so the pyright LiteralString cast at the execute call is the documented trust boundary. Reachability and emission tiers are inferred from the schema, never a query hint.
  3. Parameters: positional %s::type; not %(name)s (breaks RawSQL, collides when composed).
  4. Limits are declared once on Schema, beside what they protect; rejected: per-call overrides (a second way).
  5. Emission: target in FROM + EXISTS groups, positional aliases; hops 1..K join/EXISTS, which is what a typed bounded [*a..b] compiles to while it fits. Above K, for an open-ended *, and for every untyped bound, one WITH RECURSIVE walk per occurrence: a typed walk's state is an edge row, the end it arrived at, and the trail of rows read; an untyped walk's state is the current node's label and key as one text value, the depth and the trail of tag:key rows, with one UNION ALL branch per declared edge it may read. The depth counter is the only stopping rule, so cycles terminate. Depth is validated, rejected above the bound, and inlined; the trail comparison is relationship uniqueness. Rejected: tracking visited rows as cycle detection (changes which nodes a trail may revisit). Rejected: a per-edge-type SQL blob grown in Python; the branch count is capped by max_edge_branches. Rejected: flat joins + DISTINCT (duplicate work, composes badly with OPTIONAL/NOT). Inferred paths use a label-level BFS distance plus a deterministic layered-DAG walk; symmetry no longer arises structurally (the DAG fixes each label's layer, and the old reversal dedupe is gone), so pks-only output makes OR-of-EXISTS safe; rejected: requiring every pattern to name an edge type.
  6. Docs harness: pending markers plus fence-level {requires="py3.14"}, never a silent skip.
  7. TCK: per-scenario derived schema; rejected a generic jsonb schema (a path no user has).
  8. Strings: every comparison and ordering of a declared-text operand is code-point order (COLLATE "C"), never the column's or the database's default collation. Cypher defines string order over code points, and the emitted keys feed access control, so a case-insensitive or ICU-nondeterministic collation must not be able to add, drop or reorder a row; PostgreSQL's =, its substring search and its ordering comparisons all follow the collation otherwise. Every text operand whose side the declaration types — a comparison column, an IN, STARTS WITH/ENDS WITH/CONTAINS/=~ operand, and a text key's order operand — is emitted as a Collate, so the pin exists in one place; a link whose edge column is declared but whose node key is not gets the Collate on the edge side only. One explicit Collate decides the collation of the whole comparison, so the bare operand is still compared by code point (the index consequence lives in api.md). A bound value keeps its bare %s::text cast, because the column's pin decides the comparison. No pinned predicate is left comparing through the column's collation; a link whose two key columns are both undeclared compares under their own collation, which is why declaring both keys is the safe choice. Rejected: trusting the default collation and documenting the caveat (results would then depend on a database setting the query never names); rejected: refusing non-C columns (ordinary en_US/ICU text columns are the common case). Cost: a pinned comparison of a column with another collation needs an expression index or a COLLATE "C" declaration (api.md).