icydb-core 0.104.1

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

use crate::{
    db::{
        DbSession, PersistedRow, QueryError,
        access::AccessPlan,
        executor::{
            EntityAuthority, SharedPreparedExecutionPlan,
            pipeline::execute_initial_grouped_rows_for_canister,
        },
        query::builder,
        query::plan::{AccessPlannedQuery, LogicalPlan},
        session::sql::{
            SqlProjectionContract,
            projection::{
                SqlProjectionPayload, execute_sql_projection_rows_for_canister,
                grouped_sql_statement_result_from_page,
            },
        },
        sql::lowering::{
            LoweredSqlQuery, PreparedSqlParameterContract, PreparedSqlParameterTypeFamily,
            PreparedSqlStatement, lower_sql_command_from_prepared_statement,
        },
        sql::parser::{
            SqlAggregateCall, SqlDeleteStatement, SqlExplainTarget, SqlExpr, SqlProjection,
            SqlSelectStatement, SqlStatement,
        },
    },
    model::{entity::EntityModel, field::FieldKind},
    traits::{CanisterKind, EntityValue},
    value::Value,
};

///
/// PreparedSqlQuery
///
/// Session-owned prepared reduced-SQL query shape for v1 parameter binding.
/// This keeps parsing, normalization, and parameter-contract collection stable
/// across repeated executions while still reusing the existing bound SQL
/// execution path after literal substitution.
///

#[derive(Clone, Debug)]
pub(in crate::db) struct PreparedSqlQuery {
    source_sql: String,
    statement: PreparedSqlStatement,
    parameter_contracts: Vec<PreparedSqlParameterContract>,
    execution_template: Option<PreparedSqlExecutionTemplate>,
}

///
/// PreparedSqlExecutionTemplate
///
/// Internal prepared SQL execution variants for supported fixed-route
/// parameter families.
/// `0.99` starts introducing symbolic slot ownership here without widening the
/// planner-wide IR, so legacy sentinel-backed templates and new symbolic
/// templates can coexist while the lane is migrated in bounded slices.
/// `0.103` keeps that boundary explicit: prepared templates are only for
/// predicate/access-owned parameter shapes. General expression-owned `WHERE`
/// semantics must stay on the normal bound-SQL fallback path instead of
/// growing template-local `filter_expr` ownership.
///

#[derive(Clone, Debug)]
enum PreparedSqlExecutionTemplate {
    SymbolicScalar(PreparedSqlSymbolicScalarTemplate),
    SymbolicGrouped(PreparedSqlSymbolicGroupedTemplate),
    Legacy(PreparedSqlLegacyExecutionTemplate),
}

///
/// PreparedSqlLegacyExecutionTemplate
///
/// Legacy fixed-route prepared SQL template that still freezes one concrete
/// planner-owned plan through collision-resistant sentinel values.
/// This stays in place for the existing numeric/text/grouped template surface
/// while `0.99` moves narrower shapes onto symbolic slot ownership.
///

#[derive(Clone, Debug)]
struct PreparedSqlLegacyExecutionTemplate {
    authority: EntityAuthority,
    projection: SqlProjectionContract,
    plan: AccessPlannedQuery,
}

///
/// PreparedSqlSymbolicScalarTemplate
///
/// First symbolic-slot prepared SQL template family for `0.99`.
/// This owns one scalar compare-family prepared route through symbolic slot
/// metadata so scalar prepared queries can stay on the fast lane without
/// sentinel literals in execution.
///

#[derive(Clone, Debug)]
struct PreparedSqlSymbolicScalarTemplate {
    authority: EntityAuthority,
    projection: SqlProjectionContract,
    plan: AccessPlannedQuery,
    predicate: Option<PreparedSqlScalarPredicateTemplate>,
    access: Option<PreparedSqlScalarAccessPathTemplate>,
}

///
/// PreparedSqlSymbolicGroupedTemplate
///
/// Symbolic grouped prepared SQL template for the grouped `0.99` lane.
/// This template owns grouped scalar `WHERE`, grouped access payloads, and
/// optional `HAVING` rebinding on the same frozen grouped route.
///

#[derive(Clone, Debug)]
struct PreparedSqlSymbolicGroupedTemplate {
    authority: EntityAuthority,
    projection: SqlProjectionContract,
    plan: AccessPlannedQuery,
    predicate: Option<PreparedSqlScalarPredicateTemplate>,
    access: Option<PreparedSqlScalarAccessPathTemplate>,
    having_expr: Option<PreparedSqlGroupedExprTemplate>,
}

///
/// PreparedSqlScalarCompareSlotTemplate
///
/// Frozen compare slot metadata for one symbolic scalar prepared template.
/// The template keeps the planner-chosen field/operator/coercion shape and
/// reads only the runtime value from the referenced binding slot.
///

#[derive(Clone, Debug)]
struct PreparedSqlScalarCompareSlotTemplate {
    field: String,
    op: crate::db::predicate::CompareOp,
    coercion: crate::db::predicate::CoercionId,
    slot_index: usize,
}

///
/// PreparedSqlScalarPredicateTemplate
///
/// Symbolic scalar prepared predicate template for the first `0.99` lane.
/// This keeps logical predicate ownership local to prepared SQL execution
/// while reusing planner-owned compare metadata gathered during lowering.
///

#[derive(Clone, Debug)]
enum PreparedSqlScalarPredicateTemplate {
    Compare(PreparedSqlScalarCompareSlotTemplate),
    And(Vec<Self>),
    Or(Vec<Self>),
    Not(Box<Self>),
}

///
/// PreparedSqlScalarAccessValueTemplate
///
/// Frozen scalar access payload leaf for the first symbolic access slice.
/// Static leaves keep planner-owned access literals unchanged, while slot
/// leaves read their runtime value through the prepared binding vector.
///

#[derive(Clone, Debug)]
enum PreparedSqlScalarAccessValueTemplate {
    Static(Value),
    SlotLiteral(usize),
}

///
/// PreparedSqlScalarAccessPathTemplate
///
/// Symbolic scalar access payload template for the first `0.99` access slice.
/// This stays intentionally narrow on one single-path secondary prefix route
/// so prepared SQL can stop mutating access payloads by sentinel replacement.
///

#[derive(Clone, Debug)]
enum PreparedSqlScalarAccessPathTemplate {
    ByKey {
        key: PreparedSqlScalarAccessValueTemplate,
    },
    KeyRange {
        start: PreparedSqlScalarAccessValueTemplate,
        end: PreparedSqlScalarAccessValueTemplate,
    },
    IndexPrefix {
        index: crate::model::index::IndexModel,
        values: Vec<PreparedSqlScalarAccessValueTemplate>,
    },
}

///
/// PreparedSqlGroupedExprTemplate
///
/// Symbolic grouped post-aggregate expression template for the first grouped
/// `0.99` slice. Static subtrees keep planner-owned `Expr` nodes directly,
/// while bound literal leaves read their runtime value through slot identity.
///

#[derive(Clone, Debug)]
enum PreparedSqlGroupedExprTemplate {
    Static(crate::db::query::plan::expr::Expr),
    SlotLiteral(usize),
    Unary {
        op: crate::db::query::plan::expr::UnaryOp,
        expr: Box<Self>,
    },
    Binary {
        op: crate::db::query::plan::expr::BinaryOp,
        left: Box<Self>,
        right: Box<Self>,
    },
}

///
/// PreparedSqlExecutionTemplateKind
///
/// Test-only classifier for the internal prepared SQL execution template lane.
/// This keeps `0.99` migration coverage precise without exposing the internal
/// template representation to production callers.
///

#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum PreparedSqlExecutionTemplateKind {
    SymbolicScalar,
    SymbolicGrouped,
    Legacy,
}

impl PreparedSqlQuery {
    #[must_use]
    pub(in crate::db) fn source_sql(&self) -> &str {
        &self.source_sql
    }

    #[must_use]
    pub(in crate::db) const fn parameter_contracts(&self) -> &[PreparedSqlParameterContract] {
        self.parameter_contracts.as_slice()
    }

    #[must_use]
    pub(in crate::db) const fn parameter_count(&self) -> usize {
        self.parameter_contracts.len()
    }

    #[cfg(test)]
    #[must_use]
    pub(in crate::db) const fn template_kind_for_test(
        &self,
    ) -> Option<PreparedSqlExecutionTemplateKind> {
        match self.execution_template.as_ref() {
            Some(PreparedSqlExecutionTemplate::SymbolicScalar(_)) => {
                Some(PreparedSqlExecutionTemplateKind::SymbolicScalar)
            }
            Some(PreparedSqlExecutionTemplate::SymbolicGrouped(_)) => {
                Some(PreparedSqlExecutionTemplateKind::SymbolicGrouped)
            }
            Some(PreparedSqlExecutionTemplate::Legacy(_)) => {
                Some(PreparedSqlExecutionTemplateKind::Legacy)
            }
            None => None,
        }
    }
}

impl<C: CanisterKind> DbSession<C> {
    /// Prepare one parameterized reduced-SQL query shape for repeated execution.
    pub(in crate::db) fn prepare_sql_query<E>(
        &self,
        sql: &str,
    ) -> Result<PreparedSqlQuery, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let statement = crate::db::session::sql::parse_sql_statement_with_attribution(sql)
            .map(|(statement, _)| statement)?;
        Self::ensure_sql_query_statement_supported(&statement)?;

