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