dibs-qgen 0.1.1

Query DSL code generator for dibs (parses .styx query files into Rust and SQL)
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
//! Rust code generation from query schema types using the `codegen` crate.
//!
//! # Design
//!
//! For queries with JOINs (relations), we generate:
//! 1. A **flat row struct** with all columns from the SELECT (using aliased names)
//! 2. Use `from_row()` to deserialize each row into the flat struct
//! 3. Grouping/deduplication logic works on the deserialized values
//!
//! This approach uses facet-tokio-postgres for all deserialization, which
//! properly handles complex types like `Jsonb<T>` via reflection.

use crate::error::QErrorKind;
use crate::sqlgen::SqlGenContext;
use crate::{QError, QSource};
use codegen::{Block, Function, Scope, Struct};
use dibs_db_schema::{Schema, Table};
use dibs_query_schema::{
    Decl, Delete, FieldDef, Insert, InsertMany, Meta, Params, QueryFile, Returning, Returns,
    Select, SelectFields, Span, Update, Upsert, UpsertMany,
};
use std::sync::Arc;

/// Generated Rust code for a query file.
#[derive(Debug, Clone)]
pub struct GeneratedCode {
    /// Full Rust source code.
    pub code: String,
}

/// Wrap a generated function body so its `Result` is fed through
/// `TraceErr::trace_err(query_name)` before being returned. This is
/// the *single point* where postgres-side error detail gets pushed
/// into `tracing`, regardless of what each call site does with the
/// `QueryError` afterward.
///
/// The body string is expected to be an expression evaluating to
/// `Result<_, QueryError>` (which is what every generator already
/// emits). We wrap it in `async { … }.await` so any `?` inside
/// propagates to the wrapped Result instead of to the outer function,
/// then let the inserted helper observe the Err and re-yield the
/// Result.
fn wrap_with_trace_err(body: &str, fn_name: &str) -> String {
    format!(
        "let __dibs_result = async {{\n{body}\n}}.await;\n\
         <_ as TraceErr>::trace_err(__dibs_result, \"{fn_name}\")"
    )
}

/// Look up the Rust type for a column in a schema.
fn schema_column_type(schema: &Schema, table: &str, column: &str) -> Option<String> {
    let table_info = schema.get_table(table)?;
    let col = table_info.columns.iter().find(|c| c.name == column)?;
    let rust_type = col
        .rust_type
        .clone()
        .unwrap_or_else(|| col.pg_type.to_rust_type().to_string());
    if col.nullable {
        Some(format!("Option<{}>", rust_type))
    } else {
        Some(rust_type)
    }
}

/// Context for code generation.
struct CodegenContext<'a> {
    schema: &'a Schema,
    source: Arc<QSource>,
    #[allow(dead_code)]
    scope: Scope,
}

impl CodegenContext<'_> {
    /// Look up the Rust type for a column.
    fn column_type(&self, table: &str, column: &str) -> Option<String> {
        schema_column_type(self.schema, table, column)
    }

    /// Build a `TableNotFound` error pointing at `span`, listing the tables the
    /// schema *does* contain (empty list ⇒ the schema itself is empty, which the
    /// error renders as a "you forgot ensure_linked()" hint).
    fn table_not_found(&self, table: &str, span: Span) -> QError {
        let mut available: Vec<String> = self.schema.tables.keys().cloned().collect();
        available.sort();
        QError {
            source: self.source.clone(),
            span,
            kind: QErrorKind::TableNotFound {
                table: table.to_string(),
                available,
            },
        }
    }

    /// Resolve a table that is referenced in the query at `span`, erroring (with
    /// the span pointing at the table reference, not some column) if it isn't in
    /// the schema. Call this once per table reference before looking up its
    /// columns, so a missing/empty schema is reported against the table.
    fn require_table(&self, table: &str, span: Span) -> Result<&Table, QError> {
        self.schema
            .get_table(table)
            .ok_or_else(|| self.table_not_found(table, span))
    }

    /// Look up the Rust type for a column referenced in the query at `span`,
    /// erroring if the table or column can't be resolved from the schema.
    ///
    /// Use this for every column whose type ends up in a generated result/param
    /// struct. A missing column means the schema handed to codegen is wrong or
    /// empty (e.g. a build script that forgot to link its table definitions);
    /// silently falling back to `String` there generates wrong-typed structs
    /// that compile fine and corrupt data at runtime.
    fn column_type_at(&self, table: &str, column: &str, span: Span) -> Result<String, QError> {
        let table_info = self.require_table(table, span)?;
        if let Some(ty) = schema_column_type(self.schema, table, column) {
            return Ok(ty);
        }
        Err(QError {
            source: self.source.clone(),
            span,
            kind: QErrorKind::ColumnNotFound {
                table: table.to_string(),
                column: column.to_string(),
                available: table_info.columns.iter().map(|c| c.name.clone()).collect(),
            },
        })
    }

    /// Create an SqlGenContext for this codegen context.
    fn sqlgen_ctx(&self) -> SqlGenContext<'_> {
        SqlGenContext::new(self.schema, self.source.clone())
    }
}

