neumann_parser 0.4.0

Hand-written recursive descent parser for the Neumann query language
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
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Abstract Syntax Tree (AST) nodes for the Neumann query language.
//!
//! Defines all AST node types for:
//! - SQL statements (SELECT, INSERT, UPDATE, DELETE, CREATE, DROP)
//! - Graph commands (NODE, EDGE, NEIGHBORS, PATH)
//! - Vector commands (EMBED, SIMILAR)
//! - Expressions (binary, unary, literals, function calls)

use std::fmt;

use crate::span::Span;

/// A complete statement.
#[derive(Clone, Debug, PartialEq)]
pub struct Statement {
    /// The kind of statement.
    pub kind: StatementKind,
    /// Source location of this statement.
    pub span: Span,
}

impl Statement {
    /// Creates a new statement.
    #[must_use]
    pub const fn new(kind: StatementKind, span: Span) -> Self {
        Self { kind, span }
    }
}

/// Statement variants.
#[derive(Clone, Debug, PartialEq)]
pub enum StatementKind {
    // === SQL Statements ===
    /// SELECT query
    Select(SelectStmt),
    /// INSERT statement
    Insert(InsertStmt),
    /// UPDATE statement
    Update(UpdateStmt),
    /// DELETE statement
    Delete(DeleteStmt),
    /// CREATE TABLE statement
    CreateTable(CreateTableStmt),
    /// DROP TABLE statement
    DropTable(DropTableStmt),
    /// CREATE INDEX statement
    CreateIndex(CreateIndexStmt),
    /// DROP INDEX statement
    DropIndex(DropIndexStmt),
    /// SHOW TABLES statement
    ShowTables,
    /// SHOW EMBEDDINGS statement
    ShowEmbeddings {
        /// Maximum number of embeddings to show.
        limit: Option<Expr>,
    },
    /// SHOW VECTOR INDEX statement
    ShowVectorIndex,
    /// COUNT EMBEDDINGS statement
    CountEmbeddings,
    /// DESCRIBE statement
    Describe(DescribeStmt),

    // === Graph Statements ===
    /// NODE command
    Node(NodeStmt),
    /// EDGE command
    Edge(EdgeStmt),
    /// NEIGHBORS command
    Neighbors(NeighborsStmt),
    /// PATH command
    Path(PathStmt),

    // === Vector Statements ===
    /// EMBED command
    Embed(EmbedStmt),
    /// SIMILAR search
    Similar(SimilarStmt),

    // === Spatial Statements ===
    /// SPATIAL command
    Spatial(SpatialStmt),

    // === Unified Statements ===
    /// FIND unified query
    Find(FindStmt),
    /// ENTITY command
    Entity(EntityStmt),

    // === Vault Statements ===
    /// VAULT command
    Vault(VaultStmt),

    // === Cache Statements ===
    /// CACHE command
    Cache(CacheStmt),

    // === Blob Storage Statements ===
    /// BLOB command
    Blob(BlobStmt),
    /// BLOBS command (list/query blobs)
    Blobs(BlobsStmt),

    // === Checkpoint Statements ===
    /// CHECKPOINT command - create a named checkpoint
    Checkpoint(CheckpointStmt),
    /// ROLLBACK command - restore to a checkpoint
    Rollback(RollbackStmt),
    /// CHECKPOINTS command - list checkpoints
    Checkpoints(CheckpointsStmt),

    // === Chain Statements ===
    /// CHAIN command
    Chain(ChainStmt),

    // === Cluster Statements ===
    /// CLUSTER command
    Cluster(ClusterStmt),

    // === Extended Graph Statements ===
    /// GRAPH ALGORITHM command (`PageRank`, centrality, etc.)
    GraphAlgorithm(GraphAlgorithmStmt),
    /// GRAPH CONSTRAINT command
    GraphConstraint(GraphConstraintStmt),
    /// GRAPH INDEX command
    GraphIndex(GraphIndexStmt),
    /// GRAPH AGGREGATE command (COUNT NODES, etc.)
    GraphAggregate(GraphAggregateStmt),
    /// GRAPH PATTERN command (MATCH PATTERN)
    GraphPattern(GraphPatternStmt),
    /// GRAPH BATCH command
    GraphBatch(GraphBatchStmt),

    // === Cypher Graph Statements ===
    /// Cypher MATCH statement
    CypherMatch(crate::cypher::CypherMatchStmt),
    /// Cypher CREATE statement
    CypherCreate(crate::cypher::CypherCreateStmt),
    /// Cypher DELETE statement
    CypherDelete(crate::cypher::CypherDeleteStmt),
    /// Cypher MERGE statement
    CypherMerge(crate::cypher::CypherMergeStmt),

    /// Empty statement (just semicolons)
    Empty,
}

// =============================================================================
// SQL Statements
// =============================================================================

/// SELECT statement.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectStmt {
    /// DISTINCT modifier
    pub distinct: bool,
    /// Selected columns/expressions
    pub columns: Vec<SelectItem>,
    /// FROM clause
    pub from: Option<FromClause>,
    /// WHERE clause
    pub where_clause: Option<Box<Expr>>,
    /// GROUP BY clause
    pub group_by: Vec<Expr>,
    /// HAVING clause
    pub having: Option<Box<Expr>>,
    /// ORDER BY clause
    pub order_by: Vec<OrderByItem>,
    /// LIMIT
    pub limit: Option<Box<Expr>>,
    /// OFFSET
    pub offset: Option<Box<Expr>>,
}

/// A selected column or expression.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectItem {
    /// The selected expression.
    pub expr: Expr,
    /// Optional alias (`AS name`).
    pub alias: Option<Ident>,
}

/// FROM clause with optional joins.
#[derive(Clone, Debug, PartialEq)]
pub struct FromClause {
    /// The primary table reference.
    pub table: TableRef,
    /// Join clauses.
    pub joins: Vec<Join>,
}

/// A table reference.
#[derive(Clone, Debug, PartialEq)]
pub struct TableRef {
    /// The table reference kind.
    pub kind: TableRefKind,
    /// Optional table alias.
    pub alias: Option<Ident>,
    /// Source location.
    pub span: Span,
}

/// Table reference variants.
#[derive(Clone, Debug, PartialEq)]
pub enum TableRefKind {
    /// Simple table name
    Table(Ident),
    /// Subquery
    Subquery(Box<SelectStmt>),
}

/// A JOIN clause.
#[derive(Clone, Debug, PartialEq)]
pub struct Join {
    /// The type of join.
    pub kind: JoinKind,
    /// The joined table.
    pub table: TableRef,
    /// Join condition (ON or USING).
    pub condition: Option<JoinCondition>,
    /// Source location.
    pub span: Span,
}

/// JOIN types.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JoinKind {
    /// Inner join.
    Inner,
    /// Left outer join.
    Left,
    /// Right outer join.
    Right,
    /// Full outer join.
    Full,
    /// Cross join.
    Cross,
    /// Natural join.
    Natural,
}

/// JOIN conditions.
#[derive(Clone, Debug, PartialEq)]
pub enum JoinCondition {
    /// ON condition
    On(Box<Expr>),
    /// USING columns
    Using(Vec<Ident>),
}

/// ORDER BY item.
#[derive(Clone, Debug, PartialEq)]
pub struct OrderByItem {
    /// The expression to sort by.
    pub expr: Expr,
    /// Sort direction (ASC or DESC).
    pub direction: SortDirection,
    /// NULLS FIRST or NULLS LAST.
    pub nulls: Option<NullsOrder>,
}

/// Sort direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum SortDirection {
    /// Ascending order.
    #[default]
    Asc,
    /// Descending order.
    Desc,
}

/// NULLS FIRST/LAST.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NullsOrder {
    /// Nulls sort before non-null values.
    First,
    /// Nulls sort after non-null values.
    Last,
}

/// INSERT statement.
#[derive(Clone, Debug, PartialEq)]
pub struct InsertStmt {
    /// Target table.
    pub table: Ident,
    /// Optional column list.
    pub columns: Option<Vec<Ident>>,
    /// Source of values.
    pub source: InsertSource,
}

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

