switchy_database 0.5.0

Switchy database package
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
//! SQL query builder types and expressions
//!
//! This module provides a type-safe query builder API for constructing SQL queries
//! without writing raw SQL strings. It includes support for SELECT, INSERT, UPDATE,
//! DELETE, and UPSERT operations with WHERE clauses, JOINs, and complex expressions.
//!
//! # Query Builder Pattern
//!
//! The query builders use a fluent API that mirrors SQL syntax:
//!
//! ```rust,ignore
//! use switchy_database::{Database, DatabaseError};
//!
//! # async fn example(db: &dyn Database) -> Result<(), DatabaseError> {
//! // SELECT - methods like where_eq require importing FilterableQuery trait
//! let users = db.select("users")
//!     .columns(&["id", "name", "email"])
//!     .limit(10)
//!     .execute(db)
//!     .await?;
//!
//! // INSERT with values
//! let new_user = db.insert("users")
//!     .value("name", "Alice")
//!     .value("email", "alice@example.com")
//!     .execute(db)
//!     .await?;
//!
//! // UPDATE with values
//! let updated = db.update("users")
//!     .value("last_login", switchy_database::DatabaseValue::Now)
//!     .execute(db)
//!     .await?;
//!
//! // DELETE
//! let deleted = db.delete("users")
//!     .execute(db)
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Expression System
//!
//! The module provides an [`Expression`](crate::query::Expression) trait and various expression types
//! for building complex WHERE clauses and query conditions:
//!
//! * **Comparison**: `Eq`, `NotEq`, `Gt`, `Gte`, `Lt`, `Lte`
//! * **Logical**: `And`, `Or`
//! * **List operations**: `In`, `NotIn`, `InList`
//! * **SQL functions**: `Coalesce`
//! * **Raw SQL**: `Literal` for SQL expressions, `Identifier` for column names
//!
//! # JOINs
//!
//! The query builder supports INNER and LEFT JOINs:
//!
//! ```rust,ignore
//! use switchy_database::{Database, DatabaseError};
//!
//! # async fn example(db: &dyn Database) -> Result<(), DatabaseError> {
//! let results = db.select("orders")
//!     .columns(&["orders.id", "users.name"])
//!     .join("users", (
//!         qualified_column("orders", "user_id"),
//!         qualified_column("users", "id"),
//!     ))  // INNER JOIN
//!     .left_join("addresses", (
//!         qualified_column("users", "address_id"),
//!         qualified_column("addresses", "id"),
//!     ))  // LEFT JOIN
//!     .execute(db)
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::fmt::Debug;

use crate::{Database, DatabaseError, DatabaseValue, Row};

/// Render an exact identifier, preserving the transitional raw-enabled behavior.
#[cfg(any(
    feature = "sqlite-rusqlite",
    feature = "sqlite-sqlx",
    feature = "postgres-raw",
    feature = "postgres-sqlx",
    feature = "mysql-sqlx",
    feature = "duckdb",
    feature = "turso"
))]
pub(crate) fn render_identifier(value: &str, delimiter: char) -> String {
    if cfg!(feature = "raw-sql") {
        value.to_owned()
    } else {
        let escaped = value.replace(delimiter, &format!("{delimiter}{delimiter}"));
        format!("{delimiter}{escaped}{delimiter}")
    }
}

/// Render a legacy SELECT column list without allowing fragments in no-raw builds.
/// The standalone wildcard retains its query-builder meaning; all other strings
/// are exact identifiers, including strings containing dots.
#[cfg(any(
    feature = "sqlite-rusqlite",
    feature = "sqlite-sqlx",
    feature = "postgres-sqlx",
    feature = "postgres-raw",
    feature = "mysql-sqlx",
    feature = "duckdb",
    feature = "turso"
))]
pub(crate) fn render_columns(columns: &[&str], delimiter: char) -> String {
    columns
        .iter()
        .map(|column| {
            if *column == "*" {
                "*".to_owned()
            } else {
                render_identifier(column, delimiter)
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Sort direction for ORDER BY clauses
#[derive(Debug, Clone, Copy)]
pub enum SortDirection {
    /// Ascending order (smallest to largest, A to Z)
    Asc,
    /// Descending order (largest to smallest, Z to A)
    Desc,
}

/// Sort expression combining a column/expression with a sort direction
#[derive(Debug)]
pub struct Sort {
    /// The column or expression to sort by
    pub expression: Box<dyn Expression>,
    /// The sort direction (ascending or descending)
    pub direction: SortDirection,
}

impl Expression for Sort {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Sort(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}

/// JOIN clause specification for combining tables
#[derive(Debug, Clone)]
pub struct Join<'a> {
    /// Name of the table to join with
    pub table_name: &'a str,
    /// Typed equality condition, or a feature-gated raw predicate.
    pub on: JoinCondition,
    /// Whether this is a LEFT JOIN (true) or INNER JOIN (false)
    pub left: bool,
}

/// A JOIN predicate that cannot carry caller SQL without `raw-sql`.
#[cfg_attr(
    not(feature = "raw-sql"),
    doc = r#"
```compile_fail
use switchy_database::query::JoinCondition;
let _ = JoinCondition::Raw("1 = 1".to_owned());
```
```compile_fail
use switchy_database::query::join;
let _ = join("items", "1 = 1");
```
```compile_fail
use switchy_database::query::select;
let _ = select("items").join("other", "1 = 1");
```
```compile_fail
use switchy_database::query::left_join;
let _ = left_join("items", "1 = 1");
```
```compile_fail
use switchy_database::query::select;
let _ = select("items").left_join("other", "1 = 1");
```
"#
)]
#[derive(Debug, Clone)]
pub enum JoinCondition {
    /// Equality between independently quoted, qualified columns.
    ColumnsEqual(QualifiedColumn, QualifiedColumn),
    /// Conjunction of typed JOIN conditions. An empty conjunction is true.
    And(Vec<Self>),
    /// Arbitrary SQL retained only for compatibility callers.
    #[cfg(feature = "raw-sql")]
    Raw(String),
}

impl From<(QualifiedColumn, QualifiedColumn)> for JoinCondition {
    fn from((first, second): (QualifiedColumn, QualifiedColumn)) -> Self {
        Self::ColumnsEqual(first, second)
    }
}

#[cfg(feature = "raw-sql")]
impl From<&str> for JoinCondition {
    fn from(sql: &str) -> Self {
        Self::Raw(sql.to_owned())
    }
}

#[cfg(feature = "raw-sql")]
impl From<String> for JoinCondition {
    fn from(sql: String) -> Self {
        Self::Raw(sql)
    }
}

impl JoinCondition {
    #[cfg(any(
        feature = "sqlite-rusqlite",
        feature = "sqlite-sqlx",
        feature = "postgres-raw",
        feature = "postgres-sqlx",
        feature = "mysql-sqlx",
        feature = "duckdb",
        feature = "turso"
    ))]
    pub(crate) fn render(&self, delimiter: char) -> String {
        match self {
            Self::ColumnsEqual(left, right) => {
                format!("{} = {}", left.render(delimiter), right.render(delimiter))
            }
            Self::And(conditions) => {
                if conditions.is_empty() {
                    return "1 = 1".to_owned();
                }
                format!(
                    "({})",
                    conditions
                        .iter()
                        .map(|condition| condition.render(delimiter))
                        .collect::<Vec<_>>()
                        .join(" AND ")
                )
            }
            #[cfg(feature = "raw-sql")]
            Self::Raw(sql) => sql.clone(),
        }
    }
}

/// Creates a JOIN using equality of exact qualified column names.
///
/// Set `left` for a LEFT JOIN. Dots and quotes within each name are literal;
/// use [`qualified_column`] to specify qualification explicitly.
#[must_use]
pub const fn join_columns(
    table_name: &str,
    first: QualifiedColumn,
    second: QualifiedColumn,
    left: bool,
) -> Join<'_> {
    Join {
        table_name,
        on: JoinCondition::ColumnsEqual(first, second),
        left,
    }
}

impl Join<'_> {
    #[cfg(any(
        feature = "sqlite-rusqlite",
        feature = "sqlite-sqlx",
        feature = "postgres-raw",
        feature = "postgres-sqlx",
        feature = "mysql-sqlx",
        feature = "duckdb",
        feature = "turso"
    ))]
    pub(crate) fn render_table(&self, delimiter: char) -> String {
        #[cfg(feature = "raw-sql")]
        if matches!(self.on, JoinCondition::Raw(_)) {
            return self.table_name.to_owned();
        }
        let escaped = self
            .table_name
            .replace(delimiter, &format!("{delimiter}{delimiter}"));
        format!("{delimiter}{escaped}{delimiter}")
    }
}

impl Expression for Join<'_> {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Join(self)
    }
}

