solidb 1.2.2

A lightweight, high-performance structured database server written in Rust.
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
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A single Common Table Expression (CTE)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CteClause {
    /// CTE name (e.g., "temp" in "WITH temp AS (...)")
    pub name: String,
    /// Optional column names: WITH temp(col1, col2) AS (...)
    pub columns: Vec<String>,
    /// Whether this is a recursive CTE
    pub recursive: bool,
    /// The CTE body query
    pub query: Box<Query>,
}

/// WITH clause containing one or more CTEs
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WithClause {
    pub ctes: Vec<CteClause>,
}

/// Set operation combining two query blocks: `a UNION b`, `a INTERSECT c`, ...
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SetOperator {
    /// UNION - concatenates and removes duplicates
    Union,
    /// UNION ALL - concatenates keeping duplicates
    UnionAll,
    /// INTERSECT - rows present in both sides, duplicates removed
    Intersect,
    /// EXCEPT - rows of the left side not present in the right side, duplicates removed
    Except,
}

/// One operand on the right-hand side of a set operation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SetOperationClause {
    pub op: SetOperator,
    pub query: Box<Query>,
}

impl SetOperator {
    /// True for the `ALL` variants, which keep duplicate rows
    pub fn is_all(&self) -> bool {
        matches!(self, SetOperator::UnionAll)
    }
}

/// AST node for a complete SDBQL query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Query {
    /// Optional WITH clause for CTEs (Common Table Expressions)
    pub with_clause: Option<WithClause>,
    /// LET clauses for variable bindings (executed first, before any FOR)
    pub let_clauses: Vec<LetClause>,
    /// Multiple FOR clauses for JOINs (nested loops)
    pub for_clauses: Vec<ForClause>,
    /// JOIN clauses for cross-collection queries
    pub join_clauses: Vec<JoinClause>,
    /// Multiple FILTER clauses (can reference any FOR variable)
    pub filter_clauses: Vec<FilterClause>,
    pub sort_clause: Option<SortClause>,
    pub limit_clause: Option<LimitClause>,
    /// RETURN clause is optional - queries with only mutations (INSERT/UPDATE/REMOVE) don't need it
    pub return_clause: Option<ReturnClause>,
    /// Optional CREATE STREAM clause (wraps the query definition)
    pub create_stream_clause: Option<CreateStreamClause>,
    /// Optional CREATE MATERIALIZED VIEW clause
    pub create_materialized_view_clause: Option<CreateMaterializedViewClause>,
    /// Optional REFRESH MATERIALIZED VIEW clause
    pub refresh_materialized_view_clause: Option<RefreshMaterializedViewClause>,
    /// Optional WINDOW clause for stream processing
    pub window_clause: Option<WindowClause>,

    /// `LET` bindings written *after* `LIMIT`, evaluated on the surviving rows.
    ///
    /// They are kept apart from `body_clauses` because their position is the
    /// whole point: a `LET` before `LIMIT` is computed for every row the query
    /// touches, one after `LIMIT` only for the rows that survive it. Folding
    /// them into the body would accept the syntax and quietly do the expensive
    /// thing — on a page of fifty rows out of five thousand, a correlated
    /// subquery would run a hundred times too often.
    pub post_limit_lets: Vec<LetClause>,

    /// Ordered body clauses (FOR, LET, FILTER) preserving declaration order
    /// This enables correlated subqueries where LET can reference outer FOR variables
    pub body_clauses: Vec<BodyClause>,

    /// Set operations applied after this query block: `q1 UNION q2 INTERSECT q3`
    /// is parsed as `q1` with `set_operations = [UNION q2, INTERSECT q3]`.
    #[serde(default)]
    pub set_operations: Vec<SetOperationClause>,
}

impl Query {
    /// True if executing this query writes data (INSERT/UPDATE/UPSERT/REMOVE
    /// clauses, stream or materialized-view DDL). Used to decide whether a
    /// principal needs Write rather than Read permission.
    pub fn has_mutations(&self) -> bool {
        if self.body_clauses.iter().any(|clause| {
            matches!(
                clause,
                BodyClause::Insert(_)
                    | BodyClause::Update(_)
                    | BodyClause::Upsert(_)
                    | BodyClause::Remove(_)
            )
        }) || self.create_stream_clause.is_some()
            || self.create_materialized_view_clause.is_some()
            || self.refresh_materialized_view_clause.is_some()
            || self
                .set_operations
                .iter()
                .any(|op| op.query.has_mutations())
            || self
                .with_clause
                .as_ref()
                .is_some_and(|with| with.ctes.iter().any(|cte| cte.query.has_mutations()))
            || self
                .create_materialized_view_clause
                .as_ref()
                .is_some_and(|c| c.query.has_mutations())
        {
            return true;
        }

        // A mutation can also hide inside an *expression*: a parenthesised
        // subquery (`RETURN (FOR e IN c INSERT {} INTO c)`) is executed by the
        // full body executor, and the catalog builtins below write `_views` /
        // `_graphs` directly. Neither appears in `body_clauses`, so a check
        // that only walked clauses classified them as reads and `/cursor`
        // never upgraded the caller to Write.
        self.expressions().any(expression_mutates)
    }

