prax-query 0.11.0

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

use std::marker::PhantomData;

use crate::error::QueryResult;
use crate::filter::{Filter, FilterValue};
use crate::inputs::WriteOp;
use crate::nested::NestedWriteOp;
use crate::traits::{Model, ModelWithPk, QueryEngine};
use crate::types::Select;

/// An upsert (insert or update) operation.
///
/// # Example
///
/// ```rust,ignore
/// let user = client
///     .user()
///     .upsert()
///     .r#where(user::email::equals("test@example.com"))
///     .create(user::Create { email: "test@example.com".into(), name: Some("Test".into()) })
///     .update(user::Update { name: Some("Updated".into()), ..Default::default() })
///     .exec()
///     .await?;
/// ```
pub struct UpsertOperation<E: QueryEngine, M: Model> {
    engine: E,
    filter: Filter,
    create_columns: Vec<String>,
    create_values: Vec<FilterValue>,
    update_columns: Vec<String>,
    update_values: Vec<FilterValue>,
    /// Update-path entries pushed via [`Self::with_update_input`] or
    /// [`Self::update_set_op`]. When non-empty these take precedence
    /// over `update_columns`/`update_values` because they carry atomic
    /// operators (`Increment`/`Decrement`/`Unset`) the flat
    /// column/value pair can't express.
    update_ops: Vec<(String, WriteOp)>,
    conflict_columns: Vec<String>,
    select: Select,
    /// Nested-write ops to run when the *create* branch fires (the
    /// row didn't previously exist). Empty on the fast path.
    create_nested: Vec<NestedWriteOp>,
    /// Nested-write ops to run when the *update* branch fires (the
    /// row already existed). Empty on the fast path.
    update_nested: Vec<NestedWriteOp>,
    _model: PhantomData<M>,
}

impl<E: QueryEngine, M: Model + crate::row::FromRow> UpsertOperation<E, M> {
    /// Create a new Upsert operation.
    pub fn new(engine: E) -> Self {
        Self {
            engine,
            filter: Filter::None,
            create_columns: Vec::new(),
            create_values: Vec::new(),
            update_columns: Vec::new(),
            update_values: Vec::new(),
            update_ops: Vec::new(),
            conflict_columns: Vec::new(),
            select: Select::All,
            create_nested: Vec::new(),
            update_nested: Vec::new(),
            _model: PhantomData,
        }
    }