/// Tagged union representing different types of SQL expressions
///
/// This enum is used internally by the query builder to distinguish between
/// different expression types when generating SQL. Each variant holds a reference
/// to the actual expression object.
pub enum ExpressionType<'a> {
    /// SQLite JSON storage type predicate at a validated path.
    JsonTypeIs(&'a JsonTypeIs),
    /// SQLite storage-class observation.
    StorageType(&'a StorageType),
    /// Typed arithmetic addition.
    Add(&'a Add),
    /// SQLite zero-filled BLOB.
    ZeroBlob(&'a ZeroBlob),
    /// Typed SQLite storage-class cast.
    StorageCast(&'a StorageCast),
    #[cfg(feature = "schema")]
    /// A closed persistent schema predicate with escaped constants.
    SchemaPredicate(&'a SchemaPredicate),
    /// A bounded SQLite text projection preserving invalid rows with a fallback.
    BoundedText(&'a BoundedText),
    /// Greater-than comparison between structured expressions.
    GtExpression(&'a GtExpression),
    /// Equality between structured expressions.
    EqExpression(&'a EqExpression),
    /// Inequality between structured expressions.
    NotEqExpression(&'a NotEqExpression),
    /// Equality comparison expression
    Eq(&'a Eq),
    /// Greater than comparison expression
    Gt(&'a Gt),
    /// IN clause expression
    In(&'a In<'a>),
    /// Less than comparison expression
    Lt(&'a Lt),
    /// Logical OR expression
    Or(&'a Or),
    /// Logical AND expression
    And(&'a And),
    /// Greater than or equal comparison expression
    Gte(&'a Gte),
    /// Less than or equal comparison expression
    Lte(&'a Lte),
    /// JOIN clause expression
    Join(&'a Join<'a>),
    /// Sort expression
    Sort(&'a Sort),
    /// NOT IN clause expression
    NotIn(&'a NotIn<'a>),
    /// Not equal comparison expression
    NotEq(&'a NotEq),
    /// Negated SQL pattern comparison.
    NotLike(&'a NotLike),
    /// IN list expression (with explicit list of values)
    InList(&'a InList),
    /// Raw SQL literal expression
    #[cfg(feature = "raw-sql")]
    Literal(&'a Literal),
    /// UTF-8 byte length of a text expression (NULL remains NULL).
    ByteLength(&'a ByteLength),
    /// Minimum non-NULL value of a typed expression.
    Min(&'a Min),
    /// Maximum non-NULL value of a typed expression.
    Max(&'a Max),
    /// Number of rows, or non-NULL values of a typed expression.
    Count(&'a Count),
    /// COALESCE function expression
    Coalesce(&'a Coalesce),
    /// Explicitly qualified column with separately quoted components.
    QualifiedColumn(&'a QualifiedColumn),
    /// Column/table identifier expression
    Identifier(&'a Identifier),
    /// Subquery expression
    SelectQuery(&'a SelectQuery<'a>),
    /// Database value expression
    DatabaseValue(&'a DatabaseValue),
}

/// Base trait for all SQL expression types
///
/// This trait provides the common interface for all expression types in the query builder.
/// Expressions can be column references, comparisons, logical operations, literals, or subqueries.
pub trait Expression: Send + Sync + Debug {
    /// Returns the type tag for this expression
    fn expression_type(&self) -> ExpressionType<'_>;

    /// Extracts bindable parameters from this expression
    ///
    /// Returns only values that can be bound as query parameters, filtering out
    /// NULL values and SQL function expressions like `NOW()`.
    fn params(&self) -> Option<Vec<&DatabaseValue>> {
        self.values().map(|x| {
            x.into_iter()
                .filter(|value| {
                    !value.is_null()
                        && !matches!(value, DatabaseValue::Now | DatabaseValue::NowPlus(_))
                })
                .collect::<Vec<_>>()
        })
    }

    /// Extracts all database values from this expression
    ///
    /// Returns all [`DatabaseValue`] instances within this expression, including those
    /// that cannot be bound as parameters. Default implementation returns `None`.
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        None
    }

    /// Checks if this expression represents a NULL value
    ///
    /// Returns `true` if this expression is a NULL value, `false` otherwise.
    /// Default implementation returns `false`.
    fn is_null(&self) -> bool {
        false
    }
}

/// Raw SQL literal expression
///
/// Represents a raw SQL expression that will be inserted into the generated SQL
/// without escaping or parameterization. Use with caution to avoid SQL injection.
///
/// # Safety
///
/// The value is inserted directly into SQL. Never use with untrusted user input.
#[cfg(feature = "raw-sql")]
#[derive(Debug)]
pub struct Literal {
    /// The raw SQL expression text
    pub value: String,
}

#[cfg(feature = "raw-sql")]
impl From<&str> for Literal {
    fn from(val: &str) -> Self {
        Self {
            value: val.to_string(),
        }
    }
}

#[cfg(feature = "raw-sql")]
impl From<&String> for Literal {
    fn from(val: &String) -> Self {
        Self { value: val.clone() }
    }
}

#[cfg(feature = "raw-sql")]
impl From<String> for Literal {
    fn from(val: String) -> Self {
        Self { value: val }
    }
}

#[cfg(feature = "raw-sql")]
impl From<Literal> for Box<dyn Expression> {
    fn from(val: Literal) -> Self {
        Box::new(val)
    }
}

#[cfg(feature = "raw-sql")]
impl Expression for Literal {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Literal(self)
    }
}

/// Creates a raw SQL literal expression
///
/// # Safety
///
/// The value is inserted directly into SQL without escaping. Never use with untrusted user input.
#[must_use]
#[cfg(feature = "raw-sql")]
pub fn literal(value: &str) -> Literal {
    Literal {
        value: value.to_string(),
    }
}

/// Minimum non-NULL value of a typed expression.
///
/// An empty input or an input containing only NULL values produces SQL NULL.
#[derive(Debug)]
pub struct Min {
    /// Operand, rendered through the backend's typed expression implementation.
    pub expression: Box<dyn Expression>,
}

impl Expression for Min {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Min(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}

impl From<Min> for Box<dyn Expression> {
    fn from(value: Min) -> Self {
        Box::new(value)
    }
}

/// Returns the minimum non-NULL value of a typed expression.
///
/// Use a typed column expression for column operands. Bound values remain bound;
/// no caller-supplied SQL function name or fragment is accepted.
#[must_use]
pub fn min(expression: impl Into<Box<dyn Expression>>) -> Min {
    Min {
        expression: expression.into(),
    }
}

/// Maximum non-NULL value of a typed expression.
///
/// An empty input or an input containing only NULL values produces SQL NULL.
#[derive(Debug)]
pub struct Max {
    /// Typed operand; never an SQL fragment.
    pub expression: Box<dyn Expression>,
}

impl Expression for Max {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Max(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}

impl From<Max> for Box<dyn Expression> {
    fn from(value: Max) -> Self {
        Box::new(value)
    }
}

/// Returns the maximum non-NULL value of a typed expression.
#[must_use]
pub fn max(expression: impl Into<Box<dyn Expression>>) -> Max {
    Max {
        expression: expression.into(),
    }
}

/// Counts rows or non-NULL expression values. Empty input produces zero.
#[derive(Debug)]
pub struct Count {
    /// None counts all rows; Some counts non-NULL values of the typed operand.
    pub expression: Option<Box<dyn Expression>>,
}

impl Expression for Count {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Count(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.as_ref().and_then(|value| value.values())
    }
}

impl From<Count> for Box<dyn Expression> {
    fn from(value: Count) -> Self {
        Box::new(value)
    }
}

/// Counts non-NULL values of a typed expression, preserving bound parameters.
#[must_use]
pub fn count(expression: impl Into<Box<dyn Expression>>) -> Count {
    Count {
        expression: Some(expression.into()),
    }
}

/// Counts all rows, including rows containing NULL values.
#[must_use]
pub const fn count_all() -> Count {
    Count { expression: None }
}

/// UTF-8 byte length of a text expression, preserving SQL NULL.
///
/// This is not a character or grapheme count. The operand must be text;
/// behavior for other SQL types is backend-dependent.
#[derive(Debug)]
pub struct ByteLength {
    /// Typed text operand; never an SQL fragment.
    pub expression: Box<dyn Expression>,
}

impl Expression for ByteLength {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::ByteLength(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}

impl From<ByteLength> for Box<dyn Expression> {
    fn from(value: ByteLength) -> Self {
        Box::new(value)
    }
}

/// Counts UTF-8 bytes in a typed text expression, preserving SQL NULL.
///
/// Use [`identifier`] or [`qualified_column`] for column operands, or a
/// [`DatabaseValue`] for bound text. Strings are not interpreted as SQL.
#[must_use]
pub fn byte_length(expression: impl Into<Box<dyn Expression>>) -> ByteLength {
    ByteLength {
        expression: expression.into(),
    }
}

/// A column qualified by an exact table name or table alias.
///
/// Both components are always quoted independently, even with `raw-sql` enabled.
/// Dots within a component are literal name characters, never extra qualification.
#[derive(Debug, Clone)]
pub struct QualifiedColumn {
    /// Exact table name or alias.
    pub table: String,
    /// Exact column name.
    pub column: String,
}

impl Expression for QualifiedColumn {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::QualifiedColumn(self)
    }
}

impl From<QualifiedColumn> for Box<dyn Expression> {
    fn from(value: QualifiedColumn) -> Self {
        Box::new(value)
    }
}

/// Refers to a column through an explicit table name or alias.
///
/// Unlike `identifier("table.column")`, this produces two independently quoted
/// identifiers separated by a qualification dot. Neither argument accepts SQL.
#[must_use]
pub fn qualified_column(table: &str, column: &str) -> QualifiedColumn {
    QualifiedColumn {
        table: table.to_owned(),
        column: column.to_owned(),
    }
}

impl QualifiedColumn {
    #[cfg(any(
        feature = "sqlite-rusqlite",
        feature = "sqlite-sqlx",
        feature = "postgres-raw",
        feature = "postgres-sqlx",
        feature = "mysql-sqlx",
        feature = "duckdb",
        feature = "turso"
    ))]
    pub(crate) fn render(&self, delimiter: char) -> String {
        let quote = |name: &str| {
            let escaped = name.replace(delimiter, &format!("{delimiter}{delimiter}"));
            format!("{delimiter}{escaped}{delimiter}")
        };
        format!("{}.{}", quote(&self.table), quote(&self.column))
    }
}

/// SQL identifier (column or table name)
///
/// Represents a database identifier that will be properly quoted/escaped
/// for the target database backend.
#[derive(Debug)]
pub struct Identifier {
    /// The identifier name (column or table)
    pub value: String,
}

impl From<&str> for Identifier {
    fn from(val: &str) -> Self {
        Self {
            value: val.to_string(),
        }
    }
}

impl From<String> for Identifier {
    fn from(val: String) -> Self {
        Self { value: val }
    }
}

impl From<Identifier> for Box<dyn Expression> {
    fn from(val: Identifier) -> Self {
        Box::new(val)
    }
}

impl Expression for Identifier {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Identifier(self)
    }
}

/// Creates an SQL identifier expression for a column or table name
///
/// Without `raw-sql`, this expression denotes one exact identifier. Dots,
/// quotes, spaces, and SQL-looking content are part of its name, not SQL.
#[must_use]
pub fn identifier(value: &str) -> Identifier {
    Identifier {
        value: value.to_string(),
    }
}

impl Expression for DatabaseValue {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::DatabaseValue(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        Some(vec![self])
    }

    fn is_null(&self) -> bool {
        #[cfg(all(not(feature = "decimal"), not(feature = "uuid")))]
        {
            matches!(
                self,
                Self::Null
                    | Self::BoolOpt(None)
                    | Self::Real64Opt(None)
                    | Self::Real32Opt(None)
                    | Self::StringOpt(None)
                    | Self::Int64Opt(None)
                    | Self::UInt64Opt(None)
            )
        }
        #[cfg(all(feature = "decimal", not(feature = "uuid")))]
        {
            matches!(
                self,
                Self::Null
                    | Self::BoolOpt(None)
                    | Self::Real64Opt(None)
                    | Self::Real32Opt(None)
                    | Self::StringOpt(None)
                    | Self::Int64Opt(None)
                    | Self::UInt64Opt(None)
                    | Self::DecimalOpt(None)
            )
        }
        #[cfg(all(not(feature = "decimal"), feature = "uuid"))]
        {
            matches!(
                self,
                Self::Null
                    | Self::BoolOpt(None)
                    | Self::Real64Opt(None)
                    | Self::Real32Opt(None)
                    | Self::StringOpt(None)
                    | Self::Int64Opt(None)
                    | Self::UInt64Opt(None)
                    | Self::UuidOpt(None)
            )
        }
        #[cfg(all(feature = "decimal", feature = "uuid"))]
        {
            matches!(
                self,
                Self::Null
                    | Self::BoolOpt(None)
                    | Self::Real64Opt(None)
                    | Self::Real32Opt(None)
                    | Self::StringOpt(None)
                    | Self::Int64Opt(None)
                    | Self::UInt64Opt(None)
                    | Self::DecimalOpt(None)
                    | Self::UuidOpt(None)
            )
        }
    }
}

impl<T: Into<DatabaseValue>> From<T> for Box<dyn Expression> {
    fn from(value: T) -> Self {
        Box::new(value.into())
    }
}

/// Marker trait for expressions that evaluate to boolean values
///
/// Used to ensure WHERE clause expressions are boolean-valued.
pub trait BooleanExpression: Expression {}

/// Logical AND expression combining multiple boolean conditions
#[derive(Debug)]
pub struct And {
    pub(crate) conditions: Vec<Box<dyn BooleanExpression>>,
}

impl BooleanExpression for And {}
impl Expression for And {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::And(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let values = self
            .conditions
            .iter()
            .filter_map(|x| x.values())
            .collect::<Vec<_>>()
            .concat();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// Logical OR expression combining multiple boolean conditions
#[derive(Debug)]
pub struct Or {
    /// The boolean conditions to combine with OR
    pub conditions: Vec<Box<dyn BooleanExpression>>,
}

impl BooleanExpression for Or {}
impl Expression for Or {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Or(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let values = self
            .conditions
            .iter()
            .filter_map(|x| x.values())
            .collect::<Vec<_>>()
            .concat();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// Negated SQL LIKE comparison. The pattern is bound as data.
#[derive(Debug)]
pub struct NotLike {
    /// Exact column identifier.
    pub left: Identifier,
    /// Pattern value.
    pub right: DatabaseValue,
}

impl BooleanExpression for NotLike {}
impl Expression for NotLike {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::NotLike(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        Some(vec![&self.right])
    }
}

/// Exclude rows matching a SQL LIKE pattern (`%` and `_` are wildcards).
#[must_use]
pub fn where_not_like(column: impl Into<Identifier>, pattern: impl Into<String>) -> NotLike {
    NotLike {
        left: column.into(),
        right: DatabaseValue::String(pattern.into()),
    }
}

/// A validated JSON object-member path; callers cannot supply SQL or path fragments.
#[derive(Debug, Clone)]
pub struct JsonPath {
    member: String,
}
impl JsonPath {
    /// Exact validated object member represented by this path.
    #[must_use]
    pub fn member_name(&self) -> &str {
        &self.member
    }

    /// Select one exact object key using a conservative portable path segment.
    ///
    /// # Errors
    /// * Rejects empty keys and characters other than ASCII letters, digits and underscore.
    pub fn member(member: impl Into<String>) -> Result<Self, crate::DatabaseError> {
        let member = member.into();
        if member.is_empty()
            || !member
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
        {
            return Err(crate::DatabaseError::InvalidQuery(
                "Invalid JSON object path segment".into(),
            ));
        }
        Ok(Self { member })
    }
    #[cfg(any(
        feature = "sqlite-rusqlite",
        feature = "sqlite-sqlx",
        feature = "postgres-raw",
        feature = "postgres-sqlx",
        feature = "mysql-sqlx",
        feature = "duckdb",
        feature = "turso"
    ))]
    pub(crate) fn sqlite(&self) -> String {
        format!("'$.{}'", self.member)
    }
}
/// Closed JSON value type names, distinct from SQL storage classes.
#[derive(Debug, Clone, Copy)]
pub enum JsonType {
    /// JSON integer.
    Integer,
    /// JSON non-integer number.
    Real,
    /// JSON string.
    Text,
    /// Explicit JSON null (not a missing member).
    Null,
    /// JSON object.
    Object,
    /// JSON array.
    Array,
    /// JSON true.
    True,
    /// JSON false.
    False,
}
impl JsonType {
    #[cfg(any(
        feature = "sqlite-rusqlite",
        feature = "sqlite-sqlx",
        feature = "postgres-raw",
        feature = "postgres-sqlx",
        feature = "mysql-sqlx",
        feature = "duckdb",
        feature = "turso"
    ))]
    pub(crate) const fn sqlite(self) -> &'static str {
        match self {
            Self::Integer => "integer",
            Self::Real => "real",
            Self::Text => "text",
            Self::Null => "null",
            Self::Object => "object",
            Self::Array => "array",
            Self::True => "true",
            Self::False => "false",
        }
    }
}
/// Test a JSON member's type without fetching or parsing the JSON in the caller.
#[derive(Debug)]
pub struct JsonTypeIs {
    /// Structured JSON operand.
    pub expression: Box<dyn Expression>,
    /// Validated object-member path.
    pub path: JsonPath,
    /// Required JSON type.
    pub kind: JsonType,
}
impl BooleanExpression for JsonTypeIs {}
impl Expression for JsonTypeIs {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::JsonTypeIs(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}
/// Require an exact JSON type. Malformed JSON remains a backend execution error.
#[must_use]
pub fn json_type_is(
    expression: impl Into<Box<dyn Expression>>,
    path: JsonPath,
    kind: JsonType,
) -> JsonTypeIs {
    JsonTypeIs {
        expression: expression.into(),
        path,
        kind,
    }
}

/// Observe SQLite's storage class without decoding the value.
#[derive(Debug)]
pub struct StorageType {
    /// Structured operand.
    pub expression: Box<dyn Expression>,
}
impl Expression for StorageType {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::StorageType(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}
impl From<StorageType> for Box<dyn Expression> {
    fn from(value: StorageType) -> Self {
        Box::new(value)
    }
}
/// Return SQLite's closed storage-class name (null/integer/real/text/blob).
#[must_use]
pub fn storage_type(expression: impl Into<Box<dyn Expression>>) -> StorageType {
    StorageType {
        expression: expression.into(),
    }
}

/// Typed arithmetic addition used in atomic assignments.
#[derive(Debug)]
pub struct Add {
    /// Structured left operand.
    pub left: Box<dyn Expression>,
    /// Structured right operand.
    pub right: Box<dyn Expression>,
}
impl Expression for Add {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Add(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        Some(
            [
                self.left.values().unwrap_or_default(),
                self.right.values().unwrap_or_default(),
            ]
            .concat(),
        )
    }
}
impl From<Add> for Box<dyn Expression> {
    fn from(value: Add) -> Self {
        Box::new(value)
    }
}
/// Add structured operands; values remain bound, never SQL fragments.
#[must_use]
pub fn add(left: impl Into<Box<dyn Expression>>, right: impl Into<Box<dyn Expression>>) -> Add {
    Add {
        left: left.into(),
        right: right.into(),
    }
}

/// A zero-filled SQLite BLOB, allocated by SQLite rather than the caller.
#[derive(Debug)]
pub struct ZeroBlob {
    /// Requested byte length.
    pub length: u32,
}
impl Expression for ZeroBlob {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::ZeroBlob(self)
    }
}
impl From<ZeroBlob> for Box<dyn Expression> {
    fn from(value: ZeroBlob) -> Self {
        Box::new(value)
    }
}
/// Construct a SQLite zero-filled BLOB. Oversized allocations fail at execution.
#[must_use]
pub const fn zero_blob(length: u32) -> ZeroBlob {
    ZeroBlob { length }
}
/// Closed SQLite storage-class cast targets.
#[derive(Debug, Clone, Copy)]
pub enum StorageCastTarget {
    /// BLOB storage.
    Blob,
    /// TEXT storage.
    Text,
}
/// A typed storage-class cast with no caller type-name fragment.
#[derive(Debug)]
pub struct StorageCast {
    /// Structured operand.
    pub expression: Box<dyn Expression>,
    /// Closed target.
    pub target: StorageCastTarget,
}
impl Expression for StorageCast {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::StorageCast(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.expression.values()
    }
}
impl From<StorageCast> for Box<dyn Expression> {
    fn from(value: StorageCast) -> Self {
        Box::new(value)
    }
}
/// Cast a typed expression to SQLite BLOB storage.
#[must_use]
pub fn cast_blob(expression: impl Into<Box<dyn Expression>>) -> StorageCast {
    StorageCast {
        expression: expression.into(),
        target: StorageCastTarget::Blob,
    }
}
/// Cast a typed expression to SQLite TEXT storage.
#[must_use]
pub fn cast_text(expression: impl Into<Box<dyn Expression>>) -> StorageCast {
    StorageCast {
        expression: expression.into(),
        target: StorageCastTarget::Text,
    }
}

/// A closed persistent predicate rendered from the typed schema AST.
#[cfg(feature = "schema")]
#[derive(Debug)]
pub struct SchemaPredicate {
    pub(crate) sqlite: String,
    #[cfg(feature = "mysql-sqlx")]
    pub(crate) mysql: String,
}
#[cfg(feature = "schema")]
impl SchemaPredicate {
    /// Canonical escaped SQLite representation of this closed typed predicate.
    #[must_use]
    pub fn canonical_sqlite(&self) -> &str {
        &self.sqlite
    }
}
#[cfg(feature = "schema")]
impl BooleanExpression for SchemaPredicate {}
#[cfg(feature = "schema")]
impl Expression for SchemaPredicate {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::SchemaPredicate(self)
    }
}
/// Preserve a persistent predicate's literal AST for planner compatibility.
///
/// # Errors
/// * Rejects malformed typed schema constants or predicates.
#[cfg(feature = "schema")]
pub fn schema_predicate(
    predicate: &crate::schema::SchemaExpression,
) -> Result<SchemaPredicate, crate::DatabaseError> {
    Ok(SchemaPredicate {
        sqlite: predicate.render('"')?,
        #[cfg(feature = "mysql-sqlx")]
        mysql: predicate.render('`')?,
    })
}

/// A SQLite text projection that does not materialize oversized or wrongly typed values.
#[derive(Debug)]
pub struct BoundedText {
    /// Exact column/expression to inspect.
    pub expression: Box<dyn Expression>,
    /// UTF-8 byte budget.
    pub max_bytes: u64,
    /// Value returned for non-text and oversized inputs, including NULL.
    pub fallback: DatabaseValue,
}
impl Expression for BoundedText {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::BoundedText(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        // The inspected expression is rendered three times; retain bind order.
        let mut values = Vec::new();
        for _ in 0..3 {
            values.extend(self.expression.values().unwrap_or_default());
        }
        values.push(&self.fallback);
        Some(values)
    }
}
impl From<BoundedText> for Box<dyn Expression> {
    fn from(value: BoundedText) -> Self {
        Box::new(value)
    }
}
/// Project text only when its SQLite storage class is text and its byte length is bounded.
/// NULL, non-text and oversized inputs yield the caller's typed fallback, never drop rows.
#[must_use]
pub fn bounded_text(
    expression: impl Into<Box<dyn Expression>>,
    max_bytes: u64,
    fallback: DatabaseValue,
) -> BoundedText {
    BoundedText {
        expression: expression.into(),
        max_bytes,
        fallback,
    }
}

/// Equality between structured expressions, including qualified columns.
#[derive(Debug)]
pub struct EqExpression {
    /// Structured left operand.
    pub left: Box<dyn Expression>,
    /// Structured right operand.
    pub right: Box<dyn Expression>,
}
impl BooleanExpression for EqExpression {}
impl Expression for EqExpression {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::EqExpression(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        Some(
            [
                self.left.values().unwrap_or_default(),
                self.right.values().unwrap_or_default(),
            ]
            .concat(),
        )
    }
}
/// Inequality between structured expressions, including qualified columns.
#[derive(Debug)]
pub struct NotEqExpression {
    /// Structured left operand.
    pub left: Box<dyn Expression>,
    /// Structured right operand.
    pub right: Box<dyn Expression>,
}
impl BooleanExpression for NotEqExpression {}
impl Expression for NotEqExpression {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::NotEqExpression(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        Some(
            [
                self.left.values().unwrap_or_default(),
                self.right.values().unwrap_or_default(),
            ]
            .concat(),
        )
    }
}
/// Greater-than comparison between typed expressions.
#[derive(Debug)]
pub struct GtExpression {
    /// Structured left operand.
    pub left: Box<dyn Expression>,
    /// Structured right operand.
    pub right: Box<dyn Expression>,
}
impl BooleanExpression for GtExpression {}
impl Expression for GtExpression {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::GtExpression(self)
    }
    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        Some(
            [
                self.left.values().unwrap_or_default(),
                self.right.values().unwrap_or_default(),
            ]
            .concat(),
        )
    }
}
/// Compare typed expressions using strict greater-than ordering.
#[must_use]
pub fn where_gt_expression(
    left: impl Into<Box<dyn Expression>>,
    right: impl Into<Box<dyn Expression>>,
) -> GtExpression {
    GtExpression {
        left: left.into(),
        right: right.into(),
    }
}

/// Compare typed expressions without flattening qualified column names.
#[must_use]
pub fn where_eq_expression(
    left: impl Into<Box<dyn Expression>>,
    right: impl Into<Box<dyn Expression>>,
) -> EqExpression {
    EqExpression {
        left: left.into(),
        right: right.into(),
    }
}
/// Exclude equal typed expressions; a NULL right operand means IS NOT NULL.
#[must_use]
pub fn where_not_eq_expression(
    left: impl Into<Box<dyn Expression>>,
    right: impl Into<Box<dyn Expression>>,
) -> NotEqExpression {
    NotEqExpression {
        left: left.into(),
        right: right.into(),
    }
}

/// Not equal comparison expression (!=)
#[derive(Debug)]
pub struct NotEq {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// Right-hand side (value or expression)
    pub right: Box<dyn Expression>,
}

impl BooleanExpression for NotEq {}
impl Expression for NotEq {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::NotEq(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.right.values()
    }
}

/// Equal comparison expression (=)
#[derive(Debug)]
pub struct Eq {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// Right-hand side (value or expression)
    pub right: Box<dyn Expression>,
}

impl BooleanExpression for Eq {}
impl Expression for Eq {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Eq(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.right.values()
    }
}

/// Greater than comparison expression (>)
#[derive(Debug)]
pub struct Gt {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// Right-hand side (value or expression)
    pub right: Box<dyn Expression>,
}

impl BooleanExpression for Gt {}
impl Expression for Gt {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Gt(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.right.values()
    }
}

/// Greater than or equal comparison expression (>=)
#[derive(Debug)]
pub struct Gte {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// Right-hand side (value or expression)
    pub right: Box<dyn Expression>,
}

impl BooleanExpression for Gte {}
impl Expression for Gte {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Gte(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.right.values()
    }
}

/// Less than comparison expression (<)
#[derive(Debug)]
pub struct Lt {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// Right-hand side (value or expression)
    pub right: Box<dyn Expression>,
}

impl BooleanExpression for Lt {}
impl Expression for Lt {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Lt(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.right.values()
    }
}

/// Less than or equal comparison expression (<=)
#[derive(Debug)]
pub struct Lte {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// Right-hand side (value or expression)
    pub right: Box<dyn Expression>,
}

impl BooleanExpression for Lte {}
impl Expression for Lte {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Lte(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        self.right.values()
    }
}

/// IN clause expression checking if column value is in a list
#[derive(Debug)]
pub struct In<'a> {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// List of values or subquery to check against
    pub values: Box<dyn List + 'a>,
}

impl BooleanExpression for In<'_> {}
impl Expression for In<'_> {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::In(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let values = [
            self.left.values().unwrap_or_default(),
            self.values.values().unwrap_or_default(),
        ]
        .concat();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// NOT IN clause expression checking if column value is not in a list
#[derive(Debug)]
pub struct NotIn<'a> {
    /// Left-hand side (column identifier)
    pub left: Identifier,
    /// List of values or subquery to check against
    pub values: Box<dyn List + 'a>,
}

impl BooleanExpression for NotIn<'_> {}
impl Expression for NotIn<'_> {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::NotIn(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let values = [
            self.left.values().unwrap_or_default(),
            self.values.values().unwrap_or_default(),
        ]
        .concat();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// Creates a sort expression for ORDER BY clauses
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::{sort, identifier, SortDirection};
///
/// // Sort by name ascending
/// let sort_asc = sort(identifier("name"), SortDirection::Asc);
///
/// // Sort by age descending
/// let sort_desc = sort(identifier("age"), SortDirection::Desc);
/// ```
#[must_use]
pub fn sort<T>(expression: T, direction: SortDirection) -> Sort
where
    T: Into<Box<dyn Expression>>,
{
    Sort {
        expression: expression.into(),
        direction,
    }
}

/// Creates an equality comparison expression (column = value)
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::where_eq;
/// use switchy_database::DatabaseValue;
///
/// // Compare column to value
/// let filter = where_eq("user_id", DatabaseValue::Int64(123));
/// ```
#[must_use]
pub fn where_eq<L, R>(left: L, right: R) -> Eq
where
    L: Into<Identifier>,
    R: Into<Box<dyn Expression>>,
{
    Eq {
        left: left.into(),
        right: right.into(),
    }
}

/// Creates a not-equal comparison expression (column != value)
#[must_use]
pub fn where_not_eq<L, R>(left: L, right: R) -> NotEq
where
    L: Into<Identifier>,
    R: Into<Box<dyn Expression>>,
{
    NotEq {
        left: left.into(),
        right: right.into(),
    }
}

/// Creates a greater-than comparison expression (column > value)
#[must_use]
pub fn where_gt<L, R>(left: L, right: R) -> Gt
where
    L: Into<Identifier>,
    R: Into<Box<dyn Expression>>,
{
    Gt {
        left: left.into(),
        right: right.into(),
    }
}

/// Creates a greater-than-or-equal comparison expression (column >= value)
#[must_use]
pub fn where_gte<L, R>(left: L, right: R) -> Gte
where
    L: Into<Identifier>,
    R: Into<Box<dyn Expression>>,
{
    Gte {
        left: left.into(),
        right: right.into(),
    }
}

/// Creates a less-than comparison expression (column < value)
#[must_use]
pub fn where_lt<L, R>(left: L, right: R) -> Lt
where
    L: Into<Identifier>,
    R: Into<Box<dyn Expression>>,
{
    Lt {
        left: left.into(),
        right: right.into(),
    }
}

/// Creates a less-than-or-equal comparison expression (column <= value)
#[must_use]
pub fn where_lte<L, R>(left: L, right: R) -> Lte
where
    L: Into<Identifier>,
    R: Into<Box<dyn Expression>>,
{
    Lte {
        left: left.into(),
        right: right.into(),
    }
}

/// Creates a logical AND expression combining multiple boolean expressions
///
/// All conditions must be true for the AND expression to evaluate to true.
#[must_use]
pub fn where_and(conditions: Vec<Box<dyn BooleanExpression>>) -> And {
    And { conditions }
}

/// Creates a logical OR expression combining multiple boolean expressions
///
/// At least one condition must be true for the OR expression to evaluate to true.
#[must_use]
pub fn where_or(conditions: Vec<Box<dyn BooleanExpression>>) -> Or {
    Or { conditions }
}

/// Creates an INNER JOIN clause with a typed column pair.
///
/// SQL-string predicates are accepted only with the `raw-sql` feature.
///
/// # Examples
///
/// ```
/// use switchy_database::query::{join, qualified_column};
///
/// let join_clause = join("orders", (
///     qualified_column("orders", "user_id"),
///     qualified_column("users", "id"),
/// ));
/// ```
#[must_use]
pub fn join(table_name: &str, on: impl Into<JoinCondition>) -> Join<'_> {
    Join {
        table_name,
        on: on.into(),
        left: false,
    }
}

/// Creates a LEFT JOIN clause with a typed column pair.
///
/// SQL-string predicates are accepted only with the `raw-sql` feature.
///
/// # Examples
///
/// ```
/// use switchy_database::query::{left_join, qualified_column};
///
/// let join_clause = left_join("orders", (
///     qualified_column("orders", "user_id"),
///     qualified_column("users", "id"),
/// ));
/// ```
#[must_use]
pub fn left_join(table_name: &str, on: impl Into<JoinCondition>) -> Join<'_> {
    Join {
        table_name,
        on: on.into(),
        left: true,
    }
}

/// COALESCE SQL function expression returning first non-NULL value
#[derive(Debug)]
pub struct Coalesce {
    /// List of expressions to evaluate in order
    pub values: Vec<Box<dyn Expression>>,
}

impl List for Coalesce {}
impl Expression for Coalesce {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::Coalesce(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let values = self
            .values
            .iter()
            .flat_map(|x| x.values().unwrap_or_default())
            .collect::<Vec<_>>();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// Creates a COALESCE expression that returns the first non-NULL value
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::{coalesce, identifier};
/// use switchy_database::DatabaseValue;
///
/// // Returns first non-NULL value from list
/// let expr = coalesce(vec![
///     Box::new(identifier("email")),
///     Box::new(DatabaseValue::String("unknown@example.com".to_string())),
/// ]);
/// ```
#[must_use]
pub fn coalesce(values: Vec<Box<dyn Expression>>) -> Coalesce {
    Coalesce { values }
}

/// List of expressions for IN clause
#[derive(Debug)]
pub struct InList {
    /// The expressions in the list
    pub values: Vec<Box<dyn Expression>>,
}

impl List for InList {}
impl Expression for InList {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::InList(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let values = self
            .values
            .iter()
            .flat_map(|x| x.values().unwrap_or_default())
            .collect::<Vec<_>>();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// Marker trait for expressions that represent lists of values
///
/// Used for IN and NOT IN clauses to ensure type safety.
pub trait List: Expression {}

impl<T> From<Vec<T>> for Box<dyn List>
where
    T: Into<Box<dyn Expression>> + Send + Sync,
{
    fn from(val: Vec<T>) -> Self {
        Box::new(InList {
            values: val.into_iter().map(std::convert::Into::into).collect(),
        })
    }
}

/// Creates an IN expression (column IN (values...))
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::where_in;
/// use switchy_database::DatabaseValue;
///
/// let filter = where_in("status", vec![
///     DatabaseValue::String("active".to_string()),
///     DatabaseValue::String("pending".to_string()),
/// ]);
/// ```
#[must_use]
pub fn where_in<'a, L, V>(left: L, values: V) -> In<'a>
where
    L: Into<Identifier>,
    V: Into<Box<dyn List + 'a>>,
{
    In {
        left: left.into(),
        values: values.into(),
    }
}

/// Creates a NOT IN expression (column NOT IN (values...))
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::where_not_in;
/// use switchy_database::DatabaseValue;
///
/// let filter = where_not_in("status", vec![
///     DatabaseValue::String("archived".to_string()),
///     DatabaseValue::String("deleted".to_string()),
/// ]);
/// ```
#[must_use]
pub fn where_not_in<'a, L, V>(left: L, values: V) -> NotIn<'a>
where
    L: Into<Identifier>,
    V: Into<Box<dyn List + 'a>>,
{
    NotIn {
        left: left.into(),
        values: values.into(),
    }
}

/// Helper macro to create boxed expression vectors for query builders
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::{boxed, query::{where_eq, where_gt}};
/// use switchy_database::DatabaseValue;
///
/// // Create a vec of boxed expressions
/// let conditions = boxed![
///     where_eq("user_id", DatabaseValue::Int64(123)),
///     where_gt("age", DatabaseValue::Int32(18)),
/// ];
/// ```
#[macro_export]
macro_rules! boxed {
    () => (
        Vec::new()
    );
    ($($x:expr),+ $(,)?) => (
        vec![$(Box::new($x)),+]
    );
}

/// Trait for query types that support WHERE clause filtering
///
/// Provides a fluent API for adding filter conditions to SELECT, UPDATE, and DELETE statements.
#[allow(clippy::module_name_repetitions)]
pub trait FilterableQuery
where
    Self: Sized,
{
    /// Add a strict greater-than predicate over structured expressions.
    #[must_use]
    fn where_gt_expression(
        self,
        left: impl Into<Box<dyn Expression>>,
        right: impl Into<Box<dyn Expression>>,
    ) -> Self {
        self.filter(Box::new(where_gt_expression(left, right)))
    }

    /// Add equality between structured expressions, including qualified columns.
    #[must_use]
    fn where_eq_expression(
        self,
        left: impl Into<Box<dyn Expression>>,
        right: impl Into<Box<dyn Expression>>,
    ) -> Self {
        self.filter(Box::new(where_eq_expression(left, right)))
    }

    /// Add inequality between structured expressions, retaining NULL semantics.
    #[must_use]
    fn where_not_eq_expression(
        self,
        left: impl Into<Box<dyn Expression>>,
        right: impl Into<Box<dyn Expression>>,
    ) -> Self {
        self.filter(Box::new(where_not_eq_expression(left, right)))
    }

    /// Adds multiple filter conditions to the query
    #[must_use]
    fn filters(self, filters: Vec<Box<dyn BooleanExpression>>) -> Self {
        let mut this = self;
        for filter in filters {
            this = this.filter(filter);
        }
        this
    }

    /// Excludes rows matching a bound SQL LIKE pattern.
    #[must_use]
    fn where_not_like(self, column: impl Into<Identifier>, pattern: impl Into<String>) -> Self {
        self.filter(Box::new(where_not_like(column, pattern)))
    }

    /// Adds a single filter condition to the WHERE clause.
    #[must_use]
    fn filter(self, filter: Box<dyn BooleanExpression>) -> Self;

    /// Conditionally adds a filter if the option contains a value
    #[must_use]
    fn filter_if_some<T: BooleanExpression + 'static>(self, filter: Option<T>) -> Self {
        if let Some(filter) = filter {
            self.filter(Box::new(filter))
        } else {
            self
        }
    }

    /// Adds an IN clause filter (column IN (values...))
    #[must_use]
    fn where_in<L, V>(self, left: L, values: V) -> Self
    where
        L: Into<Identifier>,
        V: Into<Box<dyn List>>,
    {
        self.filter(Box::new(where_in(left, values)))
    }

    /// Adds a NOT IN clause filter (column NOT IN (values...))
    #[must_use]
    fn where_not_in<L, V>(self, left: L, values: V) -> Self
    where
        L: Into<Identifier>,
        V: Into<Box<dyn List>>,
    {
        self.filter(Box::new(where_not_in(left, values)))
    }

    /// Adds a logical AND filter combining multiple conditions
    #[must_use]
    fn where_and(self, conditions: Vec<Box<dyn BooleanExpression>>) -> Self {
        self.filter(Box::new(where_and(conditions)))
    }

    /// Adds a logical OR filter combining multiple conditions
    #[must_use]
    fn where_or(self, conditions: Vec<Box<dyn BooleanExpression>>) -> Self {
        self.filter(Box::new(where_or(conditions)))
    }

    /// Adds an equality comparison filter (column = value)
    #[must_use]
    fn where_eq<L, R>(self, left: L, right: R) -> Self
    where
        L: Into<Identifier>,
        R: Into<Box<dyn Expression>>,
    {
        self.filter(Box::new(where_eq(left, right)))
    }

    /// Adds a not-equal comparison filter (column != value)
    #[must_use]
    fn where_not_eq<L, R>(self, left: L, right: R) -> Self
    where
        L: Into<Identifier>,
        R: Into<Box<dyn Expression>>,
    {
        self.filter(Box::new(where_not_eq(left, right)))
    }

    /// Adds a greater-than comparison filter (column > value)
    #[must_use]
    fn where_gt<L, R>(self, left: L, right: R) -> Self
    where
        L: Into<Identifier>,
        R: Into<Box<dyn Expression>>,
    {
        self.filter(Box::new(where_gt(left, right)))
    }

    /// Adds a greater-than-or-equal comparison filter (column >= value)
    #[must_use]
    fn where_gte<L, R>(self, left: L, right: R) -> Self
    where
        L: Into<Identifier>,
        R: Into<Box<dyn Expression>>,
    {
        self.filter(Box::new(where_gte(left, right)))
    }

    /// Adds a less-than comparison filter (column < value)
    #[must_use]
    fn where_lt<L, R>(self, left: L, right: R) -> Self
    where
        L: Into<Identifier>,
        R: Into<Box<dyn Expression>>,
    {
        self.filter(Box::new(where_lt(left, right)))
    }

    /// Adds a less-than-or-equal comparison filter (column <= value)
    #[must_use]
    fn where_lte<L, R>(self, left: L, right: R) -> Self
    where
        L: Into<Identifier>,
        R: Into<Box<dyn Expression>>,
    {
        self.filter(Box::new(where_lte(left, right)))
    }
}

impl<'a> From<SelectQuery<'a>> for Box<dyn List + 'a> {
    fn from(val: SelectQuery<'a>) -> Self {
        Box::new(val)
    }
}

/// A typed SELECT expression with an optional exact, quoted output name.
#[derive(Debug)]
pub struct Projection {
    /// Expression evaluated by the database.
    pub expression: Box<dyn Expression>,
    /// Exact output name, never interpreted as SQL (including with `raw-sql`).
    pub alias: Option<String>,
}

impl Projection {
    /// Construct an unaliased projection.
    #[must_use]
    pub fn new(expression: impl Into<Box<dyn Expression>>) -> Self {
        Self {
            expression: expression.into(),
            alias: None,
        }
    }

    /// Assign an exact output name.
    #[must_use]
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.alias = Some(alias.into());
        self
    }
}

/// SELECT query builder for retrieving data from tables
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct SelectQuery<'a> {
    /// Exact table alias, independently quoted from the table name.
    pub table_alias: Option<&'a str>,
    /// Force an exact SQLite index; unsupported backends reject this option.
    pub indexed_by: Option<&'a str>,
    /// Table to select from
    pub table_name: &'a str,
    /// Whether to return only distinct rows
    pub distinct: bool,
    /// Columns to retrieve (empty means *)
    pub columns: &'a [&'a str],
    /// Typed projections; when nonempty these replace the legacy columns.
    pub projections: Vec<Projection>,
    /// Typed GROUP BY expressions, in SQL order.
    pub groups: Vec<Box<dyn Expression>>,
    /// WHERE clause filters
    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
    /// JOIN clauses
    pub joins: Option<Vec<Join<'a>>>,
    /// ORDER BY clauses
    pub sorts: Option<Vec<Sort>>,
    /// Maximum number of rows to return
    pub limit: Option<usize>,
}

impl List for SelectQuery<'_> {}
impl Expression for SelectQuery<'_> {
    fn expression_type(&self) -> ExpressionType<'_> {
        ExpressionType::SelectQuery(self)
    }

    fn values(&self) -> Option<Vec<&DatabaseValue>> {
        let joins_values = self
            .joins
            .as_ref()
            .map(|x| {
                x.iter()
                    .flat_map(|j| j.values().unwrap_or_default())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        let filters_values = self
            .filters
            .as_ref()
            .map(|x| {
                x.iter()
                    .flat_map(|j| j.values().unwrap_or_default())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        let sorts_values = self
            .sorts
            .as_ref()
            .map(|x| {
                x.iter()
                    .flat_map(|j| j.values().unwrap_or_default())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        let projections_values = self
            .projections
            .iter()
            .flat_map(|p| p.expression.values().unwrap_or_default())
            .collect::<Vec<_>>();
        let groups_values = self
            .groups
            .iter()
            .flat_map(|p| p.values().unwrap_or_default())
            .collect::<Vec<_>>();
        let values: Vec<_> = [
            projections_values,
            joins_values,
            filters_values,
            groups_values,
            sorts_values,
        ]
        .concat();

        if values.is_empty() {
            None
        } else {
            Some(values)
        }
    }
}

/// Creates a SELECT query builder for the specified table
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::select;
///
/// let query = select("users")
///     .columns(&["id", "name"])
///     .execute(db)
///     .await?;
/// ```
#[must_use]
pub fn select(table_name: &str) -> SelectQuery<'_> {
    SelectQuery {
        table_alias: None,
        indexed_by: None,
        table_name,
        distinct: false,
        columns: &["*"],
        projections: Vec::new(),
        groups: Vec::new(),
        filters: None,
        joins: None,
        sorts: None,
        limit: None,
    }
}

impl FilterableQuery for SelectQuery<'_> {
    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
        if let Some(filters) = &mut self.filters {
            filters.push(filter);
        } else {
            self.filters.replace(vec![filter]);
        }
        self
    }
}

impl<'a> SelectQuery<'a> {
    /// Alias the selected table using an exact identifier, never a SQL fragment.
    #[must_use]
    pub const fn table_alias(mut self, alias: &'a str) -> Self {
        self.table_alias = Some(alias);
        self
    }

    #[cfg(any(
        feature = "sqlite-rusqlite",
        feature = "sqlite-sqlx",
        feature = "postgres-raw",
        feature = "postgres-sqlx",
        feature = "mysql-sqlx",
        feature = "duckdb",
        feature = "turso"
    ))]
    pub(crate) fn render_table(&self, delimiter: char) -> String {
        let table = render_identifier(self.table_name, delimiter);
        self.table_alias.map_or_else(
            || table.clone(),
            |alias| {
                format!(
                    "{table} AS {delimiter}{}{delimiter}",
                    alias.replace(delimiter, &format!("{delimiter}{delimiter}"))
                )
            },
        )
    }
    /// Require the SQLite planner to use this exact index.
    #[must_use]
    pub const fn indexed_by(mut self, index: &'a str) -> Self {
        self.indexed_by = Some(index);
        self
    }
    /// Replace the legacy column list with typed projections.
    #[must_use]
    pub fn projections(mut self, projections: Vec<Projection>) -> Self {
        self.projections = projections;
        self
    }

    /// Append a typed SELECT expression.
    #[must_use]
    pub fn project(mut self, expression: impl Into<Box<dyn Expression>>) -> Self {
        self.projections.push(Projection::new(expression));
        self
    }

    /// Append a typed expression with an exact, quoted output name.
    ///
    /// ```
    /// use switchy_database::query::{select, identifier, count_all, byte_length};
    /// let inventory = select("events")
    ///     .project(identifier("kind"))
    ///     .project_as(count_all(), "event_count")
    ///     .group_by(identifier("kind"));
    /// let lengths = select("events")
    ///     .project_as(byte_length(identifier("payload")), "payload_bytes");
    /// ```
    #[must_use]
    pub fn project_as(
        mut self,
        expression: impl Into<Box<dyn Expression>>,
        alias: impl Into<String>,
    ) -> Self {
        self.projections
            .push(Projection::new(expression).alias(alias));
        self
    }

    /// Append a typed GROUP BY expression.
    #[must_use]
    pub fn group_by(mut self, expression: impl Into<Box<dyn Expression>>) -> Self {
        self.groups.push(expression.into());
        self
    }

    /// Adds DISTINCT modifier to return only unique rows
    #[must_use]
    pub const fn distinct(mut self) -> Self {
        self.distinct = true;
        self
    }

    /// Specifies which columns to retrieve (default is all columns)
    #[must_use]
    pub const fn columns(mut self, columns: &'a [&'a str]) -> Self {
        self.columns = columns;
        self
    }

    /// Adds multiple JOIN clauses to the query
    #[must_use]
    pub fn joins(mut self, joins: Vec<Join<'a>>) -> Self {
        for join in joins {
            if let Some(joins) = &mut self.joins {
                joins.push(join);
            } else {
                self.joins.replace(vec![join]);
            }
        }
        self
    }

    /// Adds an INNER JOIN with a typed column pair or a `JoinCondition`.
    ///
    /// SQL-string predicates require the `raw-sql` feature.
    #[must_use]
    pub fn join(mut self, table_name: &'a str, on: impl Into<JoinCondition>) -> Self {
        if let Some(joins) = &mut self.joins {
            joins.push(join(table_name, on));
        } else {
            self.joins.replace(vec![join(table_name, on)]);
        }
        self
    }

    /// Adds multiple LEFT JOIN clauses to the query
    #[must_use]
    pub fn left_joins(mut self, left_joins: Vec<Join<'a>>) -> Self {
        for left_join in left_joins {
            if let Some(left_joins) = &mut self.joins {
                left_joins.push(left_join);
            } else {
                self.joins.replace(vec![left_join]);
            }
        }
        self
    }

    /// Adds a LEFT JOIN with a typed column pair or a `JoinCondition`.
    ///
    /// SQL-string predicates require the `raw-sql` feature.
    #[must_use]
    pub fn left_join(mut self, table_name: &'a str, on: impl Into<JoinCondition>) -> Self {
        if let Some(left_joins) = &mut self.joins {
            left_joins.push(left_join(table_name, on));
        } else {
            self.joins.replace(vec![left_join(table_name, on)]);
        }
        self
    }

    /// Adds multiple ORDER BY clauses to the query
    #[must_use]
    pub fn sorts(mut self, sorts: Vec<Sort>) -> Self {
        for sort in sorts {
            if let Some(sorts) = &mut self.sorts {
                sorts.push(sort);
            } else {
                self.sorts.replace(vec![sort]);
            }
        }
        self
    }

    /// Adds a single ORDER BY clause
    #[must_use]
    pub fn sort<T>(mut self, expression: T, direction: SortDirection) -> Self
    where
        T: Into<Identifier>,
    {
        if let Some(sorts) = &mut self.sorts {
            sorts.push(sort(expression.into(), direction));
        } else {
            self.sorts.replace(vec![sort(expression.into(), direction)]);
        }
        self
    }

    /// Limits the number of rows returned
    #[must_use]
    pub const fn limit(mut self, limit: usize) -> Self {
        self.limit.replace(limit);
        self
    }

    /// # Errors
    ///
    /// Will return `Err` if the select query execution failed.
    pub async fn execute(self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
        db.query(&self).await
    }

    /// # Errors
    ///
    /// Will return `Err` if the select query execution failed.
    pub async fn execute_first(self, db: &dyn Database) -> Result<Option<Row>, DatabaseError> {
        let this = if self.limit.is_none() {
            self.limit(1)
        } else {
            self
        };

        db.query_first(&this).await
    }
}

/// UPSERT statement for inserting multiple rows or updating on conflict
pub struct UpsertMultiStatement<'a> {
    /// Table to upsert into
    pub table_name: &'a str,
    /// Multiple rows of column-value pairs to insert/update
    pub values: Vec<Vec<(&'a str, Box<dyn Expression>)>>,
    /// Columns that form the unique constraint to detect conflicts
    pub unique: Option<Vec<Box<dyn Expression>>>,
}

/// Creates a new multi-row UPSERT statement builder
///
/// Constructs an UPSERT statement that can insert or update multiple rows in a single operation.
#[must_use]
pub fn upsert_multi(table_name: &str) -> UpsertMultiStatement<'_> {
    UpsertMultiStatement {
        table_name,
        values: vec![],
        unique: None,
    }
}

impl<'a> UpsertMultiStatement<'a> {
    /// Sets the values to upsert as multiple rows
    ///
    /// Each inner vector represents one row with column-value pairs.
    pub fn values<T: Into<Box<dyn Expression>>>(
        &mut self,
        values: Vec<Vec<(&'a str, T)>>,
    ) -> &mut Self {
        self.values.extend(values.into_iter().map(|values| {
            values
                .into_iter()
                .map(|(key, value)| (key, value.into()))
                .collect()
        }));
        self
    }

    /// Sets the unique columns that identify conflicts
    ///
    /// These columns determine when to update instead of insert.
    pub fn unique(&mut self, unique: Vec<Box<dyn Expression>>) -> &mut Self {
        self.unique.replace(unique);
        self
    }

    /// # Errors
    ///
    /// Will return `Err` if the upsert multi execution failed.
    pub async fn execute(&self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
        db.exec_upsert_multi(self).await
    }
}

/// INSERT statement for adding new rows to a table
pub struct InsertStatement<'a> {
    /// Table to insert into
    pub table_name: &'a str,
    /// Column-value pairs to insert
    pub values: Vec<(&'a str, Box<dyn Expression>)>,
}

/// Creates a new INSERT statement builder
///
/// Constructs an INSERT statement for adding rows to the specified table.
#[must_use]
pub fn insert(table_name: &str) -> InsertStatement<'_> {
    InsertStatement {
        table_name,
        values: vec![],
    }
}

/// INSERT with an exact conflict target and atomic affected-row count.
pub struct InsertConflictStatement<'a> {
    /// Structured insert.
    pub insert: InsertStatement<'a>,
    /// Exact unique columns whose conflict alone is ignored.
    pub columns: Vec<String>,
    /// SQLite OR IGNORE semantics, distinct from targeted conflict handling.
    pub or_ignore: bool,
}
impl InsertConflictStatement<'_> {
    /// Execute atomically, returning zero for an ignored conflict and one for insertion.
    ///
    /// # Errors
    /// * Returns unsupported, invalid conflict-target, or unrelated constraint failures.
    pub async fn execute_count(&self, db: &dyn Database) -> Result<u64, DatabaseError> {
        db.exec_insert_conflict_count(self).await
    }
}

impl<'a> InsertStatement<'a> {
    /// Ignore only a conflict on the exact listed unique columns.
    #[must_use]
    pub fn on_conflict_do_nothing(
        self,
        columns: impl IntoIterator<Item = impl Into<String>>,
    ) -> InsertConflictStatement<'a> {
        InsertConflictStatement {
            insert: self,
            columns: columns.into_iter().map(Into::into).collect(),
            or_ignore: false,
        }
    }
    /// Use SQLite OR IGNORE for UNIQUE, primary-key, NOT NULL and CHECK conflicts.
    /// Foreign-key failures are not suppressed.
    #[must_use]
    pub const fn or_ignore(self) -> InsertConflictStatement<'a> {
        InsertConflictStatement {
            insert: self,
            columns: Vec::new(),
            or_ignore: true,
        }
    }
    /// Sets multiple column-value pairs at once
    #[must_use]
    pub fn values<T: Into<Box<dyn Expression>>>(mut self, values: Vec<(&'a str, T)>) -> Self {
        for value in values {
            self.values.push((value.0, value.1.into()));
        }
        self
    }

    /// Adds a single column-value pair to the insert
    #[must_use]
    pub fn value<T: Into<Box<dyn Expression>>>(mut self, name: &'a str, value: T) -> Self {
        self.values.push((name, value.into()));
        self
    }

    /// # Errors
    ///
    /// Will return `Err` if the insert execution failed.
    pub async fn execute(&self, db: &dyn Database) -> Result<Row, DatabaseError> {
        db.exec_insert(self).await
    }
}

/// UPDATE statement for modifying existing rows in a table
pub struct UpdateStatement<'a> {
    /// Table to update
    pub table_name: &'a str,
    /// Column-value pairs to set
    pub values: Vec<(&'a str, Box<dyn Expression>)>,
    /// WHERE clause filters
    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
    /// Unique columns for conflict resolution
    pub unique: Option<&'a [&'a str]>,
    /// Maximum number of rows to update
    pub limit: Option<usize>,
}

/// Creates a new UPDATE statement builder
///
/// Constructs an UPDATE statement for modifying existing rows in the specified table.
#[must_use]
pub fn update(table_name: &str) -> UpdateStatement<'_> {
    UpdateStatement {
        table_name,
        values: vec![],
        filters: None,
        unique: None,
        limit: None,
    }
}

impl FilterableQuery for UpdateStatement<'_> {
    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
        if let Some(filters) = &mut self.filters {
            filters.push(filter);
        } else {
            self.filters.replace(vec![filter]);
        }
        self
    }
}

impl<'a> UpdateStatement<'a> {
    /// Sets multiple column-value pairs to update
    #[must_use]
    pub fn values<T: Into<Box<dyn Expression>>>(mut self, values: Vec<(&'a str, T)>) -> Self {
        for value in values {
            self.values.push((value.0, value.1.into()));
        }
        self
    }

    /// Sets a single column to a new value
    #[must_use]
    pub fn value<T: Into<Box<dyn Expression>>>(mut self, name: &'a str, value: T) -> Self {
        self.values.push((name, value.into()));
        self
    }

    /// Specifies unique columns for conflict resolution
    #[must_use]
    pub const fn unique(mut self, unique: &'a [&'a str]) -> Self {
        self.unique.replace(unique);
        self
    }

    /// Limits the number of rows to update
    #[must_use]
    pub const fn limit(mut self, limit: usize) -> Self {
        self.limit.replace(limit);
        self
    }

    /// # Errors
    ///
    /// Will return `Err` if the update execution failed.
    pub async fn execute(&self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
        db.exec_update(self).await
    }

    /// # Errors
    ///
    /// Will return `Err` if the update execution failed.
    pub async fn execute_first(&self, db: &dyn Database) -> Result<Option<Row>, DatabaseError> {
        db.exec_update_first(self).await
    }
}

/// UPSERT statement for inserting or updating a row on conflict
pub struct UpsertStatement<'a> {
    /// Table to upsert into
    pub table_name: &'a str,
    /// Column-value pairs to insert/update
    pub values: Vec<(&'a str, Box<dyn Expression>)>,
    /// WHERE clause filters for conditional upsert
    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
    /// Columns that form the unique constraint to detect conflicts
    pub unique: Option<&'a [&'a str]>,
    /// Maximum number of rows to upsert
    pub limit: Option<usize>,
}

/// Creates a new UPSERT statement builder
///
/// Constructs an UPSERT statement for inserting or updating rows on conflict.
#[must_use]
pub fn upsert(table_name: &str) -> UpsertStatement<'_> {
    UpsertStatement {
        table_name,
        values: vec![],
        filters: None,
        unique: None,
        limit: None,
    }
}