    /// Every expression this query block owns directly.
    ///
    /// Not recursive into nested `Query` values — [`expression_mutates`]
    /// handles that by calling [`Self::has_mutations`] on subqueries — but it
    /// must cover every field that can carry an `Expression`, or a mutation
    /// parked in the uncovered one is invisible to authorization.
    fn expressions(&self) -> impl Iterator<Item = &Expression> {
        // `post_limit_lets` belong here too: a mutating subquery written after
        // LIMIT (`... LIMIT 1 LET x = (FOR d IN c REMOVE d IN c) RETURN x`)
        // is still a write.
        let let_exprs = self
            .let_clauses
            .iter()
            .chain(self.post_limit_lets.iter())
            .map(|l| &l.expression);
        let for_exprs = self
            .for_clauses
            .iter()
            .flat_map(|f| f.source_expression.iter().chain(f.system_time.iter()));
        let valid_time = self
            .for_clauses
            .iter()
            .filter_map(|f| f.valid_time.as_ref());
        let filter_exprs = self.filter_clauses.iter().map(|f| &f.expression);
        let sort_exprs = self
            .sort_clause
            .iter()
            .flat_map(|s| s.fields.iter().map(|(e, _)| e));
        let limit_exprs = self
            .limit_clause
            .iter()
            .flat_map(|l| std::iter::once(&l.offset).chain(l.count.iter()));
        let return_expr = self.return_clause.iter().map(|r| &r.expression);
        let join_exprs = self.join_clauses.iter().flat_map(join_expressions);
        let body_exprs = self.body_clauses.iter().flat_map(body_clause_expressions);

        let_exprs
            .chain(for_exprs)
            .chain(valid_time.flat_map(valid_time_expressions))
            .chain(filter_exprs)
            .chain(sort_exprs)
            .chain(limit_exprs)
            .chain(return_expr)
            .chain(join_exprs)
            .chain(body_exprs)
    }
}

/// SDBQL functions that write server state rather than compute a value.
///
/// These take effect through `executor::catalog`, which edits the `_views` and
/// `_graphs` catalog collections. They are ordinary function calls, so no
/// clause-level check can see them: without this list a read-only principal
/// ran `RETURN DROP_GRAPH("prod")` or replaced a materialized view's
/// definition through `/cursor`, which is classified Read.
pub const MUTATING_FUNCTIONS: [&str; 4] =
    ["CREATE_VIEW", "DROP_VIEW", "CREATE_GRAPH", "DROP_GRAPH"];

/// True when `name` (case-insensitively) is a state-changing builtin.
pub fn is_mutating_function(name: &str) -> bool {
    MUTATING_FUNCTIONS
        .iter()
        .any(|f| name.eq_ignore_ascii_case(f))
}

/// Builtins that dispatch to another function chosen by their first argument.
pub const DYNAMIC_CALL_FUNCTIONS: [&str; 2] = ["APPLY", "CALL"];

fn is_dynamic_call_function(name: &str) -> bool {
    DYNAMIC_CALL_FUNCTIONS
        .iter()
        .any(|f| name.eq_ignore_ascii_case(f))
}

/// True when calling `name` with `args` changes server state.
///
/// Beyond [`MUTATING_FUNCTIONS`]:
/// - `ROW_POLICY(coll, pred)` (the two-argument setter) rewrites the
///   collection's row policy; the one-argument getter is a read (audit C4).
/// - `APPLY` / `CALL` run whatever function their first argument names, so
///   they are writes unless that argument is a string literal naming a
///   function that is itself not a write (audit A11). `ROW_POLICY` and nested
///   dynamic calls through them count as writes, since the arity of the inner
///   call is not visible here.
pub fn function_call_mutates(name: &str, args: &[Expression]) -> bool {
    if is_mutating_function(name) {
        return true;
    }
    if name.eq_ignore_ascii_case("ROW_POLICY") {
        return args.len() >= 2;
    }
    if is_dynamic_call_function(name) {
        return match args.first() {
            Some(Expression::Literal(Value::String(inner))) => {
                is_mutating_function(inner)
                    || is_dynamic_call_function(inner)
                    || inner.eq_ignore_ascii_case("ROW_POLICY")
            }
            _ => true,
        };
    }
    false
}

fn valid_time_expressions(spec: &ValidTimeSpec) -> Vec<&Expression> {
    match spec {
        ValidTimeSpec::AsOf(e) => vec![e],
        ValidTimeSpec::Range { from, to } => vec![from, to],
    }
}

fn join_expressions(join: &JoinClause) -> Vec<&Expression> {
    let mut out = vec![&join.condition];
    if let Some(asof) = &join.asof {
        out.push(&asof.left_time);
        out.push(&asof.right_time);
        out.extend(asof.tolerance.iter());
    }
    out
}

fn body_clause_expressions(clause: &BodyClause) -> Vec<&Expression> {
    match clause {
        BodyClause::For(f) => f
            .source_expression
            .iter()
            .chain(f.system_time.iter())
            .chain(
                f.valid_time
                    .iter()
                    .flat_map(|v| valid_time_expressions(v).into_iter()),
            )
            .collect(),
        BodyClause::Let(l) => vec![&l.expression],
        BodyClause::Filter(f) | BodyClause::Search(f) => vec![&f.expression],
        BodyClause::Insert(i) => vec![&i.document],
        BodyClause::Update(u) => vec![&u.selector, &u.changes],
        BodyClause::Upsert(u) => vec![&u.search, &u.insert, &u.update],
        BodyClause::Remove(r) => vec![&r.selector],
        BodyClause::Join(j) => join_expressions(j),
        BodyClause::GraphTraversal(g) => std::iter::once(&g.start_vertex)
            .chain(g.prune.iter())
            .collect(),
        BodyClause::ShortestPath(s) => vec![&s.start_vertex, &s.end_vertex],
        BodyClause::Collect(c) => c
            .group_vars
            .iter()
            .map(|(_, e)| e)
            .chain(c.aggregates.iter().filter_map(|a| a.argument.as_ref()))
            .chain(c.into_expr.iter())
            .collect(),
        BodyClause::Window(_) => Vec::new(),
    }
}

