sochdb-query 2.0.1

SochDB query engine (sync-first execution and vector query planning)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! SQL Abstract Syntax Tree
//!
//! Represents parsed SQL statements as a tree structure.

use super::token::Span;

/// Top-level SQL statement
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum Statement {
    Select(SelectStmt),
    Insert(InsertStmt),
    Update(UpdateStmt),
    Delete(DeleteStmt),
    CreateTable(CreateTableStmt),
    DropTable(DropTableStmt),
    AlterTable(AlterTableStmt),
    CreateIndex(CreateIndexStmt),
    DropIndex(DropIndexStmt),
    Begin(BeginStmt),
    Commit,
    Rollback(Option<String>), // Optional savepoint name
    Savepoint(String),
    Release(String),
    Explain(Box<Statement>),

    // ====================================================================
    // Security DDL (P2 — Scope-Based Auth)
    // ====================================================================

    /// DEFINE SCOPE <name> SESSION <duration>
    ///   SIGNIN (<expr>)
    ///   SIGNUP (<expr>)
    DefineScope(DefineScopeStmt),

    /// DEFINE TABLE <name> PERMISSIONS
    ///   FOR select WHERE <expr>
    ///   FOR create WHERE <expr>
    ///   FOR update WHERE <expr>
    ///   FOR delete WHERE <expr>
    DefineTablePermissions(DefineTablePermissionsStmt),

    /// REMOVE SCOPE <name>
    RemoveScope(String),

    // ====================================================================
    // Graph & Real-Time (P1 — Multi-Model)
    // ====================================================================

    /// RELATE <from> -> <edge> -> <to> [SET ... | CONTENT ...]
    Relate(RelateStmt),

    /// LIVE SELECT [DIFF] <columns> FROM <table> [WHERE ...]
    LiveSelect(LiveSelectStmt),

    /// DEFINE EVENT <name> ON TABLE <table> WHEN <condition> THEN <action>
    DefineEvent(DefineEventStmt),
}

/// SELECT statement
#[derive(Debug, Clone, PartialEq)]
pub struct SelectStmt {
    pub span: Span,
    pub distinct: bool,
    pub columns: Vec<SelectItem>,
    pub from: Option<FromClause>,
    pub where_clause: Option<Expr>,
    pub group_by: Vec<Expr>,
    pub having: Option<Expr>,
    pub order_by: Vec<OrderByItem>,
    pub limit: Option<Expr>,
    pub offset: Option<Expr>,
    pub unions: Vec<(SetOp, Box<SelectStmt>)>,
}

/// Items in SELECT clause
#[derive(Debug, Clone, PartialEq)]
pub enum SelectItem {
    /// SELECT *
    Wildcard,
    /// SELECT table.*
    QualifiedWildcard(String),
    /// SELECT expr [AS alias]
    Expr { expr: Expr, alias: Option<String> },
}

/// Set operations (UNION, INTERSECT, EXCEPT)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetOp {
    Union,
    UnionAll,
    Intersect,
    IntersectAll,
    Except,
    ExceptAll,
}

/// FROM clause
#[derive(Debug, Clone, PartialEq)]
pub struct FromClause {
    pub tables: Vec<TableRef>,
}

/// Table reference in FROM clause
#[derive(Debug, Clone, PartialEq)]
pub enum TableRef {
    /// Simple table: table_name [AS alias]
    Table {
        name: ObjectName,
        alias: Option<String>,
    },
    /// Subquery: (SELECT ...) AS alias
    Subquery {
        query: Box<SelectStmt>,
        alias: String,
    },
    /// Join: left JOIN right ON condition
    Join {
        left: Box<TableRef>,
        join_type: JoinType,
        right: Box<TableRef>,
        condition: Option<JoinCondition>,
    },
    /// Table-valued function: func(...) AS alias
    Function {
        name: String,
        args: Vec<Expr>,
        alias: Option<String>,
    },
}

/// Join types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
    Inner,
    Left,
    Right,
    Full,
    Cross,
}

/// Join condition
#[derive(Debug, Clone, PartialEq)]
pub enum JoinCondition {
    On(Expr),
    Using(Vec<String>),
    Natural,
}

/// ORDER BY item
#[derive(Debug, Clone, PartialEq)]
pub struct OrderByItem {
    pub expr: Expr,
    pub asc: bool,
    pub nulls_first: Option<bool>,
}