/// Generate Rust code for a query file.
pub fn generate_rust_code(
    file: &QueryFile,
    schema: &Schema,
    source: Arc<QSource>,
) -> Result<GeneratedCode, QError> {
    let mut scope = Scope::new();

    // Add file header as raw code
    scope.raw("// Generated by dibs-qgen. Do not edit.");
    scope.raw("");

    // Imports
    scope.import("dibs_runtime::prelude", "*");
    scope.import("dibs_runtime", "tokio_postgres");

    let ctx = CodegenContext {
        schema,
        source,
        scope: Scope::new(),
    };

    // Iterate through declarations and generate code for each type
    for (name_meta, decl) in &file.0 {
        match decl {
            Decl::Select(select) => {
                generate_select_code(&ctx, name_meta, select, &mut scope)?;
            }
            Decl::Insert(insert) => {
                generate_insert_code(&ctx, name_meta, insert, &mut scope)?;
            }
            Decl::InsertMany(insert_many) => {
                generate_insert_many_code(&ctx, name_meta, insert_many, &mut scope)?;
            }
            Decl::Upsert(upsert) => {
                generate_upsert_code(&ctx, name_meta, upsert, &mut scope)?;
            }
            Decl::UpsertMany(upsert_many) => {
                generate_upsert_many_code(&ctx, name_meta, upsert_many, &mut scope)?;
            }
            Decl::Update(update) => {
                generate_update_code(&ctx, name_meta, update, &mut scope)?;
            }
            Decl::Delete(delete) => {
                generate_delete_code(&ctx, name_meta, delete, &mut scope)?;
            }
        }
    }

    Ok(GeneratedCode {
        code: scope.to_string(),
    })
}

fn generate_select_code(
    ctx: &CodegenContext,
    name_meta: &Meta<String>,
    select: &Select,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let struct_name = format!("{}Result", name);

    // Generate result struct(s)
    if let Some(from) = &select.from {
        if select.fields.is_some() {
            generate_result_struct(ctx, select, name_meta, &struct_name, from, scope)?;

            // For queries with relations, also generate a flat row struct for deserialization
            if select.has_relations() {
                let flat_struct_name = format!("{}Row", name);
                generate_flat_row_struct(ctx, select, &flat_struct_name, from, scope)?;
            }
        }
    } else if let Some(returns) = &select.returns {
        // Raw SQL query with explicit returns clause
        generate_raw_sql_result_struct(&struct_name, returns, scope);
    }

    // Generate query function
    generate_select_function(ctx, name_meta, select, &struct_name, scope)?;
    Ok(())
}

/// Generate a flat row struct that matches the SQL result columns exactly.
///
/// This struct is used with `from_row()` to deserialize each database row,
/// then transformed into the nested result struct.
///
/// For a query like:
/// ```text
/// ProductDetails @select{
///     from product
///     fields { id, handle, variants @rel{ from product_variant, fields { id, sku } } }
/// }
/// ```
///
/// Generates:
/// ```text
/// struct ProductDetailsRow {
///     id: i64,
///     handle: String,
///     variants_id: Option<i64>,    // Option because LEFT JOIN
///     variants_sku: Option<String>,
/// }
/// ```
fn generate_flat_row_struct(
    ctx: &CodegenContext,
    select: &Select,
    struct_name: &str,
    table: &Meta<dibs_sql::TableName>,
    scope: &mut Scope,
) -> Result<(), QError> {
    let mut st = Struct::new(struct_name);
    // Internal struct - not pub
    st.derive("Debug");
    st.derive("Clone");
    st.derive("Facet");
    st.attr("facet(crate = dibs_runtime::facet)");

    let table_name = table.value.as_str();
    ctx.require_table(table_name, table.span)?;

    if let Some(select_fields) = &select.fields {
        // Add root table columns
        add_flat_fields_for_select(ctx, &mut st, table_name, "", select_fields)?;
    }

    scope.push_struct(st);
    Ok(())
}

/// Recursively add fields to the flat row struct for a SelectFields.
fn add_flat_fields_for_select(
    ctx: &CodegenContext,
    st: &mut Struct,
    table_name: &str,
    prefix: &str,
    select_fields: &SelectFields,
) -> Result<(), QError> {
    for (field_name_meta, field_def) in &select_fields.fields {
        let field_name = field_name_meta.value.as_str();

        match field_def {
            None => {
                // Simple column
                let rust_ty = ctx.column_type_at(table_name, field_name, field_name_meta.span)?;

                let flat_field_name = if prefix.is_empty() {
                    field_name.to_string()
                } else {
                    format!("{}_{}", prefix, field_name)
                };

                // If we're in a relation (prefix is not empty), wrap in Option for LEFT JOIN
                let final_ty = if prefix.is_empty() {
                    rust_ty
                } else if rust_ty.starts_with("Option<") {
                    // Already optional
                    rust_ty
                } else {
                    format!("Option<{}>", rust_ty)
                };

                // Use rename attribute since field names with underscores need to match SQL aliases
                st.field(&flat_field_name, &final_ty);
            }
            Some(FieldDef::Rel(rel)) => {
                // Recurse into relation
                let rel_table = rel.table_name().unwrap_or(field_name);
                let rel_span = rel
                    .from
                    .as_ref()
                    .map(|m| m.span)
                    .unwrap_or(field_name_meta.span);
                ctx.require_table(rel_table, rel_span)?;
                let new_prefix = if prefix.is_empty() {
                    field_name.to_string()
                } else {
                    format!("{}_{}", prefix, field_name)
                };

                if let Some(rel_fields) = &rel.fields {
                    add_flat_fields_for_select(ctx, st, rel_table, &new_prefix, rel_fields)?;
                }
            }
            Some(FieldDef::Count(_)) => {
                // COUNT subquery result
                let flat_field_name = if prefix.is_empty() {
                    field_name.to_string()
                } else {
                    format!("{}_{}", prefix, field_name)
                };
                st.field(&flat_field_name, "i64");
            }
        }
    }
    Ok(())
}

fn generate_raw_sql_result_struct(struct_name: &str, returns: &Returns, scope: &mut Scope) {
    let mut st = Struct::new(struct_name);
    st.vis("pub");
    st.derive("Debug");
    st.derive("Clone");
    st.derive("Facet");
    st.attr("facet(crate = dibs_runtime::facet)");

    for (field_name_meta, param_type) in &returns.fields {
        let field_name = field_name_meta.value.as_str();
        let rust_ty = param_type_to_rust(param_type);
        st.field(format!("pub {}", field_name), &rust_ty);
    }

    scope.push_struct(st);
}