impl FilterableQuery for UpsertStatement<'_> {
    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
        if let Some(filters) = &mut self.filters {
            filters.push(filter);
        } else {
            self.filters.replace(vec![filter]);
        }
        self
    }
}

impl<'a> UpsertStatement<'a> {
    /// Sets multiple column-value pairs to upsert
    #[must_use]
    pub fn values<T: Into<Box<dyn Expression>>>(mut self, values: Vec<(&'a str, T)>) -> Self {
        for value in values {
            self.values.push((value.0, value.1.into()));
        }
        self
    }

    /// Sets a single column-value pair to upsert
    #[must_use]
    pub fn value<T: Into<Box<dyn Expression>>>(mut self, name: &'a str, value: T) -> Self {
        self.values.push((name, value.into()));
        self
    }

    /// Sets a column-value pair only if the value is `Some`
    ///
    /// This is useful for conditional updates where a value should only be set if present.
    #[must_use]
    pub fn value_opt<T: Into<Box<dyn Expression>>>(
        mut self,
        name: &'a str,
        value: Option<T>,
    ) -> Self {
        if let Some(value) = value {
            self.values.push((name, value.into()));
        }
        self
    }

    /// Specifies unique columns that identify conflicts
    ///
    /// These columns determine when to update instead of insert.
    #[must_use]
    pub const fn unique(mut self, unique: &'a [&'a str]) -> Self {
        self.unique.replace(unique);
        self
    }

