manifoldb-query 0.1.4

Query parsing, planning, and execution for ManifoldDB
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//! Statement AST types.
//!
//! This module defines the top-level statement types for parsed queries.

use super::expr::{Expr, Identifier, OrderByExpr, QualifiedName};
use super::pattern::GraphPattern;

/// A parsed SQL statement.
///
/// Large statement types are boxed to reduce enum size overhead.
/// This improves memory efficiency when many Statement instances
/// are created (e.g., in query planning).
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
    /// SELECT statement (boxed - 744 bytes unboxed).
    Select(Box<SelectStatement>),
    /// INSERT statement (boxed - 304 bytes unboxed).
    Insert(Box<InsertStatement>),
    /// UPDATE statement (boxed - 328 bytes unboxed).
    Update(Box<UpdateStatement>),
    /// DELETE statement (boxed - 304 bytes unboxed).
    Delete(Box<DeleteStatement>),
    /// CREATE TABLE statement.
    CreateTable(CreateTableStatement),
    /// CREATE INDEX statement (boxed - 288 bytes unboxed).
    CreateIndex(Box<CreateIndexStatement>),
    /// CREATE COLLECTION statement for vector collections.
    CreateCollection(Box<CreateCollectionStatement>),
    /// DROP TABLE statement.
    DropTable(DropTableStatement),
    /// DROP INDEX statement.
    DropIndex(DropIndexStatement),
    /// DROP COLLECTION statement.
    DropCollection(DropCollectionStatement),
    /// MATCH statement (Cypher-style graph query).
    Match(Box<MatchStatement>),
    /// EXPLAIN statement.
    Explain(Box<Statement>),
}

/// A Common Table Expression (CTE) defined in a WITH clause.
///
/// CTEs allow defining named subqueries that can be referenced multiple times
/// in the main query, similar to temporary views.
///
/// # Example
///
/// ```sql
/// WITH active_users AS (
///     SELECT * FROM users WHERE status = 'active'
/// )
/// SELECT * FROM active_users WHERE age > 21;
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct WithClause {
    /// The name of the CTE.
    pub name: Identifier,
    /// Optional column aliases for the CTE.
    pub columns: Vec<Identifier>,
    /// The subquery that defines the CTE.
    pub query: Box<SelectStatement>,
}

impl WithClause {
    /// Creates a new CTE with the given name and query.
    #[must_use]
    pub fn new(name: impl Into<Identifier>, query: SelectStatement) -> Self {
        Self { name: name.into(), columns: vec![], query: Box::new(query) }
    }

    /// Creates a new CTE with column aliases.
    #[must_use]
    pub fn with_columns(
        name: impl Into<Identifier>,
        columns: Vec<Identifier>,
        query: SelectStatement,
    ) -> Self {
        Self { name: name.into(), columns, query: Box::new(query) }
    }
}

/// A SELECT statement.
#[derive(Debug, Clone, PartialEq)]
pub struct SelectStatement {
    /// Common Table Expressions (WITH clause).
    pub with_clauses: Vec<WithClause>,
    /// Whether DISTINCT is specified.
    pub distinct: bool,
    /// The projection (SELECT list).
    pub projection: Vec<SelectItem>,
    /// The FROM clause.
    pub from: Vec<TableRef>,
    /// Optional MATCH clause for graph patterns.
    pub match_clause: Option<GraphPattern>,
    /// OPTIONAL MATCH clauses for left outer join graph patterns.
    /// Each pattern is joined with the main query using a LEFT OUTER JOIN,
    /// returning NULL for unmatched optional patterns.
    pub optional_match_clauses: Vec<GraphPattern>,
    /// Optional WHERE clause.
    pub where_clause: Option<Expr>,
    /// Optional GROUP BY clause.
    pub group_by: Vec<Expr>,
    /// Optional HAVING clause.
    pub having: Option<Expr>,
    /// Optional ORDER BY clause.
    pub order_by: Vec<OrderByExpr>,
    /// Optional LIMIT clause.
    pub limit: Option<Expr>,
    /// Optional OFFSET clause.
    pub offset: Option<Expr>,
    /// Set operations (UNION, INTERSECT, EXCEPT).
    pub set_op: Option<Box<SetOperation>>,
}

