Skip to main content

reddb_rql/
core.rs

1use std::fmt;
2
3use super::builders::{GraphQueryBuilder, PathQueryBuilder, TableQueryBuilder};
4use reddb_types::catalog::CollectionModel;
5pub use reddb_types::distance::DistanceMetric;
6pub use reddb_types::queue_mode::QueueMode;
7use reddb_types::types::{SqlTypeName, Value};
8pub use reddb_types::vector_metadata::MetadataFilter;
9
10/// Root query expression
11#[derive(Debug, Clone)]
12#[allow(clippy::large_enum_variant)]
13pub enum QueryExpr {
14    /// Pure table query: SELECT ... FROM ...
15    Table(TableQuery),
16    /// Pure graph query: MATCH ... RETURN ...
17    Graph(GraphQuery),
18    /// Join between table and graph
19    Join(JoinQuery),
20    /// Path query: PATH FROM ... TO ...
21    Path(PathQuery),
22    /// Vector similarity search
23    Vector(VectorQuery),
24    /// Hybrid query combining structured and vector search
25    Hybrid(HybridQuery),
26    /// INSERT INTO table (cols) VALUES (vals)
27    Insert(InsertQuery),
28    /// UPDATE table SET col=val WHERE filter
29    Update(UpdateQuery),
30    /// DELETE FROM table WHERE filter
31    Delete(DeleteQuery),
32    /// CREATE TABLE name (columns)
33    CreateTable(CreateTableQuery),
34    /// CREATE COLLECTION name KIND kind
35    CreateCollection(CreateCollectionQuery),
36    /// CREATE VECTOR name DIM n [METRIC metric]
37    CreateVector(CreateVectorQuery),
38    /// DROP TABLE name
39    DropTable(DropTableQuery),
40    /// DROP GRAPH name
41    DropGraph(DropGraphQuery),
42    /// DROP VECTOR name
43    DropVector(DropVectorQuery),
44    /// DROP DOCUMENT name
45    DropDocument(DropDocumentQuery),
46    /// DROP KV name
47    DropKv(DropKvQuery),
48    /// DROP COLLECTION name
49    DropCollection(DropCollectionQuery),
50    /// TRUNCATE [model] name
51    Truncate(TruncateQuery),
52    /// ALTER TABLE name ADD/DROP/RENAME COLUMN
53    AlterTable(AlterTableQuery),
54    /// CREATE BRANCH/TAG ref DDL
55    CreateVcsRef(CreateVcsRefQuery),
56    /// DROP BRANCH/TAG ref DDL
57    DropVcsRef(DropVcsRefQuery),
58    /// GRAPH subcommand (NEIGHBORHOOD, SHORTEST_PATH, etc.)
59    GraphCommand(GraphCommand),
60    /// SEARCH subcommand (SIMILAR, TEXT, HYBRID)
61    SearchCommand(SearchCommand),
62    /// ASK 'question' — RAG query with LLM synthesis
63    Ask(AskQuery),
64    /// CREATE INDEX name ON table (columns) USING type
65    CreateIndex(CreateIndexQuery),
66    /// DROP INDEX name ON table
67    DropIndex(DropIndexQuery),
68    /// Probabilistic data structure commands (HLL, SKETCH, FILTER)
69    ProbabilisticCommand(ProbabilisticCommand),
70    /// CREATE TIMESERIES name [RETENTION duration] [CHUNK_SIZE n]
71    CreateTimeSeries(CreateTimeSeriesQuery),
72    /// CREATE METRIC path TYPE kind ROLE role
73    CreateMetric(CreateMetricQuery),
74    /// ALTER METRIC path SET <ROLE|KIND|TYPE|PATH> <value>
75    AlterMetric(AlterMetricQuery),
76    /// CREATE SLO path ON metric_path TARGET t WINDOW d UNIT
77    CreateSlo(CreateSloQuery),
78    /// DROP TIMESERIES name
79    DropTimeSeries(DropTimeSeriesQuery),
80    /// CREATE QUEUE name [WORK|STANDARD|FIFO|FANOUT] [MAX_SIZE n] [PRIORITY] [WITH TTL duration]
81    CreateQueue(CreateQueueQuery),
82    /// ALTER QUEUE name SET MODE [FANOUT|WORK|STANDARD|FIFO]
83    AlterQueue(AlterQueueQuery),
84    /// DROP QUEUE name
85    DropQueue(DropQueueQuery),
86    /// Read-only queue projection: SELECT ... FROM QUEUE name
87    QueueSelect(QueueSelectQuery),
88    /// QUEUE subcommand (PUSH, POP, PEEK, LEN, PURGE, GROUP, READ, ACK, NACK)
89    QueueCommand(QueueCommand),
90    /// KV subcommand (PUT, GET, DELETE)
91    KvCommand(KvCommand),
92    /// CONFIG keyed command (PUT, GET, ROTATE, DELETE, HISTORY)
93    ConfigCommand(ConfigCommand),
94    /// CREATE TREE name IN collection ROOT ... MAX_CHILDREN n
95    CreateTree(CreateTreeQuery),
96    /// DROP TREE name IN collection
97    DropTree(DropTreeQuery),
98    /// TREE subcommand (INSERT, MOVE, DELETE, VALIDATE, REBALANCE)
99    TreeCommand(TreeCommand),
100    /// SET CONFIG key = value
101    SetConfig { key: String, value: Value },
102    /// SHOW CONFIG [prefix] [AS JSON|FORMAT JSON]
103    ShowConfig {
104        prefix: Option<String>,
105        as_json: bool,
106    },
107    /// SET SECRET key = value
108    SetSecret { key: String, value: Value },
109    /// DELETE SECRET key
110    DeleteSecret { key: String },
111    /// SHOW SECRET[S] [prefix]
112    ShowSecrets { prefix: Option<String> },
113    /// SET KV key = value
114    ///
115    /// Stores a plain (non-encrypted) user key-value entry in the KV
116    /// store — a sibling to `SET SECRET`, but backed by an independent
117    /// flat-map with no vault encryption. Gated by `kv:write` (#1602).
118    SetKv { key: String, value: Value },
119    /// DELETE KV key — remove a plain KV entry. Gated by `kv:write` (#1602).
120    DeleteKv { key: String },
121    /// `SET TENANT 'id'` / `SET TENANT = 'id'` / `RESET TENANT`
122    ///
123    /// Session-scoped multi-tenancy handle. Populates a per-connection
124    /// thread-local that `CURRENT_TENANT()` reads and that RLS
125    /// policies combine with via `USING (tenant_id = CURRENT_TENANT())`.
126    /// `None` clears the current tenant (RESET TENANT or SET TENANT
127    /// NULL). Unlike `SetConfig` this is *not* persisted to red_config —
128    /// it lives for the connection's lifetime only.
129    SetTenant(Option<String>),
130    /// `SHOW TENANT` — returns the thread-local tenant id (or NULL).
131    ShowTenant,
132    /// EXPLAIN ALTER FOR CREATE TABLE name (...) [FORMAT JSON]
133    ///
134    /// Pure read command that diffs the embedded `CREATE TABLE`
135    /// statement against the live `CollectionContract` of the
136    /// table with the same name and returns the `ALTER TABLE`
137    /// operations that would close the gap. Never executes
138    /// anything — output is text (default) or JSON depending on
139    /// the optional `FORMAT JSON` suffix. Powers the Purple
140    /// framework's migration generator and any other client that
141    /// wants reddb to own the schema-diff rules.
142    ExplainAlter(ExplainAlterQuery),
143    /// CREATE MIGRATION name [DEPENDS ON dep1, dep2] [BATCH n ROWS] [NO ROLLBACK] body
144    CreateMigration(CreateMigrationQuery),
145    /// APPLY MIGRATION name | APPLY MIGRATION *  [FOR TENANT id]
146    ApplyMigration(ApplyMigrationQuery),
147    /// ROLLBACK MIGRATION name
148    RollbackMigration(RollbackMigrationQuery),
149    /// EXPLAIN MIGRATION name
150    ExplainMigration(ExplainMigrationQuery),
151    /// `EVENTS BACKFILL collection [WHERE pred] TO queue [LIMIT n]`.
152    EventsBackfill(EventsBackfillQuery),
153    /// `EVENTS BACKFILL STATUS collection` placeholder for the status slice.
154    EventsBackfillStatus { collection: String },
155    /// Transaction control: BEGIN, COMMIT, ROLLBACK, SAVEPOINT, RELEASE, ROLLBACK TO.
156    ///
157    /// Phase 1.1 (PG parity): parser + dispatch are wired so clients (psql, JDBC, etc.)
158    /// can issue these statements without errors. Real isolation/atomicity semantics
159    /// arrive with Phase 2.3 MVCC. Until then statements behave as autocommit (each
160    /// DML is its own transaction); BEGIN/COMMIT/ROLLBACK return success but do NOT
161    /// provide rollback-on-failure guarantees across multiple statements.
162    TransactionControl(TxnControl),
163    /// Maintenance commands: VACUUM [FULL] [table], ANALYZE [table].
164    ///
165    /// Phase 1.2 (PG parity): `VACUUM` triggers segment/page flush + planner stats
166    /// refresh. `ANALYZE` refreshes planner statistics (histograms, null counts,
167    /// distinct estimates). Both accept an optional table target; omitting the
168    /// target iterates every collection.
169    MaintenanceCommand(MaintenanceCommand),
170    /// VCS working-set commands: CHECKPOINT, CHECKOUT, RESET, MERGE,
171    /// CHERRY PICK, REVERT, RESOLVE CONFLICT.
172    VcsCommand(VcsCommand),
173    /// `CREATE SCHEMA [IF NOT EXISTS] name`
174    ///
175    /// Phase 1.3 (PG parity): schemas are logical namespaces stored in
176    /// `red_config` under the key `schema.{name}`. Tables created inside a
177    /// schema use `schema.table` qualified names (collection name = "schema.table").
178    CreateSchema(CreateSchemaQuery),
179    /// `DROP SCHEMA [IF EXISTS] name [CASCADE]`
180    DropSchema(DropSchemaQuery),
181    /// `CREATE SEQUENCE [IF NOT EXISTS] name [START [WITH] n] [INCREMENT [BY] n]`
182    ///
183    /// Phase 1.3 (PG parity): sequences are 64-bit monotonic counters persisted
184    /// in `red_config` under the key `sequence.{name}`. Values are produced by
185    /// the scalar functions `nextval('name')` and `currval('name')`.
186    CreateSequence(CreateSequenceQuery),
187    /// `DROP SEQUENCE [IF EXISTS] name`
188    DropSequence(DropSequenceQuery),
189    /// `COPY table FROM 'path' [WITH ...]` — CSV import (Phase 1.5 PG parity).
190    ///
191    /// Supported options: `DELIMITER c`, `HEADER [true|false]`. Rows stream
192    /// into the named collection via the `CsvImporter`.
193    CopyFrom(CopyFromQuery),
194    /// `CREATE [OR REPLACE] [MATERIALIZED] VIEW [IF NOT EXISTS] name AS SELECT ...`
195    ///
196    /// Phase 2.1 (PG parity): views are stored as `view.{name}` entries in
197    /// `red_config`. Materialized views additionally allocate a slot in the
198    /// shared `MaterializedViewCache`; `REFRESH MATERIALIZED VIEW` re-runs
199    /// the underlying query and repopulates the cache.
200    CreateView(CreateViewQuery),
201    /// `DROP [MATERIALIZED] VIEW [IF EXISTS] name`
202    DropView(DropViewQuery),
203    /// `REFRESH MATERIALIZED VIEW name`
204    ///
205    /// Re-executes the view's query and writes the result into the cache.
206    RefreshMaterializedView(RefreshMaterializedViewQuery),
207    /// `CREATE POLICY name ON table [FOR action] [TO role] USING (filter)`
208    ///
209    /// Phase 2.5 (PG parity): row-level security policy definition.
210    /// Evaluated at read time — when the table has RLS enabled, all
211    /// matching policies for the current role are combined with OR and
212    /// AND-ed into the query's WHERE clause.
213    CreatePolicy(CreatePolicyQuery),
214    /// `DROP POLICY [IF EXISTS] name ON table`
215    DropPolicy(DropPolicyQuery),
216    /// `CREATE SERVER name FOREIGN DATA WRAPPER kind OPTIONS (...)`
217    /// (Phase 3.2 PG parity). Registers a named foreign-data-wrapper
218    /// instance in the runtime's `ForeignTableRegistry`.
219    CreateServer(CreateServerQuery),
220    /// `DROP SERVER [IF EXISTS] name [CASCADE]`
221    DropServer(DropServerQuery),
222    /// `CREATE FOREIGN TABLE name (cols) SERVER srv OPTIONS (...)`
223    /// (Phase 3.2 PG parity). Makes `name` resolvable as a foreign table
224    /// via the parent server's `ForeignDataWrapper`.
225    CreateForeignTable(CreateForeignTableQuery),
226    /// `DROP FOREIGN TABLE [IF EXISTS] name`
227    DropForeignTable(DropForeignTableQuery),
228    /// `GRANT { actions | ALL [PRIVILEGES] }
229    ///   ON { TABLE | SCHEMA | DATABASE | FUNCTION } object_list
230    ///   TO grant_principal_list
231    ///   [WITH GRANT OPTION]`
232    ///
233    /// Granular RBAC primitive layered on top of the legacy 3-role model.
234    /// See `crate::auth::privileges` for the resolution algorithm.
235    Grant(GrantStmt),
236    /// `REVOKE [GRANT OPTION FOR] { actions | ALL } ON … FROM …`
237    Revoke(RevokeStmt),
238    /// `ALTER USER name [VALID UNTIL 'ts'] [CONNECTION LIMIT n]
239    ///   [ENABLE | DISABLE] [SET search_path = ...]`
240    AlterUser(AlterUserStmt),
241    /// `CREATE USER [tenant.]name [WITH] PASSWORD 'plaintext' [ROLE read|write|admin]`
242    CreateUser(CreateUserStmt),
243    // ----- IAM policy DDL (Agent #28 / IAM kernel integration) -----
244    /// `CREATE POLICY '<id>' AS '<json>'` — installs an IAM policy
245    /// document in the AuthStore. Distinct from the RLS-flavoured
246    /// `CreatePolicy(CreatePolicyQuery)` above (which uses
247    /// `CREATE POLICY name ON table ...`); the parser disambiguates
248    /// at parse time by inspecting the token after the policy name.
249    CreateIamPolicy { id: String, json: String },
250    /// `DROP POLICY '<id>'` — removes an IAM policy and its
251    /// attachments.
252    DropIamPolicy { id: String },
253    /// `ATTACH POLICY '<id>' TO USER <name>` /
254    /// `ATTACH POLICY '<id>' TO GROUP <name>`.
255    AttachPolicy {
256        policy_id: String,
257        principal: PolicyPrincipalRef,
258    },
259    /// `DETACH POLICY '<id>' FROM USER <name>` /
260    /// `DETACH POLICY '<id>' FROM GROUP <name>`.
261    DetachPolicy {
262        policy_id: String,
263        principal: PolicyPrincipalRef,
264    },
265    /// `SHOW POLICIES [FOR USER <name> | FOR GROUP <name>]`.
266    ShowPolicies { filter: Option<PolicyPrincipalRef> },
267    /// `SHOW EFFECTIVE PERMISSIONS FOR <name> [ON <kind>:<name>]`.
268    ShowEffectivePermissions {
269        user: PolicyUserRef,
270        resource: Option<PolicyResourceRef>,
271    },
272    /// Exact rank of one row in a declared leaderboard ranking.
273    RankOf(RankOfQuery),
274    /// Approximate tail rank of one row in a declared leaderboard ranking.
275    ApproxRankOf(RankOfQuery),
276    /// Exact rank-ordered range in a declared leaderboard ranking.
277    RankRange(RankRangeQuery),
278    /// `SIMULATE <name> ACTION <verb> ON <kind>:<name>`.
279    SimulatePolicy {
280        user: PolicyUserRef,
281        action: String,
282        resource: PolicyResourceRef,
283    },
284    /// `LINT POLICY '<id>'` — fetch a stored policy from the
285    /// AuthStore and run the [`PolicyLinter`](crate::auth::policy_linter)
286    /// against its serialized JSON.
287    ///
288    /// `LINT POLICY JSON '<json>'` — lint the supplied JSON document
289    /// directly without consulting the AuthStore. Issue #710.
290    LintPolicy { source: LintPolicySource },
291    /// `MIGRATE POLICY MODE TO '<target>' [DRY RUN]` — switch the
292    /// install from the legacy_rbac fallback to strict policy_only
293    /// after running the pre-flight delta simulator. With `DRY RUN`,
294    /// only the delta is returned. Without it, the migration refuses
295    /// if the delta is non-empty and otherwise mutates the
296    /// enforcement mode. Issue #714.
297    MigratePolicyMode { target: String, dry_run: bool },
298}
299
300/// Source of the policy document being linted.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum LintPolicySource {
303    /// Fetch the document from the AuthStore by id.
304    Id(String),
305    /// Use the supplied JSON literal verbatim.
306    Json(String),
307}
308
309/// Tenant-qualified user reference for IAM policy SQL DDL.
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct PolicyUserRef {
312    pub tenant: Option<String>,
313    pub username: String,
314}
315
316/// Resource reference (`<kind>:<name>`) used in `SIMULATE` /
317/// `SHOW EFFECTIVE PERMISSIONS`.
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct PolicyResourceRef {
320    pub kind: String,
321    pub name: String,
322}
323
324/// Principal target for ATTACH / DETACH / SHOW POLICIES filter.
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub enum PolicyPrincipalRef {
327    User(PolicyUserRef),
328    Group(String),
329}
330
331/// `RANK OF <entity_id> IN <ranking>` canonical leaderboard read.
332///
333/// Redis-flavor `ZRANK <ranking> <entity_id>` desugars to this exact same
334/// shape, so it carries no execution semantics that the canonical rank read
335/// lacks.
336#[derive(Debug, Clone, PartialEq, Eq)]
337pub struct RankOfQuery {
338    pub ranking: String,
339    pub entity_id: u64,
340}
341
342/// `RANK RANGE <lo> TO <hi> IN <ranking>` canonical leaderboard read.
343///
344/// Redis-flavor `ZRANGE <ranking> <start> <stop> [WITHSCORES]` desugars by
345/// translating Redis' zero-based inclusive offsets to the canonical one-based
346/// rank bounds.
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct RankRangeQuery {
349    pub ranking: String,
350    pub lo: u64,
351    pub hi: u64,
352}
353
354// ---------------------------------------------------------------------------
355// GRANT / REVOKE / ALTER USER AST
356// ---------------------------------------------------------------------------
357
358/// Object class targeted by a GRANT/REVOKE.
359#[derive(Debug, Clone, PartialEq, Eq)]
360pub enum GrantObjectKind {
361    Table,
362    Schema,
363    Database,
364    Function,
365}
366
367/// One target object in a `GRANT ... ON ... <object_list>` clause.
368///
369/// `name` follows the parser's standard `[schema.]object` shape; the
370/// optional `schema` is only populated for `Table` / `Function` and
371/// stays `None` when the user wrote a bare identifier.
372#[derive(Debug, Clone)]
373pub struct GrantObject {
374    pub schema: Option<String>,
375    pub name: String,
376}
377
378/// Principal target of a GRANT (i.e. the recipient).
379#[derive(Debug, Clone)]
380pub enum GrantPrincipalRef {
381    /// `TO username` — username may include an `@tenant` suffix.
382    User {
383        tenant: Option<String>,
384        name: String,
385    },
386    /// `TO PUBLIC`.
387    Public,
388    /// `TO GROUP groupname` (parsed today, enforcement deferred).
389    Group(String),
390}
391
392/// `GRANT` statement AST.
393#[derive(Debug, Clone)]
394pub struct GrantStmt {
395    /// Privilege keywords as the user typed them, normalised to upper
396    /// case. Matches the `Action` set in `crate::auth::privileges`. An
397    /// empty list together with `all = true` represents `ALL [PRIVILEGES]`.
398    pub actions: Vec<String>,
399    /// Optional column list — populates the AST for column-level
400    /// grants but enforcement is deferred (stretch goal).
401    pub columns: Option<Vec<String>>,
402    pub object_kind: GrantObjectKind,
403    pub objects: Vec<GrantObject>,
404    pub principals: Vec<GrantPrincipalRef>,
405    pub with_grant_option: bool,
406    /// `true` when the privilege list was `ALL [PRIVILEGES]`.
407    pub all: bool,
408}
409
410/// `REVOKE` statement AST.
411#[derive(Debug, Clone)]
412pub struct RevokeStmt {
413    pub actions: Vec<String>,
414    pub columns: Option<Vec<String>>,
415    pub object_kind: GrantObjectKind,
416    pub objects: Vec<GrantObject>,
417    pub principals: Vec<GrantPrincipalRef>,
418    /// `REVOKE GRANT OPTION FOR ...` — strips just the grant option,
419    /// keeping the underlying privilege.
420    pub grant_option_for: bool,
421    pub all: bool,
422}
423
424/// One attribute setting under `ALTER USER`.
425#[derive(Debug, Clone)]
426pub enum AlterUserAttribute {
427    ValidUntil(String),
428    ConnectionLimit(i64),
429    Enable,
430    Disable,
431    SetSearchPath(String),
432    AddGroup(String),
433    DropGroup(String),
434    /// Reset password (carry the new plaintext until the runtime
435    /// hands it to AuthStore::change_password). Out of scope for the
436    /// initial milestone — present so the parser can accept the
437    /// keyword without a follow-up grammar change.
438    Password(String),
439}
440
441/// `ALTER USER` statement AST.
442#[derive(Debug, Clone)]
443pub struct AlterUserStmt {
444    pub tenant: Option<String>,
445    pub username: String,
446    pub attributes: Vec<AlterUserAttribute>,
447}
448
449/// `CREATE USER` statement AST.
450#[derive(Debug, Clone)]
451pub struct CreateUserStmt {
452    pub tenant: Option<String>,
453    pub username: String,
454    pub password: String,
455    pub role: String,
456}
457
458#[derive(Debug, Clone)]
459pub struct CreateServerQuery {
460    pub name: String,
461    /// Wrapper kind declared in `FOREIGN DATA WRAPPER <kind>`.
462    pub wrapper: String,
463    /// Generic `(key 'value', ...)` option bag.
464    pub options: Vec<(String, String)>,
465    pub if_not_exists: bool,
466}
467
468#[derive(Debug, Clone)]
469pub struct DropServerQuery {
470    pub name: String,
471    pub if_exists: bool,
472    pub cascade: bool,
473}
474
475#[derive(Debug, Clone)]
476pub struct CreateForeignTableQuery {
477    pub name: String,
478    pub server: String,
479    pub columns: Vec<ForeignColumnDef>,
480    pub options: Vec<(String, String)>,
481    pub if_not_exists: bool,
482}
483
484#[derive(Debug, Clone)]
485pub struct ForeignColumnDef {
486    pub name: String,
487    pub data_type: String,
488    pub not_null: bool,
489}
490
491#[derive(Debug, Clone)]
492pub struct DropForeignTableQuery {
493    pub name: String,
494    pub if_exists: bool,
495}
496
497/// Row-level security policy definition.
498#[derive(Debug, Clone)]
499pub struct CreatePolicyQuery {
500    pub name: String,
501    pub table: String,
502    /// Which action this policy gates. `None` = `ALL` (applies to all four).
503    pub action: Option<PolicyAction>,
504    /// Role the policy applies to. `None` = all roles.
505    pub role: Option<String>,
506    /// Boolean predicate the row must satisfy.
507    pub using: Box<Filter>,
508    /// Entity kind this policy targets (Phase 2.5.5 RLS universal).
509    /// `CREATE POLICY p ON t ...` defaults to `Table`; writing
510    /// `ON NODES OF g` / `ON VECTORS OF v` / `ON MESSAGES OF q` /
511    /// `ON POINTS OF ts` / `ON EDGES OF g` targets the matching
512    /// non-tabular kind. The evaluator filters polices by kind so
513    /// a graph policy only gates graph reads, vector policy only
514    /// gates vector reads, etc.
515    pub target_kind: PolicyTargetKind,
516}
517
518/// Which flavour of entity a policy governs (Phase 2.5.5).
519#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
520pub enum PolicyTargetKind {
521    Table,
522    Nodes,
523    Edges,
524    Vectors,
525    Messages,
526    Points,
527    Documents,
528}
529
530impl PolicyTargetKind {
531    /// Lowercase identifier for UX — used in messages and the
532    /// `red_config.rls.policies.*` persistence key.
533    pub fn as_ident(&self) -> &'static str {
534        match self {
535            Self::Table => "table",
536            Self::Nodes => "nodes",
537            Self::Edges => "edges",
538            Self::Vectors => "vectors",
539            Self::Messages => "messages",
540            Self::Points => "points",
541            Self::Documents => "documents",
542        }
543    }
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
547pub enum PolicyAction {
548    Select,
549    Insert,
550    Update,
551    Delete,
552}
553
554#[derive(Debug, Clone, PartialEq, Eq)]
555pub struct DropPolicyQuery {
556    pub name: String,
557    pub table: String,
558    pub if_exists: bool,
559}
560
561#[derive(Debug, Clone)]
562pub struct CreateViewQuery {
563    pub name: String,
564    /// Parsed `SELECT ...` body. Stored as a boxed `QueryExpr` so the
565    /// runtime can substitute the tree directly when a query references
566    /// this view (no re-parsing per read).
567    pub query: Box<QueryExpr>,
568    pub materialized: bool,
569    pub if_not_exists: bool,
570    /// `CREATE OR REPLACE VIEW` — overwrites any existing definition.
571    pub or_replace: bool,
572    /// `REFRESH EVERY <duration>` clause — only valid on materialized
573    /// views. When set, a background scheduler ticks the view at this
574    /// cadence. `None` means refresh-on-demand only (slice 9 behaviour).
575    /// Issue #583 slice 10.
576    pub refresh_every_ms: Option<u64>,
577    /// `WITH RETENTION <duration>` clause — only valid on materialized
578    /// views (issue #584 slice 12). Opts the view's backing storage
579    /// into a retention policy independent of the source. Persisted on
580    /// the view definition; the physical sweep is applied to the
581    /// MV's backing rows once slice-9's row-storage follow-up lands.
582    /// `None` means the view is unaffected by source retention.
583    pub retention_duration_ms: Option<u64>,
584}
585
586#[derive(Debug, Clone, PartialEq, Eq)]
587pub struct DropViewQuery {
588    pub name: String,
589    pub materialized: bool,
590    pub if_exists: bool,
591}
592
593#[derive(Debug, Clone, PartialEq, Eq)]
594pub struct RefreshMaterializedViewQuery {
595    pub name: String,
596}
597
598#[derive(Debug, Clone, PartialEq, Eq)]
599pub struct CopyFromQuery {
600    pub table: String,
601    pub path: String,
602    pub format: CopyFormat,
603    pub delimiter: Option<char>,
604    pub has_header: bool,
605}
606
607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
608pub enum CopyFormat {
609    Csv,
610}
611
612#[derive(Debug, Clone, PartialEq, Eq)]
613pub struct CreateSchemaQuery {
614    pub name: String,
615    pub if_not_exists: bool,
616}
617
618#[derive(Debug, Clone, PartialEq, Eq)]
619pub struct DropSchemaQuery {
620    pub name: String,
621    pub if_exists: bool,
622    pub cascade: bool,
623}
624
625#[derive(Debug, Clone, PartialEq, Eq)]
626pub struct CreateSequenceQuery {
627    pub name: String,
628    pub if_not_exists: bool,
629    /// First value produced by `nextval`. Default 1.
630    pub start: i64,
631    /// Added to the current value on each `nextval`. Default 1.
632    pub increment: i64,
633}
634
635#[derive(Debug, Clone, PartialEq, Eq)]
636pub struct DropSequenceQuery {
637    pub name: String,
638    pub if_exists: bool,
639}
640
641/// Transaction-control statement variants. See [`QueryExpr::TransactionControl`].
642#[derive(Debug, Clone, PartialEq, Eq)]
643pub enum TxnControl {
644    /// `BEGIN [WORK | TRANSACTION]`, `START TRANSACTION`
645    Begin,
646    /// `COMMIT [WORK | TRANSACTION]`, `END`
647    Commit,
648    /// `ROLLBACK [WORK | TRANSACTION]`
649    Rollback,
650    /// `SAVEPOINT name`
651    Savepoint(String),
652    /// `RELEASE [SAVEPOINT] name`
653    ReleaseSavepoint(String),
654    /// `ROLLBACK TO [SAVEPOINT] name`
655    RollbackToSavepoint(String),
656}
657
658/// Maintenance command variants. See [`QueryExpr::MaintenanceCommand`].
659#[derive(Debug, Clone, PartialEq, Eq)]
660pub enum MaintenanceCommand {
661    /// `VACUUM [FULL] [table]`
662    ///
663    /// Triggers segment compaction and planner stats refresh. `FULL` additionally
664    /// forces a full pager sync. Target `None` applies to every collection.
665    Vacuum { target: Option<String>, full: bool },
666    /// `ANALYZE [table]`
667    ///
668    /// Refreshes planner statistics (histogram, distinct estimates, null counts).
669    /// Target `None` re-analyzes every collection.
670    Analyze { target: Option<String> },
671}
672
673#[derive(Debug, Clone, PartialEq, Eq)]
674pub enum VcsCommand {
675    Checkpoint {
676        message: String,
677        author: Option<String>,
678    },
679    Checkout {
680        target: String,
681    },
682    Reset {
683        mode: VcsResetMode,
684        target: String,
685    },
686    Merge {
687        branch: String,
688    },
689    CherryPick {
690        commit: String,
691    },
692    Revert {
693        commit: String,
694    },
695    ResolveConflict {
696        key: String,
697        resolution: VcsConflictResolution,
698    },
699}
700
701#[derive(Debug, Clone, Copy, PartialEq, Eq)]
702pub enum VcsResetMode {
703    Hard,
704    Soft,
705    Mixed,
706}
707
708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
709pub enum VcsConflictResolution {
710    Ours,
711    Theirs,
712}
713
714/// AST node for `EXPLAIN ALTER FOR <CreateTableStmt> [FORMAT JSON]`.
715///
716/// `target` carries the CREATE TABLE structure exactly as the
717/// parser produces it for a regular CREATE — full reuse of
718/// `parse_create_table_body`. `format` determines whether the
719/// executor emits a `ALTER TABLE …;`-flavored text payload
720/// (the default — copy-paste friendly into the REPL) or a
721/// structured JSON object (machine-friendly).
722#[derive(Debug, Clone)]
723pub struct ExplainAlterQuery {
724    pub target: CreateTableQuery,
725    pub format: ExplainFormat,
726}
727
728/// Output format requested for an `EXPLAIN ALTER` command.
729#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
730pub enum ExplainFormat {
731    /// Plain SQL text — `ALTER TABLE …;` lines plus header
732    /// comments and rename hints. Default; copy-paste friendly.
733    #[default]
734    Sql,
735    /// Structured JSON object with `operations`,
736    /// `rename_candidates`, `summary`. Machine-friendly for
737    /// driver code (Purple migration generator, dashboards,
738    /// CLI tools).
739    Json,
740}
741
742#[derive(Debug, Clone, PartialEq)]
743pub struct CreateMigrationQuery {
744    pub name: String,
745    pub body: String,
746    pub depends_on: Vec<String>,
747    pub batch_size: Option<u64>,
748    pub no_rollback: bool,
749}
750
751#[derive(Debug, Clone, PartialEq)]
752pub struct ApplyMigrationQuery {
753    pub target: ApplyMigrationTarget,
754    pub for_tenant: Option<String>,
755}
756
757#[derive(Debug, Clone, PartialEq)]
758pub enum ApplyMigrationTarget {
759    Named(String),
760    All,
761}
762
763#[derive(Debug, Clone, PartialEq)]
764pub struct RollbackMigrationQuery {
765    pub name: String,
766}
767
768#[derive(Debug, Clone, PartialEq)]
769pub struct ExplainMigrationQuery {
770    pub name: String,
771}
772
773/// Probabilistic data structure commands
774#[derive(Debug, Clone)]
775pub enum ProbabilisticCommand {
776    // HyperLogLog
777    CreateHll {
778        name: String,
779        precision: u8,
780        if_not_exists: bool,
781    },
782    HllAdd {
783        name: String,
784        elements: Vec<String>,
785    },
786    HllCount {
787        names: Vec<String>,
788    },
789    HllMerge {
790        dest: String,
791        sources: Vec<String>,
792    },
793    HllInfo {
794        name: String,
795    },
796    DropHll {
797        name: String,
798        if_exists: bool,
799    },
800
801    // Count-Min Sketch (Fase 7)
802    CreateSketch {
803        name: String,
804        width: usize,
805        depth: usize,
806        if_not_exists: bool,
807    },
808    SketchAdd {
809        name: String,
810        element: String,
811        count: u64,
812    },
813    SketchCount {
814        name: String,
815        element: String,
816    },
817    SketchMerge {
818        dest: String,
819        sources: Vec<String>,
820    },
821    SketchInfo {
822        name: String,
823    },
824    DropSketch {
825        name: String,
826        if_exists: bool,
827    },
828
829    // Cuckoo Filter (Fase 8)
830    CreateFilter {
831        name: String,
832        capacity: usize,
833        if_not_exists: bool,
834    },
835    FilterAdd {
836        name: String,
837        element: String,
838    },
839    FilterCheck {
840        name: String,
841        element: String,
842    },
843    FilterDelete {
844        name: String,
845        element: String,
846    },
847    FilterCount {
848        name: String,
849    },
850    FilterInfo {
851        name: String,
852    },
853    DropFilter {
854        name: String,
855        if_exists: bool,
856    },
857}
858
859/// Default H3 resolution for `CREATE INDEX ... USING H3` when no
860/// explicit resolution is supplied. Resolution 9 ≈ ~150 m hex edge
861/// (PRD #1574 slice 2, #1576).
862pub const DEFAULT_H3_RESOLUTION: u8 = 9;
863
864/// Index type for CREATE INDEX ... USING <type>
865#[derive(Debug, Clone, PartialEq, Eq)]
866pub enum IndexMethod {
867    BTree,
868    Hash,
869    Bitmap,
870    RTree,
871    /// Generic spatial index request (`USING SPATIAL`) — the engine picks
872    /// the default spatial backend. As of PRD #1574 slice 4 (#1578) that
873    /// default is the disk-resident H3 index (RAM stays O(working set)),
874    /// not the unbounded in-RAM `RTree`. Use the explicit `USING RTREE`
875    /// form when the memory-capped in-RAM R-tree is specifically wanted.
876    Spatial,
877    /// H3 hexagonal spatial index: the `(lat, lon)` geo column is
878    /// encoded to a single H3 cell-id `u64` (at `resolution`) and stored
879    /// in the existing disk-paged B-tree (PRD #1574 slice 2, #1576).
880    H3 {
881        resolution: u8,
882    },
883}
884
885impl fmt::Display for IndexMethod {
886    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887        match self {
888            Self::BTree => write!(f, "BTREE"),
889            Self::Hash => write!(f, "HASH"),
890            Self::Bitmap => write!(f, "BITMAP"),
891            Self::RTree => write!(f, "RTREE"),
892            Self::Spatial => write!(f, "SPATIAL"),
893            Self::H3 { .. } => write!(f, "H3"),
894        }
895    }
896}
897
898/// CREATE INDEX [UNIQUE] [IF NOT EXISTS] name ON table (col1, col2, ...) [USING method]
899#[derive(Debug, Clone)]
900pub struct CreateIndexQuery {
901    pub name: String,
902    pub table: String,
903    pub columns: Vec<String>,
904    pub method: IndexMethod,
905    pub unique: bool,
906    pub if_not_exists: bool,
907}
908
909/// DROP INDEX [IF EXISTS] name ON table
910#[derive(Debug, Clone)]
911pub struct DropIndexQuery {
912    pub name: String,
913    pub table: String,
914    pub if_exists: bool,
915}
916
917/// ASK 'question' [USING provider] [MODEL 'model'] [DEPTH n] [LIMIT n] [MIN_SCORE x]
918///                [COLLECTION col] [TEMPERATURE x] [SEED n] [STRICT ON|OFF] [STREAM]
919///                [CACHE TTL '5m' | NOCACHE] [AS RQL]
920///
921/// `temperature` and `seed` are per-query overrides resolved by the
922/// `DeterminismDecider` (issue #400). The parser merely surfaces the
923/// requested values; capability-based dropping happens at decide time.
924#[derive(Debug, Clone)]
925pub struct AskQuery {
926    /// `EXPLAIN ASK '...'` returns the retrieval/provider/cost plan
927    /// without making the LLM call.
928    pub explain: bool,
929    pub question: String,
930    /// Optional `$N` / `?` parameter slot for the question text.
931    pub question_param: Option<usize>,
932    pub provider: Option<String>,
933    pub model: Option<String>,
934    pub depth: Option<usize>,
935    pub limit: Option<usize>,
936    pub min_score: Option<f32>,
937    pub collection: Option<String>,
938    /// Per-query temperature override (`ASK '...' TEMPERATURE 0.7`).
939    /// `None` means fall back to `ask.default_temperature`.
940    pub temperature: Option<f32>,
941    /// Per-query seed override (`ASK '...' SEED 42`). `None` means the
942    /// decider derives one from `hash(question + sources_fingerprint)`.
943    pub seed: Option<u64>,
944    /// Strict citation validation is on by default. `STRICT OFF` keeps
945    /// citation diagnostics as warnings and skips retry/error handling.
946    pub strict: bool,
947    /// HTTP-only SSE response requested via `ASK '...' STREAM`.
948    pub stream: bool,
949    /// Per-query answer-cache override.
950    pub cache: AskCacheClause,
951    /// `ASK '...' AS RQL` returns a validated RQL candidate instead of
952    /// calling an AI provider. The runtime owns translation and validation.
953    pub as_rql: bool,
954    /// `ASK '...' EXECUTE` opts in to auto-running a generated RQL
955    /// candidate when (and only when) it is read-only. A mutating
956    /// candidate is refused for auto-execution regardless of this flag.
957    pub execute: bool,
958}
959
960#[derive(Debug, Clone, PartialEq, Eq, Default)]
961pub enum AskCacheClause {
962    #[default]
963    Default,
964    CacheTtl(String),
965    NoCache,
966}
967
968impl QueryExpr {
969    /// Create a table query
970    pub fn table(name: &str) -> TableQueryBuilder {
971        TableQueryBuilder::new(name)
972    }
973
974    /// Create a graph query
975    pub fn graph() -> GraphQueryBuilder {
976        GraphQueryBuilder::new()
977    }
978
979    /// Create a path query
980    pub fn path(from: NodeSelector, to: NodeSelector) -> PathQueryBuilder {
981        PathQueryBuilder::new(from, to)
982    }
983}
984
985// ============================================================================
986// Table Query
987// ============================================================================
988
989/// Table query: SELECT columns FROM table WHERE filter ORDER BY ... LIMIT ...
990#[derive(Debug, Clone)]
991pub struct TableQuery {
992    /// Table name. Legacy slot — still populated even when `source`
993    /// is set to a subquery so existing call sites that read
994    /// `query.table.as_str()` keep compiling. When `source` is
995    /// `Some(TableSource::Subquery(…))`, this field holds a synthetic
996    /// sentinel name (`"__subq_NNNN"`) that runtime code must never
997    /// resolve against the real schema registry.
998    pub table: String,
999    /// Fase 2 Week 3: structured table source. `None` means the
1000    /// legacy `table` field is authoritative. `Some(Name)` is the
1001    /// same information as `table` but in typed form. `Some(Subquery)`
1002    /// wires a `(SELECT …) AS alias` in a FROM position — the Fase
1003    /// 1.7 unlock.
1004    pub source: Option<TableSource>,
1005    /// Optional table alias
1006    pub alias: Option<String>,
1007    /// Canonical SQL select list.
1008    pub select_items: Vec<SelectItem>,
1009    /// Columns to select (empty = all)
1010    pub columns: Vec<Projection>,
1011    /// Canonical SQL WHERE clause.
1012    pub where_expr: Option<super::Expr>,
1013    /// Filter condition
1014    pub filter: Option<Filter>,
1015    /// Canonical SQL GROUP BY items.
1016    pub group_by_exprs: Vec<super::Expr>,
1017    /// GROUP BY fields
1018    pub group_by: Vec<String>,
1019    /// Canonical SQL HAVING clause.
1020    pub having_expr: Option<super::Expr>,
1021    /// HAVING filter (applied after grouping)
1022    pub having: Option<Filter>,
1023    /// Order by clauses
1024    pub order_by: Vec<OrderByClause>,
1025    /// Limit
1026    pub limit: Option<u64>,
1027    /// User-supplied-parameter slot for `LIMIT $N`. Set by the parser
1028    /// when the LIMIT clause references `$N`/`?` instead of a literal;
1029    /// cleared by the binder (`user_params::bind`) after substituting
1030    /// the parameter into `limit`. Mirrors the `limit_param` slot on
1031    /// `SearchCommand` variants — see #361 slice 11.
1032    pub limit_param: Option<usize>,
1033    /// Offset
1034    pub offset: Option<u64>,
1035    /// User-supplied-parameter slot for `OFFSET $N`. Same lifecycle as
1036    /// `limit_param`. See #361 slice 11.
1037    pub offset_param: Option<usize>,
1038    /// WITH EXPAND options (graph traversal, cross-ref following)
1039    pub expand: Option<ExpandOptions>,
1040    /// Time-travel anchor. When present the executor resolves this
1041    /// to an MVCC xid and evaluates the query against that snapshot
1042    /// instead of the current one. Mirrors git's `AS OF` semantics.
1043    pub as_of: Option<AsOfClause>,
1044    /// `SESSIONIZE BY <actor> GAP <duration> [ORDER BY <ts>]` operator
1045    /// (issue #585 slice 8). When present, the executor annotates each
1046    /// result row with a `session_id` column. `actor_col` / `gap_ms`
1047    /// may be `None` when the source collection's descriptor (slice 1
1048    /// `SESSION_KEY` / `SESSION_GAP`) supplies the defaults; one
1049    /// without the other resolved at execution time is the typed
1050    /// `MissingSessionKey` error.
1051    pub sessionize: Option<SessionizeClause>,
1052    /// `SELECT DISTINCT` projection quantifier. When `true` the executor
1053    /// deduplicates the projected output row-set (over the projected
1054    /// columns) before ORDER BY / LIMIT. `DISTINCT` inside an aggregate
1055    /// argument (`COUNT(DISTINCT x)`) is unrelated and lives on the
1056    /// aggregate call, not here.
1057    pub distinct: bool,
1058}
1059
1060/// `SESSIONIZE BY <actor_col> GAP <duration> [ORDER BY <ts_col>]`.
1061#[derive(Debug, Clone, Default)]
1062pub struct SessionizeClause {
1063    /// Explicit `BY <ident>`. `None` means "default from descriptor's
1064    /// `SESSION_KEY`" — resolved at execution time.
1065    pub actor_col: Option<String>,
1066    /// Explicit `GAP <duration>` in milliseconds. `None` means
1067    /// "default from descriptor's `SESSION_GAP`".
1068    pub gap_ms: Option<u64>,
1069    /// Explicit `ORDER BY <ident>` immediately after `GAP`. When
1070    /// `None` the executor falls back to the collection's timestamp
1071    /// column (the same resolution as `retention_filter`).
1072    pub order_col: Option<String>,
1073}
1074
1075/// Source spec for `AS OF` — parsed form sits in `TableQuery`, then
1076/// `vcs_resolve_as_of` turns it into an MVCC xid at execute time.
1077#[derive(Debug, Clone)]
1078pub enum AsOfClause {
1079    /// Explicit commit hash literal: `AS OF COMMIT '<hex>'`.
1080    Commit(String),
1081    /// Branch or ref: `AS OF BRANCH 'main'` or `AS OF 'refs/heads/main'`.
1082    Branch(String),
1083    /// Tag: `AS OF TAG 'v1.0'`.
1084    Tag(String),
1085    /// Unix epoch milliseconds: `AS OF TIMESTAMP 1710000000000`.
1086    TimestampMs(i64),
1087    /// Raw MVCC snapshot xid: `AS OF SNAPSHOT 12345`.
1088    Snapshot(u64),
1089}
1090
1091/// Structured FROM source for a `TableQuery`. Additive alongside the
1092/// legacy `TableQuery.table: String` slot — callers that understand
1093/// this type can branch on subqueries; callers that only read `table`
1094/// fall back to the synthetic sentinel name and, for subqueries,
1095/// produce an "unknown table" error until they migrate.
1096#[derive(Debug, Clone)]
1097pub enum TableSource {
1098    /// Plain table reference — equivalent to the legacy `String` form.
1099    Name(String),
1100    /// A subquery in FROM position: `FROM (SELECT …) AS alias`.
1101    Subquery(Box<QueryExpr>),
1102    /// A table-valued function call in FROM position, e.g.
1103    /// `FROM components(g)` (issue #795). `name` is the function
1104    /// identifier; `args` are its positional identifier arguments;
1105    /// `named_args` are `key => <f64>` named arguments such as
1106    /// `louvain(g, resolution => 0.5)` (issue #796), preserved in source
1107    /// order. Positional args always precede named args.
1108    Function {
1109        name: String,
1110        args: Vec<String>,
1111        named_args: Vec<(String, f64)>,
1112    },
1113    /// A graph-analytics table-valued function whose graph is supplied
1114    /// inline as two subqueries instead of a graph-collection reference
1115    /// (issue #799), e.g.
1116    /// `components(nodes => (SELECT id FROM hosts), edges => (SELECT src, dst FROM links))`.
1117    ///
1118    /// Structurally distinct from `Function` so the executor can tell the
1119    /// inline form from the graph-collection form. `nodes`/`edges` are the
1120    /// two materialization subqueries (the first column of `nodes` is the
1121    /// node id; the first two-or-three columns of `edges` are
1122    /// `(source, target [, weight])`). `named_args` carries any remaining
1123    /// numeric named arguments (e.g. `resolution => 0.5`).
1124    InlineGraphFunction {
1125        name: String,
1126        nodes: Box<QueryExpr>,
1127        edges: Box<QueryExpr>,
1128        named_args: Vec<(String, f64)>,
1129    },
1130}
1131
1132/// Options for WITH EXPAND clause on SELECT queries.
1133#[derive(Debug, Clone, Default)]
1134pub struct ExpandOptions {
1135    /// Expand via graph edges (WITH EXPAND GRAPH)
1136    pub graph: bool,
1137    /// Graph expansion depth (DEPTH n)
1138    pub graph_depth: usize,
1139    /// Expand via cross-references (WITH EXPAND CROSS_REFS)
1140    pub cross_refs: bool,
1141    /// Index hint from the optimizer (which index to prefer for this query)
1142    pub index_hint: Option<reddb_types::index_hint::IndexHint>,
1143}
1144
1145impl TableQuery {
1146    /// Create a new table query
1147    pub fn new(table: &str) -> Self {
1148        Self {
1149            table: table.to_string(),
1150            source: None,
1151            alias: None,
1152            select_items: Vec::new(),
1153            columns: Vec::new(),
1154            where_expr: None,
1155            filter: None,
1156            group_by_exprs: Vec::new(),
1157            group_by: Vec::new(),
1158            having_expr: None,
1159            having: None,
1160            order_by: Vec::new(),
1161            limit: None,
1162            limit_param: None,
1163            offset: None,
1164            offset_param: None,
1165            expand: None,
1166            as_of: None,
1167            sessionize: None,
1168            distinct: false,
1169        }
1170    }
1171
1172    /// Create a TableQuery that wraps a subquery in FROM position.
1173    /// The legacy `table` slot holds a synthetic sentinel so code that
1174    /// only reads `table.as_str()` errors loudly with a
1175    /// recognisable marker instead of silently treating it as a
1176    /// real collection.
1177    pub fn from_subquery(subquery: QueryExpr, alias: Option<String>) -> Self {
1178        let sentinel = match &alias {
1179            Some(a) => format!("__subq_{a}"),
1180            None => "__subq_anon".to_string(),
1181        };
1182        Self {
1183            table: sentinel,
1184            source: Some(TableSource::Subquery(Box::new(subquery))),
1185            alias,
1186            select_items: Vec::new(),
1187            columns: Vec::new(),
1188            where_expr: None,
1189            filter: None,
1190            group_by_exprs: Vec::new(),
1191            group_by: Vec::new(),
1192            having_expr: None,
1193            having: None,
1194            order_by: Vec::new(),
1195            limit: None,
1196            limit_param: None,
1197            offset: None,
1198            offset_param: None,
1199            expand: None,
1200            as_of: None,
1201            sessionize: None,
1202            distinct: false,
1203        }
1204    }
1205}
1206
1207/// Canonical SQL select item for table queries.
1208#[derive(Debug, Clone, PartialEq)]
1209pub enum SelectItem {
1210    Wildcard,
1211    Expr {
1212        expr: super::Expr,
1213        alias: Option<String>,
1214    },
1215}
1216
1217// ============================================================================
1218// Graph Query
1219// ============================================================================
1220
1221/// Graph query: MATCH pattern WHERE filter RETURN projection
1222#[derive(Debug, Clone)]
1223pub struct GraphQuery {
1224    /// Optional outer alias when used as a join source
1225    pub alias: Option<String>,
1226    /// Graph pattern to match
1227    pub pattern: GraphPattern,
1228    /// Filter condition
1229    pub filter: Option<Filter>,
1230    /// Return projections
1231    pub return_: Vec<Projection>,
1232    /// Optional row limit
1233    pub limit: Option<u64>,
1234}
1235
1236impl GraphQuery {
1237    /// Create a new graph query
1238    pub fn new(pattern: GraphPattern) -> Self {
1239        Self {
1240            alias: None,
1241            pattern,
1242            filter: None,
1243            return_: Vec::new(),
1244            limit: None,
1245        }
1246    }
1247
1248    /// Set outer alias
1249    pub fn alias(mut self, alias: &str) -> Self {
1250        self.alias = Some(alias.to_string());
1251        self
1252    }
1253}
1254
1255/// Graph pattern: collection of node and edge patterns
1256#[derive(Debug, Clone, Default)]
1257pub struct GraphPattern {
1258    /// Node patterns
1259    pub nodes: Vec<NodePattern>,
1260    /// Edge patterns connecting nodes
1261    pub edges: Vec<EdgePattern>,
1262}
1263
1264impl GraphPattern {
1265    /// Create an empty pattern
1266    pub fn new() -> Self {
1267        Self::default()
1268    }
1269
1270    /// Add a node pattern
1271    pub fn node(mut self, pattern: NodePattern) -> Self {
1272        self.nodes.push(pattern);
1273        self
1274    }
1275
1276    /// Add an edge pattern
1277    pub fn edge(mut self, pattern: EdgePattern) -> Self {
1278        self.edges.push(pattern);
1279        self
1280    }
1281}
1282
1283/// Node pattern: (alias:Type {properties})
1284#[derive(Debug, Clone)]
1285pub struct NodePattern {
1286    /// Variable alias for this node
1287    pub alias: String,
1288    /// Optional label filter. Stored as the user-supplied label string so
1289    /// the parser is registry-free; executors resolve it against the live
1290    /// [`crate::storage::engine::graph_store::LabelRegistry`].
1291    pub node_label: Option<String>,
1292    /// Property filters
1293    pub properties: Vec<PropertyFilter>,
1294}
1295
1296impl NodePattern {
1297    /// Create a new node pattern
1298    pub fn new(alias: &str) -> Self {
1299        Self {
1300            alias: alias.to_string(),
1301            node_label: None,
1302            properties: Vec::new(),
1303        }
1304    }
1305
1306    /// Set the label filter (string form — preferred).
1307    pub fn of_label(mut self, label: impl Into<String>) -> Self {
1308        self.node_label = Some(label.into());
1309        self
1310    }
1311
1312    /// Add property filter
1313    pub fn with_property(mut self, name: &str, op: CompareOp, value: Value) -> Self {
1314        self.properties.push(PropertyFilter {
1315            name: name.to_string(),
1316            op,
1317            value,
1318        });
1319        self
1320    }
1321}
1322
1323/// Edge pattern: -[alias:Type*min..max]->
1324#[derive(Debug, Clone)]
1325pub struct EdgePattern {
1326    /// Optional alias for this edge
1327    pub alias: Option<String>,
1328    /// Source node alias
1329    pub from: String,
1330    /// Target node alias
1331    pub to: String,
1332    /// Optional label filter (user-supplied string).
1333    pub edge_label: Option<String>,
1334    /// Edge direction
1335    pub direction: EdgeDirection,
1336    /// Minimum hops (for variable-length patterns)
1337    pub min_hops: u32,
1338    /// Maximum hops (for variable-length patterns)
1339    pub max_hops: u32,
1340}
1341
1342impl EdgePattern {
1343    /// Create a new edge pattern
1344    pub fn new(from: &str, to: &str) -> Self {
1345        Self {
1346            alias: None,
1347            from: from.to_string(),
1348            to: to.to_string(),
1349            edge_label: None,
1350            direction: EdgeDirection::Outgoing,
1351            min_hops: 1,
1352            max_hops: 1,
1353        }
1354    }
1355
1356    /// Set label filter (string form — preferred).
1357    pub fn of_label(mut self, label: impl Into<String>) -> Self {
1358        self.edge_label = Some(label.into());
1359        self
1360    }
1361
1362    /// Set direction
1363    pub fn direction(mut self, dir: EdgeDirection) -> Self {
1364        self.direction = dir;
1365        self
1366    }
1367
1368    /// Set hop range for variable-length patterns
1369    pub fn hops(mut self, min: u32, max: u32) -> Self {
1370        self.min_hops = min;
1371        self.max_hops = max;
1372        self
1373    }
1374
1375    /// Set alias
1376    pub fn alias(mut self, alias: &str) -> Self {
1377        self.alias = Some(alias.to_string());
1378        self
1379    }
1380}
1381
1382/// Edge direction
1383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1384pub enum EdgeDirection {
1385    /// Outgoing: (a)-[r]->(b)
1386    Outgoing,
1387    /// Incoming: (a)<-[r]-(b)
1388    Incoming,
1389    /// Both: (a)-[r]-(b)
1390    Both,
1391}
1392
1393/// Property filter: name op value
1394#[derive(Debug, Clone)]
1395pub struct PropertyFilter {
1396    pub name: String,
1397    pub op: CompareOp,
1398    pub value: Value,
1399}
1400
1401// ============================================================================
1402// Join Query
1403// ============================================================================
1404
1405/// Join query: combines table and graph queries
1406#[derive(Debug, Clone)]
1407pub struct JoinQuery {
1408    /// Left side (typically table)
1409    pub left: Box<QueryExpr>,
1410    /// Right side (typically graph)
1411    pub right: Box<QueryExpr>,
1412    /// Join type
1413    pub join_type: JoinType,
1414    /// Join condition
1415    pub on: JoinCondition,
1416    /// Post-join filter condition
1417    pub filter: Option<Filter>,
1418    /// Post-join ordering
1419    pub order_by: Vec<OrderByClause>,
1420    /// Post-join limit
1421    pub limit: Option<u64>,
1422    /// Post-join offset
1423    pub offset: Option<u64>,
1424    /// Canonical SQL RETURN projection.
1425    pub return_items: Vec<SelectItem>,
1426    /// Post-join projection
1427    pub return_: Vec<Projection>,
1428}
1429
1430impl JoinQuery {
1431    /// Create a new join query
1432    pub fn new(left: QueryExpr, right: QueryExpr, on: JoinCondition) -> Self {
1433        Self {
1434            left: Box::new(left),
1435            right: Box::new(right),
1436            join_type: JoinType::Inner,
1437            on,
1438            filter: None,
1439            order_by: Vec::new(),
1440            limit: None,
1441            offset: None,
1442            return_items: Vec::new(),
1443            return_: Vec::new(),
1444        }
1445    }
1446
1447    /// Set join type
1448    pub fn join_type(mut self, jt: JoinType) -> Self {
1449        self.join_type = jt;
1450        self
1451    }
1452}
1453
1454/// Join type
1455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1456pub enum JoinType {
1457    /// Inner join — only matching pairs emitted
1458    Inner,
1459    /// Left outer join — every left row, matched or padded with nulls on the right
1460    LeftOuter,
1461    /// Right outer join — every right row, matched or padded with nulls on the left
1462    RightOuter,
1463    /// Full outer join — LeftOuter ∪ RightOuter, each unmatched side padded
1464    FullOuter,
1465    /// Cross join — Cartesian product, no predicate
1466    Cross,
1467}
1468
1469/// Join condition: how to match rows with nodes
1470#[derive(Debug, Clone)]
1471pub struct JoinCondition {
1472    /// Left field (table side)
1473    pub left_field: FieldRef,
1474    /// Right field (graph side)
1475    pub right_field: FieldRef,
1476}
1477
1478impl JoinCondition {
1479    /// Create a new join condition
1480    pub fn new(left: FieldRef, right: FieldRef) -> Self {
1481        Self {
1482            left_field: left,
1483            right_field: right,
1484        }
1485    }
1486}
1487
1488/// Reference to a field (table column, node property, or edge property)
1489#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1490pub enum FieldRef {
1491    /// Table column: table.column
1492    TableColumn { table: String, column: String },
1493    /// Node property: alias.property
1494    NodeProperty { alias: String, property: String },
1495    /// Edge property: alias.property
1496    EdgeProperty { alias: String, property: String },
1497    /// Node ID: alias.id
1498    NodeId { alias: String },
1499}
1500
1501impl FieldRef {
1502    /// Create a table column reference
1503    pub fn column(table: &str, column: &str) -> Self {
1504        Self::TableColumn {
1505            table: table.to_string(),
1506            column: column.to_string(),
1507        }
1508    }
1509
1510    /// Create a node property reference
1511    pub fn node_prop(alias: &str, property: &str) -> Self {
1512        Self::NodeProperty {
1513            alias: alias.to_string(),
1514            property: property.to_string(),
1515        }
1516    }
1517
1518    /// Create a node ID reference
1519    pub fn node_id(alias: &str) -> Self {
1520        Self::NodeId {
1521            alias: alias.to_string(),
1522        }
1523    }
1524
1525    /// Create an edge property reference
1526    pub fn edge_prop(alias: &str, property: &str) -> Self {
1527        Self::EdgeProperty {
1528            alias: alias.to_string(),
1529            property: property.to_string(),
1530        }
1531    }
1532}
1533
1534// ============================================================================
1535// Path Query
1536// ============================================================================
1537
1538/// Path query: find paths between nodes
1539#[derive(Debug, Clone)]
1540pub struct PathQuery {
1541    /// Optional outer alias when used as a join source
1542    pub alias: Option<String>,
1543    /// Source node selector
1544    pub from: NodeSelector,
1545    /// Target node selector
1546    pub to: NodeSelector,
1547    /// Edge labels to traverse (empty = any). Strings are resolved against
1548    /// the runtime registry by the executor.
1549    pub via: Vec<String>,
1550    /// Maximum path length
1551    pub max_length: u32,
1552    /// Filter on paths
1553    pub filter: Option<Filter>,
1554    /// Return projections
1555    pub return_: Vec<Projection>,
1556}
1557
1558impl PathQuery {
1559    /// Create a new path query
1560    pub fn new(from: NodeSelector, to: NodeSelector) -> Self {
1561        Self {
1562            alias: None,
1563            from,
1564            to,
1565            via: Vec::new(),
1566            max_length: 10,
1567            filter: None,
1568            return_: Vec::new(),
1569        }
1570    }
1571
1572    /// Set outer alias
1573    pub fn alias(mut self, alias: &str) -> Self {
1574        self.alias = Some(alias.to_string());
1575        self
1576    }
1577
1578    /// Add an edge label constraint to traverse (string form).
1579    pub fn via_label(mut self, label: impl Into<String>) -> Self {
1580        self.via.push(label.into());
1581        self
1582    }
1583}
1584
1585/// Node selector for path queries
1586#[derive(Debug, Clone)]
1587pub enum NodeSelector {
1588    /// By node ID
1589    ById(String),
1590    /// By node label and property
1591    ByType {
1592        node_label: String,
1593        filter: Option<PropertyFilter>,
1594    },
1595    /// By table row (linked node)
1596    ByRow { table: String, row_id: u64 },
1597}
1598
1599impl NodeSelector {
1600    /// Select by node ID
1601    pub fn by_id(id: &str) -> Self {
1602        Self::ById(id.to_string())
1603    }
1604
1605    /// Select by label string (preferred).
1606    pub fn by_label(label: impl Into<String>) -> Self {
1607        Self::ByType {
1608            node_label: label.into(),
1609            filter: None,
1610        }
1611    }
1612
1613    /// Select by table row
1614    pub fn by_row(table: &str, row_id: u64) -> Self {
1615        Self::ByRow {
1616            table: table.to_string(),
1617            row_id,
1618        }
1619    }
1620}
1621
1622// ============================================================================
1623// Vector Query
1624// ============================================================================
1625
1626/// Vector similarity search query
1627///
1628/// ```text
1629/// VECTOR SEARCH embeddings
1630/// SIMILAR TO [0.1, 0.2, ..., 0.5]
1631/// WHERE metadata.source = 'nmap'
1632/// LIMIT 10
1633/// ```
1634#[derive(Debug, Clone)]
1635pub struct VectorQuery {
1636    /// Optional outer alias when used as a join source
1637    pub alias: Option<String>,
1638    /// Collection name to search
1639    pub collection: String,
1640    /// Query vector (or reference to get vector from)
1641    pub query_vector: VectorSource,
1642    /// Number of results to return
1643    pub k: usize,
1644    /// Metadata filter
1645    pub filter: Option<MetadataFilter>,
1646    /// Distance metric to use (defaults to collection's metric)
1647    pub metric: Option<DistanceMetric>,
1648    /// Include vectors in results
1649    pub include_vectors: bool,
1650    /// Include metadata in results
1651    pub include_metadata: bool,
1652    /// Minimum similarity threshold (optional)
1653    pub threshold: Option<f32>,
1654}
1655
1656impl VectorQuery {
1657    /// Create a new vector query
1658    pub fn new(collection: &str, query: VectorSource) -> Self {
1659        Self {
1660            alias: None,
1661            collection: collection.to_string(),
1662            query_vector: query,
1663            k: 10,
1664            filter: None,
1665            metric: None,
1666            include_vectors: false,
1667            include_metadata: true,
1668            threshold: None,
1669        }
1670    }
1671
1672    /// Set the number of results
1673    pub fn limit(mut self, k: usize) -> Self {
1674        self.k = k;
1675        self
1676    }
1677
1678    /// Set metadata filter
1679    pub fn with_filter(mut self, filter: MetadataFilter) -> Self {
1680        self.filter = Some(filter);
1681        self
1682    }
1683
1684    /// Include vectors in results
1685    pub fn with_vectors(mut self) -> Self {
1686        self.include_vectors = true;
1687        self
1688    }
1689
1690    /// Set similarity threshold
1691    pub fn min_similarity(mut self, threshold: f32) -> Self {
1692        self.threshold = Some(threshold);
1693        self
1694    }
1695
1696    /// Set outer alias
1697    pub fn alias(mut self, alias: &str) -> Self {
1698        self.alias = Some(alias.to_string());
1699        self
1700    }
1701}
1702
1703/// Source of query vector
1704#[derive(Debug, Clone)]
1705pub enum VectorSource {
1706    /// Literal vector values
1707    Literal(Vec<f32>),
1708    /// Text to embed (requires embedding function)
1709    Text(String),
1710    /// Reference to another vector by ID
1711    Reference { collection: String, vector_id: u64 },
1712    /// From a subquery result
1713    Subquery(Box<QueryExpr>),
1714}
1715
1716impl VectorSource {
1717    /// Create from literal vector
1718    pub fn literal(values: Vec<f32>) -> Self {
1719        Self::Literal(values)
1720    }
1721
1722    /// Create from text (to be embedded)
1723    pub fn text(s: &str) -> Self {
1724        Self::Text(s.to_string())
1725    }
1726
1727    /// Reference another vector
1728    pub fn reference(collection: &str, vector_id: u64) -> Self {
1729        Self::Reference {
1730            collection: collection.to_string(),
1731            vector_id,
1732        }
1733    }
1734}
1735
1736// ============================================================================
1737// Hybrid Query
1738// ============================================================================
1739
1740/// Hybrid query combining structured (table/graph) and vector search
1741///
1742/// ```text
1743/// FROM hosts h
1744/// JOIN VECTOR embeddings e ON h.id = e.metadata.host_id
1745/// SIMILAR TO 'ssh vulnerability'
1746/// WHERE h.os = 'Linux'
1747/// RETURN h.*, e.distance
1748/// ```
1749#[derive(Debug, Clone)]
1750pub struct HybridQuery {
1751    /// Optional outer alias when used as a join source
1752    pub alias: Option<String>,
1753    /// Structured query part (table/graph)
1754    pub structured: Box<QueryExpr>,
1755    /// Vector search part
1756    pub vector: VectorQuery,
1757    /// How to combine results
1758    pub fusion: FusionStrategy,
1759    /// Final result limit
1760    pub limit: Option<usize>,
1761}
1762
1763impl HybridQuery {
1764    /// Create a new hybrid query
1765    pub fn new(structured: QueryExpr, vector: VectorQuery) -> Self {
1766        Self {
1767            alias: None,
1768            structured: Box::new(structured),
1769            vector,
1770            fusion: FusionStrategy::Rerank { weight: 0.5 },
1771            limit: None,
1772        }
1773    }
1774
1775    /// Set fusion strategy
1776    pub fn with_fusion(mut self, fusion: FusionStrategy) -> Self {
1777        self.fusion = fusion;
1778        self
1779    }
1780
1781    /// Set result limit
1782    pub fn limit(mut self, limit: usize) -> Self {
1783        self.limit = Some(limit);
1784        self
1785    }
1786
1787    /// Set outer alias
1788    pub fn alias(mut self, alias: &str) -> Self {
1789        self.alias = Some(alias.to_string());
1790        self
1791    }
1792}
1793
1794/// Strategy for combining structured and vector search results
1795#[derive(Debug, Clone)]
1796pub enum FusionStrategy {
1797    /// Vector similarity re-ranks structured results
1798    /// weight: 0.0 = pure structured, 1.0 = pure vector
1799    Rerank { weight: f32 },
1800    /// Filter with structured query, then search vectors among filtered
1801    FilterThenSearch,
1802    /// Search vectors first, then filter with structured query
1803    SearchThenFilter,
1804    /// Reciprocal Rank Fusion
1805    /// k: RRF constant (typically 60)
1806    RRF { k: u32 },
1807    /// Intersection: only return results that match both
1808    Intersection,
1809    /// Union: return results from either (with combined scores)
1810    Union {
1811        structured_weight: f32,
1812        vector_weight: f32,
1813    },
1814}
1815
1816impl Default for FusionStrategy {
1817    fn default() -> Self {
1818        Self::Rerank { weight: 0.5 }
1819    }
1820}
1821
1822// ============================================================================
1823// DML/DDL Query Types
1824// ============================================================================
1825
1826/// Entity type qualifier for INSERT statements
1827#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1828pub enum InsertEntityType {
1829    /// Default: plain row
1830    #[default]
1831    Row,
1832    /// INSERT INTO t NODE (...)
1833    Node,
1834    /// INSERT INTO t EDGE (...)
1835    Edge,
1836    /// INSERT INTO t VECTOR (...)
1837    Vector,
1838    /// INSERT INTO t DOCUMENT (...)
1839    Document,
1840    /// INSERT INTO t KV (...)
1841    Kv,
1842}
1843
1844/// Explicit item-kind qualifier for UPDATE statements.
1845#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1846pub enum UpdateTarget {
1847    /// Default: table/document/KV row-shaped items.
1848    #[default]
1849    Rows,
1850    /// UPDATE t DOCUMENTS SET ...
1851    Documents,
1852    /// UPDATE t KV SET ...
1853    Kv,
1854    /// UPDATE t NODES SET ...
1855    Nodes,
1856    /// UPDATE t EDGES SET ...
1857    Edges,
1858}
1859
1860/// An item in a RETURNING clause: either `*` (all columns) or a named column.
1861#[derive(Debug, Clone, PartialEq)]
1862pub enum ReturningItem {
1863    /// RETURNING *
1864    All,
1865    /// RETURNING col
1866    Column(String),
1867}
1868
1869/// INSERT INTO table (columns) VALUES (row1), (row2), ... [WITH TTL duration] [WITH METADATA (k=v)]
1870#[derive(Debug, Clone)]
1871pub struct InsertQuery {
1872    /// Target table name
1873    pub table: String,
1874    /// Entity type qualifier
1875    pub entity_type: InsertEntityType,
1876    /// Column names
1877    pub columns: Vec<String>,
1878    /// Canonical SQL rows of expressions.
1879    pub value_exprs: Vec<Vec<super::Expr>>,
1880    /// Rows of values (each inner Vec is one row)
1881    pub values: Vec<Vec<Value>>,
1882    /// Optional RETURNING clause items.
1883    pub returning: Option<Vec<ReturningItem>>,
1884    /// Optional TTL in milliseconds (from WITH TTL clause)
1885    pub ttl_ms: Option<u64>,
1886    /// Optional absolute expiration (from WITH EXPIRES AT clause)
1887    pub expires_at_ms: Option<u64>,
1888    /// Optional metadata key-value pairs (from WITH METADATA clause)
1889    pub with_metadata: Vec<(String, Value)>,
1890    /// Auto-embed fields on insert (from WITH AUTO EMBED clause)
1891    pub auto_embed: Option<AutoEmbedConfig>,
1892    /// Skip event subscription emission for this statement (SUPPRESS EVENTS).
1893    pub suppress_events: bool,
1894}
1895
1896/// Configuration for automatic embedding generation on INSERT.
1897#[derive(Debug, Clone)]
1898pub struct AutoEmbedConfig {
1899    /// Fields to extract text from for embedding
1900    pub fields: Vec<String>,
1901    /// AI provider (e.g. "openai")
1902    pub provider: String,
1903    /// Optional model override
1904    pub model: Option<String>,
1905}
1906
1907/// EVENTS BACKFILL collection [WHERE pred] TO queue [LIMIT n]
1908#[derive(Debug, Clone)]
1909pub struct EventsBackfillQuery {
1910    pub collection: String,
1911    pub where_filter: Option<String>,
1912    pub target_queue: String,
1913    pub limit: Option<u64>,
1914}
1915
1916/// UPDATE table SET col=val, ... WHERE filter [WITH TTL duration] [WITH METADATA (...)]
1917#[derive(Debug, Clone)]
1918pub struct UpdateQuery {
1919    /// Target table name
1920    pub table: String,
1921    /// Explicit item-kind target. Omitted targets default to rows.
1922    pub target: UpdateTarget,
1923    /// Canonical SQL assignments.
1924    pub assignment_exprs: Vec<(String, super::Expr)>,
1925    /// Per-assignment compound operator for `SET col += expr` forms.
1926    /// `None` means ordinary `SET col = expr`.
1927    pub compound_assignment_ops: Vec<Option<super::BinOp>>,
1928    /// Best-effort literal-only cache of assignments. Non-foldable expressions
1929    /// are preserved exclusively in `assignment_exprs` and evaluated later
1930    /// against the row pre-image by the runtime.
1931    pub assignments: Vec<(String, Value)>,
1932    /// Canonical SQL WHERE clause.
1933    pub where_expr: Option<super::Expr>,
1934    /// Optional WHERE filter
1935    pub filter: Option<Filter>,
1936    /// Optional TTL in milliseconds (from WITH TTL clause)
1937    pub ttl_ms: Option<u64>,
1938    /// Optional absolute expiration (from WITH EXPIRES AT clause)
1939    pub expires_at_ms: Option<u64>,
1940    /// Optional metadata key-value pairs (from WITH METADATA clause)
1941    pub with_metadata: Vec<(String, Value)>,
1942    /// Optional RETURNING clause items.
1943    pub returning: Option<Vec<ReturningItem>>,
1944    /// Optional Concurrent claim cardinality.
1945    pub claim_limit: Option<u64>,
1946    /// Require the claim cardinality to be fully satisfied before mutating.
1947    pub claim_exact: bool,
1948    /// Optional deterministic target ordering for limited UPDATE batches.
1949    pub order_by: Vec<OrderByClause>,
1950    /// Optional `LIMIT N` cap. Caps the number of targets the executor
1951    /// will mutate in a single statement. Required by `BATCH N ROWS`
1952    /// data migrations (#37) which run the same UPDATE body in a
1953    /// loop, advancing a checkpoint between batches.
1954    pub limit: Option<u64>,
1955    /// Skip event subscription emission for this statement (SUPPRESS EVENTS).
1956    pub suppress_events: bool,
1957}
1958
1959/// DELETE FROM table WHERE filter
1960#[derive(Debug, Clone)]
1961pub struct DeleteQuery {
1962    /// Target table name
1963    pub table: String,
1964    /// Canonical SQL WHERE clause.
1965    pub where_expr: Option<super::Expr>,
1966    /// Optional WHERE filter
1967    pub filter: Option<Filter>,
1968    /// Optional RETURNING clause items.
1969    pub returning: Option<Vec<ReturningItem>>,
1970    /// Skip event subscription emission for this statement (SUPPRESS EVENTS).
1971    pub suppress_events: bool,
1972}
1973
1974/// CREATE TABLE name (columns) or CREATE {KV|CONFIG|VAULT} name
1975#[derive(Debug, Clone)]
1976pub struct CreateTableQuery {
1977    /// Declared collection model. Defaults to Table for CREATE TABLE.
1978    pub collection_model: CollectionModel,
1979    /// Table name
1980    pub name: String,
1981    /// Column definitions
1982    pub columns: Vec<CreateColumnDef>,
1983    /// IF NOT EXISTS flag
1984    pub if_not_exists: bool,
1985    /// Optional default TTL applied to newly inserted items in this collection.
1986    pub default_ttl_ms: Option<u64>,
1987    /// Metrics rollup tiers declared by `CREATE METRICS ... DOWNSAMPLE`.
1988    /// Uses the existing time-series policy spelling: target:source:aggregation.
1989    pub metrics_rollup_policies: Vec<String>,
1990    /// Fields to prioritize in the context index (WITH CONTEXT INDEX ON (f1, f2))
1991    pub context_index_fields: Vec<String>,
1992    /// Enables the global context index for this table
1993    /// (`WITH context_index = true`). Default false — pure OLTP tables
1994    /// skip the tokenisation / 3-way RwLock write storm on every insert.
1995    /// Having `context_index_fields` non-empty also enables it implicitly.
1996    pub context_index_enabled: bool,
1997    /// When true, CREATE TABLE implicitly adds two user-visible columns
1998    /// `created_at` and `updated_at` (BIGINT unix-ms). The runtime
1999    /// populates them from `UnifiedEntity::created_at/updated_at` on
2000    /// every write; `created_at` is immutable after insert.
2001    /// Enabled via `WITH timestamps = true` in the DDL.
2002    pub timestamps: bool,
2003    /// Partitioning spec (Phase 2.2 PG parity).
2004    ///
2005    /// When present the table is the *parent* of a partition tree — every
2006    /// child partition is registered via `ALTER TABLE ... ATTACH PARTITION`.
2007    /// Phase 2.2 stops at registry-only: queries against a partitioned
2008    /// parent don't auto-rewrite as UNION yet (Phase 4 adds pruning).
2009    pub partition_by: Option<PartitionSpec>,
2010    /// Table-scoped multi-tenancy declaration (Phase 2.5.4).
2011    ///
2012    /// Syntax: `CREATE TABLE t (...) WITH (tenant_by = 'col_name')` or
2013    /// the shorthand `CREATE TABLE t (...) TENANT BY (col_name)`. The
2014    /// runtime treats the named column as the tenant discriminator and
2015    /// automatically:
2016    ///
2017    /// 1. Registers the table → column mapping so INSERTs that omit the
2018    ///    column get `CURRENT_TENANT()` auto-filled.
2019    /// 2. Installs an implicit RLS policy equivalent to
2020    ///    `USING (col = CURRENT_TENANT())` for SELECT/UPDATE/DELETE/INSERT.
2021    /// 3. Flips `rls_enabled_tables` on so the policy actually applies.
2022    ///
2023    /// None leaves the table non-tenant-scoped — callers manage tenancy
2024    /// manually via explicit CREATE POLICY if they want it.
2025    pub tenant_by: Option<String>,
2026    /// When true, UPDATE and DELETE on this table are rejected at
2027    /// parse time. Corresponds to `CREATE TABLE ... APPEND ONLY` or
2028    /// `WITH (append_only = true)`. Default false (mutable).
2029    pub append_only: bool,
2030    /// Declarative event subscriptions for this table. #291 stores
2031    /// metadata only; event emission is intentionally out of scope.
2032    pub subscriptions: Vec<reddb_types::catalog::SubscriptionDescriptor>,
2033    /// Analytics views declared by `CREATE GRAPH ... WITH ANALYTICS (...)`
2034    /// (issue #800). Empty for every collection model except graphs that
2035    /// opt in. Threaded into the persisted `CollectionContract` at execution
2036    /// time so each `<graph>.<output>` view is durable.
2037    pub analytics_config: Vec<reddb_types::catalog::AnalyticsViewDescriptor>,
2038    /// `CREATE VAULT ... WITH OWN MASTER KEY`: provision per-vault
2039    /// key material instead of using the cluster vault key.
2040    pub vault_own_master_key: bool,
2041    /// Per-collection AI policy declared by `WITH (EMBED (...) | MODERATE
2042    /// (...) | VISION (...))` (PRD #1267, issue #1271). `None` when no AI
2043    /// clause is present. The parser validates the grammar; the runtime
2044    /// validates each modality's provider/model against the capability
2045    /// matrix (#1269) at DDL execution time and persists the policy in
2046    /// the `CollectionContract`.
2047    pub ai_policy: Option<reddb_types::catalog::AiPolicy>,
2048}
2049
2050/// CREATE METRIC path TYPE kind ROLE role
2051///   [SOURCE <ident>] [QUERY '<text>'] [WINDOW <duration>] [TIME_FIELD <ident>]
2052///
2053/// Issue #790 — when any of the derived-metric clauses are present the
2054/// descriptor is a *derived* metric: it names the inputs that a future
2055/// execution layer would consume. v0 stores the metadata only; reads of
2056/// the metric's *output* (not its descriptor) return a structured
2057/// "not yet implemented" error.
2058#[derive(Debug, Clone)]
2059pub struct CreateMetricQuery {
2060    pub path: String,
2061    pub kind: String,
2062    pub role: String,
2063    pub source: Option<String>,
2064    pub query: Option<String>,
2065    pub window_ms: Option<u64>,
2066    pub time_field: Option<String>,
2067}
2068
2069/// ALTER METRIC path SET <field> <value>
2070///
2071/// v0 mutability:
2072/// - `set_role`: mutable — role is a semantic label (operational/kpi/sli).
2073/// - `attempted_kind`: parser captured a `SET KIND`/`SET TYPE` clause; the
2074///   runtime rejects with a clear error because kind changes alter the
2075///   metric's mathematical meaning (counter vs gauge vs histogram, etc.).
2076/// - `attempted_path`: parser captured a `SET PATH` clause; the runtime
2077///   rejects because path is the descriptor's identity.
2078#[derive(Debug, Clone)]
2079pub struct AlterMetricQuery {
2080    pub path: String,
2081    pub set_role: Option<String>,
2082    pub attempted_kind: Option<String>,
2083    pub attempted_path: Option<String>,
2084}
2085
2086/// CREATE SLO path ON metric_path TARGET t WINDOW d UNIT
2087///
2088/// Issue #791 — declared over an existing SLI-role metric descriptor.
2089/// `target` is the objective (0 < target <= 1, e.g. 0.999); `window_ms`
2090/// is the rolling window the objective is evaluated over. Burn-rate /
2091/// error-budget evaluation is deferred to later slices — v0 stores
2092/// catalog state only.
2093#[derive(Debug, Clone)]
2094pub struct CreateSloQuery {
2095    pub path: String,
2096    pub metric_path: String,
2097    pub target: f64,
2098    pub window_ms: u64,
2099}
2100
2101/// CREATE COLLECTION name KIND kind [SIGNED_BY ('pubkey_hex', ...)]
2102#[derive(Debug, Clone)]
2103pub struct CreateCollectionQuery {
2104    pub name: String,
2105    pub kind: String,
2106    pub if_not_exists: bool,
2107    pub vector_dimension: Option<usize>,
2108    pub vector_metric: Option<DistanceMetric>,
2109    /// Initial Ed25519 allowed-signer registry. Empty = unsigned collection.
2110    /// Each entry is a 32-byte Ed25519 public key. Mutable post-create via
2111    /// `ALTER COLLECTION ... ADD|REVOKE SIGNER` (see issue #520).
2112    pub allowed_signers: Vec<[u8; 32]>,
2113}
2114
2115/// CREATE VECTOR name DIM n [METRIC metric]
2116#[derive(Debug, Clone)]
2117pub struct CreateVectorQuery {
2118    pub name: String,
2119    pub dimension: usize,
2120    pub metric: DistanceMetric,
2121    pub if_not_exists: bool,
2122}
2123
2124/// `PARTITION BY RANGE|LIST|HASH (column)` clause.
2125#[derive(Debug, Clone, PartialEq, Eq)]
2126pub struct PartitionSpec {
2127    pub kind: PartitionKind,
2128    /// Partition key column(s). Simple single-column for Phase 2.2.
2129    pub column: String,
2130}
2131
2132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2133pub enum PartitionKind {
2134    /// `PARTITION BY RANGE(col)` — children bind `FOR VALUES FROM (a) TO (b)`.
2135    Range,
2136    /// `PARTITION BY LIST(col)` — children bind `FOR VALUES IN (v1, v2, ...)`.
2137    List,
2138    /// `PARTITION BY HASH(col)` — children bind `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2139    Hash,
2140}
2141
2142/// Column definition for CREATE TABLE
2143#[derive(Debug, Clone)]
2144pub struct CreateColumnDef {
2145    /// Column name
2146    pub name: String,
2147    /// Legacy declared type string preserved for the runtime/storage pipeline.
2148    pub data_type: String,
2149    /// Structured SQL type used by the semantic layer.
2150    pub sql_type: SqlTypeName,
2151    /// NOT NULL constraint
2152    pub not_null: bool,
2153    /// DEFAULT value expression
2154    pub default: Option<String>,
2155    /// Compression level (COMPRESS:N)
2156    pub compress: Option<u8>,
2157    /// UNIQUE constraint
2158    pub unique: bool,
2159    /// PRIMARY KEY constraint
2160    pub primary_key: bool,
2161    /// Enum variant names (for ENUM type)
2162    pub enum_variants: Vec<String>,
2163    /// Array element type (for ARRAY type)
2164    pub array_element: Option<String>,
2165    /// Decimal precision (for DECIMAL type)
2166    pub decimal_precision: Option<u8>,
2167}
2168
2169/// DROP TABLE name
2170#[derive(Debug, Clone)]
2171pub struct DropTableQuery {
2172    /// Table name
2173    pub name: String,
2174    /// IF EXISTS flag
2175    pub if_exists: bool,
2176}
2177
2178/// DROP GRAPH [IF EXISTS] name
2179#[derive(Debug, Clone)]
2180pub struct DropGraphQuery {
2181    pub name: String,
2182    pub if_exists: bool,
2183}
2184
2185/// DROP VECTOR [IF EXISTS] name
2186#[derive(Debug, Clone)]
2187pub struct DropVectorQuery {
2188    pub name: String,
2189    pub if_exists: bool,
2190}
2191
2192/// DROP DOCUMENT [IF EXISTS] name
2193#[derive(Debug, Clone)]
2194pub struct DropDocumentQuery {
2195    pub name: String,
2196    pub if_exists: bool,
2197}
2198
2199/// DROP {KV|CONFIG|VAULT} [IF EXISTS] name
2200#[derive(Debug, Clone)]
2201pub struct DropKvQuery {
2202    pub name: String,
2203    pub if_exists: bool,
2204    pub model: CollectionModel,
2205}
2206
2207/// DROP COLLECTION [IF EXISTS] name
2208#[derive(Debug, Clone)]
2209pub struct DropCollectionQuery {
2210    pub name: String,
2211    pub if_exists: bool,
2212    pub model: Option<CollectionModel>,
2213}
2214
2215/// TRUNCATE {TABLE|GRAPH|VECTOR|DOCUMENT|TIMESERIES|KV|QUEUE|COLLECTION} [IF EXISTS] name
2216#[derive(Debug, Clone)]
2217pub struct TruncateQuery {
2218    pub name: String,
2219    pub model: Option<CollectionModel>,
2220    pub if_exists: bool,
2221}
2222
2223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2224pub enum VcsRefKind {
2225    Branch,
2226    Tag,
2227}
2228
2229/// CREATE BRANCH 'name' [FROM commitish] / CREATE TAG 'name' [AT commitish]
2230#[derive(Debug, Clone)]
2231pub struct CreateVcsRefQuery {
2232    pub kind: VcsRefKind,
2233    pub name: String,
2234    pub target: Option<String>,
2235}
2236
2237/// DROP BRANCH 'name' / DROP TAG 'name'
2238#[derive(Debug, Clone)]
2239pub struct DropVcsRefQuery {
2240    pub kind: VcsRefKind,
2241    pub name: String,
2242}
2243
2244/// ALTER TABLE name operations
2245#[derive(Debug, Clone)]
2246pub struct AlterTableQuery {
2247    /// Table name
2248    pub name: String,
2249    /// Alter operations
2250    pub operations: Vec<AlterOperation>,
2251}
2252
2253/// Single ALTER TABLE operation
2254#[derive(Debug, Clone)]
2255pub enum AlterOperation {
2256    /// ADD COLUMN definition
2257    AddColumn(CreateColumnDef),
2258    /// DROP COLUMN name
2259    DropColumn(String),
2260    /// RENAME COLUMN from TO to
2261    RenameColumn { from: String, to: String },
2262    /// `ATTACH PARTITION child FOR VALUES ...` (Phase 2.2 PG parity).
2263    ///
2264    /// Binds an existing child table to the parent partitioned table.
2265    /// The `bound` string captures the raw bound expression so the
2266    /// runtime can round-trip it back into `red_config` without a
2267    /// dedicated per-kind AST.
2268    AttachPartition {
2269        child: String,
2270        /// Human-readable bound string, e.g. `FROM (2024-01-01) TO (2025-01-01)`
2271        /// or `IN (1, 2, 3)` or `WITH (MODULUS 4, REMAINDER 0)`.
2272        bound: String,
2273    },
2274    /// `DETACH PARTITION child`
2275    DetachPartition { child: String },
2276    /// `ENABLE ROW LEVEL SECURITY` (Phase 2.5 PG parity).
2277    ///
2278    /// Flips the table into RLS-enforced mode. Reads against the table
2279    /// will be filtered by every matching `CREATE POLICY` (for the
2280    /// current role) combined with `AND`.
2281    EnableRowLevelSecurity,
2282    /// `DISABLE ROW LEVEL SECURITY` — disables enforcement; policies
2283    /// remain defined but are ignored until re-enabled.
2284    DisableRowLevelSecurity,
2285    /// `ENABLE TENANCY ON (col)` (Phase 2.5.4 PG parity-ish).
2286    ///
2287    /// Retrofit a tenant-scoped declaration onto an existing table —
2288    /// registers the column, installs the auto `__tenant_iso` RLS
2289    /// policy, and flips RLS on. Equivalent to re-running
2290    /// `CREATE TABLE ... TENANT BY (col)` minus the schema creation.
2291    EnableTenancy { column: String },
2292    /// `DISABLE TENANCY` — tears down the auto-policy and clears the
2293    /// tenancy registration. User-defined policies on the table are
2294    /// untouched; RLS stays enabled if any survive.
2295    DisableTenancy,
2296    /// `SET APPEND_ONLY = true|false` — flips the catalog flag.
2297    /// Setting `true` rejects all future UPDATE/DELETE at parse-time
2298    /// guard; setting `false` re-enables them. Existing rows are
2299    /// untouched either way — this is a purely declarative switch.
2300    SetAppendOnly(bool),
2301    /// `SET VERSIONED = true|false` — opt the table into (or out of)
2302    /// Git-for-Data. Enables merge / diff / AS OF semantics against
2303    /// this collection. Works retroactively: previously-created
2304    /// rows become part of the history accessible via AS OF as long
2305    /// as their xmin is still pinned by an existing commit.
2306    SetVersioned(bool),
2307    /// `ENABLE EVENTS ...` — install or re-enable table event subscription metadata.
2308    EnableEvents(reddb_types::catalog::SubscriptionDescriptor),
2309    /// `DISABLE EVENTS` — mark all table event subscriptions disabled.
2310    DisableEvents,
2311    /// `ADD SUBSCRIPTION name TO queue [REDACT (...)] [WHERE ...]` — add a named subscription.
2312    AddSubscription {
2313        name: String,
2314        descriptor: reddb_types::catalog::SubscriptionDescriptor,
2315    },
2316    /// `DROP SUBSCRIPTION name` — remove a named subscription by name.
2317    DropSubscription { name: String },
2318    /// Issue #522 — `ALTER COLLECTION name ADD SIGNER 'hex_pubkey'`.
2319    /// Appends the key to the per-collection signer registry and
2320    /// records an `Add` entry on the `signer_history` audit log.
2321    AddSigner { pubkey: [u8; 32] },
2322    /// Issue #522 — `ALTER COLLECTION name REVOKE SIGNER 'hex_pubkey'`.
2323    /// Removes the key from the *currently allowed* set and records a
2324    /// `Revoke` entry. Past rows signed by `pubkey` remain readable
2325    /// and re-verifiable — only future inserts are rejected.
2326    RevokeSigner { pubkey: [u8; 32] },
2327    /// Issue #580 — `ALTER COLLECTION name SET RETENTION <duration>`.
2328    /// Stores a declarative retention policy on the collection contract.
2329    /// Enforcement is lazy-on-scan: reads silently filter out rows older
2330    /// than `now - duration_ms` by the collection's timestamp column.
2331    SetRetention { duration_ms: u64 },
2332    /// Issue #580 — `ALTER COLLECTION name UNSET RETENTION`.
2333    /// Removes the policy. Previously-hidden expired rows become
2334    /// readable again — the slice never physically dropped them.
2335    UnsetRetention,
2336    /// Issue #801 — `ALTER GRAPH name ADD ANALYTICS (<output> [opts] [, ...])`.
2337    /// Idempotently enables analytics outputs on an existing graph's
2338    /// `analytics_config` without recreating the collection. Adding an
2339    /// already-enabled output is a no-op (no error, no duplicate state);
2340    /// the next read of `<graph>.<output>` materializes on demand.
2341    AddAnalytics(Vec<reddb_types::catalog::AnalyticsViewDescriptor>),
2342    /// Issue #801 — `ALTER GRAPH name DROP ANALYTICS <output>`.
2343    /// Removes the output from `analytics_config`; the next read of
2344    /// `<graph>.<output>` no longer resolves. Dropping an output that is
2345    /// not currently enabled is a clean error (handled in the executor).
2346    DropAnalytics(reddb_types::catalog::AnalyticsOutput),
2347}
2348
2349// ============================================================================
2350// Shared Types
2351// ============================================================================
2352
2353/// Column/field projection
2354#[derive(Debug, Clone, PartialEq)]
2355pub enum Projection {
2356    /// Select all columns (*)
2357    All,
2358    /// Single column by name
2359    Column(String),
2360    /// Column with alias
2361    Alias(String, String),
2362    /// Function call (name, args)
2363    Function(String, Vec<Projection>),
2364    /// Expression with optional alias
2365    Expression(Box<Filter>, Option<String>),
2366    /// Field reference (for graph properties)
2367    Field(FieldRef, Option<String>),
2368    /// Window function call: `fn(args) OVER (PARTITION BY ... ORDER BY ...
2369    /// [frame])`. Carries the window specification as a sibling so the
2370    /// planner can lower it without re-parsing. No runtime in slice 7a —
2371    /// the analytics executor lands in a subsequent slice (issue #589
2372    /// follow-ups). See `super::WindowSpec`.
2373    Window {
2374        name: String,
2375        args: Vec<Projection>,
2376        window: Box<super::WindowSpec>,
2377        alias: Option<String>,
2378    },
2379}
2380
2381impl Projection {
2382    /// Create a projection from a field reference
2383    pub fn from_field(field: FieldRef) -> Self {
2384        Projection::Field(field, None)
2385    }
2386
2387    /// Create a column projection
2388    pub fn column(name: &str) -> Self {
2389        Projection::Column(name.to_string())
2390    }
2391
2392    /// Create an aliased projection
2393    pub fn with_alias(column: &str, alias: &str) -> Self {
2394        Projection::Alias(column.to_string(), alias.to_string())
2395    }
2396}
2397
2398/// Filter condition
2399#[derive(Debug, Clone, PartialEq)]
2400pub enum Filter {
2401    /// Comparison: field op value
2402    Compare {
2403        field: FieldRef,
2404        op: CompareOp,
2405        value: Value,
2406    },
2407    /// Field-to-field comparison: left.field op right.field. Used when
2408    /// WHERE / BETWEEN operands reference another column instead of a
2409    /// literal — the pre-Fase-2-parser-v2 shim for column-to-column
2410    /// predicates. Once the Expr-rewrite lands, this collapses into
2411    /// `Compare { left: Expr, op, right: Expr }`.
2412    CompareFields {
2413        left: FieldRef,
2414        op: CompareOp,
2415        right: FieldRef,
2416    },
2417    /// Expression-to-expression comparison: `lhs op rhs` where either
2418    /// side may be an arbitrary `Expr` tree (function call, CAST,
2419    /// arithmetic, nested CASE). This is the most general compare
2420    /// variant — `Compare` and `CompareFields` stay as fast-path
2421    /// specialisations because the planner / cost model / index
2422    /// selector all pattern-match on the simpler shapes. The parser
2423    /// only emits this variant when a simpler one cannot express the
2424    /// predicate.
2425    CompareExpr {
2426        lhs: super::Expr,
2427        op: CompareOp,
2428        rhs: super::Expr,
2429    },
2430    /// Logical AND
2431    And(Box<Filter>, Box<Filter>),
2432    /// Logical OR
2433    Or(Box<Filter>, Box<Filter>),
2434    /// Logical NOT
2435    Not(Box<Filter>),
2436    /// IS NULL
2437    IsNull(FieldRef),
2438    /// IS NOT NULL
2439    IsNotNull(FieldRef),
2440    /// IN (value1, value2, ...)
2441    In { field: FieldRef, values: Vec<Value> },
2442    /// BETWEEN low AND high
2443    Between {
2444        field: FieldRef,
2445        low: Value,
2446        high: Value,
2447    },
2448    /// LIKE pattern
2449    Like { field: FieldRef, pattern: String },
2450    /// STARTS WITH prefix
2451    StartsWith { field: FieldRef, prefix: String },
2452    /// ENDS WITH suffix
2453    EndsWith { field: FieldRef, suffix: String },
2454    /// CONTAINS substring
2455    Contains { field: FieldRef, substring: String },
2456}
2457
2458impl Filter {
2459    /// Create a comparison filter
2460    pub fn compare(field: FieldRef, op: CompareOp, value: Value) -> Self {
2461        Self::Compare { field, op, value }
2462    }
2463
2464    /// Combine with AND
2465    pub fn and(self, other: Filter) -> Self {
2466        Self::And(Box::new(self), Box::new(other))
2467    }
2468
2469    /// Combine with OR
2470    pub fn or(self, other: Filter) -> Self {
2471        Self::Or(Box::new(self), Box::new(other))
2472    }
2473
2474    /// Negate
2475    // Filter combinator wrapping `self` in `Filter::Not`; unrelated to
2476    // `std::ops::Not`, so that trait is intentionally not implemented.
2477    #[allow(clippy::should_implement_trait)]
2478    pub fn not(self) -> Self {
2479        Self::Not(Box::new(self))
2480    }
2481
2482    /// Bottom-up AST rewrites: OR-of-equalities → IN, AND/OR flatten.
2483    /// Inspired by MongoDB's `MatchExpression::optimize()`.
2484    /// Call on the result of `effective_table_filter()` before evaluation.
2485    pub fn optimize(self) -> Self {
2486        crate::filter_optimizer::optimize(self)
2487    }
2488}
2489
2490/// Comparison operator
2491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2492pub enum CompareOp {
2493    /// Equal (=)
2494    Eq,
2495    /// Not equal (<> or !=)
2496    Ne,
2497    /// Less than (<)
2498    Lt,
2499    /// Less than or equal (<=)
2500    Le,
2501    /// Greater than (>)
2502    Gt,
2503    /// Greater than or equal (>=)
2504    Ge,
2505}
2506
2507impl fmt::Display for CompareOp {
2508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2509        match self {
2510            CompareOp::Eq => write!(f, "="),
2511            CompareOp::Ne => write!(f, "<>"),
2512            CompareOp::Lt => write!(f, "<"),
2513            CompareOp::Le => write!(f, "<="),
2514            CompareOp::Gt => write!(f, ">"),
2515            CompareOp::Ge => write!(f, ">="),
2516        }
2517    }
2518}
2519
2520/// Order by clause.
2521///
2522/// Fase 2 migration: `field` is the legacy bare column reference and
2523/// remains populated for back-compat with existing callers (SPARQL /
2524/// Gremlin / Cypher translators, the planner cost model, etc.). The
2525/// new `expr` slot carries an arbitrary `Expr` tree — when present,
2526/// runtime comparators prefer it over `field`, so the parser can
2527/// emit `ORDER BY CAST(a AS INT)`, `ORDER BY a + b * 2`, etc. without
2528/// breaking the rest of the codebase.
2529///
2530/// When `expr` is `None`, the clause behaves exactly like before.
2531/// When `expr` is `Some(Expr::Column(f))`, runtime code may still use
2532/// the legacy path — it's equivalent. Constructors default `expr` to
2533/// `None` so all existing call sites stay source-compatible.
2534#[derive(Debug, Clone)]
2535pub struct OrderByClause {
2536    /// Field to order by. Left populated even when `expr` is set so
2537    /// legacy consumers (planner cardinality estimate, cost model,
2538    /// mode translators) that still pattern-match on `field` keep
2539    /// working during the Fase 2 migration.
2540    pub field: FieldRef,
2541    /// Fase 2 expression-aware sort key. When `Some`, runtime order
2542    /// comparators evaluate this expression per row and sort on the
2543    /// resulting values — unlocks `ORDER BY expr` (Fase 1.6).
2544    pub expr: Option<super::Expr>,
2545    /// Ascending or descending
2546    pub ascending: bool,
2547    /// Nulls first or last
2548    pub nulls_first: bool,
2549}
2550
2551impl OrderByClause {
2552    /// Create ascending order
2553    pub fn asc(field: FieldRef) -> Self {
2554        Self {
2555            field,
2556            expr: None,
2557            ascending: true,
2558            nulls_first: false,
2559        }
2560    }
2561
2562    /// Create descending order
2563    pub fn desc(field: FieldRef) -> Self {
2564        Self {
2565            field,
2566            expr: None,
2567            ascending: false,
2568            nulls_first: true,
2569        }
2570    }
2571
2572    /// Attach an `Expr` sort key to an existing clause. Leaves `field`
2573    /// untouched so back-compat match sites keep their pattern.
2574    pub fn with_expr(mut self, expr: super::Expr) -> Self {
2575        self.expr = Some(expr);
2576        self
2577    }
2578}
2579
2580// ============================================================================
2581// Window OVER clause (issue #589 slice 7a)
2582// ============================================================================
2583//
2584// Syntactic representation of `OVER (PARTITION BY ... ORDER BY ... [frame])`.
2585// Slice 7a: AST + parser only. No runtime / executor wiring.
2586
2587/// Frame unit: `ROWS` (physical row offset) or `RANGE` (logical value
2588/// offset). Slice 7a stores the choice but does not yet differentiate
2589/// at runtime — semantics arrive with the analytics executor.
2590#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2591pub enum WindowFrameUnit {
2592    Rows,
2593    Range,
2594}
2595
2596/// One endpoint of a frame: UNBOUNDED PRECEDING / CURRENT ROW /
2597/// PRECEDING(expr) / FOLLOWING(expr) / UNBOUNDED FOLLOWING.
2598#[derive(Debug, Clone, PartialEq)]
2599pub enum WindowFrameBound {
2600    UnboundedPreceding,
2601    UnboundedFollowing,
2602    CurrentRow,
2603    Preceding(Box<super::Expr>),
2604    Following(Box<super::Expr>),
2605}
2606
2607/// `ROWS|RANGE BETWEEN start AND end` — or the single-bound shorthand
2608/// `ROWS start` (end implied as CURRENT ROW per SQL standard). Slice 7a
2609/// represents both shapes uniformly with `end: Option<...>` so downstream
2610/// code can normalise.
2611#[derive(Debug, Clone, PartialEq)]
2612pub struct WindowFrame {
2613    pub unit: WindowFrameUnit,
2614    pub start: WindowFrameBound,
2615    pub end: Option<WindowFrameBound>,
2616}
2617
2618/// One ORDER BY item inside a window spec. Window order keys are
2619/// expression-based by SQL standard, so we carry an `Expr` directly
2620/// rather than reusing the top-level `OrderByClause` (which still has
2621/// a legacy `FieldRef` slot for the Fase 2 migration).
2622#[derive(Debug, Clone, PartialEq)]
2623pub struct WindowOrderItem {
2624    pub expr: super::Expr,
2625    pub ascending: bool,
2626    pub nulls_first: bool,
2627}
2628
2629/// Full window specification — the AST node behind `OVER (...)`.
2630/// `frame` is `None` when the user did not specify a frame clause; the
2631/// analytics executor will materialise the SQL default (RANGE UNBOUNDED
2632/// PRECEDING AND CURRENT ROW when ORDER BY is present, the full
2633/// partition otherwise) once it lands.
2634#[derive(Debug, Clone, PartialEq, Default)]
2635pub struct WindowSpec {
2636    pub partition_by: Vec<super::Expr>,
2637    pub order_by: Vec<WindowOrderItem>,
2638    pub frame: Option<WindowFrame>,
2639}
2640
2641// ============================================================================
2642// Graph Commands
2643// ============================================================================
2644
2645/// Graph analytics command issued via SQL-like syntax
2646#[derive(Debug, Clone)]
2647pub struct GraphCommandOrderBy {
2648    pub metric: String,
2649    pub ascending: bool,
2650}
2651
2652#[derive(Debug, Clone)]
2653pub enum GraphCommand {
2654    /// GRAPH NEIGHBORHOOD 'source' [DEPTH n] [DIRECTION dir] [EDGES IN ('label', ...)]
2655    Neighborhood {
2656        source: String,
2657        depth: u32,
2658        direction: String,
2659        edge_labels: Option<Vec<String>>,
2660    },
2661    /// GRAPH SHORTEST_PATH 'source' TO 'target' [ALGORITHM alg] [DIRECTION dir] [ORDER BY metric [ASC|DESC]] [LIMIT n]
2662    ShortestPath {
2663        source: String,
2664        target: String,
2665        algorithm: String,
2666        direction: String,
2667        limit: Option<u32>,
2668        order_by: Option<GraphCommandOrderBy>,
2669    },
2670    /// GRAPH TRAVERSE 'source' [STRATEGY bfs|dfs] [DEPTH n] [DIRECTION dir] [EDGES IN ('label', ...)]
2671    Traverse {
2672        source: String,
2673        strategy: String,
2674        depth: u32,
2675        direction: String,
2676        edge_labels: Option<Vec<String>>,
2677    },
2678    /// GRAPH CENTRALITY [ALGORITHM alg] [ORDER BY metric [ASC|DESC]] [LIMIT n]
2679    ///
2680    /// `limit = None` keeps the historical implicit top-100 cap. `Some(n)`
2681    /// caps the returned rows at `n`.
2682    Centrality {
2683        algorithm: String,
2684        limit: Option<u32>,
2685        order_by: Option<GraphCommandOrderBy>,
2686    },
2687    /// GRAPH COMMUNITY [ALGORITHM alg] [MAX_ITERATIONS n] [ORDER BY metric [ASC|DESC]] [LIMIT n] [RETURN ASSIGNMENTS]
2688    ///
2689    /// `return_assignments = false` (default) keeps the historical per-community
2690    /// aggregate shape (`community_id`, `size`). `true` emits one row per node
2691    /// (`node_id`, `community_id`) — the node→community map (#660).
2692    Community {
2693        algorithm: String,
2694        max_iterations: u32,
2695        limit: Option<u32>,
2696        order_by: Option<GraphCommandOrderBy>,
2697        return_assignments: bool,
2698    },
2699    /// GRAPH COMPONENTS [MODE connected|weak|strong] [ORDER BY metric [ASC|DESC]] [LIMIT n]
2700    Components {
2701        mode: String,
2702        limit: Option<u32>,
2703        order_by: Option<GraphCommandOrderBy>,
2704    },
2705    /// GRAPH CYCLES [MAX_LENGTH n]
2706    Cycles { max_length: u32 },
2707    /// GRAPH CLUSTERING
2708    Clustering,
2709    /// GRAPH TOPOLOGICAL_SORT
2710    TopologicalSort,
2711    /// GRAPH PROPERTIES ['<id-or-label>']
2712    ///
2713    /// `source = None` returns graph-wide stats. `source = Some("...")` returns
2714    /// the full property bag of a specific node, resolved via the same label
2715    /// index as `GRAPH NEIGHBORHOOD` / `GRAPH TRAVERSE` (issue #416).
2716    Properties { source: Option<String> },
2717}
2718
2719// ============================================================================
2720// Search Commands
2721// ============================================================================
2722
2723/// Search command issued via SQL-like syntax
2724#[derive(Debug, Clone)]
2725pub enum SearchCommand {
2726    /// SEARCH SIMILAR [v1, v2, ...] | $N | TEXT 'query' [COLLECTION col] [LIMIT n] [MIN_SCORE f] [USING provider]
2727    Similar {
2728        vector: Vec<f32>,
2729        text: Option<String>,
2730        provider: Option<String>,
2731        collection: String,
2732        limit: usize,
2733        min_score: f32,
2734        /// `$N` placeholder for the vector slot. `Some(idx)` when the SQL
2735        /// used `SEARCH SIMILAR $N ...`; the binder substitutes the
2736        /// user-supplied `Value::Vector` and clears this back to `None`.
2737        /// Runtime executors assert this is `None` post-bind.
2738        vector_param: Option<usize>,
2739        /// `$N` placeholder for the `LIMIT` slot (issue #361). The binder
2740        /// substitutes the user-supplied positive integer into `limit`
2741        /// and clears this back to `None`.
2742        limit_param: Option<usize>,
2743        /// `$N` placeholder for the `MIN_SCORE` slot (issue #361). The
2744        /// binder substitutes the user-supplied float into `min_score`
2745        /// and clears this back to `None`.
2746        min_score_param: Option<usize>,
2747        /// `$N` placeholder for `SEARCH SIMILAR TEXT $N` (issue #361).
2748        /// Binder substitutes the user-supplied text into `text` and
2749        /// clears this back to `None`.
2750        text_param: Option<usize>,
2751    },
2752    /// SEARCH TEXT 'query' [COLLECTION col] [LIMIT n] [FUZZY]
2753    Text {
2754        query: String,
2755        collection: Option<String>,
2756        limit: usize,
2757        fuzzy: bool,
2758        /// `$N` placeholder for the `LIMIT` slot (issue #361). Same
2759        /// shape as `SearchCommand::Hybrid::limit_param`; the binder
2760        /// substitutes the user-supplied positive integer into `limit`
2761        /// and clears this back to `None`.
2762        limit_param: Option<usize>,
2763    },
2764    /// SEARCH HYBRID [vector] [TEXT 'query'] COLLECTION col [LIMIT n]
2765    Hybrid {
2766        vector: Option<Vec<f32>>,
2767        query: Option<String>,
2768        collection: String,
2769        limit: usize,
2770        /// `$N` placeholder for the `LIMIT` / `K` slot (issue #361).
2771        /// Same shape as `SearchCommand::Similar::limit_param`; the
2772        /// binder substitutes the user-supplied positive integer and
2773        /// clears this back to `None`.
2774        limit_param: Option<usize>,
2775    },
2776    /// SEARCH MULTIMODAL 'key_or_query' [COLLECTION col] [LIMIT n]
2777    Multimodal {
2778        query: String,
2779        collection: Option<String>,
2780        limit: usize,
2781        /// `$N` placeholder for the `LIMIT` slot (issue #361). Same
2782        /// shape as `SearchCommand::Hybrid::limit_param`; the binder
2783        /// substitutes the user-supplied positive integer into `limit`
2784        /// and clears this back to `None`.
2785        limit_param: Option<usize>,
2786    },
2787    /// SEARCH INDEX index VALUE 'value' [COLLECTION col] [LIMIT n] [EXACT]
2788    Index {
2789        index: String,
2790        value: String,
2791        collection: Option<String>,
2792        limit: usize,
2793        exact: bool,
2794        /// `$N` placeholder for the `LIMIT` slot (issue #361). Same
2795        /// shape as `SearchCommand::Hybrid::limit_param`; the binder
2796        /// substitutes the user-supplied positive integer into `limit`
2797        /// and clears this back to `None`.
2798        limit_param: Option<usize>,
2799    },
2800    /// SEARCH CONTEXT 'query' [FIELD field] [COLLECTION col] [LIMIT n] [DEPTH n]
2801    Context {
2802        query: String,
2803        field: Option<String>,
2804        collection: Option<String>,
2805        limit: usize,
2806        depth: usize,
2807        /// `$N` placeholder for the `LIMIT` slot (issue #361). Same
2808        /// shape as `SearchCommand::Hybrid::limit_param`; the binder
2809        /// substitutes the user-supplied positive integer into `limit`
2810        /// and clears this back to `None`.
2811        limit_param: Option<usize>,
2812    },
2813    /// SEARCH SPATIAL RADIUS lat lon radius_km COLLECTION col COLUMN col [LIMIT n]
2814    SpatialRadius {
2815        center_lat: f64,
2816        center_lon: f64,
2817        radius_km: f64,
2818        collection: String,
2819        column: String,
2820        limit: usize,
2821        /// `$N` placeholder for the `LIMIT` slot (issue #361). Same
2822        /// shape as `SearchCommand::Hybrid::limit_param`; the binder
2823        /// substitutes the user-supplied positive integer into `limit`
2824        /// and clears this back to `None`.
2825        limit_param: Option<usize>,
2826    },
2827    /// SEARCH SPATIAL BBOX min_lat min_lon max_lat max_lon COLLECTION col COLUMN col [LIMIT n]
2828    SpatialBbox {
2829        min_lat: f64,
2830        min_lon: f64,
2831        max_lat: f64,
2832        max_lon: f64,
2833        collection: String,
2834        column: String,
2835        limit: usize,
2836        /// `$N` placeholder for the `LIMIT` slot (issue #361). Same
2837        /// shape as `SearchCommand::Hybrid::limit_param`; the binder
2838        /// substitutes the user-supplied positive integer into `limit`
2839        /// and clears this back to `None`.
2840        limit_param: Option<usize>,
2841    },
2842    /// SEARCH SPATIAL NEAREST lat lon K n COLLECTION col COLUMN col
2843    SpatialNearest {
2844        lat: f64,
2845        lon: f64,
2846        k: usize,
2847        collection: String,
2848        column: String,
2849        /// `$N` placeholder for the `K` slot (issue #361). Same shape
2850        /// as `SearchCommand::Hybrid::limit_param`; the binder
2851        /// substitutes the user-supplied positive integer into `k`
2852        /// and clears this back to `None`.
2853        k_param: Option<usize>,
2854    },
2855}
2856
2857// ============================================================================
2858// Time-Series DDL
2859// ============================================================================
2860
2861/// CREATE TIMESERIES name [RETENTION duration] [CHUNK_SIZE n] [DOWNSAMPLE spec[, spec...]]
2862///
2863/// `CREATE HYPERTABLE` lands on the same AST with `hypertable` populated.
2864/// The TimescaleDB-style syntax (time column + chunk_interval) gives the
2865/// runtime enough to register a `HypertableSpec` alongside the
2866/// underlying collection contract, so chunk routing and TTL sweeps can
2867/// address the table without a separate DDL.
2868#[derive(Debug, Clone)]
2869pub struct CreateTimeSeriesQuery {
2870    pub name: String,
2871    pub retention_ms: Option<u64>,
2872    pub chunk_size: Option<usize>,
2873    pub downsample_policies: Vec<String>,
2874    pub if_not_exists: bool,
2875    /// When `Some`, the DDL was spelled `CREATE HYPERTABLE` and the
2876    /// runtime must register the spec with the hypertable registry.
2877    pub hypertable: Option<HypertableDdl>,
2878    /// `WITH SESSION_KEY <col>` — default partition column for the
2879    /// `SESSIONIZE` operator. Persisted on the collection contract so
2880    /// queries that omit `BY <col>` pick it up. Issue #576 slice 1.
2881    pub session_key: Option<String>,
2882    /// `SESSION_GAP <duration>` — default inactivity gap (ms) for the
2883    /// `SESSIONIZE` operator. Issue #576 slice 1.
2884    pub session_gap_ms: Option<u64>,
2885    /// `COLUMNAR` — activate columnar analytical storage (PRD #850,
2886    /// #911). When true the collection contract is built with
2887    /// `analytical_storage.columnar = true`, so sealing a chunk routes
2888    /// through `seal_chunk_with_config`'s columnar arm and emits an
2889    /// RDCC `ColumnBlock` instead of the row seal.
2890    pub columnar: bool,
2891}
2892
2893/// Hypertable-specific DDL fields — set only when the caller used
2894/// `CREATE HYPERTABLE`.
2895#[derive(Debug, Clone)]
2896pub struct HypertableDdl {
2897    /// Column that carries the nanosecond timestamp axis.
2898    pub time_column: String,
2899    /// Chunk width in nanoseconds.
2900    pub chunk_interval_ns: u64,
2901    /// Per-chunk default TTL in nanoseconds (`None` = no TTL).
2902    pub default_ttl_ns: Option<u64>,
2903}
2904
2905/// DROP TIMESERIES [IF EXISTS] name
2906#[derive(Debug, Clone)]
2907pub struct DropTimeSeriesQuery {
2908    pub name: String,
2909    pub if_exists: bool,
2910}
2911
2912// ============================================================================
2913// Queue DDL & Commands
2914// ============================================================================
2915
2916/// Default `MAX_ATTEMPTS` for `CREATE QUEUE` when omitted.
2917pub const DEFAULT_QUEUE_MAX_ATTEMPTS: u32 = 3;
2918/// Default `LOCK_DEADLINE_MS` for `CREATE QUEUE` when omitted.
2919pub const DEFAULT_QUEUE_LOCK_DEADLINE_MS: u64 = 30_000;
2920/// Default `IN_FLIGHT_CAP_PER_GROUP` for `CREATE QUEUE` when omitted.
2921pub const DEFAULT_QUEUE_IN_FLIGHT_CAP_PER_GROUP: u32 = 10_000;
2922
2923/// CREATE QUEUE name [MAX_SIZE n] [PRIORITY] [WITH TTL duration] [WITH DLQ name]
2924/// [MAX_ATTEMPTS n] [LOCK_DEADLINE_MS n] [IN_FLIGHT_CAP_PER_GROUP n]
2925/// [RETRY_DELAY duration]
2926#[derive(Debug, Clone)]
2927pub struct CreateQueueQuery {
2928    pub name: String,
2929    pub mode: QueueMode,
2930    pub priority: bool,
2931    pub max_size: Option<usize>,
2932    pub ttl_ms: Option<u64>,
2933    pub dlq: Option<String>,
2934    pub max_attempts: u32,
2935    pub lock_deadline_ms: u64,
2936    pub in_flight_cap_per_group: u32,
2937    pub if_not_exists: bool,
2938    /// Default retry delay applied to NACK-requeued messages before they
2939    /// become re-deliverable. `None` means no delay — the released
2940    /// message is immediately available again (pre-#723 behaviour).
2941    /// `Some(ms)` reuses the per-message availability machinery from
2942    /// issue #722 to defer the next delivery attempt. An authorized
2943    /// `NACK ... WITH DELAY <duration>` overrides this per-failure.
2944    pub retry_delay_ms: Option<u64>,
2945}
2946
2947/// ALTER QUEUE name SET <clause>
2948///   MODE [FANOUT|WORK|STANDARD|FIFO]
2949///   MAX_ATTEMPTS n
2950///   LOCK_DEADLINE_MS n
2951///   IN_FLIGHT_CAP_PER_GROUP n
2952///   DLQ name
2953///   RETRY_DELAY duration
2954#[derive(Debug, Clone, Default)]
2955pub struct AlterQueueQuery {
2956    pub name: String,
2957    pub mode: Option<QueueMode>,
2958    pub max_attempts: Option<u32>,
2959    pub lock_deadline_ms: Option<u64>,
2960    pub in_flight_cap_per_group: Option<u32>,
2961    pub dlq: Option<String>,
2962    /// Update the queue's default retry delay (issue #723). `Some(0)`
2963    /// clears the delay back to immediate requeue.
2964    pub retry_delay_ms: Option<u64>,
2965}
2966
2967/// DROP QUEUE [IF EXISTS] name
2968#[derive(Debug, Clone)]
2969pub struct DropQueueQuery {
2970    pub name: String,
2971    pub if_exists: bool,
2972}
2973
2974/// SELECT <columns> FROM QUEUE name [WHERE filter] [LIMIT n]
2975#[derive(Debug, Clone)]
2976pub struct QueueSelectQuery {
2977    pub queue: String,
2978    pub columns: Vec<String>,
2979    pub filter: Option<Filter>,
2980    pub limit: Option<u64>,
2981}
2982
2983/// Which end of the queue
2984#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2985pub enum QueueSide {
2986    Left,
2987    Right,
2988}
2989
2990/// Per-message delayed availability for `QUEUE PUSH` (PRD #718 / #722).
2991///
2992/// `DelayMs` is relative — the runtime resolves it against the push-time
2993/// wall clock. `AtUnixMs` is absolute — the runtime promotes it to
2994/// nanoseconds unchanged. Both ultimately surface to consumers as an
2995/// `available_at_ns` metadata field that delivery paths filter on.
2996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2997pub enum QueueAvailability {
2998    /// Delay the first delivery by this many milliseconds from push time.
2999    DelayMs(u64),
3000    /// Make the message first-deliverable at this absolute unix-ms instant.
3001    AtUnixMs(u64),
3002}
3003
3004/// Queue operation commands
3005// The largest variant carries an inline `Filter`; boxing it would ripple
3006// to every construction and match site for a marginal stack-size win, so
3007// the size difference is accepted.
3008#[allow(clippy::large_enum_variant)]
3009#[derive(Debug, Clone)]
3010pub enum QueueCommand {
3011    Push {
3012        queue: String,
3013        value: Value,
3014        side: QueueSide,
3015        priority: Option<i32>,
3016        /// Per-message delayed availability (issue #722). `None` means the
3017        /// message is deliverable immediately. `Some(_)` resolves to an
3018        /// `available_at_ns` metadata field at push time; delivery paths
3019        /// (`QUEUE READ`, `QUEUE POP`, `QUEUE READ … WAIT`) refuse to
3020        /// deliver the message until that instant.
3021        available: Option<QueueAvailability>,
3022    },
3023    Pop {
3024        queue: String,
3025        side: QueueSide,
3026        count: usize,
3027    },
3028    Peek {
3029        queue: String,
3030        count: usize,
3031    },
3032    Len {
3033        queue: String,
3034    },
3035    Purge {
3036        queue: String,
3037    },
3038    GroupCreate {
3039        queue: String,
3040        group: String,
3041    },
3042    GroupRead {
3043        queue: String,
3044        group: Option<String>,
3045        consumer: String,
3046        count: usize,
3047        /// Optional blocking-read deadline in milliseconds (PRD #718 slice
3048        /// A: `QUEUE READ … WAIT <duration>`). `None` means classic
3049        /// non-blocking semantics. The runtime currently honors the field
3050        /// synchronously — the actual wait registry lands in slice C.
3051        wait_ms: Option<u64>,
3052    },
3053    Pending {
3054        queue: String,
3055        group: String,
3056    },
3057    Claim {
3058        queue: String,
3059        group: String,
3060        consumer: String,
3061        min_idle_ms: u64,
3062    },
3063    Ack {
3064        queue: String,
3065        // Legacy tuple handle. Empty `group` / `message_id` strings mean
3066        // the request relies solely on `delivery_id`. ADR 0026: when both
3067        // `delivery_id` and the tuple are supplied, `delivery_id` wins.
3068        group: String,
3069        message_id: String,
3070        /// Server-issued opaque base32 delivery handle (ADR 0026). When
3071        /// present, takes precedence over the legacy tuple; the tuple is
3072        /// kept for one minor release as a wire-compat bridge.
3073        delivery_id: Option<String>,
3074    },
3075    Nack {
3076        queue: String,
3077        group: String,
3078        message_id: String,
3079        delivery_id: Option<String>,
3080        /// Per-failure retry delay override (issue #723). `Some(ms)`
3081        /// requests that the failed message become re-deliverable only
3082        /// after `ms` milliseconds; takes precedence over the queue's
3083        /// default `retry_delay_ms`. Authorization is enforced at the
3084        /// runtime layer: requests from a read-only identity are
3085        /// rejected.
3086        delay_ms: Option<u64>,
3087    },
3088    Move {
3089        source: String,
3090        destination: String,
3091        filter: Option<Filter>,
3092        limit: usize,
3093    },
3094}
3095
3096// ============================================================================
3097// Tree DDL & Commands
3098// ============================================================================
3099
3100#[derive(Debug, Clone)]
3101pub struct TreeNodeSpec {
3102    pub label: String,
3103    pub node_type: Option<String>,
3104    pub properties: Vec<(String, Value)>,
3105    pub metadata: Vec<(String, Value)>,
3106    pub max_children: Option<usize>,
3107}
3108
3109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3110pub enum TreePosition {
3111    First,
3112    Last,
3113    Index(usize),
3114}
3115
3116#[derive(Debug, Clone)]
3117pub struct CreateTreeQuery {
3118    pub collection: String,
3119    pub name: String,
3120    pub root: TreeNodeSpec,
3121    pub default_max_children: usize,
3122    pub if_not_exists: bool,
3123}
3124
3125#[derive(Debug, Clone)]
3126pub struct DropTreeQuery {
3127    pub collection: String,
3128    pub name: String,
3129    pub if_exists: bool,
3130}
3131
3132#[derive(Debug, Clone)]
3133pub enum TreeCommand {
3134    Insert {
3135        collection: String,
3136        tree_name: String,
3137        parent_id: u64,
3138        node: TreeNodeSpec,
3139        position: TreePosition,
3140    },
3141    Move {
3142        collection: String,
3143        tree_name: String,
3144        node_id: u64,
3145        parent_id: u64,
3146        position: TreePosition,
3147    },
3148    Delete {
3149        collection: String,
3150        tree_name: String,
3151        node_id: u64,
3152    },
3153    Validate {
3154        collection: String,
3155        tree_name: String,
3156    },
3157    Rebalance {
3158        collection: String,
3159        tree_name: String,
3160        dry_run: bool,
3161    },
3162}
3163
3164// ============================================================================
3165// KV DSL Commands
3166// ============================================================================
3167
3168/// KV verb commands: `KV PUT key = value [EXPIRE n] [IF NOT EXISTS]`, `KV GET key`, `KV DELETE key`
3169#[derive(Debug, Clone)]
3170pub enum KvCommand {
3171    Put {
3172        model: CollectionModel,
3173        collection: String,
3174        key: String,
3175        value: Value,
3176        /// TTL in milliseconds (from EXPIRE clause)
3177        ttl_ms: Option<u64>,
3178        tags: Vec<String>,
3179        if_not_exists: bool,
3180    },
3181    InvalidateTags {
3182        collection: String,
3183        tags: Vec<String>,
3184    },
3185    Get {
3186        model: CollectionModel,
3187        collection: String,
3188        key: String,
3189    },
3190    Unseal {
3191        collection: String,
3192        key: String,
3193        version: Option<i64>,
3194    },
3195    Rotate {
3196        collection: String,
3197        key: String,
3198        value: Value,
3199        tags: Vec<String>,
3200    },
3201    History {
3202        collection: String,
3203        key: String,
3204    },
3205    List {
3206        model: CollectionModel,
3207        collection: String,
3208        prefix: Option<String>,
3209        limit: Option<usize>,
3210        offset: usize,
3211        as_json: bool,
3212    },
3213    Purge {
3214        collection: String,
3215        key: String,
3216    },
3217    Watch {
3218        model: CollectionModel,
3219        collection: String,
3220        key: String,
3221        prefix: bool,
3222        from_lsn: Option<u64>,
3223    },
3224    Delete {
3225        model: CollectionModel,
3226        collection: String,
3227        key: String,
3228    },
3229    /// `KV INCR key [BY n] [EXPIRE dur]` — atomic increment; negative `by` = decrement.
3230    Incr {
3231        model: CollectionModel,
3232        collection: String,
3233        key: String,
3234        /// Step value; negative for DECR. Defaults to 1.
3235        by: i64,
3236        ttl_ms: Option<u64>,
3237    },
3238    /// `KV CAS key EXPECT <expected|NULL> SET <new> [EXPIRE dur]` — compare-and-set.
3239    ///
3240    /// `expected = None` means `EXPECT NULL` (key must be absent).
3241    Cas {
3242        model: CollectionModel,
3243        collection: String,
3244        key: String,
3245        /// The value the caller expects to be current; `None` = key must be absent.
3246        expected: Option<Value>,
3247        new_value: Value,
3248        ttl_ms: Option<u64>,
3249    },
3250}
3251
3252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3253pub enum ConfigValueType {
3254    Bool,
3255    Int,
3256    String,
3257    Url,
3258    Object,
3259    Array,
3260}
3261
3262impl ConfigValueType {
3263    pub fn as_str(self) -> &'static str {
3264        match self {
3265            Self::Bool => "bool",
3266            Self::Int => "int",
3267            Self::String => "string",
3268            Self::Url => "url",
3269            Self::Object => "object",
3270            Self::Array => "array",
3271        }
3272    }
3273
3274    pub fn parse(input: &str) -> Option<Self> {
3275        match input.to_ascii_lowercase().as_str() {
3276            "bool" | "boolean" => Some(Self::Bool),
3277            "int" | "integer" => Some(Self::Int),
3278            "string" | "str" | "text" => Some(Self::String),
3279            "url" => Some(Self::Url),
3280            "object" | "json_object" => Some(Self::Object),
3281            "array" | "list" => Some(Self::Array),
3282            _ => None,
3283        }
3284    }
3285}
3286
3287#[derive(Debug, Clone)]
3288pub enum ConfigCommand {
3289    Put {
3290        collection: String,
3291        key: String,
3292        value: Value,
3293        value_type: Option<ConfigValueType>,
3294        tags: Vec<String>,
3295    },
3296    Get {
3297        collection: String,
3298        key: String,
3299    },
3300    Resolve {
3301        collection: String,
3302        key: String,
3303    },
3304    Rotate {
3305        collection: String,
3306        key: String,
3307        value: Value,
3308        value_type: Option<ConfigValueType>,
3309        tags: Vec<String>,
3310    },
3311    Delete {
3312        collection: String,
3313        key: String,
3314    },
3315    History {
3316        collection: String,
3317        key: String,
3318    },
3319    List {
3320        collection: String,
3321        prefix: Option<String>,
3322        limit: Option<usize>,
3323        offset: usize,
3324    },
3325    Watch {
3326        collection: String,
3327        key: String,
3328        prefix: bool,
3329        from_lsn: Option<u64>,
3330    },
3331    InvalidVolatileOperation {
3332        operation: String,
3333        collection: String,
3334        key: Option<String>,
3335    },
3336}
3337
3338#[cfg(test)]
3339mod tests {
3340    use super::*;
3341    use crate::ast::{Expr, Span};
3342
3343    fn table_expr(name: &str) -> QueryExpr {
3344        QueryExpr::Table(TableQuery::new(name))
3345    }
3346
3347    #[test]
3348    fn policy_target_kind_identifiers_cover_all_variants() {
3349        assert_eq!(PolicyTargetKind::Table.as_ident(), "table");
3350        assert_eq!(PolicyTargetKind::Nodes.as_ident(), "nodes");
3351        assert_eq!(PolicyTargetKind::Edges.as_ident(), "edges");
3352        assert_eq!(PolicyTargetKind::Vectors.as_ident(), "vectors");
3353        assert_eq!(PolicyTargetKind::Messages.as_ident(), "messages");
3354        assert_eq!(PolicyTargetKind::Points.as_ident(), "points");
3355        assert_eq!(PolicyTargetKind::Documents.as_ident(), "documents");
3356    }
3357
3358    #[test]
3359    fn index_method_display_names_are_sql_keywords() {
3360        assert_eq!(IndexMethod::BTree.to_string(), "BTREE");
3361        assert_eq!(IndexMethod::Hash.to_string(), "HASH");
3362        assert_eq!(IndexMethod::Bitmap.to_string(), "BITMAP");
3363        assert_eq!(IndexMethod::RTree.to_string(), "RTREE");
3364        assert_eq!(IndexMethod::Spatial.to_string(), "SPATIAL");
3365        assert_eq!(IndexMethod::H3 { resolution: 9 }.to_string(), "H3");
3366    }
3367
3368    #[test]
3369    fn table_query_defaults_and_subquery_source() {
3370        let query = TableQuery::new("hosts");
3371        assert_eq!(query.table, "hosts");
3372        assert!(query.source.is_none());
3373        assert!(query.alias.is_none());
3374        assert!(query.select_items.is_empty());
3375        assert!(!query.distinct);
3376
3377        let subquery = table_expr("inner");
3378        let wrapped = TableQuery::from_subquery(subquery, Some("h".to_string()));
3379        assert_eq!(wrapped.table, "__subq_h");
3380        assert_eq!(wrapped.alias.as_deref(), Some("h"));
3381        assert!(matches!(wrapped.source, Some(TableSource::Subquery(_))));
3382
3383        let anonymous = TableQuery::from_subquery(table_expr("inner"), None);
3384        assert_eq!(anonymous.table, "__subq_anon");
3385        assert!(anonymous.alias.is_none());
3386    }
3387
3388    #[test]
3389    fn graph_pattern_query_and_components_builders_set_fields() {
3390        let node = NodePattern::new("h").of_label("Host").with_property(
3391            "os",
3392            CompareOp::Eq,
3393            Value::text("linux"),
3394        );
3395        assert_eq!(node.alias, "h");
3396        assert_eq!(node.node_label.as_deref(), Some("Host"));
3397        assert_eq!(node.properties.len(), 1);
3398
3399        let edge = EdgePattern::new("h", "s")
3400            .alias("r")
3401            .of_label("HAS_SERVICE")
3402            .direction(EdgeDirection::Incoming)
3403            .hops(2, 4);
3404        assert_eq!(edge.alias.as_deref(), Some("r"));
3405        assert_eq!(edge.edge_label.as_deref(), Some("HAS_SERVICE"));
3406        assert_eq!(edge.direction, EdgeDirection::Incoming);
3407        assert_eq!((edge.min_hops, edge.max_hops), (2, 4));
3408
3409        let pattern = GraphPattern::new().node(node).edge(edge);
3410        assert_eq!(pattern.nodes.len(), 1);
3411        assert_eq!(pattern.edges.len(), 1);
3412
3413        let graph = GraphQuery::new(pattern).alias("g");
3414        assert_eq!(graph.alias.as_deref(), Some("g"));
3415        assert!(graph.filter.is_none());
3416        assert!(graph.return_.is_empty());
3417    }
3418
3419    #[test]
3420    fn join_condition_and_join_query_defaults() {
3421        let left = FieldRef::column("hosts", "id");
3422        let right = FieldRef::node_id("h");
3423        let condition = JoinCondition::new(left.clone(), right.clone());
3424        assert_eq!(condition.left_field, left);
3425        assert_eq!(condition.right_field, right);
3426
3427        let join = JoinQuery::new(
3428            table_expr("hosts"),
3429            table_expr("services"),
3430            condition.clone(),
3431        )
3432        .join_type(JoinType::LeftOuter);
3433        assert!(matches!(*join.left, QueryExpr::Table(_)));
3434        assert!(matches!(*join.right, QueryExpr::Table(_)));
3435        assert_eq!(join.join_type, JoinType::LeftOuter);
3436        assert_eq!(join.on.left_field, condition.left_field);
3437        assert!(join.return_items.is_empty());
3438    }
3439
3440    #[test]
3441    fn field_ref_projection_filter_and_order_builders() {
3442        let column = FieldRef::column("hosts", "ip");
3443        let node_prop = FieldRef::node_prop("h", "os");
3444        let edge_prop = FieldRef::edge_prop("r", "weight");
3445        assert!(matches!(column, FieldRef::TableColumn { .. }));
3446        assert!(matches!(node_prop, FieldRef::NodeProperty { .. }));
3447        assert!(matches!(edge_prop, FieldRef::EdgeProperty { .. }));
3448
3449        assert!(matches!(
3450            Projection::from_field(column.clone()),
3451            Projection::Field(_, None)
3452        ));
3453        assert!(matches!(
3454            Projection::column("ip"),
3455            Projection::Column(ref name) if name == "ip"
3456        ));
3457        assert!(matches!(
3458            Projection::with_alias("ip", "addr"),
3459            Projection::Alias(ref column, ref alias) if column == "ip" && alias == "addr"
3460        ));
3461
3462        let eq = Filter::compare(column.clone(), CompareOp::Eq, Value::text("127.0.0.1"));
3463        let gt = Filter::compare(node_prop, CompareOp::Gt, Value::Integer(7));
3464        let combined = eq.clone().and(gt.clone()).or(eq.clone().not());
3465        assert!(matches!(combined, Filter::Or(_, _)));
3466        assert!(matches!(gt.optimize(), Filter::Compare { .. }));
3467
3468        assert_eq!(CompareOp::Eq.to_string(), "=");
3469        assert_eq!(CompareOp::Ne.to_string(), "<>");
3470        assert_eq!(CompareOp::Lt.to_string(), "<");
3471        assert_eq!(CompareOp::Le.to_string(), "<=");
3472        assert_eq!(CompareOp::Gt.to_string(), ">");
3473        assert_eq!(CompareOp::Ge.to_string(), ">=");
3474
3475        let asc = OrderByClause::asc(column.clone());
3476        assert!(asc.ascending);
3477        assert!(!asc.nulls_first);
3478        assert!(asc.expr.is_none());
3479
3480        let desc = OrderByClause::desc(column).with_expr(Expr::lit(Value::Integer(1)));
3481        assert!(!desc.ascending);
3482        assert!(desc.nulls_first);
3483        assert!(desc.expr.is_some());
3484    }
3485
3486    #[test]
3487    fn path_and_node_selector_builders_set_expected_defaults() {
3488        let from = NodeSelector::by_id("a");
3489        let to = NodeSelector::by_row("hosts", 42);
3490        let path = PathQuery::new(from, to).alias("p").via_label("CONNECTS_TO");
3491        assert_eq!(path.alias.as_deref(), Some("p"));
3492        assert_eq!(path.via, vec!["CONNECTS_TO"]);
3493        assert_eq!(path.max_length, 10);
3494        assert!(path.filter.is_none());
3495
3496        assert!(matches!(NodeSelector::by_id("n1"), NodeSelector::ById(id) if id == "n1"));
3497        assert!(matches!(
3498            NodeSelector::by_label("Host"),
3499            NodeSelector::ByType { node_label, filter: None } if node_label == "Host"
3500        ));
3501        assert!(matches!(
3502            NodeSelector::by_row("hosts", 7),
3503            NodeSelector::ByRow { table, row_id } if table == "hosts" && row_id == 7
3504        ));
3505    }
3506
3507    #[test]
3508    fn vector_and_hybrid_builders_set_options() {
3509        let literal = VectorSource::literal(vec![0.1, 0.2]);
3510        assert!(matches!(literal, VectorSource::Literal(ref values) if values == &[0.1, 0.2]));
3511        assert!(matches!(VectorSource::text("ssh"), VectorSource::Text(ref text) if text == "ssh"));
3512        assert!(matches!(
3513            VectorSource::reference("embeddings", 9),
3514            VectorSource::Reference { collection, vector_id }
3515                if collection == "embeddings" && vector_id == 9
3516        ));
3517
3518        let vector = VectorQuery::new("embeddings", VectorSource::text("ssh"))
3519            .limit(3)
3520            .with_filter(MetadataFilter::eq("source", "nmap"))
3521            .with_vectors()
3522            .min_similarity(0.8)
3523            .alias("sim");
3524        assert_eq!(vector.collection, "embeddings");
3525        assert_eq!(vector.k, 3);
3526        assert!(vector.filter.is_some());
3527        assert!(vector.include_vectors);
3528        assert!(vector.include_metadata);
3529        assert_eq!(vector.threshold, Some(0.8));
3530        assert_eq!(vector.alias.as_deref(), Some("sim"));
3531
3532        let hybrid = HybridQuery::new(table_expr("hosts"), vector)
3533            .with_fusion(FusionStrategy::RRF { k: 60 })
3534            .limit(5)
3535            .alias("hy");
3536        assert!(matches!(*hybrid.structured, QueryExpr::Table(_)));
3537        assert_eq!(hybrid.limit, Some(5));
3538        assert_eq!(hybrid.alias.as_deref(), Some("hy"));
3539        assert!(matches!(hybrid.fusion, FusionStrategy::RRF { k: 60 }));
3540    }
3541
3542    #[test]
3543    fn window_spec_structs_are_constructible() {
3544        let order = WindowOrderItem {
3545            expr: Expr::lit(Value::Integer(1)),
3546            ascending: false,
3547            nulls_first: true,
3548        };
3549        let frame = WindowFrame {
3550            unit: WindowFrameUnit::Rows,
3551            start: WindowFrameBound::UnboundedPreceding,
3552            end: Some(WindowFrameBound::CurrentRow),
3553        };
3554        let spec = WindowSpec {
3555            partition_by: vec![Expr::lit(Value::text("tenant"))],
3556            order_by: vec![order],
3557            frame: Some(frame),
3558        };
3559        assert_eq!(spec.partition_by.len(), 1);
3560        assert_eq!(spec.order_by.len(), 1);
3561        assert!(matches!(
3562            spec.frame,
3563            Some(WindowFrame {
3564                unit: WindowFrameUnit::Rows,
3565                ..
3566            })
3567        ));
3568
3569        let default = WindowSpec::default();
3570        assert!(default.partition_by.is_empty());
3571        assert!(default.order_by.is_empty());
3572        assert!(default.frame.is_none());
3573
3574        let _ = Span::synthetic();
3575    }
3576
3577    #[test]
3578    fn config_value_type_aliases_and_display_names() {
3579        for (input, expected, as_str) in [
3580            ("bool", ConfigValueType::Bool, "bool"),
3581            ("boolean", ConfigValueType::Bool, "bool"),
3582            ("int", ConfigValueType::Int, "int"),
3583            ("integer", ConfigValueType::Int, "int"),
3584            ("str", ConfigValueType::String, "string"),
3585            ("text", ConfigValueType::String, "string"),
3586            ("url", ConfigValueType::Url, "url"),
3587            ("json_object", ConfigValueType::Object, "object"),
3588            ("list", ConfigValueType::Array, "array"),
3589        ] {
3590            let parsed = ConfigValueType::parse(input).expect("known type");
3591            assert_eq!(parsed, expected);
3592            assert_eq!(parsed.as_str(), as_str);
3593        }
3594        assert_eq!(ConfigValueType::parse("bogus"), None);
3595    }
3596}
3597
3598// ============================================================================
3599// Builders (Fluent API)
3600// ============================================================================