    /// Add a filter condition (identifies the record to upsert).
    ///
    /// On the single-statement fast path the filter doubles as the
    /// conflict target: when [`Self::on_conflict`] was not called, a
    /// simple equality filter (`col = value`, or an AND of equalities
    /// for composite keys) supplies the `ON CONFLICT (col)` columns.
    /// Explicit [`Self::on_conflict`] columns take precedence when both
    /// are set. A filter of any other shape cannot name a conflict
    /// target and is rejected by [`Self::exec`] with an
    /// `invalid_input` error unless [`Self::on_conflict`] is used. On
    /// the nested-write slow path the filter is instead used directly
    /// as the update branch's WHERE clause.
    pub fn r#where(mut self, filter: impl Into<Filter>) -> Self {
        self.filter = filter.into();
        self
    }

    /// Set the columns to check for conflict.
    ///
    /// Takes precedence over the conflict target derived from the
    /// [`Self::r#where`] filter when both are set.
    pub fn on_conflict(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.conflict_columns = columns.into_iter().map(Into::into).collect();
        self
    }

    /// Set the create data.
    pub fn create(
        mut self,
        values: impl IntoIterator<Item = (impl Into<String>, impl Into<FilterValue>)>,
    ) -> Self {
        for (col, val) in values {
            self.create_columns.push(col.into());
            self.create_values.push(val.into());
        }
        self
    }

    /// Set a single create column.
    pub fn create_set(mut self, column: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        self.create_columns.push(column.into());
        self.create_values.push(value.into());
        self
    }

    /// Set the update data.
    pub fn update(
        mut self,
        values: impl IntoIterator<Item = (impl Into<String>, impl Into<FilterValue>)>,
    ) -> Self {
        for (col, val) in values {
            self.update_columns.push(col.into());
            self.update_values.push(val.into());
        }
        self
    }

    /// Set a single update column.
    pub fn update_set(mut self, column: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        self.update_columns.push(column.into());
        self.update_values.push(value.into());
        self
    }

    /// Select specific fields to return.
    pub fn select(mut self, select: impl Into<Select>) -> Self {
        self.select = select.into();
        self
    }

    /// Apply a typed `WhereUniqueInput`. Overwrites the existing filter.
    pub fn with_where_input<W: crate::inputs::WhereUniqueInput<Model = M>>(mut self, w: W) -> Self {
        self.filter = w.into_ir();
        self
    }

    /// Apply a typed `SelectInput`.
    pub fn with_select_input<S: crate::inputs::SelectInput<Model = M>>(mut self, s: S) -> Self {
        self.select = s.into_ir();
        self
    }

    /// Apply a typed `CreateInput` to the upsert's create path.
    ///
    /// The columns / values produced by the input are appended to the
    /// existing `create_columns` / `create_values` lists. Phase 5a's
    /// codegen ensures every `<Model>CreateInput` carries the
    /// model's `@unique` conflict column, so [`Self::on_conflict`]
    /// remains useful with this method.
    pub fn with_create_input<I>(mut self, input: I) -> Self
    where
        I: crate::inputs::CreateInput<Model = M, Data = crate::inputs::CreatePayload>,
    {
        let data: crate::inputs::CreatePayload = input.into_ir();
        for (col, val) in data {
            self.create_columns.push(col);
            self.create_values.push(val);
        }
        self
    }

    /// Apply a typed `UpdateInput` to the upsert's update path.
    ///
    /// Atomic operators are preserved — when the update branch fires,
    /// `Increment(n)` emits `col = col + $n` in the `DO UPDATE SET`
    /// clause, etc. Setting any input via this method overrides any
    /// flat update columns recorded by [`Self::update`] or
    /// [`Self::update_set`].
    pub fn with_update_input<I>(mut self, input: I) -> Self
    where
        I: crate::inputs::UpdateInput<Model = M, Data = crate::inputs::UpdatePayload>,
    {
        let data: crate::inputs::UpdatePayload = input.into_ir();
        for (col, op) in data {
            self.update_ops.push((col, op));
        }
        self
    }

    /// Build the SQL query.
    ///
    /// Conflict-target precedence: [`Self::on_conflict`] columns win;
    /// otherwise a `where` filter that is a simple equality (or an AND
    /// of equalities, for composite keys) supplies the conflict
    /// column(s). Because this method returns SQL unconditionally, the
    /// combinations that would emit invalid SQL (a non-derivable
    /// `where` filter with no `.on_conflict(...)`, or an update branch
    /// with no conflict target at all) are rejected by [`Self::exec`]
    /// instead — direct callers must uphold the same contract.
    pub fn build_sql(
        &self,
        dialect: &dyn crate::dialect::SqlDialect,
    ) -> (String, Vec<FilterValue>) {
        let mut sql = String::new();
        let mut params = Vec::new();
        let mut param_idx = 1;

        // Conflict-target precedence: explicit `.on_conflict(...)`
        // columns win; otherwise a simple equality `where` filter
        // supplies the target column(s) so the filter isn't silently
        // dropped on the single-statement path. `exec` rejects the
        // remaining invalid combinations (a non-derivable filter, or
        // an update branch with no target at all). Resolved before the
        // INSERT keyword so the empty-target do-nothing form can pick
        // the dialect's INSERT prefix (see below).
        let derived_cols;
        let conflict_cols: Vec<&str> = if !self.conflict_columns.is_empty() {
            self.conflict_columns.iter().map(|s| s.as_str()).collect()
        } else {
            derived_cols = conflict_cols_from_filter(&self.filter).unwrap_or_default();
            derived_cols.iter().map(|s| s.as_str()).collect()
        };

        // Classify the dialect's empty-conflict-target do-nothing form
        // before writing the INSERT keyword — the same classification
        // create.rs uses for skip_duplicates: MySQL has no trailing
        // DO NOTHING clause and expresses the semantics as an
        // `INSERT IGNORE` prefix; MSSQL/CQL have no single-statement
        // equivalent at all; Postgres/SQLite take the target-less
        // `ON CONFLICT DO NOTHING` suffix.
        let targetless_do_nothing = dialect.upsert_do_nothing_clause(&[]);
        let do_nothing_no_target = self.update_ops.is_empty()
            && self.update_columns.is_empty()
            && conflict_cols.is_empty();
        let insert_ignore =
            do_nothing_no_target && targetless_do_nothing.starts_with(" ON DUPLICATE KEY");

        // INSERT INTO clause
        if insert_ignore {
            sql.push_str("INSERT IGNORE INTO ");
        } else {
            sql.push_str("INSERT INTO ");
        }
        sql.push_str(M::TABLE_NAME);

        // Columns
        sql.push_str(" (");
        sql.push_str(&self.create_columns.join(", "));
        sql.push(')');

        // VALUES
        sql.push_str(" VALUES (");
        let placeholders: Vec<_> = self
            .create_values
            .iter()
            .map(|v| {
                params.push(v.clone());
                let p = dialect.placeholder(param_idx);
                param_idx += 1;
                p
            })
            .collect();
        sql.push_str(&placeholders.join(", "));
        sql.push(')');

        // Upsert clause (ON CONFLICT / ON DUPLICATE KEY)
        // Build update SET clause. When `update_ops` is non-empty it
        // supplants the legacy flat column/value list — typed inputs
        // can carry atomic operators (`col = col + $n`) the flat
        // pair can't represent.
        let update_set = if !self.update_ops.is_empty() {
            let update_parts: Vec<String> = self
                .update_ops
                .iter()
                .map(|(col, op)| {
                    let placeholder = dialect.placeholder(param_idx);
                    let (fragment, value) = op.to_set_fragment(col, &placeholder);
                    if let Some(v) = value {
                        params.push(v);
                        param_idx += 1;
                    }
                    fragment
                })
                .collect();
            update_parts.join(", ")
        } else if !self.update_columns.is_empty() {
            let update_parts: Vec<_> = self
                .update_columns
                .iter()
                .zip(self.update_values.iter())
                .map(|(col, val)| {
                    params.push(val.clone());
                    let part = format!("{} = {}", col, dialect.placeholder(param_idx));
                    param_idx += 1;
                    part
                })
                .collect();
            update_parts.join(", ")
        } else {
            String::new()
        };

        if update_set.is_empty() {
            // DO NOTHING variant — routed through the dialect so each
            // backend emits its own syntax (MySQL renders a no-op
            // `ON DUPLICATE KEY UPDATE col = col` self-assign; MSSQL/CQL
            // render no clause). The dialect hook needs at least one
            // target column to produce a well-formed clause, so the
            // target-less form is spelled per dialect: an `INSERT
            // IGNORE` prefix on MySQL (written above), no clause at all
            // on MSSQL/CQL, and the bare `ON CONFLICT DO NOTHING` on
            // Postgres/SQLite — the parenthesized
            // `ON CONFLICT () DO NOTHING` would be invalid, same as
            // createMany's skip_duplicates path in create.rs.
            if conflict_cols.is_empty() {
                if insert_ignore {
                    // MySQL: the INSERT IGNORE prefix above carries the
                    // do-nothing semantics; no trailing clause exists.
                } else if targetless_do_nothing.is_empty() {
                    // MSSQL/CQL: no single-statement equivalent — emit a
                    // plain INSERT (create.rs makes the same fallback).
                    tracing::warn!(
                        table = M::TABLE_NAME,
                        "upsert do-nothing has no single-statement equivalent on this \
                         dialect without a conflict target; emitting a plain INSERT"
                    );
                } else {
                    sql.push_str(" ON CONFLICT DO NOTHING");
                }
            } else {
                sql.push_str(&dialect.upsert_do_nothing_clause(&conflict_cols));
            }
        } else {
            // Use dialect's upsert_clause for DO UPDATE SET
            sql.push_str(&dialect.upsert_clause(&conflict_cols, &update_set));
        }

        // RETURNING clause
        sql.push_str(&dialect.returning_clause(&self.select.to_sql()));

        (sql, params)
    }

    /// Enforce the single-statement upsert contract before SQL goes out.
    ///
    /// `build_sql` returns SQL unconditionally (its signature predates
    /// fallible builders in this crate), so the two combinations that
    /// would emit invalid or filter-dropping SQL are rejected here:
    ///
    /// - a `where` filter without `.on_conflict(...)` whose conflict
    ///   column(s) can't be derived (the filter isn't a simple equality
    ///   or AND of equalities) — the filter would be silently ignored;
    /// - an update branch with no conflict target at all — Postgres
    ///   rejects `ON CONFLICT () DO UPDATE`.
    fn validate_fast_path(&self) -> QueryResult<()> {
        if self.conflict_columns.is_empty() {
            if !self.filter.is_none() && conflict_cols_from_filter(&self.filter).is_none() {
                return Err(crate::error::QueryError::invalid_input(
                    "where",
                    "upsert `where` filter must be an equality on the conflict column(s) \
                     to serve as the ON CONFLICT target on the single-statement path",
                )
                .with_help(
                    "use `.on_conflict([...])` to name the conflict column(s) explicitly, \
                     or simplify the filter to `col = value` (an AND of equalities for \
                     composite keys)",
                ));
            }
            let has_update = !self.update_ops.is_empty() || !self.update_columns.is_empty();
            if has_update && self.filter.is_none() {
                return Err(crate::error::QueryError::invalid_input(
                    "on_conflict",
                    "upsert with an update branch requires `.on_conflict(...)` or a \
                     `where` filter to name the conflict target",
                )
                .with_help(
                    "add `.on_conflict([\"<unique-column>\"])` (or a `where` equality on \
                     the unique column) — Postgres rejects `ON CONFLICT () DO UPDATE`",
                ));
            }
        }
        Ok(())
    }

    /// Queue a nested write to fire when the *create* branch runs
    /// (i.e. no existing row matched).
    pub fn with_create_nested(mut self, nw: NestedWriteOp) -> Self
    where
        E: crate::capabilities::SupportsNestedWrites,
    {
        self.create_nested.push(nw);
        self
    }

    /// Queue a nested write to fire when the *update* branch runs
    /// (i.e. an existing row was found and updated).
    pub fn with_update_nested(mut self, nw: NestedWriteOp) -> Self
    where
        E: crate::capabilities::SupportsNestedWrites,
    {
        self.update_nested.push(nw);
        self
    }

    /// Execute the upsert and return the record.
    ///
    /// Fast path (no nested writes queued): runs a single
    /// vendor-specific upsert (`INSERT ... ON CONFLICT DO UPDATE` on
    /// Postgres, the dialect's equivalent elsewhere). Enforces the
    /// conflict-target contract first: a `where` filter that can't
    /// supply the target (with no `.on_conflict(...)`), or an update
    /// branch with no target at all, fails with an `invalid_input`
    /// error before any SQL is sent.
    ///
    /// Slow path (nested writes queued via `with_create_nested` /
    /// `with_update_nested`): runs a two-statement
    /// engine-agnostic upsert inside a transaction so we can tell which
    /// branch fired:
    /// 1. `UPDATE` the row by primary key. If `affected > 0`, the
    ///    update branch ran — fire `update_nested` with the PK we
    ///    already have from `where:`.
    /// 2. Otherwise `INSERT` the row, take the PK from the inserted
    ///    model, and fire `create_nested`.
    pub async fn exec(self) -> QueryResult<M>
    where
        M: Send + 'static + ModelWithPk,
    {
        // Fast path: single-statement vendor-specific upsert.
        if self.create_nested.is_empty() && self.update_nested.is_empty() {
            self.validate_fast_path()?;
            let dialect = self.engine.dialect();
            let (sql, params) = self.build_sql(dialect);
            return self.engine.execute_insert::<M>(&sql, params).await;
        }

        // Nested writes are queued — the existing where-unique must
        // equal-match the primary key column. This is the same
        // restriction as `update!`'s nested-write path.
        let parent_pk =
            crate::operations::update::extract_pk_from_filter(&self.filter, M::PRIMARY_KEY[0])
                .ok_or_else(|| {
                    crate::error::QueryError::invalid_input(
                        "where",
                        "nested writes inside `upsert!` require the `where:` clause to equal-match \
                 the primary-key column",
                    )
                    .with_help(format!(
                        "expected `where: {{ {pk}: <value> }}` on `{table}` — non-PK unique \
                 columns are not yet supported for nested writes inside upsert!. \
                 Lift this restriction by running the nested ops in a separate operation \
                 after looking up the row's PK.",
                        pk = M::PRIMARY_KEY[0],
                        table = M::TABLE_NAME,
                    ))
                })?;

        let UpsertOperation {
            engine,
            filter,
            create_columns,
            create_values,
            update_columns,
            update_values,
            update_ops,
            conflict_columns: _,
            select,
            create_nested,
            update_nested,
            _model,
        } = self;

        engine
            .transaction(move |tx| async move {
                let dialect = tx.dialect();

                // Phase 1: try UPDATE first.
                let (update_sql, update_params) = build_update_sql::<M>(
                    &filter,
                    &update_columns,
                    &update_values,
                    &update_ops,
                    dialect,
                );
                let affected = tx.execute_raw(&update_sql, update_params).await?;

                let (row, fired_nested): (M, Vec<NestedWriteOp>) = if affected > 0 {
                    // Update branch — fetch the row back via SELECT so
                    // the caller sees the freshly-updated columns. We
                    // know the PK from the where filter.
                    let (sel_sql, sel_params) =
                        build_select_by_pk_sql::<M>(parent_pk.clone(), &select, dialect);
                    let fetched: M = tx.query_one::<M>(&sel_sql, sel_params).await?;
                    (fetched, update_nested)
                } else {
                    // Create branch — INSERT and capture the returned row.
                    let (ins_sql, ins_params) =
                        build_insert_sql::<M>(&create_columns, &create_values, &select, dialect);
                    let inserted: M = tx.execute_insert::<M>(&ins_sql, ins_params).await?;
                    (inserted, create_nested)
                };

                // Dispatch the chosen nested-op vec, sharing the same
                // partition-by-target-Connect batching as create.rs.
                let parent_pk_for_nested = if affected > 0 {
                    parent_pk
                } else {
                    row.pk_value()
                };
                run_nested_ops(&tx, dialect, fired_nested, &parent_pk_for_nested).await?;

                Ok(row)
            })
            .await
    }
}