/// UPDATE statement.
#[derive(Clone, Debug, PartialEq)]
pub struct UpdateStmt {
    /// Target table.
    pub table: Ident,
    /// Column assignments.
    pub assignments: Vec<Assignment>,
    /// Optional WHERE filter.
    pub where_clause: Option<Box<Expr>>,
}

/// Column assignment.
#[derive(Clone, Debug, PartialEq)]
pub struct Assignment {
    /// Target column.
    pub column: Ident,
    /// New value expression.
    pub value: Expr,
}

/// DELETE statement.
#[derive(Clone, Debug, PartialEq)]
pub struct DeleteStmt {
    /// Target table.
    pub table: Ident,
    /// Optional WHERE filter.
    pub where_clause: Option<Box<Expr>>,
}

/// CREATE TABLE statement.
#[derive(Clone, Debug, PartialEq)]
pub struct CreateTableStmt {
    /// Whether IF NOT EXISTS was specified.
    pub if_not_exists: bool,
    /// Table name.
    pub table: Ident,
    /// Column definitions.
    pub columns: Vec<ColumnDef>,
    /// Table-level constraints.
    pub constraints: Vec<TableConstraint>,
}

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

/// Data types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DataType {
    /// SQL `INT` type.
    Int,
    /// SQL `INTEGER` type.
    Integer,
    /// SQL `BIGINT` type.
    Bigint,
    /// SQL `SMALLINT` type.
    Smallint,
    /// SQL `FLOAT` type.
    Float,
    /// SQL `DOUBLE` type.
    Double,
    /// SQL `REAL` type.
    Real,
    /// SQL `DECIMAL(precision, scale)` type.
    Decimal(Option<u32>, Option<u32>),
    /// SQL `NUMERIC(precision, scale)` type.
    Numeric(Option<u32>, Option<u32>),
    /// SQL `VARCHAR(length)` type.
    Varchar(Option<u32>),
    /// SQL `CHAR(length)` type.
    Char(Option<u32>),
    /// SQL `TEXT` type.
    Text,
    /// SQL `BOOLEAN` type.
    Boolean,
    /// SQL `DATE` type.
    Date,
    /// SQL `TIME` type.
    Time,
    /// SQL `TIMESTAMP` type.
    Timestamp,
    /// SQL `BLOB` type.
    Blob,
    /// Custom type name
    Custom(String),
}

/// Column constraints.
#[derive(Clone, Debug, PartialEq)]
pub enum ColumnConstraint {
    /// Column must not be null.
    NotNull,
    /// Column allows nulls (explicit).
    Null,
    /// Column values must be unique.
    Unique,
    /// Column is the primary key.
    PrimaryKey,
    /// Default value expression.
    Default(Expr),
    /// Check constraint expression.
    Check(Expr),
    /// Foreign key reference.
    References(ForeignKeyRef),
}

/// Foreign key reference.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForeignKeyRef {
    /// Referenced table.
    pub table: Ident,
    /// Referenced column.
    pub column: Option<Ident>,
    /// Action on delete.
    pub on_delete: Option<ReferentialAction>,
    /// Action on update.
    pub on_update: Option<ReferentialAction>,
}

/// Referential actions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReferentialAction {
    /// Cascade the operation to referencing rows.
    Cascade,
    /// Restrict the operation if references exist.
    Restrict,
    /// Set referencing columns to null.
    SetNull,
    /// Set referencing columns to their default.
    SetDefault,
    /// Take no action.
    NoAction,
}

/// Table-level constraints.
#[derive(Clone, Debug, PartialEq)]
pub enum TableConstraint {
    /// Primary key on columns.
    PrimaryKey(Vec<Ident>),
    /// Unique constraint on columns.
    Unique(Vec<Ident>),
    /// Foreign key constraint.
    ForeignKey {
        /// Local columns.
        columns: Vec<Ident>,
        /// Foreign key reference.
        reference: ForeignKeyRef,
    },
    /// Check constraint.
    Check(Expr),
}

/// DROP TABLE statement.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DropTableStmt {
    /// Whether IF EXISTS was specified.
    pub if_exists: bool,
    /// Table name.
    pub table: Ident,
    /// Whether CASCADE was specified.
    pub cascade: bool,
}

/// CREATE INDEX statement.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CreateIndexStmt {
    /// Whether this is a UNIQUE index.
    pub unique: bool,
    /// Whether IF NOT EXISTS was specified.
    pub if_not_exists: bool,
    /// Index name.
    pub name: Ident,
    /// Table to index.
    pub table: Ident,
    /// Columns to index.
    pub columns: Vec<Ident>,
}

/// DROP INDEX statement.
/// Supports both `DROP INDEX name` and `DROP INDEX ON table(column)` syntax.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DropIndexStmt {
    /// Whether IF EXISTS was specified.
    pub if_exists: bool,
    /// Index name (for named indexes)
    pub name: Option<Ident>,
    /// Table name (for ON table(column) syntax)
    pub table: Option<Ident>,
    /// Column name (for ON table(column) syntax)
    pub column: Option<Ident>,
}

/// DESCRIBE statement.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DescribeStmt {
    /// What to describe.
    pub target: DescribeTarget,
}

/// Target of DESCRIBE.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DescribeTarget {
    /// DESCRIBE TABLE name
    Table(Ident),
    /// DESCRIBE NODE label
    Node(Ident),
    /// DESCRIBE EDGE type
    Edge(Ident),
}

// =============================================================================
// Graph Statements
// =============================================================================

/// NODE command.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeStmt {
    /// The node operation to perform.
    pub operation: NodeOp,
}

/// NODE operations.
#[derive(Clone, Debug, PartialEq)]
pub enum NodeOp {
    /// Create a node: `NODE label { properties }`
    Create {
        /// Node label.
        label: Ident,
        /// Node properties.
        properties: Vec<Property>,
    },
    /// Get a node: `NODE GET id`
    Get {
        /// Node ID.
        id: Expr,
    },
    /// Delete a node: `NODE DELETE id`
    Delete {
        /// Node ID.
        id: Expr,
    },
    /// List nodes: `NODE LIST [label] [LIMIT n] [OFFSET m]`
    List {
        /// Optional label filter.
        label: Option<Ident>,
        /// Maximum number of results.
        limit: Option<Box<Expr>>,
        /// Number of results to skip.
        offset: Option<Box<Expr>>,
    },
}

/// EDGE command.
#[derive(Clone, Debug, PartialEq)]
pub struct EdgeStmt {
    /// The edge operation to perform.
    pub operation: EdgeOp,
}

/// EDGE operations.
#[derive(Clone, Debug, PartialEq)]
pub enum EdgeOp {
    /// Create an edge: `EDGE from_ref edge_type to_ref { properties }`
    Create {
        /// Source node ID.
        from_id: Expr,
        /// Target node ID.
        to_id: Expr,
        /// Edge type label.
        edge_type: Ident,
        /// Edge properties.
        properties: Vec<Property>,
    },
    /// Get an edge: `EDGE GET id`
    Get {
        /// Edge ID.
        id: Expr,
    },
    /// Delete an edge: `EDGE DELETE id`
    Delete {
        /// Edge ID.
        id: Expr,
    },
    /// List edges: `EDGE LIST [type] [LIMIT n] [OFFSET m]`
    List {
        /// Optional edge type filter.
        edge_type: Option<Ident>,
        /// Maximum number of results.
        limit: Option<Box<Expr>>,
        /// Number of results to skip.
        offset: Option<Box<Expr>>,
    },
}

/// A property key-value pair.
#[derive(Clone, Debug, PartialEq)]
pub struct Property {
    /// Property name.
    pub key: Ident,
    /// Property value expression.
    pub value: Expr,
}

/// NEIGHBORS command.
#[derive(Clone, Debug, PartialEq)]
pub struct NeighborsStmt {
    /// ID of the node to query neighbors for.
    pub node_id: Expr,
    /// Traversal direction.
    pub direction: Direction,
    /// Optional edge type filter.
    pub edge_type: Option<Ident>,
    /// Optional BY SIMILARITY constraint for cross-engine queries
    pub by_similarity: Option<Vec<Expr>>,
    /// Optional LIMIT for BY SIMILARITY queries
    pub limit: Option<Expr>,
}

