scythe-codegen 0.20.0

Polyglot code generation backends for scythe
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
use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{composite_type_name, enum_type_name, enum_variant_name, fn_name, to_snake_case};
use scythe_backend::types::resolve_type;
use std::fmt::Write;

use scythe_core::analyzer::{AnalyzedQuery, CompositeInfo, EnumInfo};
use scythe_core::errors::{ErrorCode, ScytheError};
use scythe_core::parser::QueryCommand;

use crate::backend_options::reject_unknown_options;
use crate::backend_trait::{CodegenBackend, ResolvedColumn, ResolvedParam};
use crate::backends::typescript_common::parse_bool_option;

const DEFAULT_MANIFEST_TOML: &str = include_str!("../../manifests/rust-sibyl.toml");

pub struct RustSibylBackend {
    manifest: BackendManifest,
    /// When true, every generated struct/enum derives `serde::Serialize` and
    /// `serde::Deserialize` in addition to its base derives. Set via the
    /// `serde` backend option -- see [`Self::apply_options`].
    serde: bool,
    /// Extra derive macros appended after the base derives (and after serde,
    /// when enabled) on every generated struct/enum. Set via the `derive`
    /// backend option -- see [`Self::apply_options`].
    extra_derives: Vec<String>,
}

impl RustSibylBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        match engine {
            "oracle" => {}
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InvalidConfig,
                    format!("rust-sibyl only supports Oracle, got engine '{}'", engine),
                ));
            }
        }
        let manifest = super::parse_manifest(DEFAULT_MANIFEST_TOML)?;
        Ok(Self {
            manifest,
            serde: false,
            extra_derives: Vec::new(),
        })
    }

    /// Build the derive line for structs, incorporating serde and extra derives.
    fn struct_derives(&self) -> String {
        let mut derives = vec!["Debug", "Clone"];
        if self.serde {
            derives.push("serde::Serialize");
            derives.push("serde::Deserialize");
        }
        for d in &self.extra_derives {
            derives.push(d);
        }
        format!("#[derive({})]", derives.join(", "))
    }

    /// Build the derive line for enums. Unlike tokio-postgres/tiberius, the
    /// base here is `PartialEq` only (no `Eq`) -- matching the pre-existing
    /// non-configurable derive this replaces, which never had `Eq` either.
    fn enum_derives(&self) -> String {
        let mut derives = vec!["Debug", "Clone", "PartialEq"];
        if self.serde {
            derives.push("serde::Serialize");
            derives.push("serde::Deserialize");
        }
        for d in &self.extra_derives {
            derives.push(d);
        }
        format!("#[derive({})]", derives.join(", "))
    }

    /// Build the sibyl 0.7 `execute`/`query` args expression for IN params.
    /// Single param: `(":NAME", val)` — no outer tuple needed (it IS a (&str, T)).
    /// Multiple params: `((":A", a), (":B", b))`.
    /// Zero params: `()`.
    fn build_in_args(params: &[ResolvedParam]) -> String {
        match params.len() {
            0 => "()".to_string(),
            1 => format!(
                "(\"{}\", {})",
                Self::named_placeholder(&params[0].field_name),
                params[0].field_name
            ),
            _ => {
                let pairs: Vec<String> = params
                    .iter()
                    .map(|p| format!("(\"{}\", {})", Self::named_placeholder(&p.field_name), p.field_name))
                    .collect();
                format!("({})", pairs.join(", "))
            }
        }
    }

    /// `:PARAM_NAME` — named placeholder used in SQL for IN params.
    fn named_placeholder(field_name: &str) -> String {
        format!(":{}", field_name.to_uppercase())
    }

    /// `:OUT_COL_NAME` — named placeholder used in SQL for RETURNING INTO OUT params.
    fn out_named_placeholder(field_name: &str) -> String {
        format!(":OUT_{}", field_name.to_uppercase())
    }

    /// Rewrite positional `:N` placeholders in SQL to named `:PARAM_NAME` form.
    fn sql_with_named_params(sql: &str, params: &[ResolvedParam]) -> String {
        let mut result = sql.to_string();
        for (i, p) in params.iter().enumerate().rev() {
            let positional = format!(":{}", i + 1);
            let named = format!(":{}", p.field_name.to_uppercase());
            result = result.replace(&positional, &named);
        }
        result
    }

    /// Build the RETURNING INTO clause and the full SQL for a RETURNING DML.
    /// Returns the full SQL including RETURNING ... INTO :OUT_COL_NAME ...
    fn sql_with_returning(base_sql: &str, columns: &[ResolvedColumn]) -> String {
        let out_names: Vec<String> = columns
            .iter()
            .map(|c| format!(":OUT_{}", c.field_name.to_uppercase()))
            .collect();
        let upper = base_sql.to_uppercase();
        if let Some(ret_pos) = upper.find("RETURNING") {
            let prefix = &base_sql[..ret_pos];
            let rest = &base_sql[ret_pos + "RETURNING".len()..];
            let col_list = if let Some(into_pos) = rest.to_uppercase().find(" INTO ") {
                rest[..into_pos].trim()
            } else {
                rest.trim()
            };
            format!("{}RETURNING {} INTO {}", prefix, col_list, out_names.join(", "))
        } else {
            base_sql.to_string()
        }
    }

    /// Emit the variable declaration for a RETURNING INTO out variable.
    /// sibyl 0.7 accepts `&mut` primitive types (i64, f64, String) and sibyl types (Date, Number).
    /// For dates: declare a `Date::new(session)` placeholder.
    /// For int64: use i64 directly (Oracle NUMBER → SQLT_INT).
    /// For float/decimal: use f64 (Oracle NUMBER → SQLT_BDOUBLE).
    fn emit_out_var_decl_typed(col: &ResolvedColumn) -> String {
        match col.neutral_type.as_str() {
            "int16" | "int32" | "int64" => {
                format!("    let mut out_{}: i64 = 0;", col.field_name)
            }
            "float32" | "float64" | "decimal" => {
                format!("    let mut out_{}: f64 = 0.0;", col.field_name)
            }
            "date" | "datetime" | "datetime_tz" => {
                format!("    let mut out_{} = Date::new(session);", col.field_name)
            }
            _ => {
                // sibyl sizes the OCI out-buffer from the String's capacity; a zero-capacity
                // String silently truncates the returned value. 4000 bytes covers Oracle's
                // standard VARCHAR2 maximum.
                format!("    let mut out_{} = String::with_capacity(4000);", col.field_name)
            }
        }
    }

    /// For RETURNING args, get the `&mut var` expression for the out column.
    fn out_var_ref_for_returning(col: &ResolvedColumn) -> String {
        format!("&mut out_{}", col.field_name)
    }

    /// Emit the post-execute conversion from the `out_*` var to the struct field type.
    fn emit_out_var_conversion(col: &ResolvedColumn) -> String {
        match col.neutral_type.as_str() {
            "int16" => format!("    let {} = out_{} as i16;", col.field_name, col.field_name),
            "int32" => format!("    let {} = out_{} as i32;", col.field_name, col.field_name),
            "int64" => format!("    let {} = out_{};", col.field_name, col.field_name),
            "float32" => format!("    let {} = out_{} as f32;", col.field_name, col.field_name),
            "float64" | "decimal" => {
                format!("    let {} = out_{};", col.field_name, col.field_name)
            }
            "date" | "datetime" | "datetime_tz" => {
                format!(
                    "    let {name} = {{ let (y, mo, d, h, mi, s) = out_{name}.date_and_time(); chrono::NaiveDate::from_ymd_opt(y as i32, mo as u32, d as u32).and_then(|dt| dt.and_hms_opt(h as u32, mi as u32, s as u32)).expect(\"invalid date from Oracle\") }};",
                    name = col.field_name
                )
            }
            _ => {
                if col.nullable {
                    format!(
                        "    let {name} = if stmt.is_null(\"{placeholder}\")? {{ None }} else {{ Some(out_{name}) }};",
                        name = col.field_name,
                        placeholder = Self::out_named_placeholder(&col.field_name)
                    )
                } else {
                    format!("    let {} = out_{};", col.field_name, col.field_name)
                }
            }
        }
    }

    /// Emit the row.get() call for a SELECT column.
    /// sibyl 0.7's FromSql supports: String, &str, integers (via Integer trait), f32, f64,
    /// Date<'_>, Timestamp<'_>, etc. — but NOT chrono::NaiveDateTime.
    /// For date/datetime: get as Date<'_> then convert via date_and_time().
    /// decimal maps to f64 in the manifest (OCI NUMBER → SQLT_BDOUBLE), so it's handled as float.
    ///
    /// Oracle LOB columns need special handling: sibyl's `FromSql<String>` only matches
    /// `ColumnBuffer::Text` (VARCHAR2/CHAR) — a CLOB/NCLOB/BLOB/BFILE column's buffer is a
    /// LOB locator (`ColumnBuffer::CLOB`/`ColumnBuffer::BLOB`/...) and reading it via
    /// `row.get::<String, _>(i)` fails at runtime with `Interface("cannot return as a
    /// String")`. Every one of these four types must be fetched as a LOB locator and its
    /// content read explicitly. `neutral_type` alone can't distinguish this (CLOB and
    /// VARCHAR2 both resolve to `"string"`; BLOB and BFILE both resolve to `"bytes"`), so
    /// this matches on `sql_type`, the raw source SQL type.
    fn emit_row_get(col: &ResolvedColumn, index: usize, indent: &str) -> String {
        match col.sql_type.as_str() {
            "clob" | "nclob" => return Self::emit_row_get_lob(col, index, indent, LobKind::Text),
            "blob" => return Self::emit_row_get_lob(col, index, indent, LobKind::Blob),
            "bfile" => return Self::emit_row_get_lob(col, index, indent, LobKind::BFile),
            _ => {}
        }
        match col.neutral_type.as_str() {
            "date" | "datetime" | "datetime_tz" => {
                if col.nullable {
                    format!(
                        "{indent}let {name}: {ty} = row.get::<Option<Date<'_>>, _>({i})?.map(|d| {{ let (y, mo, d2, h, mi, s) = d.date_and_time(); chrono::NaiveDate::from_ymd_opt(y as i32, mo as u32, d2 as u32).and_then(|dt| dt.and_hms_opt(h as u32, mi as u32, s as u32)).expect(\"invalid date from Oracle\") }});",
                        indent = indent,
                        name = col.field_name,
                        i = index,
                        ty = col.full_type
                    )
                } else {
                    format!(
                        "{indent}let {name}_date: Date<'_> = row.get({i})?;\n\
                         {indent}let {name}: {ty} = {{ let (y, mo, d, h, mi, s) = {name}_date.date_and_time(); chrono::NaiveDate::from_ymd_opt(y as i32, mo as u32, d as u32).and_then(|dt| dt.and_hms_opt(h as u32, mi as u32, s as u32)).expect(\"invalid date from Oracle\") }};",
                        indent = indent,
                        name = col.field_name,
                        i = index,
                        ty = col.full_type
                    )
                }
            }
            _ => {
                format!(
                    "{indent}let {name}: {ty} = row.get({i})?;",
                    indent = indent,
                    name = col.field_name,
                    i = index,
                    ty = col.full_type
                )
            }
        }
    }

    /// Emit the row.get() call for an Oracle LOB column (CLOB, NCLOB, BLOB, or BFILE).
    /// Fetches the LOB locator, then reads its full content via a loop that keeps
    /// calling `LOB::read` until the accumulated read count reaches the LOB's reported
    /// length.
    ///
    /// sibyl's `LOB::read(offset, len, buf)` issues a single `OCI_ONE_PIECE` OCI call and
    /// returns the number of characters (CLOB/NCLOB) or bytes (BLOB/BFILE) actually read —
    /// sibyl's own doc example demonstrates this can be *less* than `len` (it returns
    /// whatever is available up to the LOB's current end, e.g. when the LOB shrinks
    /// between the `len()` call and the `read()` call, or is read concurrently). Discarding
    /// that count and trusting a single call to have read everything risks silent
    /// truncation, so the generated code loops, re-requesting the remaining amount from the
    /// new offset, until the full length is consumed. A call that makes zero progress
    /// (returns 0 while data is still outstanding) is treated as a hard error rather than
    /// spinning forever.
    fn emit_row_get_lob(col: &ResolvedColumn, index: usize, indent: &str, kind: LobKind) -> String {
        let name = &col.field_name;
        let locator_ty = kind.locator_ty();
        let buf_init = kind.buf_init();
        let unit = kind.unit();

        if col.nullable {
            // ~keep Inside the `Some(lob) => { ... }` arm, the locator is always bound to `lob`.
            let open_line = if kind.needs_open() {
                format!("{indent}        lob.open_file().await?;\n")
            } else {
                String::new()
            };
            format!(
                "{indent}let {name}: {ty} = match row.get::<Option<{locator_ty}<'_>>, _>({i})? {{\n\
                 {indent}    Some(lob) => {{\n\
                 {open_line}\
                 {indent}        let len = lob.len().await?;\n\
                 {indent}        let mut buf = {buf_init};\n\
                 {indent}        let mut read = 0usize;\n\
                 {indent}        while read < len {{\n\
                 {indent}            let n = lob.read(read, len - read, &mut buf).await?;\n\
                 {indent}            if n == 0 {{\n\
                 {indent}                return Err(sibyl::Error::Interface(format!(\"incomplete LOB read for column '{name}': expected {{}} {unit}, got {{}}\", len, read)));\n\
                 {indent}            }}\n\
                 {indent}            read += n;\n\
                 {indent}        }}\n\
                 {indent}        Some(buf)\n\
                 {indent}    }}\n\
                 {indent}    None => None,\n\
                 {indent}}};",
                indent = indent,
                open_line = open_line,
                name = name,
                i = index,
                ty = col.full_type,
                locator_ty = locator_ty,
                buf_init = buf_init,
                unit = unit,
            )
        } else {
            let open_line = if kind.needs_open() {
                format!("{indent}{name}_lob.open_file().await?;\n")
            } else {
                String::new()
            };
            format!(
                "{indent}let {name}_lob: {locator_ty}<'_> = row.get({i})?;\n\
                 {open_line}\
                 {indent}let {name}_len = {name}_lob.len().await?;\n\
                 {indent}let mut {name}: {ty} = {buf_init};\n\
                 {indent}let mut {name}_read = 0usize;\n\
                 {indent}while {name}_read < {name}_len {{\n\
                 {indent}    let {name}_n = {name}_lob.read({name}_read, {name}_len - {name}_read, &mut {name}).await?;\n\
                 {indent}    if {name}_n == 0 {{\n\
                 {indent}        return Err(sibyl::Error::Interface(format!(\"incomplete LOB read for column '{name}': expected {{}} {unit}, got {{}}\", {name}_len, {name}_read)));\n\
                 {indent}    }}\n\
                 {indent}    {name}_read += {name}_n;\n\
                 {indent}}}",
                indent = indent,
                open_line = open_line,
                name = name,
                i = index,
                ty = col.full_type,
                locator_ty = locator_ty,
                buf_init = buf_init,
                unit = unit,
            )
        }
    }
}