        let authority = EntityAuthority::for_type::<E>();
        let prepared = Self::prepare_sql_statement_for_authority(&statement, authority)?;
        let parameter_contracts = prepared
            .parameter_contracts(authority.model())
            .map_err(QueryError::from_sql_lowering_error)?;
        let execution_template =
            self.build_prepared_sql_execution_template(&prepared, &parameter_contracts, authority)?;

        Ok(PreparedSqlQuery {
            source_sql: sql.to_string(),
            statement: prepared,
            parameter_contracts,
            execution_template,
        })
    }

    /// Execute one prepared reduced-SQL query with one validated binding vector.
    pub(in crate::db) fn execute_prepared_sql_query<E>(
        &self,
        prepared: &PreparedSqlQuery,
        bindings: &[Value],
    ) -> Result<crate::db::session::sql::SqlStatementResult, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        validate_parameter_bindings(prepared.parameter_contracts(), bindings)?;

        if let Some(template) = prepared.execution_template.as_ref()
            && bindings.iter().all(|value| !matches!(value, Value::Null))
        {
            let bound_plan = match template {
                PreparedSqlExecutionTemplate::SymbolicScalar(template) => {
                    bind_symbolic_scalar_template_plan(
                        template.plan.clone(),
                        template.predicate.as_ref(),
                        template.access.as_ref(),
                        bindings,
                        template.authority,
                    )?
                }
                PreparedSqlExecutionTemplate::SymbolicGrouped(template) => {
                    bind_symbolic_grouped_template_plan(
                        template.plan.clone(),
                        template.predicate.as_ref(),
                        template.access.as_ref(),
                        template.having_expr.as_ref(),
                        bindings,
                        template.authority,
                    )?
                }
                PreparedSqlExecutionTemplate::Legacy(template) => bind_prepared_template_plan(
                    template.plan.clone(),
                    prepared.parameter_contracts(),
                    bindings,
                    template.authority,
                )?,
            };
            let prepared_plan =
                SharedPreparedExecutionPlan::from_plan(bound_plan.authority(), bound_plan.plan);

            let projection = match template {
                PreparedSqlExecutionTemplate::SymbolicScalar(template) => &template.projection,
                PreparedSqlExecutionTemplate::SymbolicGrouped(template) => &template.projection,
                PreparedSqlExecutionTemplate::Legacy(template) => &template.projection,
            };

            return self.execute_prepared_template_plan(prepared_plan, projection);
        }

        let bound_statement = prepared.statement.bind_literals(bindings)?;
        let authority = EntityAuthority::for_type::<E>();

        self.execute_bound_prepared_sql_query_without_caches(&bound_statement, authority)
    }

    // Build one internal fixed-route prepared SQL execution shell when every
    // parameter slot exposes a collision-resistant non-null template binding.
    // This boundary stays intentionally narrower than general SQL admission:
    // prepared templates only own predicate/access-shaped parameters, while
    // general expression-owned `WHERE` semantics stay on prepared fallback.
    fn build_prepared_sql_execution_template(
        &self,
        prepared: &PreparedSqlStatement,
        parameter_contracts: &[PreparedSqlParameterContract],
        authority: EntityAuthority,
    ) -> Result<Option<PreparedSqlExecutionTemplate>, QueryError> {
        if parameter_contracts.is_empty() {
            return Ok(None);
        }
        if let SqlStatement::Select(select) = prepared.statement()
            && select
                .predicate
                .as_ref()
                .is_some_and(sql_expr_uses_general_filter_expr_parameters)
        {
            return Ok(None);
        }
        if let Some(template) = self.build_symbolic_scalar_prepared_sql_execution_template(
            prepared,
            parameter_contracts,
            authority,
        )? {
            return Ok(Some(template));
        }
        if let Some(template) = self.build_symbolic_grouped_prepared_sql_execution_template(
            prepared,
            parameter_contracts,
            authority,
        )? {
            return Ok(Some(template));
        }

        let Some(template_bindings) = parameter_contracts
            .iter()
            .map(|contract| contract.template_binding().cloned())
            .collect::<Option<Vec<_>>>()
        else {
            return Ok(None);
        };
        if prepared_statement_contains_template_literal_collision(
            prepared.statement(),
            template_bindings.as_slice(),
        ) {
            return Ok(None);
        }
        let bound_statement = prepared.bind_literals(template_bindings.as_slice())?;
        let normalized_prepared =
            Self::prepare_sql_statement_for_authority(&bound_statement, authority)?;
        let lowered =
            lower_sql_command_from_prepared_statement(normalized_prepared, authority.model())
                .map_err(QueryError::from_sql_lowering_error)?;
        let Some(LoweredSqlQuery::Select(select)) = lowered.into_query() else {
            return Ok(None);
        };
        let structural = Self::structural_query_from_lowered_select(select, authority)?;
        let (_, plan) =
            self.build_structural_plan_with_visible_indexes_for_authority(structural, authority)?;
        let prepared_plan = SharedPreparedExecutionPlan::from_plan(authority, plan.clone());
        let projection = Self::sql_select_projection_contract_from_shared_prepared_plan(
            authority,
            &prepared_plan,
        );

        Ok(Some(PreparedSqlExecutionTemplate::Legacy(
            PreparedSqlLegacyExecutionTemplate {
                authority,
                projection,
                plan,
            },
        )))
    }

    // Build the first symbolic-slot prepared SQL template family for `0.99`.
    // This slice stays disciplined on purpose: scalar compare-family routes
    // only, with access binding widened only for one single-path index-prefix
    // access payload shape.
    #[expect(clippy::too_many_lines)]
    fn build_symbolic_scalar_prepared_sql_execution_template(
        &self,
        prepared: &PreparedSqlStatement,
        parameter_contracts: &[PreparedSqlParameterContract],
        authority: EntityAuthority,
    ) -> Result<Option<PreparedSqlExecutionTemplate>, QueryError> {
        if parameter_contracts.is_empty() {
            return Ok(None);
        }

        // Phase 1: admit only one scalar prepared SELECT with one compare-only
        // predicate shape owned entirely by the logical predicate tree.
        let SqlStatement::Select(select) = prepared.statement() else {
            return Ok(None);
        };
        let Some(sql_predicate) = select.predicate.as_ref() else {
            return Ok(None);
        };

        // Phase 2: compile one exemplar plan so the structural route stays
        // planner-owned while the scalar predicate moves onto a symbolic
        // template instantiated from slot metadata at execute time.
        let Some(exemplar_bindings) = parameter_contracts
            .iter()
            .map(prepared_sql_contract_exemplar_binding)
            .collect::<Option<Vec<_>>>()
        else {
            return Ok(None);
        };
        let mut exemplar_bindings = exemplar_bindings;
        apply_sql_range_exemplar_override(
            select.predicate.as_ref(),
            parameter_contracts,
            exemplar_bindings.as_mut_slice(),
            authority.model(),
        );
        let bound_statement = prepared.bind_literals(exemplar_bindings.as_slice())?;
        let normalized_prepared =
            Self::prepare_sql_statement_for_authority(&bound_statement, authority)?;
        let lowered =
            lower_sql_command_from_prepared_statement(normalized_prepared, authority.model())
                .map_err(QueryError::from_sql_lowering_error)?;
        let Some(LoweredSqlQuery::Select(select)) = lowered.into_query() else {
            return Ok(None);
        };
        let structural = Self::structural_query_from_lowered_select(select, authority)?;
        let (_, plan) =
            self.build_structural_plan_with_visible_indexes_for_authority(structural, authority)?;

        // Phase 3: freeze the symbolic predicate and, when needed, one
        // symbolic access payload only when the lowered scalar plan still
        // matches the admitted compare-family shape exactly.
        let LogicalPlan::Scalar(scalar) = &plan.logical else {
            return Ok(None);
        };

        let predicate_template = match scalar.predicate.as_ref() {
            Some(predicate) => {
                let Some(predicate_template) =
                    build_symbolic_scalar_predicate_template(sql_predicate, predicate)
                else {
                    return Ok(None);
                };

                Some(predicate_template)
            }
            None => None,
        };
        let symbolic_value_candidates = parameter_contracts
            .iter()
            .zip(exemplar_bindings.iter())
            .filter(|(contract, _)| contract.type_family() != PreparedSqlParameterTypeFamily::Bool)
            .map(|(_, binding)| binding.clone())
            .collect::<Vec<_>>();
        if predicate_template.is_none()
            && scalar.predicate.as_ref().is_some_and(|predicate| {
                predicate_contains_any_runtime_values(
                    predicate,
                    symbolic_value_candidates.as_slice(),
                )
            })
        {
            return Ok(None);
        }
        let access_template = build_symbolic_scalar_access_path_template(
            &plan.access,
            parameter_contracts,
            exemplar_bindings.as_slice(),
        );
        if access_template.is_none()
            && !symbolic_value_candidates.is_empty()
            && plan
                .access
                .contains_any_runtime_values(symbolic_value_candidates.as_slice())
        {
            return Ok(None);
        }
        if access_template.is_some()
            && prepared_statement_contains_template_literal_collision(
                prepared.statement(),
                exemplar_bindings.as_slice(),
            )
        {
            return Ok(None);
        }
        if predicate_template.is_none() && access_template.is_none() {
            return Ok(None);
        }

        let prepared_plan = SharedPreparedExecutionPlan::from_plan(authority, plan.clone());
        let projection = Self::sql_select_projection_contract_from_shared_prepared_plan(
            authority,
            &prepared_plan,
        );

        Ok(Some(PreparedSqlExecutionTemplate::SymbolicScalar(
            PreparedSqlSymbolicScalarTemplate {
                authority,
                projection,
                plan,
                predicate: predicate_template,
                access: access_template,
            },
        )))
    }

    // Build the first grouped symbolic-slot prepared SQL template family for
    // `0.99`: admitted grouped scalar predicates, grouped access payloads, and
    // optional compare-family HAVING, with grouped routing and access
    // ownership still frozen through one exemplar plan.
    #[expect(clippy::too_many_lines)]
    fn build_symbolic_grouped_prepared_sql_execution_template(
        &self,
        prepared: &PreparedSqlStatement,
        parameter_contracts: &[PreparedSqlParameterContract],
        authority: EntityAuthority,
    ) -> Result<Option<PreparedSqlExecutionTemplate>, QueryError> {
        if parameter_contracts.is_empty() {
            return Ok(None);
        }

        let SqlStatement::Select(statement) = prepared.statement() else {
            return Ok(None);
        };

        // Phase 1: compile one exemplar grouped plan so route/projection stay
        // planner-owned while post-aggregate slot binding becomes symbolic.
        let Some(exemplar_bindings) = parameter_contracts
            .iter()
            .map(prepared_sql_contract_exemplar_binding)
            .collect::<Option<Vec<_>>>()
        else {
            return Ok(None);
        };
        let mut exemplar_bindings = exemplar_bindings;
        apply_sql_range_exemplar_override(
            statement.predicate.as_ref(),
            parameter_contracts,
            exemplar_bindings.as_mut_slice(),
            authority.model(),
        );
        if prepared_statement_contains_template_literal_collision(
            prepared.statement(),
            exemplar_bindings.as_slice(),
        ) {
            return Ok(None);
        }
        let bound_statement = prepared.bind_literals(exemplar_bindings.as_slice())?;
        let normalized_prepared =
            Self::prepare_sql_statement_for_authority(&bound_statement, authority)?;
        let lowered =
            lower_sql_command_from_prepared_statement(normalized_prepared, authority.model())
                .map_err(QueryError::from_sql_lowering_error)?;
        let Some(LoweredSqlQuery::Select(select)) = lowered.into_query() else {
            return Ok(None);
        };
        let structural = Self::structural_query_from_lowered_select(select, authority)?;
        let (_, plan) =
            self.build_structural_plan_with_visible_indexes_for_authority(structural, authority)?;

        // Phase 2: freeze the symbolic grouped template only when any grouped
        // scalar predicate or grouped post-aggregate expression still matches
        // the admitted symbolic slice exactly.
        let LogicalPlan::Grouped(grouped) = &plan.logical else {
            return Ok(None);
        };
        let symbolic_access_candidates = parameter_contracts
            .iter()
            .zip(exemplar_bindings.iter())
            .filter(|(contract, _)| contract.type_family() != PreparedSqlParameterTypeFamily::Bool)
            .map(|(_, binding)| binding.clone())
            .collect::<Vec<_>>();
        let access_template = build_symbolic_scalar_access_path_template(
            &plan.access,
            parameter_contracts,
            exemplar_bindings.as_slice(),
        );
        let predicate_template = match (
            statement.predicate.as_ref(),
            grouped.scalar.predicate.as_ref(),
        ) {
            (Some(sql_predicate), Some(predicate)) => {
                let Some(predicate_template) =
                    build_symbolic_scalar_predicate_template(sql_predicate, predicate)
                else {
                    return Ok(None);
                };

                Some(predicate_template)
            }
            // Grouped routes may push the whole admitted compare-family WHERE
            // into one symbolic access payload and leave no residual grouped
            // scalar predicate behind. That shape is still safe to keep on the
            // grouped symbolic lane as long as access rebinding owns the slot.
            (Some(_), None) if access_template.is_some() => None,
            (None, None) => None,
            _ => return Ok(None),
        };
        // Grouped `0.99` access ownership is still intentionally narrower than
        // the scalar lane. Exact/prefix grouped access can stay symbolic on
        // its own, grouped scalar predicates can stay symbolic on their own,
        // and simple same-field grouped key ranges can stay symbolic when the
        // whole WHERE predicate is already owned by the access payload.
        // Compound grouped `WHERE` shapes that mix symbolic access with extra
        // residual predicate work still fail closed for now.
        if access_template.is_some()
            && statement
                .predicate
                .as_ref()
                .is_some_and(sql_expr_is_compound_boolean)
            && !(predicate_template.is_none()
                && sql_simple_range_slots(
                    statement.predicate.as_ref(),
                    authority.model(),
                    parameter_contracts,
                )
                .is_some())
        {
            return Ok(None);
        }
        if access_template.is_none()
            && !symbolic_access_candidates.is_empty()
            && plan
                .access
                .contains_any_runtime_values(symbolic_access_candidates.as_slice())
        {
            return Ok(None);
        }
        let having_template = match grouped.having_expr.as_ref() {
            Some(having_expr) => {
                let Some(having_template) = build_symbolic_grouped_expr_template(
                    having_expr,
                    parameter_contracts,
                    exemplar_bindings.as_slice(),
                ) else {
                    return Ok(None);
                };

                Some(having_template)
            }
            None => None,
        };
        if access_template.is_some()
            && prepared_statement_contains_template_literal_collision(
                prepared.statement(),
                exemplar_bindings.as_slice(),
            )
        {
            return Ok(None);
        }
        if predicate_template.is_none() && access_template.is_none() && having_template.is_none() {
            return Ok(None);
        }

        let prepared_plan = SharedPreparedExecutionPlan::from_plan(authority, plan.clone());
        let projection = Self::sql_select_projection_contract_from_shared_prepared_plan(
            authority,
            &prepared_plan,
        );

        Ok(Some(PreparedSqlExecutionTemplate::SymbolicGrouped(
            PreparedSqlSymbolicGroupedTemplate {
                authority,
                projection,
                plan,
                predicate: predicate_template,
                access: access_template,
                having_expr: having_template,
            },
        )))
    }

    // Execute one already-bound prepared SQL template plan without routing
    // back through the raw SQL compiled cache or the shared structural cache.
    fn execute_prepared_template_plan(
        &self,
        prepared_plan: SharedPreparedExecutionPlan,
        projection: &SqlProjectionContract,
    ) -> Result<crate::db::session::sql::SqlStatementResult, QueryError> {
        if prepared_plan.logical_plan().grouped_plan().is_some() {
            let authority = prepared_plan.authority();
            let plan = prepared_plan.logical_plan().clone();
            let (columns, fixed_scales) = projection.clone().into_parts();
            let page =
                execute_initial_grouped_rows_for_canister(&self.db, self.debug, authority, plan)
                    .map_err(QueryError::execute)?;
            let statement_result =
                grouped_sql_statement_result_from_page(columns, fixed_scales, page)?;

            Ok(statement_result)
        } else {
            let (columns, fixed_scales) = projection.clone().into_parts();
            let projected =
                execute_sql_projection_rows_for_canister(&self.db, self.debug, prepared_plan)
                    .map_err(QueryError::execute)?;
            let (rows, row_count) = projected.into_parts();
            let payload = SqlProjectionPayload::new(columns, fixed_scales, rows, row_count);

            Ok(payload.into_statement_result())
        }
    }

    // Execute one prepared fallback query directly from its bound SQL shape
    // without routing through either the raw SQL compiled-command cache or the
    // shared structural query-plan cache. Prepared fallback must rebind full
    // expression semantics per execution, so cache-key aliasing on source SQL
    // text or structural shape would be unsound here.
    fn execute_bound_prepared_sql_query_without_caches(
        &self,
        bound_statement: &SqlStatement,
        authority: EntityAuthority,
    ) -> Result<crate::db::session::sql::SqlStatementResult, QueryError> {
        let normalized_prepared =
            Self::prepare_sql_statement_for_authority(bound_statement, authority)?;
        let lowered =
            lower_sql_command_from_prepared_statement(normalized_prepared, authority.model())
                .map_err(QueryError::from_sql_lowering_error)?;
        let Some(LoweredSqlQuery::Select(select)) = lowered.into_query() else {
            return Err(QueryError::invariant(
                "prepared SQL query fallback must lower to lowered SQL SELECT",
            ));
        };
        let structural = Self::structural_query_from_lowered_select(select, authority)?;
        let (_, plan) =
            self.build_structural_plan_with_visible_indexes_for_authority(structural, authority)?;
        let prepared_plan = SharedPreparedExecutionPlan::from_plan(authority, plan);
        let projection = Self::sql_select_projection_contract_from_shared_prepared_plan(
            authority,
            &prepared_plan,
        );

        self.execute_prepared_template_plan(prepared_plan, &projection)
    }
}