fn generate_result_struct(
    ctx: &CodegenContext,
    select: &Select,
    name_meta: &Meta<String>,
    struct_name: &str,
    table: &Meta<dibs_sql::TableName>,
    scope: &mut Scope,
) -> Result<(), QError> {
    let mut st = Struct::new(struct_name);
    st.vis("pub");
    st.derive("Debug");
    st.derive("Clone");
    st.derive("Facet");
    st.attr("facet(crate = dibs_runtime::facet)");

    // Regular query - use select fields
    let parent_prefix = &name_meta.value;
    let table_name = table.value.as_str();
    // Resolve the table once up front so a missing/empty schema is reported
    // against the `from` clause rather than the first selected column.
    ctx.require_table(table_name, table.span)?;

    if let Some(select_fields) = &select.fields {
        for (field_name_meta, field_def) in &select_fields.fields {
            let field_name = field_name_meta.value.as_str();
            match field_def {
                None => {
                    // Simple column
                    let rust_ty =
                        ctx.column_type_at(table_name, field_name, field_name_meta.span)?;
                    st.field(format!("pub {}", field_name), &rust_ty);
                }
                Some(FieldDef::Rel(rel)) => {
                    let nested_name = format!("{}{}", parent_prefix, to_pascal_case(field_name));
                    let ty = if rel.first.is_some() {
                        format!("Option<{}>", nested_name)
                    } else {
                        format!("Vec<{}>", nested_name)
                    };
                    st.field(format!("pub {}", field_name), &ty);
                }
                Some(FieldDef::Count(_)) => {
                    st.field(format!("pub {}", field_name), "i64");
                }
            }
        }
    }

    scope.push_struct(st);

    // Generate nested structs for relations (recursively)
    if let Some(select_fields) = &select.fields {
        generate_nested_structs(ctx, parent_prefix, select_fields, scope)?;
    }
    Ok(())
}

/// Recursively generate structs for nested relations.
///
/// `parent_prefix` is used to namespace the struct names to avoid collisions
/// when multiple queries have relations with the same field name.
fn generate_nested_structs(
    ctx: &CodegenContext,
    parent_prefix: &str,
    select_fields: &SelectFields,
    scope: &mut Scope,
) -> Result<(), QError> {
    for (field_name_meta, field_def) in &select_fields.fields {
        if let Some(FieldDef::Rel(rel)) = field_def {
            let field_name = field_name_meta.value.as_str();
            let nested_name = format!("{}{}", parent_prefix, to_pascal_case(field_name));
            let rel_table = rel.table_name().unwrap_or(field_name);
            let rel_span = rel
                .from
                .as_ref()
                .map(|m| m.span)
                .unwrap_or(field_name_meta.span);
            ctx.require_table(rel_table, rel_span)?;

            let mut nested_st = Struct::new(&nested_name);
            nested_st.vis("pub");
            nested_st.derive("Debug");
            nested_st.derive("Clone");
            nested_st.derive("Facet");
            nested_st.attr("facet(crate = dibs_runtime::facet)");

            if let Some(rel_fields) = &rel.fields {
                for (rel_field_name_meta, rel_field_def) in &rel_fields.fields {
                    let rel_field_name = rel_field_name_meta.value.as_str();
                    match rel_field_def {
                        None => {
                            // Simple column
                            let rust_ty = ctx.column_type_at(
                                rel_table,
                                rel_field_name,
                                rel_field_name_meta.span,
                            )?;
                            nested_st.field(format!("pub {}", rel_field_name), &rust_ty);
                        }
                        Some(FieldDef::Rel(nested_rel)) => {
                            // Nested relation field - namespace with current struct name
                            let nested_rel_name =
                                format!("{}{}", nested_name, to_pascal_case(rel_field_name));
                            let ty = if nested_rel.first.is_some() {
                                format!("Option<{}>", nested_rel_name)
                            } else {
                                format!("Vec<{}>", nested_rel_name)
                            };
                            nested_st.field(format!("pub {}", rel_field_name), &ty);
                        }
                        Some(FieldDef::Count(_)) => {
                            nested_st.field(format!("pub {}", rel_field_name), "i64");
                        }
                    }
                }
            }

            scope.push_struct(nested_st);

            // Recursively generate structs for nested relations
            if let Some(rel_fields) = &rel.fields {
                generate_nested_structs(ctx, &nested_name, rel_fields, scope)?;
            }
        }
    }
    Ok(())
}

fn generate_select_function(
    ctx: &CodegenContext,
    name_meta: &Meta<String>,
    query: &Select,
    struct_name: &str,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);

    let return_ty = if query.first.is_some() {
        format!("Result<Option<{}>, QueryError>", struct_name)
    } else {
        format!("Result<Vec<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");
    // Allow clone_on_copy since we generate .clone() calls on parent IDs that might be Copy types
    func.attr("allow(clippy::clone_on_copy)");

    if let Some(params) = &query.params {
        for (param_name_meta, param_type) in &params.params {
            let param_name = &param_name_meta.value;
            let rust_ty = param_type_to_rust(param_type);
            func.arg(param_name, format!("&{}", rust_ty));
        }
    }

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    // Generate function body
    let body = if let Some(raw_sql_meta) = &query.sql {
        block_to_string(&generate_raw_query_body(query, &raw_sql_meta.value))
    } else {
        generate_query_body(ctx, query, struct_name)?
    };
    func.line(wrap_with_trace_err(&body, &fn_name));

    scope.push_fn(func);
    Ok(())
}

