scythe-codegen 0.19.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
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
use std::collections::HashMap;
use std::fmt::Write;

use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{
    composite_type_name, enum_type_name, enum_variant_name, fn_name, to_camel_case, to_pascal_case,
};
use scythe_backend::types::resolve_type;

use scythe_core::SqlDialect;
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, GroupedQueryFn, ResolvedColumn, ResolvedParam};
use crate::backends::jvm_common;

const DEFAULT_MANIFEST_PG: &str = include_str!("../../manifests/kotlin-exposed.toml");

pub struct KotlinExposedBackend {
    manifest: BackendManifest,
}

impl KotlinExposedBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        let default_toml = match engine {
            "postgresql" | "postgres" | "pg" => DEFAULT_MANIFEST_PG,
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InvalidConfig,
                    format!("unsupported engine '{}' for kotlin-exposed backend", engine),
                ));
            }
        };
        let manifest = super::parse_manifest(default_toml)?;
        Ok(Self { manifest })
    }
}

/// Get the Exposed column type function for a given Kotlin type.
fn exposed_column_fn(kotlin_type: &str) -> &str {
    match kotlin_type {
        "Boolean" => "bool",
        "Byte" => "byte",
        "Short" => "short",
        "Int" => "integer",
        "Long" => "long",
        "Float" => "float",
        "Double" => "double",
        "String" => "text",
        "ByteArray" => "binary",
        _ if kotlin_type.contains("BigDecimal") => "decimal",
        _ if kotlin_type.contains("LocalDate") => "date",
        _ if kotlin_type.contains("LocalTime") => "time",
        _ if kotlin_type.contains("OffsetTime") => "time",
        _ if kotlin_type.contains("LocalDateTime") => "datetime",
        _ if kotlin_type.contains("OffsetDateTime") => "timestampWithTimeZone",
        _ if kotlin_type.contains("UUID") => "uuid",
        _ => "text",
    }
}

/// The Kotlin element type an array column's `List<{T}>` reader casts each
/// element to. See `kotlin_jdbc.rs`'s `element_kotlin_type` -- identical
/// reasoning, duplicated rather than shared because it is a five-line wrapper
/// and the two backends have no other coupling.
fn element_kotlin_type(element_neutral: &str, manifest: &BackendManifest) -> String {
    resolve_type(element_neutral, manifest, false)
        .map(|t| t.into_owned())
        .unwrap_or_else(|_| "Any".to_string())
}

/// The Kotlin `List<T>` expression that turns a `java.sql.Array` (already
/// known non-null) into the declared element type. See `kotlin_jdbc.rs`'s
/// `array_list_expr` for the full reasoning.
fn array_list_expr(sql_array_expr: &str, element_type: &str) -> String {
    format!("({sql_array_expr}.array as Array<*>).map {{ it as {element_type} }}")
}