/// True when evaluating `expr` can write: it contains a mutating subquery or
/// a state-changing builtin, at any depth.
pub fn expression_mutates(expr: &Expression) -> bool {
    match expr {
        Expression::Subquery(q) => q.has_mutations(),
        Expression::FunctionCall { name, args } => {
            function_call_mutates(name, args) || args.iter().any(expression_mutates)
        }
        Expression::WindowFunctionCall {
            function,
            arguments,
            over_clause,
        } => {
            is_mutating_function(function)
                || arguments.iter().any(expression_mutates)
                || over_clause.partition_by.iter().any(expression_mutates)
                || over_clause
                    .order_by
                    .iter()
                    .any(|(e, _)| expression_mutates(e))
        }
        Expression::FieldAccess(base, _)
        | Expression::OptionalFieldAccess(base, _)
        | Expression::ArraySpreadAccess(base, _) => expression_mutates(base),
        Expression::DynamicFieldAccess(a, b)
        | Expression::ArrayAccess(a, b)
        | Expression::Range(a, b)
        | Expression::Pipeline { left: a, right: b } => {
            expression_mutates(a) || expression_mutates(b)
        }
        Expression::BinaryOp { left, right, .. } => {
            expression_mutates(left) || expression_mutates(right)
        }
        Expression::UnaryOp { operand, .. } => expression_mutates(operand),
        Expression::Object(fields) => fields.iter().any(|(_, e)| expression_mutates(e)),
        Expression::Array(items) => items.iter().any(expression_mutates),
        Expression::Ternary {
            condition,
            true_expr,
            false_expr,
        } => {
            expression_mutates(condition)
                || expression_mutates(true_expr)
                || expression_mutates(false_expr)
        }
        Expression::Case {
            operand,
            when_clauses,
            else_clause,
        } => {
            operand.as_deref().is_some_and(expression_mutates)
                || when_clauses
                    .iter()
                    .any(|(c, r)| expression_mutates(c) || expression_mutates(r))
                || else_clause.as_deref().is_some_and(expression_mutates)
        }
        Expression::Lambda { body, .. } => expression_mutates(body),
        Expression::TemplateString { parts } => parts.iter().any(|p| match p {
            TemplateStringPart::Expression(e) => expression_mutates(e),
            TemplateStringPart::Literal(_) => false,
        }),
        Expression::ArrayComparison {
            quantifier,
            left,
            right,
            ..
        } => {
            expression_mutates(left)
                || expression_mutates(right)
                || matches!(quantifier, ArrayQuantifier::AtLeast(n) if expression_mutates(n))
        }
        Expression::ArrayInline {
            base,
            filter,
            limit,
            projection,
            ..
        } => {
            expression_mutates(base)
                || filter.as_deref().is_some_and(expression_mutates)
                || limit
                    .as_ref()
                    .is_some_and(|(o, c)| expression_mutates(o) || expression_mutates(c))
                || projection.as_deref().is_some_and(expression_mutates)
        }
        Expression::Variable(_) | Expression::BindVariable(_) | Expression::Literal(_) => false,
    }
}

/// True when `name` is read as a variable anywhere in `query`, subqueries,
/// CTE bodies and set-operation operands included.
///
/// The parser uses it to decide whether a mutation must bind `OLD` / `NEW`:
/// binding `OLD` costs an extra document read per row, and `NEW` on a bulk
/// write forces the per-row path, so neither is paid for when nothing reads
/// it. Shadowing is ignored, which can only over-report.
pub fn query_references_variable(query: &Query, name: &str) -> bool {
    query
        .expressions()
        .any(|e| expression_references_variable(e, name))
        || query
            .set_operations
            .iter()
            .any(|op| query_references_variable(&op.query, name))
        || query.with_clause.as_ref().is_some_and(|with| {
            with.ctes
                .iter()
                .any(|cte| query_references_variable(&cte.query, name))
        })
}

/// True when `expr` reads the variable `name` at any depth.
pub fn expression_references_variable(expr: &Expression, name: &str) -> bool {
    match expr {
        Expression::Variable(v) => v == name,
        Expression::Subquery(q) => query_references_variable(q, name),
        other => {
            let mut found = false;
            other.for_each_child(&mut |child| {
                found = found || expression_references_variable(child, name);
            });
            found
        }
    }
}

/// A clause that can appear in the query body (preserves order for correlated subqueries)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BodyClause {
    For(ForClause),
    Let(LetClause),
    Filter(FilterClause),
    Insert(InsertClause),
    Update(UpdateClause),
    Upsert(UpsertClause),
    Remove(RemoveClause),
    Join(JoinClause),
    GraphTraversal(GraphTraversalClause),
    ShortestPath(ShortestPathClause),
    Collect(CollectClause),
    Window(WindowClause),
    /// Scored filter (`SEARCH expr`); numeric scores are stored as `__search_score`.
    Search(FilterClause),
}

/// Edge direction for graph traversals
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EdgeDirection {
    /// Follow edges where start_vertex == _from
    Outbound,
    /// Follow edges where start_vertex == _to
    Inbound,
    /// Follow edges in both directions
    Any,
}

/// FOR vertex[, edge] IN [depth..depth] OUTBOUND|INBOUND|ANY start_vertex edge_collection
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GraphTraversalClause {
    /// Variable for the visited vertices
    pub vertex_var: String,
    /// Optional variable for the edges (can be omitted)
    pub edge_var: Option<String>,
    /// Direction of traversal
    pub direction: EdgeDirection,
    /// Starting vertex (expression like "users/alice" or @start)
    pub start_vertex: Expression,
    /// Edge collection to traverse
    pub edge_collection: String,
    /// Minimum traversal depth (default 1)
    pub min_depth: usize,
    /// Maximum traversal depth (default 1)
    pub max_depth: usize,
    /// Optional path variable `FOR v, e, p`
    #[serde(default)]
    pub path_var: Option<String>,
    /// Stop expanding when this expression is true
    #[serde(default)]
    pub prune: Option<Expression>,
    /// `OPTIONS { uniqueVertices, uniqueEdges, order }`
    #[serde(default)]
    pub options: TraversalOptions,
}

/// Vertex uniqueness during a traversal (`OPTIONS { uniqueVertices: ... }`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum UniqueVertices {
    /// A vertex may be visited again on another path, or even on the same one
    /// (only `uniqueEdges` and the depth bound stop the walk).
    None,
    /// A vertex appears at most once on any single path.
    Path,
    /// A vertex is visited at most once per start vertex. The historical
    /// SoliDB behaviour, and the default when no `order: "dfs"` is asked for.
    #[default]
    Global,
}