/// Generate query body for all queries (with or without JOINs).
///
/// For queries without relations: use `from_row()` directly into the result struct.
/// For queries with relations: deserialize into flat row struct, then transform.
fn generate_query_body(
    ctx: &CodegenContext,
    query: &Select,
    struct_name: &str,
) -> Result<String, QError> {
    let sqlgen_ctx = ctx.sqlgen_ctx();
    let generated = match crate::sqlgen::generate_select_sql(&sqlgen_ctx, query) {
        Ok(g) => g,
        Err(e) => {
            panic!("SELECT SQL generation failed: {}", e);
        }
    };

    let mut block = Block::new("");

    // SQL constant
    block.line(format!("const SQL: &str = r#\"{}\"#;", generated.sql));
    block.line("");

    // Build params array - filter out literal placeholders
    let params: Vec<_> = generated
        .param_order
        .iter()
        .filter(|p| !p.as_str().starts_with("__literal_"))
        .collect();

    if params.is_empty() {
        block.line("let rows = client.query(SQL, &[]).await?;");
    } else {
        let params_str = params
            .iter()
            .map(|p| p.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        block.line(format!(
            "let rows = client.query(SQL, &[{}]).await?;",
            params_str
        ));
    }

    // If no relations, use from_row() directly into the result struct
    if !query.has_relations() {
        if query.first.is_some() {
            let mut match_block = Block::new("match rows.into_iter().next()");
            match_block.line("Some(row) => Ok(Some(from_row(&row)?)),");
            match_block.line("None => Ok(None),");
            block.push_block(match_block);
        } else {
            block.line("rows.iter().map(|row| Ok(from_row(row)?)).collect()");
        }
        return Ok(block_to_string(&block));
    }

    // For queries with relations, deserialize into flat row struct then transform
    let query_name = struct_name.strip_suffix("Result").unwrap_or(struct_name);
    let flat_struct_name = format!("{}Row", query_name);

    block.line("");
    block.line("// Deserialize all rows into flat structs using facet reflection");
    block.line(format!(
        "let flat_rows: Vec<{flat_struct_name}> = rows.iter().map(from_row).collect::<Result<Vec<_>, _>>()?;"
    ));
    block.line("");

    // Generate the transformation from flat rows to nested result
    let Some(select_fields) = &query.fields else {
        // No fields - shouldn't happen for queries with relations
        block.line("Ok(vec![])".to_string());
        return Ok(block_to_string(&block));
    };

    let root_table = query
        .from
        .as_ref()
        .map(|m| m.value.as_str())
        .unwrap_or("unknown");
    let is_first = query.is_first();

    block.line(generate_flat_to_nested_transform(
        ctx,
        select_fields,
        struct_name,
        root_table,
        is_first,
    )?);

    Ok(block_to_string(&block))
}

/// Generate code to transform flat rows into nested result structs.
fn generate_flat_to_nested_transform(
    ctx: &CodegenContext,
    select_fields: &SelectFields,
    struct_name: &str,
    root_table: &str,
    is_first: bool,
) -> Result<String, QError> {
    let mut block = Block::new("");

    // Find the ID column for grouping (typically "id")
    let id_column = select_fields
        .id_column()
        .map(|c| c.to_string())
        .unwrap_or_else(|| "id".to_string());

    let id_type = ctx
        .column_type(root_table, &id_column)
        .unwrap_or_else(|| "i64".to_string());

    // Determine if we need grouping (Vec relations) or simple mapping (Option relations only)
    if select_fields.has_vec_relations() {
        // Group by parent ID for Vec relations
        block.line("// Group flat rows by parent ID and assemble nested structs");
        block.line(format!(
            "let mut grouped: std::collections::HashMap<{id_type}, {struct_name}> = std::collections::HashMap::new();"
        ));

        // Track seen relation IDs to avoid duplicates from JOINs
        generate_seen_id_declarations(&mut block, ctx, select_fields, &id_type, "")?;

        block.line("");

        let mut for_block = Block::new("for flat_row in flat_rows");
        for_block.line(format!("let parent_id = flat_row.{id_column}.clone();"));
        for_block.line("");

        // Get or create the entry
        let mut entry_block = Block::new(format!(
            "let entry = grouped.entry(parent_id.clone()).or_insert_with(|| {struct_name}"
        ));

        // Add root columns
        for (field_name_meta, field_def) in &select_fields.fields {
            let field_name = field_name_meta.value.as_str();
            match field_def {
                None => {
                    entry_block.line(format!("{field_name}: flat_row.{field_name}.clone(),"));
                }
                Some(FieldDef::Rel(rel)) => {
                    if rel.is_first() {
                        entry_block.line(format!("{field_name}: None,"));
                    } else {
                        entry_block.line(format!("{field_name}: Vec::new(),"));
                    }
                }
                Some(FieldDef::Count(_)) => {
                    entry_block.line(format!("{field_name}: flat_row.{field_name},"));
                }
            }
        }
        entry_block.after(");");
        for_block.push_block(entry_block);
        for_block.line("");

        // Add relations
        let parent_prefix = struct_name.strip_suffix("Result").unwrap_or(struct_name);
        generate_relation_assembly(
            &mut for_block,
            ctx,
            select_fields,
            parent_prefix,
            "",
            &id_type,
        )?;

        block.push_block(for_block);
        block.line("");

        if is_first {
            block.line("Ok(grouped.into_values().next())");
        } else {
            block.line("Ok(grouped.into_values().collect())");
        }
    } else {
        // Option-only relations - each row becomes one result
        block.line("// Transform flat rows into nested structs (Option relations only)");

        let mut map_block = Block::new(
            "let results: Result<Vec<_>, QueryError> = flat_rows.into_iter().map(|flat_row| {",
        );

        let mut result_block = Block::new(format!("Ok({struct_name}"));
        let parent_prefix = struct_name.strip_suffix("Result").unwrap_or(struct_name);

        for (field_name_meta, field_def) in &select_fields.fields {
            let field_name = field_name_meta.value.as_str();
            match field_def {
                None => {
                    result_block.line(format!("{field_name}: flat_row.{field_name},"));
                }
                Some(FieldDef::Rel(rel)) => {
                    if rel.is_first() {
                        // Option relation - check if first column is Some
                        if let Some(rel_fields) = &rel.fields {
                            let rel_table = rel.table_name().unwrap_or(field_name);
                            let first_col = rel_fields
                                .first_column()
                                .map(|c| c.as_str())
                                .unwrap_or("id");
                            let first_alias = format!("{field_name}_{first_col}");
                            let nested_struct =
                                format!("{}{}", parent_prefix, to_pascal_case(field_name));

                            let mut map_inner = Block::new(format!(
                                "{field_name}: flat_row.{first_alias}.as_ref().map(|_| {nested_struct}"
                            ));

                            for (inner_field_meta, inner_def) in &rel_fields.fields {
                                let inner_name = inner_field_meta.value.as_str();
                                if inner_def.is_none() {
                                    let alias = format!("{field_name}_{inner_name}");
                                    let rust_ty = ctx.column_type_at(
                                        rel_table,
                                        inner_name,
                                        inner_field_meta.span,
                                    )?;

                                    // Unwrap the Option from LEFT JOIN
                                    if rust_ty.starts_with("Option<") {
                                        map_inner.line(format!(
                                            "{inner_name}: flat_row.{alias}.clone(),"
                                        ));
                                    } else {
                                        map_inner.line(format!(
                                            "{inner_name}: flat_row.{alias}.clone().expect(\"non-null column from LEFT JOIN\"),"
                                        ));
                                    }
                                }
                            }

                            map_inner.after("),");
                            result_block.push_block(map_inner);
                        }
                    } else {
                        // Vec relation in option-only assembly - shouldn't happen
                        result_block.line(format!("{field_name}: Vec::new(),"));
                    }
                }
                Some(FieldDef::Count(_)) => {
                    result_block.line(format!("{field_name}: flat_row.{field_name},"));
                }
            }
        }

        result_block.after(")");
        map_block.push_block(result_block);
        map_block.after("}).collect();");
        block.push_block(map_block);
        block.line("");

        if is_first {
            block.line("results.map(|mut v| v.pop())");
        } else {
            block.line("results");
        }
    }

    Ok(block_to_string(&block))
}

/// Generate declarations for tracking seen relation IDs (for deduplication).
fn generate_seen_id_declarations(
    block: &mut Block,
    ctx: &CodegenContext,
    select_fields: &SelectFields,
    parent_id_type: &str,
    prefix: &str,
) -> Result<(), QError> {
    for (field_name_meta, field_def) in &select_fields.fields {
        if let Some(FieldDef::Rel(rel)) = field_def {
            let field_name = field_name_meta.value.as_str();
            if !rel.is_first() {
                // Vec relation needs deduplication
                if let Some(rel_fields) = &rel.fields {
                    let rel_table = rel.table_name().unwrap_or(field_name);
                    let id_col = rel_fields.id_column().map(|c| c.as_str()).unwrap_or("id");
                    let id_type = ctx
                        .column_type(rel_table, id_col)
                        .unwrap_or_else(|| "i64".to_string());

                    let set_name = if prefix.is_empty() {
                        format!("seen_{field_name}")
                    } else {
                        format!("seen_{prefix}_{field_name}")
                    };

                    block.line(format!(
                        "let mut {set_name}: std::collections::HashSet<({parent_id_type}, {id_type})> = std::collections::HashSet::new();"
                    ));

                    // Recurse for nested Vec relations
                    let new_prefix = if prefix.is_empty() {
                        field_name.to_string()
                    } else {
                        format!("{prefix}_{field_name}")
                    };

                    // For nested relations, the parent ID is now this relation's ID
                    generate_seen_id_declarations(block, ctx, rel_fields, &id_type, &new_prefix)?;
                }
            }
        }
    }
    Ok(())
}

/// Generate code to assemble relations from flat row data.
fn generate_relation_assembly(
    for_block: &mut Block,
    ctx: &CodegenContext,
    select_fields: &SelectFields,
    parent_prefix: &str,
    flat_prefix: &str,
    _parent_id_type: &str,
) -> Result<(), QError> {
    for (field_name_meta, field_def) in &select_fields.fields {
        if let Some(FieldDef::Rel(rel)) = field_def {
            let field_name = field_name_meta.value.as_str();
            let rel_table = rel.table_name().unwrap_or(field_name);
            let nested_struct = format!("{}{}", parent_prefix, to_pascal_case(field_name));

            let flat_field_prefix = if flat_prefix.is_empty() {
                field_name.to_string()
            } else {
                format!("{flat_prefix}_{field_name}")
            };

            if let Some(rel_fields) = &rel.fields {
                let first_col = rel_fields
                    .first_column()
                    .map(|c| c.as_str())
                    .unwrap_or("id");
                let id_col = rel_fields
                    .id_column()
                    .map(|c| c.as_str())
                    .unwrap_or(first_col);
                let id_alias = format!("{flat_field_prefix}_{id_col}");

                if rel.is_first() {
                    // Option relation
                    for_block.line(format!("// Populate {field_name} (Option relation)"));

                    let mut if_block = Block::new(format!(
                        "if entry.{field_name}.is_none() && flat_row.{id_alias}.is_some()"
                    ));

                    let mut some_block =
                        Block::new(format!("entry.{field_name} = Some({nested_struct}"));
                    generate_relation_fields(
                        &mut some_block,
                        ctx,
                        rel_fields,
                        rel_table,
                        &flat_field_prefix,
                    )?;
                    some_block.after(");");
                    if_block.push_block(some_block);

                    for_block.push_block(if_block);
                    for_block.line("");
                } else {
                    // Vec relation with deduplication
                    let set_name = if flat_prefix.is_empty() {
                        format!("seen_{field_name}")
                    } else {
                        format!("seen_{flat_prefix}_{field_name}")
                    };

                    for_block.line(format!("// Append to {field_name} (Vec relation)"));

                    let mut if_block =
                        Block::new(format!("if let Some(ref rel_id) = flat_row.{id_alias}"));
                    if_block.line("let key = (parent_id.clone(), rel_id.clone());".to_string());

                    let mut if_insert = Block::new(format!("if {set_name}.insert(key)"));
                    let mut push_block =
                        Block::new(format!("entry.{field_name}.push({nested_struct}"));
                    generate_relation_fields(
                        &mut push_block,
                        ctx,
                        rel_fields,
                        rel_table,
                        &flat_field_prefix,
                    )?;
                    push_block.after(");");
                    if_insert.push_block(push_block);

                    if_block.push_block(if_insert);
                    for_block.push_block(if_block);
                    for_block.line("");
                }
            }
        }
    }
    Ok(())
}

/// Generate field assignments for a relation struct.
fn generate_relation_fields(
    block: &mut Block,
    ctx: &CodegenContext,
    select_fields: &SelectFields,
    table_name: &str,
    flat_prefix: &str,
) -> Result<(), QError> {
    for (field_name_meta, field_def) in &select_fields.fields {
        let field_name = field_name_meta.value.as_str();
        let alias = format!("{flat_prefix}_{field_name}");

        match field_def {
            None => {
                let rust_ty = ctx.column_type_at(table_name, field_name, field_name_meta.span)?;

                // Flat struct has Option<T> for relation columns due to LEFT JOIN
                // Need to unwrap unless the original type was already Option
                if rust_ty.starts_with("Option<") {
                    block.line(format!("{field_name}: flat_row.{alias}.clone(),"));
                } else {
                    block.line(format!(
                        "{field_name}: flat_row.{alias}.clone().expect(\"non-null from LEFT JOIN\"),"
                    ));
                }
            }
            Some(FieldDef::Rel(rel)) => {
                if rel.is_first() {
                    block.line(format!(
                        "{field_name}: None, // TODO: nested Option relation"
                    ));
                } else {
                    block.line(format!(
                        "{field_name}: Vec::new(), // TODO: nested Vec relation"
                    ));
                }
            }
            Some(FieldDef::Count(_)) => {
                block.line(format!("{field_name}: flat_row.{alias},"));
            }
        }
    }
    Ok(())
}

fn generate_raw_query_body(query: &Select, raw_sql: &str) -> Block {
    let cleaned: String = raw_sql
        .lines()
        .map(|l| l.trim())
        .collect::<Vec<_>>()
        .join("\n");

    let mut block = Block::new("");

    // SQL constant
    block.line(format!("const SQL: &str = r#\"{}\"#;", cleaned.trim()));
    block.line("");

    // Query execution
    if let Some(params) = &query.params {
        let param_names: Vec<&str> = params.iter().map(|(meta, _)| meta.value.as_str()).collect();
        if !param_names.is_empty() {
            let params_str = param_names.join(", ");
            block.line(format!(
                "let rows = client.query(SQL, &[{}]).await?;",
                params_str
            ));
        } else {
            block.line("let rows = client.query(SQL, &[]).await?;");
        }
    } else {
        block.line("let rows = client.query(SQL, &[]).await?;");
    }

    // Result processing
    if query.first.is_some() {
        let mut match_block = Block::new("match rows.into_iter().next()");
        match_block.line("Some(row) => Ok(Some(from_row(&row)?)),");
        match_block.line("None => Ok(None),");
        block.push_block(match_block);
    } else {
        block.line("rows.iter().map(|row| Ok(from_row(row)?)).collect()");
    }

    block
}

fn param_type_to_rust(ty: &dibs_query_schema::ParamType) -> String {
    use dibs_query_schema::ParamType;
    match ty {
        ParamType::String => "String".to_string(),
        ParamType::Int => "i64".to_string(),
        ParamType::Float => "f64".to_string(),
        ParamType::Bool => "bool".to_string(),
        ParamType::Uuid => "Uuid".to_string(),
        ParamType::Decimal => "Decimal".to_string(),
        ParamType::Timestamp => "Timestamp".to_string(),
        ParamType::Bytes => "Vec<u8>".to_string(),
        // JSONB params travel over the wire as JSON-encoded text and
        // get cast `::jsonb` at the binding site (see sqlgen). The
        // caller-facing type is therefore plain `String` — the same
        // shape they'd produce from `facet_json::to_string`, an axum
        // body, or a webhook delivery.
        ParamType::Jsonb => "String".to_string(),
        ParamType::Optional(inner_vec) => {
            if let Some(inner) = inner_vec.first() {
                format!("Option<{}>", param_type_to_rust(inner))
            } else {
                "Option<String>".to_string()
            }
        }
    }
}

/// Helper to format a Block to a String.
fn block_to_string(block: &Block) -> String {
    let mut output = String::new();
    let mut formatter = codegen::Formatter::new(&mut output);
    block.fmt(&mut formatter).expect("formatting failed");
    output
}

fn to_pascal_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    result
}