///
/// BoundPreparedTemplatePlan
///
/// One freshly instantiated prepared template plan plus its frozen authority.
/// This keeps the symbolic and legacy bind paths on one shared return shape
/// before they hand off to `SharedPreparedExecutionPlan`.
///

#[derive(Clone, Debug)]
struct BoundPreparedTemplatePlan {
    authority: EntityAuthority,
    plan: AccessPlannedQuery,
}

impl BoundPreparedTemplatePlan {
    #[must_use]
    const fn new(authority: EntityAuthority, plan: AccessPlannedQuery) -> Self {
        Self { authority, plan }
    }

    #[must_use]
    const fn authority(&self) -> EntityAuthority {
        self.authority
    }
}

// Refuse the fixed-route template lane when one chosen sentinel already exists
// as an ordinary SQL literal in the prepared statement. The current binding
// step still substitutes by literal-value equality, so reusing that sentinel
// would risk rewriting one user-authored constant during execution.
fn prepared_statement_contains_template_literal_collision(
    statement: &SqlStatement,
    template_bindings: &[Value],
) -> bool {
    match statement {
        SqlStatement::Select(select) => {
            sql_select_contains_template_literal_collision(select, template_bindings)
        }
        SqlStatement::Delete(delete) => {
            sql_delete_contains_template_literal_collision(delete, template_bindings)
        }
        SqlStatement::Explain(explain) => match &explain.statement {
            SqlExplainTarget::Select(select) => {
                sql_select_contains_template_literal_collision(select, template_bindings)
            }
            SqlExplainTarget::Delete(delete) => {
                sql_delete_contains_template_literal_collision(delete, template_bindings)
            }
        },
        SqlStatement::Insert(_)
        | SqlStatement::Update(_)
        | SqlStatement::Describe(_)
        | SqlStatement::ShowIndexes(_)
        | SqlStatement::ShowColumns(_)
        | SqlStatement::ShowEntities(_) => false,
    }
}