/// Edge uniqueness during a traversal (`OPTIONS { uniqueEdges: ... }`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum UniqueEdges {
    None,
    /// An edge appears at most once on any single path (AQL's default).
    #[default]
    Path,
}

/// Visit order of a traversal (`OPTIONS { order: "bfs" | "dfs" }`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum TraversalOrder {
    #[default]
    Bfs,
    Dfs,
}

/// Traversal `OPTIONS`. The default reproduces the pre-OPTIONS behaviour:
/// breadth-first with global vertex uniqueness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct TraversalOptions {
    pub unique_vertices: UniqueVertices,
    pub unique_edges: UniqueEdges,
    pub order: TraversalOrder,
}

/// FOR vertex[, edge] IN SHORTEST_PATH start_vertex TO end_vertex OUTBOUND|INBOUND|ANY edge_collection
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShortestPathClause {
    /// Variable for the vertices in the path
    pub vertex_var: String,
    /// Optional variable for the edges in the path
    pub edge_var: Option<String>,
    /// Starting vertex
    pub start_vertex: Expression,
    /// Target vertex
    pub end_vertex: Expression,
    /// Direction of traversal
    pub direction: EdgeDirection,
    /// Edge collection to traverse
    pub edge_collection: String,
    /// Optional numeric edge field used as Dijkstra weight
    #[serde(default)]
    pub weight: Option<String>,
    #[serde(default)]
    pub path_var: Option<String>,
    #[serde(default)]
    pub mode: PathFindMode,
    #[serde(default)]
    pub k: Option<usize>,
    #[serde(default)]
    pub min_len: Option<usize>,
    #[serde(default)]
    pub max_len: Option<usize>,
    #[serde(default)]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub enum PathFindMode {
    #[default]
    Shortest,
    AllShortest,
    KShortest,
    KPaths,
}

/// CREATE STREAM name AS ...
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateStreamClause {
    pub name: String,
    pub if_not_exists: bool,
}

/// CREATE MATERIALIZED VIEW name [REFRESH "<interval>"] AS ...
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateMaterializedViewClause {
    pub name: String,
    pub if_not_exists: bool,
    /// The query definition
    pub query: Box<Query>,
    /// Optional automatic refresh interval (e.g. "30s", "5m", "1h", "2d", or a
    /// plain number of seconds). When set, a background worker re-runs the view
    /// query on that cadence. `None` = manual `REFRESH MATERIALIZED VIEW` only.
    #[serde(default)]
    pub refresh_schedule: Option<String>,
}

/// REFRESH MATERIALIZED VIEW name
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RefreshMaterializedViewClause {
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum WindowType {
    /// TUMBLING (SIZE "1m") - Fixed non-overlapping windows
    Tumbling,
    /// SLIDING (SIZE "1m") - Sliding windows (hopping)
    Sliding,
}

/// WINDOW TUMBLING (SIZE "1m")
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WindowClause {
    pub window_type: WindowType,
    /// Duration string (e.g., "1m", "30s", "1h")
    pub duration: String,
}

/// LET variable = expression (can be a subquery)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LetClause {
    pub variable: String,
    pub expression: Expression,
}

/// FOR variable IN collection/expression
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ForClause {
    pub variable: String,
    pub collection: String,
    /// Optional: iterate over a variable (e.g., FOR x IN someLetVar)
    pub source_variable: Option<String>,
    /// Optional: iterate over an expression (e.g., FOR i IN 1..5)
    pub source_expression: Option<Expression>,
    /// `SYSTEM_TIME AS OF` timestamp expression (epoch ms or RFC3339)
    #[serde(default)]
    pub system_time: Option<Expression>,
    /// Application valid-time filter (`valid_from` / `valid_to` fields)
    #[serde(default)]
    pub valid_time: Option<ValidTimeSpec>,
    /// `FOR ... OPTIONS { indexHint, forceIndexHint }`, for the optimizer.
    #[serde(default)]
    pub options: Option<ForOptions>,
}

/// `FOR doc IN coll OPTIONS { indexHint: "idx" | ["a", "b"], forceIndexHint: bool }`.
///
/// Parsed here and consumed by the index selector (`executor::index_opt`):
/// when `index_hint` is non-empty the selector should prefer the named
/// indexes, in order, over its own choice; with `force_index_hint` it should
/// fail the query instead of falling back when none of them can serve the
/// FILTER.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ForOptions {
    /// Index names, in order of preference. Empty = no hint.
    #[serde(default)]
    pub index_hint: Vec<String>,
    #[serde(default)]
    pub force_index_hint: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ValidTimeSpec {
    AsOf(Expression),
    Range { from: Expression, to: Expression },
}

/// FILTER expression
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilterClause {
    pub expression: Expression,
}

/// `INSERT` behaviour when the document's `_key` already exists
/// (`OPTIONS { overwriteMode: ... }`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OverwriteMode {
    /// Keep the stored document; the row's `NEW` is null.
    Ignore,
    /// Replace the stored document wholesale.
    Replace,
    /// Merge into the stored document, like `UPDATE`.
    Update,
    /// Fail with a conflict (the default).
    Conflict,
}

/// `OPTIONS { ... }` on INSERT / UPDATE / REPLACE / UPSERT / REMOVE.
///
/// Every field defaults to the behaviour the statement has without OPTIONS,
/// so `MutationOptions::default()` changes nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct MutationOptions {
    /// Skip rows whose document-level write fails (missing document, key or
    /// unique conflict, invalid document) instead of failing the query. The
    /// skipped row produces no output.
    #[serde(default)]
    pub ignore_errors: bool,
    /// `keepNull: false` removes attributes the patch sets to `null`
    /// (UPDATE, UPSERT's update branch, INSERT with overwriteMode "update").
    /// `None` = keep them (store `null`), the default.
    #[serde(default)]
    pub keep_null: Option<bool>,
    /// `mergeObjects: true` merges nested objects recursively; `false` (and
    /// `None`, SoliDB's default) replaces a top-level attribute wholesale.
    #[serde(default)]
    pub merge_objects: Option<bool>,
    /// INSERT only. `None` = conflict.
    #[serde(default)]
    pub overwrite_mode: Option<OverwriteMode>,
}