/// Derive `ON CONFLICT` target columns from a where-unique filter.
///
/// Handles the shapes codegen produces for `upsert!`: a single
/// equality (`col = value`) or an AND of equalities (composite unique
/// keys). Any other filter shape (OR, ranges, `Contains`, ...) has no
/// single conflict target, so this returns `None` and the caller
/// either falls back to explicit `.on_conflict(...)` columns or errors.
fn conflict_cols_from_filter(filter: &Filter) -> Option<Vec<String>> {
    match filter {
        Filter::Equals(name, _) => Some(vec![name.to_string()]),
        Filter::And(parts) => {
            let mut cols = Vec::with_capacity(parts.len());
            for part in parts.iter() {
                match part {
                    Filter::Equals(name, _) => cols.push(name.to_string()),
                    _ => return None,
                }
            }
            if cols.is_empty() { None } else { Some(cols) }
        }
        _ => None,
    }
}

/// Build a two-statement-style UPDATE for the upsert's "update branch".
///
/// Uses `update_ops` when populated (carries atomic operators), else
/// falls back to the legacy flat `update_columns`/`update_values` pair.
/// Always emits a `WHERE` clause from `filter` (the where-unique).
fn build_update_sql<M: Model>(
    filter: &Filter,
    update_columns: &[String],
    update_values: &[FilterValue],
    update_ops: &[(String, WriteOp)],
    dialect: &dyn crate::dialect::SqlDialect,
) -> (String, Vec<FilterValue>) {
    let mut sql = String::new();
    let mut params = Vec::new();
    let mut param_idx = 1;

    sql.push_str("UPDATE ");
    sql.push_str(M::TABLE_NAME);
    sql.push_str(" SET ");

    let set_parts: Vec<String> = if !update_ops.is_empty() {
        update_ops
            .iter()
            .map(|(col, op)| {
                let placeholder = dialect.placeholder(param_idx);
                let (fragment, value) = op.to_set_fragment(col, &placeholder);
                if let Some(v) = value {
                    params.push(v);
                    param_idx += 1;
                }
                fragment
            })
            .collect()
    } else {
        update_columns
            .iter()
            .zip(update_values.iter())
            .map(|(col, val)| {
                params.push(val.clone());
                let part = format!("{} = {}", col, dialect.placeholder(param_idx));
                param_idx += 1;
                part
            })
            .collect()
    };
    sql.push_str(&set_parts.join(", "));

    if !filter.is_none() {
        let (where_sql, where_params) = filter.to_sql(param_idx - 1, dialect);
        sql.push_str(" WHERE ");
        sql.push_str(&where_sql);
        params.extend(where_params);
    }

    (sql, params)
}