    /// Limits the number of rows affected by the upsert
    #[must_use]
    pub const fn limit(mut self, limit: usize) -> Self {
        self.limit.replace(limit);
        self
    }

    /// # Errors
    ///
    /// Will return `Err` if the upsert execution failed.
    pub async fn execute(self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
        if self.values.is_empty() {
            return db.query(&self.into()).await;
        }
        db.exec_upsert(&self).await
    }

    /// # Errors
    ///
    /// Will return `Err` if the upsert execution failed.
    pub async fn execute_first(self, db: &dyn Database) -> Result<Row, DatabaseError> {
        if self.values.is_empty() {
            return db
                .query_first(&self.into())
                .await?
                .ok_or(DatabaseError::NoRow);
        }
        db.exec_upsert_first(&self).await
    }
}

impl<'a> From<UpsertStatement<'a>> for SelectQuery<'a> {
    fn from(value: UpsertStatement<'a>) -> Self {
        Self {
            table_alias: None,
            indexed_by: None,
            table_name: value.table_name,
            distinct: false,
            columns: &["*"],
            projections: Vec::new(),
            groups: Vec::new(),
            filters: value.filters,
            joins: None,
            sorts: None,
            limit: value.limit,
        }
    }
}

/// DELETE statement for removing rows from a table
pub struct DeleteStatement<'a> {
    /// Table to delete from
    pub table_name: &'a str,
    /// WHERE clause filters
    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
    /// Maximum number of rows to delete
    pub limit: Option<usize>,
}