impl MutationOptions {
    /// True when UPDATE must compute the merged document itself instead of
    /// handing the patch to the storage layer's shallow merge.
    pub fn needs_custom_merge(&self) -> bool {
        self.keep_null == Some(false) || self.merge_objects == Some(true)
    }
}

/// INSERT document INTO|IN collection [OPTIONS {...}]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InsertClause {
    pub document: Expression,
    pub collection: String,
    #[serde(default)]
    pub options: MutationOptions,
    /// Something in the query block reads `NEW` / `OLD`: bind them per row.
    /// Set by the parser (see [`query_references_variable`]).
    #[serde(default)]
    pub binds_new: bool,
    #[serde(default)]
    pub binds_old: bool,
}

/// `UPDATE doc [WITH changes] IN collection [OPTIONS {...}]`, and
/// `REPLACE doc [WITH replacement] IN collection` (`replace = true`).
///
/// Without `WITH`, `changes` is a copy of `selector`: the document names its
/// own `_key` and is the patch (or the replacement).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpdateClause {
    /// The document or key to update (usually a variable like `doc` or `doc._key`)
    pub selector: Expression,
    /// The changes to apply (object expression)
    pub changes: Expression,
    /// The collection to update in
    pub collection: String,
    /// `REPLACE`: the stored document becomes `changes` (system attributes
    /// aside) instead of having `changes` merged into it.
    #[serde(default)]
    pub replace: bool,
    #[serde(default)]
    pub options: MutationOptions,
    /// See [`InsertClause::binds_new`].
    #[serde(default)]
    pub binds_old: bool,
    #[serde(default)]
    pub binds_new: bool,
}

/// UPSERT search INSERT insert UPDATE|REPLACE update IN collection [OPTIONS {...}]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpsertClause {
    pub search: Expression,
    pub insert: Expression,
    pub update: Expression,
    pub collection: String,
    pub replace: bool,
    #[serde(default)]
    pub options: MutationOptions,
    /// See [`InsertClause::binds_new`]. `NEW` is always bound for UPSERT.
    #[serde(default)]
    pub binds_old: bool,
}

/// REMOVE document IN collection [OPTIONS {...}]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RemoveClause {
    /// The document or key to remove (usually a variable like `doc` or `doc._key`)
    pub selector: Expression,
    /// The collection to remove from
    pub collection: String,
    #[serde(default)]
    pub options: MutationOptions,
    /// See [`InsertClause::binds_new`].
    #[serde(default)]
    pub binds_old: bool,
}

/// JOIN type (INNER vs LEFT/RIGHT/FULL)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum JoinType {
    Inner,
    Left,
    Right,
    FullOuter,
    Asof,
}

/// As-of join time alignment
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AsofStrategy {
    Backward,
    Forward,
    Nearest,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AsofSpec {
    pub left_time: Expression,
    pub right_time: Expression,
    pub strategy: AsofStrategy,
    pub tolerance: Option<Expression>,
}

/// JOIN variable IN collection ON condition
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JoinClause {
    /// Type of join (INNER, LEFT, etc.)
    pub join_type: JoinType,
    /// Variable to bind joined documents to
    pub variable: String,
    /// Collection to join with
    pub collection: String,
    /// Join condition (e.g., user._key == orders.user_key)
    pub condition: Expression,
    #[serde(default)]
    pub asof: Option<AsofSpec>,
}

/// COLLECT var = expr [INTO group [KEEP var1, var2]] [WITH COUNT INTO count] [AGGREGATE ...]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CollectClause {
    /// Group variables: (variable_name, expression) pairs
    pub group_vars: Vec<(String, Expression)>,
    /// INTO variable (collects grouped documents into an array)
    pub into_var: Option<String>,
    /// Optional KEEP restriction on the variables stored in the INTO array.
    /// Empty = keep every variable currently in scope (default).
    #[serde(default)]
    pub keep_vars: Vec<String>,
    /// WITH COUNT INTO variable
    pub count_var: Option<String>,
    /// AGGREGATE expressions
    pub aggregates: Vec<AggregateExpr>,
    /// `INTO g = expr`: each group member is `expr` evaluated on the row,
    /// instead of the object of every variable in scope. Exclusive with
    /// `keep_vars`. Only meaningful with `into_var`.
    #[serde(default)]
    pub into_expr: Option<Expression>,
    /// `OPTIONS { method: "hash" | "sorted" }`. `None` behaves as `Sorted`.
    #[serde(default)]
    pub method: Option<CollectMethod>,
}

/// COLLECT grouping method (`OPTIONS { method: ... }`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CollectMethod {
    /// Groups come out in no particular order.
    Hash,
    /// Groups come out sorted by their group values, in `group_vars` order
    /// (AQL's default).
    Sorted,
}

/// Aggregate expression: var = FUNC(expr)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AggregateExpr {
    /// Variable to store the result
    pub variable: String,
    /// Aggregate function name (SUM, AVG, MIN, MAX, COUNT, LENGTH, etc.)
    pub function: String,
    /// Argument expression
    pub argument: Option<Expression>,
}

/// SORT expression [ASC|DESC]
/// Supports both field-based sorting (SORT doc.age) and function-based sorting (SORT BM25(doc.content, "query"))
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SortClause {
    pub fields: Vec<(Expression, bool)>, // (expression, ascending)
}

/// LIMIT [offset,] count -- or a standalone OFFSET, which has no count
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LimitClause {
    pub offset: Expression,
    /// Row count. `None` means "no upper bound" (`OFFSET n` without `LIMIT`):
    /// callers must not substitute a sentinel maximum, because the count is
    /// pushed down into storage scans and index lookups as an allocation hint.
    pub count: Option<Expression>,
}