impl SelectStatement {
    /// Creates a new SELECT statement with the given projection.
    #[must_use]
    pub const fn new(projection: Vec<SelectItem>) -> Self {
        Self {
            with_clauses: vec![],
            distinct: false,
            projection,
            from: vec![],
            match_clause: None,
            optional_match_clauses: vec![],
            where_clause: None,
            group_by: vec![],
            having: None,
            order_by: vec![],
            limit: None,
            offset: None,
            set_op: None,
        }
    }

    /// Adds a WITH clause (CTE) to the statement.
    #[must_use]
    pub fn with_cte(mut self, cte: WithClause) -> Self {
        self.with_clauses.push(cte);
        self
    }

    /// Adds a FROM clause.
    #[must_use]
    pub fn from(mut self, table: TableRef) -> Self {
        self.from.push(table);
        self
    }

    /// Sets the WHERE clause.
    #[must_use]
    pub fn where_clause(mut self, condition: Expr) -> Self {
        self.where_clause = Some(condition);
        self
    }

    /// Sets the MATCH clause.
    #[must_use]
    pub fn match_clause(mut self, pattern: GraphPattern) -> Self {
        self.match_clause = Some(pattern);
        self
    }

    /// Adds an OPTIONAL MATCH clause.
    ///
    /// OPTIONAL MATCH clauses are joined using LEFT OUTER JOIN semantics,
    /// returning NULL for variables in the optional pattern when no match exists.
    #[must_use]
    pub fn optional_match_clause(mut self, pattern: GraphPattern) -> Self {
        self.optional_match_clauses.push(pattern);
        self
    }

    /// Adds ORDER BY.
    #[must_use]
    pub fn order_by(mut self, orders: Vec<OrderByExpr>) -> Self {
        self.order_by = orders;
        self
    }

    /// Sets the LIMIT.
    #[must_use]
    pub fn limit(mut self, limit: Expr) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the OFFSET.
    #[must_use]
    pub fn offset(mut self, offset: Expr) -> Self {
        self.offset = Some(offset);
        self
    }
}

/// A standalone MATCH statement (Cypher-style graph query).
///
/// This provides pure Cypher-like syntax for graph pattern matching:
///
/// ```text
/// MATCH (a:User)-[:FOLLOWS]->(b:User)
/// WHERE a.name = 'Alice'
/// RETURN b.name, b.email
/// ORDER BY b.name
/// LIMIT 10;
/// ```
///
/// Internally, this is converted to a SELECT statement during planning.
#[derive(Debug, Clone, PartialEq)]
pub struct MatchStatement {
    /// The graph pattern to match.
    pub pattern: GraphPattern,
    /// Optional WHERE clause.
    pub where_clause: Option<Expr>,
    /// The RETURN clause (required in Cypher).
    pub return_clause: Vec<ReturnItem>,
    /// Whether RETURN DISTINCT is specified.
    pub distinct: bool,
    /// Optional ORDER BY clause.
    pub order_by: Vec<OrderByExpr>,
    /// Optional SKIP clause (equivalent to OFFSET).
    pub skip: Option<Expr>,
    /// Optional LIMIT clause.
    pub limit: Option<Expr>,
}

impl MatchStatement {
    /// Creates a new MATCH statement with a pattern and return items.
    #[must_use]
    pub const fn new(pattern: GraphPattern, return_clause: Vec<ReturnItem>) -> Self {
        Self {
            pattern,
            where_clause: None,
            return_clause,
            distinct: false,
            order_by: vec![],
            skip: None,
            limit: None,
        }
    }

    /// Sets the WHERE clause.
    #[must_use]
    pub fn where_clause(mut self, condition: Expr) -> Self {
        self.where_clause = Some(condition);
        self
    }

    /// Sets DISTINCT on the RETURN clause.
    #[must_use]
    pub const fn distinct(mut self) -> Self {
        self.distinct = true;
        self
    }

    /// Sets the ORDER BY clause.
    #[must_use]
    pub fn order_by(mut self, orders: Vec<OrderByExpr>) -> Self {
        self.order_by = orders;
        self
    }

    /// Sets the SKIP clause.
    #[must_use]
    pub fn skip(mut self, skip: Expr) -> Self {
        self.skip = Some(skip);
        self
    }