/// Direction for graph traversal.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Direction {
    /// Outgoing edges only.
    #[default]
    Outgoing,
    /// Incoming edges only.
    Incoming,
    /// Both directions.
    Both,
}

/// PATH command.
#[derive(Clone, Debug, PartialEq)]
pub struct PathStmt {
    /// Path-finding algorithm to use.
    pub algorithm: PathAlgorithm,
    /// Source node ID.
    pub from_id: Expr,
    /// Destination node ID.
    pub to_id: Expr,
    /// Maximum traversal depth.
    pub max_depth: Option<Expr>,
    /// Minimum traversal depth.
    pub min_depth: Option<Expr>,
    /// Edge property to use as weight.
    pub weight_property: Option<Ident>,
}

/// Path-finding algorithms.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PathAlgorithm {
    /// Shortest unweighted path (BFS).
    #[default]
    Shortest,
    /// All paths up to max depth.
    All,
    /// Shortest weighted path (Dijkstra).
    Weighted,
    /// All weighted paths.
    AllWeighted,
    /// Variable-length path pattern.
    Variable,
}

// =============================================================================
// Vector Statements
// =============================================================================

/// EMBED command.
#[derive(Clone, Debug, PartialEq)]
pub struct EmbedStmt {
    /// The embed operation to perform.
    pub operation: EmbedOp,
    /// Optional collection name (e.g., `IN my_collection`).
    pub collection: Option<String>,
}

/// EMBED operations.
#[derive(Clone, Debug, PartialEq)]
pub enum EmbedOp {
    /// Store embedding: `EMBED STORE 'key' [vector]`
    Store {
        /// Embedding key.
        key: Expr,
        /// Embedding vector values.
        vector: Vec<Expr>,
    },
    /// Get embedding: `EMBED GET 'key'`
    Get {
        /// Embedding key.
        key: Expr,
    },
    /// Delete embedding: `EMBED DELETE 'key'`
    Delete {
        /// Embedding key.
        key: Expr,
    },
    /// Build HNSW index: `EMBED BUILD INDEX`
    BuildIndex,
    /// Batch store embeddings: `EMBED BATCH [('key1', [v1, v2]), ('key2', [v1, v2])]`
    Batch {
        /// Key-vector pairs to store.
        items: Vec<(Expr, Vec<Expr>)>,
    },
}

/// SIMILAR search.
#[derive(Clone, Debug, PartialEq)]
pub struct SimilarStmt {
    /// The similarity query (by key or vector).
    pub query: SimilarQuery,
    /// Maximum number of results.
    pub limit: Option<Expr>,
    /// Distance metric to use.
    pub metric: Option<DistanceMetric>,
    /// Optional CONNECTED TO constraint for cross-engine queries
    pub connected_to: Option<Expr>,
    /// Optional collection name (e.g., `IN my_collection`).
    pub collection: Option<String>,
    /// Optional WHERE clause for filtered search.
    pub where_clause: Option<Box<Expr>>,
}

/// Query for SIMILAR search.
#[derive(Clone, Debug, PartialEq)]
pub enum SimilarQuery {
    /// Search by key
    Key(Expr),
    /// Search by vector
    Vector(Vec<Expr>),
}

/// Distance metrics.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum DistanceMetric {
    /// Cosine similarity.
    #[default]
    Cosine,
    /// Euclidean distance.
    Euclidean,
    /// Dot product similarity.
    DotProduct,
}

// =============================================================================
// Spatial Statements
// =============================================================================

/// SPATIAL statement.
#[derive(Clone, Debug, PartialEq)]
pub struct SpatialStmt {
    /// The spatial operation.
    pub op: SpatialOp,
}

/// Spatial operations.
#[derive(Clone, Debug, PartialEq)]
pub enum SpatialOp {
    /// Insert entry: `SPATIAL INSERT 'key' BOUNDS x y w h`
    Insert {
        /// Key identifier for the entry.
        key: Expr,
        /// Bounding box x coordinate.
        x: Expr,
        /// Bounding box y coordinate.
        y: Expr,
        /// Bounding box width.
        width: Expr,
        /// Bounding box height.
        height: Expr,
    },
    /// Range query: `SPATIAL WITHIN x y RADIUS r [LIMIT n]`
    WithinRadius {
        /// Center x coordinate.
        x: Expr,
        /// Center y coordinate.
        y: Expr,
        /// Search radius.
        radius: Expr,
        /// Maximum results.
        limit: Option<Expr>,
    },
    /// Remove entry: `SPATIAL DELETE 'key' BOUNDS x y w h`
    Delete {
        /// Key identifier for the entry.
        key: Expr,
        /// Bounding box x coordinate.
        x: Expr,
        /// Bounding box y coordinate.
        y: Expr,
        /// Bounding box width.
        width: Expr,
        /// Bounding box height.
        height: Expr,
    },
    /// Nearest centroid query: `SPATIAL NEAREST x y [LIMIT k]`
    Nearest {
        /// X coordinate of query point.
        x: Expr,
        /// Y coordinate of query point.
        y: Expr,
        /// Maximum results to return (defaults to 1 at execution).
        limit: Option<Expr>,
    },
    /// Count entries: `SPATIAL COUNT`
    Count,
}

// =============================================================================
// Unified Statements
// =============================================================================

/// FIND unified query.
#[derive(Clone, Debug, PartialEq)]
pub struct FindStmt {
    /// The find pattern.
    pub pattern: FindPattern,
    /// Optional WHERE filter.
    pub where_clause: Option<Box<Expr>>,
    /// Optional SIMILAR TO clause for vector similarity ranking.
    pub similar_to: Option<Expr>,
    /// Optional CONNECTED TO clause for graph connectivity constraint.
    pub connected_to: Option<Expr>,
    /// Items to return.
    pub return_items: Vec<SelectItem>,
    /// Maximum number of results.
    pub limit: Option<Box<Expr>>,
}

/// FIND pattern.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FindPattern {
    /// Match nodes by label
    Nodes {
        /// Optional label filter.
        label: Option<Ident>,
    },
    /// Match edges by type
    Edges {
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Match rows in a relational table: `FIND ROWS FROM table`
    Rows {
        /// Table name.
        table: Ident,
    },
    /// Match path pattern
    Path {
        /// Source node label.
        from: Option<Ident>,
        /// Edge type.
        edge: Option<Ident>,
        /// Target node label.
        to: Option<Ident>,
    },
}

/// ENTITY command.
#[derive(Clone, Debug, PartialEq)]
pub struct EntityStmt {
    /// The entity operation to perform.
    pub operation: EntityOp,
}

/// ENTITY operations.
#[derive(Clone, Debug, PartialEq)]
pub enum EntityOp {
    /// Create an entity: `ENTITY CREATE 'key' { properties } [EMBEDDING [vector]]`
    Create {
        /// Entity key.
        key: Expr,
        /// Entity properties.
        properties: Vec<Property>,
        /// Optional embedding vector.
        embedding: Option<Vec<Expr>>,
    },
    /// Get an entity: `ENTITY GET 'key'`
    Get {
        /// Entity key.
        key: Expr,
    },
    /// Update an entity: `ENTITY UPDATE 'key' { properties } [EMBEDDING [vector]]`
    Update {
        /// Entity key.
        key: Expr,
        /// Entity properties.
        properties: Vec<Property>,
        /// Optional embedding vector.
        embedding: Option<Vec<Expr>>,
    },
    /// Delete an entity: `ENTITY DELETE 'key'`
    Delete {
        /// Entity key.
        key: Expr,
    },
    /// Connect entities: `ENTITY CONNECT 'from' -> 'to' : type`
    Connect {
        /// Source entity key.
        from_key: Expr,
        /// Target entity key.
        to_key: Expr,
        /// Edge type label.
        edge_type: Ident,
    },
    /// Batch create entities: `ENTITY BATCH CREATE [{key: 'k1', props...}, ...]`
    Batch {
        /// Entity definitions.
        entities: Vec<BatchEntityDef>,
    },
}

/// Batch entity definition for ENTITY BATCH CREATE.
#[derive(Clone, Debug, PartialEq)]
pub struct BatchEntityDef {
    /// Entity key.
    pub key: Expr,
    /// Entity properties.
    pub properties: Vec<Property>,
    /// Optional embedding vector.
    pub embedding: Option<Vec<Expr>>,
}