/// RETURN [DISTINCT] expression
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReturnClause {
    pub expression: Expression,
    /// RETURN DISTINCT - remove duplicate result rows (first occurrence wins)
    #[serde(default)]
    pub distinct: bool,
}

/// Part of a template string (used in AST after parsing)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TemplateStringPart {
    /// Static text between interpolations
    Literal(String),
    /// Parsed expression inside ${...}
    Expression(Box<Expression>),
}

/// Expression types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expression {
    /// Variable reference (e.g., doc)
    Variable(String),

    /// Bind variable reference (e.g., @name) - for parameterized queries
    BindVariable(String),

    /// Field access (e.g., doc.name)
    FieldAccess(Box<Expression>, String),

    /// Optional field access (e.g., doc?.name) - returns null if base is null
    OptionalFieldAccess(Box<Expression>, String),

    /// Dynamic field access (e.g., doc[@fieldName] or doc["name"])
    DynamicFieldAccess(Box<Expression>, Box<Expression>),

    /// Array element access (e.g., arr[0], arr[i])
    ArrayAccess(Box<Expression>, Box<Expression>),

    /// Array spread access (e.g., arr[*].field extracts field from all elements)
    /// field_path is None for bare [*], Some("field.nested") for chained access
    ArraySpreadAccess(Box<Expression>, Option<String>),

    /// Literal value
    Literal(Value),

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

    /// Unary operation
    UnaryOp {
        op: UnaryOperator,
        operand: Box<Expression>,
    },

    /// Object construction
    Object(Vec<(String, Expression)>),

    /// Array construction
    Array(Vec<Expression>),

    /// Range expression (e.g., 1..5 produces [1, 2, 3, 4, 5])
    Range(Box<Expression>, Box<Expression>),

    /// Function call (e.g., DISTANCE(lat1, lon1, lat2, lon2))
    FunctionCall { name: String, args: Vec<Expression> },

    /// Subquery (FOR ... RETURN ...) wrapped in parentheses
    Subquery(Box<Query>),

    /// Ternary conditional (condition ? true_expr : false_expr)
    Ternary {
        condition: Box<Expression>,
        true_expr: Box<Expression>,
        false_expr: Box<Expression>,
    },

    /// CASE expression - SQL-style conditional
    /// Simple form: CASE expr WHEN val1 THEN res1 WHEN val2 THEN res2 ELSE default END
    /// Searched form: CASE WHEN cond1 THEN res1 WHEN cond2 THEN res2 ELSE default END
    Case {
        /// Optional operand for simple CASE (None for searched CASE)
        operand: Option<Box<Expression>>,
        /// List of (condition/value, result) pairs
        when_clauses: Vec<(Expression, Expression)>,
        /// Optional ELSE result
        else_clause: Option<Box<Expression>>,
    },

    /// Pipeline operation (value |> FUNC(args))
    /// Left value becomes first argument to right-side function call
    Pipeline {
        left: Box<Expression>,
        right: Box<Expression>,
    },

    /// Lambda expression (x -> expr) or ((a, b) -> expr)
    /// Used as arguments to higher-order functions like FILTER, MAP
    Lambda {
        params: Vec<String>,
        body: Box<Expression>,
    },

    /// Window function call with OVER clause
    /// Example: ROW_NUMBER() OVER (PARTITION BY doc.region ORDER BY doc.amount DESC)
    WindowFunctionCall {
        function: String,
        arguments: Vec<Expression>,
        over_clause: WindowSpec,
    },

    /// Template string with interpolated expressions: $"Hello ${name}!"
    /// Syntax: $"text ${expression} more text"
    TemplateString { parts: Vec<TemplateStringPart> },

    /// Array comparison operator (AQL): `arr ANY == x`, `arr ALL IN list`,
    /// `arr NONE > 3`, `arr AT LEAST (2) == "a"`.
    ///
    /// `op` is applied between every element of `left` and `right`. A
    /// non-array `left` is `false`; for `IN` / `NOT IN` a non-array `right`
    /// is `false` too. Empty arrays: `ALL` and `NONE` are true, `ANY` false,
    /// `AT LEAST (n)` true only for `n <= 0`.
    ArrayComparison {
        quantifier: ArrayQuantifier,
        left: Box<Expression>,
        /// One of `==`, `!=`, `<`, `<=`, `>`, `>=`, `IN`, `NOT IN`.
        op: BinaryOperator,
        right: Box<Expression>,
    },

    /// Inline array expression (AQL):
    /// `arr[* FILTER cond LIMIT off, n RETURN proj].path`, and `arr[**]`.
    ///
    /// Inside `filter` / `limit` / `projection`, `CURRENT` is the element.
    /// Plain `arr[*]` / `arr[*].path` stay [`Expression::ArraySpreadAccess`].
    ArrayInline {
        base: Box<Expression>,
        /// Number of `*` in the brackets. `2` (`[**]`) flattens the operand
        /// one level before expanding it, `3` two levels, and so on.
        depth: usize,
        filter: Option<Box<Expression>>,
        /// `LIMIT [offset,] count`, as `(offset, count)`.
        limit: Option<(Box<Expression>, Box<Expression>)>,
        projection: Option<Box<Expression>>,
        /// Attribute path written after `]`, read from every result.
        field_path: Option<String>,
    },
}

/// Quantifier of an [`Expression::ArrayComparison`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ArrayQuantifier {
    Any,
    All,
    None,
    /// `AT LEAST (n)`: at least `n` elements satisfy the comparison.
    AtLeast(Box<Expression>),
}