    /// Sets the LIMIT clause.
    #[must_use]
    pub fn limit(mut self, limit: Expr) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Converts this MATCH statement to an equivalent SELECT statement.
    ///
    /// This is used during planning to leverage the existing SELECT infrastructure.
    #[must_use]
    pub fn to_select(&self) -> SelectStatement {
        // Convert return items to select items
        let projection: Vec<SelectItem> = self
            .return_clause
            .iter()
            .map(|item| match item {
                ReturnItem::Wildcard => SelectItem::Wildcard,
                ReturnItem::Expr { expr, alias } => {
                    SelectItem::Expr { expr: expr.clone(), alias: alias.clone() }
                }
            })
            .collect();

        SelectStatement {
            with_clauses: vec![], // MATCH statements don't have CTEs
            distinct: self.distinct,
            projection,
            from: vec![], // Graph patterns don't need a FROM clause
            match_clause: Some(self.pattern.clone()),
            optional_match_clauses: vec![], // TODO: Add support for OPTIONAL MATCH in standalone Cypher
            where_clause: self.where_clause.clone(),
            group_by: vec![],
            having: None,
            order_by: self.order_by.clone(),
            limit: self.limit.clone(),
            offset: self.skip.clone(), // Cypher SKIP = SQL OFFSET
            set_op: None,
        }
    }
}

/// An item in a RETURN clause.
#[derive(Debug, Clone, PartialEq)]
pub enum ReturnItem {
    /// A wildcard (*) - return all bound variables.
    Wildcard,
    /// An expression, optionally aliased.
    Expr {
        /// The expression to return.
        expr: Expr,
        /// Optional alias (AS name).
        alias: Option<Identifier>,
    },
}

impl ReturnItem {
    /// Creates a wildcard return item.
    #[must_use]
    pub const fn wildcard() -> Self {
        Self::Wildcard
    }

    /// Creates an unaliased expression return item.
    #[must_use]
    pub const fn expr(expr: Expr) -> Self {
        Self::Expr { expr, alias: None }
    }

    /// Creates an aliased expression return item.
    #[must_use]
    pub fn aliased(expr: Expr, alias: impl Into<Identifier>) -> Self {
        Self::Expr { expr, alias: Some(alias.into()) }
    }
}

impl From<Expr> for ReturnItem {
    fn from(expr: Expr) -> Self {
        Self::expr(expr)
    }
}

/// An item in a SELECT list.
#[derive(Debug, Clone, PartialEq)]
pub enum SelectItem {
    /// An expression, optionally aliased.
    Expr {
        /// The expression.
        expr: Expr,
        /// Optional alias.
        alias: Option<Identifier>,
    },
    /// Wildcard (*).
    Wildcard,
    /// Qualified wildcard (table.*).
    QualifiedWildcard(QualifiedName),
}

impl SelectItem {
    /// Creates an unaliased expression item.
    #[must_use]
    pub const fn expr(expr: Expr) -> Self {
        Self::Expr { expr, alias: None }
    }

    /// Creates an aliased expression item.
    #[must_use]
    pub fn aliased(expr: Expr, alias: impl Into<Identifier>) -> Self {
        Self::Expr { expr, alias: Some(alias.into()) }
    }
}

impl From<Expr> for SelectItem {
    fn from(expr: Expr) -> Self {
        Self::expr(expr)
    }
}

/// A table reference in a FROM clause.
#[derive(Debug, Clone, PartialEq)]
pub enum TableRef {
    /// A simple table reference.
    Table {
        /// The table name.
        name: QualifiedName,
        /// Optional alias.
        alias: Option<TableAlias>,
    },
    /// A subquery.
    Subquery {
        /// The subquery.
        query: Box<SelectStatement>,
        /// Required alias for subqueries.
        alias: TableAlias,
    },
    /// A join between two table references.
    Join(Box<JoinClause>),
    /// A table function call.
    TableFunction {
        /// The function name.
        name: QualifiedName,
        /// Function arguments.
        args: Vec<Expr>,
        /// Optional alias.
        alias: Option<TableAlias>,
    },
}

impl TableRef {
    /// Creates a simple table reference.
    #[must_use]
    pub fn table(name: impl Into<QualifiedName>) -> Self {
        Self::Table { name: name.into(), alias: None }
    }

    /// Creates an aliased table reference.
    #[must_use]
    pub fn aliased(name: impl Into<QualifiedName>, alias: impl Into<TableAlias>) -> Self {
        Self::Table { name: name.into(), alias: Some(alias.into()) }
    }
}

/// A table alias with optional column aliases.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableAlias {
    /// The alias name.
    pub name: Identifier,
    /// Optional column aliases.
    pub columns: Vec<Identifier>,
}