/// Distinguishes the three sibyl LOB locator shapes so `emit_row_get_lob` can emit the
/// right locator type, buffer type, and unit label. CLOB and NCLOB share sibyl's `CLOB<'_>`
/// type (NCLOB is just a CLOB with a different charset form, resolved internally by
/// sibyl's `charset_form()`), so they share `LobKind::Text`.
#[derive(Clone, Copy)]
enum LobKind {
    /// CLOB / NCLOB — character data, `CLOB<'_>` locator, `String` buffer.
    Text,
    /// BLOB — binary data, `BLOB<'_>` locator, `Vec<u8>` buffer.
    Blob,
    /// BFILE — binary data via a read-only external-file locator; `BFile<'_>` locator,
    /// `Vec<u8>` buffer. Must be opened with `open_file()` before it can be read.
    BFile,
}

impl LobKind {
    fn locator_ty(self) -> &'static str {
        match self {
            LobKind::Text => "CLOB",
            LobKind::Blob => "BLOB",
            LobKind::BFile => "BFile",
        }
    }

    fn buf_init(self) -> &'static str {
        match self {
            LobKind::Text => "String::new()",
            LobKind::Blob | LobKind::BFile => "Vec::new()",
        }
    }

    fn unit(self) -> &'static str {
        match self {
            LobKind::Text => "characters",
            LobKind::Blob | LobKind::BFile => "bytes",
        }
    }

    /// BFILE locators must be opened with `open_file()` before they can be read;
    /// CLOB/NCLOB/BLOB locators don't need this.
    fn needs_open(self) -> bool {
        matches!(self, LobKind::BFile)
    }
}