fn to_snake_case(s: &str) -> String {
    let mut result = String::new();

    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }

    result
}

// ============================================================================
// Mutation code generation
// ============================================================================

fn generate_insert_code(
    _ctx: &CodegenContext,
    name_meta: &Meta<String>,
    insert: &Insert,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);
    let generated = crate::sqlgen::generate_insert_sql(insert);

    // Generate result struct if RETURNING is used
    let has_returning = insert.returning.is_some();
    let return_ty = if !has_returning {
        "Result<u64, QueryError>".to_string()
    } else {
        let struct_name = format!("{}Result", name);
        if let Some(returning) = &insert.returning {
            generate_mutation_result_struct(
                _ctx,
                &struct_name,
                insert.into.value.as_str(),
                insert.into.span,
                returning,
                scope,
            )?;
        }
        format!("Result<Option<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");

    if let Some(params) = &insert.params {
        for (param_name_meta, param_type) in &params.params {
            let param_name = param_name_meta.value.as_str();
            let rust_ty = param_type_to_rust(param_type);
            func.arg(param_name, format!("&{}", rust_ty));
        }
    }

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    let body = generate_mutation_body(&generated.sql, &generated.params, !has_returning);
    func.line(wrap_with_trace_err(&block_to_string(&body), &fn_name));

    scope.push_fn(func);
    Ok(())
}