// =============================================================================
// Vault Statements
// =============================================================================

/// VAULT command.
#[derive(Clone, Debug, PartialEq)]
pub struct VaultStmt {
    /// The vault operation to perform.
    pub operation: VaultOp,
}

/// VAULT operations.
#[derive(Clone, Debug, PartialEq)]
pub enum VaultOp {
    /// Set a secret: `VAULT SET 'key' 'value'`
    Set {
        /// Secret key.
        key: Expr,
        /// Secret value.
        value: Expr,
    },
    /// Get a secret: `VAULT GET 'key'`
    Get {
        /// Secret key.
        key: Expr,
    },
    /// Delete a secret: `VAULT DELETE 'key'`
    Delete {
        /// Secret key.
        key: Expr,
    },
    /// List secrets: `VAULT LIST 'pattern'`
    List {
        /// Optional name pattern.
        pattern: Option<Expr>,
    },
    /// Rotate a secret: `VAULT ROTATE 'key' 'new_value'`
    Rotate {
        /// Secret key.
        key: Expr,
        /// New secret value.
        new_value: Expr,
    },
    /// Grant access: `VAULT GRANT 'entity' ON 'key'`
    Grant {
        /// Entity to grant access to.
        entity: Expr,
        /// Secret key.
        key: Expr,
    },
    /// Revoke access: `VAULT REVOKE 'entity' ON 'key'`
    Revoke {
        /// Entity to revoke access from.
        entity: Expr,
        /// Secret key.
        key: Expr,
    },
}

// =============================================================================
// Cache Statements
// =============================================================================

/// CACHE command.
#[derive(Clone, Debug, PartialEq)]
pub struct CacheStmt {
    /// The cache operation to perform.
    pub operation: CacheOp,
}

/// CACHE operations.
#[derive(Clone, Debug, PartialEq)]
pub enum CacheOp {
    /// Initialize cache: `CACHE INIT`
    Init,
    /// Show cache statistics: `CACHE STATS`
    Stats,
    /// Clear all cache entries: `CACHE CLEAR`
    Clear,
    /// Evict entries: `CACHE EVICT [n]`
    Evict {
        /// Number of entries to evict.
        count: Option<Expr>,
    },
    /// Get cached response: `CACHE GET 'key'`
    Get {
        /// Cache key.
        key: Expr,
    },
    /// Store cache entry: `CACHE PUT 'key' 'value'`
    Put {
        /// Cache key.
        key: Expr,
        /// Value to cache.
        value: Expr,
    },
    /// Semantic cache lookup: `CACHE SEMANTIC GET 'query' [THRESHOLD n]`
    SemanticGet {
        /// Query string.
        query: Expr,
        /// Similarity threshold.
        threshold: Option<Expr>,
    },
    /// Semantic cache store: `CACHE SEMANTIC PUT 'query' 'response' EMBEDDING [vector]`
    SemanticPut {
        /// Query string.
        query: Expr,
        /// Cached response.
        response: Expr,
        /// Embedding vector.
        embedding: Vec<Expr>,
    },
}

// =============================================================================
// Cluster Statements
// =============================================================================

/// CLUSTER command.
#[derive(Clone, Debug, PartialEq)]
pub struct ClusterStmt {
    /// The cluster operation to perform.
    pub operation: ClusterOp,
}

/// CLUSTER operations.
#[derive(Clone, Debug, PartialEq)]
pub enum ClusterOp {
    /// Connect to cluster: `CLUSTER CONNECT 'address'`
    Connect {
        /// Cluster address(es).
        addresses: Expr,
    },
    /// Disconnect from cluster: `CLUSTER DISCONNECT`
    Disconnect,
    /// Show cluster status: `CLUSTER STATUS`
    Status,
    /// List cluster nodes: `CLUSTER NODES`
    Nodes,
    /// Show current leader: `CLUSTER LEADER`
    Leader,
}

// =============================================================================
// Blob Storage Statements
// =============================================================================

/// BLOB command.
#[derive(Clone, Debug, PartialEq)]
pub struct BlobStmt {
    /// The blob operation to perform.
    pub operation: BlobOp,
}

/// BLOB operations.
#[derive(Clone, Debug, PartialEq)]
pub enum BlobOp {
    /// Initialize blob store: `BLOB INIT`
    Init,
    /// Store blob: `BLOB PUT 'filename' DATA` or `BLOB PUT 'filename' FROM 'path'`
    Put {
        /// File name for the blob.
        filename: Expr,
        /// Inline data content.
        data: Option<Expr>,
        /// Path to read data from.
        from_path: Option<Expr>,
        /// Additional options.
        options: BlobOptions,
    },
    /// Get blob: `BLOB GET 'artifact_id'` or `BLOB GET 'artifact_id' TO 'path'`
    Get {
        /// Artifact ID.
        artifact_id: Expr,
        /// Optional file path to write to.
        to_path: Option<Expr>,
    },
    /// Delete blob: `BLOB DELETE 'artifact_id'`
    Delete {
        /// Artifact ID.
        artifact_id: Expr,
    },
    /// Show blob info: `BLOB INFO 'artifact_id'`
    Info {
        /// Artifact ID.
        artifact_id: Expr,
    },
    /// Link blob to entity: `BLOB LINK 'artifact_id' TO entity`
    Link {
        /// Artifact ID.
        artifact_id: Expr,
        /// Entity to link to.
        entity: Expr,
    },
    /// Unlink blob from entity: `BLOB UNLINK 'artifact_id' FROM entity`
    Unlink {
        /// Artifact ID.
        artifact_id: Expr,
        /// Entity to unlink from.
        entity: Expr,
    },
    /// Get links: `BLOB LINKS 'artifact_id'`
    Links {
        /// Artifact ID.
        artifact_id: Expr,
    },
    /// Add tag: `BLOB TAG 'artifact_id' 'tag'`
    Tag {
        /// Artifact ID.
        artifact_id: Expr,
        /// Tag to add.
        tag: Expr,
    },
    /// Remove tag: `BLOB UNTAG 'artifact_id' 'tag'`
    Untag {
        /// Artifact ID.
        artifact_id: Expr,
        /// Tag to remove.
        tag: Expr,
    },
    /// Verify integrity: `BLOB VERIFY 'artifact_id'`
    Verify {
        /// Artifact ID.
        artifact_id: Expr,
    },
    /// Run garbage collection: `BLOB GC` or `BLOB GC FULL`
    Gc {
        /// Whether to run full GC.
        full: bool,
    },
    /// Repair blob storage: `BLOB REPAIR`
    Repair,
    /// Show blob statistics: `BLOB STATS`
    Stats,
    /// Set metadata: `BLOB META SET 'artifact_id' 'key' 'value'`
    MetaSet {
        /// Artifact ID.
        artifact_id: Expr,
        /// Metadata key.
        key: Expr,
        /// Metadata value.
        value: Expr,
    },
    /// Get metadata: `BLOB META GET 'artifact_id' 'key'`
    MetaGet {
        /// Artifact ID.
        artifact_id: Expr,
        /// Metadata key.
        key: Expr,
    },
}

/// Options for BLOB PUT.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct BlobOptions {
    /// Content type
    pub content_type: Option<Expr>,
    /// Creator
    pub created_by: Option<Expr>,
    /// Entities to link
    pub link: Vec<Expr>,
    /// Tags to apply
    pub tag: Vec<Expr>,
}

/// BLOBS command (list/query blobs).
#[derive(Clone, Debug, PartialEq)]
pub struct BlobsStmt {
    /// The blobs query operation.
    pub operation: BlobsOp,
}

/// BLOBS operations.
#[derive(Clone, Debug, PartialEq)]
pub enum BlobsOp {
    /// List all blobs: `BLOBS`
    List {
        /// Optional filename pattern.
        pattern: Option<Expr>,
    },
    /// Find blobs for entity: `BLOBS FOR entity`
    For {
        /// Entity to find blobs for.
        entity: Expr,
    },
    /// Find blobs by tag: `BLOBS BY TAG 'tag'`
    ByTag {
        /// Tag to filter by.
        tag: Expr,
    },
    /// Find blobs by content type: `BLOBS WHERE TYPE = 'type'`
    ByType {
        /// Content type to filter by.
        content_type: Expr,
    },
    /// Find similar blobs: `BLOBS SIMILAR TO 'artifact_id' LIMIT n`
    Similar {
        /// Artifact ID to compare against.
        artifact_id: Expr,
        /// Maximum number of results.
        limit: Option<Expr>,
    },
}