/// Build the create-branch INSERT used by the two-statement upsert.
fn build_insert_sql<M: Model>(
    columns: &[String],
    values: &[FilterValue],
    select: &Select,
    dialect: &dyn crate::dialect::SqlDialect,
) -> (String, Vec<FilterValue>) {
    let mut sql = String::new();
    sql.push_str("INSERT INTO ");
    sql.push_str(M::TABLE_NAME);
    sql.push_str(" (");
    sql.push_str(&columns.join(", "));
    sql.push(')');
    sql.push_str(" VALUES (");
    let placeholders: Vec<_> = (1..=values.len()).map(|i| dialect.placeholder(i)).collect();
    sql.push_str(&placeholders.join(", "));
    sql.push(')');
    sql.push_str(&dialect.returning_clause(&select.to_sql()));
    (sql, values.to_vec())
}

/// Build the SELECT-by-pk used to re-fetch the row after the update
/// branch ran.
fn build_select_by_pk_sql<M: Model>(
    pk: FilterValue,
    select: &Select,
    dialect: &dyn crate::dialect::SqlDialect,
) -> (String, Vec<FilterValue>) {
    let cols = select.to_sql();
    let sql = format!(
        "SELECT {} FROM {} WHERE {} = {}",
        if cols.is_empty() || cols == "*" {
            "*".to_string()
        } else {
            cols
        },
        M::TABLE_NAME,
        dialect.quote_ident(M::PRIMARY_KEY[0]),
        dialect.placeholder(1),
    );
    (sql, vec![pk])
}