impl TableAlias {
    /// Creates a simple alias.
    #[must_use]
    pub fn new(name: impl Into<Identifier>) -> Self {
        Self { name: name.into(), columns: vec![] }
    }

    /// Creates an alias with column names.
    #[must_use]
    pub fn with_columns(name: impl Into<Identifier>, columns: Vec<Identifier>) -> Self {
        Self { name: name.into(), columns }
    }
}

impl From<&str> for TableAlias {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl From<String> for TableAlias {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

impl From<Identifier> for TableAlias {
    fn from(id: Identifier) -> Self {
        Self::new(id)
    }
}

/// A JOIN clause.
#[derive(Debug, Clone, PartialEq)]
pub struct JoinClause {
    /// Left side of the join.
    pub left: TableRef,
    /// Right side of the join.
    pub right: TableRef,
    /// Join type.
    pub join_type: JoinType,
    /// Join condition.
    pub condition: JoinCondition,
}

impl JoinClause {
    /// Creates an inner join.
    #[must_use]
    pub const fn inner(left: TableRef, right: TableRef, on: Expr) -> Self {
        Self { left, right, join_type: JoinType::Inner, condition: JoinCondition::On(on) }
    }

    /// Creates a left outer join.
    #[must_use]
    pub const fn left_join(left: TableRef, right: TableRef, on: Expr) -> Self {
        Self { left, right, join_type: JoinType::LeftOuter, condition: JoinCondition::On(on) }
    }
}

/// Type of JOIN.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
    /// INNER JOIN.
    Inner,
    /// LEFT OUTER JOIN.
    LeftOuter,
    /// RIGHT OUTER JOIN.
    RightOuter,
    /// FULL OUTER JOIN.
    FullOuter,
    /// CROSS JOIN.
    Cross,
}

/// Condition for a JOIN.
#[derive(Debug, Clone, PartialEq)]
pub enum JoinCondition {
    /// ON clause.
    On(Expr),
    /// USING clause.
    Using(Vec<Identifier>),
    /// NATURAL join (no explicit condition).
    Natural,
    /// No condition (for CROSS JOIN).
    None,
}

/// A set operation (UNION, INTERSECT, EXCEPT).
#[derive(Debug, Clone, PartialEq)]
pub struct SetOperation {
    /// The type of set operation.
    pub op: SetOperator,
    /// Whether ALL is specified.
    pub all: bool,
    /// The right-hand SELECT statement.
    pub right: SelectStatement,
}

/// Set operation types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetOperator {
    /// UNION.
    Union,
    /// INTERSECT.
    Intersect,
    /// EXCEPT.
    Except,
}

/// An INSERT statement.
#[derive(Debug, Clone, PartialEq)]
pub struct InsertStatement {
    /// The target table.
    pub table: QualifiedName,
    /// Optional column list.
    pub columns: Vec<Identifier>,
    /// The source of values.
    pub source: InsertSource,
    /// Optional ON CONFLICT clause.
    pub on_conflict: Option<OnConflict>,
    /// Optional RETURNING clause.
    pub returning: Vec<SelectItem>,
}

impl InsertStatement {
    /// Creates a new INSERT statement with VALUES.
    #[must_use]
    pub fn values(table: impl Into<QualifiedName>, values: Vec<Vec<Expr>>) -> Self {
        Self {
            table: table.into(),
            columns: vec![],
            source: InsertSource::Values(values),
            on_conflict: None,
            returning: vec![],
        }
    }

    /// Creates a new INSERT ... SELECT statement.
    #[must_use]
    pub fn select(table: impl Into<QualifiedName>, query: SelectStatement) -> Self {
        Self {
            table: table.into(),
            columns: vec![],
            source: InsertSource::Query(Box::new(query)),
            on_conflict: None,
            returning: vec![],
        }
    }

    /// Sets the column list.
    #[must_use]
    pub fn columns(mut self, columns: Vec<Identifier>) -> Self {
        self.columns = columns;
        self
    }

    /// Sets the RETURNING clause.
    #[must_use]
    pub fn returning(mut self, items: Vec<SelectItem>) -> Self {
        self.returning = items;
        self
    }
}

/// Source of values for INSERT.
#[derive(Debug, Clone, PartialEq)]
pub enum InsertSource {
    /// VALUES clause with rows of expressions.
    Values(Vec<Vec<Expr>>),
    /// SELECT subquery.
    Query(Box<SelectStatement>),
    /// DEFAULT VALUES.
    DefaultValues,
}