impl Expression {
    /// Call `f` on every direct sub-expression. Subquery bodies are not
    /// descended into — they are queries, not expressions.
    pub fn for_each_child(&self, f: &mut dyn FnMut(&Expression)) {
        match self {
            Expression::Variable(_)
            | Expression::BindVariable(_)
            | Expression::Literal(_)
            | Expression::Subquery(_) => {}
            Expression::FieldAccess(base, _)
            | Expression::OptionalFieldAccess(base, _)
            | Expression::ArraySpreadAccess(base, _) => f(base),
            Expression::DynamicFieldAccess(a, b)
            | Expression::ArrayAccess(a, b)
            | Expression::Range(a, b) => {
                f(a);
                f(b);
            }
            Expression::BinaryOp { left, right, .. } => {
                f(left);
                f(right);
            }
            Expression::UnaryOp { operand, .. } => f(operand),
            Expression::Object(fields) => fields.iter().for_each(|(_, e)| f(e)),
            Expression::Array(items) => items.iter().for_each(&mut *f),
            Expression::FunctionCall { args, .. } => args.iter().for_each(&mut *f),
            Expression::Ternary {
                condition,
                true_expr,
                false_expr,
            } => {
                f(condition);
                f(true_expr);
                f(false_expr);
            }
            Expression::Case {
                operand,
                when_clauses,
                else_clause,
            } => {
                if let Some(o) = operand {
                    f(o);
                }
                for (w, t) in when_clauses {
                    f(w);
                    f(t);
                }
                if let Some(e) = else_clause {
                    f(e);
                }
            }
            Expression::Pipeline { left, right } => {
                f(left);
                f(right);
            }
            Expression::Lambda { body, .. } => f(body),
            Expression::WindowFunctionCall {
                arguments,
                over_clause,
                ..
            } => {
                arguments.iter().for_each(&mut *f);
                over_clause.partition_by.iter().for_each(&mut *f);
                over_clause.order_by.iter().for_each(|(e, _)| f(e));
            }
            Expression::TemplateString { parts } => {
                for p in parts {
                    if let TemplateStringPart::Expression(e) = p {
                        f(e);
                    }
                }
            }
            Expression::ArrayComparison {
                quantifier,
                left,
                right,
                ..
            } => {
                f(left);
                if let ArrayQuantifier::AtLeast(n) = quantifier {
                    f(n);
                }
                f(right);
            }
            Expression::ArrayInline {
                base,
                filter,
                limit,
                projection,
                ..
            } => {
                f(base);
                if let Some(e) = filter {
                    f(e);
                }
                if let Some((o, c)) = limit {
                    f(o);
                    f(c);
                }
                if let Some(e) = projection {
                    f(e);
                }
            }
        }
    }
}