fn generate_upsert_code(
    _ctx: &CodegenContext,
    name_meta: &Meta<String>,
    upsert: &Upsert,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);
    let generated = crate::sqlgen::generate_upsert_sql(upsert);

    let has_returning = upsert.returning.is_some();
    let return_ty = if !has_returning {
        "Result<u64, QueryError>".to_string()
    } else {
        let struct_name = format!("{}Result", name);
        if let Some(returning) = &upsert.returning {
            generate_mutation_result_struct(
                _ctx,
                &struct_name,
                upsert.into.value.as_str(),
                upsert.into.span,
                returning,
                scope,
            )?;
        }
        format!("Result<Option<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");

    if let Some(params) = &upsert.params {
        for (param_name_meta, param_type) in &params.params {
            let param_name = param_name_meta.value.as_str();
            let rust_ty = param_type_to_rust(param_type);
            func.arg(param_name, format!("&{}", rust_ty));
        }
    }

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    let body = generate_mutation_body(&generated.sql, &generated.params, !has_returning);
    func.line(wrap_with_trace_err(&block_to_string(&body), &fn_name));

    scope.push_fn(func);
    Ok(())
}

fn generate_insert_many_code(
    ctx: &CodegenContext,
    name_meta: &Meta<String>,
    insert: &InsertMany,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);
    let generated = crate::sqlgen::generate_insert_many_sql(insert);

    // Generate params struct
    let params_struct_name = format!("{}Params", name);
    if let Some(params) = &insert.params {
        generate_bulk_params_struct(
            ctx,
            &params_struct_name,
            insert.into.value.as_str(),
            params,
            scope,
        );
    }

    // Generate result struct if RETURNING is used
    let has_returning = insert.returning.is_some();
    let return_ty = if !has_returning {
        "Result<u64, QueryError>".to_string()
    } else {
        let struct_name = format!("{}Result", name);
        if let Some(returning) = &insert.returning {
            generate_mutation_result_struct(
                ctx,
                &struct_name,
                insert.into.value.as_str(),
                insert.into.span,
                returning,
                scope,
            )?;
        }
        format!("Result<Vec<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");
    func.arg("items", format!("&[{}]", params_struct_name));

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    let body = generate_bulk_mutation_body(&generated.sql, insert.params.as_ref(), !has_returning);
    func.line(wrap_with_trace_err(&block_to_string(&body), &fn_name));

    scope.push_fn(func);
    Ok(())
}

