Statement lifecycle

This page follows one SQL statement from a wire handler to a QueryResult. The engine that does this is QueryEngine, one instance per session. The later pages in this section cover each stage in detail: parser, logical plan, optimizer, cost model and statistics, execution, cursors and EXPLAIN.

Summary of the path

wire handler
  -> QueryEngine::execute(sql, params)          audit text, per-statement caches, DecimalDivisionGuard
  -> execute_top                                aborted-transaction rule, DDL undo, READ ONLY check
  -> guarded_execute / execute_unguarded        dialect guards, PREPARE/EXECUTE, query log, profile
  -> execute_with_timeout                       slow-query log
  -> execute_with_timeout_inner
       LIMIT/OFFSET $N splice, parameter typing
       text fast paths (SET, SHOW, BEGIN, ANALYZE, catalog queries, ...)
       plan cache lookup, or parse_query -> LogicalPlan
       resolve_natural_joins, promote_where_equijoins
       Optimizer::optimize (unless SYNERGYDB_OPTIMIZER=0)
  -> execute_plan                               snapshot, authorize_plan, audit event
  -> execute_plan_inner                         RLS, views, subqueries, filter pushdown, dispatch
  -> execute_select / DML / DDL / TCL handlers
  -> QueryResult

(source: src/query/engine.rs, QueryEngine::execute, QueryEngine::execute_top, QueryEngine::execute_unguarded, QueryEngine::execute_with_timeout_inner, QueryEngine::execute_plan, QueryEngine::execute_plan_inner)

There is no separate abstract syntax tree. The parser emits a LogicalPlan directly, and the engine interprets that plan (source: src/query/sql/parser.rs, Parser::parse; src/plan/logical.rs, LogicalPlan).

Who calls the engine

Most wire protocols hand SQL text to QueryEngine::execute. That includes the MySQL, SQLite/Hrana, Snowflake, Oracle, Bolt, S3, DynamoDB, gRPC, Arrow Flight SQL, Gremlin and HTTP handlers. The HTTP routes and PostgreSQL COPY also call execute_plan directly with a plan they built themselves (source: src/protocol/http/routes.rs; src/protocol/postgres/copy.rs; src/query/engine.rs, QueryEngine::execute_plan). Before a statement arrives, the wire selects the dialect with one of the setters set_mysql_dialect, set_sqlite_dialect, set_mssql_dialect, set_clickhouse_dialect or set_decimal_division (source: src/query/engine.rs). The SQL Server wire splits T-SQL batches and rewrites T-SQL into the engine's dialect before it calls the engine (source: src/protocol/mssql/tsql.rs). See the wire pages for each protocol.

Stage 1: execute

execute(&mut self, query, params: &[Option<Vec<u8>>]) is the public entry. Only for an outer statement (exec_depth == 0) it:

  • records the statement text for the audit log, truncated to 8192 characters, with up to 64 parameters of up to 256 characters each;
  • clears the per-statement caches;
  • arms DecimalDivisionGuard when the session uses decimal division (Snowflake).

It then calls execute_top, releases statement-scoped locks when in autocommit, returns any deferred error, sets MySQL LAST_INSERT_ID, and removes the empty-select marker from the result with strip_empty_select_marker (source: src/query/engine.rs, QueryEngine::execute, strip_empty_select_marker).

Stage 2: execute_top, transaction state

execute_top applies the rules that depend on transaction state:

Condition Behaviour
MySQL session, or nested call Goes straight to execute_unguarded. In MySQL a deadlock error rolls the transaction back.
PostgreSQL transaction already failed COMMIT/END become ROLLBACK. ROLLBACK, ABORT and RELEASE run. Anything else fails with "current transaction is aborted…".
Transactional DDL (CREATE, ALTER, DROP, COMMENT, TRUNCATE) inside a transaction Recorded for undo, via is_transactional_ddl.
Write in a READ ONLY transaction Fails with SQLSTATE 25006 from read_only_violation.
Error inside a transaction Sets txn_failed and calls abort_failed_transaction_now, unless a savepoint exists or the dialect is SQL Server.

(source: src/query/engine.rs, QueryEngine::execute_top, is_transactional_ddl, read_only_violation, abort_failed_transaction_now)

The transaction model is documented in Volume I, transactions.

Stage 3: execute_unguarded

guarded_execute sets the statement timestamp (STMT_NOW) once per outer statement and increments exec_depth (source: src/query/engine.rs, QueryEngine::guarded_execute). execute_unguarded then:

  1. Arms MySqlDialectGuard and MssqlCollationGuard for the session's dialect. These set thread-local flags that the lexer and comparison code read (source: src/query/sql/lexer.rs, MySqlDialectGuard).
  2. Logs the first 400 characters of the statement when SYNERGYDB_LOG_QUERIES=1. The code comment notes that this logs SQL verbatim, including literal values.
  3. Handles SQL-level PREPARE, EXECUTE and DEALLOCATE before parsing, through the session's sql_prepared map. EXECUTE substitutes the argument text into the stored statement, tries prepared_catalog_answer, and then calls execute on the result.
  4. Evicts statement-scoped pg_relations cache entries, starts the SYNERGYDB_STMT_PROFILE profiler if set, and records query_start.
  5. Calls execute_with_timeout, then record_schema_object_ddl, then clear_params.