/// INSERT statement
#[derive(Debug, Clone, PartialEq)]
pub struct InsertStmt {
    pub span: Span,
    pub table: ObjectName,
    pub columns: Option<Vec<String>>,
    pub source: InsertSource,
    pub on_conflict: Option<OnConflict>,
    pub returning: Option<Vec<SelectItem>>,
}

/// Source of INSERT data
#[derive(Debug, Clone, PartialEq)]
pub enum InsertSource {
    /// VALUES (a, b), (c, d), ...
    Values(Vec<Vec<Expr>>),
    /// SELECT ...
    Query(Box<SelectStmt>),
    /// DEFAULT VALUES
    Default,
}

/// ON CONFLICT clause
///
/// Represents conflict handling for INSERT statements across SQL dialects:
/// - PostgreSQL: `ON CONFLICT DO NOTHING/UPDATE`
/// - MySQL: `INSERT IGNORE`, `ON DUPLICATE KEY UPDATE`
/// - SQLite: `INSERT OR IGNORE/REPLACE/ABORT`
///
/// All dialects normalize to this single representation.
#[derive(Debug, Clone, PartialEq)]
pub struct OnConflict {
    pub target: Option<ConflictTarget>,
    pub action: ConflictAction,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ConflictTarget {
    Columns(Vec<String>),
    Constraint(String),
}

#[derive(Debug, Clone, PartialEq)]
pub enum ConflictAction {
    /// ON CONFLICT DO NOTHING / INSERT IGNORE / INSERT OR IGNORE
    DoNothing,
    /// ON CONFLICT DO UPDATE SET ... / ON DUPLICATE KEY UPDATE ...
    DoUpdate(Vec<Assignment>),
    /// INSERT OR REPLACE (SQLite) - replaces the entire row
    DoReplace,
    /// INSERT OR ABORT (SQLite) - abort on conflict (default behavior)
    DoAbort,
    /// INSERT OR FAIL (SQLite) - fail but continue with other rows
    DoFail,
}

/// UPDATE statement
#[derive(Debug, Clone, PartialEq)]
pub struct UpdateStmt {
    pub span: Span,
    pub table: ObjectName,
    pub alias: Option<String>,
    pub assignments: Vec<Assignment>,
    pub from: Option<FromClause>,
    pub where_clause: Option<Expr>,
    pub returning: Option<Vec<SelectItem>>,
}

/// Assignment: column = expr
#[derive(Debug, Clone, PartialEq)]
pub struct Assignment {
    pub column: String,
    pub value: Expr,
}

/// DELETE statement
#[derive(Debug, Clone, PartialEq)]
pub struct DeleteStmt {
    pub span: Span,
    pub table: ObjectName,
    pub alias: Option<String>,
    pub using: Option<FromClause>,
    pub where_clause: Option<Expr>,
    pub returning: Option<Vec<SelectItem>>,
}

/// CREATE TABLE statement
#[derive(Debug, Clone, PartialEq)]
pub struct CreateTableStmt {
    pub span: Span,
    pub if_not_exists: bool,
    pub name: ObjectName,
    pub columns: Vec<ColumnDef>,
    pub constraints: Vec<TableConstraint>,
    pub options: Vec<TableOption>,
}

/// Column definition
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnDef {
    pub name: String,
    pub data_type: DataType,
    pub constraints: Vec<ColumnConstraint>,
}

/// SQL Data types
#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
    // Numeric
    TinyInt,
    SmallInt,
    Int,
    BigInt,
    Float,
    Double,
    Decimal {
        precision: Option<u32>,
        scale: Option<u32>,
    },

    // String
    Char(Option<u32>),
    Varchar(Option<u32>),
    Text,

    // Binary
    Binary(Option<u32>),
    Varbinary(Option<u32>),
    Blob,

    // Date/Time
    Date,
    Time,
    Timestamp,
    DateTime,
    Interval,

    // Boolean
    Boolean,

    // JSON
    Json,
    Jsonb,

    // SochDB Extensions
    Vector(u32),    // VECTOR(dimensions)
    Embedding(u32), // EMBEDDING(dimensions)

    // Custom/Unknown
    Custom(String),
}