/// Creates a new DELETE statement builder
///
/// Constructs a DELETE statement for removing rows from the specified table.
#[must_use]
pub fn delete(table_name: &str) -> DeleteStatement<'_> {
    DeleteStatement {
        table_name,
        filters: None,
        limit: None,
    }
}

impl FilterableQuery for DeleteStatement<'_> {
    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
        if let Some(filters) = &mut self.filters {
            filters.push(filter);
        } else {
            self.filters.replace(vec![filter]);
        }
        self
    }
}

impl DeleteStatement<'_> {
    /// Limits the number of rows to delete
    #[must_use]
    pub const fn limit(mut self, limit: usize) -> Self {
        self.limit.replace(limit);
        self
    }

    /// # Errors
    ///
    /// Will return `Err` if the delete execution failed.
    pub async fn execute(&self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
        db.exec_delete(self).await
    }

    /// # Errors
    ///
    /// Will return `Err` if the delete execution failed.
    pub async fn execute_first(&self, db: &dyn Database) -> Result<Option<Row>, DatabaseError> {
        db.exec_delete_first(self).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DatabaseValue, sql_interval::SqlInterval};

    mod expression_params_tests {
        use super::*;

        #[test_log::test]
        fn test_params_filters_null_values() {
            let val = DatabaseValue::Null;
            let params = val.params();
            assert!(params.is_some());
            assert_eq!(params.unwrap(), [] as [&DatabaseValue; 0]);
        }

        #[test_log::test]
        fn test_params_filters_now() {
            let val = DatabaseValue::Now;
            let params = val.params();
            assert!(params.is_some());
            assert_eq!(params.unwrap(), [] as [&DatabaseValue; 0]);
        }

        #[test_log::test]
        fn test_params_filters_now_plus() {
            let val = DatabaseValue::NowPlus(SqlInterval::from_days(1));
            let params = val.params();
            assert!(params.is_some());
            assert_eq!(params.unwrap(), [] as [&DatabaseValue; 0]);
        }

        #[test_log::test]
        fn test_params_includes_regular_values() {
            let val = DatabaseValue::Int64(42);
            let params = val.params();
            assert!(params.is_some());
            let params = params.unwrap();
            assert_eq!(params.len(), 1);
            assert_eq!(params[0], &DatabaseValue::Int64(42));
        }

        #[test_log::test]
        fn test_params_includes_string_values() {
            let val = DatabaseValue::String("test".to_string());
            let params = val.params();
            assert!(params.is_some());
            let params = params.unwrap();
            assert_eq!(params.len(), 1);
        }
    }

    mod and_expression_tests {
        use super::*;

        #[test_log::test]
        fn test_and_with_no_conditions_returns_none() {
            let and_expr = And { conditions: vec![] };
            assert!(and_expr.values().is_none());
        }

        #[test_log::test]
        fn test_and_collects_values_from_conditions() {
            let eq1 = where_eq("col1", DatabaseValue::Int64(1));
            let eq2 = where_eq("col2", DatabaseValue::String("test".to_string()));

            let and_expr = where_and(vec![Box::new(eq1), Box::new(eq2)]);
            let values = and_expr.values();
            assert!(values.is_some());
            let values = values.unwrap();
            assert_eq!(values.len(), 2);
        }

        #[test_log::test]
        fn test_and_params_filters_non_bindable() {
            let eq1 = where_eq("col1", DatabaseValue::Now);
            let eq2 = where_eq("col2", DatabaseValue::Int64(42));

            let and_expr = where_and(vec![Box::new(eq1), Box::new(eq2)]);
            let params = and_expr.params();
            assert!(params.is_some());
            let params = params.unwrap();
            // NOW() should be filtered out
            assert_eq!(params.len(), 1);
            assert_eq!(params[0], &DatabaseValue::Int64(42));
        }
    }

    mod or_expression_tests {
        use super::*;

        #[test_log::test]
        fn test_or_with_no_conditions_returns_none() {
            let or_expr = Or { conditions: vec![] };
            assert!(or_expr.values().is_none());
        }

        #[test_log::test]
        fn test_or_collects_values_from_conditions() {
            let eq1 = where_eq("status", DatabaseValue::String("active".to_string()));
            let eq2 = where_eq("status", DatabaseValue::String("pending".to_string()));

            let or_expr = where_or(vec![Box::new(eq1), Box::new(eq2)]);
            let values = or_expr.values();
            assert!(values.is_some());
            let values = values.unwrap();
            assert_eq!(values.len(), 2);
        }
    }

    mod in_expression_tests {
        use super::*;

        #[test_log::test]
        fn test_in_values_collection() {
            let in_expr = where_in(
                "id",
                vec![
                    DatabaseValue::Int64(1),
                    DatabaseValue::Int64(2),
                    DatabaseValue::Int64(3),
                ],
            );
            let values = in_expr.values();
            assert!(values.is_some());
            let values = values.unwrap();
            assert_eq!(values.len(), 3);
        }

        #[test_log::test]
        fn test_not_in_values_collection() {
            let not_in = where_not_in(
                "status",
                vec![
                    DatabaseValue::String("deleted".to_string()),
                    DatabaseValue::String("archived".to_string()),
                ],
            );
            let values = not_in.values();
            assert!(values.is_some());
            let values = values.unwrap();
            assert_eq!(values.len(), 2);
        }
    }

    mod coalesce_tests {
        use super::*;

        #[test_log::test]
        fn test_coalesce_empty_returns_none() {
            let coal = coalesce(vec![]);
            assert!(coal.values().is_none());
        }

        #[test_log::test]
        fn test_coalesce_collects_values() {
            let coal = coalesce(vec![
                Box::new(DatabaseValue::StringOpt(None)),
                Box::new(DatabaseValue::String("default".to_string())),
            ]);
            let values = coal.values();
            assert!(values.is_some());
            let values = values.unwrap();
            assert_eq!(values.len(), 2);
        }
    }

    mod inlist_tests {
        use super::*;

        #[test_log::test]
        fn test_inlist_empty_returns_none() {
            let list = InList { values: vec![] };
            assert!(list.values().is_none());
        }

        #[test_log::test]
        fn test_inlist_collects_values() {
            let list = InList {
                values: vec![
                    Box::new(DatabaseValue::Int64(1)),
                    Box::new(DatabaseValue::Int64(2)),
                ],
            };
            let values = list.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 2);
        }
    }

    mod comparison_expression_tests {
        use super::*;

        #[test_log::test]
        fn test_eq_values() {
            let eq = where_eq("col", DatabaseValue::Int64(42));
            let values = eq.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_not_eq_values() {
            let neq = where_not_eq("col", DatabaseValue::String("test".to_string()));
            let values = neq.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_gt_values() {
            let gt = where_gt("age", DatabaseValue::Int32(18));
            let values = gt.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_gte_values() {
            let gte = where_gte("score", DatabaseValue::Int32(100));
            let values = gte.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_lt_values() {
            let lt = where_lt("quantity", DatabaseValue::Int32(10));
            let values = lt.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_lte_values() {
            let lte = where_lte("price", DatabaseValue::Real64(99.99));
            let values = lte.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }
    }

    mod select_query_tests {
        use super::*;

        #[test_log::test]
        fn test_select_query_no_filters_returns_none() {
            let query = select("users");
            assert!(query.values().is_none());
        }

        #[test_log::test]
        fn test_select_query_with_filter_values() {
            let query = select("users").where_eq("id", DatabaseValue::Int64(1));
            let values = query.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_select_query_with_multiple_filters() {
            let query = select("users")
                .where_eq("active", DatabaseValue::Bool(true))
                .where_gt("age", DatabaseValue::Int32(18));
            let values = query.values();
            assert!(values.is_some());
            assert_eq!(values.unwrap().len(), 2);
        }
    }

    #[cfg(feature = "raw-sql")]
    mod literal_tests {
        use super::*;

        #[test_log::test]
        fn test_literal_from_str() {
            let lit: Literal = "COUNT(*)".into();
            assert_eq!(lit.value, "COUNT(*)");
        }

        #[test_log::test]
        fn test_literal_from_string() {
            let lit: Literal = String::from("SUM(amount)").into();
            assert_eq!(lit.value, "SUM(amount)");
        }

        #[test_log::test]
        fn test_literal_function() {
            let lit = literal("NOW()");
            assert_eq!(lit.value, "NOW()");
        }
    }

    #[cfg(all(test, feature = "sqlite-rusqlite"))]
    mod qualified_column_tests {
        use super::*;

        #[test]
        fn qualification_quotes_each_exact_component() {
            let column = qualified_column("a.b\"c", "d.e\"f");
            assert_eq!(column.render('"'), "\"a.b\"\"c\".\"d.e\"\"f\"");
            let column = qualified_column("a.b`c", "d.e`f");
            assert_eq!(column.render('`'), "`a.b``c`.`d.e``f`");
        }
    }

    mod identifier_tests {
        use super::*;

        #[test_log::test]
        fn test_identifier_from_str() {
            let id: Identifier = "user_id".into();
            assert_eq!(id.value, "user_id");
        }

        #[test_log::test]
        fn test_identifier_from_string() {
            let id: Identifier = String::from("column_name").into();
            assert_eq!(id.value, "column_name");
        }

        #[test_log::test]
        fn test_identifier_function() {
            let id = identifier("table.column");
            assert_eq!(id.value, "table.column");
        }
    }

    mod typed_join_tests {
        use super::*;

        #[test_log::test]
        fn typed_join_helpers_and_chaining() {
            let condition = || {
                (
                    qualified_column("orders", "user_id"),
                    qualified_column("users", "id"),
                )
            };
            let inner = join("users", condition());
            let left = left_join("users", condition());
            assert!(!inner.left);
            assert!(left.left);
            assert!(matches!(inner.on, JoinCondition::ColumnsEqual(..)));
            assert!(matches!(left.on, JoinCondition::ColumnsEqual(..)));

            let query = select("orders")
                .join("users", condition())
                .left_join("addresses", JoinCondition::from(condition()))
                .join("more", condition());
            let joins = query.joins.unwrap();
            assert_eq!(joins.len(), 3);
            assert_eq!(joins[0].table_name, "users");
            assert!(!joins[0].left);
            assert_eq!(joins[1].table_name, "addresses");
            assert!(joins[1].left);
            assert_eq!(joins[2].table_name, "more");
            assert!(!joins[2].left);
            assert!(
                joins
                    .iter()
                    .all(|join| matches!(join.on, JoinCondition::ColumnsEqual(..)))
            );
        }
    }

    #[cfg(feature = "raw-sql")]
    mod join_tests {
        use super::*;

        #[test_log::test]
        fn test_inner_join_creation() {
            let j = join("orders", "orders.user_id = users.id");
            assert_eq!(j.table_name, "orders");
            assert!(matches!(&j.on, JoinCondition::Raw(sql) if sql == "orders.user_id = users.id"));
            assert!(!j.left);
        }

        #[test_log::test]
        fn test_left_join_creation() {
            let j = left_join("addresses", "users.address_id = addresses.id");
            assert_eq!(j.table_name, "addresses");
            assert!(j.left);
        }
    }

    mod sort_tests {
        use super::*;

        #[test_log::test]
        fn test_sort_ascending() {
            let s = sort(identifier("name"), SortDirection::Asc);
            assert!(matches!(s.direction, SortDirection::Asc));
        }

        #[test_log::test]
        fn test_sort_descending() {
            let s = sort(identifier("created_at"), SortDirection::Desc);
            assert!(matches!(s.direction, SortDirection::Desc));
        }
    }

    mod boxed_macro_tests {
        use super::*;

        #[test_log::test]
        fn test_boxed_empty() {
            let v: Vec<Box<dyn BooleanExpression>> = boxed![];
            assert!(v.is_empty());
        }

        #[test_log::test]
        fn test_boxed_single() {
            let v: Vec<Box<dyn BooleanExpression>> =
                boxed![where_eq("id", DatabaseValue::Int64(1))];
            assert_eq!(v.len(), 1);
        }

        #[test_log::test]
        fn test_boxed_multiple() {
            let v: Vec<Box<dyn BooleanExpression>> = boxed![
                where_eq("id", DatabaseValue::Int64(1)),
                where_gt("age", DatabaseValue::Int32(18)),
            ];
            assert_eq!(v.len(), 2);
        }
    }

    mod filterable_query_tests {
        use super::*;

        #[test_log::test]
        fn test_filter_if_some_with_value() {
            let query =
                select("users").filter_if_some(Some(where_eq("id", DatabaseValue::Int64(1))));
            assert!(query.filters.is_some());
            assert_eq!(query.filters.unwrap().len(), 1);
        }

        #[test_log::test]
        fn test_filter_if_some_with_none() {
            let query = select("users").filter_if_some::<Eq>(None);
            assert!(query.filters.is_none());
        }

        #[test_log::test]
        fn test_filters_adds_multiple() {
            let conditions: Vec<Box<dyn BooleanExpression>> = vec![
                Box::new(where_eq("a", DatabaseValue::Int64(1))),
                Box::new(where_eq("b", DatabaseValue::Int64(2))),
            ];
            let query = select("table").filters(conditions);
            assert!(query.filters.is_some());
            assert_eq!(query.filters.unwrap().len(), 2);
        }
    }
}