qail-core 3.0.1

QAIL AST Kernel - typed query AST, schema validation, RLS context, and native access policy
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
use crate::ast::aggregate::sort_keys_text;
use crate::ast::{AggregateFunc, Cage, Condition, ModKind, Value};

/// Binary operators for expressions
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum BinaryOp {
    // Arithmetic
    /// String concatenation `||`.
    Concat,
    /// Addition `+`.
    Add,
    /// Subtraction `-`.
    Sub,
    /// Multiplication `*`.
    Mul,
    /// Division `/`.
    Div,
    /// Modulo (%)
    Rem,
    // Bitwise (integer and bit-string operands)
    /// Bitwise AND `&`.
    BitAnd,
    /// Bitwise OR `|`.
    BitOr,
    /// Bitwise XOR `#`.
    BitXor,
    /// Bitwise shift left `<<`.
    ShiftLeft,
    /// Bitwise shift right `>>`.
    ShiftRight,
    // JSONPath (right side is cast to jsonpath)
    /// JSONPath `@?`.
    JsonPathExists,
    /// JSONPath `@@` (not full-text search).
    JsonPathMatch,
    // Logical
    /// Logical AND.
    And,
    /// Logical OR.
    Or,
    // Comparison
    /// Equals `=`.
    Eq,
    /// Not equals `<>`.
    Ne,
    /// Greater than `>`.
    Gt,
    /// Greater than or equal `>=`.
    Gte,
    /// Less than `<`.
    Lt,
    /// Less than or equal `<=`.
    Lte,
    // Null checks (unary but represented as binary with null right)
    /// IS NULL.
    IsNull,
    /// IS NOT NULL.
    IsNotNull,
    /// Null-safe inequality `IS DISTINCT FROM`.
    IsDistinctFrom,
    /// Null-safe equality `IS NOT DISTINCT FROM`.
    IsNotDistinctFrom,
    // Boolean tests (unary, like the null checks)
    /// IS TRUE.
    IsTrue,
    /// IS NOT TRUE.
    IsNotTrue,
    /// IS FALSE.
    IsFalse,
    /// IS NOT FALSE.
    IsNotFalse,
    /// IS UNKNOWN.
    IsUnknown,
    /// IS NOT UNKNOWN.
    IsNotUnknown,
}

impl BinaryOp {
    /// Unary postfix tests (`IS NULL`, `IS TRUE`, ...): `right` is a
    /// placeholder that must not be rendered.
    pub fn is_postfix(&self) -> bool {
        matches!(
            self,
            BinaryOp::IsNull
                | BinaryOp::IsNotNull
                | BinaryOp::IsTrue
                | BinaryOp::IsNotTrue
                | BinaryOp::IsFalse
                | BinaryOp::IsNotFalse
                | BinaryOp::IsUnknown
                | BinaryOp::IsNotUnknown
        )
    }
}

impl BinaryOp {
    /// JSONPath operators: the right operand is wrapped in `CAST(.. AS jsonpath)`
    /// so an untyped literal or parameter cannot resolve to text search `@@`.
    pub fn is_jsonpath(&self) -> bool {
        matches!(self, BinaryOp::JsonPathExists | BinaryOp::JsonPathMatch)
    }

    /// `(left op right)` for an infix operator whose operands are already rendered.
    pub fn infix_sql(&self, left: &str, right: &str) -> String {
        if self.is_jsonpath() {
            format!("({left} {self} CAST({right} AS jsonpath))")
        } else {
            format!("({left} {self} {right})")
        }
    }
}

impl std::fmt::Display for BinaryOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BinaryOp::Concat => write!(f, "||"),
            BinaryOp::Add => write!(f, "+"),
            BinaryOp::Sub => write!(f, "-"),
            BinaryOp::Mul => write!(f, "*"),
            BinaryOp::Div => write!(f, "/"),
            BinaryOp::Rem => write!(f, "%"),
            BinaryOp::BitAnd => write!(f, "&"),
            BinaryOp::BitOr => write!(f, "|"),
            BinaryOp::BitXor => write!(f, "#"),
            BinaryOp::ShiftLeft => write!(f, "<<"),
            BinaryOp::ShiftRight => write!(f, ">>"),
            BinaryOp::JsonPathExists => write!(f, "@?"),
            BinaryOp::JsonPathMatch => write!(f, "@@"),
            BinaryOp::And => write!(f, "AND"),
            BinaryOp::Or => write!(f, "OR"),
            BinaryOp::Eq => write!(f, "="),
            BinaryOp::Ne => write!(f, "<>"),
            BinaryOp::Gt => write!(f, ">"),
            BinaryOp::Gte => write!(f, ">="),
            BinaryOp::Lt => write!(f, "<"),
            BinaryOp::Lte => write!(f, "<="),
            BinaryOp::IsNull => write!(f, "IS NULL"),
            BinaryOp::IsNotNull => write!(f, "IS NOT NULL"),
            BinaryOp::IsDistinctFrom => write!(f, "IS DISTINCT FROM"),
            BinaryOp::IsNotDistinctFrom => write!(f, "IS NOT DISTINCT FROM"),
            BinaryOp::IsTrue => write!(f, "IS TRUE"),
            BinaryOp::IsNotTrue => write!(f, "IS NOT TRUE"),
            BinaryOp::IsFalse => write!(f, "IS FALSE"),
            BinaryOp::IsNotFalse => write!(f, "IS NOT FALSE"),
            BinaryOp::IsUnknown => write!(f, "IS UNKNOWN"),
            BinaryOp::IsNotUnknown => write!(f, "IS NOT UNKNOWN"),
        }
    }
}

/// Operand of one JSON `->` / `->>` step.
///
/// PostgreSQL overloads these operators: a text operand selects an object
/// key and an integer operand selects an array position (negative counts
/// from the end), so `doc->'0'` and `doc->0` read different values.
///
/// Serde form: an index is the decimal string (`"0"`), a key whose text is
/// not an `i64` literal is the plain string (`"name"`), and a key whose text
/// is an `i64` literal is `{"key": "0"}`. A plain string therefore keeps the
/// meaning it had when segments were bare strings, and a bare JSON integer
/// also decodes as an index.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum JsonPathSegment {
    /// Object key, rendered as a quoted text operand (`->'0'`).
    Key(String),
    /// Array position, rendered as an integer operand (`->0`).
    Index(i64),
}

impl JsonPathSegment {
    /// Classify a segment written as plain path text: an `i64` literal is an
    /// array position, anything else an object key.
    ///
    /// String-path builders (`json_path`, `.path("items.0.name")`) and
    /// plain-string serde segments use this rule.
    pub fn from_path_text(text: &str) -> Self {
        match text.parse::<i64>() {
            Ok(index) => Self::Index(index),
            Err(_) => Self::Key(text.to_string()),
        }
    }

    /// Object key text, if this segment is a key.
    pub fn as_key(&self) -> Option<&str> {
        match self {
            Self::Key(key) => Some(key),
            Self::Index(_) => None,
        }
    }
}

impl From<&str> for JsonPathSegment {
    fn from(key: &str) -> Self {
        Self::Key(key.to_string())
    }
}

impl From<String> for JsonPathSegment {
    fn from(key: String) -> Self {
        Self::Key(key)
    }
}

impl From<i64> for JsonPathSegment {
    fn from(index: i64) -> Self {
        Self::Index(index)
    }
}

/// Renders the SQL operand: `'key'` with quotes doubled, or the bare integer.
impl std::fmt::Display for JsonPathSegment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Key(key) => write!(f, "'{}'", key.replace('\'', "''")),
            Self::Index(index) => write!(f, "{index}"),
        }
    }
}

impl serde::Serialize for JsonPathSegment {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self {
            Self::Index(index) => serializer.serialize_str(&index.to_string()),
            Self::Key(key) if key.parse::<i64>().is_ok() => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("key", key)?;
                map.end()
            }
            Self::Key(key) => serializer.serialize_str(key),
        }
    }
}

impl<'de> serde::Deserialize<'de> for JsonPathSegment {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct SegmentVisitor;

        impl<'de> serde::de::Visitor<'de> for SegmentVisitor {
            type Value = JsonPathSegment;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a JSON path string, integer index, or {\"key\": text}")
            }

            fn visit_i64<E: serde::de::Error>(self, index: i64) -> Result<Self::Value, E> {
                Ok(JsonPathSegment::Index(index))
            }

            fn visit_u64<E: serde::de::Error>(self, index: u64) -> Result<Self::Value, E> {
                i64::try_from(index)
                    .map(JsonPathSegment::Index)
                    .map_err(|_| E::custom("JSON path index out of i64 range"))
            }

            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
                Ok(JsonPathSegment::from_path_text(text))
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                mut map: A,
            ) -> Result<Self::Value, A::Error> {
                use serde::de::Error;
                let Some(tag) = map.next_key::<String>()? else {
                    return Err(A::Error::custom("empty JSON path segment object"));
                };
                let segment = match tag.as_str() {
                    "key" => JsonPathSegment::Key(map.next_value()?),
                    "index" => JsonPathSegment::Index(map.next_value()?),
                    other => {
                        return Err(A::Error::unknown_field(other, &["key", "index"]));
                    }
                };
                if map.next_key::<String>()?.is_some() {
                    return Err(A::Error::custom(
                        "JSON path segment object takes exactly one field",
                    ));
                }
                Ok(segment)
            }
        }

        deserializer.deserialize_any(SegmentVisitor)
    }
}

/// An expression node in the AST.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Expr {
    /// All columns (*)
    Star,
    /// A named column or identifier.
    Named(String),
    /// An aliased expression (expr AS alias)
    Aliased {
        /// Expression name.
        name: String,
        /// Alias.
        alias: String,
    },
    /// An aggregate function (COUNT(col)) with optional FILTER and DISTINCT
    ///
    /// Shape rules, checked by [`check_aggregate_shape`](crate::ast::check_aggregate_shape)
    /// in both the transpiler and the native encoder: `col` and `args` are
    /// never both set; `order_by` and `within_group` are never both set;
    /// `within_group` is set exactly for ordered-set functions; STRING_AGG
    /// takes `args: [value, delimiter]`.
    Aggregate {
        /// Column to aggregate (`*`, `col`, `t.col`) when `args` is empty.
        /// Must be empty when `args` is set.
        col: String,
        /// Aggregate function.
        func: AggregateFunc,
        /// Whether DISTINCT is applied.
        distinct: bool,
        /// PostgreSQL FILTER (WHERE ...) clause for aggregates
        filter: Option<Vec<Condition>>,
        /// Optional alias.
        alias: Option<String>,
        /// Argument expressions, in call order (`SUM(price * quantity)`,
        /// `STRING_AGG(status, ',')`; the direct arguments of an ordered-set
        /// aggregate). Empty means the one argument is `col`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        args: Vec<Expr>,
        /// Aggregate-local ORDER BY inside the call: `ARRAY_AGG(x ORDER BY y)`.
        /// One `CageKind::Sort` cage per key; the key is its single condition's `left`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        order_by: Vec<Cage>,
        /// `WITHIN GROUP (ORDER BY ...)` of an ordered-set aggregate, same cage shape.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        within_group: Vec<Cage>,
    },
    /// Type cast expression (expr::type)
    Cast {
        /// Expression to cast.
        expr: Box<Expr>,
        /// Target SQL type.
        target_type: String,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Column definition (name, type, constraints).
    Def {
        /// Column name.
        name: String,
        /// SQL data type.
        data_type: String,
        /// Column constraints.
        constraints: Vec<Constraint>,
    },
    /// ALTER TABLE modify (ADD/DROP column).
    Mod {
        /// Modification kind.
        kind: ModKind,
        /// Column expression.
        col: Box<Expr>,
    },
    /// Window Function Definition
    Window {
        /// Window name/alias.
        name: String,
        /// Window function name.
        func: String,
        /// Function arguments as expressions (e.g., for SUM(amount), use Expr::Named("amount"))
        params: Vec<Expr>,
        /// Aggregate FILTER (WHERE ...) applied before OVER.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        filter: Option<Vec<Condition>>,
        /// PARTITION BY columns.
        partition: Vec<String>,
        /// ORDER BY clauses.
        order: Vec<Cage>,
        /// Frame specification.
        frame: Option<WindowFrame>,
    },
    /// CASE WHEN expression
    Case {
        /// WHEN condition THEN expr pairs (Expr allows functions, values, identifiers)
        when_clauses: Vec<(Condition, Box<Expr>)>,
        /// ELSE expr (optional)
        else_value: Option<Box<Expr>>,
        /// Optional alias
        alias: Option<String>,
    },
    /// JSON accessor (data->>'key' or data->'key' or chained data->'a'->0->>'b')
    JsonAccess {
        /// Base column name
        column: String,
        /// JSON path segments: (operand, as_text)
        /// as_text: true for ->> (extract as text), false for -> (extract as JSON)
        /// For chained access like x->'a'->0->>'b', this is
        /// [(Key("a"), false), (Index(0), false), (Key("b"), true)]
        path_segments: Vec<(JsonPathSegment, bool)>,
        /// Optional alias
        alias: Option<String>,
    },
    /// Function call expression (COALESCE, NULLIF, etc.)
    FunctionCall {
        /// Function name (coalesce, nullif, etc.)
        name: String,
        /// Arguments to the function (now supports nested expressions)
        args: Vec<Expr>,
        /// Optional alias
        alias: Option<String>,
    },
    /// Special SQL function with keyword arguments (SUBSTRING, EXTRACT, TRIM, etc.)
    /// e.g., SUBSTRING(expr FROM pos [FOR len]), EXTRACT(YEAR FROM date)
    SpecialFunction {
        /// Function name (SUBSTRING, EXTRACT, TRIM, etc.)
        name: String,
        /// Arguments as (optional_keyword, expr) pairs
        /// e.g., [(None, col), (Some("FROM"), 2), (Some("FOR"), 5)]
        args: Vec<(Option<String>, Box<Expr>)>,
        /// Optional alias
        alias: Option<String>,
    },
    /// Binary expression (left op right)
    Binary {
        /// Left operand.
        left: Box<Expr>,
        /// Binary operator.
        op: BinaryOp,
        /// Right operand.
        right: Box<Expr>,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Literal value (string, number) for use in expressions
    /// e.g., '62', 0, 'active'
    Literal(Value),
    /// Array constructor: ARRAY[expr1, expr2, ...]
    ArrayConstructor {
        /// Array elements.
        elements: Vec<Expr>,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Row constructor: ROW(expr1, expr2, ...) or (expr1, expr2, ...)
    RowConstructor {
        /// Row elements.
        elements: Vec<Expr>,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Array/string subscript: `arr[index]`.
    Subscript {
        /// Base expression.
        expr: Box<Expr>,
        /// Index expression.
        index: Box<Expr>,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Array slice: `arr[lower:upper]`; an omitted bound is open (`arr[2:]`, `arr[:]`).
    ArraySlice {
        /// Base expression.
        expr: Box<Expr>,
        /// Lower bound, inclusive.
        lower: Option<Box<Expr>>,
        /// Upper bound, inclusive.
        upper: Option<Box<Expr>>,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Collation: expr COLLATE "collation_name"
    Collate {
        /// Expression.
        expr: Box<Expr>,
        /// Collation name.
        collation: String,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Field selection from composite: (row).field
    FieldAccess {
        /// Composite expression.
        expr: Box<Expr>,
        /// Field name.
        field: String,
        /// Optional alias.
        alias: Option<String>,
    },
    /// Scalar subquery: (SELECT ... LIMIT 1)
    /// Used in COALESCE, comparisons, etc.
    Subquery {
        /// Inner query.
        query: Box<super::Qail>,
        /// Optional alias.
        alias: Option<String>,
    },
    /// EXISTS subquery: EXISTS(SELECT ...)
    Exists {
        /// Inner query.
        query: Box<super::Qail>,
        /// Whether this is NOT EXISTS.
        negated: bool,
        /// Optional alias.
        alias: Option<String>,
    },
    /// `DEFAULT`: the column default, as a whole MERGE UPDATE assignment value
    /// or MERGE INSERT value. Every other position rejects it.
    Default,
    /// One argument of a [`FunctionCall`](Expr::FunctionCall) in named
    /// notation (`name => value`) and/or as the `VARIADIC` array expansion.
    /// Valid only directly inside `FunctionCall.args` (or a FROM function's
    /// args); encoders reject it anywhere else. PostgreSQL requires named
    /// arguments after positional ones and `VARIADIC` on the last argument.
    FunctionArg {
        /// Parameter name for named notation.
        name: Option<String>,
        /// `VARIADIC`: pass `value` (an array) as the variadic parameter.
        variadic: bool,
        /// Argument value.
        value: Box<Expr>,
    },
}

/// PostgreSQL call-argument rules for [`Expr::FunctionArg`]: named arguments
/// after every positional one, `VARIADIC` only on the last argument, no
/// repeated name. Bare positional args need no wrapper.
pub fn validate_function_args(args: &[Expr]) -> Result<(), String> {
    let mut seen_named = false;
    let mut names: Vec<&str> = Vec::new();
    for (i, arg) in args.iter().enumerate() {
        let (name, variadic) = match arg {
            Expr::FunctionArg { name, variadic, .. } => (name.as_deref(), *variadic),
            _ => (None, false),
        };
        if variadic && i + 1 != args.len() {
            return Err("VARIADIC must mark the last function argument".to_string());
        }
        match name {
            Some(name) => {
                if names.iter().any(|seen| seen.eq_ignore_ascii_case(name)) {
                    return Err(format!("function argument `{name}` is named twice"));
                }
                names.push(name);
                seen_named = true;
            }
            None if seen_named => {
                return Err("positional function argument after a named one".to_string());
            }
            None => {}
        }
    }
    Ok(())
}

impl std::fmt::Display for Expr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Expr::Star => write!(f, "*"),
            Expr::Named(name) => write!(f, "{}", name),
            Expr::Aliased { name, alias } => write!(f, "{} AS {}", name, alias),
            Expr::Aggregate {
                col,
                func,
                distinct,
                filter,
                alias,
                args,
                order_by,
                within_group,
            } => {
                write!(f, "{}(", func)?;
                if *distinct {
                    write!(f, "DISTINCT ")?;
                }
                if args.is_empty() {
                    write!(f, "{}", col)?;
                } else {
                    for (i, arg) in args.iter().enumerate() {
                        if i > 0 {
                            write!(f, ", ")?;
                        }
                        write!(f, "{}", arg)?;
                    }
                }
                if !order_by.is_empty() {
                    write!(f, " ORDER BY {}", sort_keys_text(order_by))?;
                }
                write!(f, ")")?;
                if !within_group.is_empty() {
                    write!(
                        f,
                        " WITHIN GROUP (ORDER BY {})",
                        sort_keys_text(within_group)
                    )?;
                }
                if let Some(conditions) = filter {
                    write!(
                        f,
                        " FILTER (WHERE {})",
                        conditions
                            .iter()
                            .map(|c| c.to_string())
                            .collect::<Vec<_>>()
                            .join(" AND ")
                    )?;
                }
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Cast {
                expr,
                target_type,
                alias,
            } => {
                write!(f, "{}::{}", expr, target_type)?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Def {
                name,
                data_type,
                constraints,
            } => {
                write!(f, "{}:{}", name, data_type)?;
                for c in constraints {
                    write!(f, "^{}", c)?;
                }
                Ok(())
            }
            Expr::Mod { kind, col } => match kind {
                ModKind::Add => write!(f, "+{}", col),
                ModKind::Drop => write!(f, "-{}", col),
            },
            Expr::Window {
                name,
                func,
                params,
                filter,
                partition,
                order,
                frame,
            } => {
                write!(f, "{}:{}(", name, func)?;
                for (i, p) in params.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", p)?;
                }
                write!(f, ")")?;
                if let Some(conditions) = filter {
                    write!(
                        f,
                        " FILTER (WHERE {})",
                        conditions
                            .iter()
                            .map(|c| c.to_string())
                            .collect::<Vec<_>>()
                            .join(" AND ")
                    )?;
                }

                // Print partitions if any
                if !partition.is_empty() {
                    write!(f, "{{Part=")?;
                    for (i, p) in partition.iter().enumerate() {
                        if i > 0 {
                            write!(f, ",")?;
                        }
                        write!(f, "{}", p)?;
                    }
                    if let Some(fr) = frame {
                        write!(f, ", Frame={:?}", fr)?; // Debug format for now
                    }
                    write!(f, "}}")?;
                } else if let Some(fr) = frame {
                    write!(f, "{{Frame={:?}}}", fr)?;
                }

                // Print order cages
                for _cage in order {
                    // Order cages are sort cages - display format TBD
                }
                Ok(())
            }
            Expr::Case {
                when_clauses,
                else_value,
                alias,
            } => {
                write!(f, "CASE")?;
                for (cond, val) in when_clauses {
                    // The whole predicate: printing only `cond.left` would
                    // turn `status = 'paid'` into a bare `status`.
                    write!(f, " WHEN {} {}", cond.left, cond.op.sql_symbol())?;
                    match (&cond.op, &cond.value) {
                        (crate::ast::Operator::IsNull | crate::ast::Operator::IsNotNull, _) => {}
                        (
                            crate::ast::Operator::Between | crate::ast::Operator::NotBetween,
                            Value::Array(bounds),
                        ) if bounds.len() == 2 => {
                            write!(f, " {} AND {}", bounds[0], bounds[1])?;
                        }
                        (_, value) => write!(f, " {}", value)?,
                    }
                    write!(f, " THEN {}", val)?;
                }
                if let Some(e) = else_value {
                    write!(f, " ELSE {}", e)?;
                }
                write!(f, " END")?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::JsonAccess {
                column,
                path_segments,
                alias,
            } => {
                write!(f, "{}", column)?;
                for (segment, as_text) in path_segments {
                    let op = if *as_text { "->>" } else { "->" };
                    write!(f, "{}{}", op, segment)?;
                }
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::FunctionCall { name, args, alias } => {
                let args_str: Vec<String> = args.iter().map(|a| a.to_string()).collect();
                write!(f, "{}({})", name.to_uppercase(), args_str.join(", "))?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::SpecialFunction { name, args, alias } => {
                write!(f, "{}(", name.to_uppercase())?;
                for (i, (keyword, expr)) in args.iter().enumerate() {
                    if i > 0 {
                        write!(f, " ")?;
                    }
                    if let Some(kw) = keyword {
                        write!(f, "{} ", kw)?;
                    }
                    write!(f, "{}", expr)?;
                }
                write!(f, ")")?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Binary {
                left,
                op,
                right,
                alias,
            } => {
                if op.is_postfix() {
                    write!(f, "({} {})", left, op)?;
                } else {
                    write!(f, "{}", op.infix_sql(&left.to_string(), &right.to_string()))?;
                }
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Literal(value) => write!(f, "{}", value),
            Expr::ArrayConstructor { elements, alias } => {
                write!(f, "ARRAY[")?;
                for (i, elem) in elements.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", elem)?;
                }
                write!(f, "]")?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::RowConstructor { elements, alias } => {
                write!(f, "ROW(")?;
                for (i, elem) in elements.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", elem)?;
                }
                write!(f, ")")?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Subscript { expr, index, alias } => {
                if expr.needs_parens_for_subscript() {
                    write!(f, "({})[{}]", expr, index)?;
                } else {
                    write!(f, "{}[{}]", expr, index)?;
                }
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::ArraySlice {
                expr,
                lower,
                upper,
                alias,
            } => {
                if expr.needs_parens_for_subscript() {
                    write!(f, "({})[", expr)?;
                } else {
                    write!(f, "{}[", expr)?;
                }
                if let Some(lower) = lower {
                    write!(f, "{}", lower)?;
                }
                write!(f, ":")?;
                if let Some(upper) = upper {
                    write!(f, "{}", upper)?;
                }
                write!(f, "]")?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Collate {
                expr,
                collation,
                alias,
            } => {
                write!(f, "{} COLLATE \"{}\"", expr, collation)?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::FieldAccess { expr, field, alias } => {
                write!(f, "({}).{}", expr, field)?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Subquery { query, alias } => {
                write!(f, "({})", query)?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Exists {
                query,
                negated,
                alias,
            } => {
                if *negated {
                    write!(f, "NOT ")?;
                }
                write!(f, "EXISTS ({})", query)?;
                if let Some(a) = alias {
                    write!(f, " AS {}", a)?;
                }
                Ok(())
            }
            Expr::Default => write!(f, "DEFAULT"),
            Expr::FunctionArg {
                name,
                variadic,
                value,
            } => {
                if *variadic {
                    write!(f, "VARIADIC ")?;
                }
                if let Some(name) = name {
                    write!(f, "{} => ", name)?;
                }
                write!(f, "{}", value)
            }
        }
    }
}

impl Expr {
    /// The output alias already attached to this expression, if any
    /// (`Window` reports its output name).
    pub fn alias_name(&self) -> Option<&str> {
        match self {
            Expr::Aliased { alias, .. } => Some(alias),
            Expr::Window { name, .. } => Some(name),
            Expr::Aggregate { alias, .. }
            | Expr::Cast { alias, .. }
            | Expr::Case { alias, .. }
            | Expr::JsonAccess { alias, .. }
            | Expr::FunctionCall { alias, .. }
            | Expr::SpecialFunction { alias, .. }
            | Expr::Binary { alias, .. }
            | Expr::ArrayConstructor { alias, .. }
            | Expr::RowConstructor { alias, .. }
            | Expr::Subscript { alias, .. }
            | Expr::ArraySlice { alias, .. }
            | Expr::Collate { alias, .. }
            | Expr::FieldAccess { alias, .. }
            | Expr::Subquery { alias, .. }
            | Expr::Exists { alias, .. } => alias.as_deref(),
            Expr::Star
            | Expr::Named(_)
            | Expr::Def { .. }
            | Expr::Mod { .. }
            | Expr::Literal(_)
            | Expr::Default
            | Expr::FunctionArg { .. } => None,
        }
    }

    /// Attach `alias` to any expression that can carry one; a `Named`
    /// column becomes `Aliased`, and a `Window` takes it as its output name.
    ///
    /// Returns `false` and leaves the expression unchanged when it has no
    /// alias slot (`Star`, `Literal`, an already `Aliased` name, DDL nodes),
    /// so callers can refuse instead of silently dropping the column name.
    pub fn set_alias(&mut self, alias: impl Into<String>) -> bool {
        let alias = alias.into();
        let slot = match self {
            Expr::Named(name) => {
                let name = std::mem::take(name);
                *self = Expr::Aliased { name, alias };
                return true;
            }
            Expr::Window { name, .. } => {
                *name = alias;
                return true;
            }
            Expr::Aggregate { alias, .. }
            | Expr::Cast { alias, .. }
            | Expr::Case { alias, .. }
            | Expr::JsonAccess { alias, .. }
            | Expr::FunctionCall { alias, .. }
            | Expr::SpecialFunction { alias, .. }
            | Expr::Binary { alias, .. }
            | Expr::ArrayConstructor { alias, .. }
            | Expr::RowConstructor { alias, .. }
            | Expr::Subscript { alias, .. }
            | Expr::ArraySlice { alias, .. }
            | Expr::Collate { alias, .. }
            | Expr::FieldAccess { alias, .. }
            | Expr::Subquery { alias, .. }
            | Expr::Exists { alias, .. } => alias,
            Expr::Star
            | Expr::Aliased { .. }
            | Expr::Def { .. }
            | Expr::Mod { .. }
            | Expr::Literal(_)
            | Expr::Default
            | Expr::FunctionArg { .. } => return false,
        };
        *slot = Some(alias);
        true
    }

    /// Whether this expression must be wrapped in parentheses before `[...]`.
    ///
    /// PostgreSQL subscripts only a column reference, a positional parameter,
    /// or a parenthesized expression: `array_append(a, 2)[1]` is a syntax
    /// error and must be written `(array_append(a, 2))[1]`. Chained
    /// subscripts (`m[1][2]`) are already in subscriptable form.
    pub fn needs_parens_for_subscript(&self) -> bool {
        match self {
            Expr::Named(name) => !is_subscriptable_name(name),
            Expr::Subscript { .. } | Expr::ArraySlice { .. } => false,
            _ => true,
        }
    }
}

fn is_subscriptable_name(name: &str) -> bool {
    if let Some(digits) = name.strip_prefix('$') {
        return !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit());
    }
    !name.is_empty()
        && name.split('.').all(|part| {
            let mut chars = part.chars();
            matches!(chars.next(), Some(ch) if ch.is_alphabetic() || ch == '_' || ch == '"')
                && chars.all(|ch| ch.is_alphanumeric() || ch == '_' || ch == '"')
        })
}

/// Column constraint.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Constraint {
    /// PRIMARY KEY.
    PrimaryKey,
    /// UNIQUE.
    Unique,
    /// NULL / nullable.
    Nullable,
    /// DEFAULT value.
    Default(String),
    /// CHECK constraint.
    Check(Vec<String>),
    /// COMMENT ON COLUMN.
    Comment(String),
    /// REFERENCES foreign key.
    References(String),
    /// GENERATED column.
    Generated(ColumnGeneration),
    /// Column-definition `COLLATE` (collation name, unquoted).
    Collate(String),
}

/// Generated column type (STORED, VIRTUAL, or IDENTITY with sequence options)
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ColumnGeneration {
    /// GENERATED ALWAYS AS (expr) STORED - computed and stored
    Stored(String),
    /// GENERATED ALWAYS AS (expr) - computed at query time (default in Postgres 18+)
    Virtual(String),
    /// GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY ( sequence options ).
    ///
    /// Plain identity without options is still written as
    /// `Stored("identity")` / `Stored("identity_by_default")`.
    Identity {
        /// BY DEFAULT instead of ALWAYS.
        by_default: bool,
        /// Identity sequence options.
        options: IdentityOptions,
    },
}

/// Sequence options of an identity column (unset fields use PostgreSQL defaults).
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct IdentityOptions {
    /// START WITH.
    #[serde(default)]
    pub start: Option<i64>,
    /// INCREMENT BY.
    #[serde(default)]
    pub increment: Option<i64>,
    /// MINVALUE.
    #[serde(default)]
    pub min_value: Option<i64>,
    /// MAXVALUE.
    #[serde(default)]
    pub max_value: Option<i64>,
    /// CACHE.
    #[serde(default)]
    pub cache: Option<i64>,
    /// CYCLE.
    #[serde(default)]
    pub cycle: bool,
}

impl IdentityOptions {
    /// True when no option is set.
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    /// Render as a parenthesized PostgreSQL sequence option list, or an empty
    /// string when no option is set.
    pub fn to_sql(&self) -> String {
        let mut parts = Vec::new();
        if let Some(v) = self.start {
            parts.push(format!("START WITH {v}"));
        }
        if let Some(v) = self.increment {
            parts.push(format!("INCREMENT BY {v}"));
        }
        if let Some(v) = self.min_value {
            parts.push(format!("MINVALUE {v}"));
        }
        if let Some(v) = self.max_value {
            parts.push(format!("MAXVALUE {v}"));
        }
        if let Some(v) = self.cache {
            parts.push(format!("CACHE {v}"));
        }
        if self.cycle {
            parts.push("CYCLE".to_string());
        }
        if parts.is_empty() {
            String::new()
        } else {
            format!("({})", parts.join(" "))
        }
    }
}

/// Window frame definition for window functions
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum WindowFrame {
    /// ROWS BETWEEN start AND end
    Rows {
        /// Frame start bound.
        start: FrameBound,
        /// Frame end bound.
        end: FrameBound,
        /// Frame exclusion.
        #[serde(default, skip_serializing_if = "FrameExclusion::is_no_others")]
        exclude: FrameExclusion,
    },
    /// RANGE BETWEEN start AND end
    Range {
        /// Frame start bound.
        start: FrameBound,
        /// Frame end bound.
        end: FrameBound,
        /// Frame exclusion.
        #[serde(default, skip_serializing_if = "FrameExclusion::is_no_others")]
        exclude: FrameExclusion,
    },
    /// GROUPS BETWEEN start AND end (offsets count peer groups; needs ORDER BY)
    Groups {
        /// Frame start bound.
        start: FrameBound,
        /// Frame end bound.
        end: FrameBound,
        /// Frame exclusion.
        #[serde(default, skip_serializing_if = "FrameExclusion::is_no_others")]
        exclude: FrameExclusion,
    },
}

impl WindowFrame {
    /// Mode keyword, bounds and exclusion of this frame.
    pub fn parts(&self) -> (&'static str, &FrameBound, &FrameBound, FrameExclusion) {
        match self {
            WindowFrame::Rows {
                start,
                end,
                exclude,
            } => ("ROWS", start, end, *exclude),
            WindowFrame::Range {
                start,
                end,
                exclude,
            } => ("RANGE", start, end, *exclude),
            WindowFrame::Groups {
                start,
                end,
                exclude,
            } => ("GROUPS", start, end, *exclude),
        }
    }

    /// SQL text `MODE BETWEEN start AND end [EXCLUDE ...]`, or the reason
    /// PostgreSQL would reject the frame.
    ///
    /// PostgreSQL restricts offsets: ROWS and GROUPS take a non-negative
    /// integer, RANGE takes a non-negative value of the ORDER BY column's
    /// type (an interval for date/time columns).
    pub fn to_sql(&self) -> Result<String, &'static str> {
        let (mode, start, end, exclude) = self.parts();
        for bound in [start, end] {
            match bound {
                FrameBound::Preceding(n) | FrameBound::Following(n) if *n < 0 => {
                    return Err("frame offset must not be negative");
                }
                FrameBound::IntervalPreceding { amount, .. }
                | FrameBound::IntervalFollowing { amount, .. } => {
                    if mode != "RANGE" {
                        return Err("interval frame offsets require RANGE");
                    }
                    if *amount < 0 {
                        return Err("frame offset must not be negative");
                    }
                }
                _ => {}
            }
        }
        if matches!(start, FrameBound::UnboundedFollowing) {
            return Err("frame start cannot be UNBOUNDED FOLLOWING");
        }
        if matches!(end, FrameBound::UnboundedPreceding) {
            return Err("frame end cannot be UNBOUNDED PRECEDING");
        }
        let mut sql = format!("{mode} BETWEEN {} AND {}", start.to_sql(), end.to_sql());
        if let Some(exclusion) = exclude.sql_suffix() {
            sql.push(' ');
            sql.push_str(exclusion);
        }
        Ok(sql)
    }
}

/// Window frame boundary
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum FrameBound {
    /// UNBOUNDED PRECEDING.
    UnboundedPreceding,
    /// n PRECEDING.
    Preceding(i32),
    /// CURRENT ROW.
    CurrentRow,
    /// n FOLLOWING.
    Following(i32),
    /// UNBOUNDED FOLLOWING.
    UnboundedFollowing,
    /// `INTERVAL 'amount unit' PRECEDING` (RANGE frames over date/time columns).
    IntervalPreceding {
        /// Non-negative interval amount.
        amount: i64,
        /// Interval unit.
        unit: crate::ast::values::IntervalUnit,
    },
    /// `INTERVAL 'amount unit' FOLLOWING` (RANGE frames over date/time columns).
    IntervalFollowing {
        /// Non-negative interval amount.
        amount: i64,
        /// Interval unit.
        unit: crate::ast::values::IntervalUnit,
    },
}

impl FrameBound {
    /// SQL text of this bound.
    pub fn to_sql(&self) -> String {
        match self {
            FrameBound::UnboundedPreceding => "UNBOUNDED PRECEDING".to_string(),
            FrameBound::Preceding(n) => format!("{n} PRECEDING"),
            FrameBound::CurrentRow => "CURRENT ROW".to_string(),
            FrameBound::Following(n) => format!("{n} FOLLOWING"),
            FrameBound::UnboundedFollowing => "UNBOUNDED FOLLOWING".to_string(),
            FrameBound::IntervalPreceding { amount, unit } => {
                format!("INTERVAL '{amount} {unit}' PRECEDING")
            }
            FrameBound::IntervalFollowing { amount, unit } => {
                format!("INTERVAL '{amount} {unit}' FOLLOWING")
            }
        }
    }
}

/// Window frame exclusion (`EXCLUDE ...`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum FrameExclusion {
    /// `EXCLUDE NO OTHERS`, the default; rendered as nothing.
    #[default]
    NoOthers,
    /// `EXCLUDE CURRENT ROW`.
    CurrentRow,
    /// `EXCLUDE GROUP`: the current row and its ORDER BY peers.
    Group,
    /// `EXCLUDE TIES`: the current row's peers, keeping the row itself.
    Ties,
}

impl FrameExclusion {
    /// Serde helper: the default exclusion is omitted from payloads.
    pub fn is_no_others(&self) -> bool {
        matches!(self, FrameExclusion::NoOthers)
    }

    /// `EXCLUDE ...` text, or `None` for the default.
    pub fn sql_suffix(self) -> Option<&'static str> {
        match self {
            FrameExclusion::NoOthers => None,
            FrameExclusion::CurrentRow => Some("EXCLUDE CURRENT ROW"),
            FrameExclusion::Group => Some("EXCLUDE GROUP"),
            FrameExclusion::Ties => Some("EXCLUDE TIES"),
        }
    }
}

impl std::fmt::Display for Constraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Constraint::PrimaryKey => write!(f, "pk"),
            Constraint::Unique => write!(f, "uniq"),
            Constraint::Nullable => write!(f, "?"),
            Constraint::Default(val) => write!(f, "={}", val),
            Constraint::Check(vals) => write!(f, "check({})", vals.join(",")),
            Constraint::Comment(text) => write!(f, "comment(\"{}\")", text),
            Constraint::References(target) => write!(f, "ref({})", target),
            Constraint::Generated(generation) => match generation {
                ColumnGeneration::Stored(expr) => write!(f, "gen({})", expr),
                ColumnGeneration::Virtual(expr) => write!(f, "vgen({})", expr),
                ColumnGeneration::Identity {
                    by_default,
                    options,
                } => write!(
                    f,
                    "identity({}{})",
                    if *by_default { "by_default" } else { "always" },
                    if options.is_empty() {
                        String::new()
                    } else {
                        format!(" {}", options.to_sql())
                    }
                ),
            },
            Constraint::Collate(name) => write!(f, "collate({})", name),
        }
    }
}

/// Index definition for CREATE INDEX
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct IndexDef {
    /// Index name
    pub name: String,
    /// Target table
    pub table: String,
    /// Columns to index (ordered)
    pub columns: Vec<String>,
    /// Whether the index is unique.
    pub unique: bool,
    /// Index type (e.g., "keyword", "integer", "float", "geo", "text")
    pub index_type: Option<String>,
    /// INCLUDE columns for covering indexes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include: Vec<String>,
    /// Whether to create the index concurrently.
    #[serde(default)]
    pub concurrently: bool,
    /// Optional partial-index predicate (`WHERE ...` body without the keyword).
    pub where_clause: Option<String>,
    /// `NULLS NOT DISTINCT` (PostgreSQL 15+): NULL keys collide in a unique index.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub nulls_not_distinct: bool,
    /// Storage parameters rendered as `WITH (name = 'value', ...)`, each `name=value`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub storage_params: Vec<String>,
}

/// Foreign-key semantics beyond columns, actions, and deferral.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ForeignKeyOptions {
    /// `MATCH FULL`; the default is `MATCH SIMPLE`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub match_full: bool,
    /// Column subset for `ON DELETE SET NULL (..)` / `SET DEFAULT (..)` (PostgreSQL 15+).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub on_delete_columns: Vec<String>,
    /// `NOT VALID`. PostgreSQL ignores it inside CREATE TABLE, so encoders
    /// accept it only on `ALTER TABLE ... ADD`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub not_valid: bool,
    /// `NOT ENFORCED` (PostgreSQL 18+). The server records it as not validated too.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub not_enforced: bool,
}

impl ForeignKeyOptions {
    /// True when every option is at its PostgreSQL default.
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

/// `WITH [LOCAL | CASCADED] CHECK OPTION` on an updatable view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ViewCheckOption {
    /// `WITH LOCAL CHECK OPTION`.
    Local,
    /// `WITH CASCADED CHECK OPTION`.
    Cascaded,
}

impl ViewCheckOption {
    /// SQL keyword for the option.
    pub fn as_sql(self) -> &'static str {
        match self {
            ViewCheckOption::Local => "LOCAL",
            ViewCheckOption::Cascaded => "CASCADED",
        }
    }
}

/// ` WITH (...)` storage clause for `CREATE VIEW`, or empty when no option is set.
pub fn view_with_clause(security_invoker: bool, security_barrier: bool) -> String {
    let mut opts = Vec::new();
    if security_invoker {
        opts.push("security_invoker = true");
    }
    if security_barrier {
        opts.push("security_barrier = true");
    }
    if opts.is_empty() {
        String::new()
    } else {
        format!(" WITH ({})", opts.join(", "))
    }
}

/// ` WITH LOCAL|CASCADED CHECK OPTION` suffix for `CREATE VIEW`, or empty.
pub fn view_check_option_clause(check_option: Option<ViewCheckOption>) -> String {
    match check_option {
        Some(option) => format!(" WITH {} CHECK OPTION", option.as_sql()),
        None => String::new(),
    }
}

/// Table-level constraints for composite keys
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum TableConstraint {
    /// Composite UNIQUE constraint.
    Unique(Vec<String>),
    /// Composite PRIMARY KEY.
    PrimaryKey(Vec<String>),
    /// PostgreSQL 18 temporal key:
    /// `[CONSTRAINT name] PRIMARY KEY | UNIQUE (columns..., period WITHOUT OVERLAPS)`.
    TemporalKey {
        /// Optional constraint name.
        name: Option<String>,
        /// `PRIMARY KEY` when true, `UNIQUE` otherwise.
        primary: bool,
        /// Scalar key columns before the period column.
        columns: Vec<String>,
        /// Range column checked for overlap (emitted last).
        period: String,
    },
    /// Composite FOREIGN KEY constraint.
    ForeignKey {
        /// Optional constraint name.
        name: Option<String>,
        /// Source columns.
        columns: Vec<String>,
        /// Referenced table.
        ref_table: String,
        /// Referenced columns.
        ref_columns: Vec<String>,
        /// PostgreSQL 18 temporal FK: the last column of `columns` and of
        /// `ref_columns` is emitted as `PERIOD col`.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        period: bool,
        /// Optional ON DELETE action.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        on_delete: Option<String>,
        /// Optional ON UPDATE action.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        on_update: Option<String>,
        /// Optional DEFERRABLE clause.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        deferrable: Option<String>,
        /// MATCH mode, ON DELETE column subset, and validation/enforcement state.
        #[serde(default, skip_serializing_if = "ForeignKeyOptions::is_default")]
        options: ForeignKeyOptions,
    },
    /// CHECK constraint carrying validation/enforcement state.
    Check {
        /// Optional constraint name.
        name: Option<String>,
        /// Boolean SQL expression (without the `CHECK` keyword).
        expr: String,
        /// `NOT VALID`; only legal on `ALTER TABLE ... ADD`.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        not_valid: bool,
        /// `NOT ENFORCED` (PostgreSQL 18+).
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        not_enforced: bool,
    },
    /// EXCLUDE constraint, kept as the `pg_get_constraintdef` text from `EXCLUDE` onward.
    Exclude {
        /// Constraint name.
        name: String,
        /// `EXCLUDE USING ... (...) [INCLUDE ...] [WHERE (...)] [DEFERRABLE ...]`.
        definition: String,
    },
}

// ==================== From Implementations for Ergonomic API ====================

impl From<&str> for Expr {
    /// Convert a string reference to a Named expression.
    /// Enables: `.select(["id", "name"])` instead of `.select([col("id"), col("name")])`
    fn from(s: &str) -> Self {
        Expr::Named(s.to_string())
    }
}

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

impl From<&String> for Expr {
    fn from(s: &String) -> Self {
        Expr::Named(s.clone())
    }
}

// ==================== Function and Trigger Definitions ====================

/// PostgreSQL function definition
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FunctionDef {
    /// Function name.
    pub name: String,
    /// Function arguments (e.g., "v int", "tenant uuid").
    pub args: Vec<String>,
    /// Return type (e.g., "trigger", "integer", "void").
    pub returns: String,
    /// Function body (PL/pgSQL code).
    pub body: String,
    /// Language (default: plpgsql).
    pub language: Option<String>,
    /// Volatility modifier (IMMUTABLE/STABLE/VOLATILE), if specified.
    pub volatility: Option<String>,
    /// Execution properties beyond volatility (STRICT, SECURITY DEFINER, SET, ...).
    #[serde(default, skip_serializing_if = "FunctionOptions::is_empty")]
    pub options: FunctionOptions,
}

/// Function execution properties. Unset fields keep PostgreSQL defaults
/// (CALLED ON NULL INPUT, SECURITY INVOKER, NOT LEAKPROOF, PARALLEL UNSAFE).
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FunctionOptions {
    /// STRICT (RETURNS NULL ON NULL INPUT).
    #[serde(default)]
    pub strict: bool,
    /// SECURITY DEFINER.
    #[serde(default)]
    pub security_definer: bool,
    /// LEAKPROOF.
    #[serde(default)]
    pub leakproof: bool,
    /// PARALLEL SAFE / RESTRICTED / UNSAFE.
    #[serde(default)]
    pub parallel: Option<String>,
    /// COST planner estimate (decimal text).
    #[serde(default)]
    pub cost: Option<String>,
    /// ROWS planner estimate for set-returning functions (decimal text).
    #[serde(default)]
    pub rows: Option<String>,
    /// SET clauses, each `name TO value` with the value already in SQL form.
    #[serde(default)]
    pub config: Vec<String>,
}

impl FunctionOptions {
    /// True when every property is at its PostgreSQL default.
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }
}

/// Trigger timing (BEFORE or AFTER)
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum TriggerTiming {
    /// BEFORE.
    Before,
    /// AFTER.
    After,
    /// INSTEAD OF.
    InsteadOf,
}

/// Trigger event types
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum TriggerEvent {
    /// INSERT.
    Insert,
    /// UPDATE.
    Update,
    /// DELETE.
    Delete,
    /// TRUNCATE.
    Truncate,
}

/// PostgreSQL trigger definition
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TriggerDef {
    /// Trigger name.
    pub name: String,
    /// Target table.
    pub table: String,
    /// Timing (BEFORE, AFTER, INSTEAD OF).
    pub timing: TriggerTiming,
    /// Events that fire the trigger.
    pub events: Vec<TriggerEvent>,
    /// Optional column list for `UPDATE OF` triggers.
    pub update_columns: Vec<String>,
    /// Whether the trigger fires FOR EACH ROW.
    pub for_each_row: bool,
    /// Function to execute.
    pub execute_function: String,
    /// WHEN condition (expression without the surrounding parentheses).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition: Option<String>,
    /// REFERENCING OLD TABLE AS name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_table: Option<String>,
    /// REFERENCING NEW TABLE AS name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_table: Option<String>,
}