Logical plan

The logical plan is the one intermediate form every query language in SynergyDB is turned into. There is no separate abstract syntax tree: the SQL parser, and the analyzers for the other query languages, build LogicalPlan values directly, and the engine interprets that tree (see lifecycle and parser). This page lists the node types, the expression types inside them, and which front end produces which nodes (source: src/plan/logical.rs, LogicalPlan).

LogicalPlan, Expr and the enums below derive serde::Serialize and serde::Deserialize (crate serde) and Clone (source: src/plan/logical.rs, LogicalPlan).

Who builds plans

Each query language has an analyzer that implements the Analyzer trait (parse, language). QueryEngine::parse_query dispatches on QueryLanguage (source: src/query/mod.rs, Analyzer, QueryLanguage; src/query/engine.rs, parse_query).

QueryLanguage Builder Notes
SQL SqlAnalyzer::parse_statement full node set, see below
Cypher cypher_analyzer.parse_query (src/query/cypher/planner.rs)  
MQL mql_analyzer.parse_command (src/query/mql/planner.rs) MongoDB query language
GraphQL, SynergyQL routed to the SQL analyzer by parse_query  
SPARQL not in QueryEngine: returns Error::Unsupported("SPARQL queries not supported in QueryEngine; use QueryCompiler") src/query/sparql/planner.rs builds plans only through QueryCompiler

(source: src/query/engine.rs, parse_query; src/query/mod.rs, QueryCompiler)

Most wires send SQL text, so the SQL parser builds almost every plan the engine runs. The non-SQL analyzers emit a subset of nodes:

Analyzer Nodes it emits
Cypher planner Scan, Join, Filter, Project, Sort, Limit, Distinct, Aggregate, GraphMatch, GraphTraverse, Insert, Update, Delete, CreateIndex, DropIndex, Empty, Values
MQL planner Scan, Filter, Project, Sort, Limit, Aggregate, Distinct, Join, Insert, Update, Delete, CreateTable, DropTable, CreateIndex, DropIndex, Empty
GraphQL module Scan, Project, Limit, Insert, Update, Delete
SPARQL planner Scan, Filter, Join, Project, Union, Values, Sort, Limit, Distinct, Aggregate

(source: src/query/cypher/planner.rs, src/query/mql/planner.rs, src/query/graphql/mod.rs, src/query/sparql/planner.rs)

Node types

LogicalPlan has 100 variants. They fall into the groups below (source: src/plan/logical.rs, LogicalPlan).

Relational query nodes

Variant Fields Meaning
Scan table, alias, filter, columns, only read a table; filter is a pushed-down predicate, columns an optional projection list set by the optimizer, only is FROM ONLY (no inheritance children)
Project input, exprs select list
Filter input, predicate WHERE or HAVING
Join left, right, condition, join_type JoinType is Inner, Left, Right, Full, Cross, Semi or Anti
LateralJoin left, right, condition: Option<Expr>, join_type LATERAL subquery or function
Aggregate input, group_by, aggregates, grouping_sets grouping_sets is Option<Vec<Vec<usize>>> of indexes into group_by
Sort input, order_by  
Limit input, limit: Option<usize>, offset: usize  
LimitWithTies input, limit, offset, order_by FETCH FIRST n ROWS WITH TIES and LIMIT ... WITH TIES
Distinct input, on DISTINCT and DISTINCT ON (...)
LockRows input, lock FOR UPDATE and relatives; LockStrength is Update, NoKeyUpdate, Share, KeyShare; LockWait is Wait, NoWait, SkipLocked
Alias input, alias derived table name
RecursiveCTE name, input, columns WITH RECURSIVE
Union, Intersect, Except left, right, all set operations
TableFunction function, args, alias, column_aliases, with_ordinality FROM generate_series(...) and similar
Values rows VALUES lists and FROM-less SELECT
Empty   statement that returns nothing
Multiple statements several statements in one string
WithDml ctes, body WITH whose CTEs are INSERT/UPDATE/DELETE

For grouping_sets, ROLLUP(a, b) becomes [[0, 1], [0], []] and CUBE(a, b) becomes [[0, 1], [0], [1], []] (source: src/plan/logical.rs, LogicalPlan::Aggregate).