// Walk one parsed SQL SELECT statement and report whether it already contains
// one of the chosen template sentinel literals.
fn sql_select_contains_template_literal_collision(
    select: &SqlSelectStatement,
    template_bindings: &[Value],
) -> bool {
    sql_projection_contains_template_literal_collision(&select.projection, template_bindings)
        || select.predicate.as_ref().is_some_and(|expr| {
            sql_expr_contains_template_literal_collision(expr, template_bindings)
        })
        || select
            .having
            .iter()
            .any(|expr| sql_expr_contains_template_literal_collision(expr, template_bindings))
        || select.order_by.iter().any(|term| {
            sql_expr_contains_template_literal_collision(&term.field, template_bindings)
        })
}

// Delete-mode prepared statements only need to scan the predicate branch for
// ordinary literals equal to one chosen template sentinel.
fn sql_delete_contains_template_literal_collision(
    delete: &SqlDeleteStatement,
    template_bindings: &[Value],
) -> bool {
    delete
        .predicate
        .as_ref()
        .is_some_and(|expr| sql_expr_contains_template_literal_collision(expr, template_bindings))
}

// Return whether one parsed SQL boolean expression is compound enough that the
// grouped symbolic access lane should still fail closed instead of claiming a
// combined access+residual-predicate route in `0.99`.
const fn sql_expr_is_compound_boolean(expr: &SqlExpr) -> bool {
    matches!(
        expr,
        SqlExpr::Binary {
            op: crate::db::sql::parser::SqlExprBinaryOp::And
                | crate::db::sql::parser::SqlExprBinaryOp::Or,
            ..
        } | SqlExpr::Unary { .. }
    )
}

// Return whether one parsed SQL WHERE expression uses parameter slots inside a
// general expression-owned filter shape instead of one direct predicate/access
// shape that prepared templates are allowed to own.
fn sql_expr_uses_general_filter_expr_parameters(expr: &SqlExpr) -> bool {
    match expr {
        SqlExpr::Field(_) | SqlExpr::Literal(_) | SqlExpr::Param { .. } | SqlExpr::Aggregate(_) => {
            false
        }
        SqlExpr::Membership { expr, .. } => sql_expr_contains_param(expr.as_ref()),
        SqlExpr::NullTest { expr, .. } => !sql_null_test_target_is_template_predicate_shape(expr),
        SqlExpr::Unary { expr, .. } => sql_expr_uses_general_filter_expr_parameters(expr),
        SqlExpr::Binary { op, left, right } => match op {
            crate::db::sql::parser::SqlExprBinaryOp::And
            | crate::db::sql::parser::SqlExprBinaryOp::Or => {
                sql_expr_uses_general_filter_expr_parameters(left)
                    || sql_expr_uses_general_filter_expr_parameters(right)
            }
            crate::db::sql::parser::SqlExprBinaryOp::Eq
            | crate::db::sql::parser::SqlExprBinaryOp::Ne
            | crate::db::sql::parser::SqlExprBinaryOp::Lt
            | crate::db::sql::parser::SqlExprBinaryOp::Lte
            | crate::db::sql::parser::SqlExprBinaryOp::Gt
            | crate::db::sql::parser::SqlExprBinaryOp::Gte => {
                !(sql_compare_target_is_template_predicate_shape(left)
                    && sql_compare_target_is_template_predicate_shape(right))
                    && (sql_expr_contains_param(left) || sql_expr_contains_param(right))
            }
            crate::db::sql::parser::SqlExprBinaryOp::Add
            | crate::db::sql::parser::SqlExprBinaryOp::Sub
            | crate::db::sql::parser::SqlExprBinaryOp::Mul
            | crate::db::sql::parser::SqlExprBinaryOp::Div => {
                sql_expr_contains_param(left) || sql_expr_contains_param(right)
            }
        },
        SqlExpr::FunctionCall { function, args } => {
            if sql_text_predicate_function_is_template_shape(*function, args.as_slice()) {
                return false;
            }

            args.iter().any(sql_expr_contains_param)
        }
        SqlExpr::Case { arms, else_expr } => {
            arms.iter().any(|arm| {
                sql_expr_contains_param(&arm.condition) || sql_expr_contains_param(&arm.result)
            }) || else_expr
                .as_ref()
                .is_some_and(|expr| sql_expr_contains_param(expr))
        }
    }
}

// Return whether one parsed SQL expression is a direct compare/text-predicate
// operand shape that prepared predicate/access templates are still allowed to
// own.
fn sql_compare_target_is_template_predicate_shape(expr: &SqlExpr) -> bool {
    match expr {
        SqlExpr::Field(_) | SqlExpr::Literal(_) | SqlExpr::Param { .. } => true,
        SqlExpr::FunctionCall { function, args }
            if matches!(
                function,
                crate::db::sql::parser::SqlScalarFunction::Lower
                    | crate::db::sql::parser::SqlScalarFunction::Upper
            ) && matches!(args.as_slice(), [SqlExpr::Field(_)]) =>
        {
            true
        }
        _ => false,
    }
}

// Return whether one parsed SQL null-test target still matches the predicate
// lane that prepared templates are allowed to rebuild.
const fn sql_null_test_target_is_template_predicate_shape(expr: &SqlExpr) -> bool {
    matches!(expr, SqlExpr::Field(_))
}

// Return whether one parsed SQL function call is one direct text predicate
// shape still owned by prepared predicate templates.
fn sql_text_predicate_function_is_template_shape(
    function: crate::db::sql::parser::SqlScalarFunction,
    args: &[SqlExpr],
) -> bool {
    matches!(
        function,
        crate::db::sql::parser::SqlScalarFunction::StartsWith
            | crate::db::sql::parser::SqlScalarFunction::EndsWith
            | crate::db::sql::parser::SqlScalarFunction::Contains
    ) && matches!(
        args,
        [left, right]
            if sql_compare_target_is_template_predicate_shape(left)
                && sql_compare_target_is_template_predicate_shape(right)
    )
}

// Walk one parsed SQL expression and report whether it references any runtime
// parameter slot.
fn sql_expr_contains_param(expr: &SqlExpr) -> bool {
    match expr {
        SqlExpr::Field(_) | SqlExpr::Literal(_) => false,
        SqlExpr::Param { .. } => true,
        SqlExpr::Aggregate(aggregate) => {
            aggregate
                .input
                .as_ref()
                .is_some_and(|expr| sql_expr_contains_param(expr))
                || aggregate
                    .filter_expr
                    .as_ref()
                    .is_some_and(|expr| sql_expr_contains_param(expr))
        }
        SqlExpr::Membership { expr, .. } => sql_expr_contains_param(expr.as_ref()),
        SqlExpr::NullTest { expr, .. } | SqlExpr::Unary { expr, .. } => {
            sql_expr_contains_param(expr)
        }
        SqlExpr::FunctionCall { args, .. } => args.iter().any(sql_expr_contains_param),
        SqlExpr::Binary { left, right, .. } => {
            sql_expr_contains_param(left) || sql_expr_contains_param(right)
        }
        SqlExpr::Case { arms, else_expr } => {
            arms.iter().any(|arm| {
                sql_expr_contains_param(&arm.condition) || sql_expr_contains_param(&arm.result)
            }) || else_expr
                .as_ref()
                .is_some_and(|expr| sql_expr_contains_param(expr))
        }
    }
}

// Walk one parsed SQL projection and report whether it already contains one of
// the chosen template sentinel literals.
fn sql_projection_contains_template_literal_collision(
    projection: &SqlProjection,
    template_bindings: &[Value],
) -> bool {
    match projection {
        SqlProjection::All => false,
        SqlProjection::Items(items) => items.iter().any(|item| {
            sql_expr_contains_template_literal_collision(
                &SqlExpr::from_select_item(item),
                template_bindings,
            )
        }),
    }
}

// Aggregate input/filter expressions can carry ordinary literals that would be
// rebound accidentally if they match one of the internal template values.
fn sql_aggregate_contains_template_literal_collision(
    aggregate: &SqlAggregateCall,
    template_bindings: &[Value],
) -> bool {
    aggregate
        .input
        .as_ref()
        .is_some_and(|expr| sql_expr_contains_template_literal_collision(expr, template_bindings))
        || aggregate.filter_expr.as_ref().is_some_and(|expr| {
            sql_expr_contains_template_literal_collision(expr, template_bindings)
        })
}