/// Rewrite $1, $2, ... positional params to :PARAM_NAME named params for Oracle sibyl 0.7.
impl CodegenBackend for RustSibylBackend {
    fn name(&self) -> &str {
        "rust-sibyl"
    }

    fn manifest(&self) -> &scythe_backend::manifest::BackendManifest {
        &self.manifest
    }

    fn manifest_mut(&mut self) -> &mut scythe_backend::manifest::BackendManifest {
        &mut self.manifest
    }

    fn supported_engines(&self) -> &[&str] {
        &["oracle"]
    }

    fn file_header(&self) -> String {
        "use sibyl::*;\n".to_string()
    }

    fn apply_options(&mut self, options: &std::collections::HashMap<String, String>) -> Result<(), ScytheError> {
        reject_unknown_options(&["serde", "derive"], options)?;

        if let Some(val) = options.get("serde") {
            self.serde = parse_bool_option("serde", val)?;
        }
        if let Some(val) = options.get("derive") {
            self.extra_derives = val.split(',').map(|s| s.trim().to_string()).collect();
        }
        Ok(())
    }

    fn generate_struct_decl(
        &self,
        struct_name: &str,
        _query_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let mut out = String::new();
        let _ = writeln!(out, "{}", self.struct_derives());
        let _ = writeln!(out, "pub struct {} {{", struct_name);
        for col in columns {
            let _ = writeln!(out, "    pub {}: {},", col.field_name, col.full_type);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_query_fn(
        &self,
        analyzed: &AnalyzedQuery,
        struct_name: &str,
        columns: &[ResolvedColumn],
        params: &[ResolvedParam],
    ) -> Result<String, ScytheError> {
        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let positional_sql = super::rewrite_pg_placeholders(
            &super::clean_sql_with_optional(&analyzed.sql, &analyzed.optional_params, &analyzed.params),
            |n| format!(":{n}"),
        );
        let sql = crate::sql_literal::escape_rust_string(&Self::sql_with_named_params(&positional_sql, params));

        let param_list = params
            .iter()
            .map(|p| format!("{}: {}", p.field_name, p.borrowed_type))
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        let has_returning = sql.to_uppercase().contains("RETURNING");

        let mut out = String::new();

        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                let is_one = matches!(analyzed.command, QueryCommand::One);
                let return_type = if is_one {
                    struct_name.to_string()
                } else {
                    format!("Option<{}>", struct_name)
                };
                let _ = writeln!(
                    out,
                    "pub async fn {}<'a>(session: &'a Session<'a>{}{}) -> sibyl::Result<{}> {{",
                    func_name, sep, param_list, return_type
                );
                // ~keep sibyl's `stmt.execute()` returns the OCI-reported rows-affected
                // count (`Result<usize>`, see sibyl-0.7.1 src/stmt/nonblocking.rs), so a
                // RETURNING INTO whose WHERE clause matched nothing is detectable without
                // a second round trip: the out vars stay at their pre-execute defaults, but
                // `rows_affected == 0` catches the missing row before those are read.
                let missing_row_err = format!(
                    "sibyl::Error::Interface(\"{func_name} expected exactly one row but found none\".to_string())"
                );

                if has_returning {
                    let full_sql = Self::sql_with_returning(&sql, columns);
                    let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", full_sql);
                    for col in columns {
                        let _ = writeln!(out, "{}", Self::emit_out_var_decl_typed(col));
                    }
                    let in_pairs: Vec<String> = params
                        .iter()
                        .map(|p| format!("(\"{}\", {})", Self::named_placeholder(&p.field_name), p.field_name))
                        .collect();
                    let out_pairs: Vec<String> = columns
                        .iter()
                        .map(|col| {
                            format!(
                                "(\"{}\", {})",
                                Self::out_named_placeholder(&col.field_name),
                                Self::out_var_ref_for_returning(col)
                            )
                        })
                        .collect();
                    let all_pairs: Vec<String> = in_pairs.into_iter().chain(out_pairs).collect();
                    let args_expr = if all_pairs.len() == 1 {
                        all_pairs[0].clone()
                    } else {
                        format!("({})", all_pairs.join(", "))
                    };
                    let _ = writeln!(out, "    let rows_affected = stmt.execute({}).await?;", args_expr);
                    if is_one {
                        let _ = writeln!(out, "    if rows_affected == 0 {{ return Err({missing_row_err}); }}");
                    } else {
                        let _ = writeln!(out, "    if rows_affected == 0 {{ return Ok(None); }}");
                    }
                    for col in columns {
                        let _ = writeln!(out, "{}", Self::emit_out_var_conversion(col));
                    }
                    let field_assigns: Vec<String> = columns
                        .iter()
                        .map(|c| format!("{}: {}", c.field_name, c.field_name))
                        .collect();
                    if is_one {
                        let _ = writeln!(out, "    Ok({} {{ {} }})", struct_name, field_assigns.join(", "));
                    } else {
                        let _ = writeln!(out, "    Ok(Some({} {{ {} }}))", struct_name, field_assigns.join(", "));
                    }
                    let _ = write!(out, "}}");
                } else {
                    let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", sql);
                    let args_expr = Self::build_in_args(params);
                    let _ = writeln!(out, "    let rows = stmt.query({}).await?;", args_expr);
                    let _ = writeln!(out, "    if let Some(row) = rows.next().await? {{");
                    for (i, col) in columns.iter().enumerate() {
                        let _ = writeln!(out, "{}", Self::emit_row_get(col, i, "        "));
                    }
                    let field_assigns: Vec<String> = columns
                        .iter()
                        .map(|c| format!("{}: {}", c.field_name, c.field_name))
                        .collect();
                    if is_one {
                        let _ = writeln!(out, "        Ok({} {{ {} }})", struct_name, field_assigns.join(", "));
                        let _ = writeln!(out, "    }} else {{");
                        let _ = writeln!(out, "        Err({missing_row_err})");
                    } else {
                        let _ = writeln!(
                            out,
                            "        Ok(Some({} {{ {} }}))",
                            struct_name,
                            field_assigns.join(", ")
                        );
                        let _ = writeln!(out, "    }} else {{");
                        let _ = writeln!(out, "        Ok(None)");
                    }
                    let _ = writeln!(out, "    }}");
                    let _ = write!(out, "}}");
                }
            }
            QueryCommand::Many => {
                let _ = writeln!(
                    out,
                    "pub async fn {}<'a>(session: &'a Session<'a>{}{}) -> sibyl::Result<Vec<{}>> {{",
                    func_name, sep, param_list, struct_name
                );
                let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", sql);
                let args_expr = Self::build_in_args(params);
                let _ = writeln!(out, "    let rows = stmt.query({}).await?;", args_expr);
                let _ = writeln!(out, "    let mut results = Vec::new();");
                let _ = writeln!(out, "    while let Some(row) = rows.next().await? {{");
                for (i, col) in columns.iter().enumerate() {
                    let _ = writeln!(out, "{}", Self::emit_row_get(col, i, "        "));
                }
                let field_assigns: Vec<String> = columns
                    .iter()
                    .map(|c| format!("{}: {}", c.field_name, c.field_name))
                    .collect();
                let _ = writeln!(
                    out,
                    "        results.push({} {{ {} }});",
                    struct_name,
                    field_assigns.join(", ")
                );
                let _ = writeln!(out, "    }}");
                let _ = writeln!(out, "    Ok(results)");
                let _ = write!(out, "}}");
            }
            QueryCommand::Exec => {
                let _ = writeln!(
                    out,
                    "pub async fn {}<'a>(session: &'a Session<'a>{}{}) -> sibyl::Result<()> {{",
                    func_name, sep, param_list
                );
                let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", sql);
                let args_expr = Self::build_in_args(params);
                let _ = writeln!(out, "    stmt.execute({}).await?;", args_expr);
                let _ = writeln!(out, "    Ok(())");
                let _ = write!(out, "}}");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(
                    out,
                    "pub async fn {}<'a>(session: &'a Session<'a>{}{}) -> sibyl::Result<usize> {{",
                    func_name, sep, param_list
                );
                let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", sql);
                let args_expr = Self::build_in_args(params);
                let _ = writeln!(out, "    let num_rows = stmt.execute({}).await?;", args_expr);
                let _ = writeln!(out, "    Ok(num_rows)");
                let _ = write!(out, "}}");
            }
            QueryCommand::Batch => {
                let batch_fn_name = format!("{}_batch", func_name);
                let _ = writeln!(
                    out,
                    "pub async fn {}<'a>(session: &'a Session<'a>, items: &[({})]) -> sibyl::Result<()> {{",
                    batch_fn_name,
                    params
                        .iter()
                        .map(|p| p.full_type.clone())
                        .collect::<Vec<_>>()
                        .join(", ")
                );
                let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", sql);
                let _ = writeln!(out, "    for item in items {{");
                let item_pairs: Vec<String> = params
                    .iter()
                    .enumerate()
                    .map(|(i, p)| format!("(\"{}\", &item.{})", Self::named_placeholder(&p.field_name), i))
                    .collect();
                let args_expr = if item_pairs.len() == 1 {
                    item_pairs[0].clone()
                } else {
                    format!("({})", item_pairs.join(", "))
                };
                let _ = writeln!(out, "        stmt.execute({}).await?;", args_expr);
                let _ = writeln!(out, "    }}");
                let _ = writeln!(out, "    Ok(())");
                let _ = write!(out, "}}");
            }
            QueryCommand::Grouped => unreachable!("grouped queries are routed to generate_grouped_query_fn"),
        }

        Ok(out)
    }