/// Window specification (the OVER clause)
/// Example: OVER (PARTITION BY doc.region ORDER BY doc.date ASC)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WindowSpec {
    /// PARTITION BY expressions (optional) - groups rows into partitions
    pub partition_by: Vec<Expression>,
    /// ORDER BY within the window (optional) - defines row ordering within each partition
    /// Each tuple is (expression, ascending)
    pub order_by: Vec<(Expression, bool)>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BinaryOperator {
    // Comparison
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    /// Vector cosine distance, or three-way compare (−1/0/1).
    Spaceship,
    /// Semantic / trigram match (`a ~ b`). Unary `~` stays bitwise NOT.
    SemanticMatch,
    In,
    NotIn,

    // Logical
    And,
    Or,

    // Arithmetic
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulus, // Adding modulo strictly if needed, but standard request is just ops. Adding LIKE/REGEX first.
    Exponent, // For POW operator ^ or ** if we support it as operator

    // String matching
    Like,
    NotLike,
    RegEx,
    NotRegEx,
    FuzzyEqual, // ~= (fuzzy string matching)

    // Bitwise
    BitwiseAnd,
    BitwiseOr,
    BitwiseXor,
    LeftShift,
    RightShift,

    // Null coalescing
    NullCoalesce,

    // Logical OR (||) - returns left if truthy, otherwise right
    LogicalOr,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UnaryOperator {
    Not,
    Negate,
    BitwiseNot,
}

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

    #[test]
    fn test_expression_literal() {
        let expr = Expression::Literal(json!(42));
        assert_eq!(expr, Expression::Literal(json!(42)));
    }

    #[test]
    fn test_expression_variable() {
        let expr = Expression::Variable("doc".to_string());
        if let Expression::Variable(name) = expr {
            assert_eq!(name, "doc");
        } else {
            panic!("Expected Variable");
        }
    }

    #[test]
    fn test_expression_field_access() {
        let expr = Expression::FieldAccess(
            Box::new(Expression::Variable("doc".to_string())),
            "name".to_string(),
        );

        if let Expression::FieldAccess(base, field) = expr {
            assert_eq!(*base, Expression::Variable("doc".to_string()));
            assert_eq!(field, "name");
        } else {
            panic!("Expected FieldAccess");
        }
    }

    #[test]
    fn test_expression_binary_op() {
        let expr = Expression::BinaryOp {
            left: Box::new(Expression::Variable("a".to_string())),
            op: BinaryOperator::Add,
            right: Box::new(Expression::Literal(json!(1))),
        };

        if let Expression::BinaryOp { left, op, right } = expr {
            assert_eq!(*left, Expression::Variable("a".to_string()));
            assert_eq!(op, BinaryOperator::Add);
            assert_eq!(*right, Expression::Literal(json!(1)));
        } else {
            panic!("Expected BinaryOp");
        }
    }

    #[test]
    fn test_for_clause() {
        let clause = ForClause {
            variable: "doc".to_string(),
            collection: "users".to_string(),
            source_variable: None,
            source_expression: None,
            system_time: None,
            valid_time: None,
            options: None,
        };

        assert_eq!(clause.variable, "doc");
        assert_eq!(clause.collection, "users");
    }

    #[test]
    fn test_filter_clause() {
        let clause = FilterClause {
            expression: Expression::Literal(json!(true)),
        };

        assert_eq!(clause.expression, Expression::Literal(json!(true)));
    }

    #[test]
    fn test_limit_clause() {
        let clause = LimitClause {
            offset: Expression::Literal(json!(0)),
            count: Some(Expression::Literal(json!(10))),
        };

        assert_eq!(clause.offset, Expression::Literal(json!(0)));
        assert_eq!(clause.count, Some(Expression::Literal(json!(10))));

        // A standalone OFFSET has no count at all
        let unbounded = LimitClause {
            offset: Expression::Literal(json!(5)),
            count: None,
        };
        assert!(unbounded.count.is_none());
    }

    #[test]
    fn test_sort_clause() {
        let clause = SortClause {
            fields: vec![(
                Expression::FieldAccess(
                    Box::new(Expression::Variable("doc".to_string())),
                    "age".to_string(),
                ),
                true,
            )],
        };

        assert_eq!(clause.fields.len(), 1);
        assert!(clause.fields[0].1); // ascending
    }

    #[test]
    fn test_let_clause() {
        let clause = LetClause {
            variable: "x".to_string(),
            expression: Expression::Literal(json!(42)),
        };

        assert_eq!(clause.variable, "x");
    }

    #[test]
    fn test_insert_clause() {
        let clause = InsertClause {
            document: Expression::Object(vec![]),
            collection: "users".to_string(),
            options: MutationOptions::default(),
            binds_new: false,
            binds_old: false,
        };

        assert_eq!(clause.collection, "users");
    }

    #[test]
    fn test_edge_direction() {
        assert_ne!(EdgeDirection::Inbound, EdgeDirection::Outbound);
        assert_ne!(EdgeDirection::Any, EdgeDirection::Inbound);
    }

    #[test]
    fn test_binary_operators() {
        assert_eq!(BinaryOperator::Equal.clone(), BinaryOperator::Equal);
        assert_ne!(BinaryOperator::Equal, BinaryOperator::NotEqual);
        assert_ne!(BinaryOperator::Add, BinaryOperator::Subtract);
    }

    #[test]
    fn test_unary_operators() {
        assert_eq!(UnaryOperator::Not.clone(), UnaryOperator::Not);
        assert_ne!(UnaryOperator::Not, UnaryOperator::Negate);
    }

    #[test]
    fn test_expression_clone() {
        let expr = Expression::Variable("test".to_string());
        let cloned = expr.clone();
        assert_eq!(expr, cloned);
    }

    #[test]
    fn test_query_default() {
        let query = Query {
            with_clause: None,
            let_clauses: vec![],
            for_clauses: vec![],
            join_clauses: vec![],
            filter_clauses: vec![],
            sort_clause: None,
            limit_clause: None,
            return_clause: None,
            create_stream_clause: None,
            create_materialized_view_clause: None,
            refresh_materialized_view_clause: None,
            window_clause: None,
            post_limit_lets: vec![],
            body_clauses: vec![],
            set_operations: vec![],
        };

        assert!(query.for_clauses.is_empty());
        assert!(query.return_clause.is_none());
    }

    #[test]
    fn test_collect_clause() {
        let clause = CollectClause {
            group_vars: vec![(
                "category".to_string(),
                Expression::FieldAccess(
                    Box::new(Expression::Variable("doc".to_string())),
                    "cat".to_string(),
                ),
            )],
            into_var: Some("items".to_string()),
            keep_vars: vec![],
            count_var: Some("cnt".to_string()),
            aggregates: vec![],
            into_expr: None,
            method: None,
        };

        assert_eq!(clause.group_vars.len(), 1);
        assert_eq!(clause.into_var, Some("items".to_string()));
        assert_eq!(clause.count_var, Some("cnt".to_string()));
    }

    #[test]
    fn test_aggregate_expr() {
        let agg = AggregateExpr {
            variable: "total".to_string(),
            function: "SUM".to_string(),
            argument: Some(Expression::FieldAccess(
                Box::new(Expression::Variable("doc".to_string())),
                "price".to_string(),
            )),
        };

        assert_eq!(agg.variable, "total");
        assert_eq!(agg.function, "SUM");
        assert!(agg.argument.is_some());
    }

    #[test]
    fn test_expression_array() {
        let expr = Expression::Array(vec![
            Expression::Literal(json!(1)),
            Expression::Literal(json!(2)),
            Expression::Literal(json!(3)),
        ]);

        if let Expression::Array(items) = expr {
            assert_eq!(items.len(), 3);
        } else {
            panic!("Expected Array");
        }
    }

    #[test]
    fn test_expression_object() {
        let expr = Expression::Object(vec![
            ("name".to_string(), Expression::Literal(json!("test"))),
            ("value".to_string(), Expression::Literal(json!(42))),
        ]);

        if let Expression::Object(fields) = expr {
            assert_eq!(fields.len(), 2);
            assert_eq!(fields[0].0, "name");
        } else {
            panic!("Expected Object");
        }
    }

    #[test]
    fn test_expression_range() {
        let expr = Expression::Range(
            Box::new(Expression::Literal(json!(1))),
            Box::new(Expression::Literal(json!(5))),
        );

        if let Expression::Range(start, end) = expr {
            assert_eq!(*start, Expression::Literal(json!(1)));
            assert_eq!(*end, Expression::Literal(json!(5)));
        } else {
            panic!("Expected Range");
        }
    }

    #[test]
    fn test_expression_function_call() {
        let expr = Expression::FunctionCall {
            name: "LENGTH".to_string(),
            args: vec![Expression::Variable("arr".to_string())],
        };

        if let Expression::FunctionCall { name, args } = expr {
            assert_eq!(name, "LENGTH");
            assert_eq!(args.len(), 1);
        } else {
            panic!("Expected FunctionCall");
        }
    }

    #[test]
    fn test_expression_ternary() {
        let expr = Expression::Ternary {
            condition: Box::new(Expression::Variable("flag".to_string())),
            true_expr: Box::new(Expression::Literal(json!(1))),
            false_expr: Box::new(Expression::Literal(json!(0))),
        };

        if let Expression::Ternary {
            condition,
            true_expr,
            false_expr,
        } = expr
        {
            assert_eq!(*condition, Expression::Variable("flag".to_string()));
            assert_eq!(*true_expr, Expression::Literal(json!(1)));
            assert_eq!(*false_expr, Expression::Literal(json!(0)));
        } else {
            panic!("Expected Ternary");
        }
    }
}