/// ON CONFLICT clause for INSERT.
#[derive(Debug, Clone, PartialEq)]
pub struct OnConflict {
    /// The conflict target (columns or constraint).
    pub target: ConflictTarget,
    /// The action to take on conflict.
    pub action: ConflictAction,
}

/// Target for ON CONFLICT.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConflictTarget {
    /// Specific columns.
    Columns(Vec<Identifier>),
    /// A named constraint.
    Constraint(Identifier),
}

/// Action for ON CONFLICT.
#[derive(Debug, Clone, PartialEq)]
pub enum ConflictAction {
    /// DO NOTHING.
    DoNothing,
    /// DO UPDATE SET ...
    DoUpdate {
        /// The assignments.
        assignments: Vec<Assignment>,
        /// Optional WHERE clause.
        where_clause: Option<Expr>,
    },
}

/// An UPDATE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct UpdateStatement {
    /// The target table.
    pub table: QualifiedName,
    /// Optional alias for the table.
    pub alias: Option<TableAlias>,
    /// The assignments (SET clause).
    pub assignments: Vec<Assignment>,
    /// Optional FROM clause (for UPDATE ... FROM).
    pub from: Vec<TableRef>,
    /// Optional MATCH clause for graph patterns.
    pub match_clause: Option<GraphPattern>,
    /// Optional WHERE clause.
    pub where_clause: Option<Expr>,
    /// Optional RETURNING clause.
    pub returning: Vec<SelectItem>,
}

impl UpdateStatement {
    /// Creates a new UPDATE statement.
    #[must_use]
    pub fn new(table: impl Into<QualifiedName>, assignments: Vec<Assignment>) -> Self {
        Self {
            table: table.into(),
            alias: None,
            assignments,
            from: vec![],
            match_clause: None,
            where_clause: None,
            returning: vec![],
        }
    }

    /// Sets the WHERE clause.
    #[must_use]
    pub fn where_clause(mut self, condition: Expr) -> Self {
        self.where_clause = Some(condition);
        self
    }

    /// Sets the RETURNING clause.
    #[must_use]
    pub fn returning(mut self, items: Vec<SelectItem>) -> Self {
        self.returning = items;
        self
    }
}

/// An assignment in an UPDATE or INSERT ON CONFLICT.
#[derive(Debug, Clone, PartialEq)]
pub struct Assignment {
    /// The column to assign to.
    pub column: Identifier,
    /// The value expression.
    pub value: Expr,
}

impl Assignment {
    /// Creates a new assignment.
    #[must_use]
    pub fn new(column: impl Into<Identifier>, value: Expr) -> Self {
        Self { column: column.into(), value }
    }
}

/// A DELETE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct DeleteStatement {
    /// The target table.
    pub table: QualifiedName,
    /// Optional alias for the table.
    pub alias: Option<TableAlias>,
    /// Optional USING clause.
    pub using: Vec<TableRef>,
    /// Optional MATCH clause for graph patterns.
    pub match_clause: Option<GraphPattern>,
    /// Optional WHERE clause.
    pub where_clause: Option<Expr>,
    /// Optional RETURNING clause.
    pub returning: Vec<SelectItem>,
}

impl DeleteStatement {
    /// Creates a new DELETE statement.
    #[must_use]
    pub fn new(table: impl Into<QualifiedName>) -> Self {
        Self {
            table: table.into(),
            alias: None,
            using: vec![],
            match_clause: None,
            where_clause: None,
            returning: vec![],
        }
    }

    /// Sets the WHERE clause.
    #[must_use]
    pub fn where_clause(mut self, condition: Expr) -> Self {
        self.where_clause = Some(condition);
        self
    }

    /// Sets the RETURNING clause.
    #[must_use]
    pub fn returning(mut self, items: Vec<SelectItem>) -> Self {
        self.returning = items;
        self
    }
}

/// A CREATE TABLE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateTableStatement {
    /// Whether IF NOT EXISTS is specified.
    pub if_not_exists: bool,
    /// The table name.
    pub name: QualifiedName,
    /// Column definitions.
    pub columns: Vec<ColumnDef>,
    /// Table constraints.
    pub constraints: Vec<TableConstraint>,
}

