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