// Walk one parsed SQL expression tree and detect whether it already contains a
// literal equal to one of the template sentinel values chosen for prepared
// execution binding.
fn sql_expr_contains_template_literal_collision(
    expr: &SqlExpr,
    template_bindings: &[Value],
) -> bool {
    match expr {
        SqlExpr::Field(_) | SqlExpr::Param { .. } => false,
        SqlExpr::Aggregate(aggregate) => {
            sql_aggregate_contains_template_literal_collision(aggregate, template_bindings)
        }
        SqlExpr::Literal(value) => template_bindings.contains(value),
        SqlExpr::Membership { expr, values, .. } => {
            sql_expr_contains_template_literal_collision(expr, template_bindings)
                || values.iter().any(|value| template_bindings.contains(value))
        }
        SqlExpr::NullTest { expr, .. } | SqlExpr::Unary { expr, .. } => {
            sql_expr_contains_template_literal_collision(expr, template_bindings)
        }
        SqlExpr::FunctionCall { args, .. } => args
            .iter()
            .any(|arg| sql_expr_contains_template_literal_collision(arg, template_bindings)),
        SqlExpr::Binary { left, right, .. } => {
            sql_expr_contains_template_literal_collision(left, template_bindings)
                || sql_expr_contains_template_literal_collision(right, template_bindings)
        }
        SqlExpr::Case { arms, else_expr } => {
            arms.iter().any(|arm| {
                sql_expr_contains_template_literal_collision(&arm.condition, template_bindings)
                    || sql_expr_contains_template_literal_collision(&arm.result, template_bindings)
            }) || else_expr.as_ref().is_some_and(|expr| {
                sql_expr_contains_template_literal_collision(expr, template_bindings)
            })
        }
    }
}

fn bind_prepared_template_plan(
    mut plan: AccessPlannedQuery,
    contracts: &[PreparedSqlParameterContract],
    bindings: &[Value],
    authority: EntityAuthority,
) -> Result<BoundPreparedTemplatePlan, QueryError> {
    let replacements = contracts
        .iter()
        .filter_map(|contract| {
            contract.template_binding().map(|template_binding| {
                (
                    template_binding.clone(),
                    bindings
                        .get(contract.index())
                        .expect("validated binding vector must cover every contract index")
                        .clone(),
                )
            })
        })
        .collect::<Vec<_>>();

    // Phase 1: bind the logical predicate/HAVING surfaces back to concrete runtime literals.
    match &mut plan.logical {
        LogicalPlan::Scalar(scalar) => {
            scalar.predicate = scalar.predicate.take().map(|predicate| {
                bind_prepared_template_predicate(predicate, replacements.as_slice())
            });
        }
        LogicalPlan::Grouped(grouped) => {
            grouped.scalar.predicate = grouped.scalar.predicate.take().map(|predicate| {
                bind_prepared_template_predicate(predicate, replacements.as_slice())
            });
            grouped.having_expr = grouped
                .having_expr
                .take()
                .map(|expr| bind_prepared_template_expr(expr, replacements.as_slice()));
        }
    }

    // Phase 2: rewrite the concrete access payloads so the executor sees the
    // current bound values without reopening SQL lowering or route selection.
    plan.access = plan.access.bind_runtime_values(replacements.as_slice());

    // Phase 3: rebuild planner-frozen executor residents from the bound plan.
    plan.finalize_planner_route_profile_for_model(authority.model());
    plan.finalize_static_planning_shape_for_model(authority.model())
        .map_err(QueryError::execute)?;

    Ok(BoundPreparedTemplatePlan::new(authority, plan))
}

// Instantiate one symbolic scalar compare-family template back into the normal
// planner-owned query plan without relying on sentinel replacement.
fn bind_symbolic_scalar_template_plan(
    mut plan: AccessPlannedQuery,
    predicate_template: Option<&PreparedSqlScalarPredicateTemplate>,
    access_template: Option<&PreparedSqlScalarAccessPathTemplate>,
    bindings: &[Value],
    authority: EntityAuthority,
) -> Result<BoundPreparedTemplatePlan, QueryError> {
    let LogicalPlan::Scalar(scalar) = &mut plan.logical else {
        return Err(QueryError::unsupported_query(
            "symbolic scalar prepared template expected scalar logical plan",
        ));
    };
    if let Some(predicate_template) = predicate_template {
        // Phase 1: rebuild the slot-owned compare-family predicate with the
        // current runtime binding environment.
        let predicate =
            instantiate_symbolic_scalar_predicate_template(predicate_template, bindings)?;
        scalar.predicate = Some(predicate);
        scalar.filter_expr = None;
    }
    if let Some(access_template) = access_template {
        // Phase 2: rebuild the slot-owned access payload without reopening
        // route selection or relying on sentinel-value replacement.
        plan.access = instantiate_symbolic_scalar_access_path_template(access_template, bindings)?;
    }

    // Phase 3: rebuild planner-frozen executor residents from the rebound plan.
    plan.finalize_planner_route_profile_for_model(authority.model());
    plan.finalize_static_planning_shape_for_model(authority.model())
        .map_err(QueryError::execute)?;

    Ok(BoundPreparedTemplatePlan::new(authority, plan))
}

// Instantiate one symbolic grouped prepared template back into the normal
// planner-owned grouped plan without relying on sentinel replacement.
fn bind_symbolic_grouped_template_plan(
    mut plan: AccessPlannedQuery,
    predicate_template: Option<&PreparedSqlScalarPredicateTemplate>,
    access_template: Option<&PreparedSqlScalarAccessPathTemplate>,
    having_template: Option<&PreparedSqlGroupedExprTemplate>,
    bindings: &[Value],
    authority: EntityAuthority,
) -> Result<BoundPreparedTemplatePlan, QueryError> {
    // Phase 1: rebuild the slot-owned grouped scalar predicate when present.
    let LogicalPlan::Grouped(grouped) = &mut plan.logical else {
        return Err(QueryError::unsupported_query(
            "symbolic grouped prepared template expected grouped logical plan",
        ));
    };
    if let Some(predicate_template) = predicate_template {
        grouped.scalar.predicate = Some(instantiate_symbolic_scalar_predicate_template(
            predicate_template,
            bindings,
        )?);
        grouped.scalar.filter_expr = None;
    }
    if let Some(access_template) = access_template {
        plan.access = instantiate_symbolic_scalar_access_path_template(access_template, bindings)?;
    }

    // Phase 2: rebuild the slot-owned grouped HAVING expression when present.
    if let Some(having_template) = having_template {
        let having_expr = instantiate_symbolic_grouped_expr_template(having_template, bindings)?;
        grouped.having_expr = Some(having_expr);
    }

    // Phase 3: rebuild planner-frozen executor residents from the rebound plan.
    plan.finalize_planner_route_profile_for_model(authority.model());
    plan.finalize_static_planning_shape_for_model(authority.model())
        .map_err(QueryError::execute)?;

    Ok(BoundPreparedTemplatePlan::new(authority, plan))
}

// Return one exemplar binding for internal symbolic-template plan compilation.
// `0.99` still compiles one concrete exemplar plan to freeze routing/projection,
// but slot identity comes from the symbolic predicate template rather than from
// these concrete values during execution.
fn prepared_sql_contract_exemplar_binding(
    contract: &PreparedSqlParameterContract,
) -> Option<Value> {
    match contract.type_family() {
        PreparedSqlParameterTypeFamily::Bool => Some(Value::Bool(false)),
        PreparedSqlParameterTypeFamily::Numeric | PreparedSqlParameterTypeFamily::Text => {
            contract.template_binding().cloned()
        }
    }
}

// Rewrite one prepared exemplar binding pair when the parsed SQL predicate is a
// simple same-field lower/upper range. Numeric template sentinels descend by
// slot index, so range pairs would otherwise compile one empty exemplar route
// and never recover at execute time.
fn apply_sql_range_exemplar_override(
    predicate: Option<&SqlExpr>,
    contracts: &[PreparedSqlParameterContract],
    exemplar_bindings: &mut [Value],
    model: &'static EntityModel,
) {
    let Some((field_kind, lower_slot, upper_slot)) =
        sql_simple_range_slots(predicate, model, contracts)
    else {
        return;
    };
    let Some((lower_value, upper_value)) =
        ordered_exemplar_range_values_for_field_kind(field_kind, lower_slot, upper_slot)
    else {
        return;
    };
    let Some(lower_binding) = exemplar_bindings.get_mut(lower_slot) else {
        return;
    };
    *lower_binding = lower_value;
    let Some(upper_binding) = exemplar_bindings.get_mut(upper_slot) else {
        return;
    };
    *upper_binding = upper_value;
}

// Return one simple same-field lower/upper range pair when the parsed SQL
// predicate is exactly `field >= ? AND field < ?` (or the analogous strict/
// inclusive variants) over one admitted prepared compare-family field.
fn sql_simple_range_slots(
    predicate: Option<&SqlExpr>,
    model: &'static EntityModel,
    contracts: &[PreparedSqlParameterContract],
) -> Option<(FieldKind, usize, usize)> {
    let SqlExpr::Binary {
        op: crate::db::sql::parser::SqlExprBinaryOp::And,
        left,
        right,
    } = predicate?
    else {
        return None;
    };
    let first = sql_range_compare_descriptor(left)?;
    let second = sql_range_compare_descriptor(right)?;
    if first.field != second.field {
        return None;
    }
    let (lower_slot, upper_slot) = match (first.bound, second.bound) {
        (SqlRangeBoundKind::Lower, SqlRangeBoundKind::Upper) => {
            (first.slot_index, second.slot_index)
        }
        (SqlRangeBoundKind::Upper, SqlRangeBoundKind::Lower) => {
            (second.slot_index, first.slot_index)
        }
        _ => return None,
    };
    if contracts.get(lower_slot)?.type_family() != contracts.get(upper_slot)?.type_family() {
        return None;
    }
    let field_kind = model
        .fields()
        .iter()
        .find(|candidate| candidate.name() == first.field)
        .map(crate::model::field::FieldModel::kind)?;

    Some((field_kind, lower_slot, upper_slot))
}