impl CreateTableStatement {
    /// Creates a new CREATE TABLE statement.
    #[must_use]
    pub fn new(name: impl Into<QualifiedName>, columns: Vec<ColumnDef>) -> Self {
        Self { if_not_exists: false, name: name.into(), columns, constraints: vec![] }
    }
}

/// A column definition.
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnDef {
    /// The column name.
    pub name: Identifier,
    /// The data type.
    pub data_type: DataType,
    /// Column constraints.
    pub constraints: Vec<ColumnConstraint>,
}

impl ColumnDef {
    /// Creates a new column definition.
    #[must_use]
    pub fn new(name: impl Into<Identifier>, data_type: DataType) -> Self {
        Self { name: name.into(), data_type, constraints: vec![] }
    }

    /// Adds a NOT NULL constraint.
    #[must_use]
    pub fn not_null(mut self) -> Self {
        self.constraints.push(ColumnConstraint::NotNull);
        self
    }

    /// Adds a PRIMARY KEY constraint.
    #[must_use]
    pub fn primary_key(mut self) -> Self {
        self.constraints.push(ColumnConstraint::PrimaryKey);
        self
    }

    /// Adds a UNIQUE constraint.
    #[must_use]
    pub fn unique(mut self) -> Self {
        self.constraints.push(ColumnConstraint::Unique);
        self
    }

    /// Adds a DEFAULT value.
    #[must_use]
    pub fn default(mut self, value: Expr) -> Self {
        self.constraints.push(ColumnConstraint::Default(value));
        self
    }
}

/// SQL data types.
#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
    /// BOOLEAN.
    Boolean,
    /// SMALLINT (16-bit).
    SmallInt,
    /// INTEGER (32-bit).
    Integer,
    /// BIGINT (64-bit).
    BigInt,
    /// REAL (32-bit float).
    Real,
    /// DOUBLE PRECISION (64-bit float).
    DoublePrecision,
    /// NUMERIC with optional precision and scale.
    Numeric {
        /// Total digits.
        precision: Option<u32>,
        /// Digits after decimal point.
        scale: Option<u32>,
    },
    /// VARCHAR with optional length.
    Varchar(Option<u32>),
    /// TEXT (unlimited length string).
    Text,
    /// BYTEA (binary data).
    Bytea,
    /// TIMESTAMP.
    Timestamp,
    /// DATE.
    Date,
    /// TIME.
    Time,
    /// INTERVAL.
    Interval,
    /// JSON.
    Json,
    /// JSONB.
    Jsonb,
    /// UUID.
    Uuid,
    /// VECTOR with dimension.
    Vector(Option<u32>),
    /// Array of another type.
    Array(Box<DataType>),
    /// Custom/user-defined type.
    Custom(String),
}

/// Column constraints.
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnConstraint {
    /// NOT NULL.
    NotNull,
    /// NULL (explicit).
    Null,
    /// UNIQUE.
    Unique,
    /// PRIMARY KEY.
    PrimaryKey,
    /// REFERENCES (foreign key).
    References {
        /// Referenced table.
        table: QualifiedName,
        /// Referenced column.
        column: Option<Identifier>,
    },
    /// CHECK constraint.
    Check(Expr),
    /// DEFAULT value.
    Default(Expr),
}

/// Table-level constraints.
#[derive(Debug, Clone, PartialEq)]
pub enum TableConstraint {
    /// PRIMARY KEY.
    PrimaryKey {
        /// Optional constraint name.
        name: Option<Identifier>,
        /// Columns in the key.
        columns: Vec<Identifier>,
    },
    /// UNIQUE.
    Unique {
        /// Optional constraint name.
        name: Option<Identifier>,
        /// Columns in the constraint.
        columns: Vec<Identifier>,
    },
    /// FOREIGN KEY.
    ForeignKey {
        /// Optional constraint name.
        name: Option<Identifier>,
        /// Local columns.
        columns: Vec<Identifier>,
        /// Referenced table.
        references_table: QualifiedName,
        /// Referenced columns.
        references_columns: Vec<Identifier>,
    },
    /// CHECK.
    Check {
        /// Optional constraint name.
        name: Option<Identifier>,
        /// The check expression.
        expr: Expr,
    },
}