// =============================================================================
// Checkpoint Statements
// =============================================================================

/// CHECKPOINT statement: `CHECKPOINT` or `CHECKPOINT 'name'`
#[derive(Clone, Debug, PartialEq)]
pub struct CheckpointStmt {
    /// Optional checkpoint name.
    pub name: Option<Expr>,
}

/// ROLLBACK statement: `ROLLBACK TO 'checkpoint_id'`
#[derive(Clone, Debug, PartialEq)]
pub struct RollbackStmt {
    /// Checkpoint ID or name to roll back to.
    pub target: Expr,
}

/// CHECKPOINTS statement: `CHECKPOINTS` or `CHECKPOINTS LIMIT n`
#[derive(Clone, Debug, PartialEq)]
pub struct CheckpointsStmt {
    /// Maximum number of checkpoints to list.
    pub limit: Option<Expr>,
}

// =============================================================================
// Chain Statements
// =============================================================================

/// CHAIN command.
#[derive(Clone, Debug, PartialEq)]
pub struct ChainStmt {
    /// The chain operation to perform.
    pub operation: ChainOp,
}

/// CHAIN operations.
#[derive(Clone, Debug, PartialEq)]
pub enum ChainOp {
    /// Begin a chain transaction: `BEGIN CHAIN TRANSACTION`
    Begin,
    /// Commit a chain transaction: `COMMIT CHAIN`
    Commit,
    /// Rollback chain to height: `ROLLBACK CHAIN TO height`
    Rollback {
        /// Block height to roll back to.
        height: Expr,
    },
    /// Get chain history for key: `CHAIN HISTORY 'key'`
    History {
        /// Key to get history for.
        key: Expr,
    },
    /// Search chain by similarity: `CHAIN SIMILAR [embedding] LIMIT n`
    Similar {
        /// Embedding vector to search by.
        embedding: Vec<Expr>,
        /// Maximum number of results.
        limit: Option<Expr>,
    },
    /// Get chain drift metrics: `CHAIN DRIFT FROM height TO height`
    Drift {
        /// Starting block height.
        from_height: Expr,
        /// Ending block height.
        to_height: Expr,
    },
    /// Show global codebook: `SHOW CODEBOOK GLOBAL`
    ShowCodebookGlobal,
    /// Show local codebook: `SHOW CODEBOOK LOCAL 'domain'`
    ShowCodebookLocal {
        /// Codebook domain.
        domain: Expr,
    },
    /// Analyze codebook transitions: `ANALYZE CODEBOOK TRANSITIONS`
    AnalyzeTransitions,
    /// Get chain height: `CHAIN HEIGHT`
    Height,
    /// Get chain tip: `CHAIN TIP`
    Tip,
    /// Get block at height: `CHAIN BLOCK height`
    Block {
        /// Block height.
        height: Expr,
    },
    /// Verify chain integrity: `CHAIN VERIFY`
    Verify,
}

// =============================================================================
// Extended Graph Statements
// =============================================================================

/// GRAPH ALGORITHM command.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphAlgorithmStmt {
    /// The graph algorithm to run.
    pub operation: GraphAlgorithmOp,
}

/// Graph algorithm operations.
#[derive(Clone, Debug, PartialEq)]
pub enum GraphAlgorithmOp {
    /// Run `PageRank` centrality.
    PageRank {
        /// Damping factor (default 0.85).
        damping: Option<Expr>,
        /// Convergence tolerance.
        tolerance: Option<Expr>,
        /// Maximum number of iterations.
        max_iterations: Option<Expr>,
        /// Traversal direction.
        direction: Option<Direction>,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Run betweenness centrality.
    BetweennessCentrality {
        /// Fraction of nodes to sample.
        sampling_ratio: Option<Expr>,
        /// Traversal direction.
        direction: Option<Direction>,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Run closeness centrality.
    ClosenessCentrality {
        /// Traversal direction.
        direction: Option<Direction>,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Run eigenvector centrality.
    EigenvectorCentrality {
        /// Maximum number of iterations.
        max_iterations: Option<Expr>,
        /// Convergence tolerance.
        tolerance: Option<Expr>,
        /// Traversal direction.
        direction: Option<Direction>,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Detect communities using the Louvain method.
    LouvainCommunities {
        /// Resolution parameter for community granularity.
        resolution: Option<Expr>,
        /// Maximum number of passes.
        max_passes: Option<Expr>,
        /// Traversal direction.
        direction: Option<Direction>,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Detect communities via label propagation.
    LabelPropagation {
        /// Maximum number of iterations.
        max_iterations: Option<Expr>,
        /// Traversal direction.
        direction: Option<Direction>,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
}

/// GRAPH CONSTRAINT command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphConstraintStmt {
    /// The constraint operation.
    pub operation: GraphConstraintOp,
}

/// Graph constraint operations.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphConstraintOp {
    /// Create a new constraint.
    Create {
        /// Constraint name.
        name: Ident,
        /// Constraint target (node or edge).
        target: ConstraintTarget,
        /// Property to constrain.
        property: Ident,
        /// Type of constraint.
        constraint_type: ConstraintType,
    },
    /// Drop a constraint by name.
    Drop {
        /// Constraint name.
        name: Ident,
    },
    /// List all constraints.
    List,
    /// Get a constraint by name.
    Get {
        /// Constraint name.
        name: Ident,
    },
}

/// Constraint target (NODE or EDGE).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConstraintTarget {
    /// Constraint on nodes.
    Node {
        /// Optional node label filter.
        label: Option<Ident>,
    },
    /// Constraint on edges.
    Edge {
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
}

/// Constraint types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConstraintType {
    /// Unique property values.
    Unique,
    /// Property must exist.
    Exists,
    /// Property must have a specific type.
    Type(String),
}

/// GRAPH INDEX command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphIndexStmt {
    /// The index operation.
    pub operation: GraphIndexOp,
}

/// Graph index operations.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphIndexOp {
    /// Create index on a node property.
    CreateNodeProperty {
        /// Property to index.
        property: Ident,
    },
    /// Create index on an edge property.
    CreateEdgeProperty {
        /// Property to index.
        property: Ident,
    },
    /// Create index on node labels.
    CreateLabel,
    /// Create index on edge types.
    CreateEdgeType,
    /// Drop a node property index.
    DropNode {
        /// Property whose index to drop.
        property: Ident,
    },
    /// Drop an edge property index.
    DropEdge {
        /// Property whose index to drop.
        property: Ident,
    },
    /// Show node indexes.
    ShowNodeIndexes,
    /// Show edge indexes.
    ShowEdgeIndexes,
}

/// GRAPH AGGREGATE command.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphAggregateStmt {
    /// The aggregate operation.
    pub operation: GraphAggregateOp,
}

/// Graph aggregate operations.
#[derive(Clone, Debug, PartialEq)]
pub enum GraphAggregateOp {
    /// Count nodes, optionally filtered by label.
    CountNodes {
        /// Optional label filter.
        label: Option<Ident>,
    },
    /// Count edges, optionally filtered by type.
    CountEdges {
        /// Optional edge type filter.
        edge_type: Option<Ident>,
    },
    /// Aggregate a node property.
    AggregateNodeProperty {
        /// Aggregate function to apply.
        function: AggregateFunction,
        /// Property to aggregate.
        property: Ident,
        /// Optional label filter.
        label: Option<Ident>,
        /// Optional WHERE filter.
        filter: Option<Box<Expr>>,
    },
    /// Aggregate an edge property.
    AggregateEdgeProperty {
        /// Aggregate function to apply.
        function: AggregateFunction,
        /// Property to aggregate.
        property: Ident,
        /// Optional edge type filter.
        edge_type: Option<Ident>,
        /// Optional WHERE filter.
        filter: Option<Box<Expr>>,
    },
}