enum SqlRangeBoundKind {
    Lower,
    Upper,
}

struct SqlRangeCompareDescriptor<'a> {
    field: &'a str,
    slot_index: usize,
    bound: SqlRangeBoundKind,
}

fn sql_range_compare_descriptor(expr: &SqlExpr) -> Option<SqlRangeCompareDescriptor<'_>> {
    let SqlExpr::Binary { op, left, right } = expr else {
        return None;
    };
    let (SqlExpr::Field(field), SqlExpr::Param { index }) = (&**left, &**right) else {
        return None;
    };
    let bound = match op {
        crate::db::sql::parser::SqlExprBinaryOp::Gt
        | crate::db::sql::parser::SqlExprBinaryOp::Gte => SqlRangeBoundKind::Lower,
        crate::db::sql::parser::SqlExprBinaryOp::Lt
        | crate::db::sql::parser::SqlExprBinaryOp::Lte => SqlRangeBoundKind::Upper,
        _ => return None,
    };

    Some(SqlRangeCompareDescriptor {
        field,
        slot_index: *index,
        bound,
    })
}

fn ordered_exemplar_range_values_for_field_kind(
    field_kind: FieldKind,
    lower_slot: usize,
    upper_slot: usize,
) -> Option<(Value, Value)> {
    let lower_offset = u64::try_from(lower_slot).ok()?;
    let upper_offset = u64::try_from(upper_slot).ok()?;

    match field_kind {
        FieldKind::Int => {
            let lower = i64::try_from(lower_offset).ok()?;
            let upper = i64::try_from(upper_offset).ok()?.saturating_add(1);

            Some((Value::Int(lower), Value::Int(upper)))
        }
        FieldKind::Int128 => Some((
            Value::Int128((i128::from(lower_offset)).into()),
            Value::Int128((i128::from(upper_offset).saturating_add(1)).into()),
        )),
        FieldKind::IntBig => Some((
            Value::IntBig(crate::types::Int::from(i32::try_from(lower_offset).ok()?)),
            Value::IntBig(crate::types::Int::from(
                i32::try_from(upper_offset.saturating_add(1)).ok()?,
            )),
        )),
        FieldKind::Uint => Some((
            Value::Uint(lower_offset),
            Value::Uint(upper_offset.saturating_add(1)),
        )),
        FieldKind::Uint128 => Some((
            Value::Uint128((u128::from(lower_offset)).into()),
            Value::Uint128((u128::from(upper_offset).saturating_add(1)).into()),
        )),
        FieldKind::UintBig => Some((
            Value::UintBig(lower_offset.into()),
            Value::UintBig(upper_offset.saturating_add(1).into()),
        )),
        FieldKind::Decimal { scale } => Some((
            Value::Decimal(crate::types::Decimal::from_i128_with_scale(
                i128::from(lower_offset),
                scale,
            )),
            Value::Decimal(crate::types::Decimal::from_i128_with_scale(
                i128::from(upper_offset).saturating_add(1),
                scale,
            )),
        )),
        FieldKind::Duration => Some((
            Value::Duration(crate::types::Duration::from_millis(lower_offset)),
            Value::Duration(crate::types::Duration::from_millis(
                upper_offset.saturating_add(1),
            )),
        )),
        FieldKind::Timestamp => Some((
            Value::Timestamp(crate::types::Timestamp::from_millis(
                i64::try_from(lower_offset).ok()?,
            )),
            Value::Timestamp(crate::types::Timestamp::from_millis(
                i64::try_from(upper_offset).ok()?.saturating_add(1),
            )),
        )),
        FieldKind::Text => Some((
            Value::Text(format!("__icydb_prepared_range_lower_{lower_slot}__")),
            Value::Text(format!("__icydb_prepared_range_upper_{upper_slot}__")),
        )),
        _ => None,
    }
}

// Build one symbolic scalar access payload template when the selected access
// path carries slot-owned values and the current `0.99` slice knows how to
// rebuild that payload without sentinel replacement.
fn build_symbolic_scalar_access_path_template(
    access: &AccessPlan<Value>,
    parameter_contracts: &[PreparedSqlParameterContract],
    exemplar_bindings: &[Value],
) -> Option<PreparedSqlScalarAccessPathTemplate> {
    if let Some(key) = access.as_by_key_path() {
        return Some(PreparedSqlScalarAccessPathTemplate::ByKey {
            key: build_symbolic_scalar_access_value_template(
                key,
                parameter_contracts,
                exemplar_bindings,
            ),
        });
    }
    if let Some((start, end)) = access.as_primary_key_range_path() {
        let start = build_symbolic_scalar_access_value_template(
            start,
            parameter_contracts,
            exemplar_bindings,
        );
        let end = build_symbolic_scalar_access_value_template(
            end,
            parameter_contracts,
            exemplar_bindings,
        );
        if matches!(start, PreparedSqlScalarAccessValueTemplate::Static(_))
            && matches!(end, PreparedSqlScalarAccessValueTemplate::Static(_))
        {
            return None;
        }

        return Some(PreparedSqlScalarAccessPathTemplate::KeyRange { start, end });
    }
    let (index, values) = access.as_index_prefix_path()?;
    let mut had_slot = false;
    let mut templates = Vec::with_capacity(values.len());
    for value in values {
        let template = build_symbolic_scalar_access_value_template(
            value,
            parameter_contracts,
            exemplar_bindings,
        );
        had_slot |= matches!(
            template,
            PreparedSqlScalarAccessValueTemplate::SlotLiteral(_)
        );
        templates.push(template);
    }
    if !had_slot {
        return None;
    }

    Some(PreparedSqlScalarAccessPathTemplate::IndexPrefix {
        index: *index,
        values: templates,
    })
}

// Return one scalar access payload leaf template by resolving an exemplar
// access literal back to one unique prepared binding slot when possible.
fn build_symbolic_scalar_access_value_template(
    value: &Value,
    parameter_contracts: &[PreparedSqlParameterContract],
    exemplar_bindings: &[Value],
) -> PreparedSqlScalarAccessValueTemplate {
    prepared_sql_slot_index_for_exemplar_value(value, parameter_contracts, exemplar_bindings)
        .map_or_else(
            || PreparedSqlScalarAccessValueTemplate::Static(value.clone()),
            PreparedSqlScalarAccessValueTemplate::SlotLiteral,
        )
}

// Return one unique prepared binding slot index for one exemplar literal value
// when that value comes from the admitted non-bool prepared compare families.
fn prepared_sql_slot_index_for_exemplar_value(
    value: &Value,
    parameter_contracts: &[PreparedSqlParameterContract],
    exemplar_bindings: &[Value],
) -> Option<usize> {
    let mut matching_slot = None;
    for (contract, exemplar) in parameter_contracts.iter().zip(exemplar_bindings.iter()) {
        if contract.type_family() == PreparedSqlParameterTypeFamily::Bool || exemplar != value {
            continue;
        }
        if matching_slot.is_some() {
            return None;
        }
        matching_slot = Some(contract.index());
    }

    matching_slot
}

// Instantiate one symbolic scalar access payload template back into the
// planner-owned access tree without relying on sentinel replacement.
fn instantiate_symbolic_scalar_access_path_template(
    template: &PreparedSqlScalarAccessPathTemplate,
    bindings: &[Value],
) -> Result<AccessPlan<Value>, QueryError> {
    match template {
        PreparedSqlScalarAccessPathTemplate::ByKey { key } => Ok(AccessPlan::by_key(
            instantiate_symbolic_scalar_access_value_template(key, bindings)?,
        )),
        PreparedSqlScalarAccessPathTemplate::KeyRange { start, end } => Ok(AccessPlan::key_range(
            instantiate_symbolic_scalar_access_value_template(start, bindings)?,
            instantiate_symbolic_scalar_access_value_template(end, bindings)?,
        )),
        PreparedSqlScalarAccessPathTemplate::IndexPrefix { index, values } => {
            let mut bound_values = Vec::with_capacity(values.len());
            for value in values {
                bound_values.push(instantiate_symbolic_scalar_access_value_template(
                    value, bindings,
                )?);
            }

            Ok(AccessPlan::index_prefix(*index, bound_values))
        }
    }
}

// Instantiate one symbolic scalar access leaf with the current runtime
// binding vector.
fn instantiate_symbolic_scalar_access_value_template(
    template: &PreparedSqlScalarAccessValueTemplate,
    bindings: &[Value],
) -> Result<Value, QueryError> {
    match template {
        PreparedSqlScalarAccessValueTemplate::Static(value) => Ok(value.clone()),
        PreparedSqlScalarAccessValueTemplate::SlotLiteral(slot_index) => {
            bindings.get(*slot_index).cloned().ok_or_else(|| {
                QueryError::unsupported_query(format!(
                    "missing prepared SQL binding at index={slot_index}",
                ))
            })
        }
    }
}