/// Splits a PostgreSQL composite's text form (`"(a,b,c)"`) into its raw field tokens. See
/// `java_jdbc.rs`'s twin constant for the full reasoning -- duplicated rather than shared
/// because the two backends have no other coupling.
const KT_PARSE_COMPOSITE_FIELDS_METHOD: &str = r#"        /**
         * ~keep Splits a PostgreSQL composite's text form ("(a,b,c)") into its raw field tokens,
         * honoring its escaping rules: an empty unquoted field is SQL NULL (returned as `null`);
         * a field needing quoting (containing a comma, paren, quote, backslash, or
         * leading/trailing space, or the empty string) is wrapped in double quotes with `"` and
         * `\` backslash-escaped inside; every other field is unquoted and taken literally. A
         * nested composite's own "(x,y)" text form always contains parens, so it always comes
         * back quoted here, ready for that type's own `fromText` to parse recursively.
         */
        private fun parseCompositeFields(text: String): List<String?> {
            val fields = mutableListOf<String?>()
            val inner = text.substring(1, text.length - 1)
            var i = 0
            val n = inner.length
            while (true) {
                val field = StringBuilder()
                var isNull = false
                if (i < n && inner[i] == '"') {
                    i++
                    while (i < n) {
                        val c = inner[i]
                        if (c == '\\' && i + 1 < n) {
                            field.append(inner[i + 1])
                            i += 2
                        } else if (c == '"' && i + 1 < n && inner[i + 1] == '"') {
                            field.append('"')
                            i += 2
                        } else if (c == '"') {
                            i++
                            break
                        } else {
                            field.append(c)
                            i++
                        }
                    }
                } else {
                    val start = i
                    while (i < n && inner[i] != ',') {
                        i++
                    }
                    field.append(inner, start, i)
                    isNull = field.isEmpty()
                }
                fields.add(if (isNull) null else field.toString())
                if (i < n && inner[i] == ',') {
                    i++
                    continue
                }
                break
            }
            return fields
        }
"#;

/// PostgreSQL's default `bytea` text output is hex (`"\x48656c6c6f"`); decode the digits after
/// the `\x` prefix back into bytes. Emitted only when a composite has a `bytes` field.
const KT_PARSE_COMPOSITE_BYTES_METHOD: &str = r#"        /**
         * ~keep PostgreSQL's default `bytea` text output is hex: "\x48656c6c6f". Decode the hex
         * digits after the "\x" prefix back into bytes.
         */
        private fun parseCompositeBytes(hex: String): ByteArray {
            val digits = hex.substring(2)
            val result = ByteArray(digits.length / 2)
            for (i in result.indices) {
                result[i] = digits.substring(i * 2, i * 2 + 2).toInt(16).toByte()
            }
            return result
        }
"#;

/// PostgreSQL's default `timestamptz` text output uses a space instead of `T` and omits the
/// offset's minutes when they are zero; normalize both before handing the text to `java.time`.
/// Emitted only when a composite has a `datetime_tz` field.
const KT_PARSE_COMPOSITE_OFFSET_DATETIME_METHOD: &str = r#"        /**
         * ~keep PostgreSQL's default `timestamptz` text output uses a space instead of `T`
         * ("2024-01-15 10:30:00+00") and omits the offset's minutes when they are zero ("+00"
         * rather than "+00:00"). Normalize both before parsing.
         */
        private fun parseCompositeOffsetDateTime(raw: String): java.time.OffsetDateTime {
            var s = raw.replace(' ', 'T')
            val sign = s[s.length - 3]
            if (sign == '+' || sign == '-') {
                s += ":00"
            }
            return java.time.OffsetDateTime.parse(s)
        }
"#;

/// PostgreSQL's default `timetz` text output omits the offset's minutes when they are zero;
/// `OffsetTime.parse` rejects that. Emitted only when a composite has a `time_tz` field.
const KT_PARSE_COMPOSITE_OFFSET_TIME_METHOD: &str = r#"        /**
         * ~keep PostgreSQL's default `timetz` text output omits the offset's minutes when they
         * are zero ("13:22:43-05" rather than "13:22:43-05:00"), which `OffsetTime.parse` rejects.
         */
        private fun parseCompositeOffsetTime(raw: String): java.time.OffsetTime {
            var s = raw
            val sign = s[s.length - 3]
            if (sign == '+' || sign == '-') {
                s += ":00"
            }
            return java.time.OffsetTime.parse(s)
        }
"#;

fn composite_needs_bytes_helper(composite: &CompositeInfo) -> bool {
    composite.fields.iter().any(|f| f.neutral_type == "bytes")
}

fn composite_needs_offset_datetime_helper(composite: &CompositeInfo) -> bool {
    composite.fields.iter().any(|f| f.neutral_type == "datetime_tz")
}

fn composite_needs_offset_time_helper(composite: &CompositeInfo) -> bool {
    composite.fields.iter().any(|f| f.neutral_type == "time_tz")
}

/// ~keep Convert one non-null composite field token into its non-null Kotlin type. Nullable
/// fields wrap this expression in `?.let` at the call site so SQL NULL remains Kotlin null.
fn composite_field_from_text_kotlin(
    neutral_type: &str,
    field_type: &str,
    raw: &str,
    manifest: &BackendManifest,
) -> String {
    if let Some(sql_name) = neutral_type.strip_prefix("composite::") {
        return format!(
            "{}.fromText({})!!",
            composite_type_name(sql_name, &manifest.naming),
            raw
        );
    }
    if neutral_type.starts_with("enum::") {
        return format!("{}.fromValue({})", field_type, raw);
    }
    match neutral_type {
        "bool" => format!("{} == \"t\"", raw),
        "int16" => format!("{}.toShort()", raw),
        "int32" => format!("{}.toInt()", raw),
        "int64" => format!("{}.toLong()", raw),
        "float32" => format!("{}.toFloat()", raw),
        "float64" => format!("{}.toDouble()", raw),
        "decimal" => format!("java.math.BigDecimal({})", raw),
        "uuid" => format!("java.util.UUID.fromString({})", raw),
        "date" => format!("java.time.LocalDate.parse({})", raw),
        "time" => format!("java.time.LocalTime.parse({})", raw),
        "datetime" => format!("java.time.LocalDateTime.parse({}.replace(' ', 'T'))", raw),
        "datetime_tz" => format!("parseCompositeOffsetDateTime({})", raw),
        "time_tz" => format!("parseCompositeOffsetTime({})", raw),
        "bytes" => format!("parseCompositeBytes({})", raw),
        // ~keep String-like fields need no conversion. Unsupported composite field kinds retain
        // the existing raw-token fallback.
        _ => raw.to_string(),
    }
}

/// The inline read expression for a kotlin-exposed column.
///
/// Exposed's `exec(sql) { rs -> ... }` block hands out a plain
/// `java.sql.ResultSet`, so this is the same problem `kotlin-jdbc` has and the
/// same answer: a named getter where JDBC has one, `rs.getObject(col,
/// T::class.java)` where it does not, and never the untyped
/// `rs.getObject(col)` whose `Any!` result is assignable to nothing.
///
/// Nullable columns return the preamble local written by
/// [`write_exposed_nullable_preamble`] instead of an inline read. This backend
/// had no preamble at all: a nullable `Int?` column was read with
/// `rs.getInt(col)`, which JDBC specifies to return `0` — not null — for SQL
/// NULL, so every NULL in a nullable numeric or boolean column silently became
/// `0`/`false` in the row object.
///
/// board #196: a composite column is checked before the blanket `col.nullable` preamble
/// dispatch -- pgjdbc registers no type map for a user-defined composite, so
/// `rs.getObject(col, T::class.java)` throws `PSQLException: conversion to class T ... not
/// supported` at runtime. `T.fromText` (emitted by `generate_composite_def`) parses the
/// driver's text form instead and is already null-safe, so composite needs no preamble local
/// (see the matching skip in `write_exposed_nullable_preamble`).
fn exposed_rs_expr(col: &ResolvedColumn, manifest: &BackendManifest) -> String {
    if col.neutral_type.starts_with("composite::") {
        // ~keep `fromText` returns `T?` so a NULL column stays expressible; a NOT NULL column's
        // field is declared `T` and needs the unwrap or Kotlin rejects the argument. Same fix as
        // `kotlin_jdbc::kt_rs_expr`; Java has no compile-time nullability and so needs nothing.
        let unwrap = if col.nullable { "" } else { "!!" };
        return format!("{}.fromText(rs.getString(\"{}\")){}", col.lang_type, col.name, unwrap);
    }
    if col.nullable {
        return col.field_name.clone();
    }
    if let Some(element) = jvm_common::array_element_neutral_type(&col.neutral_type) {
        let element_type = element_kotlin_type(element, manifest);
        return array_list_expr(&format!("rs.getArray(\"{}\")", col.name), &element_type);
    }
    if jvm_common::is_enum_column(&col.neutral_type) {
        return format!("{}.fromValue(rs.getString(\"{}\"))", col.lang_type, col.name);
    }
    jvm_common::kotlin_jdbc_read_call(&col.name, &col.lang_type)
}

/// Emit the nullable-column preamble locals a following row construction reads
/// through [`exposed_rs_expr`].
fn write_exposed_nullable_preamble(
    out: &mut String,
    cols: &[ResolvedColumn],
    indent: &str,
    manifest: &BackendManifest,
) {
    for col in cols {
        if !col.nullable {
            continue;
        }
        // ~keep board #196: `exposed_rs_expr` returns the composite's `fromText` call inline
        // for every composite column, nullable or not (see its own comment) -- so no preamble
        // local is ever read for one, and emitting `rs.getObject(col, T::class.java)` here
        // would both be dead code and reintroduce the type-map-less accessor this fix removes.
        if col.neutral_type.starts_with("composite::") {
            continue;
        }
        if let Some(element) = jvm_common::array_element_neutral_type(&col.neutral_type) {
            // ~keep A nullable array column's `rs.getArray(col)` returns
            // `null` for SQL NULL; calling `.array` on that null throws
            // `NullPointerException`, so the guard is on the `java.sql.Array`
            // local, before the element conversion runs.
            let element_type = element_kotlin_type(element, manifest);
            let _ = writeln!(
                out,
                "{}val {}SqlArray = rs.getArray(\"{}\")",
                indent, col.field_name, col.name
            );
            let list_expr = array_list_expr(&format!("{}SqlArray", col.field_name), &element_type);
            let _ = writeln!(
                out,
                "{}val {} = if ({}SqlArray == null) null else {}",
                indent, col.field_name, col.field_name, list_expr
            );
            continue;
        }
        if jvm_common::is_enum_column(&col.neutral_type) {
            // ~keep `getString` returns null for SQL NULL, so the guard is on
            // the raw string: `fromValue(rs.getString(col))` would throw on
            // exactly the value a nullable enum column exists to hold.
            let _ = writeln!(
                out,
                "{}val {}Value = rs.getString(\"{}\")",
                indent, col.field_name, col.name
            );
            let _ = writeln!(
                out,
                "{}val {} = if ({}Value == null) null else {}.fromValue({}Value)",
                indent, col.field_name, col.field_name, col.lang_type, col.field_name
            );
            continue;
        }
        let _ = writeln!(
            out,
            "{}val {}Value = {}",
            indent,
            col.field_name,
            jvm_common::kotlin_jdbc_read_call(&col.name, &col.lang_type)
        );
        let _ = writeln!(
            out,
            "{}val {} = if (rs.wasNull()) null else {}Value",
            indent, col.field_name, col.field_name
        );
    }
}

/// Get the Exposed column type class for use in `exec()` parameter binding.
fn exposed_column_type_class(kotlin_type: &str) -> &str {
    match kotlin_type {
        "Boolean" => "BooleanColumnType()",
        "Byte" => "ByteColumnType()",
        "Short" => "ShortColumnType()",
        "Int" => "IntegerColumnType()",
        "Long" => "LongColumnType()",
        "Float" => "FloatColumnType()",
        "Double" => "DoubleColumnType()",
        "String" => "TextColumnType()",
        "ByteArray" => "BinaryColumnType()",
        _ if kotlin_type.contains("BigDecimal") => "DecimalColumnType(10, 2)",
        _ if kotlin_type.contains("LocalDate") => "JavaLocalDateColumnType()",
        _ if kotlin_type.contains("LocalTime") => "JavaLocalTimeColumnType()",
        _ if kotlin_type.contains("OffsetTime") => "JavaLocalTimeColumnType()",
        _ if kotlin_type.contains("LocalDateTime") => "JavaLocalDateTimeColumnType()",
        _ if kotlin_type.contains("OffsetDateTime") => "JavaOffsetDateTimeColumnType()",
        _ if kotlin_type.contains("UUID") => "UUIDColumnType()",
        _ => "TextColumnType()",
    }
}

/// ~keep The value bound at an Exposed `exec` placeholder for `param`.
///
/// An enum parameter is paired with `TextColumnType()` -- the SQL side genuinely is text --
/// but the *value* must be the enum's SQL spelling, not the Kotlin enum object. Exposed's
/// `exec(sql, args: List<Pair<IColumnType, Any?>>)` takes `Any?`, so binding the object
/// compiles and then fails at execution time against a `user_status` column. `.value` is the
/// accessor `generate_enum_def` already emits and the exact inverse of the `fromValue(...)`
/// the read path uses, so a value round-trips even when its SQL spelling is not the uppercase
/// of its variant name.
fn exposed_bind_value(param: &ResolvedParam) -> String {
    exposed_bind_value_for(param, &param.field_name)
}

fn exposed_bind_value_for(param: &ResolvedParam, receiver: &str) -> String {
    if param.neutral_type.starts_with("enum::") {
        format!("{receiver}?.value")
    } else if param.neutral_type.starts_with("composite::") {
        format!("{receiver}?.toPgText()")
    } else {
        receiver.to_string()
    }
}

impl CodegenBackend for KotlinExposedBackend {
    fn name(&self) -> &str {
        "kotlin-exposed"
    }

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

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

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

        if let Some(value) = options.get("field_case") {
            super::apply_field_case_option(&mut self.manifest.naming, "kotlin-exposed", value)?;
        }
        Ok(())
    }

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

    fn file_header(&self) -> String {
        // ~keep `package generated` to match kotlin_jdbc.rs:593 and the directory the CLI writes
        // into. Without it the file lands in the default package and any caller doing
        // `import generated.*` -- which is how every kotlin harness reaches the query functions --
        // fails with "Unresolved reference 'generated'". java_r2dbc and kotlin_r2dbc shipped with
        // the same omission; it stays invisible until something actually imports the output.
        "package generated\n\n\
         import org.jetbrains.exposed.v1.core.dao.id.IntIdTable\n\
         import org.jetbrains.exposed.v1.core.dao.id.LongIdTable\n\
         import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable\n\
         import org.jetbrains.exposed.v1.core.BinaryColumnType\n\
         import org.jetbrains.exposed.v1.core.BooleanColumnType\n\
         import org.jetbrains.exposed.v1.core.ByteColumnType\n\
         import org.jetbrains.exposed.v1.core.DecimalColumnType\n\
         import org.jetbrains.exposed.v1.core.IColumnType\n\
         import org.jetbrains.exposed.v1.core.DoubleColumnType\n\
         import org.jetbrains.exposed.v1.core.FloatColumnType\n\
         import org.jetbrains.exposed.v1.core.IntegerColumnType\n\
         import org.jetbrains.exposed.v1.core.LongColumnType\n\
         import org.jetbrains.exposed.v1.core.ShortColumnType\n\
         import org.jetbrains.exposed.v1.core.TextColumnType\n\
         import org.jetbrains.exposed.v1.core.java.UUIDColumnType\n\
         import org.jetbrains.exposed.v1.javatime.JavaLocalDateColumnType\n\
         import org.jetbrains.exposed.v1.javatime.JavaLocalDateTimeColumnType\n\
         import org.jetbrains.exposed.v1.javatime.JavaLocalTimeColumnType\n\
         import org.jetbrains.exposed.v1.javatime.JavaOffsetDateTimeColumnType\n\
         import org.jetbrains.exposed.v1.core.statements.StatementType\n\
         import org.jetbrains.exposed.v1.jdbc.transactions.transaction\n"
            .to_string()
    }

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

    /// #214: this used to declare only `object EvTable : IntIdTable("ev")`
    /// and no row type at all, while the query function `determine_struct_name`
    /// pairs it with constructs `Ev(...)` -- a type declared nowhere. Exposed's
    /// idiom genuinely is a table object (there is no idiomatic way to drop
    /// it), so the fix emits *both*: the table object, for callers who want to
    /// build Exposed DSL queries against it, and the `data class` the query
    /// function already references.
    ///
    /// `struct_name` is derived through [`crate::model_struct_name`] -- the
    /// same function the base trait's default `generate_model_struct` and
    /// `determine_struct_name` both use -- not `to_pascal_case(table_name)`,
    /// whose un-singularized spelling (`"events"` -> `Events`, not `Event`) is
    /// exactly the #164 divergence this repo already fixed for every other
    /// backend.
    fn generate_model_struct(&self, table_name: &str, columns: &[ResolvedColumn]) -> Result<String, ScytheError> {
        let struct_name = crate::model_struct_name(table_name, &self.manifest.naming);
        let table_obj_name = format!("{}Table", struct_name);
        let mut out = String::new();
        let table_base = exposed_id_table_type(columns);
        let _ = writeln!(out, "object {} : {}(\"{}\") {{", table_obj_name, table_base, table_name);
        for col in columns.iter() {
            let col_fn = exposed_column_fn(&col.lang_type);
            let nullable_suffix = if col.nullable { ".nullable()" } else { "" };
            let _ = writeln!(
                out,
                "    val {} = {}(\"{}\"){}",
                col.field_name, col_fn, col.name, nullable_suffix
            );
        }
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
        let row_decl = self.generate_struct_decl(&struct_name, &struct_name, columns)?;
        out.push_str(&row_decl);
        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 dialect = SqlDialect::PostgreSQL;
        let cleaned_sql = super::clean_sql_oneline_with_optional_dialect(
            &analyzed.sql,
            dialect,
            &analyzed.optional_params,
            &analyzed.params,
        );
        let (rewritten_sql, occurrences) =
            super::rewrite_pg_typed_placeholders(&cleaned_sql, &analyzed.params, params, true, |_| "?".to_string());
        let sql = crate::sql_literal::escape_kotlin_string(&rewritten_sql);

        let mut out = String::new();

        let write_fn_sig = |out: &mut String, name: &str, ret: &str, params: &[ResolvedParam]| {
            let inline_params: String = params
                .iter()
                .map(|p| format!("{}: {}", p.field_name, p.full_type))
                .collect::<Vec<_>>()
                .join(", ");
            let sig = format!("fun {}({}){} =", name, inline_params, ret);
            if sig.len() <= 100 {
                let _ = writeln!(out, "{}", sig);
            } else {
                let _ = writeln!(out, "fun {}(", name);
                for p in params {
                    let _ = writeln!(out, "    {}: {},", p.field_name, p.full_type);
                }
                let _ = writeln!(out, "){} =", ret);
            }
            let _ = writeln!(out, "    transaction {{");
        };

        let build_args = |occurrences: &[u32]| -> String {
            if occurrences.is_empty() {
                return String::new();
            }
            let pairs: Vec<String> = occurrences
                .iter()
                .map(|&position| {
                    let p = super::resolved_param_for_position(&analyzed.params, params, position);
                    format!(
                        "{} to {}",
                        exposed_column_type_class(&p.lang_type),
                        exposed_bind_value(p)
                    )
                })
                .collect();
            // ~keep The explicit element type is load-bearing, not decoration. A bare `listOf(...)`
            // makes Kotlin infer one `T` across heterogeneous pairs, and with a mixed
            // parameter set -- `Pair<TextColumnType, String>` beside
            // `Pair<UUIDColumnType, UUID>` and `Pair<TextColumnType, TortureAddress?>` --
            // inference gives up: "Not enough information to infer type argument for 'T'",
            // then a cascade that even reports "actual type is 'String', but 'String' was
            // expected". Naming the type Exposed's `exec` actually takes short-circuits all
            // of it. The pg fixture happened to infer cleanly; the torture schema did not.
            format!(", listOf<Pair<IColumnType<*>, Any?>>({})", pairs.join(", "))
        };

        match &analyzed.command {
            QueryCommand::Exec => {
                write_fn_sig(&mut out, &func_name, "", params);
                let args = build_args(&occurrences);
                let _ = writeln!(out, "        exec(\"{}\"{})", sql, args);
                let _ = writeln!(out, "    }}");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                // ~keep This used to emit `exec(sql, args) ?: 0` typed `: Int`, which never
                // compiled against any Exposed this backend could resolve: the no-transform
                // `Transaction.exec(String, Iterable<Pair<IColumnType<*>, Any?>>, StatementType?)`
                // returns `Unit`, not `Int?` (verified from the exposed-core jar for both 0.56.0
                // and 0.61.0), so the elvis produced `Any` and the function failed with
                // "actual type is 'Any', but 'Int' was expected". Exposed surfaces an update count
                // only through the prepared-statement API, so that is what an affected-rows query
                // has to use. `false` is `returnKeys` -- these queries want the count, not
                // generated keys.
                write_fn_sig(&mut out, &func_name, ": Int", params);
                let args = build_args(&occurrences);
                let _ = writeln!(
                    out,
                    "        val stmt = connection.prepareStatement(\"{}\", false)",
                    sql
                );
                if !args.is_empty() {
                    // `build_args` renders a leading ", " for the exec call site; this one needs
                    // the list on its own.
                    let list = args.trim_start_matches(", ");
                    let _ = writeln!(out, "        stmt.fillParameters({})", list);
                }
                let _ = writeln!(out, "        stmt.executeUpdate()");
                let _ = writeln!(out, "    }}");
            }
            QueryCommand::One | QueryCommand::Opt => {
                // ~keep #192: see java-jdbc's generate_query_fn for the full
                // reasoning -- this shared arm used to render byte-identical
                // code for :one and :opt, so :one silently returned null on a
                // missing row instead of erroring. `is_one` is the only
                // difference from here down. The `rs.next()` if/else itself
                // -- including its `null` branch -- stays identical between
                // :one and :opt: `Transaction.exec(sql) { rs -> T }` returns
                // `T?` regardless of what the lambda's branches do, so a
                // throw *inside* the lambda would not change the static
                // nullability of the `exec(...)` call it's nested in, and
                // `: {Struct}` (no `?`) would not type-check against it. The
                // fallback instead sits on the *outer* call, as `exec(...) {
                // ... } ?: throw NoSuchElementException(...)` -- turning the
                // nullable result non-null the same way it would for a
                // driver-level absent-ResultSet null, not only the
                // rs.next()-false case (`kotlin.NoSuchElementException` is in
                // Kotlin's default imports, so no import is needed).
                let is_one = matches!(analyzed.command, QueryCommand::One);
                let ret = if is_one {
                    format!(": {}", struct_name)
                } else {
                    format!(": {}?", struct_name)
                };
                write_fn_sig(&mut out, &func_name, &ret, params);
                let args = build_args(&occurrences);
                let _ = writeln!(
                    out,
                    "        exec(\"{}\"{}, explicitStatementType = StatementType.SELECT) {{ rs ->",
                    sql, args
                );
                let _ = writeln!(out, "            if (rs.next()) {{");
                write_exposed_nullable_preamble(&mut out, columns, "                ", &self.manifest);
                let _ = writeln!(out, "                {}(", struct_name);
                for col in columns.iter() {
                    let _ = writeln!(
                        out,
                        "                    {} = {},",
                        col.field_name,
                        exposed_rs_expr(col, &self.manifest)
                    );
                }
                let _ = writeln!(out, "                )");
                let _ = writeln!(out, "            }} else {{");
                let _ = writeln!(out, "                null");
                let _ = writeln!(out, "            }}");
                if is_one {
                    let _ = writeln!(
                        out,
                        "        }} ?: throw NoSuchElementException(\"{}: no rows returned\")",
                        func_name
                    );
                } else {
                    let _ = writeln!(out, "        }}");
                }
                let _ = writeln!(out, "    }}");
            }
            QueryCommand::Batch => {
                let batch_fn_name = format!("{}Batch", func_name);
                if params.len() > 1 {
                    let params_class_name = format!("{}BatchParams", to_pascal_case(&analyzed.name));
                    let _ = writeln!(out, "data class {}(", params_class_name);
                    for p in params {
                        let _ = writeln!(out, "    val {}: {},", p.field_name, p.full_type);
                    }
                    let _ = writeln!(out, ")");
                    let _ = writeln!(out);
                    let _ = writeln!(out, "fun {}(items: List<{}>) =", batch_fn_name, params_class_name);
                    let _ = writeln!(out, "    transaction {{");
                    let _ = writeln!(out, "        for (item in items) {{");
                    let args: Vec<String> = occurrences
                        .iter()
                        .map(|&position| {
                            let p = super::resolved_param_for_position(&analyzed.params, params, position);
                            let receiver = format!("item.{}", p.field_name);
                            format!(
                                "{} to {}",
                                exposed_column_type_class(&p.lang_type),
                                exposed_bind_value_for(p, &receiver)
                            )
                        })
                        .collect();
                    let _ = writeln!(out, "            exec(\"{}\", listOf({}))", sql, args.join(", "));
                    let _ = writeln!(out, "        }}");
                    let _ = writeln!(out, "    }}");
                } else if params.len() == 1 {
                    let _ = writeln!(out, "fun {}(items: List<{}>) =", batch_fn_name, params[0].full_type);
                    let _ = writeln!(out, "    transaction {{");
                    let _ = writeln!(out, "        for (item in items) {{");
                    let args: Vec<String> = occurrences
                        .iter()
                        .map(|_| {
                            format!(
                                "{} to {}",
                                exposed_column_type_class(&params[0].lang_type),
                                exposed_bind_value_for(&params[0], "item")
                            )
                        })
                        .collect();
                    let _ = writeln!(out, "            exec(\"{}\", listOf({}))", sql, args.join(", "));
                    let _ = writeln!(out, "        }}");
                    let _ = writeln!(out, "    }}");
                } else {
                    let _ = writeln!(out, "fun {}(count: Int) =", batch_fn_name);
                    let _ = writeln!(out, "    transaction {{");
                    let _ = writeln!(out, "        repeat(count) {{");
                    let _ = writeln!(out, "            exec(\"{}\")", sql);
                    let _ = writeln!(out, "        }}");
                    let _ = writeln!(out, "    }}");
                }
            }
            QueryCommand::Grouped => {
                unreachable!("routed to generate_grouped_query_fn")
            }
            QueryCommand::Many => {
                let ret = format!(": List<{}>", struct_name);
                write_fn_sig(&mut out, &func_name, &ret, params);
                let args = build_args(&occurrences);
                let _ = writeln!(out, "        val result = mutableListOf<{}>()", struct_name);
                let _ = writeln!(
                    out,
                    "        exec(\"{}\"{}, explicitStatementType = StatementType.SELECT) {{ rs ->",
                    sql, args
                );
                let _ = writeln!(out, "            while (rs.next()) {{");
                write_exposed_nullable_preamble(&mut out, columns, "                ", &self.manifest);
                let _ = writeln!(out, "                result.add(");
                let _ = writeln!(out, "                    {}(", struct_name);
                for col in columns.iter() {
                    let _ = writeln!(
                        out,
                        "                        {} = {},",
                        col.field_name,
                        exposed_rs_expr(col, &self.manifest)
                    );
                }
                let _ = writeln!(out, "                    ),");
                let _ = writeln!(out, "                )");
                let _ = writeln!(out, "            }}");
                let _ = writeln!(out, "        }}");
                let _ = writeln!(out, "        result");
                let _ = writeln!(out, "    }}");
            }
        }

        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, "enum class {}(val value: String) {{", type_name);
        for (i, value) in enum_info.values.iter().enumerate() {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let sep = if i + 1 < enum_info.values.len() { "," } else { ";" };
            let _ = writeln!(out, "    {}(\"{}\"){}", variant, value, sep);
        }
        let _ = writeln!(out);
        // ~keep #213: see `java_jdbc.rs`'s `generate_enum_def` for the full
        // reasoning -- decoding against the declared `value` rather than the
        // sanitised variant spelling is what makes `fromValue(x.value) == x`
        // hold for every variant.
        let _ = writeln!(out, "    companion object {{");
        let _ = writeln!(out, "        fun fromValue(value: String): {} =", type_name);
        let _ = writeln!(out, "            values().firstOrNull {{ it.value == value }}");
        let _ = writeln!(
            out,
            "                ?: throw IllegalArgumentException(\"Unknown {} value: $value\")",
            type_name
        );
        let _ = writeln!(out, "    }}");
        let _ = writeln!(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 field_types: Vec<String> = composite
            .fields
            .iter()
            .map(|f| {
                resolve_type(&f.neutral_type, &self.manifest, f.nullable)
                    .map(|t| t.into_owned())
                    .unwrap_or_else(|_| "Any".to_string())
            })
            .collect();
        let field_base_types: Vec<String> = composite
            .fields
            .iter()
            .map(|f| {
                resolve_type(&f.neutral_type, &self.manifest, false)
                    .map(|t| t.into_owned())
                    .unwrap_or_else(|_| "Any".to_string())
            })
            .collect();
        let _ = writeln!(out, "data class {}(", name);
        for (field, field_type) in composite.fields.iter().zip(&field_types) {
            let field_name = to_camel_case(&field.name);
            let _ = writeln!(out, "    val {}: {},", field_name, field_type);
        }
        // ~keep board #196: a zero-field composite cannot exist in PostgreSQL (`CREATE TYPE ...
        // AS ()` is rejected), so -- like `kotlin_jdbc.rs`'s twin case -- there is no reachable
        // runtime value that would need a `fromText` here.
        if composite.fields.is_empty() {
            let _ = writeln!(out, ")");
            return Ok(out);
        }
        let _ = writeln!(out, ") {{");
        let encoded_fields = composite
            .fields
            .iter()
            .map(|field| {
                let field_name = to_camel_case(&field.name);
                if field.neutral_type.starts_with("composite::") {
                    format!("{field_name}?.toPgText()")
                } else if field.neutral_type.starts_with("enum::") {
                    format!("{field_name}?.value")
                } else if field.neutral_type == "bytes" {
                    format!("{field_name}?.joinToString(\"\") {{ \"%02x\".format(it) }}?.let {{ \"\\\\\\\\x\" + it }}")
                } else {
                    field_name.into_owned()
                }
            })
            .collect::<Vec<_>>()
            .join(", ");
        let _ = writeln!(
            out,
            "    fun toPgText(): String = listOf({encoded_fields}).joinToString(\",\", \"(\", \")\") {{ encodeCompositeField(it) }}"
        );
        let _ = writeln!(out);
        let _ = writeln!(out, "    companion object {{");
        let _ = writeln!(out, "        private fun encodeCompositeField(value: Any?): String {{");
        let _ = writeln!(out, "            if (value == null) return \"\"");
        let _ = writeln!(out, "            val raw = value.toString()");
        out.push_str(
            r#"            val quote = raw.isEmpty() || raw.any { it in charArrayOf('(', ')', ',', '"', '\\') } || raw != raw.trim()
"#,
        );
        let _ = writeln!(out, "            if (!quote) return raw");
        out.push_str(
            r#"            return "\"" + raw.replace("\\", "\\\\").replace("\"", "\"\"") + "\""
"#,
        );
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out);
        let _ = writeln!(out, "        /**");
        let _ = writeln!(
            out,
            "         * ~keep board #196: pgjdbc registers no `getObject(col, {}::class.java)`",
            name
        );
        let _ = writeln!(
            out,
            "         * type map for this composite -- it throws `PSQLException: conversion to"
        );
        let _ = writeln!(
            out,
            "         * class {}` at runtime. Parse the driver's composite text form instead.",
            name
        );
        let _ = writeln!(out, "         */");
        let _ = writeln!(out, "        fun fromText(text: String?): {}? {{", name);
        let _ = writeln!(out, "            if (text == null) {{");
        let _ = writeln!(out, "                return null");
        let _ = writeln!(out, "            }}");
        let _ = writeln!(out, "            val f = parseCompositeFields(text)");
        let _ = writeln!(out, "            return {}(", name);
        for (i, (field, field_type)) in composite.fields.iter().zip(&field_base_types).enumerate() {
            let raw = format!("f[{}]", i);
            let expr = if field.nullable {
                let conversion =
                    composite_field_from_text_kotlin(&field.neutral_type, field_type, "value", &self.manifest);
                format!("{raw}?.let {{ value -> {conversion} }}")
            } else {
                composite_field_from_text_kotlin(&field.neutral_type, field_type, &format!("{raw}!!"), &self.manifest)
            };
            let _ = writeln!(out, "                {},", expr);
        }
        let _ = writeln!(out, "            )");
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out);
        out.push_str(KT_PARSE_COMPOSITE_FIELDS_METHOD);
        if composite_needs_bytes_helper(composite) {
            let _ = writeln!(out);
            out.push_str(KT_PARSE_COMPOSITE_BYTES_METHOD);
        }
        if composite_needs_offset_datetime_helper(composite) {
            let _ = writeln!(out);
            out.push_str(KT_PARSE_COMPOSITE_OFFSET_DATETIME_METHOD);
        }
        if composite_needs_offset_time_helper(composite) {
            let _ = writeln!(out);
            out.push_str(KT_PARSE_COMPOSITE_OFFSET_TIME_METHOD);
        }
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out, "}}");
        Ok(out)
    }

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

        let _ = writeln!(out, "data class {}(", child_struct_name);
        for col in child_columns {
            let _ = writeln!(out, "    val {}: {},", col.field_name, col.full_type);
        }
        let _ = writeln!(out, ")");
        let _ = writeln!(out);

        let _ = writeln!(out, "data class {}(", parent_struct_name);
        for col in parent_columns {
            let _ = writeln!(out, "    val {}: {},", col.field_name, col.full_type);
        }
        let _ = writeln!(out, "    val children: MutableList<{}>,", child_struct_name);
        let _ = write!(out, ")");

        Ok(out)
    }

    fn generate_grouped_query_fn(&self, request: &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 dialect = SqlDialect::PostgreSQL;
        let cleaned_sql = super::clean_sql_oneline_with_optional_dialect(
            &analyzed.sql,
            dialect,
            &analyzed.optional_params,
            &analyzed.params,
        );
        let (rewritten_sql, occurrences) =
            super::rewrite_pg_typed_placeholders(&cleaned_sql, &analyzed.params, params, true, |_| "?".to_string());
        let sql = crate::sql_literal::escape_kotlin_string(&rewritten_sql);

        let key_col = parent_columns
            .iter()
            .find(|c| c.name == key_column)
            .unwrap_or(&parent_columns[0]);
        let key_type = key_col.full_type.trim_end_matches('?');

        let args = if occurrences.is_empty() {
            String::new()
        } else {
            let pairs: Vec<String> = occurrences
                .iter()
                .map(|&position| {
                    let p = super::resolved_param_for_position(&analyzed.params, params, position);
                    format!(
                        "{} to {}",
                        exposed_column_type_class(&p.lang_type),
                        exposed_bind_value(p)
                    )
                })
                .collect();
            // ~keep The explicit element type is load-bearing, not decoration. A bare `listOf(...)`
            // makes Kotlin infer one `T` across heterogeneous pairs, and with a mixed
            // parameter set -- `Pair<TextColumnType, String>` beside
            // `Pair<UUIDColumnType, UUID>` and `Pair<TextColumnType, TortureAddress?>` --
            // inference gives up: "Not enough information to infer type argument for 'T'",
            // then a cascade that even reports "actual type is 'String', but 'String' was
            // expected". Naming the type Exposed's `exec` actually takes short-circuits all
            // of it. The pg fixture happened to infer cleanly; the torture schema did not.
            format!(", listOf<Pair<IColumnType<*>, Any?>>({})", pairs.join(", "))
        };

        let inline_params: String = params
            .iter()
            .map(|p| format!("{}: {}", p.field_name, p.full_type))
            .collect::<Vec<_>>()
            .join(", ");
        let sig = format!("fun {}({}): List<{parent_struct_name}> =", func_name, inline_params);
        let mut out = String::new();
        if sig.len() <= 100 {
            let _ = writeln!(out, "{sig}");
        } else {
            let _ = writeln!(out, "fun {}(", func_name);
            for p in params {
                let _ = writeln!(out, "    {}: {},", p.field_name, p.full_type);
            }
            let _ = writeln!(out, "): List<{parent_struct_name}> =");
        }
        let _ = writeln!(out, "    transaction {{");
        let _ = writeln!(
            out,
            "        val lookup = LinkedHashMap<{key_type}, {parent_struct_name}>()"
        );
        let _ = writeln!(out, "        val result = mutableListOf<{parent_struct_name}>()");
        let _ = writeln!(out, "        exec(\"{sql}\"{args}) {{ rs ->");
        let _ = writeln!(out, "            while (rs.next()) {{");

        write_exposed_nullable_preamble(&mut out, child_columns, "                ", &self.manifest);
        write_exposed_nullable_preamble(&mut out, parent_columns, "                ", &self.manifest);

        let key_expr = exposed_rs_expr(key_col, &self.manifest);
        let _ = writeln!(out, "                val key = {key_expr}");

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

        let _ = writeln!(out, "                if (lookup.containsKey(key)) {{");
        let _ = writeln!(out, "                    lookup[key]!!.children.add(child)");
        let _ = writeln!(out, "                }} else {{");
        let _ = writeln!(out, "                    val parent = {parent_struct_name}(");
        for col in parent_columns {
            let _ = writeln!(
                out,
                "                        {} = {},",
                col.field_name,
                exposed_rs_expr(col, &self.manifest)
            );
        }
        let _ = writeln!(out, "                        children = mutableListOf(child),");
        let _ = writeln!(out, "                    )");
        let _ = writeln!(out, "                    lookup[key] = parent");
        let _ = writeln!(out, "                    result.add(parent)");
        let _ = writeln!(out, "                }}");
        let _ = writeln!(out, "            }}");
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out, "        result");
        let _ = write!(out, "    }}");

        Ok(out)
    }
}