/// Column constraints
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnConstraint {
    NotNull,
    Null,
    Unique,
    PrimaryKey,
    Default(Expr),
    Check(Expr),
    References {
        table: ObjectName,
        columns: Vec<String>,
        on_delete: Option<ReferentialAction>,
        on_update: Option<ReferentialAction>,
    },
    AutoIncrement,
    Generated {
        expr: Expr,
        stored: bool,
    },
}

/// Table-level constraints
#[derive(Debug, Clone, PartialEq)]
pub enum TableConstraint {
    PrimaryKey {
        name: Option<String>,
        columns: Vec<String>,
    },
    Unique {
        name: Option<String>,
        columns: Vec<String>,
    },
    ForeignKey {
        name: Option<String>,
        columns: Vec<String>,
        ref_table: ObjectName,
        ref_columns: Vec<String>,
        on_delete: Option<ReferentialAction>,
        on_update: Option<ReferentialAction>,
    },
    Check {
        name: Option<String>,
        expr: Expr,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReferentialAction {
    NoAction,
    Restrict,
    Cascade,
    SetNull,
    SetDefault,
}

/// Table options (ENGINE, CHARSET, etc.)
#[derive(Debug, Clone, PartialEq)]
pub struct TableOption {
    pub name: String,
    pub value: String,
}

/// DROP TABLE statement
#[derive(Debug, Clone, PartialEq)]
pub struct DropTableStmt {
    pub span: Span,
    pub if_exists: bool,
    pub names: Vec<ObjectName>,
    pub cascade: bool,
}

/// ALTER TABLE statement
#[derive(Debug, Clone, PartialEq)]
pub struct AlterTableStmt {
    pub span: Span,
    pub name: ObjectName,
    pub operations: Vec<AlterTableOp>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AlterTableOp {
    AddColumn(ColumnDef),
    DropColumn {
        name: String,
        cascade: bool,
    },
    AlterColumn {
        name: String,
        operation: AlterColumnOp,
    },
    AddConstraint(TableConstraint),
    DropConstraint {
        name: String,
        cascade: bool,
    },
    RenameTable(ObjectName),
    RenameColumn {
        old_name: String,
        new_name: String,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub enum AlterColumnOp {
    SetType(DataType),
    SetNotNull,
    DropNotNull,
    SetDefault(Expr),
    DropDefault,
}

/// CREATE INDEX statement
#[derive(Debug, Clone, PartialEq)]
pub struct CreateIndexStmt {
    pub span: Span,
    pub unique: bool,
    pub if_not_exists: bool,
    pub name: String,
    pub table: ObjectName,
    pub columns: Vec<IndexColumn>,
    pub where_clause: Option<Expr>,
    pub index_type: Option<IndexType>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexColumn {
    pub name: String,
    pub asc: bool,
    pub nulls_first: Option<bool>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndexType {
    BTree,
    Hash,
    Gin,
    Gist,
    // SochDB extensions
    Hnsw,   // For vector search
    Vamana, // For vector search
}

/// DROP INDEX statement
#[derive(Debug, Clone, PartialEq)]
pub struct DropIndexStmt {
    pub span: Span,
    pub if_exists: bool,
    pub name: String,
    pub table: Option<ObjectName>,
    pub cascade: bool,
}

/// BEGIN statement
#[derive(Debug, Clone, PartialEq)]
pub struct BeginStmt {
    pub read_only: bool,
    pub isolation_level: Option<IsolationLevel>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    ReadUncommitted,
    ReadCommitted,
    RepeatableRead,
    Serializable,
    Snapshot,
}

/// Object name (potentially qualified: schema.table)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ObjectName {
    pub parts: Vec<String>,
}

impl ObjectName {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            parts: vec![name.into()],
        }
    }

    pub fn qualified(schema: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            parts: vec![schema.into(), name.into()],
        }
    }

    pub fn name(&self) -> &str {
        self.parts.last().map(|s| s.as_str()).unwrap_or("")
    }

    pub fn schema(&self) -> Option<&str> {
        if self.parts.len() > 1 {
            Some(&self.parts[self.parts.len() - 2])
        } else {
            None
        }
    }
}

impl std::fmt::Display for ObjectName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.parts.join("."))
    }
}