/// Aggregate functions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AggregateFunction {
    /// Sum of values.
    Sum,
    /// Average of values.
    Avg,
    /// Minimum value.
    Min,
    /// Maximum value.
    Max,
    /// Count of values.
    Count,
}

/// GRAPH PATTERN command.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphPatternStmt {
    /// The pattern operation.
    pub operation: GraphPatternOp,
}

/// Graph pattern operations.
#[derive(Clone, Debug, PartialEq)]
pub enum GraphPatternOp {
    /// Match a pattern and return results.
    Match {
        /// The pattern to match.
        pattern: PatternSpec,
        /// Maximum number of results.
        limit: Option<Expr>,
    },
    /// Count matches of a pattern.
    Count {
        /// The pattern to count.
        pattern: PatternSpec,
    },
    /// Check if a pattern exists.
    Exists {
        /// The pattern to check.
        pattern: PatternSpec,
    },
}

/// Pattern specification for graph matching.
#[derive(Clone, Debug, PartialEq)]
pub struct PatternSpec {
    /// Node patterns in this match.
    pub nodes: Vec<NodePatternSpec>,
    /// Edge patterns in this match.
    pub edges: Vec<EdgePatternSpec>,
}

/// Node pattern in a match.
#[derive(Clone, Debug, PartialEq)]
pub struct NodePatternSpec {
    /// Optional binding alias.
    pub alias: Option<Ident>,
    /// Optional node label filter.
    pub label: Option<Ident>,
    /// Property filters.
    pub properties: Vec<Property>,
}

/// Edge pattern in a match.
#[derive(Clone, Debug, PartialEq)]
pub struct EdgePatternSpec {
    /// Optional binding alias.
    pub alias: Option<Ident>,
    /// Optional edge type filter.
    pub edge_type: Option<Ident>,
    /// Traversal direction.
    pub direction: Direction,
    /// Index of the source node in the pattern.
    pub from_node: usize,
    /// Index of the target node in the pattern.
    pub to_node: usize,
    /// Property filters.
    pub properties: Vec<Property>,
}

/// GRAPH BATCH command.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphBatchStmt {
    /// The batch operation.
    pub operation: GraphBatchOp,
}

/// Graph batch operations.
#[derive(Clone, Debug, PartialEq)]
pub enum GraphBatchOp {
    /// Batch create nodes.
    CreateNodes {
        /// Node definitions.
        nodes: Vec<BatchNodeDef>,
    },
    /// Batch create edges.
    CreateEdges {
        /// Edge definitions.
        edges: Vec<BatchEdgeDef>,
    },
    /// Batch delete nodes by ID.
    DeleteNodes {
        /// Node IDs to delete.
        ids: Vec<Expr>,
    },
    /// Batch delete edges by ID.
    DeleteEdges {
        /// Edge IDs to delete.
        ids: Vec<Expr>,
    },
    /// Batch update node properties.
    UpdateNodes {
        /// Node updates.
        updates: Vec<BatchNodeUpdate>,
    },
}

/// Batch node definition for creation.
#[derive(Clone, Debug, PartialEq)]
pub struct BatchNodeDef {
    /// Node labels.
    pub labels: Vec<Ident>,
    /// Node properties.
    pub properties: Vec<Property>,
}

/// Batch edge definition for creation.
#[derive(Clone, Debug, PartialEq)]
pub struct BatchEdgeDef {
    /// Source node ID.
    pub from_id: Expr,
    /// Target node ID.
    pub to_id: Expr,
    /// Edge type label.
    pub edge_type: Ident,
    /// Edge properties.
    pub properties: Vec<Property>,
}

/// Batch node update definition.
#[derive(Clone, Debug, PartialEq)]
pub struct BatchNodeUpdate {
    /// Node ID to update.
    pub id: Expr,
    /// New properties to set.
    pub properties: Vec<Property>,
}

/// Pagination options for paginated queries.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct PaginationOpts {
    /// Number of results to skip.
    pub skip: Option<Expr>,
    /// Maximum number of results.
    pub limit: Option<Expr>,
    /// Whether to include total count.
    pub count_total: bool,
}

// =============================================================================
// Expressions
// =============================================================================

/// An expression.
#[derive(Clone, Debug, PartialEq)]
pub struct Expr {
    /// The expression kind.
    pub kind: ExprKind,
    /// Source location.
    pub span: Span,
}

impl Expr {
    /// Creates a new expression.
    #[must_use]
    pub const fn new(kind: ExprKind, span: Span) -> Self {
        Self { kind, span }
    }

    /// Creates a boxed expression.
    #[must_use]
    pub fn boxed(kind: ExprKind, span: Span) -> Box<Self> {
        Box::new(Self::new(kind, span))
    }
}

/// Expression variants.
#[derive(Clone, Debug, PartialEq)]
pub enum ExprKind {
    /// Literal value
    Literal(Literal),
    /// Identifier (column name, variable)
    Ident(Ident),
    /// Qualified name (table.column)
    Qualified(Box<Expr>, Ident),
    /// Binary operation
    Binary(Box<Expr>, BinaryOp, Box<Expr>),
    /// Unary operation
    Unary(UnaryOp, Box<Expr>),
    /// Function call
    Call(FunctionCall),
    /// CASE expression
    Case(CaseExpr),
    /// Subquery
    Subquery(Box<SelectStmt>),
    /// EXISTS subquery
    Exists(Box<SelectStmt>),
    /// IN / NOT IN expression
    In {
        /// Expression to test.
        expr: Box<Expr>,
        /// List of values or subquery.
        list: InList,
        /// Whether this is NOT IN.
        negated: bool,
    },
    /// BETWEEN expression
    Between {
        /// Expression to test.
        expr: Box<Expr>,
        /// Lower bound.
        low: Box<Expr>,
        /// Upper bound.
        high: Box<Expr>,
        /// Whether this is NOT BETWEEN.
        negated: bool,
    },
    /// LIKE expression
    Like {
        /// Expression to test.
        expr: Box<Expr>,
        /// LIKE pattern.
        pattern: Box<Expr>,
        /// Whether this is NOT LIKE.
        negated: bool,
    },
    /// IS NULL / IS NOT NULL
    IsNull {
        /// Expression to test.
        expr: Box<Expr>,
        /// Whether this is IS NOT NULL.
        negated: bool,
    },
    /// Array literal
    Array(Vec<Expr>),
    /// Tuple/row literal
    Tuple(Vec<Expr>),
    /// Cast expression
    Cast(Box<Expr>, DataType),
    /// Wildcard (*)
    Wildcard,
    /// Qualified wildcard (table.*)
    QualifiedWildcard(Ident),
}

/// Literal values.
#[derive(Clone, Debug, PartialEq)]
pub enum Literal {
    /// SQL `NULL` literal.
    Null,
    /// Boolean literal (`TRUE` or `FALSE`).
    Boolean(bool),
    /// Integer literal.
    Integer(i64),
    /// Floating-point literal.
    Float(f64),
    /// String literal.
    String(String),
}

/// An identifier.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Ident {
    /// The identifier text.
    pub name: String,
    /// Source location.
    pub span: Span,
}

impl Ident {
    /// Creates a new identifier.
    pub fn new(name: impl Into<String>, span: Span) -> Self {
        Self {
            name: name.into(),
            span,
        }
    }

    /// Creates an identifier with a dummy span.
    pub fn unspanned(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            span: Span::dummy(),
        }
    }
}

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

/// Binary operators.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BinaryOp {
    /// Addition (`+`).
    Add,
    /// Subtraction (`-`).
    Sub,
    /// Multiplication (`*`).
    Mul,
    /// Division (`/`).
    Div,
    /// Modulo (`%`).
    Mod,
    /// Equality (`=`).
    Eq,
    /// Inequality (`!=`).
    Ne,
    /// Less than (`<`).
    Lt,
    /// Less than or equal (`<=`).
    Le,
    /// Greater than (`>`).
    Gt,
    /// Greater than or equal (`>=`).
    Ge,
    /// Logical AND.
    And,
    /// Logical OR.
    Or,
    /// String concatenation (`||`).
    Concat,
    /// Bitwise AND (`&`).
    BitAnd,
    /// Bitwise OR (`|`).
    BitOr,
    /// Bitwise XOR (`^`).
    BitXor,
    /// Left shift (`<<`).
    Shl,
    /// Right shift (`>>`).
    Shr,
}