fn generate_upsert_many_code(
    ctx: &CodegenContext,
    name_meta: &Meta<String>,
    upsert: &UpsertMany,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);
    let generated = crate::sqlgen::generate_upsert_many_sql(upsert);

    // Generate params struct
    let params_struct_name = format!("{}Params", name);
    if let Some(params) = &upsert.params {
        generate_bulk_params_struct(
            ctx,
            &params_struct_name,
            upsert.into.value.as_str(),
            params,
            scope,
        );
    }

    // Generate result struct if RETURNING is used
    let has_returning = upsert.returning.is_some();
    let return_ty = if !has_returning {
        "Result<u64, QueryError>".to_string()
    } else {
        let struct_name = format!("{}Result", name);
        if let Some(returning) = &upsert.returning {
            generate_mutation_result_struct(
                ctx,
                &struct_name,
                upsert.into.value.as_str(),
                upsert.into.span,
                returning,
                scope,
            )?;
        }
        format!("Result<Vec<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");
    func.arg("items", format!("&[{}]", params_struct_name));

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    let body = generate_bulk_mutation_body(&generated.sql, upsert.params.as_ref(), !has_returning);
    func.line(wrap_with_trace_err(&block_to_string(&body), &fn_name));

    scope.push_fn(func);
    Ok(())
}

/// Generate a params struct for bulk operations.
fn generate_bulk_params_struct(
    ctx: &CodegenContext,
    struct_name: &str,
    table: &str,
    params: &Params,
    scope: &mut Scope,
) {
    let mut st = Struct::new(struct_name);
    st.vis("pub");
    st.derive("Debug");
    st.derive("Clone");

    for (param_name_meta, param_type) in &params.params {
        let param_name = param_name_meta.value.as_str();
        let rust_ty = ctx
            .column_type(table, param_name)
            .unwrap_or_else(|| param_type_to_rust(param_type));
        st.field(format!("pub {}", param_name), &rust_ty);
    }

    scope.push_struct(st);
}

/// Generate body for bulk mutation (INSERT MANY / UPSERT MANY).
fn generate_bulk_mutation_body(sql: &str, params: Option<&Params>, execute_only: bool) -> Block {
    let mut block = Block::new("");

    // SQL constant
    block.line(format!("const SQL: &str = r#\"{}\"#;", sql));
    block.line("");

    // Convert slice of structs to parallel arrays
    if let Some(params) = params {
        block.line("// Convert items to parallel arrays for UNNEST");
        for (param_name_meta, param_type) in &params.params {
            let param_name = param_name_meta.value.as_str();
            let rust_ty = param_type_to_rust(param_type);
            block.line(format!(
                "let {}_arr: Vec<{}> = items.iter().map(|i| i.{}.clone()).collect();",
                param_name, rust_ty, param_name
            ));
        }
        block.line("");

        // Build the params reference array
        let param_refs: Vec<String> = params
            .params
            .keys()
            .map(|p| format!("&{}_arr", p.value))
            .collect();

        if execute_only {
            // No RETURNING - use execute
            block.line(format!(
                "let affected = client.execute(SQL, &[{}]).await?;",
                param_refs.join(", ")
            ));
            block.line("Ok(affected)");
        } else {
            // Has RETURNING - use query
            block.line(format!(
                "let rows = client.query(SQL, &[{}]).await?;",
                param_refs.join(", ")
            ));
            block.line("rows.iter().map(|row| Ok(from_row(row)?)).collect()");
        }
    }

    block
}