/// A CREATE INDEX statement.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateIndexStatement {
    /// Whether UNIQUE is specified.
    pub unique: bool,
    /// Whether IF NOT EXISTS is specified.
    pub if_not_exists: bool,
    /// The index name.
    pub name: Identifier,
    /// The table to index.
    pub table: QualifiedName,
    /// The columns/expressions to index.
    pub columns: Vec<IndexColumn>,
    /// The index method (btree, hash, gin, hnsw, ivfflat).
    pub using: Option<String>,
    /// Index-specific options.
    pub with: Vec<(String, String)>,
    /// Optional WHERE clause for partial indexes.
    pub where_clause: Option<Expr>,
}

/// A column in an index.
#[derive(Debug, Clone, PartialEq)]
pub struct IndexColumn {
    /// The column or expression.
    pub expr: Expr,
    /// Sort order (ASC/DESC).
    pub asc: Option<bool>,
    /// NULLS FIRST/LAST.
    pub nulls_first: Option<bool>,
    /// Operator class.
    pub opclass: Option<String>,
}

impl IndexColumn {
    /// Creates a new index column.
    #[must_use]
    pub const fn new(expr: Expr) -> Self {
        Self { expr, asc: None, nulls_first: None, opclass: None }
    }
}

/// A DROP TABLE statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropTableStatement {
    /// Whether IF EXISTS is specified.
    pub if_exists: bool,
    /// The table(s) to drop.
    pub names: Vec<QualifiedName>,
    /// Whether CASCADE is specified.
    pub cascade: bool,
}

/// A DROP INDEX statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropIndexStatement {
    /// Whether IF EXISTS is specified.
    pub if_exists: bool,
    /// The index(es) to drop.
    pub names: Vec<QualifiedName>,
    /// Whether CASCADE is specified.
    pub cascade: bool,
}

/// A CREATE COLLECTION statement for vector collections.
///
/// Creates a collection with named vector configurations and optional payload fields:
///
/// ```sql
/// CREATE COLLECTION documents (
///     title TEXT,
///     content TEXT,
///     VECTOR text_embedding DIMENSION 1536,
///     VECTOR image_embedding DIMENSION 512,
///     VECTOR summary_embedding DIMENSION 1536
/// );
/// ```
///
/// Alternative syntax with USING and WITH clauses:
///
/// ```sql
/// CREATE COLLECTION documents (
///     dense VECTOR(768) USING hnsw WITH (distance = 'cosine'),
///     sparse SPARSE_VECTOR USING inverted,
///     colbert MULTI_VECTOR(128) USING hnsw WITH (aggregation = 'maxsim')
/// );
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct CreateCollectionStatement {
    /// Whether IF NOT EXISTS is specified.
    pub if_not_exists: bool,
    /// The collection name.
    pub name: Identifier,
    /// Named vector definitions.
    pub vectors: Vec<VectorDef>,
    /// Payload field definitions.
    pub payload_fields: Vec<PayloadFieldDef>,
}

/// A payload field definition in a collection.
///
/// Defines a field in the collection's payload schema.
#[derive(Debug, Clone, PartialEq)]
pub struct PayloadFieldDef {
    /// The field name.
    pub name: Identifier,
    /// The field data type.
    pub data_type: DataType,
    /// Whether the field is indexed.
    pub indexed: bool,
}

impl CreateCollectionStatement {
    /// Creates a new CREATE COLLECTION statement.
    #[must_use]
    pub fn new(name: impl Into<Identifier>, vectors: Vec<VectorDef>) -> Self {
        Self { if_not_exists: false, name: name.into(), vectors, payload_fields: vec![] }
    }

    /// Creates a CREATE COLLECTION statement with vectors and payload fields.
    #[must_use]
    pub fn with_payload(
        name: impl Into<Identifier>,
        vectors: Vec<VectorDef>,
        payload_fields: Vec<PayloadFieldDef>,
    ) -> Self {
        Self { if_not_exists: false, name: name.into(), vectors, payload_fields }
    }

    /// Set IF NOT EXISTS flag.
    #[must_use]
    pub const fn if_not_exists(mut self) -> Self {
        self.if_not_exists = true;
        self
    }

    /// Add a payload field definition.
    #[must_use]
    pub fn with_field(mut self, field: PayloadFieldDef) -> Self {
        self.payload_fields.push(field);
        self
    }
}

impl PayloadFieldDef {
    /// Creates a new payload field definition.
    #[must_use]
    pub fn new(name: impl Into<Identifier>, data_type: DataType) -> Self {
        Self { name: name.into(), data_type, indexed: false }
    }

    /// Set the field as indexed.
    #[must_use]
    pub const fn indexed(mut self) -> Self {
        self.indexed = true;
        self
    }
}