(source: src/query/engine.rs, QueryEngine::execute_unguarded)

execute_with_timeout wraps the call with the slow-query log. A statement that takes longer than SYNERGYDB_SLOW_QUERY_US microseconds is written to SYNERGYDB_SLOW_QUERY_LOG (default /tmp/synergydb-slow.log) (source: src/query/engine.rs, QueryEngine::execute_with_timeout). See the configuration reference.

Not wired: despite its name, execute_with_timeout does not enforce a statement timeout. QueryEngine::check_timeout exists and compares elapsed time with a QueryTimeout (default 30,000 ms), but nothing calls it (source: src/query/engine.rs, QueryEngine::check_timeout; src/query/types.rs, QueryTimeout).

Stage 4: parameters

When the wire supplied bind parameters, execute_with_timeout_inner first calls substitute_limit_offset_params. That splices LIMIT $n and OFFSET $n values into the text as integers, because LogicalPlan::Limit stores a usize fixed at parse time. It then runs detect_parameter_types and set_params unless types were preset by the wire. Every other $n stays a placeholder: the lexer produces TokenType::Parameter(n) and the parser produces Expr::Param(n-1), which the evaluator reads from the bound parameter list (source: src/query/engine.rs, substitute_limit_offset_params, QueryEngine::execute_with_timeout_inner; src/query/sql/parser.rs, Parser::parse_primary_expression).

Stage 5: statements that bypass the planner

After stripping leading comments and a trailing ;, execute_with_timeout_inner tests the upper-cased text against a list of fast paths. A match returns without parsing to a plan or running the optimizer:

Order Statement Handling
1 TRUNCATE a, b, ... Split into single-table TRUNCATEs run as a set
2 ANALYZE [VERBOSE] [t, ...] handle_analyze, see statistics
3 VACUUM FULL Storage compact_full
4 REINDEX TABLE t rebuild_row_key_indexes, only outside a transaction
5 Any other VACUUM / REINDEX Returns Empty
6 DISCARD ALL / DISCARD TEMP Drops temporary tables and resets the role
7 BEGIN / START TRANSACTION MVCC begin, default isolation ReadCommitted. A second BEGIN is a no-op.
8 COMMIT / END [WORK \| TRANSACTION] Commit
9 ROLLBACK Rollback
10 SET, RESET, SHOW Session variable handlers
11 SELECT set_config(...) try_set_config_statement
12 CREATE / DROP / ALTER SCHEMA Schema handler
13 SELECT lists made only of lastval(), nextval, currval, setval calls Sequence handler
14 pg_advisory* calls Advisory lock handler
15 DEALLOCATE, COMMENT ON Return Empty
16 CREATE DATABASE, ALTER DATABASE ... OWNER TO, DROP DATABASE Database handlers
17 CREATE/DROP EXTENSION, AGGREGATE, LANGUAGE, TEXT SEARCH and similar Return a success tag only
18 Catalog and system queries (handle_system_query), unless the text is already in the plan cache Answered from the virtual catalog

(source: src/query/engine.rs, QueryEngine::execute_with_timeout_inner, handle_analyze, handle_system_query)

Some statements reach the parser but are still not planned: GRANT that fails to parse is logged as a warning and returns Empty without granting anything, and DISCARD, LOCK, FLUSH, COMMENT and SET CONSTRAINTS parse to Empty (source: src/query/sql/parser.rs, Parser::parse_statement). Tested by grant_and_revoke_on_tables_parse and unparseable_revoke_is_an_error in src/query/sql/parser.rs.

The virtual catalog that answers the last row is described with the catalog in Volume I.

Stage 6: plan caches

QueryEngine keeps two maps keyed by the trimmed statement text after the LIMIT/OFFSET splice:

Cache Contents Limit
plan_cache Parsed LogicalPlan 512 entries (PLAN_CACHE_MAX_ENTRIES). Statements longer than 16 KiB (PLAN_CACHE_MAX_QUERY_BYTES) are not cached.
opt_plan_cache Optimized LogicalPlan Filled only when the text is in plan_cache and plan_opt_cacheable holds

When plan_cache is full, both maps are cleared; there is no LRU order. plan_opt_cacheable accepts only plans built from Scan, Project, Filter, Sort, Limit, LimitWithTies, Distinct, Aggregate, LockRows and Alias, so plans with joins are optimized again on every run. set_database clears both maps. DDL does not clear them; the code comment says plans resolve table and column names against the catalog at execution time (source: src/query/engine.rs, QueryEngine::execute_with_timeout_inner, plan_opt_cacheable, QueryEngine::set_database). Tested by statement_caches_follow_views_and_sequences_from_other_sessions and catalog_relation_cache_follows_analyze_and_sequences in src/query/engine.rs.