// Return whether one lowered scalar predicate still carries any exemplar
// runtime literal that the symbolic scalar template did not actually lift into
// slot ownership.
fn predicate_contains_any_runtime_values(
    predicate: &crate::db::predicate::Predicate,
    candidates: &[Value],
) -> bool {
    match predicate {
        crate::db::predicate::Predicate::True
        | crate::db::predicate::Predicate::False
        | crate::db::predicate::Predicate::CompareFields(_)
        | crate::db::predicate::Predicate::IsNull { .. }
        | crate::db::predicate::Predicate::IsNotNull { .. }
        | crate::db::predicate::Predicate::IsMissing { .. }
        | crate::db::predicate::Predicate::IsEmpty { .. }
        | crate::db::predicate::Predicate::IsNotEmpty { .. } => false,
        crate::db::predicate::Predicate::Compare(compare) => candidates.contains(compare.value()),
        crate::db::predicate::Predicate::And(children)
        | crate::db::predicate::Predicate::Or(children) => children
            .iter()
            .any(|child| predicate_contains_any_runtime_values(child, candidates)),
        crate::db::predicate::Predicate::Not(child) => {
            predicate_contains_any_runtime_values(child, candidates)
        }
        crate::db::predicate::Predicate::TextContains { value, .. }
        | crate::db::predicate::Predicate::TextContainsCi { value, .. } => {
            candidates.contains(value)
        }
    }
}

// Build one symbolic scalar prepared predicate template by pairing the
// prepared SQL predicate structure with the lowered predicate compare metadata.
fn build_symbolic_scalar_predicate_template(
    sql_expr: &SqlExpr,
    predicate: &crate::db::predicate::Predicate,
) -> Option<PreparedSqlScalarPredicateTemplate> {
    match (sql_expr, predicate) {
        (
            SqlExpr::Binary {
                op: crate::db::sql::parser::SqlExprBinaryOp::And,
                left,
                right,
            },
            crate::db::predicate::Predicate::And(children),
        ) if children.len() == 2 => build_symbolic_scalar_binary_children_template(
            left,
            right,
            &children[0],
            &children[1],
            PreparedSqlScalarPredicateTemplate::And,
        ),
        (
            SqlExpr::Binary {
                op: crate::db::sql::parser::SqlExprBinaryOp::Or,
                left,
                right,
            },
            crate::db::predicate::Predicate::Or(children),
        ) if children.len() == 2 => build_symbolic_scalar_binary_children_template(
            left,
            right,
            &children[0],
            &children[1],
            PreparedSqlScalarPredicateTemplate::Or,
        ),
        (SqlExpr::Unary { expr, .. }, crate::db::predicate::Predicate::Not(child)) => {
            Some(PreparedSqlScalarPredicateTemplate::Not(Box::new(
                build_symbolic_scalar_predicate_template(expr, child)?,
            )))
        }
        (
            SqlExpr::Binary {
                op:
                    crate::db::sql::parser::SqlExprBinaryOp::Eq
                    | crate::db::sql::parser::SqlExprBinaryOp::Ne
                    | crate::db::sql::parser::SqlExprBinaryOp::Lt
                    | crate::db::sql::parser::SqlExprBinaryOp::Lte
                    | crate::db::sql::parser::SqlExprBinaryOp::Gt
                    | crate::db::sql::parser::SqlExprBinaryOp::Gte,
                left,
                right,
            },
            crate::db::predicate::Predicate::Compare(compare),
        ) => match (&**left, &**right) {
            (SqlExpr::Field(_), SqlExpr::Param { index }) => Some(
                PreparedSqlScalarPredicateTemplate::Compare(PreparedSqlScalarCompareSlotTemplate {
                    field: compare.field.clone(),
                    op: compare.op,
                    coercion: compare.coercion.id,
                    slot_index: *index,
                }),
            ),
            _ => None,
        },
        _ => None,
    }
}

// Pair one binary SQL predicate subtree with two lowered predicate children.
// Lowering may reorder compare-family `AND`/`OR` leaves during extraction, so
// symbolic template ownership must accept either stable child ordering as long
// as the rebuilt predicate semantics are unchanged.
fn build_symbolic_scalar_binary_children_template(
    left_sql: &SqlExpr,
    right_sql: &SqlExpr,
    first_child: &crate::db::predicate::Predicate,
    second_child: &crate::db::predicate::Predicate,
    ctor: fn(Vec<PreparedSqlScalarPredicateTemplate>) -> PreparedSqlScalarPredicateTemplate,
) -> Option<PreparedSqlScalarPredicateTemplate> {
    if let (Some(left), Some(right)) = (
        build_symbolic_scalar_predicate_template(left_sql, first_child),
        build_symbolic_scalar_predicate_template(right_sql, second_child),
    ) {
        return Some(ctor(vec![left, right]));
    }

    let (Some(left), Some(right)) = (
        build_symbolic_scalar_predicate_template(left_sql, second_child),
        build_symbolic_scalar_predicate_template(right_sql, first_child),
    ) else {
        return None;
    };

    Some(ctor(vec![left, right]))
}

// Instantiate one symbolic scalar predicate template with the current binding
// vector and rebuild a normal planner-owned predicate tree.
fn instantiate_symbolic_scalar_predicate_template(
    template: &PreparedSqlScalarPredicateTemplate,
    bindings: &[Value],
) -> Result<crate::db::predicate::Predicate, QueryError> {
    match template {
        PreparedSqlScalarPredicateTemplate::Compare(compare) => {
            let binding = bindings
                .get(compare.slot_index)
                .ok_or_else(|| {
                    QueryError::unsupported_query(format!(
                        "missing prepared SQL binding at index={}",
                        compare.slot_index,
                    ))
                })?
                .clone();

            Ok(crate::db::predicate::Predicate::Compare(
                crate::db::predicate::ComparePredicate::with_coercion(
                    compare.field.clone(),
                    compare.op,
                    binding,
                    compare.coercion,
                ),
            ))
        }
        PreparedSqlScalarPredicateTemplate::And(children) => {
            Ok(crate::db::predicate::Predicate::And(
                children
                    .iter()
                    .map(|child| instantiate_symbolic_scalar_predicate_template(child, bindings))
                    .collect::<Result<Vec<_>, _>>()?,
            ))
        }
        PreparedSqlScalarPredicateTemplate::Or(children) => {
            Ok(crate::db::predicate::Predicate::Or(
                children
                    .iter()
                    .map(|child| instantiate_symbolic_scalar_predicate_template(child, bindings))
                    .collect::<Result<Vec<_>, _>>()?,
            ))
        }
        PreparedSqlScalarPredicateTemplate::Not(child) => {
            Ok(crate::db::predicate::Predicate::Not(Box::new(
                instantiate_symbolic_scalar_predicate_template(child, bindings)?,
            )))
        }
    }
}

// Build one symbolic grouped post-aggregate expression template by walking the
// lowered planner-owned HAVING tree and turning exemplar-bound literal leaves
// back into slot references for the current prepared contracts.
fn build_symbolic_grouped_expr_template(
    expr: &crate::db::query::plan::expr::Expr,
    parameter_contracts: &[PreparedSqlParameterContract],
    exemplar_bindings: &[Value],
) -> Option<PreparedSqlGroupedExprTemplate> {
    match expr {
        crate::db::query::plan::expr::Expr::Literal(value) => {
            let slot_index = parameter_contracts.iter().find_map(|contract| {
                exemplar_bindings
                    .get(contract.index())
                    .filter(|binding| *binding == value)
                    .map(|_| contract.index())
            });

            Some(slot_index.map_or_else(
                || PreparedSqlGroupedExprTemplate::Static(expr.clone()),
                PreparedSqlGroupedExprTemplate::SlotLiteral,
            ))
        }
        crate::db::query::plan::expr::Expr::Unary { op, expr } => {
            let child =
                build_symbolic_grouped_expr_template(expr, parameter_contracts, exemplar_bindings)?;
            if matches!(child, PreparedSqlGroupedExprTemplate::Static(_)) {
                Some(PreparedSqlGroupedExprTemplate::Static(
                    crate::db::query::plan::expr::Expr::Unary {
                        op: *op,
                        expr: Box::new(
                            instantiate_symbolic_grouped_expr_template(&child, exemplar_bindings)
                                .ok()?,
                        ),
                    },
                ))
            } else {
                Some(PreparedSqlGroupedExprTemplate::Unary {
                    op: *op,
                    expr: Box::new(child),
                })
            }
        }
        crate::db::query::plan::expr::Expr::Binary { op, left, right } => {
            let left_template =
                build_symbolic_grouped_expr_template(left, parameter_contracts, exemplar_bindings)?;
            let right_template = build_symbolic_grouped_expr_template(
                right,
                parameter_contracts,
                exemplar_bindings,
            )?;
            if matches!(left_template, PreparedSqlGroupedExprTemplate::Static(_))
                && matches!(right_template, PreparedSqlGroupedExprTemplate::Static(_))
            {
                Some(PreparedSqlGroupedExprTemplate::Static(expr.clone()))
            } else {
                Some(PreparedSqlGroupedExprTemplate::Binary {
                    op: *op,
                    left: Box::new(left_template),
                    right: Box::new(right_template),
                })
            }
        }
        _ => Some(PreparedSqlGroupedExprTemplate::Static(expr.clone())),
    }
}