/// Expression
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// Literal value
    Literal(Literal),

    /// Column reference: [table.]column
    Column(ColumnRef),

    /// Binary operation: expr op expr
    BinaryOp {
        left: Box<Expr>,
        op: BinaryOperator,
        right: Box<Expr>,
    },

    /// Unary operation: op expr
    UnaryOp { op: UnaryOperator, expr: Box<Expr> },

    /// Function call: func(args)
    Function(FunctionCall),

    /// CASE expression
    Case {
        operand: Option<Box<Expr>>,
        conditions: Vec<(Expr, Expr)>, // (WHEN, THEN)
        else_result: Option<Box<Expr>>,
    },

    /// Subquery: (SELECT ...)
    Subquery(Box<SelectStmt>),

    /// EXISTS (SELECT ...)
    Exists(Box<SelectStmt>),

    /// expr IN (values)
    InList {
        expr: Box<Expr>,
        list: Vec<Expr>,
        negated: bool,
    },

    /// expr IN (SELECT ...)
    InSubquery {
        expr: Box<Expr>,
        subquery: Box<SelectStmt>,
        negated: bool,
    },

    /// expr BETWEEN low AND high
    Between {
        expr: Box<Expr>,
        low: Box<Expr>,
        high: Box<Expr>,
        negated: bool,
    },

    /// expr LIKE pattern [ESCAPE escape]
    Like {
        expr: Box<Expr>,
        pattern: Box<Expr>,
        escape: Option<Box<Expr>>,
        negated: bool,
    },

    /// expr IS [NOT] NULL
    IsNull { expr: Box<Expr>, negated: bool },

    /// CAST(expr AS type)
    Cast {
        expr: Box<Expr>,
        data_type: DataType,
    },

    /// Placeholder: $1, $2, ?
    Placeholder(u32),

    /// Array: [a, b, c] or ARRAY[a, b, c]
    Array(Vec<Expr>),

    /// Tuple/Row: (a, b, c)
    Tuple(Vec<Expr>),

    /// Array subscript: arr[index]
    Subscript { expr: Box<Expr>, index: Box<Expr> },

    // ========== SochDB Extensions ==========
    /// Vector literal: [1.0, 2.0, 3.0]::VECTOR
    Vector(Vec<f32>),

    /// Vector search: VECTOR_SEARCH(column, query_vector, k, metric)
    VectorSearch {
        column: Box<Expr>,
        query: Box<Expr>,
        k: u32,
        metric: VectorMetric,
    },

    /// JSON path: json_col -> 'path'
    JsonAccess {
        expr: Box<Expr>,
        path: Box<Expr>,
        return_text: bool, // -> vs ->>
    },

    /// Context window for LLM: CONTEXT_WINDOW(tokens, priority_expr)
    ContextWindow {
        source: Box<Expr>,
        max_tokens: u32,
        priority: Option<Box<Expr>>,
    },

    /// Record ID literal: table:id (e.g. person:1, post:abc)
    RecordId {
        table: String,
        id: Box<Expr>,
    },
}

/// Literal values
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    Null,
    Boolean(bool),
    Integer(i64),
    Float(f64),
    String(String),
    Blob(Vec<u8>),
}

/// Column reference
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnRef {
    pub table: Option<String>,
    pub column: String,
}

impl ColumnRef {
    pub fn new(column: impl Into<String>) -> Self {
        Self {
            table: None,
            column: column.into(),
        }
    }

    pub fn qualified(table: impl Into<String>, column: impl Into<String>) -> Self {
        Self {
            table: Some(table.into()),
            column: column.into(),
        }
    }
}

/// Binary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOperator {
    // Arithmetic
    Plus,
    Minus,
    Multiply,
    Divide,
    Modulo,

    // Comparison
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,

    // Logical
    And,
    Or,

    // String
    Concat,
    Like,

    // Bitwise
    BitAnd,
    BitOr,
    BitXor,
    LeftShift,
    RightShift,

    // Graph traversal
    GraphRight, // ->  (outgoing edge)
    GraphLeft,  // <-  (incoming edge)
    GraphBi,    // <-> (bidirectional edge)
}

/// Unary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOperator {
    Plus,
    Minus,
    Not,
    BitNot,
}

/// Function call
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionCall {
    pub name: ObjectName,
    pub args: Vec<Expr>,
    pub distinct: bool,
    pub filter: Option<Box<Expr>>,
    pub over: Option<WindowSpec>,
}