impl BinaryOp {
    /// Returns the precedence of this operator (higher = binds tighter).
    #[must_use]
    pub const fn precedence(self) -> u8 {
        match self {
            Self::Or => 1,
            Self::And => 2,
            Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge => 3,
            Self::BitOr => 4,
            Self::BitXor => 5,
            Self::BitAnd => 6,
            Self::Shl | Self::Shr => 7,
            Self::Add | Self::Sub | Self::Concat => 8,
            Self::Mul | Self::Div | Self::Mod => 9,
        }
    }

    /// Returns true if this operator is left-associative.
    #[must_use]
    pub const fn is_left_assoc(self) -> bool {
        true
    }
}

impl fmt::Display for BinaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Add => "+",
            Self::Sub => "-",
            Self::Mul => "*",
            Self::Div => "/",
            Self::Mod => "%",
            Self::Eq => "=",
            Self::Ne => "!=",
            Self::Lt => "<",
            Self::Le => "<=",
            Self::Gt => ">",
            Self::Ge => ">=",
            Self::And => "AND",
            Self::Or => "OR",
            Self::Concat => "||",
            Self::BitAnd => "&",
            Self::BitOr => "|",
            Self::BitXor => "^",
            Self::Shl => "<<",
            Self::Shr => ">>",
        };
        write!(f, "{s}")
    }
}

/// Unary operators.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnaryOp {
    /// Logical NOT.
    Not,
    /// Arithmetic negation (`-`).
    Neg,
    /// Bitwise NOT (`~`).
    BitNot,
}

impl fmt::Display for UnaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Not => "NOT",
            Self::Neg => "-",
            Self::BitNot => "~",
        };
        write!(f, "{s}")
    }
}

/// Function call.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionCall {
    /// Function name.
    pub name: Ident,
    /// Function arguments.
    pub args: Vec<Expr>,
    /// Whether DISTINCT was specified.
    pub distinct: bool,
}

/// CASE expression.
#[derive(Clone, Debug, PartialEq)]
pub struct CaseExpr {
    /// Optional CASE operand for simple CASE.
    pub operand: Option<Box<Expr>>,
    /// WHEN...THEN clauses.
    pub when_clauses: Vec<WhenClause>,
    /// Optional ELSE clause.
    pub else_clause: Option<Box<Expr>>,
}

/// WHEN clause in CASE expression.
#[derive(Clone, Debug, PartialEq)]
pub struct WhenClause {
    /// The WHEN condition.
    pub condition: Expr,
    /// The THEN result expression.
    pub result: Expr,
}

/// IN list (values or subquery).
#[derive(Clone, Debug, PartialEq)]
pub enum InList {
    /// List of value expressions.
    Values(Vec<Expr>),
    /// Subquery returning a set.
    Subquery(Box<SelectStmt>),
}

// =============================================================================
// Display implementations
// =============================================================================

impl fmt::Display for DataType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Int => write!(f, "INT"),
            Self::Integer => write!(f, "INTEGER"),
            Self::Bigint => write!(f, "BIGINT"),
            Self::Smallint => write!(f, "SMALLINT"),
            Self::Float => write!(f, "FLOAT"),
            Self::Double => write!(f, "DOUBLE"),
            Self::Real => write!(f, "REAL"),
            Self::Decimal(p, s) => match (p, s) {
                (Some(p), Some(s)) => write!(f, "DECIMAL({p}, {s})"),
                (Some(p), None) => write!(f, "DECIMAL({p})"),
                _ => write!(f, "DECIMAL"),
            },
            Self::Numeric(p, s) => match (p, s) {
                (Some(p), Some(s)) => write!(f, "NUMERIC({p}, {s})"),
                (Some(p), None) => write!(f, "NUMERIC({p})"),
                _ => write!(f, "NUMERIC"),
            },
            Self::Varchar(n) => match n {
                Some(n) => write!(f, "VARCHAR({n})"),
                None => write!(f, "VARCHAR"),
            },
            Self::Char(n) => match n {
                Some(n) => write!(f, "CHAR({n})"),
                None => write!(f, "CHAR"),
            },
            Self::Text => write!(f, "TEXT"),
            Self::Boolean => write!(f, "BOOLEAN"),
            Self::Date => write!(f, "DATE"),
            Self::Time => write!(f, "TIME"),
            Self::Timestamp => write!(f, "TIMESTAMP"),
            Self::Blob => write!(f, "BLOB"),
            Self::Custom(name) => write!(f, "{name}"),
        }
    }
}

impl fmt::Display for JoinKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Inner => "INNER JOIN",
            Self::Left => "LEFT JOIN",
            Self::Right => "RIGHT JOIN",
            Self::Full => "FULL JOIN",
            Self::Cross => "CROSS JOIN",
            Self::Natural => "NATURAL JOIN",
        };
        write!(f, "{s}")
    }
}

impl fmt::Display for SortDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Asc => write!(f, "ASC"),
            Self::Desc => write!(f, "DESC"),
        }
    }
}

impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Outgoing => write!(f, "OUTGOING"),
            Self::Incoming => write!(f, "INCOMING"),
            Self::Both => write!(f, "BOTH"),
        }
    }
}

impl fmt::Display for DistanceMetric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cosine => write!(f, "COSINE"),
            Self::Euclidean => write!(f, "EUCLIDEAN"),
            Self::DotProduct => write!(f, "DOT_PRODUCT"),
        }
    }
}