fn exposed_id_table_type(columns: &[ResolvedColumn]) -> &str {
    let Some(id_column) = columns.iter().find(|column| column.name.eq_ignore_ascii_case("id")) else {
        return "IntIdTable";
    };
    match id_column.lang_type.as_str() {
        "Long" => "LongIdTable",
        ty if ty.contains("UUID") => "UUIDTable",
        _ => "IntIdTable",
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use scythe_core::analyzer::{
        AnalyzedColumn, AnalyzedParam, AnalyzedQuery, CompositeFieldInfo, CompositeInfo, GroupByConfig,
    };
    use scythe_core::parser::QueryCommand;

    use super::KotlinExposedBackend;
    use crate::backend_trait::CodegenBackend;

    #[test]
    fn generated_fixture_uses_exposed_v1_imports() {
        let backend = KotlinExposedBackend::new("postgresql").unwrap();
        let header = backend.file_header();
        let fixture = include_str!("../../../../integration_tests/kotlin-exposed/src/main/kotlin/generated/queries.kt");
        let imports = |source: &str| {
            source
                .lines()
                .filter(|line| line.starts_with("import org.jetbrains.exposed."))
                .map(str::to_owned)
                .collect::<Vec<_>>()
        };

        assert_eq!(imports(&header), imports(fixture));
        assert!(header.contains("import org.jetbrains.exposed.v1.core.java.UUIDColumnType"));
        assert!(header.contains("import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable"));
        assert!(header.contains("import org.jetbrains.exposed.v1.jdbc.transactions.transaction"));
        assert!(!header.contains("org.jetbrains.exposed.sql."));
        assert!(!header.contains("org.jetbrains.exposed.dao."));
    }

    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()
            },
        ];
        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()
            },
        ];
        let all_cols = [parent_cols.clone(), child_cols.clone()].concat();
        AnalyzedQuery::build(|aq| {
            aq.name = "GetUsersWithOrders".to_string();
            aq.command = QueryCommand::Grouped;
            aq.sql = "SELECT u.id, u.name, o.id AS order_id, o.total FROM users u 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_kotlin_exposed_structs() {
        let backend = crate::backends::get_backend("kotlin-exposed", "postgresql").unwrap();
        let query = make_grouped_query();
        let result = crate::generate_with_backend(&query, &*backend).unwrap();
        let row_struct = result.row_struct.as_deref().unwrap();

        assert!(
            row_struct.contains("data class GetUsersWithOrdersChildRow"),
            "missing child data class; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("data class GetUsersWithOrdersRow"),
            "missing parent data class; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("val children: MutableList<GetUsersWithOrdersChildRow>"),
            "parent missing children field; got:\n{row_struct}"
        );
        let child_pos = row_struct.find("data class GetUsersWithOrdersChildRow").unwrap();
        let parent_pos = row_struct.find("data class GetUsersWithOrdersRow(").unwrap();
        assert!(child_pos < parent_pos, "child must precede parent");
    }

    #[test]
    fn test_grouped_kotlin_exposed_query_fn() {
        let backend = crate::backends::get_backend("kotlin-exposed", "postgresql").unwrap();
        let query = make_grouped_query();
        let result = crate::generate_with_backend(&query, &*backend).unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            query_fn.contains("List<GetUsersWithOrdersRow>"),
            "wrong return type; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("transaction {"),
            "must use transaction block; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("LinkedHashMap"),
            "must use LinkedHashMap for fold lookup; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("lookup.containsKey(key)"),
            "must fold with containsKey; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("children.add(child)"),
            "must append child; got:\n{query_fn}"
        );
    }

    fn make_one_query_with_snake_case_columns() -> AnalyzedQuery {
        AnalyzedQuery::build(|q| {
            q.name = "GetSession".to_string();
            q.command = QueryCommand::One;
            q.sql = "SELECT id, user_id FROM sessions WHERE id = $1".to_string();
            q.columns = vec![
                AnalyzedColumn {
                    name: "id".to_string(),
                    neutral_type: "int32".to_string(),
                    nullable: false,
                    ..Default::default()
                },
                AnalyzedColumn {
                    name: "user_id".to_string(),
                    neutral_type: "int32".to_string(),
                    nullable: false,
                    ..Default::default()
                },
            ];
            // ~keep The SQL text declares `$1`; the analyzer would always
            // register a matching `AnalyzedParam` for a placeholder it sees,
            // so an empty list here (as this fixture had before #149) is a
            // combination the real pipeline never produces and panics
            // `resolved_param_for_position` (#149's occurrence-based bind
            // lookup has no position to resolve `$1` against).
            q.params = vec![AnalyzedParam {
                name: "id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                position: 1,
                source_relation: None,
            }];
            q.deprecated = None;
            q.source_table = None;
            q.composites = vec![];
            q.enums = vec![];
            q.optional_params = vec![];
            q.group_by = None;
            q.custom = vec![];
        })
    }

    /// The safety invariant this whole feature depends on: renaming the
    /// declared field must never touch the key the driver is asked to look
    /// up. `generate_query_fn`'s `One`/`Opt` branch reads `rs.getInt(col.name)`
    /// -- the raw SQL column name -- and only the data class' declared
    /// property (`col.field_name`) changes under `field_case = "camelCase"`.
    #[test]
    fn test_field_case_camel_case_renames_field_but_keeps_raw_lookup_key() {
        let mut backend = KotlinExposedBackend::new("postgresql").unwrap();
        backend
            .apply_options(&HashMap::from([("field_case".to_string(), "camelCase".to_string())]))
            .unwrap();
        let query = make_one_query_with_snake_case_columns();
        let result = crate::generate_with_backend(&query, &backend).unwrap();
        let row_struct = result.row_struct.as_deref().unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            row_struct.contains("val userId: Int"),
            "field_case must rename the declared data class property; got:\n{row_struct}"
        );
        assert!(
            !row_struct.contains("val user_id"),
            "must not leave the raw SQL name in the declared property; got:\n{row_struct}"
        );
        assert!(
            query_fn.contains("userId = rs.getInt(\"user_id\")"),
            "the ResultSet lookup key must stay the raw SQL column name; got:\n{query_fn}"
        );
        assert!(
            !query_fn.contains("rs.getInt(\"userId\")"),
            "must never look the driver up by the renamed field; got:\n{query_fn}"
        );
    }

    fn make_select_star_query() -> AnalyzedQuery {
        AnalyzedQuery::build(|q| {
            q.name = "GetAllUsers".to_string();
            q.command = QueryCommand::Many;
            q.sql = "SELECT * FROM users".to_string();
            q.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()
                },
            ];
            q.params = vec![];
            q.deprecated = None;
            q.source_table = Some("users".to_string());
            q.composites = vec![];
            q.enums = vec![];
            q.optional_params = vec![];
            q.group_by = None;
            q.custom = vec![];
        })
    }

    /// #214: `generate_model_struct` used to emit only the Exposed table
    /// object (`object UserTable : IntIdTable("users")`), never a row type,
    /// while `determine_struct_name` -- shared naming code this backend does
    /// not control -- decided the query function would construct `User(...)`,
    /// a type declared nowhere. `test_select_star_declares_and_references_the_same_struct_name_across_all_backends`
    /// in `lib.rs` checks this invariant generically across every backend;
    /// this test exercises the same fix directly so it lives with the code it
    /// covers.
    #[test]
    fn test_select_star_declares_both_the_table_object_and_the_row_data_class() {
        let backend = KotlinExposedBackend::new("postgresql").unwrap();
        let query = make_select_star_query();
        let result = crate::generate_with_backend(&query, &backend).unwrap();
        let model_struct = result.model_struct.as_deref().unwrap();
        let query_fn = result.query_fn.as_deref().unwrap();

        assert!(
            model_struct.contains("object UserTable : IntIdTable(\"users\") {"),
            "must still declare the Exposed table object; got:\n{model_struct}"
        );
        assert!(
            model_struct.contains("data class User("),
            "must also declare the row type the query function references; got:\n{model_struct}"
        );
        assert!(
            query_fn.contains("User("),
            "the query function must construct the declared row type; got:\n{query_fn}"
        );
    }

    #[test]
    fn test_field_case_option_rejects_invalid_value() {
        let mut backend = KotlinExposedBackend::new("postgresql").unwrap();
        let result = backend.apply_options(&HashMap::from([("field_case".to_string(), "PascalCase".to_string())]));
        assert!(result.is_err(), "expected 'PascalCase' to be rejected");
    }

    fn make_composite_with_consecutive_capitals() -> CompositeInfo {
        CompositeInfo {
            sql_name: "CreateAPIKey".to_string(),
            fields: vec![
                CompositeFieldInfo {
                    name: "HTTPSUrl".to_string(),
                    neutral_type: "string".to_string(),
                    nullable: false,
                },
                CompositeFieldInfo {
                    name: "internal_id".to_string(),
                    neutral_type: "int32".to_string(),
                    nullable: false,
                },
            ],
        }
    }

    /// `to_pascal_case`/`to_camel_case` now normalize consecutive capitals
    /// through `to_snake_case` (commit 6ab8994), so a composite's field
    /// names that carry runs of capitals ("HTTPSUrl") changed shape here too
    /// -- this backend's `generate_composite_def` had no coverage of that
    /// change landing.
    #[test]
    fn test_composite_def_normalizes_consecutive_capitals() {
        let backend = KotlinExposedBackend::new("postgresql").unwrap();
        let composite = make_composite_with_consecutive_capitals();
        let def = backend.generate_composite_def(&composite).unwrap();

        assert!(
            def.contains("data class CreateApiKey("),
            "composite type name must normalize consecutive capitals; got:\n{def}"
        );
        assert!(
            def.contains("val httpsUrl: String"),
            "composite field name must normalize consecutive capitals; got:\n{def}"
        );
        assert!(
            def.contains("val internalId: Int"),
            "composite field name must still camelCase a plain snake_case field; got:\n{def}"
        );
    }
}