translate

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 19 Imported by: 0

README

openCypher to PgSQL 16 Translation

Renaming

All variable bindings in an openCypher query are renamed to simplify reordering, decomposition and optimization operations.

match (n) return labels(n)

TODO: match (n)-[r:MemberOf]->()

The above openCypher query has the named variable n renamed to n0 in the below SQL translation:

with s0 as (select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0 from node n0)
select (s0.n0).kind_ids
from s0;

Scope Management

Plain node DELETE materializes its input before checking incident relationships. The check uses matched input IDs, keeping error evaluation away from unrelated stored nodes regardless of the DELETE join plan. Relationship exclusions cover all explicitly deleted edges and detached nodes in the query part, including other input rows; optional null targets are omitted from those ID arrays. The schema helper reads the statement snapshot so data-modifying CTE execution order cannot turn a connected-node plain DELETE into a detach. DETACH cleanup uses graph-scoped statement triggers on both parent tables and node partitions.

Translation requires some amount of query planning and result dependency negotiation. This translation driver organizes openCypher query plans as an incrementally named variable in the SQL translation as sN where N is the scope's frame.

A fixed relationship pattern that reuses a named relationship gets a fresh SQL edge binding, constrained by ID to the original binding. The Cypher alias continues to refer to the original value. Endpoint joins and inline kind/property constraints use the fresh scan; frame rewriting qualifies the original value through its carried frame. This also keeps property constraints inside a correlated pattern predicate. Bound paths record the fresh edge as a dependency so that path construction includes every hop.

An undirected fixed continuation pairs both endpoint orientations in the terminal node join: (near = start AND far = end) OR (far = start AND near = end). Frame rewriting qualifies the near endpoint before the new step is materialized, preserving both scalar-ID and composite representations. This excludes a false return to the near node while retaining self-loops and duplicate input paths.

Relationship uniqueness spans all comma-separated parts of an ordinary MATCH. Each part retains preceding traversal steps from that clause, and projection pruning keeps fixed relationship IDs and expansion path arrays needed by later parts. Fixed steps compare IDs or exclude membership in earlier paths; completed expansions exclude preceding fixed IDs and reject overlap with earlier edge-ID arrays. These are row predicates, preserving valid path and input-row multiplicity. Separate MATCH clauses and pattern predicates start fresh scopes; OPTIONAL MATCH applies uniqueness before merging null-extended input rows. Checks compare preceding step pairs and expansion arrays after traversal; they do not prune recursive search using the preceding paths.

Consider the following openCypher query:

match (n), ()-[r]->() return n, r

The above openCypher query, when translated is broken up into two distinct planned elements. First, the plan executes a select for match (n) with n renamed to n0 and saves the projection under the result alias s0 such that s0.n0 contains the result of match (n) return n:

s0 as (select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0 from node n0)

The second planned element executes a select and join for the match ()-[r]->() with r renamed to e0. The current implement also eagerly binds all anonymous pattern elements in a given pattern part. The declarations are then saved as a projection under the result alias s1. In addition to joining n1, e0, n2 to the result scope, the previous result s0.n0 is also copied as s1.n0:

