switchy_database 0.3.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
//! 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", "orders.user_id = users.id")  // INNER JOIN
//!     .left_join("addresses", "users.address_id = addresses.id")  // LEFT JOIN
//!     .execute(db)
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::fmt::Debug;

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

/// 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)
    }
}

/// 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,
    /// JOIN condition (e.g., "users.id = `orders.user_id`")
    pub on: &'a str,
    /// Whether this is a LEFT JOIN (true) or INNER JOIN (false)
    pub left: bool,
}

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> {
    /// 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),
    /// IN list expression (with explicit list of values)
    InList(&'a InList),
    /// Raw SQL literal expression
    Literal(&'a Literal),
    /// COALESCE function expression
    Coalesce(&'a Coalesce),
    /// 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.
#[derive(Debug)]
pub struct Literal {
    /// The raw SQL expression text
    pub value: String,
}

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

impl From<&String> for Literal {
    fn from(val: &String) -> Self {
        Self { value: val.clone() }
    }
}

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

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

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]
pub fn literal(value: &str) -> Literal {
    Literal {
        value: value.to_string(),
    }
}

/// 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
#[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)
        }
    }
}

/// 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
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::join;
///
/// let join_clause = join("orders", "orders.user_id = users.id");
/// ```
#[must_use]
pub const fn join<'a>(table_name: &'a str, on: &'a str) -> Join<'a> {
    Join {
        table_name,
        on,
        left: false,
    }
}

/// Creates a LEFT JOIN clause
///
/// # Examples
///
/// ```rust,ignore
/// use switchy_database::query::left_join;
///
/// let join_clause = left_join("orders", "orders.user_id = users.id");
/// ```
#[must_use]
pub const fn left_join<'a>(table_name: &'a str, on: &'a str) -> Join<'a> {
    Join {
        table_name,
        on,
        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,
{
    /// 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
    }

    /// 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)
    }
}

/// SELECT query builder for retrieving data from tables
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct SelectQuery<'a> {
    /// 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],
    /// 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 values: Vec<_> = [joins_values, filters_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_name,
        distinct: false,
        columns: &["*"],
        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> {
    /// 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 clause
    #[must_use]
    pub fn join(mut self, table_name: &'a str, on: &'a str) -> 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 clause
    #[must_use]
    pub fn left_join(mut self, table_name: &'a str, on: &'a str) -> 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![],
    }
}

impl<'a> InsertStatement<'a> {
    /// 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_name: value.table_name,
            distinct: false,
            columns: &["*"],
            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!(params.unwrap().is_empty());
        }

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

        #[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!(params.unwrap().is_empty());
        }

        #[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);
        }
    }

    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()");
        }
    }

    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 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_eq!(j.on, "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);
        }
    }
}