These caches are per session. The separate StatementCache in src/query/stmt_cache.rs is not used; see the parser page.

Stage 7: parse and language detection

On a cache miss parse_query calls detect_language:

Text starts with or contains Language Analyzer
MATCH, OPTIONAL MATCH, MERGE, CREATE (, or CREATE followed by a (x:Label) pattern (excluding SQL object keywords and :: casts) Cypher Cypher analyzer
{ or db. MQL MQL analyzer
anything else SQL SqlAnalyzer

GraphQL and SynergyQL are routed to the SQL analyzer, and SPARQL returns an "unsupported" error from QueryEngine (source: src/query/engine.rs, QueryEngine::parse_query, detect_language). A parse error tries catalog_fallback and otherwise returns the parse error to the client.

QueryCompiler::compile_auto in src/query/mod.rs has its own detector. It sends text starting with SELECT, INSERT, UPDATE, DELETE, CREATE or DROP to SQL first, so its later SELECT ... WHERE { SPARQL branch is never reached (source: src/query/mod.rs, QueryCompiler::compile_auto). Not verified: no test exercises that branch.

Stage 8: rewrites and optimizer

Before optimization the engine runs two rewrites: resolve_natural_joins turns the parser's __natural_join__ marker into USING equalities, and promote_where_equijoins moves a.x = b.y conjuncts from WHERE into the condition of an inner or cross join so the hash join can use them (source: src/query/engine.rs, resolve_natural_joins, promote_where_equijoins). Tested by test_comma_join_becomes_inner_join and star_over_using_and_natural_joins_shows_the_key_once.

If optimizer_enabled() is true, the engine calls Optimizer::optimize. An optimizer error is swallowed and the unoptimized plan is used. See optimizer.

What SYNERGYDB_OPTIMIZER=0 changes

optimizer_enabled() reads SYNERGYDB_OPTIMIZER once per process through a OnceLock. The values 0, false and off disable it; anything else, or unset, enables it (source: src/query/engine.rs, optimizer_enabled). With the optimizer disabled:

  • Optimizer::optimize is not called, so none of the rewrite rules and no join reordering run;
  • opt_plan_cache is neither read nor written;
  • everything else is unchanged: the text fast paths, resolve_natural_joins, promote_where_equijoins, the engine-side rewrites in execute_plan_inner and execute_select_plan, the access-path cascade and the hash join all still run.

(source: src/query/engine.rs, QueryEngine::execute_with_timeout_inner)

The comment above the call site still describes the optimizer as "OFF BY DEFAULT and EXPERIMENTAL"; the function it calls defaults to on. Not verified: no test runs with SYNERGYDB_OPTIMIZER=0.

Stage 9: execute_plan and execute_plan_inner

execute_plan takes a statement snapshot for read-only plan types (unless one exists already or reads_one_key says the plan is a single-key read), runs authorize_plan and ownership_effect, calls execute_plan_inner, and writes an audit event (source: src/query/engine.rs, QueryEngine::execute_plan, reads_one_key). Authorization is documented in the security guide.

execute_plan_inner handles plan shapes that need setup and then dispatches:

  1. LockRows goes to apply_select_row_locks; WithDml runs each data-modifying CTE and binds its result; MySQL SERIALIZABLE adds an implicit FOR SHARE; Multiple runs its statements in order; temporary tables have their own path.
  2. Graph leaf plans are routed to the graph engine, and a Cypher join of inserts is handled.
  3. apply_rls adds row-level security filters (the Select policy for reads; Insert, Update, Delete for DML).
  4. expand_views_in_plan, resolve_plan_subqueries and pushdown_filters_into_scans rewrite the plan.
  5. Dispatch: Project, Scan, Filter, Limit, LimitWithTies, Join, LateralJoin, Aggregate and Sort go to execute_select; Union, Intersect, Except and Distinct have their own handlers; DDL, transaction control and cursor plans are executed in place; Explain goes to execute_explain.

(source: src/query/engine.rs, QueryEngine::execute_plan_inner)

Execution is described on the executor page.

Stage 10: result post-processing

After execution execute_with_timeout_inner pads bpchar values for PostgreSQL, applies MySQL declared column types, and normalizes jsonb text (type OID 3802). A plan execution error also tries catalog_fallback (source: src/query/engine.rs, QueryEngine::execute_with_timeout_inner). The result type is QueryResult: Select { columns, rows }, Insert/Update/Delete { count }, DDL and transaction tags, or Empty. ColumnInfo carries name, type_oid, type_size and, for MySQL only, declared_type (source: src/query/types.rs, QueryResult, ColumnInfo).

End-to-end tests

tests/persistence_query_parity_test.rs drives QueryEngine::execute end to end. Its query_parity module covers WHERE filtering, ORDER BY, LIMIT, COUNT and SUM, GROUP BY, UPDATE and DELETE with WHERE, SELECT * and DROP TABLE; other modules cover persistence, type fidelity, crash recovery, multi-session use and type OID mapping (source: tests/persistence_query_parity_test.rs).