s1 as (select s0.n0                                                                     as n0,
               (n1.id, n1.kind_ids, n1.properties)::nodecomposite                        as n1,
               (e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite as e0,
               (n2.id, n2.kind_ids, n2.properties)::nodecomposite                        as n2
        from s0,
             edge e0
                 join node n1 on n1.id = e0.start_id
                 join node n2 on n2.id = e0.end_id)

Once the query reaches the final select statement, the following namespace is available authored in openCypher: match (n0), (n1)-[e0]->(n2). The resulting projection may then access them user the result alias s1:

select s1.n0 as n, s1.e0 as r
from s1;

The resulting translation being equal to: return n, r. The translation strives to preserve user preference with regard to projection aliases. In the case of the original openCypher query, the result set the querying client expects is: (n), [r] where n is a node and r is an edge.

The complete translation is:

with s0 as (select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0 from node n0),
     s1 as (select s0.n0                                                                     as n0,
                   (n1.id, n1.kind_ids, n1.properties)::nodecomposite                        as n1,
                   (e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite as e0,
                   (n2.id, n2.kind_ids, n2.properties)::nodecomposite                        as n2
            from s0,
                 edge e0
                     join node n1 on n1.id = e0.start_id
                     join node n2 on n2.id = e0.end_id)
select s1.n0 as n, s1.e0 as r
from s1;

Criteria Decomposition

openCypher formally specifies bound elements of a query in the pattern component: match (s)-[r]->(e) return s, r, e and allows referencing of the components in openCpyher expressions: match (s)-[r]->(e) where s.name = '123' return s, r, e.

The translator isolates filtering criteria for bound elements in a data structure named a constraint. Constraints are collected and organized by the bound elements they reference. This allows the translator to reduce, deconstruct and reorder filtering criteria.

For example, consider the following openCypher query:

match (s)-[r]->(e) where s.name = '123' and e:Target and not r.property return s, r, e.

The above openCypher query would first undergo renaming:

match (n0)-[e0]->(n1) where n0.name = '123' and n1:Target and not e0.property return n0 as s, e0 as r, n1 as e.

After renaming the translator will isolate the following constraints:

  • (n0) where n0.name = '123'
  • [e0] where not e0.property
  • (n1) where n1:Target

After renaming the translator, will construct the required SQL AST nodes and assigns constraints to their associated select operations. This is done by comparing the available scope declarations and the requirements of the constraints:

-- match (s)-[r]->(e) where s.name = '123' and e:NodeKind1 and not r.property return s, r, e
with s0 as (select (n0.id, n0.kind_ids, n0.properties)::nodecomposite                        as n0,
                   (e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite as e0,
                   (n1.id, n1.kind_ids, n1.properties)::nodecomposite                        as n1
            from edge e0
                     join node n0 on n0.properties ->> 'name' = '123' and n0.id = e0.start_id
                     join node n1 on n1.kind_ids operator (pg_catalog.&&) array [1]::int2[] and n1.id = e0.end_id
            where not (e0.properties -> 'property')::bool)
select s0.n0 as s, s0.e0 as r, s0.n1 as e
from s0;
Dependency Satisfaction

Query filter expressions may involve operations that can not be isolated to a single bound element. Take for example the following openCypher query: match (s:NodeKind1), (e:NodeKind2) where s.selected or s.tid = e.tid and e.enabled return s, e

The above openCypher query would first undergo renaming:

match (n0:NodeKind1), (n1:NodeKind2) where n0.selected or n0.tid = n1.tid and n1.enabled return n0 as s, n1 as e

After renaming the translator will isolate the following constraints:

  • (n0) where n0:NodeKind1
  • (n1) where n1:NodeKind2
  • (n0), (n1) where n0.selected or n0.tid = n1.tid and n1.enabled

The comparison n0.selected or n0.tid = n1.tid can not be decomposed further and must have both n0 and n1 projected in scope before it can be satisfied. When the query plan first selects for n0 it can only satisfy the constraint (n0) where n0:NodeKind1:

s0 as (select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0
            from node n0
            where n0.kind_ids operator (pg_catalog.&&) array [1]::int2[])

The second query will project n1 and make it available. This then allows the planner to satisfy both remaining constraints: (n1) where n1:NodeKind2 and (n0), (n1) where n0.selected or n0.tid = n1.tid:

s1 as (select s0.n0 as n0, (n1.id, n1.kind_ids, n1.properties)::nodecomposite as n1
            from s0,
                 node n1
            where n1.kind_ids operator (pg_catalog.&&) array [2]::int2[] and ((s0.n0).properties -> 'selected')::bool
               or (s0.n0).properties -> 'tid' = n1.properties -> 'tid' and (n1.properties -> 'enabled')::bool)

The complete translation is:

-- match (s:NodeKind1), (e:NodeKind2) where s.selected or s.tid = e.tid and e.enabled return s, e
with s0 as (select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0
            from node n0
            where n0.kind_ids operator (pg_catalog.&&) array [1]::int2[]),
     s1 as (select s0.n0 as n0, (n1.id, n1.kind_ids, n1.properties)::nodecomposite as n1
            from s0,
                 node n1
            where n1.kind_ids operator (pg_catalog.&&) array [2]::int2[] and ((s0.n0).properties -> 'selected')::bool
               or (s0.n0).properties -> 'tid' = n1.properties -> 'tid' and (n1.properties -> 'enabled')::bool)
select s1.n0 as s, s1.n1 as e
from s1;

Expansions

  • packages/go/cypher/models/pgsql/translate/expansion.go
  • packages/go/cypher/models/pgsql/translate/translation_cases/pattern_expansion.sql

The translator represents pattern expansion as a recursive CTE to offload as much of the traversal work to the database. Currently, all expansions are hard limited to an expansion depth of 5 steps.

Consider the following openCypher query: match (n)-[*..]->(e) return n, e.

To perform the recursive traversal, the translator first defines a record shape for the CTE to represent the expansion's pathspace:

with s0 as (with recursive ex0(root_id, next_id, depth, satisfied, is_cycle, path)
Column type Usage
root_id Int8 Node that the path originated from. Simplifies referencing the root node of each path.
next_id Int8 Next node to expand to.
depth Int Depth of the current traversal.
satisfied Boolean True if the expansion is satisfied.
is_cycle Boolean True if the expansion is a cycle.
path Int8[] Array of edges in order of traversal.

The translator then formats two queries. First is the primer query that populates the initial pathspace of the expansion:

select e0.start_id,
       e0.end_id,
       1,
       false,
       e0.start_id = e0.end_id,
       array [e0.id]
from edge e0
         join node n0 on n0.id = e0.start_id
         join node n1 on n1.id = e0.end_id

This query is then unioned to a recursive query. Unlike the primer query, the recursive query also includes the temporary table defined by the pathspace record shape ex0:

select ex0.root_id,
       e0.end_id,
       ex0.depth + 1,
       false,
       e0.id = any (ex0.path),
       ex0.path || e0.id
from ex0
         join edge e0 on e0.start_id = ex0.next_id
         join node n1 on n1.id = e0.end_id
where ex0.depth < 5
  and not ex0.is_cycle

The resulting output of the result alias s0 is then populated from the pathspace table:

select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0,
       (select array_agg((e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite)
        from edge e0
        where e0.id = any (ex0.path))                     as e0,
       ex0.path                                           as ep0,
       (n1.id, n1.kind_ids, n1.properties)::nodecomposite as n1
from ex0
         join edge e0 on e0.id = any (ex0.path)
         join node n0 on n0.id = ex0.root_id
         join node n1 on e0.id = ex0.path[array_length(ex0.path, 1)::int4] and n1.id = e0.end_id

This binds the following additional components to query scope:

Component Type Usage
n0 nodecomposite Root node of each recursively expanded path.
e0 edgecomposite[] edgecomposite array of edges
ep0 int4[] Int4 array of edge identifiers
n1 nodecomposite Terminal node of each recursively expanded path.

The translator then authors the final projection return n, e:

select s0.n0 as n, s0.n1 as e
from s0;

The complete translation is:

-- match (n)-[*..]->(e) return n, e
with s0 as (with recursive ex0(root_id, next_id, depth, satisfied, is_cycle, path) as (select e0.start_id,
                                                                                              e0.end_id,
                                                                                              1,
                                                                                              false,
                                                                                              e0.start_id = e0.end_id,
                                                                                              array [e0.id]
                                                                                       from edge e0
                                                                                                join node n0 on n0.id = e0.start_id
                                                                                                join node n1 on n1.id = e0.end_id
                                                                                       union
                                                                                       select ex0.root_id,
                                                                                              e0.end_id,
                                                                                              ex0.depth + 1,
                                                                                              false,
                                                                                              e0.id = any (ex0.path),
                                                                                              ex0.path || e0.id
                                                                                       from ex0
                                                                                                join edge e0 on e0.start_id = ex0.next_id
                                                                                                join node n1 on n1.id = e0.end_id
                                                                                       where ex0.depth < 5
                                                                                         and not ex0.is_cycle)
            select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0,
                   (select array_agg((e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite)
                    from edge e0
                    where e0.id = any (ex0.path))                     as e0,
                   ex0.path                                           as ep0,
                   (n1.id, n1.kind_ids, n1.properties)::nodecomposite as n1
            from ex0
                     join edge e0 on e0.id = any (ex0.path)
                     join node n0 on n0.id = ex0.root_id
                     join node n1 on e0.id = ex0.path[array_length(ex0.path, 1)::int4] and n1.id = e0.end_id)
select s0.n0 as n, s0.n1 as e
from s0;
All Shortest Paths
  • packages/go/cypher/models/pgsql/translate/expansion.go
  • packages/go/cypher/models/pgsql/translate/translation_cases/shortest_paths.sql

Recursive harness in PL/pgSQL with non-parameterized primer and recursive queries.

All shortest paths is a search function that will return the first path found and all other paths of the same depth. Naively, this early termination can be authored as a condition in the temporary table of a recursive expansion CTE however recursive CTEs may not perform certain operations on the temporary table allocated for the CTE statement: https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-RECURSIVE.

This means a different construct is required to perform early termination of a shortest-path traversal. For all shortest paths queries, a PL/PgSQL function named asp_harness exists to execute recursive expansion with early termination.

The goal of this effort, even with the caveats of the method pursued, is to prevent the need for unnecessary round trips to the database by offloading as much of the expansion logic to the database as possible. This may result in a sizeable query that is less efficient than its constituent components if reordered, but it allows the implementation to avoid hundreds of thousands or millions of round trips to execute a traversal expansion.

asp_harness
-- All shortest path traversal harness.
create or replace function public.asp_harness(primer_query text, recursive_query text, max_depth int4)
    returns table
            (
                root_id   int4,
                next_id   int4,
                depth     int4,
                satisfied bool,
                is_cycle  bool,
                path      int4[]
            )
as
$$
declare
    depth int4 := 1;
begin
    -- Define two tables to represent pathspace of the recursive expansion. These are temporary and as such are unlogged.
    create temporary table pathspace
    (
        root_id   int4   not null,
        next_id   int4   not null,
        depth     int4   not null,
        satisfied bool   not null,
        is_cycle  bool   not null,
        path      int4[] not null,
        primary key (path)
    ) on commit drop;

    create temporary table next_pathspace
    (
        root_id   int4   not null,
        next_id   int4   not null,
        depth     int4   not null,
        satisfied bool   not null,
        is_cycle  bool   not null,
        path      int4[] not null,
        primary key (path)
    ) on commit drop;

    -- Creating these indexes should speed up certain operations during recursive expansion. Benchmarking should be done
    -- to validate assumptions here.
    create index pathspace_next_id_index on pathspace using btree (next_id);
    create index pathspace_satisfied_index on pathspace using btree (satisfied);
    create index pathspace_is_cycle_index on pathspace using btree (is_cycle);

    create index next_pathspace_next_id_index on next_pathspace using btree (next_id);
    create index next_pathspace_satisfied_index on next_pathspace using btree (satisfied);
    create index next_pathspace_is_cycle_index on next_pathspace using btree (is_cycle);

    -- Populate initial pathspace with the primer query
    execute primer_query;

    -- Iterate until either we reach a depth limit or if there are satisfied paths
    while depth < max_depth and not exists(select 1 from next_pathspace np where np.satisfied)
        loop
            -- Rename tables to swap in the next pathspace as the current pathspace for the next traversal step
            alter table pathspace
                rename to pathspace_old;
            alter table next_pathspace
                rename to pathspace;
            alter table pathspace_old
                rename to next_pathspace;

            -- Clear the next pathspace scratch
            truncate table next_pathspace;

            -- Remove any non-satisfied terminals and cycles from pathspace to prune any terminal, non-satisfied paths
            delete
            from pathspace p
            where p.is_cycle
               or not exists(select 1 from edge e where e.start_id = p.next_id);

            -- Increase the current depth and execute the recursive query
            depth := depth + 1;
            execute recursive_query;
        end loop;

    -- Return all satisfied paths from the next pathspace table
    return query select *
                 from next_pathspace np
                 where np.satisfied;

    -- Close the result set
    return;
end;
$$
    language plpgsql volatile
                     strict;
Expansion using the ASP Harness

Take for consideration the following openCypher query: match p = allShortestPaths((s:NodeKind1)-[*..]->()) return p

The table record shape of the asp_harness function matches the recursive CTE traversal's record shape, meaning the result alias for this expansion can be dropped into a chain of expansions with minimal result set processing. As such the result alias record shape for an all shortest paths query is declared no differently than a recursive CTE traversal:

with ex0(root_id, next_id, depth, satisfied, is_cycle, path)

The harness function is then called. The first two parameters are expected to be Text values that contain reified statements that represent the primer and recursive queries for the traversal expansion. In the test case being explored, these parameter expectations are encoded in the test case header:

-- pgsql_params: {"pi0":"insert into next_pathspace (root_id, next_id, depth, satisfied, is_cycle, path) select e0.start_id, e0.end_id, 1, exists (select 1 from edge e0 where n1.id = e0.start_id), e0.start_id = e0.end_id, array [e0.id] from edge e0 join node n0 on n0.kind_ids operator (pg_catalog.&&) array [1]::int2[] and n0.id = e0.start_id join node n1 on n1.id = e0.end_id;", "pi1":"insert into next_pathspace (root_id, next_id, depth, satisfied, is_cycle, path) select ex0.root_id, e0.end_id, ex0.depth + 1, exists (select 1 from edge e0 where n1.id = e0.start_id), e0.id = any (ex0.path), ex0.path || e0.id from pathspace ex0 join edge e0 on e0.start_id = ex0.next_id join node n1 on n1.id = e0.end_id where ex0.depth < 5 and not ex0.is_cycle;"}

For this translation the primer query will be formated as the pi0 parameter:

insert into next_pathspace (root_id, next_id, depth, satisfied, is_cycle, path)
select e0.start_id,
       e0.end_id,
       1,
       exists (select 1 from edge e0 where n1.id = e0.start_id),
       e0.start_id = e0.end_id,
       array [e0.id]
from edge e0
         join node n0 on n0.kind_ids operator (pg_catalog.&&) array [1]::int2[] and n0.id = e0.start_id
         join node n1 on n1.id = e0.end_id;

The translation then authors the recursive query formatted as the pi1 parameter:

insert into next_pathspace (root_id, next_id, depth, satisfied, is_cycle, path)
select ex0.root_id,
       e0.end_id,
       ex0.depth + 1,
       exists (select 1 from edge e0 where n1.id = e0.start_id),
       e0.id = any (ex0.path),
       ex0.path || e0.id
from pathspace ex0
         join edge e0 on e0.start_id = ex0.next_id
         join node n1 on n1.id = e0.end_id
where ex0.depth < 5
  and not ex0.is_cycle;

The resulting output of the result alias s0 is then populated from the pathspace table:

select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0,
       (select array_agg((e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite)
        from edge e0
        where e0.id = any (ex0.path))                     as e0,
       ex0.path                                           as ep0,
       (n1.id, n1.kind_ids, n1.properties)::nodecomposite as n1
from ex0
         join edge e0 on e0.id = any (ex0.path)
         join node n0 on n0.id = ex0.root_id
         join node n1 on e0.id = ex0.path[array_length(ex0.path, 1)::int4] and n1.id = e0.end_id

This binds the following additional components to query scope:

Component Type Usage
n0 nodecomposite Root node of each recursively expanded path.
e0 edgecomposite[] edgecomposite array of edges
ep0 int4[] Int4 array of edge identifiers
n1 nodecomposite Terminal node of each recursively expanded path.

Lastly, since this query is to return the traversed paths, the result variable ep0 is passed to a function edges_to_path to create the expected return record shape:

select edges_to_path(variadic ep0)::pathcomposite as p
from s0;

The complete translation is:

-- match p = allShortestPaths((s:NodeKind1)-[*..]->()) return p
with s0 as (with ex0(root_id, next_id, depth, satisfied, is_cycle, path)
                     as (select * from asp_harness(@pi0::text, @pi1::text, 5))
            select (n0.id, n0.kind_ids, n0.properties)::nodecomposite as n0,
                   (select array_agg((e0.id, e0.start_id, e0.end_id, e0.kind_id, e0.properties)::edgecomposite)
                    from edge e0
                    where e0.id = any (ex0.path))                     as e0,
                   ex0.path                                           as ep0,
                   (n1.id, n1.kind_ids, n1.properties)::nodecomposite as n1
            from ex0
                     join edge e0 on e0.id = any (ex0.path)
                     join node n0 on n0.id = ex0.root_id
                     join node n1 on e0.id = ex0.path[array_length(ex0.path, 1)::int4] and n1.id = e0.end_id)
select edges_to_path(variadic ep0)::pathcomposite as p
from s0;

Pattern-predicate futures belong to the MATCH that collected them and are resolved once. Before entering another MATCH, a pending predicate filter is consumed into a projection over its original frame. This keeps correlation references in scope and prevents later scans from consuming old filters into new joins. OPTIONAL MATCH consumes its own remaining filters in its outer join.

A multipart query part reserves a frame for its closing WITH output before its reading clauses are translated. That frame is not an input relation. New traversal frames link to the preceding materialized frame, while the scope stack retains the reserved frame for unwinding at the boundary. This applies to fixed hops, bound endpoints and expansions. Literal WITH projections also retain the current input frame so duplicate and empty streams preserve their cardinality.

Ordinary expansion seeds retain root IDs rather than input-row identities. Predicates that reference an outer input therefore also gate the completed-path projection, including zero-hop results. This preserves the association between each path and its input values when the projection rejoins the prior frame.

Documentation

Index

Constants

View Source
const DefaultGraphID int32 = 0

DefaultGraphID selects graph zero for tests and tooling that do not target a concrete graph.

Variables

View Source
var ErrUnsupportedExpansionDirection = errors.New("unsupported expansion direction")

ErrUnsupportedExpansionDirection reports a traversal direction that cannot be lowered to SQL.

Functions

func ConjoinExpressions

func ConjoinExpressions(kindMapper *contextAwareKindMapper, expressions []pgsql.Expression) (pgsql.Expression, error)

func ContainsAggregateFunction added in v0.5.2

func ContainsAggregateFunction(node pgsql.SyntaxNode) (bool, error)

func ExtractSyntaxNodeReferences

func ExtractSyntaxNodeReferences(root pgsql.SyntaxNode) (*pgsql.IdentifierSet, error)

func FromCypher

func FromCypher(ctx context.Context, regularQuery *cypher.RegularQuery, kindMapper pgsql.KindMapper, stripLiterals bool, graphID int32) (format.Formatted, error)

FromCypher renders a Cypher query as a SQL comment followed by its PostgreSQL translation.

func GetAggregatedFunctionParameterSymbols

func GetAggregatedFunctionParameterSymbols(call pgsql.FunctionCall) (*pgsql.SymbolTable, error)

func GetAggregatedFunctionParameterSymbolsIn added in v0.5.2

func GetAggregatedFunctionParameterSymbolsIn(node pgsql.SyntaxNode) (*pgsql.SymbolTable, error)

func GetNonAggregatedSymbols added in v0.5.2

func GetNonAggregatedSymbols(node pgsql.SyntaxNode) (*pgsql.SymbolTable, error)

func GetTypeHint

func GetTypeHint(expression pgsql.Expression) (pgsql.DataType, bool)

func InferExpressionType

func InferExpressionType(expression pgsql.Expression) (pgsql.DataType, error)

InferExpressionType derives the PostgreSQL data type produced by an expression when it can be determined statically.

func MeasureSelectivity

func MeasureSelectivity(scope *Scope, expression pgsql.Expression) (int, error)

func NonAggregateGroupByExpressions added in v0.5.2

func NonAggregateGroupByExpressions(expression pgsql.Expression) ([]pgsql.Expression, error)

func RewriteFrameBindings

func RewriteFrameBindings(scope *Scope, expression pgsql.Expression) error

func SymbolsFor

func SymbolsFor(node pgsql.SyntaxNode) (*pgsql.SymbolTable, error)

func Translated

func Translated(translation Result) (format.Formatted, error)

Translated renders a translation result as PostgreSQL for its target graph.

func TranslatedStatements added in v1.0.0

func TranslatedStatements(translation Result, tablePrefix string) ([]format.Formatted, error)

TranslatedStatements formats each statement in execution order. tablePrefix must uniquely identify the temporary relations for this execution.

func TypeCastExpression

func TypeCastExpression(expression pgsql.Expression, dataType pgsql.DataType) (pgsql.Expression, error)

TypeCastExpression applies a type hint, rewriting property comparisons when the operator requires element typing.

Types

type BindingResult

type BindingResult struct {
	// Binding supplies the binding input to the BindingResult contract.
	Binding *BoundIdentifier
	// AlreadyBound indicates whether already bound applies.
	AlreadyBound bool
}

BindingResult groups SQL model state that must remain consistent while translating binding result.

type BoundIdentifier

type BoundIdentifier struct {
	// Identifier is the canonical PostgreSQL name allocated for the binding.
	Identifier pgsql.Identifier
	// Alias is the optional source-visible name projected for the binding.
	Alias models.Optional[pgsql.Identifier]
	// Parameter is the translated SQL parameter represented by this binding, when applicable.
	Parameter *pgsql.Parameter
	// LastProjection is the most recent frame that materialized the binding.
	LastProjection *Frame
	// Dependencies are the bindings required to reconstruct this value.
	Dependencies []*BoundIdentifier
	// DataType is the PostgreSQL representation carried by the binding.
	DataType pgsql.DataType
	// IDOnly reports that the binding is represented by a scalar entity ID instead of a composite.
	IDOnly bool

	// PathDirectionReversed marks a path composite binding whose dependency order was produced
	// from an optimizer-reversed pattern. Path materialization reverses the assembled node and
	// edge references so the path renders in its original left-to-right logical order.
	PathDirectionReversed bool
	// DistanceOnly reports that the binding carries only shortest-path distance state.
	DistanceOnly bool
	// contains filtered or unexported fields
}

BoundIdentifier is a declared query identifier bound to the current scope frame.

Bound identifiers have two states:

  • Defined - the translation code is aware of this identifier and its type
  • Visible - the identifier has been projected into the query's scope and can be referenced

Bound identifiers may also be aliased if the source query contains an alias for the identifier. In the openCypher query `match (n) return n as e` the projection for `n` is aliased as `e`. The translations will eagerly bind anonymous identifiers for traversal steps and rebind existing identifiers and their aliases to prevent naming collisions.

func (*BoundIdentifier) Aliased

func (s *BoundIdentifier) Aliased() pgsql.Identifier

func (*BoundIdentifier) Copy

func (s *BoundIdentifier) Copy() *BoundIdentifier

Copy returns an independent binding whose dependency slice can be modified without affecting the source.

func (*BoundIdentifier) Dematerialize

func (s *BoundIdentifier) Dematerialize()

func (*BoundIdentifier) DependOn

func (s *BoundIdentifier) DependOn(other *BoundIdentifier)

func (*BoundIdentifier) MaterializedBy

func (s *BoundIdentifier) MaterializedBy(frame *Frame)

type BoundProjections

type BoundProjections struct {
	// Items contains the SQL expressions emitted by the projection.
	Items pgsql.Projection

	// Bindings contains the scope bindings represented by Items.
	Bindings []*BoundIdentifier
}

BoundProjections pairs rendered select items with the identifiers they carry into the next frame.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

func NewExpressionTreeBuilder

func NewExpressionTreeBuilder() *Builder

func (*Builder) Depth

func (s *Builder) Depth() int

func (*Builder) IsEmpty

func (s *Builder) IsEmpty() bool

func (*Builder) PeekOperand

func (s *Builder) PeekOperand() pgsql.Expression

func (*Builder) PopOperand

func (s *Builder) PopOperand(kindMapper *contextAwareKindMapper) (pgsql.Expression, error)

PopOperand removes and returns the next operand from the expression stack. An empty stack is a producer bug rather than a caller-facing panic: every visitor that pops operands must have pushed them first, so the underflow is reported as an ordinary translation error instead.

func (*Builder) PushOperand

func (s *Builder) PushOperand(operand pgsql.Expression)

type Constraint

type Constraint struct {
	Dependencies *pgsql.IdentifierSet
	Expression   pgsql.Expression
}

Constraint is an extracted expression that contains an identifier set of symbols required to be in scope for this constraint to be solvable.

type ConstraintTracker

type ConstraintTracker struct {
	Constraints []*Constraint
}

ConstraintTracker is a tool for associating constraints (e.g. binary or unary expressions that constrain a set of identifiers) with the identifier set they constrain.

This is useful for rewriting a where-clause so that conjoined components can be isolated:

Where Clause:

where a.name = 'a' and b.name = 'b' and c.name = 'c' and a.num_a > 1 and a.ef = b.ef + c.ef

Isolated Constraints:

"a":           a.name = 'a' and a.num_a > 1
"b":           b.name = 'b'
"c":           c.name = 'c'
"a", "b", "c": a.ef = b.ef + c.ef

func NewConstraintTracker

func NewConstraintTracker() *ConstraintTracker

func (*ConstraintTracker) Constrain

func (s *ConstraintTracker) Constrain(kindMapper *contextAwareKindMapper, dependencies *pgsql.IdentifierSet, constraintExpression pgsql.Expression) error

func (*ConstraintTracker) ConsumeAll

func (s *ConstraintTracker) ConsumeAll(kindMapper *contextAwareKindMapper) (*Constraint, error)

func (*ConstraintTracker) ConsumeSet

func (s *ConstraintTracker) ConsumeSet(kindMapper *contextAwareKindMapper, visible *pgsql.IdentifierSet) (*Constraint, error)

ConsumeSet takes a given scope (a set of identifiers considered in-scope) and locates all constraints that can be satisfied by the scope's identifiers.

```

visible := pgsql.IdentifierSet{
	"a": struct{}{},
	"b": struct{}{},
}

tracker := ConstraintTracker{
	Constraints: []*Constraint{{
		Dependencies: pgsql.IdentifierSet{
			"a": struct{}{},
		},
		Expression: &pgsql.BinaryExpression{
			Operator: pgsql.OperatorEquals,
			LOperand: pgsql.CompoundIdentifier{"a", "name"},
			ROperand: pgsql.Literal{
				Value: "a",
			},
		},
	}},
}

satisfiedConstraints, expression := tracker.ConsumeSet(visible)

```

func (*ConstraintTracker) HasConstraints

func (s *ConstraintTracker) HasConstraints(scope *pgsql.IdentifierSet) (bool, error)

func (*ConstraintTracker) HasEndpointInequality added in v0.5.0

func (s *ConstraintTracker) HasEndpointInequality(leftEndpoint, rightEndpoint pgsql.Identifier) bool

type Delete

type Delete struct {
	// Detach permits removal of incident relationships when deleting a node.
	Detach bool
	// Frame supplies the frame input to the Delete contract.
	Frame *Frame
	// TargetBinding supplies the target binding input to the Delete contract.
	TargetBinding *BoundIdentifier
	// UpdateBinding supplies the update binding input to the Delete contract.
	UpdateBinding *BoundIdentifier
}

Delete groups SQL model state that must remain consistent while translating delete.

type EdgeCreate added in v0.5.0

type EdgeCreate struct {
	// Binding supplies the binding input to the EdgeCreate contract.
	Binding *BoundIdentifier
	// Properties supplies the properties input to the EdgeCreate contract.
	Properties TranslatedProperties
	// Kinds supplies the kinds input to the EdgeCreate contract.
	Kinds graph.Kinds
	// LeftNode supplies the left node input to the EdgeCreate contract.
	LeftNode *BoundIdentifier
	// RightNode supplies the right node input to the EdgeCreate contract.
	RightNode *BoundIdentifier
	// Direction selects the traversal orientation covered by the contract.
	Direction graph.Direction
}

EdgeCreate groups SQL model state that must remain consistent while translating edge create.

type Expansion

type Expansion struct {
	// Frame is the scope frame that materializes the expansion result.
	Frame *Frame
	// PathBinding is the optional Cypher path variable backed by recursive path state.
	PathBinding *BoundIdentifier
	// Options records shortest-path mode and traversal depth bounds.
	Options ExpansionOptions

	// PrimerNodeConstraints restricts root nodes used to seed recursive traversal.
	PrimerNodeConstraints pgsql.Expression
	// PrimerNodeSatisfactionProjection evaluates terminal satisfaction at the seed node.
	PrimerNodeSatisfactionProjection pgsql.SelectItem
	// PrimerNodeJoinCondition joins the expansion seed to its root node.
	PrimerNodeJoinCondition pgsql.Expression
	// EdgeConstraints restricts relationships admitted into the expansion.
	EdgeConstraints pgsql.Expression
	// PreviousRelationshipUniqueness rejects relationships already traversed in this MATCH.
	PreviousRelationshipUniqueness pgsql.Expression
	// EdgeJoinCondition joins a relationship to the current traversal frontier.
	EdgeJoinCondition pgsql.Expression
	// RecursiveConstraints restricts recursive states independently of edge and node predicates.
	RecursiveConstraints pgsql.Expression
	// ExpansionNodeJoinCondition joins the traversed relationship to its next node.
	ExpansionNodeJoinCondition pgsql.Expression
	// TerminalNodeConstraints restricts nodes considered valid expansion terminals.
	TerminalNodeConstraints pgsql.Expression
	// TerminalNodeSatisfactionProjection computes whether a recursive state satisfies terminal predicates.
	TerminalNodeSatisfactionProjection pgsql.SelectItem
	// DeferredNodeSatisfactionConstraint retains terminal predicates that require outer bindings.
	DeferredNodeSatisfactionConstraint pgsql.Expression
	// UseMaterializedTerminalFilter enables lookup against precomputed terminal node IDs.
	UseMaterializedTerminalFilter bool
	// UseMaterializedEndpointPairFilter enables lookup against precomputed root-terminal ID pairs.
	UseMaterializedEndpointPairFilter bool
	// HasExplicitEndpointInequality reports whether the source query already excludes identical endpoints.
	HasExplicitEndpointInequality bool

	// PrimerQueryParameter identifies the harness parameter containing the forward primer query.
	PrimerQueryParameter *BoundIdentifier
	// BackwardPrimerQueryParameter identifies the harness parameter containing the backward primer query.
	BackwardPrimerQueryParameter *BoundIdentifier
	// RecursiveQueryParameter identifies the harness parameter containing the forward recursive query.
	RecursiveQueryParameter *BoundIdentifier
	// BackwardRecursiveQueryParameter identifies the harness parameter containing the backward recursive query.
	BackwardRecursiveQueryParameter *BoundIdentifier

	// UseBidirectionalSearch reports whether shortest-path traversal expands from both endpoints.
	UseBidirectionalSearch bool
	// ShortestPathExecutor selects the physical implementation for this shortest-path expansion.
	ShortestPathExecutor optimize.ShortestPathExecutor
	// ShortestPathTarget locates this expansion in the optimizer's lowering plan.
	ShortestPathTarget optimize.TraversalStepTarget
	// ShortestPathStateLimit caps distinct seen state for compact executors.
	ShortestPathStateLimit int64
	// ShortestPathFrontierLimit caps current and queued frontier state.
	ShortestPathFrontierLimit int64
	// ShortestPathPredecessorLimit caps retained witness predecessors.
	ShortestPathPredecessorLimit int64
	// ShortestPathEnumerationLimit caps staged all-shortest-path arrays.
	ShortestPathEnumerationLimit int64
	// ShortestPathOutputBytesLimit caps staged all-shortest-path array bytes.
	ShortestPathOutputBytesLimit int64
	// SingletonRootID holds the statically resolved root ID when exactly one root is known.
	SingletonRootID pgsql.Expression
	// SingletonTerminalID holds the statically resolved terminal ID when exactly one terminal is known.
	SingletonTerminalID pgsql.Expression
	// RelationshipKindIDs contains the statically resolved relationship kinds admitted by the expansion.
	RelationshipKindIDs []int16

	// EdgeStartIdentifier is the unqualified edge endpoint column from which the chosen direction advances.
	EdgeStartIdentifier pgsql.Identifier
	// EdgeStartColumn is the qualified edge endpoint expression from which the chosen direction advances.
	EdgeStartColumn pgsql.CompoundIdentifier
	// EdgeEndIdentifier is the unqualified edge endpoint column reached by the chosen direction.
	EdgeEndIdentifier pgsql.Identifier
	// EdgeEndColumn is the qualified edge endpoint expression reached by the chosen direction.
	EdgeEndColumn pgsql.CompoundIdentifier

	// Projection contains the select items exposed by the completed expansion frame.
	Projection []pgsql.SelectItem
}

Expansion contains the bindings, constraints, and execution choices for one variable-length traversal.

func NewExpansionModel

func NewExpansionModel(part *PatternPart, relationshipPattern *cypher.RelationshipPattern) *Expansion

NewExpansionModel builds the SQL model fragment responsible for new expansion model.

func (*Expansion) CanExecuteBidirectionalSearch

func (s *Expansion) CanExecuteBidirectionalSearch() bool

CanExecuteBidirectionalSearch builds the SQL model fragment responsible for can execute bidirectional search.

func (*Expansion) CompletePattern

func (s *Expansion) CompletePattern(traversalStep *TraversalStep) error

CompletePattern builds the SQL model fragment responsible for complete pattern.

func (*Expansion) FlipDirection

func (s *Expansion) FlipDirection()

FlipDirection builds the SQL model fragment responsible for flip direction.

func (*Expansion) UsesSingletonEndpointPair added in v1.0.0

func (s *Expansion) UsesSingletonEndpointPair() bool

UsesSingletonEndpointPair reports whether both expansion endpoints are statically singleton IDs.

type ExpansionBuilder

type ExpansionBuilder struct {
	// PrimerStatement produces the first traversal edge for each root.
	PrimerStatement pgsql.Select

	// RecursiveStatement advances each eligible expansion state by one edge.
	RecursiveStatement pgsql.Select

	// ProjectionStatement converts internal expansion state into the requested result shape.
	ProjectionStatement pgsql.Select

	// ZeroDepthStatement produces empty-path rows when the traversal admits depth zero.
	ZeroDepthStatement *pgsql.Select

	// UseUnionAll controls whether recursive branches retain duplicate states.
	UseUnionAll bool
	// contains filtered or unexported fields
}

ExpansionBuilder assembles the seed, recursive, and projection statements for one traversal expansion.

func NewExpansionBuilder

func NewExpansionBuilder(queryParameters map[string]any, traversalStep *TraversalStep, graphID int32) (*ExpansionBuilder, error)

NewExpansionBuilder validates traversal expansion state and constructs its SQL builder.

func (*ExpansionBuilder) Build

func (s *ExpansionBuilder) Build(expansionIdentifier pgsql.Identifier, commonTableExpressions ...pgsql.CommonTableExpression) pgsql.Query

Build combines the configured expansion stages into a recursive CTE and final projection query.

func (*ExpansionBuilder) BuildAllShortestPathsDAGRoot added in v1.0.0

func (s *ExpansionBuilder) BuildAllShortestPathsDAGRoot() (pgsql.Query, error)

BuildAllShortestPathsDAGRoot builds the bound-endpoint query that enumerates all shortest paths from a predecessor DAG.

func (*ExpansionBuilder) BuildAllShortestPathsNoPathProbeRoot added in v1.0.0

func (s *ExpansionBuilder) BuildAllShortestPathsNoPathProbeRoot() (pgsql.Query, error)

BuildAllShortestPathsNoPathProbeRoot builds the exact A1 wrapper that can return early only after bounded target-side reachability exhausts.

func (*ExpansionBuilder) BuildAllShortestPathsRoot

func (s *ExpansionBuilder) BuildAllShortestPathsRoot() (pgsql.Query, error)

BuildAllShortestPathsRoot builds a unidirectional all-shortest-paths harness query.

func (*ExpansionBuilder) BuildB1AllShortestPathsDAGRoot added in v1.0.0

func (s *ExpansionBuilder) BuildB1AllShortestPathsDAGRoot() (pgsql.Query, error)

BuildB1AllShortestPathsDAGRoot builds strict node-alternating two-sided predecessor-DAG enumeration.

func (*ExpansionBuilder) BuildB1CompactShortestPathRoot added in v1.0.0

func (s *ExpansionBuilder) BuildB1CompactShortestPathRoot() (pgsql.Query, error)

BuildB1CompactShortestPathRoot builds strict node-alternating compact bidirectional search.

func (*ExpansionBuilder) BuildB2AllShortestPathsDAGRoot added in v1.0.0

func (s *ExpansionBuilder) BuildB2AllShortestPathsDAGRoot() (pgsql.Query, error)

BuildB2AllShortestPathsDAGRoot builds smaller-current-level two-sided predecessor-DAG enumeration.

func (*ExpansionBuilder) BuildB2CompactShortestPathRoot added in v1.0.0

func (s *ExpansionBuilder) BuildB2CompactShortestPathRoot() (pgsql.Query, error)

BuildB2CompactShortestPathRoot builds smaller-current-level compact bidirectional search.

func (*ExpansionBuilder) BuildBiDirectionalAllShortestPathsRoot

func (s *ExpansionBuilder) BuildBiDirectionalAllShortestPathsRoot() (pgsql.Query, error)

BuildBiDirectionalAllShortestPathsRoot builds a bidirectional all-shortest-paths harness query.

func (*ExpansionBuilder) BuildBiDirectionalShortestPathsRoot added in v0.5.0

func (s *ExpansionBuilder) BuildBiDirectionalShortestPathsRoot() (pgsql.Query, error)

BuildBiDirectionalShortestPathsRoot builds a bidirectional single-shortest-path harness query.

func (*ExpansionBuilder) BuildBiDirectionalShortestPathsRootWithDirectPreflight added in v1.0.0

func (s *ExpansionBuilder) BuildBiDirectionalShortestPathsRootWithDirectPreflight() (pgsql.Query, error)

BuildBiDirectionalShortestPathsRootWithDirectPreflight emits the tool-only SP-S0-DIRECT arm. A materialized one-edge probe returns immediately when it finds a valid bound-endpoint witness. The workspace-backed incumbent is dependent on a zero-or-one-row fallback endpoint CTE, so PostgreSQL cannot invoke it on a direct hit. Both branches execute in one statement snapshot.

func (*ExpansionBuilder) BuildCompactShortestPathRoot added in v1.0.0

func (s *ExpansionBuilder) BuildCompactShortestPathRoot() (pgsql.Query, error)

BuildCompactShortestPathRoot builds the bound-endpoint query that returns one compact shortest-path witness.

func (*ExpansionBuilder) BuildInlineAllShortestPathsDAGRoot added in v1.0.0

func (s *ExpansionBuilder) BuildInlineAllShortestPathsDAGRoot() (pgsql.Query, error)

BuildInlineAllShortestPathsDAGRoot emits the guarded ASP-I1 predecessor-DAG statement.

func (*ExpansionBuilder) BuildInlineCanonicalShortestPathRoot added in v1.0.0

func (s *ExpansionBuilder) BuildInlineCanonicalShortestPathRoot() (pgsql.Query, error)

BuildInlineCanonicalShortestPathRoot emits one guarded canonical witness and invokes compact S4 exactly once if any candidate resource sentinel overflows.

func (*ExpansionBuilder) BuildInlineGuardedShortestDistanceRoot added in v1.0.0

func (s *ExpansionBuilder) BuildInlineGuardedShortestDistanceRoot() (pgsql.Query, error)

BuildInlineGuardedShortestDistanceRoot emits reverse-physical, ID-only minimum-distance discovery. The bounded candidate remains invisible until independent total-state and per-level frontier gates pass; overflow invokes exact compact S4 in the same top-level statement.

func (*ExpansionBuilder) BuildInlineGuardedShortestDistanceRootV2 added in v1.0.0

func (s *ExpansionBuilder) BuildInlineGuardedShortestDistanceRootV2() (pgsql.Query, error)

BuildInlineGuardedShortestDistanceRootV2 emits the selected E1 V2 architecture. Admission is materialized once before target selection. With production's equal caps, total-state admission dominates frontier admission and no GROUP BY depth aggregate is rendered. Unequal diagnostic caps retain exactly one independent frontier check.

func (*ExpansionBuilder) BuildShortestDistanceRoot added in v1.0.0

func (s *ExpansionBuilder) BuildShortestDistanceRoot() (pgsql.Query, error)

BuildShortestDistanceRoot emits the bounded, distance-only SP-S3-U-D recursive search. ID-only endpoint projections use only next ID and depth; other projections retain the constant root ID. Neither shape contains path, predecessor, visited-edge, cycle, or materialization columns.

func (*ExpansionBuilder) BuildShortestPathEdgeM0Root added in v1.0.0

func (s *ExpansionBuilder) BuildShortestPathEdgeM0Root() (pgsql.Query, error)

BuildShortestPathEdgeM0Root emits the bounded one-path SP-S3-U-E search and direction-aware MAT-M0 hydration. Recursive state contains only the current node, depth, and ordered edge IDs; node order is derived from edge endpoints.

func (*ExpansionBuilder) BuildShortestPathsRoot

func (s *ExpansionBuilder) BuildShortestPathsRoot() (pgsql.Query, error)

BuildShortestPathsRoot builds a unidirectional single-shortest-path harness query.

func (*ExpansionBuilder) SetUnwindClauses added in v0.6.0

func (s *ExpansionBuilder) SetUnwindClauses(clauses []UnwindClause)

SetUnwindClauses registers the active UNWIND bindings and their SQL sources for expansion queries.

type ExpansionOptions added in v0.3.1

type ExpansionOptions struct {
	// FindShortestPath identifies the filesystem find shortest path.
	FindShortestPath bool
	// FindAllShortestPaths identifies the filesystem find all shortest paths.
	FindAllShortestPaths bool
	// MinDepth supplies the min depth input to the ExpansionOptions contract.
	MinDepth models.Optional[int64]
	// MaxDepth supplies the max depth input to the ExpansionOptions contract.
	MaxDepth models.Optional[int64]
}

ExpansionOptions configures expansion.

type ExpressionTreeTranslator

type ExpressionTreeTranslator struct {
	UserConstraints        *ConstraintTracker
	TranslationConstraints *ConstraintTracker
	// contains filtered or unexported fields
}

func NewExpressionTreeTranslator

func NewExpressionTreeTranslator(kindMapper *contextAwareKindMapper) *ExpressionTreeTranslator

func (*ExpressionTreeTranslator) AddTranslationConstraint

func (s *ExpressionTreeTranslator) AddTranslationConstraint(requiredIdentifiers *pgsql.IdentifierSet, expression pgsql.Expression) error

func (*ExpressionTreeTranslator) AddUserConstraint

func (s *ExpressionTreeTranslator) AddUserConstraint(requiredIdentifiers *pgsql.IdentifierSet, expression pgsql.Expression) error

func (*ExpressionTreeTranslator) CompleteBinaryExpression

func (s *ExpressionTreeTranslator) CompleteBinaryExpression(scope *Scope, operator pgsql.Operator) error

func (*ExpressionTreeTranslator) CompleteExclusiveDisjunction added in v1.0.0

func (s *ExpressionTreeTranslator) CompleteExclusiveDisjunction(scope *Scope) error

CompleteExclusiveDisjunction lowers Boolean XOR to inequality while preserving both operand and result grouping: SQL comparisons cannot be chained.

func (*ExpressionTreeTranslator) ConstrainConjoinedOperandPair

func (s *ExpressionTreeTranslator) ConstrainConjoinedOperandPair() error

func (*ExpressionTreeTranslator) ConstrainDisjointOperandPair

func (s *ExpressionTreeTranslator) ConstrainDisjointOperandPair() error

func (*ExpressionTreeTranslator) ConsumeAllConstraints

func (s *ExpressionTreeTranslator) ConsumeAllConstraints() (*Constraint, error)

func (*ExpressionTreeTranslator) ConsumeConstraintsFromVisibleSet

func (s *ExpressionTreeTranslator) ConsumeConstraintsFromVisibleSet(visible *pgsql.IdentifierSet) (*Constraint, error)

func (*ExpressionTreeTranslator) HasAnyConstraints added in v0.4.11

func (s *ExpressionTreeTranslator) HasAnyConstraints(scope *pgsql.IdentifierSet) (bool, error)

HasAnyConstraints reports whether the supplied scope can evaluate any satisfiable user or translator constraint.

func (*ExpressionTreeTranslator) HasEndpointInequality added in v0.5.0

func (s *ExpressionTreeTranslator) HasEndpointInequality(leftEndpoint, rightEndpoint pgsql.Identifier) bool

func (*ExpressionTreeTranslator) PeekOperand

func (s *ExpressionTreeTranslator) PeekOperand() pgsql.Expression

func (*ExpressionTreeTranslator) PopBinaryExpression

func (s *ExpressionTreeTranslator) PopBinaryExpression(operator pgsql.Operator) (*pgsql.BinaryExpression, error)

func (*ExpressionTreeTranslator) PopOperand

func (s *ExpressionTreeTranslator) PopOperand() (pgsql.Expression, error)

func (*ExpressionTreeTranslator) PopParenthetical

func (s *ExpressionTreeTranslator) PopParenthetical() (*pgsql.Parenthetical, error)

func (*ExpressionTreeTranslator) PopRemainingExpressionsAsUserConstraints

func (s *ExpressionTreeTranslator) PopRemainingExpressionsAsUserConstraints() error

func (*ExpressionTreeTranslator) PushOperand

func (s *ExpressionTreeTranslator) PushOperand(expression pgsql.Expression)

func (*ExpressionTreeTranslator) PushParenthetical

func (s *ExpressionTreeTranslator) PushParenthetical()

func (*ExpressionTreeTranslator) VisitOperator

func (s *ExpressionTreeTranslator) VisitOperator(operator pgsql.Operator)

VisitOperator is retained for callers that visit operators before their operands. Operators are assembled on completion; only explicit predicate extraction adds constraints.

type Frame

type Frame struct {
	Previous *Frame
	Binding  *BoundIdentifier
	Visible  *pgsql.IdentifierSet

	Exported *pgsql.IdentifierSet

	Synthetic bool
	// contains filtered or unexported fields
}

Frame represents a snapshot of all identifiers defined and visible in a given scope

func (*Frame) Export

func (s *Frame) Export(identifier pgsql.Identifier)

func (*Frame) Known

func (s *Frame) Known() *pgsql.IdentifierSet

func (*Frame) RestoreStashed

func (s *Frame) RestoreStashed()

func (*Frame) Reveal

func (s *Frame) Reveal(identifier pgsql.Identifier)

func (*Frame) Stash

func (s *Frame) Stash(identifier pgsql.Identifier)

func (*Frame) Unexport

func (s *Frame) Unexport(identifer pgsql.Identifier)

type FrameBindingRewriter

type FrameBindingRewriter struct {
	walk.Visitor[pgsql.SyntaxNode]
	// contains filtered or unexported fields
}

func (*FrameBindingRewriter) Enter

func (s *FrameBindingRewriter) Enter(node pgsql.SyntaxNode)

func (*FrameBindingRewriter) Exit

func (s *FrameBindingRewriter) Exit(node pgsql.SyntaxNode)

type FromClauseBuilder added in v0.5.0

type FromClauseBuilder struct {
	// contains filtered or unexported fields
}

FromClauseBuilder groups SQL model state that must remain consistent while translating from clause builder.

func NewFromClauseBuilder added in v0.5.0

func NewFromClauseBuilder() *FromClauseBuilder

NewFromClauseBuilder builds the SQL model fragment responsible for new from clause builder.

func (*FromClauseBuilder) AddBinding added in v0.5.0

func (s *FromClauseBuilder) AddBinding(binding *BoundIdentifier)

AddBinding builds the SQL model fragment responsible for add binding.

func (*FromClauseBuilder) AddIdentifier added in v0.5.0

func (s *FromClauseBuilder) AddIdentifier(frameID pgsql.Identifier)

AddIdentifier builds the SQL model fragment responsible for add identifier.

func (*FromClauseBuilder) Clauses added in v0.5.0

func (s *FromClauseBuilder) Clauses() []pgsql.FromClause

Clauses builds the SQL model fragment responsible for clauses.

type IdentifierGenerator

type IdentifierGenerator map[pgsql.DataType]int

IdentifierGenerator is a map that creates a unique identifier for each call with a given data type. This ensures that renamed identifiers in queries do not conflict with each other.

func NewIdentifierGenerator

func NewIdentifierGenerator() IdentifierGenerator

func (IdentifierGenerator) NewIdentifier

func (s IdentifierGenerator) NewIdentifier(dataType pgsql.DataType) (pgsql.Identifier, error)

NewIdentifier allocates the next SQL identifier for the requested data type.

type LabelAssignment

type LabelAssignment struct {
	// Kinds supplies the kinds input to the LabelAssignment contract.
	Kinds pgsql.Expression
}

LabelAssignment groups SQL model state that must remain consistent while translating label assignment.

type Mutations

type Mutations struct {
	// Deletions supplies the deletions input to the Mutations contract.
	Deletions *graph.IndexedSlice[pgsql.Identifier, *Delete]
	// Updates supplies the updates input to the Mutations contract.
	Updates *graph.IndexedSlice[pgsql.Identifier, *Update]
	// Creations supplies the creations input to the Mutations contract.
	Creations *graph.IndexedSlice[pgsql.Identifier, *NodeCreate]
	// EdgeCreations supplies the edge creations input to the Mutations contract.
	EdgeCreations *graph.IndexedSlice[pgsql.Identifier, *EdgeCreate]
}

Mutations groups SQL model state that must remain consistent while translating mutations.

func NewMutations

func NewMutations() *Mutations

NewMutations builds the SQL model fragment responsible for new mutations.

func (*Mutations) AddDeletion

func (s *Mutations) AddDeletion(scope *Scope, targetIdentifier pgsql.Identifier, frame *Frame) (*Delete, error)

AddDeletion builds the SQL model fragment responsible for add deletion.

func (*Mutations) AddKindAssignment

func (s *Mutations) AddKindAssignment(scope *Scope, targetIdentifier pgsql.Identifier, kinds graph.Kinds) error

AddKindAssignment builds the SQL model fragment responsible for add kind assignment.

func (*Mutations) AddKindRemoval

func (s *Mutations) AddKindRemoval(scope *Scope, targetIdentifier pgsql.Identifier, kinds graph.Kinds) error

AddKindRemoval builds the SQL model fragment responsible for add kind removal.

func (*Mutations) AddPropertyAssignment

func (s *Mutations) AddPropertyAssignment(scope *Scope, propertyLookup PropertyLookup, operator pgsql.Operator, assignmentValueExpression pgsql.Expression) error

AddPropertyAssignment retains an assignment until its input frame is known. Binding expressions here would pin later targets to an earlier update stream.

func (*Mutations) AddPropertyRemoval

func (s *Mutations) AddPropertyRemoval(scope *Scope, propertyLookup PropertyLookup) error

AddPropertyRemoval builds the SQL model fragment responsible for add property removal.

type NodeCreate added in v0.5.0

type NodeCreate struct {
	// Binding supplies the binding input to the NodeCreate contract.
	Binding *BoundIdentifier
	// Properties supplies the properties input to the NodeCreate contract.
	Properties TranslatedProperties
	// Kinds supplies the kinds input to the NodeCreate contract.
	Kinds graph.Kinds
}

NodeCreate groups SQL model state that must remain consistent while translating node create.

type NodeSelect

type NodeSelect struct {
	// Frame supplies the frame input to the NodeSelect contract.
	Frame *Frame
	// Binding supplies the binding input to the NodeSelect contract.
	Binding *BoundIdentifier
	// Select supplies the select input to the NodeSelect contract.
	Select pgsql.Select
	// Constraints supplies the constraints input to the NodeSelect contract.
	Constraints pgsql.Expression
}

NodeSelect groups SQL model state that must remain consistent while translating node select.

type OptimizationSummary added in v0.6.0

type OptimizationSummary struct {
	// Rules contains the semantic optimizer rule results in execution order.
	Rules []optimize.RuleResult `json:"rules,omitempty"`
	// PredicateAttachments records optimizer-selected predicate scopes.
	PredicateAttachments []optimize.PredicateAttachment `json:"predicate_attachments,omitempty"`
	// PlannedLowerings summarizes lowering categories selected by the optimizer.
	PlannedLowerings []optimize.LoweringDecision `json:"planned_lowerings,omitempty"`
	// Lowerings summarizes lowering categories actually emitted by translation.
	Lowerings []optimize.LoweringDecision `json:"lowerings,omitempty"`
	// SkippedLowerings explains planned lowering applications that translation did not emit.
	SkippedLowerings []SkippedLowering `json:"skipped_lowerings,omitempty"`
	// TargetOutcomes reports selection and application results for each lowering target.
	TargetOutcomes []TargetLoweringOutcome `json:"target_outcomes,omitempty"`
	// LoweringPlan exposes the optimizer decisions used to translate the statement.
	LoweringPlan *optimize.LoweringPlan `json:"lowering_plan,omitempty"`
}

OptimizationSummary records which optimizer decisions were planned, applied, or skipped during translation.

type OptimizerMode added in v0.8.0

type OptimizerMode string

OptimizerMode controls whether PostgreSQL-specific rewrites and lowering decisions are applied during translation. Disabled mode remains a semantic fallback: it translates the original AST with an empty lowering plan.

const (
	OptimizerEnabled  OptimizerMode = "enabled"
	OptimizerDisabled OptimizerMode = "disabled"
)

func (OptimizerMode) Valid added in v0.8.0

func (s OptimizerMode) Valid() bool

type Options added in v0.8.0

type Options struct {
	OptimizerMode OptimizerMode
}

Options configures a translation without changing the default Translate API.

func DefaultOptions added in v0.8.0

func DefaultOptions() Options

type Pattern

type Pattern struct {
	// Parts supplies the parts input to the Pattern contract.
	Parts []*PatternPart
}

Pattern groups SQL model state that must remain consistent while translating pattern.

func (*Pattern) CurrentPart

func (s *Pattern) CurrentPart() *PatternPart

CurrentPart builds the SQL model fragment responsible for current part.

func (*Pattern) NewPart

func (s *Pattern) NewPart() *PatternPart

NewPart builds the SQL model fragment responsible for new part.

func (*Pattern) Reset

func (s *Pattern) Reset()

Reset builds the SQL model fragment responsible for reset.

type PatternConstraints

type PatternConstraints struct {
	LeftNode  *Constraint
	Edge      *Constraint
	RightNode *Constraint
}

PatternConstraints is a struct that represents all constraints that can be solved during a traversal step pattern: `()-[]->()`.

func (*PatternConstraints) FlipNodes

func (s *PatternConstraints) FlipNodes()

func (*PatternConstraints) OptimizePatternConstraintBalance

func (s *PatternConstraints) OptimizePatternConstraintBalance(scope *Scope, traversalStep *TraversalStep) (bool, error)

OptimizePatternConstraintBalance considers the constraints that apply to a pattern segment's bound identifiers.

If only the right side of the pattern segment is constrained, this could result in an imbalanced expansion where one side of the traversal has an extreme disparity in search space.

In cases that match this heuristic, it's beneficial to begin the traversal with the most tightly constrained set of nodes. The optimizer selectivity model decides whether the step should flip; this method only applies that decision to the translated constraint and traversal state.

type PatternPart

type PatternPart struct {
	// IsTraversal indicates whether is traversal applies.
	IsTraversal bool
	// ShortestPath identifies the filesystem shortest path.
	ShortestPath bool
	// AllShortestPaths identifies the filesystem all shortest paths.
	AllShortestPaths bool
	// PathDirectionReversed is set when the optimizer reversed the originating cypher pattern's
	// element order and relationship directions. Path materialization uses it to restore the
	// original left-to-right logical order for a bound path.
	PathDirectionReversed bool
	// PatternBinding supplies the pattern binding input to the PatternPart contract.
	PatternBinding *BoundIdentifier
	// Target supplies the target input to the PatternPart contract.
	Target optimize.PatternTarget
	// HasTarget indicates whether has target applies.
	HasTarget bool
	// TraversalSteps supplies the traversal steps input to the PatternPart contract.
	TraversalSteps []*TraversalStep
	// NodeSelect supplies the node select input to the PatternPart contract.
	NodeSelect NodeSelect
	// Constraints supplies the constraints input to the PatternPart contract.
	Constraints *ConstraintTracker
	// contains filtered or unexported fields
}

PatternPart groups SQL model state that must remain consistent while translating pattern part.

func (*PatternPart) ContainsExpansions

func (s *PatternPart) ContainsExpansions() bool

ContainsExpansions builds the SQL model fragment responsible for contains expansions.

func (*PatternPart) LastStep

func (s *PatternPart) LastStep() *TraversalStep

LastStep builds the SQL model fragment responsible for last step.

type ProductionFixedSuffixCaps added in v1.0.0

type ProductionFixedSuffixCaps struct {
	SuffixRowLimit   int64 `json:"suffix_row_limit"`
	StateLimit       int64 `json:"state_limit"`
	OutputRowLimit   int64 `json:"output_row_limit"`
	OutputBytesLimit int64 `json:"output_bytes_limit"`
}

ProductionFixedSuffixCaps bind the fixed-suffix candidate's SQL and driver buffering limits to one verified policy generation.

type ProductionOptions added in v1.0.0

type ProductionOptions struct {
	// ShortestPathExecutor supplies the shortest path executor input to the ProductionOptions contract.
	ShortestPathExecutor optimize.ShortestPathExecutor
	// ShortestPathCaps supplies the shortest path caps input to the ProductionOptions contract.
	ShortestPathCaps *ProductionShortestPathCaps
	// AuthorizedBucket supplies the authorized bucket input to the ProductionOptions contract.
	AuthorizedBucket *ProductionTraversalBucket
	// EnableExpansionOrientation indicates whether enable expansion orientation applies.
	EnableExpansionOrientation bool
	// EnableTopologyFixedSuffix enables the separately versioned production
	// reverse-only fixed-suffix candidate. Callers must supply immutable caps;
	// route selection and exact fallback remain driver responsibilities.
	EnableTopologyFixedSuffix bool
	// TopologyFixedSuffixCaps are the immutable candidate and output limits.
	TopologyFixedSuffixCaps *ProductionFixedSuffixCaps
	// ExpansionOrientationPolicy identifies the manifest-authorized immutable
	// runtime formula. Production callers must set it explicitly when enabling
	// orientation so v2 evidence cannot silently execute the v1 selector.
	ExpansionOrientationPolicy optimize.ExpansionSearchPolicy
	// DisableEndpointSeededReverse indicates whether disable endpoint seeded reverse applies.
	DisableEndpointSeededReverse bool
	// DisableInlineASPDAG indicates whether disable inline aspdag applies.
	DisableInlineASPDAG bool
	// DisableInlineSPWitness indicates whether disable inline sp witness applies.
	DisableInlineSPWitness bool
	// DisableInlineSPDistance is the emergency rollback switch for SP-I2-C-D.
	DisableInlineSPDistance bool
	// SelectorVersion identifies the schema version for selector version.
	SelectorVersion string
}

ProductionOptions contains the deliberately narrow subset of experimental lowerings that may be enabled by the PostgreSQL driver's versioned, query-allowlisted canary policy. The zero value preserves all incumbent production choices.

type ProductionShortestPathCaps added in v1.0.0

type ProductionShortestPathCaps struct {
	// StateLimit supplies the state limit input to the ProductionShortestPathCaps contract.
	StateLimit int64 `json:"state_limit"`
	// FrontierLimit caps rows admitted at any one breadth-first level.
	FrontierLimit int64 `json:"frontier_limit"`
	// PredecessorLimit supplies the predecessor limit input to the ProductionShortestPathCaps contract.
	PredecessorLimit int64 `json:"predecessor_limit"`
	// EnumerationLimit supplies the enumeration limit input to the ProductionShortestPathCaps contract.
	EnumerationLimit int64 `json:"enumeration_limit"`
	// OutputBytesLimit supplies the output bytes limit input to the ProductionShortestPathCaps contract.
	OutputBytesLimit int64 `json:"output_bytes_limit"`
}

ProductionShortestPathCaps are immutable manifest-authorized limits. They are copied into the lowering decision and therefore into emitted SQL.

type ProductionTraversalBucket added in v1.0.0

type ProductionTraversalBucket struct {
	// Direction selects the traversal orientation covered by the contract.
	Direction string `json:"direction"`
	// ObservationMode identifies the observation mode.
	ObservationMode string `json:"observation_mode"`
	// MinimumDepth sets the inclusive lower traversal-depth bound.
	MinimumDepth int64 `json:"minimum_depth"`
	// MaximumDepth sets the inclusive upper traversal-depth bound.
	MaximumDepth int64 `json:"maximum_depth"`
	// RelationshipKindCount records the number of relationship kind count.
	RelationshipKindCount int `json:"relationship_kind_count"`
	// UntypedRelationship indicates whether untyped relationship applies.
	UntypedRelationship bool `json:"untyped_relationship"`
}

ProductionTraversalBucket binds an exact-query authorization to the structural target characteristics independently qualified by evidence.

type Projection

type Projection struct {
	// SelectItem supplies the select item input to the Projection contract.
	SelectItem pgsql.SelectItem
	// Alias supplies the alias input to the Projection contract.
	Alias models.Optional[pgsql.Identifier]
}

Projection groups SQL model state that must remain consistent while translating projection.

func (*Projection) SetAlias

func (s *Projection) SetAlias(alias pgsql.Identifier)

SetAlias builds the SQL model fragment responsible for set alias.

func (*Projection) SetIdentifier

func (s *Projection) SetIdentifier(identifier pgsql.Identifier)

SetIdentifier builds the SQL model fragment responsible for set identifier.

type ProjectionPruningApplication added in v0.6.0

type ProjectionPruningApplication struct {
	// LeftNode supplies the left node input to the ProjectionPruningApplication contract.
	LeftNode *BoundIdentifier
	// Relationship supplies the relationship input to the ProjectionPruningApplication contract.
	Relationship *BoundIdentifier
	// RightNode supplies the right node input to the ProjectionPruningApplication contract.
	RightNode *BoundIdentifier
	// PathBinding supplies the path binding input to the ProjectionPruningApplication contract.
	PathBinding *BoundIdentifier
}

ProjectionPruningApplication groups SQL model state that must remain consistent while translating projection pruning application.

type Projections

type Projections struct {
	// Distinct indicates whether distinct applies.
	Distinct bool
	// Frame supplies the frame input to the Projections contract.
	Frame *Frame
	// Constraints supplies the constraints input to the Projections contract.
	Constraints pgsql.Expression
	// OutputConstraints evaluates a WITH predicate for filtering after its row modifiers.
	OutputConstraints pgsql.Expression
	// Items supplies the items input to the Projections contract.
	Items []*Projection
	// GroupBy supplies the group by input to the Projections contract.
	GroupBy []pgsql.Expression
}

Projections groups SQL model state that must remain consistent while translating projections.

func (*Projections) Add

func (s *Projections) Add(projection *Projection)

Add builds the SQL model fragment responsible for add.

func (*Projections) Current

func (s *Projections) Current() *Projection

Current builds the SQL model fragment responsible for current.

type PropertyAssignment

type PropertyAssignment struct {
	// Field supplies the field input to the PropertyAssignment contract.
	Field string
	// Operator supplies the operator input to the PropertyAssignment contract.
	Operator pgsql.Operator
	// ValueExpression supplies the value expression input to the PropertyAssignment contract.
	ValueExpression pgsql.Expression
}

PropertyAssignment groups SQL model state that must remain consistent while translating property assignment.

type PropertyLookup

type PropertyLookup struct {
	Reference pgsql.CompoundIdentifier
	Field     string
}

type Query

type Query struct {
	// Parts supplies the parts input to the Query contract.
	Parts []*QueryPart
}

Query groups SQL model state that must remain consistent while translating query.

func (*Query) AddPart

func (s *Query) AddPart(part *QueryPart)

AddPart builds the SQL model fragment responsible for add part.

func (*Query) CurrentPart

func (s *Query) CurrentPart() *QueryPart

CurrentPart builds the SQL model fragment responsible for current part.

func (*Query) HasParts

func (s *Query) HasParts() bool

HasParts builds the SQL model fragment responsible for has parts.

type QueryPart

type QueryPart struct {
	// Model supplies the model input to the QueryPart contract.
	Model *pgsql.Query
	// Frame supplies the frame input to the QueryPart contract.
	Frame *Frame
	// Updates supplies the updates input to the QueryPart contract.
	Updates []*Mutations
	// SortItems supplies the sort items input to the QueryPart contract.
	SortItems []*pgsql.OrderBy
	// Skip supplies the skip input to the QueryPart contract.
	Skip pgsql.Expression
	// Limit supplies the limit input to the QueryPart contract.
	Limit pgsql.Expression
	// contains filtered or unexported fields
}

QueryPart groups SQL model state that must remain consistent while translating query part.

func NewQueryPart

func NewQueryPart(numReadingClauses, numUpdatingClauses int) *QueryPart

NewQueryPart builds the SQL model fragment responsible for new query part.

func (*QueryPart) AddFromClause

func (s *QueryPart) AddFromClause(clause pgsql.FromClause)

AddFromClause builds the SQL model fragment responsible for add from clause.

func (*QueryPart) AddPathEdgeIDArrayFuture added in v0.7.0

func (s *QueryPart) AddPathEdgeIDArrayFuture(pathEdgeIDArrayFuture *pgsql.Future[*BoundIdentifier])

AddPathEdgeIDArrayFuture builds the SQL model fragment responsible for add path edge id array future.

func (*QueryPart) AddPatternPredicateFuture

func (s *QueryPart) AddPatternPredicateFuture(predicateFuture *pgsql.Future[*Pattern])

AddPatternPredicateFuture builds the SQL model fragment responsible for add pattern predicate future.

func (*QueryPart) AddProperty

func (s *QueryPart) AddProperty(key string, expression pgsql.Expression)

AddProperty builds the SQL model fragment responsible for add property.

func (*QueryPart) AddPropertyParameter added in v0.5.0

func (s *QueryPart) AddPropertyParameter(expression pgsql.Expression)

AddPropertyParameter builds the SQL model fragment responsible for add property parameter.

func (*QueryPart) AddUnwindClause added in v0.5.0

func (s *QueryPart) AddUnwindClause(clause UnwindClause)

AddUnwindClause builds the SQL model fragment responsible for add unwind clause.

func (*QueryPart) AllowLimitPushdown added in v0.5.0

func (s *QueryPart) AllowLimitPushdown(frameIdentifier pgsql.Identifier)

AllowLimitPushdown builds the SQL model fragment responsible for allow limit pushdown.

func (*QueryPart) CanPushDownLimitTo added in v0.5.0

func (s *QueryPart) CanPushDownLimitTo(frameIdentifier pgsql.Identifier) bool

CanPushDownLimitTo builds the SQL model fragment responsible for can push down limit to.

func (*QueryPart) ConsumeCurrentPattern

func (s *QueryPart) ConsumeCurrentPattern() *Pattern

ConsumeCurrentPattern builds the SQL model fragment responsible for consume current pattern.

func (*QueryPart) ConsumeFromClauses

func (s *QueryPart) ConsumeFromClauses() []pgsql.FromClause

ConsumeFromClauses builds the SQL model fragment responsible for consume from clauses.

func (*QueryPart) ConsumeProperties

func (s *QueryPart) ConsumeProperties() TranslatedProperties

ConsumeProperties builds the SQL model fragment responsible for consume properties.

func (*QueryPart) ConsumeUnwindClauses added in v0.5.0

func (s *QueryPart) ConsumeUnwindClauses() []UnwindClause

ConsumeUnwindClauses builds the SQL model fragment responsible for consume unwind clauses.

func (*QueryPart) CurrentOrderBy

func (s *QueryPart) CurrentOrderBy() *pgsql.OrderBy

CurrentOrderBy builds the SQL model fragment responsible for current order by.

func (*QueryPart) CurrentProjection

func (s *QueryPart) CurrentProjection() *Projection

CurrentProjection constructs the SQL model used for current projection.

func (*QueryPart) HasCurrentProjection added in v1.0.0

func (s *QueryPart) HasCurrentProjection() bool

HasCurrentProjection reports whether a projection item is being translated without requiring projection state to already exist.

func (*QueryPart) HasDeletions

func (s *QueryPart) HasDeletions() bool

HasDeletions builds the SQL model fragment responsible for has deletions.

func (*QueryPart) HasMutations

func (s *QueryPart) HasMutations() bool

HasMutations builds the SQL model fragment responsible for has mutations.

func (*QueryPart) HasProjections

func (s *QueryPart) HasProjections() bool

HasProjections builds the SQL model fragment responsible for has projections.

func (*QueryPart) HasProperties

func (s *QueryPart) HasProperties() bool

HasProperties builds the SQL model fragment responsible for has properties.

func (*QueryPart) PrepareMutations

func (s *QueryPart) PrepareMutations()

PrepareMutations builds the SQL model fragment responsible for prepare mutations.

func (*QueryPart) PrepareProjection

func (s *QueryPart) PrepareProjection()

PrepareProjection constructs the SQL model used for prepare projection.

func (*QueryPart) PrepareProjections

func (s *QueryPart) PrepareProjections(distinct bool)

PrepareProjections builds the SQL model fragment responsible for prepare projections.

func (*QueryPart) ReferencesBinding added in v0.5.0

func (s *QueryPart) ReferencesBinding(binding *BoundIdentifier) bool

func (*QueryPart) ReferencesSourceIdentifier added in v0.5.0

func (s *QueryPart) ReferencesSourceIdentifier(identifier pgsql.Identifier) bool

func (*QueryPart) RestoreStashedPattern

func (s *QueryPart) RestoreStashedPattern()

RestoreStashedPattern builds the SQL model fragment responsible for restore stashed pattern.

func (*QueryPart) SetReferencedIdentifiers added in v0.5.0

func (s *QueryPart) SetReferencedIdentifiers(referencedIdentifiers *pgsql.IdentifierSet)

func (*QueryPart) StashCurrentPattern

func (s *QueryPart) StashCurrentPattern()

StashCurrentPattern builds the SQL model fragment responsible for stash current pattern.

type QueryStage added in v1.0.0

type QueryStage struct {
	Binding pgsql.Identifier
	Query   pgsql.Query
}

QueryStage is one statement in a query with sequential mutations. Binding names the output consumed by subsequent stages; the final stage has no binding.

type Removal

type Removal struct {
	// Field supplies the field input to the Removal contract.
	Field string
}

Removal groups SQL model state that must remain consistent while translating removal.

type Result

type Result struct {
	// HasMissingKinds marks plans that depend on absent kind definitions. Caches must
	// bypass these plans so a later kind registration can change the match result.
	HasMissingKinds bool
	// Statement is the translated PostgreSQL AST.
	Statement pgsql.Statement
	// Stages preserves statement boundaries around sequential mutations.
	// Staged translations must be formatted and executed in order in one transaction.
	Stages []QueryStage
	// Parameters contains SQL parameters generated during translation.
	Parameters map[string]any
	// LiteralParameters contains immutable string literals extracted during SQL formatting.
	LiteralParameters map[string]string
	// ParameterSources maps generated SQL parameter names back to Cypher parameter names.
	ParameterSources map[string]string
	// Optimization summarizes planned, applied, and skipped lowering decisions.
	Optimization OptimizationSummary
	// GraphID identifies the graph partitions targeted by the statement.
	GraphID int32
}

Result contains the translated PostgreSQL statement, parameters, graph target, and optimization diagnostics.

func Translate

func Translate(ctx context.Context, cypherQuery *cypher.RegularQuery, kindMapper pgsql.KindMapper, parameters map[string]any, graphID int32) (Result, error)

Translate optimizes and translates a Cypher query for the selected graph using production lowering choices.

func TranslateForTool added in v1.0.0

func TranslateForTool(ctx context.Context, cypherQuery *cypher.RegularQuery, kindMapper pgsql.KindMapper, parameters map[string]any, graphID int32, options ToolOptions) (Result, error)

TranslateForTool exposes qualified experimental lowerings to repository tooling without making them selectable through the production query API.

func TranslateWithOptions added in v0.8.0

func TranslateWithOptions(ctx context.Context, cypherQuery *cypher.RegularQuery, kindMapper pgsql.KindMapper, parameters map[string]any, graphID int32, options Options) (Result, error)

TranslateWithOptions translates Cypher with an explicit optimizer policy.

func TranslateWithOptionsAndParameterSources added in v0.8.0

func TranslateWithOptionsAndParameterSources(ctx context.Context, cypherQuery *cypher.RegularQuery, kindMapper pgsql.KindMapper, parameters map[string]any, graphID int32, options Options) (Result, map[string]string, error)

TranslateWithOptionsAndParameterSources translates Cypher and returns the generated-parameter provenance required to safely rebind a cached result. The input tree is borrowed: it is copied only if an optimizer rule mutates it. This is intended for compilation code that owns the input tree.

func TranslateWithProductionOptions added in v1.0.0

func TranslateWithProductionOptions(ctx context.Context, cypherQuery *cypher.RegularQuery, kindMapper pgsql.KindMapper, parameters map[string]any, graphID int32, options ProductionOptions) (Result, error)

TranslateWithProductionOptions applies a validated canary policy. B executors remain unavailable unless the driver has independently established the required transaction snapshot; this function only controls lowering.

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

Scope contains all identifier definitions and their temporal resolutions in a []*Frame field.

Frames may be pushed onto the stack, advancing the scope of the query to the next component. Frames may be popped from the stack, rewinding visibility to an earlier temporal state. This is useful when navigating subqueries and nested expressions that require their own descendent scope lifecycle.

Each frame is associated with an identifier that represents the query AST element that contains all visible projections. This is required when disambiguating references that otherwise belong to a frame.

func NewScope

func NewScope() *Scope

func (*Scope) Alias

func (s *Scope) Alias(alias pgsql.Identifier, binding *BoundIdentifier)

func (*Scope) AliasedLookup

func (s *Scope) AliasedLookup(identifier pgsql.Identifier) (*BoundIdentifier, bool)

func (*Scope) CurrentFrame

func (s *Scope) CurrentFrame() *Frame

func (*Scope) CurrentFrameBinding

func (s *Scope) CurrentFrameBinding() *BoundIdentifier

func (*Scope) Declare

func (s *Scope) Declare(identifier pgsql.Identifier)

func (*Scope) Define

func (s *Scope) Define(identifier pgsql.Identifier, dataType pgsql.DataType) *BoundIdentifier

func (*Scope) DefineNew

func (s *Scope) DefineNew(dataType pgsql.DataType) (*BoundIdentifier, error)

func (*Scope) FrameAt

func (s *Scope) FrameAt(depth int) *Frame

func (*Scope) GraphID added in v1.0.0

func (s *Scope) GraphID() int32

GraphID returns the graph used for graph-scoped table references in this scope.

func (*Scope) IsMaterialized

func (s *Scope) IsMaterialized(identifier pgsql.Identifier) bool

func (*Scope) Lookup

func (s *Scope) Lookup(identifier pgsql.Identifier) (*BoundIdentifier, bool)

func (*Scope) LookupBindings

func (s *Scope) LookupBindings(identifiers ...pgsql.Identifier) ([]*BoundIdentifier, error)

func (*Scope) LookupDataType added in v0.6.0

func (s *Scope) LookupDataType(identifier pgsql.Identifier) (pgsql.DataType, bool)

func (*Scope) LookupString

func (s *Scope) LookupString(identifierString string) (*BoundIdentifier, bool)

func (*Scope) PopFrame

func (s *Scope) PopFrame() error

func (*Scope) PreviousFrame

func (s *Scope) PreviousFrame() *Frame

func (*Scope) PruneDefinitions

func (s *Scope) PruneDefinitions(protectedIdentifiers *pgsql.IdentifierSet) error

func (*Scope) PushFrame

func (s *Scope) PushFrame() (*Frame, error)

func (*Scope) ReferenceFrame

func (s *Scope) ReferenceFrame() *Frame

func (*Scope) SetGraphID added in v1.0.0

func (s *Scope) SetGraphID(graphID int32)

SetGraphID sets the graph used for graph-scoped table references created in this scope.

func (*Scope) Snapshot

func (s *Scope) Snapshot() *Scope

func (*Scope) Symbol added in v1.0.0

func (s *Scope) Symbol(binding *BoundIdentifier) (pgsql.Identifier, bool)

Symbol returns the first deterministic symbol that aliases binding.

func (*Scope) Symbols added in v1.0.0

func (s *Scope) Symbols(binding *BoundIdentifier) []pgsql.Identifier

Symbols returns every symbol that aliases binding in lexical order.

func (*Scope) UnwindToFrame

func (s *Scope) UnwindToFrame(frame *Frame) error

func (*Scope) Visible

func (s *Scope) Visible() *pgsql.IdentifierSet

type SkippedLowering added in v0.6.0

type SkippedLowering struct {
	// Name identifies the name.
	Name string `json:"name"`
	// Reason supplies the reason input to the SkippedLowering contract.
	Reason string `json:"reason"`
	// Count records the number of count.
	Count int `json:"count,omitempty"`
}

SkippedLowering groups SQL model state that must remain consistent while translating skipped lowering.

type TargetEligibilityFact added in v1.0.0

type TargetEligibilityFact struct {
	// Name identifies the qualification check.
	Name string `json:"name"`
	// Eligible reports whether the target passed the named check.
	Eligible bool `json:"eligible"`
}

TargetEligibilityFact reports one named qualification result in a translated target outcome.

type TargetLoweringOutcome added in v1.0.0

type TargetLoweringOutcome struct {
	// Lowering names the lowering pass that produced this outcome.
	Lowering string `json:"lowering"`
	// TargetKind identifies the kind of syntax or binding targeted by the lowering.
	TargetKind string `json:"target_kind"`
	// TraversalTarget locates a traversal-step target when the lowering applies to one.
	TraversalTarget *optimize.TraversalStepTarget `json:"traversal_target,omitempty"`
	// QueryPartIndex locates a query-part target when the lowering applies to one.
	QueryPartIndex *int `json:"query_part_index,omitempty"`
	// Symbol identifies a binding target when the lowering applies to one.
	Symbol string `json:"symbol,omitempty"`
	// Family names the candidate-selection family that produced this outcome.
	Family string `json:"family,omitempty"`
	// TraversalFamily preserves the SP/ASP family for analysis-only decisions
	// whose outcome family must remain distinct from an executable traversal.
	TraversalFamily string `json:"traversal_family,omitempty"`
	// PlannedPolicy identifies the runtime policy intended for this candidate
	// family, whether or not it was emitted.
	PlannedPolicy string `json:"planned_policy,omitempty"`
	// EmittedPolicy identifies a runtime policy present in translated SQL. A
	// single incumbent or tool-forced arm has no emitted policy identity.
	EmittedPolicy string `json:"emitted_policy,omitempty"`
	// PlannedCandidates lists the candidates considered in preference order.
	PlannedCandidates []string `json:"planned_candidates,omitempty"`
	// EmittedCandidates lists the arms present in translated SQL. Runtime
	// telemetry separately records which arm executed.
	EmittedCandidates []string `json:"emitted_candidates,omitempty"`
	// ProbeCaps records bounded evidence inputs for an expansion policy.
	ProbeCaps *optimize.ExpansionSearchProbeCaps `json:"probe_caps,omitempty"`
	// Admission supplies the admission input to the TargetLoweringOutcome contract.
	Admission *optimize.ExpansionSearchAdmission `json:"admission,omitempty"`
	// EndpointRoot and EndpointTerminal describe the bounded endpoint inputs
	// considered by analysis without implying that translation emitted them.
	EndpointRoot *optimize.EndpointResolutionInput `json:"endpoint_root,omitempty"`
	// EndpointTerminal supplies the endpoint terminal input to the TargetLoweringOutcome contract.
	EndpointTerminal *optimize.EndpointResolutionInput `json:"endpoint_terminal,omitempty"`
	// EndpointPairClass records a correlation class when endpoint resolution
	// must preserve a paired input rather than independent endpoint sets.
	EndpointPairClass optimize.EndpointResolutionClass `json:"endpoint_pair_class,omitempty"`
	// EndpointResolutionCaps records immutable 1/2/32/33 admission sentinels.
	EndpointResolutionCaps *optimize.EndpointResolutionCaps `json:"endpoint_resolution_caps,omitempty"`
	// PredicateClass and its source/index expose conservative traversal
	// predicate placement analysis as a first-class target outcome.
	PredicateClass optimize.TraversalPredicateClass `json:"predicate_class,omitempty"`
	// PredicateSource supplies the predicate source input to the TargetLoweringOutcome contract.
	PredicateSource string `json:"predicate_source,omitempty"`
	// PredicateIndex supplies the predicate index input to the TargetLoweringOutcome contract.
	PredicateIndex *int `json:"predicate_index,omitempty"`
	// Scheduler identifies the selected shortest-path frontier scheduling policy.
	Scheduler string `json:"scheduler,omitempty"`
	// ExecutionBoundary identifies whether the selected executor is inline SQL,
	// a stored helper, or a guarded multi-arm statement.
	ExecutionBoundary string `json:"execution_boundary,omitempty"`
	// Candidate is the specialized candidate proposed by analysis.
	Candidate string `json:"candidate,omitempty"`
	// EligibilityFacts records named qualification checks for the candidate.
	EligibilityFacts []TargetEligibilityFact `json:"eligibility_facts,omitempty"`
	// ObservationMode describes how downstream clauses consume the target.
	ObservationMode string `json:"observation_mode,omitempty"`
	// Direction selects the traversal orientation covered by the contract.
	Direction string `json:"direction,omitempty"`
	// PhysicalExpansion supplies the physical expansion input to the TargetLoweringOutcome contract.
	PhysicalExpansion string `json:"physical_expansion,omitempty"`
	// RelationshipKindCount is the number of statically resolved relationship kinds.
	RelationshipKindCount int `json:"relationship_kind_count,omitempty"`
	// UntypedRelationship reports whether the pattern omitted relationship kinds.
	UntypedRelationship bool `json:"untyped_relationship,omitempty"`
	// TopologyClassification summarizes logical direction, physical direction, and depth.
	TopologyClassification string `json:"topology_classification,omitempty"`
	// Eligible reports the structural qualification result when one is available.
	Eligible *bool `json:"eligible,omitempty"`
	// StaticallyEligible reports the literal- and kind-based qualification result when available.
	StaticallyEligible *bool `json:"statically_eligible,omitempty"`
	// SelectionMode records whether selection was automatic or forced by tooling.
	SelectionMode string `json:"selection_mode,omitempty"`
	// SelectorVersion identifies the policy version that ranked candidates.
	SelectorVersion string `json:"selector_version,omitempty"`
	// Fallback names the candidate used if the preferred lowering was not applied.
	Fallback string `json:"fallback,omitempty"`
	// MinimumDepth is the target's inclusive lower traversal-depth bound.
	MinimumDepth *int64 `json:"minimum_depth,omitempty"`
	// MaximumDepth is the target's inclusive upper traversal-depth bound when finite.
	MaximumDepth *int64 `json:"maximum_depth,omitempty"`
	// MaximumDepthSource distinguishes an explicit upper bound from the
	// repository's existing effective cap for syntax-open shortest paths.
	MaximumDepthSource string `json:"maximum_depth_source,omitempty"`
	// StateLimit is the maximum intermediate-state count admitted by the candidate.
	StateLimit int64 `json:"state_limit,omitempty"`
	// FrontierLimit is the maximum current or queued frontier size admitted by a shortest-path candidate.
	FrontierLimit int64 `json:"frontier_limit,omitempty"`
	// PredecessorLimit is the maximum retained witness predecessor state admitted by a shortest-path candidate.
	PredecessorLimit int64 `json:"predecessor_limit,omitempty"`
	// EnumerationLimit is the maximum distinct ordered path count staged by an all-shortest-path candidate.
	EnumerationLimit int64 `json:"enumeration_limit,omitempty"`
	// OutputBytesLimit is the maximum staged ordered edge-array bytes admitted by an all-shortest-path candidate.
	OutputBytesLimit int64 `json:"output_bytes_limit,omitempty"`
	// EndpointLimit is the maximum endpoint-seed count admitted by the candidate.
	EndpointLimit int64 `json:"endpoint_limit,omitempty"`
	// SeedPredicateClass describes the predicate used to bound search seeds.
	SeedPredicateClass string `json:"seed_predicate_class,omitempty"`
	// PrefixLength is the number of fixed steps before the variable expansion.
	PrefixLength int `json:"prefix_length,omitempty"`
	// HasFinalLimit reports whether a final row limit influenced candidate selection.
	HasFinalLimit bool `json:"has_final_limit,omitempty"`
	// Selected names the candidate selected by the optimizer.
	Selected string `json:"selected,omitempty"`
	// Applied names the candidate actually emitted by translation.
	Applied string `json:"applied,omitempty"`
	// SkipReason explains why a planned candidate was not emitted.
	SkipReason string `json:"skip_reason,omitempty"`
}

TargetLoweringOutcome reports how one planned lowering target was qualified, selected, and applied.

type ToolOptions added in v1.0.0

type ToolOptions struct {
	// ForceShortestPathExecutor requests a qualified shortest-path executor instead of automatic selection.
	ForceShortestPathExecutor optimize.ShortestPathExecutor
	// GuardedDistanceStateLimit overrides SP-I2's cap+1 state admission only for
	// diagnostic tool forcing. It must be paired with a positive frontier limit.
	GuardedDistanceStateLimit int64
	// GuardedDistanceFrontierLimit overrides SP-I2's per-level frontier admission
	// only for diagnostic tool forcing. Production caps remain immutable.
	GuardedDistanceFrontierLimit int64
	// ForceExpansionSearchStrategy requests a qualified variable-expansion strategy instead of automatic selection.
	ForceExpansionSearchStrategy optimize.ExpansionSearchStrategy
	// ExpansionOrientationPolicy selects the immutable orientation selector
	// identity used by an enabled tournament or shadow mode. The zero value
	// preserves orientation-probe-v1.
	ExpansionOrientationPolicy optimize.ExpansionSearchPolicy
	// EnableExpansionOrientationTournament emits a guarded orientation policy
	// for one qualified fixed-suffix expansion. It defaults to
	// orientation-probe-v1 and is intentionally tool-only while selectors are
	// being shadow-qualified.
	EnableExpansionOrientationTournament bool
	// EnableExpansionOrientationShadow emits the same bounded orientation
	// probes and SQL-visible would_select metadata while executing only the
	// exact incumbent traversal arm.
	EnableExpansionOrientationShadow bool
	// EnableExpansionSuffixReverseGuard emits bounded fixed-suffix reverse
	// execution with exact stepwise-forward fallback for one statically eligible
	// full-path observation. It is deliberately tool-only during qualification.
	EnableExpansionSuffixReverseGuard bool
	// EnableExpansionSuffixReverseRetry emits only the bounded fixed-suffix
	// reverse candidate. The PostgreSQL tool transaction owns exact forward
	// retry; this option never installs a production selector.
	EnableExpansionSuffixReverseRetry bool
	// EnableExpansionSuffixRouteComponent emits one exact suffix-seeded reverse
	// statement with a runtime receipt. It is a default-off GraphBench component
	// arm and has no retry, probe, cache, or production policy.
	EnableExpansionSuffixRouteComponent bool
	// SuffixReverseGuardSuffixRowLimit overrides the tool-only fixed-suffix
	// payload cap. Zero selects ExpansionSearchSuffixReverseGuardSuffixRowLimit.
	SuffixReverseGuardSuffixRowLimit int64
	// SuffixReverseGuardStateLimit overrides the tool-only reverse-state cap.
	// Zero selects ExpansionSearchSuffixReverseGuardStateLimit.
	SuffixReverseGuardStateLimit int64
	// SuffixReverseRetryOutputRowLimit caps buffered candidate rows. Zero selects
	// ExpansionSearchSuffixReverseRetryOutputRowLimit.
	SuffixReverseRetryOutputRowLimit int64
	// SuffixReverseRetryOutputBytesLimit caps buffered candidate bytes. Zero
	// selects ExpansionSearchSuffixReverseRetryOutputBytesLimit.
	SuffixReverseRetryOutputBytesLimit int64
	// DisableEndpointSeededReverse is an emergency production rollback switch.
	DisableEndpointSeededReverse bool
}

ToolOptions controls experimental lowering selection exposed only to repository tooling.

type TranslatedProperties added in v0.5.0

type TranslatedProperties struct {
	// Map supplies the map input to the TranslatedProperties contract.
	Map map[string]pgsql.Expression
	// Parameter supplies the parameter input to the TranslatedProperties contract.
	Parameter pgsql.Expression
}

TranslatedProperties groups SQL model state that must remain consistent while translating translated properties.

func NewTranslatedProperties added in v0.5.0

func NewTranslatedProperties() TranslatedProperties

NewTranslatedProperties builds the SQL model fragment responsible for new translated properties.

func (TranslatedProperties) IsEmpty added in v0.5.0

func (s TranslatedProperties) IsEmpty() bool

IsEmpty builds the SQL model fragment responsible for is empty.

type Translator

type Translator struct {
	// Visitor supplies traversal control and error propagation for the Cypher walk.
	walk.Visitor[cypher.SyntaxNode]
	// contains filtered or unexported fields
}

Translator walks an optimized Cypher AST and constructs the corresponding PostgreSQL AST.

func NewTranslator

func NewTranslator(ctx context.Context, kindMapper pgsql.KindMapper, parameters map[string]any, graphID int32) *Translator

NewTranslator initializes translation state for the supplied graph and copies the caller's parameter map.

func (*Translator) Enter

func (s *Translator) Enter(expression cypher.SyntaxNode)

Enter translates a Cypher syntax node when the walker reaches it.

func (*Translator) Exit

func (s *Translator) Exit(expression cypher.SyntaxNode)

Exit builds the SQL model fragment responsible for exit.

func (*Translator) SetOptimizationPlan added in v0.6.0

func (s *Translator) SetOptimizationPlan(plan optimize.Plan)

SetOptimizationPlan indexes lowering decisions by their stable targets for use during AST traversal.

type TraversalStep

type TraversalStep struct {
	// Frame supplies the frame input to the TraversalStep contract.
	Frame *Frame
	// SourceTarget supplies the source target input to the TraversalStep contract.
	SourceTarget optimize.TraversalStepTarget
	// HasSourceTarget indicates whether has source target applies.
	HasSourceTarget bool
	// Direction selects the traversal orientation covered by the contract.
	Direction graph.Direction
	// Expansion supplies the expansion input to the TraversalStep contract.
	Expansion *Expansion
	// PathReversed indicates whether path reversed applies.
	PathReversed bool

	// OmitPreviousFrameSource suppresses comma-joining the previous frame as a FROM source. Pattern
	// predicate roots require this so that references to the enclosing query part's frame remain
	// correlated to the outer row instead of re-scanning the outer CTE.
	OmitPreviousFrameSource bool

	// ProjectionPruning supplies the projection pruning input to the TraversalStep contract.
	ProjectionPruning ProjectionPruningApplication
	// LeftNode supplies the left node input to the TraversalStep contract.
	LeftNode *BoundIdentifier
	// LeftNodeBound indicates whether left node bound applies.
	LeftNodeBound bool
	// UseExpandInto indicates whether use expand into applies.
	UseExpandInto bool
	// LeftNodeConstraints supplies the left node constraints input to the TraversalStep contract.
	LeftNodeConstraints pgsql.Expression
	// LeftNodeJoinCondition supplies the left node join condition input to the TraversalStep contract.
	LeftNodeJoinCondition pgsql.Expression
	// Edge supplies the edge input to the TraversalStep contract.
	Edge *BoundIdentifier
	// EdgeConstraints supplies the edge constraints input to the TraversalStep contract.
	EdgeConstraints *Constraint
	// EdgeJoinCondition supplies the edge join condition input to the TraversalStep contract.
	EdgeJoinCondition pgsql.Expression
	// RightNode supplies the right node input to the TraversalStep contract.
	RightNode *BoundIdentifier
	// RightNodeBound indicates whether right node bound applies.
	RightNodeBound bool
	// RightNodeConstraints supplies the right node constraints input to the TraversalStep contract.
	RightNodeConstraints pgsql.Expression
	// RightNodeJoinCondition supplies the right node join condition input to the TraversalStep contract.
	RightNodeJoinCondition pgsql.Expression
	// Projection supplies the projection input to the TraversalStep contract.
	Projection []pgsql.SelectItem
}

TraversalStep groups SQL model state that must remain consistent while translating traversal step.

func (*TraversalStep) CanExecuteBidirectionalSearch added in v0.5.0

func (s *TraversalStep) CanExecuteBidirectionalSearch() bool

CanExecuteBidirectionalSearch builds the SQL model fragment responsible for can execute bidirectional search.

func (*TraversalStep) CanExecutePairAwareBidirectionalSearch added in v0.5.0

func (s *TraversalStep) CanExecutePairAwareBidirectionalSearch(scope *Scope) (bool, error)

CanExecutePairAwareBidirectionalSearch builds the SQL model fragment responsible for can execute pair aware bidirectional search.

func (*TraversalStep) CanExecuteSelectiveBidirectionalSearch added in v0.5.0

func (s *TraversalStep) CanExecuteSelectiveBidirectionalSearch(scope *Scope) (bool, error)

CanExecuteSelectiveBidirectionalSearch builds the SQL model fragment responsible for can execute selective bidirectional search.

func (*TraversalStep) EndNode

func (s *TraversalStep) EndNode() (*BoundIdentifier, error)

EndNode will find the terminal node of this pattern segment based on the segment's direction

func (*TraversalStep) FlipNodes

func (s *TraversalStep) FlipNodes()

FlipNodes builds the SQL model fragment responsible for flip nodes.

func (*TraversalStep) StartNode

func (s *TraversalStep) StartNode() (*BoundIdentifier, error)

StartNode will find the root node of this pattern segment based on the segment's direction

type TraversalStepContext added in v0.4.11

type TraversalStepContext struct {
	// PreviousStep supplies the previous step input to the TraversalStepContext contract.
	PreviousStep *TraversalStep
	// CurrentStep supplies the current step input to the TraversalStepContext contract.
	CurrentStep *TraversalStep
	// IsRootStep indicates whether is root step applies.
	IsRootStep bool
}

TraversalStepContext groups SQL model state that must remain consistent while translating traversal step context.

type UnwindClause added in v0.5.0

type UnwindClause struct {
	// Expression supplies the expression input to the UnwindClause contract.
	Expression pgsql.Expression
	// Binding supplies the binding input to the UnwindClause contract.
	Binding *BoundIdentifier
}

UnwindClause groups SQL model state that must remain consistent while translating unwind clause.

type Update

type Update struct {
	// Frame supplies the frame input to the Update contract.
	Frame *Frame
	// JoinConstraint supplies the join constraint input to the Update contract.
	JoinConstraint pgsql.Expression
	// Projection supplies the projection input to the Update contract.
	Projection []pgsql.SelectItem
	// TargetBinding supplies the target binding input to the Update contract.
	TargetBinding *BoundIdentifier
	// UpdateBinding supplies the update binding input to the Update contract.
	UpdateBinding *BoundIdentifier
	// contains filtered or unexported fields
}

Update groups SQL model state that must remain consistent while translating update.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL