bsql-macros 0.24.0

Proc macros for bsql — compile-time safe SQL for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
//! Compile-time SQL validation via PostgreSQL PREPARE.
//!
//! Connects to the database specified by `BSQL_DATABASE_URL` and validates
//! each query by preparing it. Introspects column types and nullability
//! from `pg_catalog`.

use smallvec::SmallVec;

use bsql_driver_postgres::{ColumnDesc, Connection, DriverError};

use crate::dynamic::QueryVariant;
use crate::parse::ParsedQuery;

/// Metadata about a single result column, resolved from PostgreSQL.
#[derive(Debug, Clone)]
pub struct ColumnInfo {
    /// Column name as returned by PostgreSQL.
    pub name: String,
    /// PostgreSQL type OID.
    pub pg_oid: u32,
    /// PostgreSQL type name (e.g. `"int4"`, `"text"`).
    pub pg_type_name: String,
    /// Whether this column can be NULL.
    pub is_nullable: bool,
    /// The Rust type string for code generation (e.g. `"i32"`, `"Option<String>"`).
    pub rust_type: String,
}

/// Result of validating a query against PostgreSQL.
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Output columns (for SELECT or RETURNING queries).
    pub columns: Vec<ColumnInfo>,
    /// PostgreSQL OIDs of the expected parameter types.
    pub param_pg_oids: SmallVec<[u32; 8]>,
    /// Whether each parameter type is a PostgreSQL enum (custom type).
    /// When true, `&str`/`String` params are accepted in addition to
    /// any `#[bsql::pg_enum]`-annotated Rust enum.
    pub param_is_pg_enum: SmallVec<[bool; 8]>,
    /// EXPLAIN plan summary (only populated when `explain` feature is enabled).
    #[cfg(feature = "explain")]
    pub explain_plan: Option<String>,
}

/// Validate a parsed query against a live PostgreSQL instance.
///
/// Uses `conn.prepare_describe()` which:
/// 1. Validates SQL syntax
/// 2. Validates table/column existence
/// 3. Returns column metadata and parameter types
pub fn validate_query(
    parsed: &ParsedQuery,
    conn: &mut Connection,
) -> Result<ValidationResult, String> {
    // Prepare the query — this validates syntax, tables, columns, types.
    let result = conn
        .prepare_describe(&parsed.positional_sql)
        .map_err(|e| format_driver_error(&e, parsed))?;

    // Extract parameter type OIDs
    let param_pg_oids: SmallVec<[u32; 8]> = result.param_oids.iter().copied().collect();

    // Detect PG enums by querying pg_type.typtype for each parameter OID.
    let param_is_pg_enum = detect_pg_enums(conn, &result.param_oids);

    let columns = build_columns(conn, &result.columns, &parsed.positional_sql)?;

    Ok(ValidationResult {
        columns,
        param_pg_oids,
        param_is_pg_enum,
        #[cfg(feature = "explain")]
        explain_plan: fetch_explain_plan(conn, parsed),
    })
}

/// Resolve column metadata (name, type, nullability) from a prepared statement.
///
/// `sql` is the normalized SQL string, used to infer NOT NULL for computed
/// columns via `is_known_not_null`.
fn build_columns(
    conn: &mut Connection,
    pg_columns: &[ColumnDesc],
    sql: &str,
) -> Result<Vec<ColumnInfo>, String> {
    let mut nullable_flags = resolve_nullability_batch(conn, pg_columns);

    // Second pass: override known-NOT-NULL computed columns (Fix-6).
    // Parse the SELECT list and check each computed column (table_oid == 0)
    // against known NOT NULL expression patterns.
    let select_exprs = parse_select_expressions(sql);
    for (i, col) in pg_columns.iter().enumerate() {
        if col.table_oid == 0 && nullable_flags[i] {
            // Computed column — check if the expression is known NOT NULL.
            let expr = if i < select_exprs.len() {
                &select_exprs[i]
            } else {
                ""
            };
            if is_known_not_null(&col.name, expr) {
                nullable_flags[i] = false;
            }
        }
    }

    // Detect which columns are PG enum types (for the enum error message).
    let enum_flags = detect_column_enums(conn, pg_columns);

    let mut columns = Vec::with_capacity(pg_columns.len());
    for (i, col) in pg_columns.iter().enumerate() {
        let pg_oid = col.type_oid;
        let pg_type_name = bsql_core::types::pg_name_for_oid(pg_oid)
            .unwrap_or("unknown")
            .to_owned();
        let name = col.name.to_string();
        let is_nullable = nullable_flags[i];

        if enum_flags[i] {
            return Err(format!(
                "column \"{name}\" is PostgreSQL enum type `{pg_type_name}`. \
                 Define a Rust enum with #[bsql::pg_enum] or cast to text: {name}::text"
            ));
        }

        let base_rust_type = crate::types::resolve_rust_type(pg_oid)
            .map_err(|msg| format!("column \"{name}\": {msg}"))?;

        let rust_type = if is_nullable {
            format!("Option<{base_rust_type}>")
        } else {
            base_rust_type.to_owned()
        };

        columns.push(ColumnInfo {
            name,
            pg_oid,
            pg_type_name,
            is_nullable,
            rust_type,
        });
    }
    Ok(columns)
}

/// Parse the SELECT clause of a SQL statement and extract individual expressions.
///
/// Handles nested parentheses (e.g., `COALESCE(a, 'x')`, `SUM(CASE ... END)`)
/// by tracking parenthesis depth. Strips trailing `AS alias` from each expression.
///
/// Returns an empty `Vec` if the SQL cannot be parsed (e.g., no SELECT/FROM).
fn parse_select_expressions(sql: &str) -> Vec<String> {
    let lower = sql.to_lowercase();

    // Find "SELECT " (case insensitive)
    let select_start = match lower.find("select ") {
        Some(pos) => pos + 7, // skip "select "
        None => return Vec::new(),
    };

    // Handle SELECT DISTINCT
    let after_select = lower[select_start..].trim_start();
    let offset = if after_select.starts_with("distinct ") {
        select_start + (lower[select_start..].len() - after_select.len()) + 9
    } else {
        select_start
    };

    // Find " FROM " — end of select list.
    // Must find the FROM at depth 0 (not inside subqueries).
    let select_region = &sql[offset..];
    let mut from_pos = None;
    let mut depth: i32 = 0;
    let select_lower = &lower[offset..];
    let bytes = select_lower.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'(' => depth += 1,
            b')' => depth -= 1,
            b' ' if depth == 0 && i + 6 <= bytes.len() && &select_lower[i..i + 6] == " from " => {
                from_pos = Some(i);
                break;
            }
            _ => {}
        }
        i += 1;
    }

    let select_list = match from_pos {
        Some(pos) => &select_region[..pos],
        // No FROM clause (e.g., "SELECT 1") — entire remaining string is the select list
        None => select_region.trim_end_matches(';').trim(),
    };

    // Split by commas, respecting parenthesis depth.
    let mut exprs = Vec::new();
    let mut current_start = 0;
    depth = 0;
    let list_bytes = select_list.as_bytes();
    for j in 0..list_bytes.len() {
        match list_bytes[j] {
            b'(' => depth += 1,
            b')' => depth -= 1,
            b',' if depth == 0 => {
                let raw = select_list[current_start..j].trim();
                exprs.push(strip_alias(raw));
                current_start = j + 1;
            }
            _ => {}
        }
    }
    // Last expression
    let raw = select_list[current_start..].trim();
    if !raw.is_empty() {
        exprs.push(strip_alias(raw));
    }

    exprs
}

/// Strip a trailing `AS alias` from a SELECT expression.
///
/// Handles both `expr AS alias` and `expr alias` (implicit alias).
/// Only strips at depth 0 to avoid stripping `AS` inside subqueries.
fn strip_alias(expr: &str) -> String {
    let lower = expr.to_lowercase();

    // Look for " as " (case insensitive) at depth 0, from right to left.
    if let Some(as_pos) = lower.rfind(" as ") {
        // Verify it's at depth 0
        let depth: i32 = expr[..as_pos]
            .bytes()
            .map(|b| match b {
                b'(' => 1,
                b')' => -1,
                _ => 0,
            })
            .sum();
        if depth == 0 {
            return expr[..as_pos].trim().to_owned();
        }
    }

    expr.trim().to_owned()
}

/// Check if a SQL expression in the SELECT list is known to produce NOT NULL results.
///
/// Analyzes the expression text for patterns that the SQL standard guarantees
/// will never return NULL. Uses both the column name (from `pg_catalog`) and
/// the parsed expression text for maximum coverage.
fn is_known_not_null(col_name: &str, select_expr: &str) -> bool {
    // If the SELECT expression is empty (parsing failed), fall back to the
    // column name reported by PostgreSQL. Bare aggregates like COUNT(*)
    // produce a column name "count".
    let expr_lower = if select_expr.trim().is_empty() {
        col_name.to_lowercase()
    } else {
        select_expr.trim().to_lowercase()
    };

    // COUNT(*) and COUNT(expr) — SQL standard guarantees NOT NULL
    if expr_lower.starts_with("count(") || expr_lower == "count" {
        return true;
    }

    // COALESCE with a literal last argument — guaranteed NOT NULL
    if expr_lower.starts_with("coalesce(") {
        if let Some(last_arg) = expr_lower.rsplit(',').next() {
            let trimmed = last_arg.trim().trim_end_matches(')').trim();
            if is_literal(trimmed) {
                return true;
            }
        }
        return false;
    }

    // EXISTS(...) — always returns boolean, never NULL
    if expr_lower.starts_with("exists(") {
        return true;
    }

    // CASE WHEN ... THEN literal ELSE literal END — not null if both branches are literals
    if expr_lower.starts_with("case ") && expr_lower.ends_with(" end")
        && is_case_all_literal_branches(&expr_lower)
    {
        return true;
    }

    // Window functions that always return NOT NULL
    if is_not_null_window_function(&expr_lower) {
        return true;
    }

    // Date/time functions that always return NOT NULL
    if is_not_null_datetime_function(&expr_lower) {
        return true;
    }

    // String/array functions that return NOT NULL (given NOT NULL input assumed)
    if is_not_null_scalar_function(&expr_lower) {
        return true;
    }

    // Literals: numeric, string, boolean
    if is_literal(&expr_lower) {
        return true;
    }

    // CURRENT_DATE, CURRENT_TIMESTAMP, CURRENT_USER, etc.
    if expr_lower.starts_with("current_") {
        return true;
    }

    false
}

/// Check if an expression is a literal value (numeric, string, or boolean).
fn is_literal(expr: &str) -> bool {
    let s = expr.trim();
    s.parse::<f64>().is_ok()
        || (s.starts_with('\'') && s.ends_with('\''))
        || s == "true"
        || s == "false"
}

/// Check if a CASE expression has only literal THEN/ELSE branches.
///
/// Matches: `case when ... then 1 else 0 end`, `case when ... then 'a' else 'b' end`
/// Does NOT match if any branch is a column reference or function call.
fn is_case_all_literal_branches(expr: &str) -> bool {
    // Extract all THEN and ELSE values
    let mut rest = expr;
    while let Some(idx) = rest.find(" then ") {
        let after = &rest[idx + 6..];
        // Value runs until next WHEN, ELSE, or END
        let end = after
            .find(" when ")
            .or_else(|| after.find(" else "))
            .or_else(|| after.find(" end"))
            .unwrap_or(after.len());
        let val = after[..end].trim();
        if !is_literal(val) {
            return false;
        }
        rest = &after[end..];
    }
    // Check ELSE
    if let Some(idx) = expr.rfind(" else ") {
        let after = &expr[idx + 6..];
        let end = after.find(" end").unwrap_or(after.len());
        let val = after[..end].trim();
        if !is_literal(val) {
            return false;
        }
    }
    true
}

/// Window functions that are guaranteed to return NOT NULL.
fn is_not_null_window_function(expr: &str) -> bool {
    expr.starts_with("row_number(")
        || expr.starts_with("rank(")
        || expr.starts_with("dense_rank(")
        || expr.starts_with("ntile(")
        || expr.starts_with("cume_dist(")
        || expr.starts_with("percent_rank(")
}

/// Date/time functions guaranteed NOT NULL.
fn is_not_null_datetime_function(expr: &str) -> bool {
    expr.starts_with("now(")
        || expr.starts_with("clock_timestamp(")
        || expr.starts_with("statement_timestamp(")
        || expr.starts_with("transaction_timestamp(")
        || expr == "localtime"
        || expr == "localtimestamp"
        || expr.starts_with("extract(")
        || expr.starts_with("date_part(")
        || expr.starts_with("age(")
        || expr.starts_with("date_trunc(")
}

/// Scalar functions that return NOT NULL given non-NULL arguments.
/// We assume the input is non-NULL here (conservative: only for common patterns).
fn is_not_null_scalar_function(expr: &str) -> bool {
    expr.starts_with("length(")
        || expr.starts_with("char_length(")
        || expr.starts_with("octet_length(")
        || expr.starts_with("lower(")
        || expr.starts_with("upper(")
        || expr.starts_with("trim(")
        || expr.starts_with("ltrim(")
        || expr.starts_with("rtrim(")
        || expr.starts_with("concat(")
        || expr.starts_with("replace(")
        || expr.starts_with("substring(")
        || expr.starts_with("left(")
        || expr.starts_with("right(")
        || expr.starts_with("md5(")
        || expr.starts_with("sha256(")
        || expr.starts_with("encode(")
        || expr.starts_with("decode(")
        || expr.starts_with("abs(")
        || expr.starts_with("ceil(")
        || expr.starts_with("floor(")
        || expr.starts_with("round(")
        || expr.starts_with("trunc(")
        || expr.starts_with("sign(")
        || expr.starts_with("mod(")
        || expr.starts_with("power(")
        || expr.starts_with("sqrt(")
        || expr.starts_with("greatest(")
        || expr.starts_with("least(")
        || expr.starts_with("array_length(")
        || expr.starts_with("cardinality(")
        || expr.starts_with("jsonb_build_object(")
        || expr.starts_with("jsonb_build_array(")
        || expr.starts_with("json_build_object(")
        || expr.starts_with("json_build_array(")
        || expr.starts_with("to_char(")
        || expr.starts_with("to_number(")
        || expr.starts_with("to_date(")
        || expr.starts_with("to_timestamp(")
        || expr.starts_with("gen_random_uuid(")
}

/// Fetch EXPLAIN output for a query (only when `explain` feature is enabled).
///
/// Returns a human-readable summary of the query plan. Errors are silently
/// ignored -- EXPLAIN is informational and must never block compilation.
#[cfg(feature = "explain")]
fn fetch_explain_plan(conn: &mut Connection, parsed: &ParsedQuery) -> Option<String> {
    // EXPLAIN cannot handle parameterized queries directly. We use
    // EXPLAIN (FORMAT TEXT) with a generic plan (PG 16+ supports
    // EXPLAIN (GENERIC_PLAN) for prepared statements).
    //
    // For older PG versions, we try EXPLAIN on the raw SQL. If it fails
    // (e.g. because of parameters), we skip silently.
    let explain_sql = format!("EXPLAIN (FORMAT TEXT, COSTS) {}", parsed.positional_sql);

    match conn.simple_query_rows(&explain_sql) {
        Ok(rows) => {
            let lines: Vec<String> = rows
                .into_iter()
                .filter_map(|row| row.into_iter().next().flatten())
                .collect();

            if lines.is_empty() {
                None
            } else {
                let plan_text = lines.join("\n");

                // Analyze plan for performance warnings
                let threshold = crate::explain::explain_threshold();
                let warnings = crate::explain::analyze_plan(&plan_text, threshold);
                for warning in &warnings {
                    eprintln!("warning: [bsql] {}", warning.message);
                }

                Some(plan_text)
            }
        }
        Err(_) => None,
    }
}

/// Determine nullability for all columns in a single PG round-trip.
///
/// For columns backed by a real table, queries `pg_attribute.attnotnull` in
/// batch using string-interpolated OIDs. Computed columns (aggregates,
/// functions) default to nullable (the safe choice).
fn resolve_nullability_batch(conn: &mut Connection, columns: &[ColumnDesc]) -> Vec<bool> {
    let col_count = columns.len();
    // Default: all nullable (safe). We overwrite entries we can resolve.
    let mut result = vec![true; col_count];

    // Collect (table_oid, column_id) pairs for table-backed columns
    let mut table_oids: Vec<u32> = Vec::new();
    let mut col_nums: Vec<i16> = Vec::new();
    let mut col_indices: Vec<usize> = Vec::new();

    for (i, col) in columns.iter().enumerate() {
        if col.table_oid != 0 && col.column_id != 0 {
            table_oids.push(col.table_oid);
            col_nums.push(col.column_id);
            col_indices.push(i);
        }
    }

    if table_oids.is_empty() {
        return result;
    }

    // Build an ARRAY literal for each: '{oid1,oid2,...}' and '{num1,num2,...}'
    let oid_array = format!(
        "ARRAY[{}]::oid[]",
        table_oids
            .iter()
            .map(|o| o.to_string())
            .collect::<Vec<_>>()
            .join(",")
    );
    let num_array = format!(
        "ARRAY[{}]::int2[]",
        col_nums
            .iter()
            .map(|n| n.to_string())
            .collect::<Vec<_>>()
            .join(",")
    );

    // Single batched query: unnest the OID/attnum arrays and join pg_attribute
    let query = format!(
        "SELECT a.attrelid, a.attnum, NOT a.attnotnull \
         FROM pg_attribute a \
         WHERE (a.attrelid, a.attnum) IN (\
             SELECT unnest({oid_array}), unnest({num_array})\
         )"
    );

    if let Ok(rows) = conn.simple_query_rows(&query) {
        // Build lookup: (table_oid, col_num) -> original column index
        let mut lookup: std::collections::HashMap<(u32, i16), Vec<usize>> =
            std::collections::HashMap::with_capacity(table_oids.len());
        for (idx, (&t, &c)) in table_oids.iter().zip(col_nums.iter()).enumerate() {
            lookup.entry((t, c)).or_default().push(col_indices[idx]);
        }

        for row in &rows {
            // Columns: attrelid (oid as text), attnum (int2 as text), is_nullable (bool as text)
            let oid: u32 = row
                .first()
                .and_then(|v| v.as_deref())
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);
            let num: i16 = row
                .get(1)
                .and_then(|v| v.as_deref())
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);
            let is_nullable: bool = row
                .get(2)
                .and_then(|v| v.as_deref())
                .map(|s| s == "t" || s == "true")
                .unwrap_or(true);
            if let Some(indices) = lookup.get(&(oid, num)) {
                for &idx in indices {
                    result[idx] = is_nullable;
                }
            }
        }
    }
    // If the query fails, all columns stay nullable (safe default)

    result
}

/// Detect which parameter OIDs are PostgreSQL enum types.
///
/// Queries `pg_type.typtype` for each OID. Returns `'e'` for enum types.
/// Uses a single batched simple query with string-interpolated OIDs.
fn detect_pg_enums(conn: &mut Connection, oids: &[u32]) -> SmallVec<[bool; 8]> {
    if oids.is_empty() {
        return SmallVec::new();
    }

    let oid_list = oids
        .iter()
        .map(|o| o.to_string())
        .collect::<Vec<_>>()
        .join(",");

    let query = format!("SELECT oid, typtype FROM pg_type WHERE oid IN ({oid_list})");

    let mut enum_map: std::collections::HashMap<u32, bool> =
        std::collections::HashMap::with_capacity(oids.len());

    if let Ok(rows) = conn.simple_query_rows(&query) {
        for row in &rows {
            let oid: u32 = row
                .first()
                .and_then(|v| v.as_deref())
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);
            let typtype: &str = row.get(1).and_then(|v| v.as_deref()).unwrap_or("b");
            enum_map.insert(oid, typtype == "e");
        }
    }

    oids.iter()
        .map(|oid| enum_map.get(oid).copied().unwrap_or(false))
        .collect()
}

/// Detect which column type OIDs are PostgreSQL enum types.
///
/// Similar to `detect_pg_enums` but for column OIDs. Only queries OIDs
/// that are not in the standard built-in type range (< 10000).
fn detect_column_enums(conn: &mut Connection, columns: &[ColumnDesc]) -> Vec<bool> {
    let mut result = vec![false; columns.len()];

    // Only check non-built-in OIDs (built-in types are never enums)
    let custom_oids: Vec<(usize, u32)> = columns
        .iter()
        .enumerate()
        .filter(|(_, c)| c.type_oid >= 10000)
        .map(|(i, c)| (i, c.type_oid))
        .collect();

    if custom_oids.is_empty() {
        return result;
    }

    let oid_list = custom_oids
        .iter()
        .map(|(_, o)| o.to_string())
        .collect::<Vec<_>>()
        .join(",");

    let query = format!("SELECT oid, typtype FROM pg_type WHERE oid IN ({oid_list})");

    if let Ok(rows) = conn.simple_query_rows(&query) {
        let mut enum_set: std::collections::HashSet<u32> = std::collections::HashSet::new();
        for row in &rows {
            let oid: u32 = row
                .first()
                .and_then(|v| v.as_deref())
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);
            let typtype: &str = row.get(1).and_then(|v| v.as_deref()).unwrap_or("b");
            if typtype == "e" {
                enum_set.insert(oid);
            }
        }
        for &(idx, oid) in &custom_oids {
            if enum_set.contains(&oid) {
                result[idx] = true;
            }
        }
    }

    result
}

/// Check that user-declared parameter types match what PostgreSQL expects.
pub fn check_param_types(
    parsed: &ParsedQuery,
    validation: &ValidationResult,
) -> Result<(), String> {
    check_params_against_pg(
        &parsed.params,
        &validation.param_pg_oids,
        &validation.param_is_pg_enum,
        false,
        "",
    )
}

/// Validate all dynamic query variants against PostgreSQL.
///
/// Each variant is PREPAREd independently. The first variant's columns
/// are used as the canonical result type (all variants must return the
/// same columns — the base SELECT is identical, only WHERE clauses differ).
///
/// Note: superseded by `validate_clauses_linear` which uses O(N+1) PREPAREs.
/// Kept for backward compatibility and tests.
pub fn validate_variants(
    variants: &[QueryVariant],
    parsed: &ParsedQuery,
    conn: &mut Connection,
) -> Result<ValidationResult, String> {
    if variants.len() <= 1 {
        // Single variant or no optional clauses — use normal validation
        return validate_query(parsed, conn);
    }

    // Validate every variant and collect results.
    // All variants must produce the same column set.
    let mut canonical_result: Option<ValidationResult> = None;

    for (i, variant) in variants.iter().enumerate() {
        let result = validate_variant(variant, conn, parsed, i)?;

        // Check parameter type compatibility for this variant
        check_variant_param_types(variant, &result)?;

        if let Some(ref canonical) = canonical_result {
            // Verify column set matches the canonical (variant 0) result.
            // This should always be true for optional WHERE clauses,
            // but we check defensively.
            if result.columns.len() != canonical.columns.len() {
                return Err(format!(
                    "variant {} (mask {:#06b}) returns {} columns, but variant 0 \
                     returns {} columns. Optional clauses must not change the SELECT list.",
                    i,
                    variant.mask,
                    result.columns.len(),
                    canonical.columns.len()
                ));
            }
        } else {
            canonical_result = Some(result);
        }
    }

    canonical_result.ok_or_else(|| "no variants to validate (internal error)".to_owned())
}

fn validate_variant(
    variant: &QueryVariant,
    conn: &mut Connection,
    parsed: &ParsedQuery,
    variant_index: usize,
) -> Result<ValidationResult, String> {
    let result = conn
        .prepare_describe(&variant.sql)
        .map_err(|e| format_variant_driver_error(&e, variant, parsed, variant_index))?;

    let param_pg_oids: SmallVec<[u32; 8]> = result.param_oids.iter().copied().collect();
    let param_is_pg_enum = detect_pg_enums(conn, &result.param_oids);

    let columns = build_columns(conn, &result.columns, &variant.sql)?;

    Ok(ValidationResult {
        columns,
        param_pg_oids,
        param_is_pg_enum,
        #[cfg(feature = "explain")]
        explain_plan: None,
    })
}

/// Check parameter types for a specific variant.
pub fn check_variant_param_types(
    variant: &QueryVariant,
    validation: &ValidationResult,
) -> Result<(), String> {
    check_params_against_pg(
        &variant.params,
        &validation.param_pg_oids,
        &validation.param_is_pg_enum,
        true,
        &format!("variant (mask {:#06b})", variant.mask),
    )
}

/// Unified parameter type checking against PostgreSQL OIDs.
///
/// `strip_option_wrapper`: when true, strips `Option<>` before comparison
/// (used for dynamic query variants where optional clause params are `Option<T>`).
///
/// `context`: empty string for static queries, or a description like
/// `"variant (mask 0b0011)"` for error messages.
fn check_params_against_pg(
    params: &[crate::parse::Param],
    pg_oids: &[u32],
    pg_enum_flags: &[bool],
    strip_option_wrapper: bool,
    context: &str,
) -> Result<(), String> {
    if params.len() != pg_oids.len() {
        let ctx = if context.is_empty() {
            String::new()
        } else {
            format!(" in {context}")
        };
        return Err(format!(
            "parameter count mismatch{ctx}: query has {} parameters but PostgreSQL \
             expects {}. Check your $name: Type declarations.",
            params.len(),
            pg_oids.len()
        ));
    }

    for (i, (param, &pg_oid)) in params.iter().zip(pg_oids).enumerate() {
        let is_pg_enum = pg_enum_flags.get(i).copied().unwrap_or(false);

        let check_type = if strip_option_wrapper {
            strip_option(&param.rust_type)
        } else {
            &param.rust_type
        };

        if is_pg_enum {
            if matches!(check_type, "&str" | "String") {
                continue;
            }
            if crate::types::is_known_non_enum_type(check_type) {
                return Err(format!(
                    "type `{}` cannot be used for PostgreSQL enum parameter `${}`. \
                     Use `&str`, `String`, or a `#[bsql::pg_enum]` type.",
                    param.rust_type, param.name
                ));
            }
            // Unknown type (likely a #[pg_enum] type) -- accept, runtime ToSql verifies
            continue;
        }

        if !crate::types::is_param_compatible_extended(check_type, pg_oid) {
            let pg_name = bsql_core::types::pg_name_for_oid(pg_oid).unwrap_or("unknown");
            let extra_hint = match crate::types::resolve_rust_type(pg_oid) {
                Ok(expected) => format!(" (expected `{expected}`)"),
                Err(msg) => format!("{msg}"),
            };
            return Err(format!(
                "type mismatch for parameter `${}`: declared `{}` but PostgreSQL \
                 expects `{}` (OID {}){extra_hint}",
                param.name, param.rust_type, pg_name, pg_oid
            ));
        }
    }

    Ok(())
}

/// Strip `Option<...>` wrapper from a type string, returning the inner type.
/// If the type is not `Option<T>`, returns it unchanged.
fn strip_option(ty: &str) -> &str {
    if let Some(inner) = ty.strip_prefix("Option<") {
        if let Some(inner) = inner.strip_suffix('>') {
            return inner;
        }
    }
    ty
}

/// Extract the common parts of a DriverError: message, detail, hint.
fn format_driver_error_base(e: &DriverError) -> String {
    match e {
        DriverError::Server {
            message,
            detail,
            hint,
            position,
            ..
        } => {
            let mut out = format!("PostgreSQL error: {message}");
            if let Some(pos) = position {
                out.push_str(&format!(" (at position {pos})"));
            }
            if let Some(d) = detail {
                out.push_str(&format!("\n  detail: {d}"));
            }
            if let Some(h) = hint {
                out.push_str(&format!("\n  hint: {h}"));
            }
            out
        }
        other => format!("PostgreSQL error: {other}"),
    }
}

/// Format a variant-specific PostgreSQL error with context about which
/// clause combination caused the failure.
fn format_variant_driver_error(
    e: &DriverError,
    variant: &QueryVariant,
    parsed: &ParsedQuery,
    variant_index: usize,
) -> String {
    let n = parsed.optional_clauses.len();
    let included: Vec<usize> = (0..n).filter(|&i| (variant.mask & (1 << i)) != 0).collect();

    let clause_desc = if included.is_empty() {
        "no optional clauses included".to_owned()
    } else {
        let clause_strs: Vec<String> = included
            .iter()
            .map(|&i| {
                format!(
                    "clause {} `[{}]`",
                    i, parsed.optional_clauses[i].sql_fragment
                )
            })
            .collect();
        format!("with {}", clause_strs.join(", "))
    };

    let base_msg = format_driver_error_base(e);
    format!(
        "optional clause variant {} ({clause_desc}) produces invalid SQL:\n  \
         {base_msg}\n  SQL: {}",
        variant_index, variant.sql
    )
}

/// Format a PostgreSQL error into a developer-friendly compile error message.
fn format_driver_error(e: &DriverError, parsed: &ParsedQuery) -> String {
    let mut out = format_driver_error_base(e);

    out.push_str(&format!("\n         SQL: {}", parsed.positional_sql));

    // Show a position indicator if the driver provides one.
    if let DriverError::Server {
        position: Some(pos),
        ..
    } = e
    {
        let col = (*pos as usize).saturating_sub(1); // 1-indexed -> 0-indexed
        let prefix_len = "         SQL: ".len();
        let marker = format!("\n{}{}", " ".repeat(prefix_len + col), "^");
        out.push_str(&marker);
    }

    out
}

/// Validate a query against a live PostgreSQL instance, with "did you mean?"
/// suggestions on failure.
pub fn validate_query_with_suggestions(
    parsed: &ParsedQuery,
    conn: &mut Connection,
) -> Result<ValidationResult, String> {
    match validate_query(parsed, conn) {
        Ok(result) => Ok(result),
        Err(base_error) => {
            // Enhance the error with "did you mean?" suggestions.
            if let Some(suggestion) = crate::suggest::enhance_error(&base_error, conn) {
                Err(format!("{base_error}{suggestion}"))
            } else {
                Err(base_error)
            }
        }
    }
}

// NOTE: `validate_sort_variants` was removed in v0.11. The proc macro cannot
// access sort enum variants (they live in user code), so compile-time validation
// of individual ORDER BY fragments is not possible without a registry. The query
// structure is validated with a dummy ORDER BY, but individual sort SQL fragments
// are verified only at runtime. See sort_enum.rs doc comment for details.

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

    // --- strip_option ---

    #[test]
    fn strip_option_wraps_i32() {
        assert_eq!(strip_option("Option<i32>"), "i32");
    }

    #[test]
    fn strip_option_no_change_plain_type() {
        assert_eq!(strip_option("i32"), "i32");
    }

    #[test]
    fn strip_option_nested() {
        // Option<Option<i32>> -> Option<i32> (only strips outer)
        assert_eq!(strip_option("Option<Option<i32>>"), "Option<i32>");
    }

    #[test]
    fn strip_option_with_str() {
        assert_eq!(strip_option("Option<&str>"), "&str");
    }

    #[test]
    fn strip_option_with_string() {
        assert_eq!(strip_option("Option<String>"), "String");
    }

    #[test]
    fn strip_option_with_whitespace_strips_outer() {
        // strip_option matches "Option<" prefix and ">" suffix regardless of inner content
        assert_eq!(strip_option("Option< i32 >"), " i32 ");
    }

    #[test]
    fn strip_option_empty_string() {
        assert_eq!(strip_option(""), "");
    }

    #[test]
    fn strip_option_prefix_only() {
        // "Option<i32" without closing > should not strip
        assert_eq!(strip_option("Option<i32"), "Option<i32");
    }

    // --- format_driver_error_base ---

    #[test]
    fn format_server_error_basic() {
        let err = DriverError::Server {
            code: *b"42P01",
            message: "relation \"users\" does not exist".into(),
            detail: None,
            hint: None,
            position: None,
        };
        let msg = format_driver_error_base(&err);
        assert!(msg.contains("relation \"users\" does not exist"));
        assert!(msg.starts_with("PostgreSQL error:"));
    }

    #[test]
    fn format_server_error_with_detail_and_hint() {
        let err = DriverError::Server {
            code: *b"42P01",
            message: "something went wrong".into(),
            detail: Some("extra detail here".into()),
            hint: Some("try this instead".into()),
            position: None,
        };
        let msg = format_driver_error_base(&err);
        assert!(msg.contains("something went wrong"));
        assert!(msg.contains("detail: extra detail here"));
        assert!(msg.contains("hint: try this instead"));
    }

    #[test]
    fn format_server_error_with_position() {
        let err = DriverError::Server {
            code: *b"42601",
            message: "syntax error".into(),
            detail: None,
            hint: None,
            position: Some(15),
        };
        let msg = format_driver_error_base(&err);
        assert!(msg.contains("at position 15"));
    }

    #[test]
    fn format_non_server_error() {
        let err = DriverError::Pool("connection lost".into());
        let msg = format_driver_error_base(&err);
        assert!(msg.contains("PostgreSQL error:"));
        assert!(msg.contains("connection lost"));
    }

    // --- format_driver_error (includes SQL) ---

    #[test]
    fn format_driver_error_includes_sql() {
        let err = DriverError::Server {
            code: *b"42P01",
            message: "relation does not exist".into(),
            detail: None,
            hint: None,
            position: None,
        };
        let parsed = crate::parse::parse_query("SELECT id FROM users WHERE id = $id: i32").unwrap();
        let msg = format_driver_error(&err, &parsed);
        assert!(msg.contains("SQL:"), "should include SQL in error: {msg}");
        assert!(msg.contains("$1"), "should include positional SQL: {msg}");
    }

    #[test]
    fn format_driver_error_includes_position_marker() {
        let err = DriverError::Server {
            code: *b"42601",
            message: "syntax error".into(),
            detail: None,
            hint: None,
            position: Some(8),
        };
        let parsed = crate::parse::parse_query("SELECT id FROM users WHERE id = $id: i32").unwrap();
        let msg = format_driver_error(&err, &parsed);
        assert!(msg.contains('^'), "should include position marker: {msg}");
    }

    // --- check_params_against_pg ---

    #[test]
    fn check_params_count_mismatch() {
        let params = vec![Param {
            name: "id".into(),
            rust_type: "i32".into(),
            position: 1,
        }];
        // PG expects 2 params but we declared 1
        let pg_oids = [23u32, 25u32]; // int4, text
        let pg_enum = [false, false];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("parameter count mismatch"), "error: {err}");
    }

    #[test]
    fn check_params_count_mismatch_with_context() {
        let params = vec![];
        let pg_oids = [23u32];
        let pg_enum = [false];
        let result =
            check_params_against_pg(&params, &pg_oids, &pg_enum, false, "variant (mask 0b0011)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("variant (mask 0b0011)"),
            "should include context: {err}"
        );
    }

    #[test]
    fn check_params_type_mismatch() {
        let params = vec![Param {
            name: "id".into(),
            rust_type: "&str".into(), // declared &str
            position: 1,
        }];
        let pg_oids = [23u32]; // PG expects int4
        let pg_enum = [false];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("type mismatch"),
            "should mention type mismatch: {err}"
        );
    }

    #[test]
    fn check_params_matching_types_ok() {
        let params = vec![Param {
            name: "id".into(),
            rust_type: "i32".into(),
            position: 1,
        }];
        let pg_oids = [23u32]; // int4
        let pg_enum = [false];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_ok());
    }

    #[test]
    fn check_params_empty_ok() {
        let params: Vec<Param> = vec![];
        let pg_oids: [u32; 0] = [];
        let pg_enum: [bool; 0] = [];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_ok());
    }

    #[test]
    fn check_params_enum_with_str_ok() {
        let params = vec![Param {
            name: "status".into(),
            rust_type: "&str".into(),
            position: 1,
        }];
        let pg_oids = [99999u32]; // some custom enum OID
        let pg_enum = [true];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_ok(), "enum param with &str should be accepted");
    }

    #[test]
    fn check_params_enum_with_string_ok() {
        let params = vec![Param {
            name: "status".into(),
            rust_type: "String".into(),
            position: 1,
        }];
        let pg_oids = [99999u32];
        let pg_enum = [true];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_ok(), "enum param with String should be accepted");
    }

    #[test]
    fn check_params_enum_with_i32_error() {
        let params = vec![Param {
            name: "status".into(),
            rust_type: "i32".into(),
            position: 1,
        }];
        let pg_oids = [99999u32];
        let pg_enum = [true];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("cannot be used for PostgreSQL enum"),
            "should reject i32 for enum: {err}"
        );
    }

    #[test]
    fn check_params_enum_with_custom_type_ok() {
        // Unknown type (likely a #[pg_enum] user type) should be accepted
        let params = vec![Param {
            name: "status".into(),
            rust_type: "MyStatusEnum".into(),
            position: 1,
        }];
        let pg_oids = [99999u32];
        let pg_enum = [true];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_ok(), "custom enum type should be accepted");
    }

    #[test]
    fn check_params_strip_option_in_variant_mode() {
        // In variant mode (strip_option_wrapper=true), Option<i32> -> i32
        let params = vec![Param {
            name: "id".into(),
            rust_type: "Option<i32>".into(),
            position: 1,
        }];
        let pg_oids = [23u32]; // int4
        let pg_enum = [false];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, true, "variant");
        assert!(
            result.is_ok(),
            "Option<i32> stripped to i32 should match int4"
        );
    }

    #[test]
    fn check_params_strip_option_mismatch() {
        let params = vec![Param {
            name: "id".into(),
            rust_type: "Option<&str>".into(),
            position: 1,
        }];
        let pg_oids = [23u32]; // int4
        let pg_enum = [false];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, true, "variant");
        assert!(
            result.is_err(),
            "Option<&str> stripped to &str should not match int4"
        );
    }

    // --- is_known_not_null ---

    #[test]
    fn is_known_not_null_count() {
        assert!(is_known_not_null("count", "count(*)"));
        assert!(is_known_not_null("count", "COUNT(id)"));
        assert!(is_known_not_null("total", "count(*)"));
    }

    #[test]
    fn is_known_not_null_coalesce_with_literal() {
        assert!(is_known_not_null("x", "coalesce(name, 'unknown')"));
        assert!(is_known_not_null("x", "COALESCE(a, b, 0)"));
    }

    #[test]
    fn is_known_not_null_coalesce_without_literal() {
        assert!(!is_known_not_null("x", "coalesce(a, b)"));
    }

    #[test]
    fn is_known_not_null_exists() {
        assert!(is_known_not_null("x", "exists(select 1 from t)"));
    }

    #[test]
    fn is_known_not_null_literals() {
        assert!(is_known_not_null("x", "1"));
        assert!(is_known_not_null("x", "'hello'"));
        assert!(is_known_not_null("x", "true"));
        assert!(is_known_not_null("x", "42.5"));
    }

    #[test]
    fn is_known_not_null_current() {
        assert!(is_known_not_null("x", "current_timestamp"));
        assert!(is_known_not_null("x", "current_date"));
    }

    #[test]
    fn is_known_not_null_regular_column() {
        assert!(!is_known_not_null("name", "name"));
        assert!(!is_known_not_null("x", "some_function(a)"));
    }

    // --- parse_select_expressions ---

    #[test]
    fn parse_select_list_simple() {
        let exprs = parse_select_expressions("select id, name from users");
        assert_eq!(exprs, vec!["id", "name"]);
    }

    #[test]
    fn parse_select_list_with_functions() {
        let exprs =
            parse_select_expressions("select count(*), coalesce(name, 'x') as n from users");
        assert_eq!(exprs, vec!["count(*)", "coalesce(name, 'x')"]);
    }

    #[test]
    fn parse_select_list_nested_parens() {
        let exprs =
            parse_select_expressions("select id, sum(case when x > 0 then 1 else 0 end) from t");
        assert_eq!(exprs, vec!["id", "sum(case when x > 0 then 1 else 0 end)"]);
    }

    #[test]
    fn parse_select_list_no_from() {
        // "SELECT 1" has no FROM clause
        let exprs = parse_select_expressions("SELECT 1");
        assert_eq!(exprs, vec!["1"]);
    }

    #[test]
    fn parse_select_list_distinct() {
        let exprs = parse_select_expressions("SELECT DISTINCT id, name FROM t");
        assert_eq!(exprs, vec!["id", "name"]);
    }

    // --- is_known_not_null: aggregate functions that remain nullable ---

    #[test]
    fn sum_remains_nullable() {
        // SUM on an empty group returns NULL
        assert!(!is_known_not_null("total", "sum(col)"));
        assert!(!is_known_not_null("total", "SUM(amount)"));
    }

    #[test]
    fn avg_remains_nullable() {
        assert!(!is_known_not_null("avg", "avg(col)"));
        assert!(!is_known_not_null("average", "AVG(score)"));
    }

    #[test]
    fn max_remains_nullable() {
        assert!(!is_known_not_null("mx", "max(col)"));
        assert!(!is_known_not_null("mx", "MAX(created_at)"));
    }

    #[test]
    fn min_remains_nullable() {
        assert!(!is_known_not_null("mn", "min(col)"));
        assert!(!is_known_not_null("mn", "MIN(id)"));
    }

    #[test]
    fn coalesce_without_literal_remains_nullable() {
        // COALESCE(a, b) where both args are columns — still nullable
        assert!(!is_known_not_null("x", "coalesce(a, b)"));
        assert!(!is_known_not_null("x", "COALESCE(col1, col2)"));
    }

    #[test]
    fn count_distinct_is_not_null() {
        assert!(is_known_not_null("cnt", "count(distinct col)"));
        assert!(is_known_not_null("cnt", "COUNT(DISTINCT id)"));
    }

    #[test]
    fn arithmetic_expression_remains_nullable() {
        // `1 + 1` is an expression, not a single literal — the parser
        // sees "1 + 1" as a whole, which does not match a bare numeric literal
        assert!(!is_known_not_null("x", "1 + 1"));
    }

    #[test]
    fn cast_remains_nullable() {
        assert!(!is_known_not_null("x", "cast(col as integer)"));
        assert!(!is_known_not_null("x", "CAST(name AS TEXT)"));
    }

    #[test]
    fn nested_coalesce_count_is_not_null() {
        // COALESCE(COUNT(*), 0) — COUNT is NOT NULL, plus COALESCE with literal
        // But is_known_not_null checks the outermost expression.
        // It sees "coalesce(count(*), 0)" — COALESCE with literal 0 => NOT NULL
        assert!(is_known_not_null("x", "coalesce(count(*), 0)"));
    }

    #[test]
    fn count_star_not_null() {
        // Redundant but explicit: COUNT(*) is always NOT NULL
        assert!(is_known_not_null("count", "COUNT(*)"));
        assert!(is_known_not_null("x", "count(*)"));
    }

    #[test]
    fn coalesce_with_string_literal_not_null() {
        assert!(is_known_not_null("x", "coalesce(name, 'N/A')"));
    }

    #[test]
    fn coalesce_with_numeric_literal_not_null() {
        assert!(is_known_not_null("x", "coalesce(val, 0)"));
    }

    #[test]
    fn coalesce_with_boolean_literal_not_null() {
        assert!(is_known_not_null("x", "coalesce(flag, false)"));
    }

    // --- parse_select_expressions: more edge cases ---

    #[test]
    fn parse_select_empty_string() {
        let exprs = parse_select_expressions("");
        assert!(exprs.is_empty());
    }

    #[test]
    fn parse_select_star() {
        // SELECT * FROM t — * is the single expression
        let exprs = parse_select_expressions("SELECT * FROM t");
        assert_eq!(exprs, vec!["*"]);
    }

    #[test]
    fn parse_select_subquery_in_from() {
        // SELECT x FROM (SELECT 1 AS x) sub
        // The parser looks for " FROM " at depth 0. The subquery in FROM
        // changes depth, but the outer FROM is at depth 0.
        let exprs = parse_select_expressions("SELECT x FROM (SELECT 1 AS x) sub");
        assert_eq!(exprs, vec!["x"]);
    }

    #[test]
    fn parse_select_case_when() {
        let exprs = parse_select_expressions(
            "SELECT CASE WHEN status = 1 THEN 'active' ELSE 'inactive' END AS label FROM t",
        );
        assert_eq!(
            exprs,
            vec!["CASE WHEN status = 1 THEN 'active' ELSE 'inactive' END"]
        );
    }

    #[test]
    fn parse_select_mixed_columns_and_aggregates() {
        let exprs =
            parse_select_expressions("SELECT id, COUNT(*), name FROM users GROUP BY id, name");
        assert_eq!(exprs, vec!["id", "COUNT(*)", "name"]);
    }

    #[test]
    fn parse_select_no_select_keyword() {
        // Garbage input — should return empty
        let exprs = parse_select_expressions("INSERT INTO t VALUES (1)");
        assert!(exprs.is_empty());
    }

    // --- is_known_not_null: column name fallback ---

    #[test]
    fn is_known_not_null_column_name_count_fallback() {
        // When select_expr is empty, falls back to col_name
        assert!(is_known_not_null("count", ""));
    }

    #[test]
    fn is_known_not_null_empty_both() {
        // Empty column name and empty expression — not known NOT NULL
        assert!(!is_known_not_null("", ""));
    }

    // --- is_known_not_null: false literal ---

    #[test]
    fn is_known_not_null_false_literal() {
        assert!(is_known_not_null("x", "false"));
    }

    // --- is_known_not_null: COALESCE with negative number ---

    #[test]
    fn is_known_not_null_coalesce_with_negative_number() {
        assert!(is_known_not_null("x", "coalesce(val, -1)"));
    }

    // --- is_known_not_null: COALESCE with floating point literal ---

    #[test]
    fn is_known_not_null_coalesce_with_float_literal() {
        assert!(is_known_not_null("x", "coalesce(val, 0.0)"));
    }

    // --- is_known_not_null: COALESCE with boolean literal ---

    #[test]
    fn is_known_not_null_coalesce_with_true_literal() {
        assert!(is_known_not_null("x", "coalesce(flag, true)"));
    }

    // --- is_known_not_null: EXISTS is always not null ---

    #[test]
    fn is_known_not_null_exists_complex() {
        assert!(is_known_not_null(
            "has_orders",
            "exists(select 1 from orders where user_id = u.id)"
        ));
    }

    // --- is_known_not_null: CURRENT_TIMESTAMP etc ---

    #[test]
    fn is_known_not_null_current_user() {
        assert!(is_known_not_null("x", "current_user"));
    }

    // --- is_known_not_null: string literal ---

    #[test]
    fn is_known_not_null_empty_string_literal() {
        assert!(is_known_not_null("x", "''"));
    }

    // --- is_known_not_null: SUM is nullable ---

    #[test]
    fn sum_of_not_null_column_remains_nullable() {
        // SUM returns NULL for empty groups, even on NOT NULL columns
        assert!(!is_known_not_null("total", "SUM(amount)"));
    }

    // --- parse_select_expressions: trailing semicolon ---

    #[test]
    fn parse_select_with_trailing_semicolon() {
        let exprs = parse_select_expressions("SELECT 1;");
        assert_eq!(exprs, vec!["1"]);
    }

    // --- parse_select_expressions: multiple items no FROM ---

    #[test]
    fn parse_select_multiple_no_from() {
        let exprs = parse_select_expressions("SELECT 1, 'hello', true");
        assert_eq!(exprs, vec!["1", "'hello'", "true"]);
    }

    // --- strip_alias: complex cases ---

    #[test]
    fn strip_alias_simple() {
        assert_eq!(strip_alias("count(*) AS cnt"), "count(*)");
    }

    #[test]
    fn strip_alias_no_alias() {
        assert_eq!(strip_alias("id"), "id");
    }

    #[test]
    fn strip_alias_nested_as_in_parens() {
        // "CASE WHEN status AS thing END AS label" — should strip outer AS
        assert_eq!(
            strip_alias("CASE WHEN x THEN 'a' ELSE 'b' END AS label"),
            "CASE WHEN x THEN 'a' ELSE 'b' END"
        );
    }

    // --- check_params_against_pg: enum param with bool rejected ---

    #[test]
    fn check_params_enum_with_bool_error() {
        let params = vec![Param {
            name: "status".into(),
            rust_type: "bool".into(),
            position: 1,
        }];
        let pg_oids = [99999u32];
        let pg_enum = [true];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("cannot be used for PostgreSQL enum"),
            "should reject bool for enum: {err}"
        );
    }

    // --- check_params_against_pg: multiple params all matching ---

    #[test]
    fn check_params_multiple_matching() {
        let params = vec![
            Param {
                name: "id".into(),
                rust_type: "i32".into(),
                position: 1,
            },
            Param {
                name: "name".into(),
                rust_type: "&str".into(),
                position: 2,
            },
            Param {
                name: "flag".into(),
                rust_type: "bool".into(),
                position: 3,
            },
        ];
        let pg_oids = [23u32, 25, 16]; // int4, text, bool
        let pg_enum = [false, false, false];
        let result = check_params_against_pg(&params, &pg_oids, &pg_enum, false, "");
        assert!(result.is_ok());
    }

    // --- format_driver_error_base: Protocol error ---

    #[test]
    fn format_protocol_error() {
        let err = bsql_driver_postgres::DriverError::Protocol("unexpected msg type 'Z'".into());
        let msg = format_driver_error_base(&err);
        assert!(msg.contains("unexpected msg type"), "error: {msg}");
    }

    // --- is_known_not_null: numeric literal 0 ---

    #[test]
    fn is_known_not_null_zero_literal() {
        assert!(is_known_not_null("x", "0"));
    }

    // --- is_known_not_null: negative number as literal ---

    #[test]
    fn is_known_not_null_negative_number() {
        // "-1" as an expression — parse::<f64>() returns Ok
        assert!(is_known_not_null("x", "-1"));
    }

    // --- is_known_not_null: new patterns ---

    #[test]
    fn case_with_literal_branches_not_null() {
        assert!(is_known_not_null("x", "CASE WHEN a > 0 THEN 1 ELSE 0 END"));
        assert!(is_known_not_null(
            "x",
            "CASE WHEN active THEN 'yes' ELSE 'no' END"
        ));
    }

    #[test]
    fn case_with_column_branch_remains_nullable() {
        assert!(!is_known_not_null(
            "x",
            "CASE WHEN a > 0 THEN name ELSE 'unknown' END"
        ));
    }

    #[test]
    fn row_number_is_not_null() {
        assert!(is_known_not_null("x", "row_number()"));
        assert!(is_known_not_null("x", "rank()"));
        assert!(is_known_not_null("x", "dense_rank()"));
        assert!(is_known_not_null("x", "ntile(4)"));
    }

    #[test]
    fn now_and_datetime_functions_not_null() {
        assert!(is_known_not_null("x", "now()"));
        assert!(is_known_not_null("x", "clock_timestamp()"));
        assert!(is_known_not_null("x", "extract(year from created_at)"));
        assert!(is_known_not_null("x", "date_part('year', created_at)"));
        assert!(is_known_not_null("x", "date_trunc('month', created_at)"));
    }

    #[test]
    fn string_functions_not_null() {
        assert!(is_known_not_null("x", "length(name)"));
        assert!(is_known_not_null("x", "lower(name)"));
        assert!(is_known_not_null("x", "upper(name)"));
        assert!(is_known_not_null("x", "trim(name)"));
        assert!(is_known_not_null("x", "concat(first_name, ' ', last_name)"));
        assert!(is_known_not_null("x", "replace(name, 'old', 'new')"));
    }

    #[test]
    fn math_functions_not_null() {
        assert!(is_known_not_null("x", "abs(amount)"));
        assert!(is_known_not_null("x", "ceil(rating)"));
        assert!(is_known_not_null("x", "floor(rating)"));
        assert!(is_known_not_null("x", "round(price, 2)"));
        assert!(is_known_not_null("x", "greatest(a, b, 0)"));
        assert!(is_known_not_null("x", "least(a, b, 100)"));
    }

    #[test]
    fn array_functions_not_null() {
        assert!(is_known_not_null("x", "array_length(tags, 1)"));
        assert!(is_known_not_null("x", "cardinality(tags)"));
    }

    #[test]
    fn json_build_functions_not_null() {
        assert!(is_known_not_null("x", "jsonb_build_object('key', value)"));
        assert!(is_known_not_null("x", "json_build_array(1, 2, 3)"));
    }

    #[test]
    fn gen_random_uuid_not_null() {
        assert!(is_known_not_null("x", "gen_random_uuid()"));
    }

    #[test]
    fn to_char_and_conversion_functions_not_null() {
        assert!(is_known_not_null("x", "to_char(created_at, 'YYYY-MM-DD')"));
        assert!(is_known_not_null("x", "to_timestamp(epoch_secs)"));
    }

    #[test]
    fn sum_avg_still_nullable() {
        // SUM/AVG return NULL for empty groups — must stay Option
        assert!(!is_known_not_null("x", "sum(amount)"));
        assert!(!is_known_not_null("x", "avg(score)"));
        assert!(!is_known_not_null("x", "max(created_at)"));
        assert!(!is_known_not_null("x", "min(created_at)"));
    }

    #[test]
    fn unknown_function_remains_nullable() {
        assert!(!is_known_not_null("x", "my_custom_func(col)"));
    }
}