/// Iterate `nested` against `tx`, batching consecutive Connect ops with
/// the same target — mirrors the create.rs partition loop.
async fn run_nested_ops<E: QueryEngine>(
    tx: &E,
    dialect: &dyn crate::dialect::SqlDialect,
    nested: Vec<NestedWriteOp>,
    parent_pk: &FilterValue,
) -> QueryResult<()> {
    let mut idx = 0;
    while idx < nested.len() {
        if let NestedWriteOp::Connect {
            target_table: run_table,
            foreign_key: run_fk,
            target_pk: run_target_pk,
            ..
        } = &nested[idx]
        {
            let run_table = *run_table;
            let run_fk = *run_fk;
            let run_target_pk = *run_target_pk;
            let mut end = idx + 1;
            while end < nested.len() {
                match &nested[end] {
                    NestedWriteOp::Connect {
                        target_table,
                        foreign_key,
                        target_pk,
                        ..
                    } if *target_table == run_table
                        && *foreign_key == run_fk
                        && *target_pk == run_target_pk =>
                    {
                        end += 1;
                    }
                    _ => break,
                }
            }

            if end - idx == 1 {
                let op = nested[idx].clone();
                op.execute(tx, parent_pk).await?;
            } else {
                let expected = (end - idx) as u64;
                let mut pks: Vec<FilterValue> = Vec::with_capacity(end - idx + 1);
                pks.push(parent_pk.clone());
                for op in &nested[idx..end] {
                    if let NestedWriteOp::Connect { pk, .. } = op {
                        pks.push(pk.clone());
                    }
                }
                let placeholders: Vec<String> =
                    (2..=pks.len()).map(|i| dialect.placeholder(i)).collect();
                let sql = format!(
                    "UPDATE {} SET {} = {} WHERE {} IN ({})",
                    dialect.quote_ident(run_table),
                    dialect.quote_ident(run_fk),
                    dialect.placeholder(1),
                    dialect.quote_ident(run_target_pk),
                    placeholders.join(", "),
                );
                let affected = tx.execute_raw(&sql, pks).await?;
                if affected != expected {
                    return Err(crate::error::QueryError::not_found(run_table)
                        .with_context("Nested Connect batch")
                        .with_help(format!(
                            "Expected {} matching rows but UPDATE affected {}",
                            expected, affected
                        )));
                }
            }
            idx = end;
        } else {
            let op = nested[idx].clone();
            op.execute(tx, parent_pk).await?;
            idx += 1;
        }
    }
    Ok(())
}

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

    #[derive(Debug)]
    struct TestModel;

    impl Model for TestModel {
        const MODEL_NAME: &'static str = "TestModel";
        const TABLE_NAME: &'static str = "test_models";
        const PRIMARY_KEY: &'static [&'static str] = &["id"];
        const COLUMNS: &'static [&'static str] = &["id", "name", "email"];
    }

    impl crate::row::FromRow for TestModel {
        fn from_row(_row: &impl crate::row::RowRef) -> Result<Self, crate::row::RowError> {
            Ok(TestModel)
        }
    }

    // Phase-5c slow-path nested-write wiring requires `ModelWithPk` on
    // the return type. The constant PK is fine because the legacy
    // single-statement tests never exercise the slow path.
    impl crate::traits::ModelWithPk for TestModel {
        fn pk_value(&self) -> FilterValue {
            FilterValue::Int(0)
        }
        fn get_column_value(&self, _column: &str) -> Option<FilterValue> {
            None
        }
    }

    #[derive(Clone)]
    struct MockEngine;

    impl QueryEngine for MockEngine {
        fn dialect(&self) -> &dyn crate::dialect::SqlDialect {
            &crate::dialect::Postgres
        }

        fn query_many<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<Vec<T>>> {
            Box::pin(async { Ok(Vec::new()) })
        }

        fn query_one<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<T>> {
            Box::pin(async { Err(QueryError::not_found("test")) })
        }

        fn query_optional<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<Option<T>>> {
            Box::pin(async { Ok(None) })
        }

        fn execute_insert<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<T>> {
            Box::pin(async { Err(QueryError::not_found("test")) })
        }

        fn execute_update<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<Vec<T>>> {
            Box::pin(async { Ok(Vec::new()) })
        }

        fn execute_delete(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<u64>> {
            Box::pin(async { Ok(0) })
        }

        fn execute_raw(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<u64>> {
            Box::pin(async { Ok(0) })
        }

        fn count(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<u64>> {
            Box::pin(async { Ok(0) })
        }
    }

    // ========== Construction Tests ==========

    #[test]
    fn test_upsert_new() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine);
        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("INSERT INTO test_models"));
        assert!(sql.contains("ON CONFLICT"));
        assert!(sql.contains("RETURNING *"));
        assert!(params.is_empty());
    }

    #[test]
    fn test_upsert_basic() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .create_set("name", "Test")
            .update_set("name", "Updated");

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("INSERT INTO test_models"));
        assert!(sql.contains("ON CONFLICT (\"email\")"));
        assert!(sql.contains("DO UPDATE SET"));
        assert!(sql.contains("RETURNING *"));
        assert_eq!(params.len(), 3); // 2 create + 1 update
    }

    // ========== Conflict Column Tests ==========

    #[test]
    fn test_upsert_single_conflict_column() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .create_set("id", FilterValue::Int(1));

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("ON CONFLICT (\"id\")"));
    }

    #[test]
    fn test_upsert_multiple_conflict_columns() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["tenant_id", "email"])
            .create_set("email", "test@example.com")
            .create_set("tenant_id", FilterValue::Int(1));

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("ON CONFLICT (\"tenant_id\", \"email\")"));
    }

    #[test]
    fn test_upsert_without_conflict_columns() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .create_set("email", "test@example.com");

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("ON CONFLICT"));
        assert!(!sql.contains("ON CONFLICT ("));
    }

    // ========== Create Tests ==========

    #[test]
    fn test_upsert_create_with_set() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .create_set("name", "Test User");

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("(email, name)"));
        assert!(sql.contains("VALUES ($1, $2)"));
        assert_eq!(params.len(), 2);
    }

    #[test]
    fn test_upsert_create_with_iterator() {
        let create_data = vec![
            ("email", FilterValue::String("test@example.com".to_string())),
            ("name", FilterValue::String("Test User".to_string())),
            ("age", FilterValue::Int(25)),
        ];
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create(create_data);

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("(email, name, age)"));
        assert!(sql.contains("VALUES ($1, $2, $3)"));
        assert_eq!(params.len(), 3);
    }

    // ========== Update Tests ==========

    #[test]
    fn test_upsert_update_with_set() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .update_set("name", "Updated Name")
            .update_set("updated_at", "2024-01-01");

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("DO UPDATE SET"));
        assert!(sql.contains("name = $"));
        assert!(sql.contains("updated_at = $"));
        assert_eq!(params.len(), 3); // 1 create + 2 update
    }

    #[test]
    fn test_upsert_update_with_iterator() {
        let update_data = vec![
            ("name", FilterValue::String("Updated".to_string())),
            ("status", FilterValue::String("active".to_string())),
        ];
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .create_set("id", FilterValue::Int(1))
            .update(update_data);

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("DO UPDATE SET"));
        assert_eq!(params.len(), 3); // 1 create + 2 update
    }

    // ========== Do Nothing Tests ==========

    #[test]
    fn test_upsert_do_nothing() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com");

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("DO NOTHING"));
        assert!(!sql.contains("DO UPDATE"));
    }

    #[test]
    fn test_upsert_do_nothing_multiple_create() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .create_set("name", "Test");

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("DO NOTHING"));
        assert_eq!(params.len(), 2);
    }

    #[test]
    fn test_upsert_do_nothing_mysql() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com");

        let (sql, _) = op.build_sql(&crate::dialect::Mysql);

        // MySQL has no ON CONFLICT — the dialect renders a no-op
        // self-assign on the first conflict column instead.
        assert!(
            sql.contains("ON DUPLICATE KEY UPDATE `email` = `email`"),
            "got: {sql}"
        );
        assert!(!sql.contains("ON CONFLICT"), "got: {sql}");
    }

    #[test]
    fn test_upsert_do_nothing_mysql_no_conflict_target() {
        // MySQL has no ON CONFLICT DO NOTHING; an empty conflict target
        // must come out as an INSERT IGNORE prefix (the canonical MySQL
        // form — mirrors create.rs's skip_duplicates), never the Postgres
        // target-less spelling.
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .create_set("email", "test@example.com");

        let (sql, _) = op.build_sql(&crate::dialect::Mysql);

        assert!(
            sql.starts_with("INSERT IGNORE INTO test_models"),
            "expected INSERT IGNORE prefix, got: {sql}"
        );
        assert!(!sql.contains("ON CONFLICT"), "got: {sql}");
        assert!(
            !sql.contains("ON DUPLICATE KEY"),
            "INSERT IGNORE replaces the self-assign suffix: {sql}"
        );
    }

    // ========== Select Tests ==========

    #[test]
    fn test_upsert_with_select() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .update_set("name", "Updated")
            .select(Select::fields(["id", "email"]));

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("RETURNING id, email"));
        assert!(!sql.contains("RETURNING *"));
    }

    #[test]
    fn test_upsert_select_all() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .select(Select::All);

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("RETURNING *"));
    }

    // ========== Where Filter Tests ==========

    #[test]
    fn test_upsert_with_where() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .r#where(Filter::Equals(
                "email".into(),
                FilterValue::String("test@example.com".to_string()),
            ))
            .on_conflict(["email"])
            .create_set("email", "test@example.com");

        let (_, _) = op.build_sql(&crate::dialect::Postgres);
        // where_ sets the filter but doesn't affect upsert SQL directly
    }

    // ========== Conflict-Target Validation Tests ==========

    #[test]
    fn test_upsert_where_derives_conflict_target() {
        // No explicit .on_conflict(...) — the where equality supplies
        // the ON CONFLICT column so the filter isn't silently dropped.
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .r#where(Filter::Equals(
                "email".into(),
                FilterValue::String("test@example.com".to_string()),
            ))
            .create_set("email", "test@example.com")
            .update_set("name", "Updated");

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("ON CONFLICT (\"email\")"), "got: {sql}");
        assert!(sql.contains("DO UPDATE SET"), "got: {sql}");
    }

    #[tokio::test]
    async fn test_upsert_update_without_conflict_target_errors() {
        // An update branch with neither .on_conflict(...) nor a where
        // filter would render `ON CONFLICT () DO UPDATE` — rejected
        // before any SQL goes out.
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .create_set("email", "test@example.com")
            .update_set("name", "Updated");

        let err = op.exec().await.unwrap_err();

        assert_eq!(err.code, crate::error::ErrorCode::InvalidParameter);
        let msg = format!("{err}");
        assert!(msg.contains("on_conflict"), "msg: {msg}");
    }

    #[tokio::test]
    async fn test_upsert_non_derivable_where_without_conflict_errors() {
        // A range filter can't name a conflict target; with no
        // .on_conflict(...) the filter would be silently dropped.
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .r#where(Filter::Gt("id".into(), FilterValue::Int(3)))
            .create_set("email", "test@example.com");

        let err = op.exec().await.unwrap_err();

        assert_eq!(err.code, crate::error::ErrorCode::InvalidParameter);
        let msg = format!("{err}");
        assert!(msg.contains("where"), "msg: {msg}");
    }

    // ========== SQL Structure Tests ==========

    #[test]
    fn test_upsert_sql_structure() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .update_set("name", "Updated")
            .select(Select::fields(["id"]));

        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        let insert_pos = sql.find("INSERT INTO").unwrap();
        let values_pos = sql.find("VALUES").unwrap();
        let conflict_pos = sql.find("ON CONFLICT").unwrap();
        let update_pos = sql.find("DO UPDATE SET").unwrap();
        let returning_pos = sql.find("RETURNING").unwrap();

        assert!(insert_pos < values_pos);
        assert!(values_pos < conflict_pos);
        assert!(conflict_pos < update_pos);
        assert!(update_pos < returning_pos);
    }

    #[test]
    fn test_upsert_table_name() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine);
        let (sql, _) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("test_models"));
    }

    // ========== Param Ordering Tests ==========

    #[test]
    fn test_upsert_param_ordering() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "create@test.com")
            .create_set("name", "Create Name")
            .update_set("name", "Update Name");

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        // Create params first, then update params
        assert!(sql.contains("VALUES ($1, $2)"));
        assert!(sql.contains("name = $3"));
        assert_eq!(params.len(), 3);
        assert_eq!(
            params[0],
            FilterValue::String("create@test.com".to_string())
        );
        assert_eq!(params[1], FilterValue::String("Create Name".to_string()));
        assert_eq!(params[2], FilterValue::String("Update Name".to_string()));
    }

    // ========== Async Execution Tests ==========

    #[tokio::test]
    async fn test_upsert_exec() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .create_set("email", "test@example.com");

        let result = op.exec().await;

        // MockEngine returns not_found for execute_insert
        assert!(result.is_err());
    }

    // ========== Method Chaining Tests ==========

    #[test]
    fn test_upsert_full_chain() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .r#where(Filter::Equals(
                "email".into(),
                FilterValue::String("test@example.com".to_string()),
            ))
            .on_conflict(["email"])
            .create_set("email", "test@example.com")
            .create_set("name", "Test User")
            .update_set("name", "Updated User")
            .select(Select::fields(["id", "name", "email"]));

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);

        assert!(sql.contains("INSERT INTO test_models"));
        assert!(sql.contains("ON CONFLICT (\"email\")"));
        assert!(sql.contains("DO UPDATE SET"));
        assert!(sql.contains("RETURNING id, name, email"));
        assert_eq!(params.len(), 3);
    }

    // ========== Value Type Tests ==========

    #[test]
    fn test_upsert_with_null_value() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .create_set("id", FilterValue::Int(1))
            .create_set("nickname", FilterValue::Null);

        let (_, params) = op.build_sql(&crate::dialect::Postgres);

        assert_eq!(params[1], FilterValue::Null);
    }

    #[test]
    fn test_upsert_with_boolean_value() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .create_set("id", FilterValue::Int(1))
            .create_set("active", FilterValue::Bool(true))
            .update_set("active", FilterValue::Bool(false));

        let (_, params) = op.build_sql(&crate::dialect::Postgres);

        assert_eq!(params[1], FilterValue::Bool(true));
        assert_eq!(params[2], FilterValue::Bool(false));
    }

    #[test]
    fn test_upsert_with_numeric_values() {
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .create_set("id", FilterValue::Int(1))
            .create_set("score", FilterValue::Float(99.5));

        let (_, params) = op.build_sql(&crate::dialect::Postgres);

        assert_eq!(params[0], FilterValue::Int(1));
        assert_eq!(params[1], FilterValue::Float(99.5));
    }

    #[test]
    fn test_upsert_with_json_value() {
        let json = serde_json::json!({"key": "value"});
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .create_set("id", FilterValue::Int(1))
            .create_set("metadata", FilterValue::Json(json.clone()));

        let (_, params) = op.build_sql(&crate::dialect::Postgres);

        assert_eq!(params[1], FilterValue::Json(json));
    }

    // ========== Phase 5a: typed-input wiring ==========

    struct MockCreateInput(Vec<(String, FilterValue)>);

    impl crate::inputs::CreateInput for MockCreateInput {
        type Model = TestModel;
        type Data = crate::inputs::CreatePayload;
        fn into_ir(self) -> Self::Data {
            self.0
        }
    }

    struct MockUpdateInput(Vec<(String, WriteOp)>);

    impl crate::inputs::UpdateInput for MockUpdateInput {
        type Model = TestModel;
        type Data = crate::inputs::UpdatePayload;
        fn into_ir(self) -> Self::Data {
            self.0
        }
    }

    #[test]
    fn upsert_with_create_input_appends_create_columns() {
        let input = MockCreateInput(vec![
            ("email".into(), FilterValue::String("a@x.com".into())),
            ("name".into(), FilterValue::String("Alice".into())),
        ]);
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["email"])
            .with_create_input(input)
            .update_set("name", "Updated");

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);
        assert!(sql.contains("(email, name)"), "got: {sql}");
        assert!(sql.contains("VALUES ($1, $2)"), "got: {sql}");
        assert!(sql.contains("ON CONFLICT (\"email\")"));
        // 2 create params + 1 update param.
        assert_eq!(params.len(), 3);
    }

    #[test]
    fn upsert_with_update_input_uses_atomic_ops() {
        let create = MockCreateInput(vec![("id".into(), FilterValue::Int(1))]);
        let update = MockUpdateInput(vec![
            (
                "name".into(),
                WriteOp::Set(FilterValue::String("Renamed".into())),
            ),
            (
                "login_count".into(),
                WriteOp::Increment(FilterValue::Int(1)),
            ),
        ]);
        let op = UpsertOperation::<MockEngine, TestModel>::new(MockEngine)
            .on_conflict(["id"])
            .with_create_input(create)
            .with_update_input(update);

        let (sql, params) = op.build_sql(&crate::dialect::Postgres);
        // Atomic operator must round-trip through the upsert path.
        assert!(sql.contains("login_count = login_count + $"), "got: {sql}");
        // 1 create + 2 update params.
        assert_eq!(params.len(), 3);
    }

    // ========== Phase 5c: nested-write wiring on upsert! ==========

    use std::sync::{Arc, Mutex};

    type StatementLog = Arc<Mutex<Vec<(String, Vec<FilterValue>)>>>;

    /// Recording engine that exposes a settable `affected` sequence and
    /// returns a default `TestModel` from `execute_insert` / `query_one`
    /// (the two paths the nested-upsert exec consumes).
    #[derive(Clone)]
    struct RecordingEngine {
        recorded: StatementLog,
        affected: Arc<Mutex<Vec<u64>>>,
    }

    impl RecordingEngine {
        fn with_affected(seq: Vec<u64>) -> Self {
            let mut rev = seq;
            rev.reverse();
            Self {
                recorded: Arc::new(Mutex::new(Vec::new())),
                affected: Arc::new(Mutex::new(rev)),
            }
        }

        fn statements(&self) -> Vec<(String, Vec<FilterValue>)> {
            self.recorded.lock().unwrap().clone()
        }
    }

    impl crate::capabilities::SupportsNestedWrites for RecordingEngine {}

    impl QueryEngine for RecordingEngine {
        fn dialect(&self) -> &dyn crate::dialect::SqlDialect {
            &crate::dialect::Postgres
        }

        fn query_many<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<Vec<T>>> {
            Box::pin(async { Ok(Vec::new()) })
        }

        fn query_one<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            sql: &str,
            params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<T>> {
            let recorded = self.recorded.clone();
            let sql = sql.to_string();
            Box::pin(async move {
                recorded.lock().unwrap().push((sql, params));
                T::from_row(&CannedRow).map_err(|e| QueryError::internal(e.to_string()))
            })
        }

        fn query_optional<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<Option<T>>> {
            Box::pin(async { Ok(None) })
        }

        fn execute_insert<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            sql: &str,
            params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<T>> {
            let recorded = self.recorded.clone();
            let sql = sql.to_string();
            Box::pin(async move {
                recorded.lock().unwrap().push((sql, params));
                T::from_row(&CannedRow).map_err(|e| QueryError::internal(e.to_string()))
            })
        }

        fn execute_update<T: Model + crate::row::FromRow + Send + 'static>(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<Vec<T>>> {
            Box::pin(async { Ok(Vec::new()) })
        }

        fn execute_delete(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<u64>> {
            Box::pin(async { Ok(0) })
        }

        fn execute_raw(
            &self,
            sql: &str,
            params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<u64>> {
            let recorded = self.recorded.clone();
            let affected = self.affected.clone();
            let sql_string = sql.to_string();
            let default = if sql.contains(" IN (") {
                (params.len() as u64).saturating_sub(1)
            } else {
                1
            };
            Box::pin(async move {
                recorded.lock().unwrap().push((sql_string, params));
                Ok(affected.lock().unwrap().pop().unwrap_or(default))
            })
        }

        fn count(
            &self,
            _sql: &str,
            _params: Vec<FilterValue>,
        ) -> crate::traits::BoxFuture<'_, QueryResult<u64>> {
            Box::pin(async { Ok(0) })
        }
    }

    /// Stand-in RowRef so `execute_insert` / `query_one` can synthesise
    /// a `TestModel` value without a live database.
    struct CannedRow;

    impl crate::row::RowRef for CannedRow {
        fn get_i32(&self, _column: &str) -> Result<i32, crate::row::RowError> {
            Ok(0)
        }
        fn get_i32_opt(&self, _column: &str) -> Result<Option<i32>, crate::row::RowError> {
            Ok(Some(0))
        }
        fn get_i64(&self, _column: &str) -> Result<i64, crate::row::RowError> {
            Ok(0)
        }
        fn get_i64_opt(&self, _column: &str) -> Result<Option<i64>, crate::row::RowError> {
            Ok(None)
        }
        fn get_f64(&self, _column: &str) -> Result<f64, crate::row::RowError> {
            Ok(0.0)
        }
        fn get_f64_opt(&self, _column: &str) -> Result<Option<f64>, crate::row::RowError> {
            Ok(None)
        }
        fn get_bool(&self, _column: &str) -> Result<bool, crate::row::RowError> {
            Ok(false)
        }
        fn get_bool_opt(&self, _column: &str) -> Result<Option<bool>, crate::row::RowError> {
            Ok(None)
        }
        fn get_str(&self, _column: &str) -> Result<&str, crate::row::RowError> {
            Ok("canned")
        }
        fn get_str_opt(&self, _column: &str) -> Result<Option<&str>, crate::row::RowError> {
            Ok(Some("canned"))
        }
        fn get_bytes(&self, _column: &str) -> Result<&[u8], crate::row::RowError> {
            Ok(b"")
        }
        fn get_bytes_opt(&self, _column: &str) -> Result<Option<&[u8]>, crate::row::RowError> {
            Ok(None)
        }
    }

    #[tokio::test]
    async fn upsert_with_nested_in_update_branch_fires_update_nested_only() {
        // affected=1 on the UPDATE → update branch.
        let engine = RecordingEngine::with_affected(vec![1]);
        let op = UpsertOperation::<RecordingEngine, TestModel>::new(engine.clone())
            .r#where(Filter::Equals("id".into(), FilterValue::Int(7)))
            .create_set("id", FilterValue::Int(7))
            .create_set("email", "new@x.com")
            .update_set("name", "Renamed")
            .with_update_nested(NestedWriteOp::Disconnect {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                target_pk: "id",
                pk: FilterValue::Int(42),
            })
            .with_create_nested(NestedWriteOp::Create {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                payload: vec![vec![("title".into(), FilterValue::String("p1".into()))]],
            });

        let _ = op.exec().await.expect("upsert update branch");

        let stmts = engine.statements();
        // Expect: UPDATE (affected=1) + SELECT (re-fetch) + nested Disconnect UPDATE
        assert_eq!(
            stmts.len(),
            3,
            "UPDATE + SELECT + nested disconnect; got {stmts:#?}"
        );
        assert!(
            stmts[0].0.starts_with("UPDATE test_models"),
            "first stmt should be parent UPDATE: {}",
            stmts[0].0
        );
        assert!(
            stmts[1].0.starts_with("SELECT"),
            "second stmt should re-fetch the row: {}",
            stmts[1].0
        );
        // Third stmt is the nested Disconnect — UPDATE child + NULL.
        assert!(stmts[2].0.contains("UPDATE"), "got: {}", stmts[2].0);
        assert!(stmts[2].0.contains("posts"), "got: {}", stmts[2].0);
        assert!(stmts[2].0.contains("NULL"), "got: {}", stmts[2].0);
        // Verify no INSERT (no create branch) and no nested Create (FK splicing).
        assert!(
            !stmts.iter().any(|(s, _)| s.starts_with("INSERT INTO")),
            "no INSERT must fire on update branch: {stmts:#?}"
        );
    }

    #[tokio::test]
    async fn upsert_with_nested_in_create_branch_fires_create_nested_only() {
        // affected=0 on UPDATE → create branch (INSERT runs).
        let engine = RecordingEngine::with_affected(vec![0]);
        let op = UpsertOperation::<RecordingEngine, TestModel>::new(engine.clone())
            .r#where(Filter::Equals("id".into(), FilterValue::Int(7)))
            .create_set("id", FilterValue::Int(7))
            .create_set("email", "new@x.com")
            .update_set("name", "Renamed")
            .with_update_nested(NestedWriteOp::Disconnect {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                target_pk: "id",
                pk: FilterValue::Int(42),
            })
            .with_create_nested(NestedWriteOp::Create {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                payload: vec![vec![("title".into(), FilterValue::String("p1".into()))]],
            });

        let _ = op.exec().await.expect("upsert create branch");

        let stmts = engine.statements();
        // Expect: UPDATE (affected=0) + INSERT + nested Create child INSERT
        assert_eq!(
            stmts.len(),
            3,
            "UPDATE + INSERT + nested child INSERT; got {stmts:#?}"
        );
        assert!(
            stmts[0].0.starts_with("UPDATE test_models"),
            "first stmt should be parent UPDATE: {}",
            stmts[0].0
        );
        assert!(
            stmts[1].0.contains("INSERT INTO test_models"),
            "second stmt should be the create-branch INSERT: {}",
            stmts[1].0
        );
        assert!(
            stmts[2].0.contains("INSERT INTO"),
            "third stmt should be the nested Create child INSERT: {}",
            stmts[2].0
        );
        assert!(
            stmts[2].0.contains("posts"),
            "nested INSERT targets posts: {}",
            stmts[2].0
        );
        // No SELECT (we got the row directly from the INSERT) and no
        // nested Disconnect UPDATE on posts table.
        assert!(
            !stmts.iter().any(|(s, _)| s.starts_with("SELECT")),
            "no SELECT must fire on create branch: {stmts:#?}"
        );
        assert!(
            !stmts
                .iter()
                .any(|(s, _)| s.contains("UPDATE \"posts\"") || s.contains("UPDATE posts")),
            "no nested Disconnect on update_nested must fire: {stmts:#?}"
        );
    }

    #[tokio::test]
    async fn upsert_both_branches_carry_nested_only_one_fires() {
        // Run twice with two engines — once for each branch — and
        // confirm only the branch-appropriate nested ops execute.
        // Branch 1: update.
        let engine_u = RecordingEngine::with_affected(vec![1]);
        let _ = UpsertOperation::<RecordingEngine, TestModel>::new(engine_u.clone())
            .r#where(Filter::Equals("id".into(), FilterValue::Int(7)))
            .create_set("id", FilterValue::Int(7))
            .update_set("name", "Renamed")
            .with_update_nested(NestedWriteOp::Disconnect {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                target_pk: "id",
                pk: FilterValue::Int(42),
            })
            .with_create_nested(NestedWriteOp::Create {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                payload: vec![vec![("title".into(), FilterValue::String("p".into()))]],
            })
            .exec()
            .await
            .expect("update branch");
        let u_stmts = engine_u.statements();
        // Disconnect must fire, child INSERT (nested Create) must not.
        assert!(
            u_stmts.iter().any(|(s, _)| s.contains("NULL")),
            "expected nested Disconnect: {u_stmts:#?}"
        );
        assert!(
            !u_stmts
                .iter()
                .any(|(s, _)| s.contains("INSERT INTO") && s.contains("posts")),
            "no nested Create child INSERT on update branch: {u_stmts:#?}"
        );

        // Branch 2: create.
        let engine_c = RecordingEngine::with_affected(vec![0]);
        let _ = UpsertOperation::<RecordingEngine, TestModel>::new(engine_c.clone())
            .r#where(Filter::Equals("id".into(), FilterValue::Int(7)))
            .create_set("id", FilterValue::Int(7))
            .update_set("name", "Renamed")
            .with_update_nested(NestedWriteOp::Disconnect {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                target_pk: "id",
                pk: FilterValue::Int(42),
            })
            .with_create_nested(NestedWriteOp::Create {
                relation: "posts",
                target_table: "posts",
                foreign_key: "author_id",
                payload: vec![vec![("title".into(), FilterValue::String("p".into()))]],
            })
            .exec()
            .await
            .expect("create branch");
        let c_stmts = engine_c.statements();
        // Child INSERT (nested Create on posts) must fire, Disconnect must not.
        assert!(
            c_stmts
                .iter()
                .any(|(s, _)| s.contains("INSERT INTO") && s.contains("posts")),
            "expected nested Create child INSERT: {c_stmts:#?}"
        );
        assert!(
            !c_stmts.iter().any(|(s, _)| s.contains("NULL")),
            "no nested Disconnect on create branch: {c_stmts:#?}"
        );
    }
}