fn generate_update_code(
    ctx: &CodegenContext,
    name_meta: &Meta<String>,
    update: &Update,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);
    let sqlgen_ctx = ctx.sqlgen_ctx();
    let generated = crate::sqlgen::generate_update_sql(&sqlgen_ctx, update)?;

    let has_returning = update.returning.is_some();
    let return_ty = if !has_returning {
        "Result<u64, QueryError>".to_string()
    } else {
        let struct_name = format!("{}Result", name);
        if let Some(returning) = &update.returning {
            generate_mutation_result_struct(
                ctx,
                &struct_name,
                update.table.value.as_str(),
                update.table.span,
                returning,
                scope,
            )?;
        }
        format!("Result<Option<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");

    if let Some(params) = &update.params {
        for (param_name_meta, param_type) in &params.params {
            let param_name = param_name_meta.value.as_str();
            let rust_ty = param_type_to_rust(param_type);
            func.arg(param_name, format!("&{}", rust_ty));
        }
    }

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    let body = generate_mutation_body(&generated.sql, &generated.params, !has_returning);
    func.line(wrap_with_trace_err(&block_to_string(&body), &fn_name));

    scope.push_fn(func);
    Ok(())
}

fn generate_delete_code(
    ctx: &CodegenContext,
    name_meta: &Meta<String>,
    delete: &Delete,
    scope: &mut Scope,
) -> Result<(), QError> {
    let name = &name_meta.value;
    let fn_name = to_snake_case(name);
    let sqlgen_ctx = ctx.sqlgen_ctx();
    let generated = crate::sqlgen::generate_delete_sql(&sqlgen_ctx, delete)?;

    let has_returning = delete.returning.is_some();
    let return_ty = if !has_returning {
        "Result<u64, QueryError>".to_string()
    } else {
        let struct_name = format!("{}Result", name);
        if let Some(returning) = &delete.returning {
            generate_mutation_result_struct(
                ctx,
                &struct_name,
                delete.from.value.as_str(),
                delete.from.span,
                returning,
                scope,
            )?;
        }
        format!("Result<Option<{}>, QueryError>", struct_name)
    };

    let mut func = Function::new(&fn_name);
    if let Some(doc) = &name_meta.doc {
        let doc_str = doc.join("\n");
        func.doc(&doc_str);
    }
    func.vis("pub");
    func.set_async(true);
    // Generated query fns take one arg per bound param; wide tables legitimately
    // exceed clippy's threshold. Harmless (no warning) on narrow queries.
    func.attr("allow(clippy::too_many_arguments)");
    func.generic("C");
    func.arg("client", "&C");

    if let Some(params) = &delete.params {
        for (param_name_meta, param_type) in &params.params {
            let param_name = param_name_meta.value.as_str();
            let rust_ty = param_type_to_rust(param_type);
            func.arg(param_name, format!("&{}", rust_ty));
        }
    }

    func.ret(&return_ty);
    func.bound("C", "tokio_postgres::GenericClient");

    let body = generate_mutation_body(&generated.sql, &generated.params, !has_returning);
    func.line(wrap_with_trace_err(&block_to_string(&body), &fn_name));

    scope.push_fn(func);
    Ok(())
}

fn generate_mutation_result_struct(
    ctx: &CodegenContext,
    struct_name: &str,
    table: &str,
    table_span: Span,
    returning: &Returning,
    scope: &mut Scope,
) -> Result<(), QError> {
    // Resolve the table once so a missing/empty schema is reported against the
    // mutation's table clause rather than the first RETURNING column.
    ctx.require_table(table, table_span)?;

    let mut st = Struct::new(struct_name);
    st.vis("pub");
    st.derive("Debug");
    st.derive("Clone");
    st.derive("Facet");
    st.attr("facet(crate = dibs_runtime::facet)");

    for (col_name_meta, _) in &returning.columns {
        let col_name = col_name_meta.value.as_str();
        let rust_ty = ctx.column_type_at(table, col_name, col_name_meta.span)?;
        st.field(format!("pub {col_name}"), &rust_ty);
    }

    scope.push_struct(st);
    Ok(())
}

fn generate_mutation_body(
    sql: &str,
    param_order: &[dibs_sql::ParamName],
    execute_only: bool,
) -> Block {
    let mut block = Block::new("");

    // SQL constant
    block.line(format!("const SQL: &str = r#\"{}\"#;", sql));
    block.line("");

    let params: Vec<_> = param_order
        .iter()
        .filter(|p| !p.as_str().starts_with("__literal_"))
        .collect();

    if execute_only {
        // No RETURNING - use execute
        if params.is_empty() {
            block.line("let affected = client.execute(SQL, &[]).await?;");
        } else {
            let params_str = params
                .iter()
                .map(|p| p.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            block.line(format!(
                "let affected = client.execute(SQL, &[{}]).await?;",
                params_str
            ));
        }
        block.line("Ok(affected)");
    } else {
        // Has RETURNING - use query
        if params.is_empty() {
            block.line("let rows = client.query(SQL, &[]).await?;");
        } else {
            let params_str = params
                .iter()
                .map(|p| p.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            block.line(format!(
                "let rows = client.query(SQL, &[{}]).await?;",
                params_str
            ));
        }
        let mut match_block = Block::new("match rows.into_iter().next()");
        match_block.line("Some(row) => Ok(Some(from_row(&row)?)),");
        match_block.line("None => Ok(None),");
        block.push_block(match_block);
    }

    block
}

#[cfg(test)]
mod tests;