Specialised query nodes

Variant Meaning Status
GraphMatch, GraphTraverse Cypher pattern match and traversal built by the Cypher planner
VectorScan k-nearest-neighbour scan Not wired: no analyzer emits it; execute_plan_inner has an arm for it
ShortestPath graph shortest path Not wired: no analyzer emits it; engine arm exists
FullTextSearch full-text scan Not wired: no analyzer emits it; engine arm exists
VectorJoin, Hybrid vector join, hybrid vector plus text Not wired: no analyzer emits them and src/query/engine.rs never references them

Vector search over SQL works through expressions (Expr::VectorDistance, the distance operators) and the HNSW staging in the Limit arm of the executor, not through VectorScan (source: src/query/engine.rs, execute_plan_inner, try_hnsw_candidate_keys). See executor.

DML nodes

Insert, InsertSelect, Update (table, assignments, filter, returning, from, target_alias, from_ctes) and Delete (table, filter, returning, using, target_alias, using_ctes). Joined DML sources that the planner cannot model are marked with the table name constant UNMODELED_DML_SOURCE ("<unmodeled join source>"); DML_LEFT_JOIN_SOURCE and DML_LEFT_JOIN_ON_PREFIX mark left-joined DML sources (source: src/plan/logical.rs, UNMODELED_DML_SOURCE, DML_LEFT_JOIN_SOURCE).

DDL, session and transaction nodes

Group Variants
Tables CreateTable, CreateTableAsSelect, DropTable, AlterTableAddColumn, AlterTableAddConstraint, AlterTableDropColumn, AlterTableRenameColumn, AlterTableAlterColumn, AlterColumnDefault, AlterColumnSetNullable, AlterTableRename, AlterTableNoop, AlterTableOwner, AlterTableDropIndex, AlterTableAddIndex
Indexes CreateIndex (with predicate, key_exprs, vector_metric, if_not_exists), DropIndex
Types and domains CreateType, AlterTypeAddValue, AlterTypeRename, AlterTypeRenameValue, AlterTypeNoop, CreateCompositeType, CreateRangeType, CreateDomain, AlterDomainAddConstraint, DropDomain, DropType
Security CreateRole, AlterRole, DropRole, Grant, Revoke, GrantRole, RevokeRole, CreatePolicy, DropPolicy, AlterTableRls, AlterColumnMask
Views CreateView, DropView, CreateMatView, DropMatView, RefreshMatView
Routines CreateFunction, DropFunction, CreateTrigger, DropTrigger, DoBlock
Sequences CreateSequence, AlterSequence, DropSequence, NextVal, CurrVal, SetVal
Cursors DeclareCursor { name, query }, FetchCursor { name, forward, count: Option<i64> }, MoveCursor, CloseCursor { name: Option<String> }, see cursors
Transactions BeginTransaction, Commit, Rollback, Savepoint, ReleaseSavepoint
Settings Set, Reset, Show
Diagnostics Explain { plan, analyze, format }, with ExplainFormat Text (default) or Json, see EXPLAIN

(source: src/plan/logical.rs, LogicalPlan)

Expressions

Expr is the expression tree inside Filter, Project, Join conditions and so on (source: src/plan/logical.rs, Expr).

Group Variants
References and constants Column(ColumnRef { table, column, alias }), Literal, Param(usize), Wildcard, QualifiedWildcard, Alias, FieldAccess, RangeLiteral
Operators BinaryOp, UnaryOp, Between, InList, Case, Cast
Calls Function, Aggregate (with filter and order_by), Window
Subqueries Subquery, ArraySubquery, Exists, InSubquery
Arrays ArraySubscript, ArraySlice, ArrayAny, ArrayAll
Search VectorDistance, VectorSimilarity, TextMatch, TextRank, EdgeProperty, PathLength
Dialect MySqlValues (MySQL VALUES(col) in ON DUPLICATE KEY UPDATE)

The doc comment on Expr::Param, and the comment in the parser where it is built, both say $n placeholders are text-substituted before parsing so Param never reaches the engine. The parser does build Expr::Param(n-1) from TokenType::Parameter(n), and lifecycle shows that only LIMIT/OFFSET parameters are still spliced into the text; both comments are out of date (source: src/plan/logical.rs, Expr::Param; src/query/sql/parser.rs, parse_primary_expression; src/query/engine.rs, substitute_limit_offset_params).