impl fmt::Display for Literal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => write!(f, "NULL"),
            Self::Boolean(b) => write!(f, "{}", if *b { "TRUE" } else { "FALSE" }),
            Self::Integer(n) => write!(f, "{n}"),
            Self::Float(n) => write!(f, "{n}"),
            Self::String(s) => {
                let escaped = s.replace('\'', "''");
                write!(f, "'{escaped}'")
            },
        }
    }
}

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

    #[test]
    fn test_ident() {
        let ident = Ident::new("users", Span::from_offsets(0, 5));
        assert_eq!(ident.name, "users");
        assert_eq!(format!("{}", ident), "users");

        let unspanned = Ident::unspanned("column");
        assert!(unspanned.span.is_dummy());
    }

    #[test]
    fn test_literal_display() {
        assert_eq!(format!("{}", Literal::Null), "NULL");
        assert_eq!(format!("{}", Literal::Boolean(true)), "TRUE");
        assert_eq!(format!("{}", Literal::Boolean(false)), "FALSE");
        assert_eq!(format!("{}", Literal::Integer(42)), "42");
        assert_eq!(format!("{}", Literal::Float(3.15)), "3.15");
        assert_eq!(
            format!("{}", Literal::String("hello".to_string())),
            "'hello'"
        );
        assert_eq!(
            format!("{}", Literal::String("it's".to_string())),
            "'it''s'"
        );
    }

    #[test]
    fn test_binary_op_precedence() {
        assert!(BinaryOp::Mul.precedence() > BinaryOp::Add.precedence());
        assert!(BinaryOp::Add.precedence() > BinaryOp::Eq.precedence());
        assert!(BinaryOp::Eq.precedence() > BinaryOp::And.precedence());
        assert!(BinaryOp::And.precedence() > BinaryOp::Or.precedence());
    }

    #[test]
    fn test_binary_op_display() {
        assert_eq!(format!("{}", BinaryOp::Add), "+");
        assert_eq!(format!("{}", BinaryOp::Sub), "-");
        assert_eq!(format!("{}", BinaryOp::Mul), "*");
        assert_eq!(format!("{}", BinaryOp::Eq), "=");
        assert_eq!(format!("{}", BinaryOp::And), "AND");
        assert_eq!(format!("{}", BinaryOp::Or), "OR");
    }

    #[test]
    fn test_unary_op_display() {
        assert_eq!(format!("{}", UnaryOp::Not), "NOT");
        assert_eq!(format!("{}", UnaryOp::Neg), "-");
        assert_eq!(format!("{}", UnaryOp::BitNot), "~");
    }

    #[test]
    fn test_data_type_display() {
        assert_eq!(format!("{}", DataType::Int), "INT");
        assert_eq!(format!("{}", DataType::Varchar(Some(255))), "VARCHAR(255)");
        assert_eq!(format!("{}", DataType::Varchar(None)), "VARCHAR");
        assert_eq!(
            format!("{}", DataType::Decimal(Some(10), Some(2))),
            "DECIMAL(10, 2)"
        );
        assert_eq!(
            format!("{}", DataType::Decimal(Some(10), None)),
            "DECIMAL(10)"
        );
        assert_eq!(format!("{}", DataType::Custom("UUID".to_string())), "UUID");
    }

    #[test]
    fn test_join_kind_display() {
        assert_eq!(format!("{}", JoinKind::Inner), "INNER JOIN");
        assert_eq!(format!("{}", JoinKind::Left), "LEFT JOIN");
        assert_eq!(format!("{}", JoinKind::Right), "RIGHT JOIN");
        assert_eq!(format!("{}", JoinKind::Full), "FULL JOIN");
        assert_eq!(format!("{}", JoinKind::Cross), "CROSS JOIN");
    }

    #[test]
    fn test_direction_display() {
        assert_eq!(format!("{}", Direction::Outgoing), "OUTGOING");
        assert_eq!(format!("{}", Direction::Incoming), "INCOMING");
        assert_eq!(format!("{}", Direction::Both), "BOTH");
    }

    #[test]
    fn test_distance_metric_display() {
        assert_eq!(format!("{}", DistanceMetric::Cosine), "COSINE");
        assert_eq!(format!("{}", DistanceMetric::Euclidean), "EUCLIDEAN");
        assert_eq!(format!("{}", DistanceMetric::DotProduct), "DOT_PRODUCT");
    }

    #[test]
    fn test_sort_direction_default() {
        assert_eq!(SortDirection::default(), SortDirection::Asc);
    }

    #[test]
    fn test_direction_default() {
        assert_eq!(Direction::default(), Direction::Outgoing);
    }

    #[test]
    fn test_distance_metric_default() {
        assert_eq!(DistanceMetric::default(), DistanceMetric::Cosine);
    }

    #[test]
    fn test_path_algorithm_default() {
        assert_eq!(PathAlgorithm::default(), PathAlgorithm::Shortest);
    }

    #[test]
    fn test_expr_boxed() {
        let expr = Expr::boxed(
            ExprKind::Literal(Literal::Integer(42)),
            Span::from_offsets(0, 2),
        );
        assert!(matches!(expr.kind, ExprKind::Literal(Literal::Integer(42))));
    }

    #[test]
    fn test_statement_new() {
        let stmt = Statement::new(StatementKind::Empty, Span::from_offsets(0, 1));
        assert!(matches!(stmt.kind, StatementKind::Empty));
    }

    #[test]
    fn test_binary_op_left_assoc() {
        assert!(BinaryOp::Add.is_left_assoc());
        assert!(BinaryOp::Mul.is_left_assoc());
        assert!(BinaryOp::And.is_left_assoc());
    }

    #[test]
    fn test_binary_op_display_comprehensive() {
        assert_eq!(format!("{}", BinaryOp::Div), "/");
        assert_eq!(format!("{}", BinaryOp::Mod), "%");
        assert_eq!(format!("{}", BinaryOp::Ne), "!=");
        assert_eq!(format!("{}", BinaryOp::Lt), "<");
        assert_eq!(format!("{}", BinaryOp::Le), "<=");
        assert_eq!(format!("{}", BinaryOp::Gt), ">");
        assert_eq!(format!("{}", BinaryOp::Ge), ">=");
        assert_eq!(format!("{}", BinaryOp::Concat), "||");
        assert_eq!(format!("{}", BinaryOp::BitAnd), "&");
        assert_eq!(format!("{}", BinaryOp::BitOr), "|");
        assert_eq!(format!("{}", BinaryOp::BitXor), "^");
        assert_eq!(format!("{}", BinaryOp::Shl), "<<");
        assert_eq!(format!("{}", BinaryOp::Shr), ">>");
    }

    #[test]
    fn test_data_type_display_comprehensive() {
        assert_eq!(format!("{}", DataType::Integer), "INTEGER");
        assert_eq!(format!("{}", DataType::Bigint), "BIGINT");
        assert_eq!(format!("{}", DataType::Smallint), "SMALLINT");
        assert_eq!(format!("{}", DataType::Float), "FLOAT");
        assert_eq!(format!("{}", DataType::Double), "DOUBLE");
        assert_eq!(format!("{}", DataType::Real), "REAL");
        assert_eq!(format!("{}", DataType::Text), "TEXT");
        assert_eq!(format!("{}", DataType::Boolean), "BOOLEAN");
        assert_eq!(format!("{}", DataType::Date), "DATE");
        assert_eq!(format!("{}", DataType::Time), "TIME");
        assert_eq!(format!("{}", DataType::Timestamp), "TIMESTAMP");
        assert_eq!(format!("{}", DataType::Blob), "BLOB");
        assert_eq!(format!("{}", DataType::Char(Some(10))), "CHAR(10)");
        assert_eq!(format!("{}", DataType::Char(None)), "CHAR");
        assert_eq!(format!("{}", DataType::Decimal(None, None)), "DECIMAL");
        assert_eq!(
            format!("{}", DataType::Numeric(Some(5), Some(2))),
            "NUMERIC(5, 2)"
        );
        assert_eq!(
            format!("{}", DataType::Numeric(Some(5), None)),
            "NUMERIC(5)"
        );
        assert_eq!(format!("{}", DataType::Numeric(None, None)), "NUMERIC");
    }

    #[test]
    fn test_binary_op_precedence_comprehensive() {
        // Test precedence relationships
        assert!(BinaryOp::Or.precedence() < BinaryOp::And.precedence());
        assert!(BinaryOp::And.precedence() < BinaryOp::Eq.precedence());
        // Eq and Lt have the same precedence (both comparison)
        assert_eq!(BinaryOp::Eq.precedence(), BinaryOp::Lt.precedence());
        assert!(BinaryOp::Lt.precedence() < BinaryOp::Add.precedence());
        assert!(BinaryOp::Add.precedence() < BinaryOp::Mul.precedence());
        assert!(BinaryOp::Concat.precedence() > 0);
    }

    #[test]
    fn test_nulls_order_variants() {
        // Test that NullsOrder enum works
        let first = NullsOrder::First;
        let last = NullsOrder::Last;
        assert_ne!(first, last);
    }

    #[test]
    fn test_column_constraint_variants() {
        let pk = ColumnConstraint::PrimaryKey;
        let nn = ColumnConstraint::NotNull;
        let u = ColumnConstraint::Unique;
        assert_ne!(pk, nn);
        assert_ne!(nn, u);
    }

    #[test]
    fn test_join_kind_display_all() {
        assert!(format!("{}", JoinKind::Cross).contains("CROSS"));
        assert!(format!("{}", JoinKind::Natural).contains("NATURAL"));
        assert!(format!("{}", JoinKind::Full).contains("FULL"));
    }

    #[test]
    fn test_literal_display_all() {
        assert_eq!(format!("{}", Literal::Float(3.15)), "3.15");
        assert_eq!(format!("{}", Literal::Boolean(false)), "FALSE");
    }

    #[test]
    fn test_sort_direction_display() {
        assert_eq!(format!("{}", SortDirection::Asc), "ASC");
        assert_eq!(format!("{}", SortDirection::Desc), "DESC");
    }

    #[test]
    fn test_binary_op_precedence_bitwise() {
        // Bitwise operators have specific precedence
        assert_eq!(BinaryOp::BitOr.precedence(), 4);
        assert_eq!(BinaryOp::BitXor.precedence(), 5);
        assert_eq!(BinaryOp::BitAnd.precedence(), 6);
        assert_eq!(BinaryOp::Shl.precedence(), 7);
        assert_eq!(BinaryOp::Shr.precedence(), 7);
        // Bitwise ops come between comparison and arithmetic
        assert!(BinaryOp::Eq.precedence() < BinaryOp::BitOr.precedence());
        assert!(BinaryOp::BitAnd.precedence() < BinaryOp::Shl.precedence());
        assert!(BinaryOp::Shr.precedence() < BinaryOp::Add.precedence());
    }
}