/// Window specification for window functions
#[derive(Debug, Clone, PartialEq)]
pub struct WindowSpec {
    pub partition_by: Vec<Expr>,
    pub order_by: Vec<OrderByItem>,
    pub frame: Option<WindowFrame>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct WindowFrame {
    pub kind: WindowFrameKind,
    pub start: WindowFrameBound,
    pub end: Option<WindowFrameBound>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowFrameKind {
    Rows,
    Range,
    Groups,
}

#[derive(Debug, Clone, PartialEq)]
pub enum WindowFrameBound {
    CurrentRow,
    Preceding(Option<Box<Expr>>), // None = UNBOUNDED
    Following(Option<Box<Expr>>), // None = UNBOUNDED
}

/// Vector distance metrics (SochDB extension)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VectorMetric {
    #[default]
    Cosine,
    Euclidean,
    DotProduct,
    Manhattan,
}

// ============================================================================
// Security DDL AST nodes (P2 — Scope-Based Auth)
// ============================================================================

/// DEFINE SCOPE statement — creates an authentication scope.
///
/// Mirrors SurrealDB's `DEFINE SCOPE`:
/// ```sql
/// DEFINE SCOPE user_scope SESSION 24h
///   SIGNIN (SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(password, $password))
///   SIGNUP (CREATE user SET email = $email, password = crypto::argon2::generate($password))
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct DefineScopeStmt {
    /// Scope name (e.g. "user_scope")
    pub name: String,
    /// Session duration in seconds (e.g. 86400 for 24h)
    pub session_duration_secs: Option<u64>,
    /// SIGNIN expression — evaluated to authenticate
    pub signin: Option<Box<Expr>>,
    /// SIGNUP expression — evaluated to register
    pub signup: Option<Box<Expr>>,
}

/// DEFINE TABLE PERMISSIONS — row-level security policies per operation.
///
/// Mirrors SurrealDB's per-table permissions:
/// ```sql
/// DEFINE TABLE post PERMISSIONS
///   FOR select WHERE published = true OR user = $auth.id
///   FOR create WHERE $auth.role = 'editor'
///   FOR update WHERE user = $auth.id
///   FOR delete WHERE $auth.role = 'admin'
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct DefineTablePermissionsStmt {
    /// Table name
    pub table: ObjectName,
    /// Permission rules per operation
    pub permissions: Vec<TablePermission>,
}

/// A single permission rule for a table operation.
#[derive(Debug, Clone, PartialEq)]
pub struct TablePermission {
    /// Operation this permission applies to
    pub operation: PermissionOp,
    /// WHERE clause — row is accessible if this evaluates to true
    pub condition: Expr,
}

/// Operations that can have per-table permissions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionOp {
    Select,
    Create,
    Update,
    Delete,
}

// ============================================================================
// Graph & Real-Time AST nodes (P1 — Multi-Model)
// ============================================================================

/// RELATE statement — creates a graph edge between two records.
///
/// ```sql
/// RELATE person:1 -> knows -> person:2 SET since = '2024-01-01';
/// RELATE person:1 -> knows -> person:2 CONTENT { "since": "2024-01-01" };
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct RelateStmt {
    pub span: Span,
    /// Source record (e.g. person:1)
    pub from: Expr,
    /// Edge table name (e.g. knows)
    pub edge: ObjectName,
    /// Target record (e.g. person:2)
    pub to: Expr,
    /// SET field = value, ...
    pub set: Vec<Assignment>,
    /// CONTENT { ... } — alternative to SET
    pub content: Option<Expr>,
    /// RETURNING clause
    pub returning: Option<Vec<SelectItem>>,
}

/// LIVE SELECT statement — subscribes to real-time changes on a table.
///
/// ```sql
/// LIVE SELECT * FROM person WHERE age > 18;
/// LIVE SELECT DIFF FROM person;
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct LiveSelectStmt {
    pub span: Span,
    /// The underlying SELECT statement
    pub select: SelectStmt,
    /// Whether to return diffs instead of full records
    pub diff: bool,
}

/// DEFINE EVENT statement — registers a trigger on table mutations.
///
/// ```sql
/// DEFINE EVENT email_notification ON TABLE user
///   WHEN $event = "CREATE"
///   THEN (CREATE notification SET body = "Welcome " + $after.name);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct DefineEventStmt {
    pub span: Span,
    /// Event name
    pub name: String,
    /// Table this event is attached to
    pub table: ObjectName,
    /// WHEN condition
    pub condition: Expr,
    /// THEN action (typically a statement wrapped in parens)
    pub action: Expr,
}