BinaryOp covers comparison (Eq to Ge, NullSafeEq), logic (And, Or), arithmetic (Add, Sub, Mul, Div, Mod, Power, IntegerDiv), pattern matching (Like, ILike, Regexp, RegexpCI), Concat, containment and overlap, JSONB operators, vector distance operators, bitwise operators, inet operators, TsMatch and TrgmSimilarity. UnaryOp is Not, Neg, IsNull, IsNotNull, SquareRoot, CubeRoot, BitwiseNot (source: src/plan/logical.rs, BinaryOp, UnaryOp).

AggregateFunc has Count, CountDistinct, Sum, Avg, Min, Max, First, Last, ArrayAgg, StringAgg(separator), JsonAgg, JsonObjectAgg, JsonbAgg, JsonbObjectAgg, Collect, BoolAnd, BoolOr, Mode, StddevPop, StddevSamp, VarPop, VarSamp, PercentileCont, PercentileDisc, QuantileExact and Grouping. WindowFunc has RowNumber, Rank, DenseRank, PercentRank, CumeDist, Ntile, Lag, Lead, FirstValue, LastValue, NthValue and Aggregate; window frames are Rows, Range or Groups (source: src/plan/logical.rs, AggregateFunc, WindowFunc, WindowFrame).

Shape of a SQL SELECT

parse_select stacks nodes bottom to top in this order (source: src/query/sql/parser.rs, parse_select):

flowchart BT F["FROM: Scan / Join / Alias / TableFunction / Values"] --> W["Filter (WHERE)"] W --> A["Aggregate (only with GROUP BY or HAVING)"] A --> H["Filter (HAVING)"] H --> P["Project"] P --> D["Distinct"] D --> S["Sort"] S --> L["Limit or LimitWithTies"] L --> K["LockRows (FOR UPDATE ...)"]

Source: src/query/sql/parser.rs, parse_select.

Details that matter when reading plans:

  • A FROM-less SELECT, and MySQL FROM dual, gets Values { rows: vec![vec![]] } (one empty row) as its source (source: src/query/sql/parser.rs, parse_from_clause).
  • An Aggregate node is added only when the query has GROUP BY or HAVING. SELECT count(*) FROM t has no Aggregate node; the aggregate stays inside Project and the executor evaluates it there (source: src/query/sql/parser.rs, parse_select).
  • In MySQL dialect a HAVING with no GROUP BY and no aggregate becomes a plain Filter (source: src/query/sql/parser.rs, parse_select).
  • GROUP BY 1 ordinals are resolved to select items. MySQL WITH ROLLUP fills grouping_sets (source: src/query/sql/parser.rs, parse_select).
  • DISTINCT ON builds Sort, then Distinct { on }, then Project (source: src/query/sql/parser.rs, parse_select). Tested by test_distinct_on_first_per_group.
  • Set operations are combined by combine_set_op; a trailing ORDER BY or LIMIT wraps the whole set operation (source: src/query/sql/parser.rs, parse_set_op_trailing_tail). Tested by test_set_op_trailing_order_by_limit_applies_to_whole.
  • Non-recursive CTEs are inlined by name where referenced; WITH RECURSIVE produces RecursiveCTE; CTEs that modify data produce WithDml (source: src/query/sql/parser.rs). Recursive CTEs are tested by test_recursive_cte_counter_union_all and test_recursive_cte_union_vs_union_all.

The constant EMPTY_SELECT_MARKER ("__synergydb_empty_select__") marks a select that is known to return no rows (source: src/plan/logical.rs, EMPTY_SELECT_MARKER).

Builder helpers and tests

LogicalPlan has builder helpers (scan, filter, project, sort, limit, join, aggregate) used by the non-SQL planners and by tests (source: src/plan/logical.rs). The module's own tests are test_build_simple_query, test_build_join_query and test_vector_scan; they check construction only, not execution.

What happens next

Before the optimizer runs, the engine rewrites the plan in place: resolve_natural_joins and promote_where_equijoins (see lifecycle). The optimizer then rewrites the tree, and the executor interprets it.