// Instantiate one symbolic grouped expression template with the current
// binding vector and rebuild a normal planner-owned grouped HAVING tree.
fn instantiate_symbolic_grouped_expr_template(
    template: &PreparedSqlGroupedExprTemplate,
    bindings: &[Value],
) -> Result<crate::db::query::plan::expr::Expr, QueryError> {
    match template {
        PreparedSqlGroupedExprTemplate::Static(expr) => Ok(expr.clone()),
        PreparedSqlGroupedExprTemplate::SlotLiteral(index) => {
            Ok(crate::db::query::plan::expr::Expr::Literal(
                bindings
                    .get(*index)
                    .ok_or_else(|| {
                        QueryError::unsupported_query(format!(
                            "missing prepared SQL binding at index={index}",
                        ))
                    })?
                    .clone(),
            ))
        }
        PreparedSqlGroupedExprTemplate::Unary { op, expr } => {
            Ok(crate::db::query::plan::expr::Expr::Unary {
                op: *op,
                expr: Box::new(instantiate_symbolic_grouped_expr_template(expr, bindings)?),
            })
        }
        PreparedSqlGroupedExprTemplate::Binary { op, left, right } => {
            Ok(crate::db::query::plan::expr::Expr::Binary {
                op: *op,
                left: Box::new(instantiate_symbolic_grouped_expr_template(left, bindings)?),
                right: Box::new(instantiate_symbolic_grouped_expr_template(right, bindings)?),
            })
        }
    }
}

fn bind_prepared_template_predicate(
    predicate: crate::db::predicate::Predicate,
    replacements: &[(Value, Value)],
) -> crate::db::predicate::Predicate {
    match predicate {
        crate::db::predicate::Predicate::True => crate::db::predicate::Predicate::True,
        crate::db::predicate::Predicate::False => crate::db::predicate::Predicate::False,
        crate::db::predicate::Predicate::And(children) => crate::db::predicate::Predicate::And(
            children
                .into_iter()
                .map(|child| bind_prepared_template_predicate(child, replacements))
                .collect(),
        ),
        crate::db::predicate::Predicate::Or(children) => crate::db::predicate::Predicate::Or(
            children
                .into_iter()
                .map(|child| bind_prepared_template_predicate(child, replacements))
                .collect(),
        ),
        crate::db::predicate::Predicate::Not(child) => crate::db::predicate::Predicate::Not(
            Box::new(bind_prepared_template_predicate(*child, replacements)),
        ),
        crate::db::predicate::Predicate::Compare(compare) => {
            crate::db::predicate::Predicate::Compare(
                crate::db::predicate::ComparePredicate::with_coercion(
                    compare.field,
                    compare.op,
                    bind_prepared_template_value(compare.value, replacements),
                    compare.coercion.id,
                ),
            )
        }
        crate::db::predicate::Predicate::CompareFields(compare) => {
            crate::db::predicate::Predicate::CompareFields(compare)
        }
        crate::db::predicate::Predicate::IsNull { field } => {
            crate::db::predicate::Predicate::IsNull { field }
        }
        crate::db::predicate::Predicate::IsNotNull { field } => {
            crate::db::predicate::Predicate::IsNotNull { field }
        }
        crate::db::predicate::Predicate::IsMissing { field } => {
            crate::db::predicate::Predicate::IsMissing { field }
        }
        crate::db::predicate::Predicate::IsEmpty { field } => {
            crate::db::predicate::Predicate::IsEmpty { field }
        }
        crate::db::predicate::Predicate::IsNotEmpty { field } => {
            crate::db::predicate::Predicate::IsNotEmpty { field }
        }
        crate::db::predicate::Predicate::TextContains { field, value } => {
            crate::db::predicate::Predicate::TextContains {
                field,
                value: bind_prepared_template_value(value, replacements),
            }
        }
        crate::db::predicate::Predicate::TextContainsCi { field, value } => {
            crate::db::predicate::Predicate::TextContainsCi {
                field,
                value: bind_prepared_template_value(value, replacements),
            }
        }
    }
}

fn bind_prepared_template_expr(
    expr: crate::db::query::plan::expr::Expr,
    replacements: &[(Value, Value)],
) -> crate::db::query::plan::expr::Expr {
    match expr {
        crate::db::query::plan::expr::Expr::Field(field) => {
            crate::db::query::plan::expr::Expr::Field(field)
        }
        crate::db::query::plan::expr::Expr::Literal(value) => {
            crate::db::query::plan::expr::Expr::Literal(bind_prepared_template_value(
                value,
                replacements,
            ))
        }
        crate::db::query::plan::expr::Expr::FunctionCall { function, args } => {
            crate::db::query::plan::expr::Expr::FunctionCall {
                function,
                args: args
                    .into_iter()
                    .map(|arg| bind_prepared_template_expr(arg, replacements))
                    .collect(),
            }
        }
        crate::db::query::plan::expr::Expr::Unary { op, expr } => {
            crate::db::query::plan::expr::Expr::Unary {
                op,
                expr: Box::new(bind_prepared_template_expr(*expr, replacements)),
            }
        }
        crate::db::query::plan::expr::Expr::Binary { op, left, right } => {
            crate::db::query::plan::expr::Expr::Binary {
                op,
                left: Box::new(bind_prepared_template_expr(*left, replacements)),
                right: Box::new(bind_prepared_template_expr(*right, replacements)),
            }
        }
        crate::db::query::plan::expr::Expr::Case {
            when_then_arms,
            else_expr,
        } => crate::db::query::plan::expr::Expr::Case {
            when_then_arms: when_then_arms
                .into_iter()
                .map(|arm| {
                    crate::db::query::plan::expr::CaseWhenArm::new(
                        bind_prepared_template_expr(arm.condition().clone(), replacements),
                        bind_prepared_template_expr(arm.result().clone(), replacements),
                    )
                })
                .collect(),
            else_expr: Box::new(bind_prepared_template_expr(*else_expr, replacements)),
        },
        crate::db::query::plan::expr::Expr::Aggregate(aggregate) => {
            crate::db::query::plan::expr::Expr::Aggregate(bind_prepared_template_aggregate(
                aggregate,
                replacements,
            ))
        }
        #[cfg(test)]
        crate::db::query::plan::expr::Expr::Alias { expr, name } => {
            crate::db::query::plan::expr::Expr::Alias {
                expr: Box::new(bind_prepared_template_expr(*expr, replacements)),
                name,
            }
        }
    }
}

fn bind_prepared_template_aggregate(
    aggregate: crate::db::query::builder::AggregateExpr,
    replacements: &[(Value, Value)],
) -> crate::db::query::builder::AggregateExpr {
    let kind = aggregate.kind();
    let input_expr = aggregate
        .input_expr()
        .cloned()
        .map(|expr| bind_prepared_template_expr(expr, replacements));
    let filter_expr = aggregate
        .filter_expr()
        .cloned()
        .map(|expr| bind_prepared_template_expr(expr, replacements));
    let mut rebound = input_expr.map_or_else(
        || match kind {
            crate::db::query::plan::AggregateKind::Count => builder::aggregate::count(),
            crate::db::query::plan::AggregateKind::Exists => builder::aggregate::exists(),
            crate::db::query::plan::AggregateKind::First => builder::aggregate::first(),
            crate::db::query::plan::AggregateKind::Last => builder::aggregate::last(),
            crate::db::query::plan::AggregateKind::Min => builder::aggregate::min(),
            crate::db::query::plan::AggregateKind::Max => builder::aggregate::max(),
            crate::db::query::plan::AggregateKind::Sum
            | crate::db::query::plan::AggregateKind::Avg => {
                unreachable!("SUM/AVG aggregate templates must preserve one input expression")
            }
        },
        |expr| crate::db::query::builder::AggregateExpr::from_expression_input(kind, expr),
    );

    if let Some(filter_expr) = filter_expr {
        rebound = rebound.with_filter_expr(filter_expr);
    }
    if aggregate.is_distinct() {
        rebound = rebound.distinct();
    }

    rebound
}

fn bind_prepared_template_value(value: Value, replacements: &[(Value, Value)]) -> Value {
    replacements
        .iter()
        .find(|(template, _)| *template == value)
        .map_or(value, |(_, bound)| bound.clone())
}

fn validate_parameter_bindings(
    contracts: &[PreparedSqlParameterContract],
    bindings: &[Value],
) -> Result<(), QueryError> {
    if bindings.len() != contracts.len() {
        return Err(QueryError::unsupported_query(format!(
            "prepared SQL expected {} bindings, found {}",
            contracts.len(),
            bindings.len(),
        )));
    }

    for contract in contracts {
        let binding = bindings.get(contract.index()).ok_or_else(|| {
            QueryError::unsupported_query(format!(
                "missing prepared SQL binding at index={}",
                contract.index(),
            ))
        })?;
        if !binding_matches_contract(binding, contract) {
            return Err(QueryError::unsupported_query(format!(
                "prepared SQL binding at index={} does not match the required {:?} contract",
                contract.index(),
                contract.type_family(),
            )));
        }
    }

    Ok(())
}

const fn binding_matches_contract(value: &Value, contract: &PreparedSqlParameterContract) -> bool {
    if matches!(value, Value::Null) {
        return contract.null_allowed();
    }

    match contract.type_family() {
        PreparedSqlParameterTypeFamily::Numeric => matches!(
            value,
            Value::Int(_)
                | Value::Int128(_)
                | Value::IntBig(_)
                | Value::Uint(_)
                | Value::Uint128(_)
                | Value::UintBig(_)
                | Value::Float32(_)
                | Value::Float64(_)
                | Value::Decimal(_)
                | Value::Duration(_)
                | Value::Timestamp(_)
        ),
        PreparedSqlParameterTypeFamily::Text => {
            matches!(value, Value::Text(_) | Value::Enum(_))
        }
        PreparedSqlParameterTypeFamily::Bool => matches!(value, Value::Bool(_)),
    }
}