    fn generate_enum_def(&self, enum_info: &EnumInfo) -> Result<String, ScytheError> {
        let type_name = enum_type_name(&enum_info.sql_name, &self.manifest.naming);
        let mut out = String::new();
        let _ = writeln!(out, "{}", self.enum_derives());
        let _ = writeln!(out, "pub enum {} {{", type_name);
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "    {},", variant);
        }
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
        let _ = writeln!(out, "impl {} {{", type_name);
        let _ = writeln!(out, "    pub fn as_str(&self) -> &'static str {{");
        let _ = writeln!(out, "        match self {{");
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "            {}::{} => \"{}\",", type_name, variant, value);
        }
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out, "    }}");
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_grouped_structs(
        &self,
        parent_struct_name: &str,
        child_struct_name: &str,
        parent_columns: &[crate::backend_trait::ResolvedColumn],
        child_columns: &[crate::backend_trait::ResolvedColumn],
        _key_column: &str,
    ) -> Result<String, ScytheError> {
        let mut out = String::new();

        let _ = writeln!(out, "{}", self.struct_derives());
        let _ = writeln!(out, "pub struct {} {{", child_struct_name);
        for col in child_columns {
            let _ = writeln!(out, "    pub {}: {},", col.field_name, col.full_type);
        }
        let _ = writeln!(out, "}}");

        let _ = writeln!(out);

        let _ = writeln!(out, "{}", self.struct_derives());
        let _ = writeln!(out, "pub struct {} {{", parent_struct_name);
        for col in parent_columns {
            let _ = writeln!(out, "    pub {}: {},", col.field_name, col.full_type);
        }
        let _ = writeln!(out, "    pub children: Vec<{}>,", child_struct_name);
        let _ = write!(out, "}}");

        Ok(out)
    }

    fn generate_grouped_query_fn(
        &self,
        request: &crate::backend_trait::GroupedQueryFn<'_>,
    ) -> Result<String, ScytheError> {
        let analyzed = request.analyzed;
        let parent_struct_name = request.parent_struct_name;
        let child_struct_name = request.child_struct_name;
        let parent_columns = request.parent_columns;
        let child_columns = request.child_columns;
        let params = request.params;
        let key_column = request.key_column;

        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let key_field = to_snake_case(key_column);
        let mut out = String::new();

        let positional_sql = super::rewrite_pg_placeholders(
            &super::clean_sql_with_optional(&analyzed.sql, &analyzed.optional_params, &analyzed.params),
            |n| format!(":{n}"),
        );
        let sql = crate::sql_literal::escape_rust_string(&Self::sql_with_named_params(&positional_sql, params));

        let param_list = params
            .iter()
            .map(|p| format!("{}: {}", p.field_name, p.borrowed_type))
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        let args_expr = Self::build_in_args(params);

        let _ = writeln!(
            out,
            "pub async fn {}<'a>(session: &'a Session<'a>{}{}) -> sibyl::Result<Vec<{}>> {{",
            func_name, sep, param_list, parent_struct_name
        );

        let _ = writeln!(out, "    let stmt = session.prepare(\"{}\").await?;", sql);
        let _ = writeln!(out, "    let rows = stmt.query({}).await?;", args_expr);
        let _ = writeln!(out, "    let mut result: Vec<{}> = Vec::new();", parent_struct_name);
        let _ = writeln!(out, "    while let Some(row) = rows.next().await? {{");

        for (i, col) in parent_columns.iter().enumerate() {
            let _ = writeln!(out, "{}", Self::emit_row_get(col, i, "        "));
        }

        let _ = writeln!(out, "        let key = {key_field}.clone();");

        let parent_len = parent_columns.len();
        for (j, col) in child_columns.iter().enumerate() {
            let _ = writeln!(out, "{}", Self::emit_row_get(col, parent_len + j, "        "));
        }

        let _ = writeln!(out, "        let child = {} {{", child_struct_name);
        for col in child_columns {
            let _ = writeln!(out, "            {},", col.field_name);
        }
        let _ = writeln!(out, "        }};");

        let _ = writeln!(
            out,
            "        if let Some(parent) = result.iter_mut().rev().find(|p| p.{key_field} == key) {{"
        );
        let _ = writeln!(out, "            parent.children.push(child);");
        let _ = writeln!(out, "        }} else {{");
        let _ = writeln!(out, "            result.push({} {{", parent_struct_name);
        for col in parent_columns {
            let _ = writeln!(out, "                {},", col.field_name);
        }
        let _ = writeln!(out, "                children: vec![child],");
        let _ = writeln!(out, "            }});");
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out, "    Ok(result)");
        let _ = write!(out, "}}");

        Ok(out)
    }

    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        let name = composite_type_name(&composite.sql_name, &self.manifest.naming);
        let mut out = String::new();
        let _ = writeln!(out, "{}", self.struct_derives());
        let _ = writeln!(out, "pub struct {} {{", name);
        for field in &composite.fields {
            let rust_type = resolve_type(&field.neutral_type, &self.manifest, field.nullable)
                .map(|t| t.into_owned())
                .map_err(|e| {
                    ScytheError::new(ErrorCode::InternalError, format!("composite field type error: {}", e))
                })?;
            let _ = writeln!(out, "    pub {}: {},", to_snake_case(&field.name), rust_type);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use scythe_core::analyzer::{AnalyzedColumn, AnalyzedQuery, GroupByConfig};
    use scythe_core::parser::QueryCommand;

    use super::RustSibylBackend;
    use crate::backend_trait::CodegenBackend;
    use crate::generate_with_backend;

    fn make_grouped_query() -> AnalyzedQuery {
        let parent_cols = vec![
            AnalyzedColumn {
                name: "id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "name".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "email".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            },
        ];
        let child_cols = vec![
            AnalyzedColumn {
                name: "order_id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "total".to_string(),
                neutral_type: "decimal".to_string(),
                nullable: true,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "order_date".to_string(),
                neutral_type: "datetime".to_string(),
                nullable: false,
                ..Default::default()
            },
        ];
        let all_cols = [parent_cols.clone(), child_cols.clone()].concat();
        AnalyzedQuery::build(|aq| {
            aq.name = "GetUsersWithOrders".to_string();
            aq.command = QueryCommand::Grouped;
            aq.sql = "-- @name GetUsersWithOrders\n-- @returns :grouped\n-- @group_by users.id\n\
                  SELECT u.id, u.name, u.email, o.id AS order_id, o.total, o.created_at AS order_date\n\
                  FROM users u\n\
                  JOIN orders o ON o.user_id = u.id"
                .to_string();
            aq.columns = all_cols;
            aq.params = vec![];
            aq.deprecated = None;
            aq.source_table = None;
            aq.composites = vec![];
            aq.enums = vec![];
            aq.optional_params = vec![];
            aq.group_by = Some(GroupByConfig {
                table: "users".to_string(),
                key_column: "id".to_string(),
                parent_columns: parent_cols,
                child_columns: child_cols,
            });
            aq.custom = vec![];
        })
    }

    #[test]
    fn test_grouped_sibyl_structs() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = make_grouped_query();
        let result = generate_with_backend(&query, &backend).unwrap();

        let row_struct = result.row_struct.as_deref().unwrap();

        assert!(
            row_struct.contains("pub struct GetUsersWithOrdersChildRow"),
            "missing child struct; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("pub order_id: i32"),
            "child struct missing order_id; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("pub struct GetUsersWithOrdersRow"),
            "missing parent struct; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("pub id: i32"),
            "parent struct missing id; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("pub name: String"),
            "parent struct missing name; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("pub children: Vec<GetUsersWithOrdersChildRow>"),
            "parent struct missing children field; got:\n{row_struct}"
        );
        let child_pos = row_struct.find("GetUsersWithOrdersChildRow").unwrap();
        let parent_pos = row_struct.find("pub struct GetUsersWithOrdersRow").unwrap();
        assert!(child_pos < parent_pos, "child struct must appear before parent struct");

        assert!(result.model_struct.is_none(), "grouped must not produce a model_struct");
    }

    #[test]
    fn test_grouped_sibyl_query_fn() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = make_grouped_query();
        let result = generate_with_backend(&query, &backend).unwrap();

        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("pub async fn get_users_with_orders<'a>(session: &'a Session<'a>)"),
            "missing fn; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("-> sibyl::Result<Vec<GetUsersWithOrdersRow>>"),
            "wrong return type; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("rows.next().await?"),
            "fn must iterate rows; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("GetUsersWithOrdersChildRow {"),
            "fn must construct child struct; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("children: vec![child]"),
            "fn must initialize children vec; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("parent.children.push(child)"),
            "fn must fold child into existing parent; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("Ok(result)"),
            "fn must return result; got:\n{query_fn}"
        );
    }

    /// Regression test for the "Interface(\"cannot return as a String\")" runtime error:
    /// sibyl's `FromSql<String>` only matches `ColumnBuffer::Text` (VARCHAR2/CHAR); an
    /// Oracle CLOB column's buffer is `ColumnBuffer::CLOB`, so `row.get::<String, _>(i)`
    /// fails at runtime. CLOB columns must be fetched as a `CLOB<'_>` locator and read
    /// explicitly instead.
    #[test]
    fn test_clob_column_reads_via_lob_locator_not_row_get_string() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetOrdersByUser".to_string();
            aq.command = QueryCommand::Many;
            aq.sql = "SELECT id, notes FROM orders".to_string();
            aq.columns = vec![
                AnalyzedColumn {
                    name: "id".to_string(),
                    sql_type: "integer".to_string(),
                    neutral_type: "int32".to_string(),
                    nullable: false,
                    ..Default::default()
                },
                AnalyzedColumn {
                    name: "notes".to_string(),
                    sql_type: "clob".to_string(),
                    neutral_type: "string".to_string(),
                    nullable: true,
                    ..Default::default()
                },
            ];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("row.get::<Option<CLOB<'_>>, _>(1)?"),
            "CLOB column must be fetched as a LOB locator, not a String; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("lob.read(read, len - read, &mut buf).await?"),
            "CLOB content must be read explicitly via LOB::read; got:\n{query_fn}"
        );
        assert!(
            !query_fn.contains("let notes: Option<String> = row.get(1)?;"),
            "CLOB column must not be read via the plain String path; got:\n{query_fn}"
        );
    }

    /// Regression test: a discarded `LOB::read` return count risks silent truncation for
    /// large LOBs (sibyl's own doc example shows `read()` can return fewer chars/bytes than
    /// requested). Generated code must loop until the full reported length has been read,
    /// and must error out — not spin forever — if a read call makes zero progress.
    #[test]
    fn test_clob_read_loops_until_full_length_consumed() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetOrdersByUser".to_string();
            aq.command = QueryCommand::Many;
            aq.sql = "SELECT notes FROM orders".to_string();
            aq.columns = vec![AnalyzedColumn {
                name: "notes".to_string(),
                sql_type: "clob".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            }];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("let mut notes_read = 0usize;"),
            "must track accumulated read progress; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("while notes_read < notes_len {"),
            "must loop until the full LOB length is consumed; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("let notes_n = notes_lob.read(notes_read, notes_len - notes_read, &mut notes).await?;"),
            "each iteration must request only the remaining amount from the new offset; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("if notes_n == 0 {") && query_fn.contains("return Err(sibyl::Error::Interface("),
            "a zero-progress read must be treated as a hard error, not silently accepted or looped forever; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("notes_read += notes_n;"),
            "progress must accumulate across iterations; got:\n{query_fn}"
        );
    }

    /// BLOB columns must take the same LOB-locator path as CLOB (the doc comment on
    /// `emit_row_get` has long promised this), but must decode into `Vec<u8>` — BLOB is
    /// binary data, not text, and forcing it through `String` would corrupt non-UTF8 bytes.
    #[test]
    fn test_blob_column_reads_via_lob_locator_as_bytes() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetAttachment".to_string();
            aq.command = QueryCommand::Opt;
            aq.sql = "SELECT payload FROM attachments".to_string();
            aq.columns = vec![AnalyzedColumn {
                name: "payload".to_string(),
                sql_type: "blob".to_string(),
                neutral_type: "bytes".to_string(),
                nullable: false,
                ..Default::default()
            }];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();
        let row_struct = result.row_struct.as_deref().unwrap();

        assert!(
            query_fn.contains("let payload_lob: BLOB<'_> = row.get(0)?;"),
            "BLOB column must be fetched as a LOB locator; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("let mut payload: Vec<u8> = Vec::new();"),
            "BLOB content must decode into Vec<u8>, not String; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("payload_lob.read(payload_read, payload_len - payload_read, &mut payload).await?"),
            "BLOB content must be read explicitly, looping until fully consumed; got:\n{query_fn}"
        );
        assert!(
            row_struct.contains("pub payload: Vec<u8>,"),
            "row struct field must be Vec<u8> for a BLOB column; got:\n{row_struct}"
        );
    }

    /// NCLOB shares sibyl's `CLOB<'_>` locator type (distinguished internally by charset
    /// form), so it must take the same text LOB path as CLOB — not the broken String path.
    #[test]
    fn test_nclob_column_reads_via_lob_locator() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetDoc".to_string();
            aq.command = QueryCommand::Opt;
            aq.sql = "SELECT body FROM docs".to_string();
            aq.columns = vec![AnalyzedColumn {
                name: "body".to_string(),
                sql_type: "nclob".to_string(),
                neutral_type: "string".to_string(),
                nullable: true,
                ..Default::default()
            }];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("row.get::<Option<CLOB<'_>>, _>(0)?"),
            "NCLOB column must be fetched via the CLOB locator type; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("Some(buf)"),
            "NCLOB column must produce Option<String> content; got:\n{query_fn}"
        );
        assert!(
            !query_fn.contains("let body: Option<String> = row.get(0)?;"),
            "NCLOB column must not be read via the plain String path; got:\n{query_fn}"
        );
    }

    /// BFILE locators must be opened with `open_file()` before they can be read (sibyl
    /// requires this — a fresh BFILE locator is not implicitly open), and read as bytes via
    /// the `BFile<'_>` locator type, not the plain String path.
    #[test]
    fn test_bfile_column_opens_before_reading_as_bytes() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetExternalDoc".to_string();
            aq.command = QueryCommand::Opt;
            aq.sql = "SELECT contents FROM external_docs".to_string();
            aq.columns = vec![AnalyzedColumn {
                name: "contents".to_string(),
                sql_type: "bfile".to_string(),
                neutral_type: "bytes".to_string(),
                nullable: false,
                ..Default::default()
            }];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("let contents_lob: BFile<'_> = row.get(0)?;"),
            "BFILE column must be fetched as a BFile locator; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("contents_lob.open_file().await?;"),
            "BFILE locator must be opened before reading; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("let mut contents: Vec<u8> = Vec::new();"),
            "BFILE content must decode into Vec<u8>; got:\n{query_fn}"
        );
        let open_pos = query_fn.find("open_file().await?").unwrap();
        let read_pos = query_fn.find("contents_lob.read(").unwrap();
        assert!(
            open_pos < read_pos,
            "open_file() must happen before read(); got:\n{query_fn}"
        );
    }

    #[test]
    fn test_non_clob_string_column_still_uses_plain_row_get() {
        let backend = RustSibylBackend::new("oracle").unwrap();
        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetUserById".to_string();
            aq.command = QueryCommand::Opt;
            aq.sql = "SELECT id, name FROM users".to_string();
            aq.columns = vec![
                AnalyzedColumn {
                    name: "id".to_string(),
                    sql_type: "integer".to_string(),
                    neutral_type: "int32".to_string(),
                    nullable: false,
                    ..Default::default()
                },
                AnalyzedColumn {
                    name: "name".to_string(),
                    sql_type: "varchar(255)".to_string(),
                    neutral_type: "string".to_string(),
                    nullable: false,
                    ..Default::default()
                },
            ];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("let name: String = row.get(1)?;"),
            "VARCHAR2 columns must keep using plain row.get(); got:\n{query_fn}"
        );
        assert!(
            !query_fn.contains("CLOB"),
            "non-CLOB query must not reference CLOB; got:\n{query_fn}"
        );
    }

    /// #103: before rust-sibyl declared `apply_options` at all, it inherited
    /// the `CodegenBackend` trait default, which used to be `Ok(())` for any
    /// map -- so any key, typo or otherwise, was silently discarded. Now
    /// that rust-sibyl accepts `serde`/`derive` (see
    /// `serde_and_derive_options_apply_together` below), it must still
    /// reject anything outside that pair -- `row_type` is not a rust-sibyl
    /// option and never has been.
    #[test]
    fn apply_options_rejects_unknown_key() {
        let mut backend = RustSibylBackend::new("oracle").unwrap();
        let err = backend
            .apply_options(&std::collections::HashMap::from([(
                "row_type".to_string(),
                "pydantic".to_string(),
            )]))
            .expect_err("row_type is not a known rust-sibyl option");
        assert_eq!(err.code, scythe_core::errors::ErrorCode::InvalidConfig);
        assert!(err.message.contains("row_type"), "{}", err.message);
    }

    /// Regression test for a release-blocking bug: `[sql.gen.rust] serde =
    /// true` / `derive = [...]` are documented as target-independent options
    /// under the legacy `[sql.gen.rust]` table, and the CLI's
    /// `resolve_gen_targets` inserts them into the options map regardless of
    /// which `target` the user picked (`sqlx`, `tokio-postgres`, `tiberius`,
    /// or `sibyl`). rust-sibyl's row/enum/composite structs are all plain
    /// Rust types with no macro-derived driver coupling, so there is no
    /// technical reason serde support should be limited to
    /// rust-tokio-postgres; before this, rust-sibyl declared no options at
    /// all and this config hard-errored with "unknown option 'serde'".
    #[test]
    fn serde_and_derive_options_apply_together() {
        let mut backend = RustSibylBackend::new("oracle").unwrap();
        backend
            .apply_options(&std::collections::HashMap::from([
                ("serde".to_string(), "true".to_string()),
                ("derive".to_string(), "PartialEq, Eq".to_string()),
            ]))
            .unwrap();
        assert!(backend.serde);
        assert_eq!(backend.extra_derives, vec!["PartialEq".to_string(), "Eq".to_string()]);
    }

    /// An unrecognized value must be reported, not silently treated as
    /// leaving `serde` disabled.
    #[test]
    fn serde_option_rejects_invalid_value() {
        let mut backend = RustSibylBackend::new("oracle").unwrap();
        let result = backend.apply_options(&std::collections::HashMap::from([(
            "serde".to_string(),
            "maybe".to_string(),
        )]));
        assert!(result.is_err(), "expected 'maybe' to be rejected");
    }

    /// The regression itself: applying `serde`/`derive` must not just avoid
    /// erroring, the emitted row struct must actually carry the derives.
    #[test]
    fn serde_and_derive_options_generate_row_struct_with_serde_derive() {
        let mut backend = RustSibylBackend::new("oracle").unwrap();
        backend
            .apply_options(&std::collections::HashMap::from([
                ("serde".to_string(), "true".to_string()),
                ("derive".to_string(), "PartialEq".to_string()),
            ]))
            .unwrap();

        let query = AnalyzedQuery::build(|aq| {
            aq.name = "GetUser".to_string();
            aq.command = QueryCommand::Opt;
            aq.sql = "SELECT id, name FROM users".to_string();
            aq.columns = vec![
                AnalyzedColumn {
                    name: "id".to_string(),
                    neutral_type: "int32".to_string(),
                    nullable: false,
                    ..Default::default()
                },
                AnalyzedColumn {
                    name: "name".to_string(),
                    neutral_type: "string".to_string(),
                    nullable: false,
                    ..Default::default()
                },
            ];
        });

        let result = generate_with_backend(&query, &backend).unwrap();
        let row_struct = result.row_struct.as_deref().unwrap();

        assert!(
            row_struct.contains("#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]"),
            "row struct must carry the base derives plus serde and the extra derive; got:\n{row_struct}"
        );
    }
}