/// A named vector definition in a collection.
///
/// Defines a single named vector space with its type, index method, and options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VectorDef {
    /// The vector name (e.g., "dense", "sparse", "colbert").
    pub name: Identifier,
    /// The vector type.
    pub vector_type: VectorTypeDef,
    /// The index method (e.g., "hnsw", "inverted", "flat").
    pub using: Option<String>,
    /// Index and vector options (e.g., distance, aggregation, m, ef_construction).
    pub with_options: Vec<(String, String)>,
}

impl VectorDef {
    /// Creates a new vector definition.
    #[must_use]
    pub fn new(name: impl Into<Identifier>, vector_type: VectorTypeDef) -> Self {
        Self { name: name.into(), vector_type, using: None, with_options: vec![] }
    }

    /// Set the index method.
    #[must_use]
    pub fn using(mut self, method: impl Into<String>) -> Self {
        self.using = Some(method.into());
        self
    }

    /// Add a WITH option.
    #[must_use]
    pub fn with_option(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.with_options.push((key.into(), value.into()));
        self
    }
}

/// Vector type definition in DDL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VectorTypeDef {
    /// Dense vector with fixed dimension: VECTOR(768).
    Vector {
        /// The dimension of the vector.
        dimension: u32,
    },
    /// Sparse vector with optional max dimension: SPARSE_VECTOR or SPARSE_VECTOR(30522).
    SparseVector {
        /// Maximum vocabulary size (optional).
        max_dimension: Option<u32>,
    },
    /// Multi-vector with per-token dimension: MULTI_VECTOR(128).
    MultiVector {
        /// The dimension of each token embedding.
        token_dim: u32,
    },
    /// Binary vector with bit count: BINARY_VECTOR(1024).
    BinaryVector {
        /// The number of bits.
        bits: u32,
    },
}

impl VectorTypeDef {
    /// Create a dense vector type.
    #[must_use]
    pub const fn dense(dimension: u32) -> Self {
        Self::Vector { dimension }
    }

    /// Create a sparse vector type.
    #[must_use]
    pub const fn sparse(max_dimension: Option<u32>) -> Self {
        Self::SparseVector { max_dimension }
    }

    /// Create a multi-vector type.
    #[must_use]
    pub const fn multi(token_dim: u32) -> Self {
        Self::MultiVector { token_dim }
    }

    /// Create a binary vector type.
    #[must_use]
    pub const fn binary(bits: u32) -> Self {
        Self::BinaryVector { bits }
    }
}

/// A DROP COLLECTION statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropCollectionStatement {
    /// Whether IF EXISTS is specified.
    pub if_exists: bool,
    /// The collection(s) to drop.
    pub names: Vec<Identifier>,
    /// Whether CASCADE is specified (drops associated data and indexes).
    pub cascade: bool,
}

impl DropCollectionStatement {
    /// Creates a new DROP COLLECTION statement.
    #[must_use]
    pub fn new(names: Vec<Identifier>) -> Self {
        Self { if_exists: false, names, cascade: false }
    }

    /// Set IF EXISTS flag.
    #[must_use]
    pub const fn if_exists(mut self) -> Self {
        self.if_exists = true;
        self
    }

    /// Set CASCADE flag.
    #[must_use]
    pub const fn cascade(mut self) -> Self {
        self.cascade = true;
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn select_builder() {
        let stmt = SelectStatement::new(vec![SelectItem::Wildcard])
            .from(TableRef::table(QualifiedName::simple("users")))
            .where_clause(Expr::column(QualifiedName::simple("id")).eq(Expr::integer(1)));

        assert!(stmt.where_clause.is_some());
        assert_eq!(stmt.from.len(), 1);
    }

    #[test]
    fn insert_builder() {
        let stmt = InsertStatement::values(
            QualifiedName::simple("users"),
            vec![vec![Expr::string("Alice"), Expr::integer(30)]],
        )
        .columns(vec![Identifier::new("name"), Identifier::new("age")]);

        assert_eq!(stmt.columns.len(), 2);
    }

    #[test]
    fn column_def_builder() {
        let col = ColumnDef::new("id", DataType::BigInt).primary_key().not_null();

        assert_eq!(col.constraints.len(), 2);
    }

    #[test]
    fn assignment() {
        let assign = Assignment::new("status", Expr::string("active"));
        assert_eq!(assign.column.name, "status");
    }
}