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

use scythe_core::errors::{ErrorCode, ScytheError};

use crate::backend_trait::ResolvedColumn;

/// Supported TypeScript row type styles for generated code.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TsRowType {
    #[default]
    Interface,
    Zod,
}

impl TsRowType {
    /// Parse a row_type option string into a `TsRowType`.
    pub fn from_option(value: &str) -> Result<Self, ScytheError> {
        match value {
            "interface" => Ok(Self::Interface),
            "zod" => Ok(Self::Zod),
            _ => Err(ScytheError::new(
                ErrorCode::InternalError,
                format!("invalid row_type '{}': expected 'interface' or 'zod'", value),
            )),
        }
    }
}

/// Parse a boolean backend option strictly.
///
/// Accepts (case-insensitively) `true`/`false`, `1`/`0`, and `yes`/`no`. Any
/// other value — a typo, `"on"`, an empty string — is rejected with an error
/// naming the option and the offending value, rather than being silently
/// coerced to `false` as `matches!` or `== "true"` would do.
pub fn parse_bool_option(option_name: &str, value: &str) -> Result<bool, ScytheError> {
    match value.to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" => Ok(true),
        "false" | "0" | "no" => Ok(false),
        _ => Err(ScytheError::new(
            ErrorCode::InternalError,
            format!("invalid {option_name} '{value}': expected 'true'/'false', '1'/'0', or 'yes'/'no'"),
        )),
    }
}

/// Escape a SQL string for safe splicing into a JS backtick template
/// literal.
///
/// Order matters: backslash must be escaped first, so the backslashes this
/// pass inserts ahead of a backtick or `${` are not themselves re-escaped by
/// a later pass. Left unescaped, a backslash in the source SQL (e.g.
/// `E'\n'`) would escape whatever JS character follows it; a literal
/// backtick (idiomatic identifier quoting in MySQL/MariaDB — `` `users`.`id` ``)
/// would terminate the template literal early; and a literal `${` would open
/// a live JS interpolation — worse still inside a Kysely `sql` tag, where
/// `${}` is a parameter binding.
pub fn escape_ts_template_literal(sql: &str) -> String {
    sql.replace('\\', "\\\\").replace('`', "\\`").replace("${", "\\${")
}

/// Escape a SQL string for safe splicing into a double-quoted JS string
/// literal.
///
/// Used by the oracledb backend, which binds SQL text as a plain
/// double-quoted string rather than a template literal, so `` ` `` and `${`
/// are inert there but a literal `"` would terminate the string early.
/// Backslash is escaped first for the same reason as
/// [`escape_ts_template_literal`].
pub fn escape_ts_double_quoted_literal(sql: &str) -> String {
    sql.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Map a neutral type to its Zod v4 schema expression.
/// Note: This does not handle enums - use column_to_zod for full column handling.
pub fn neutral_to_zod(neutral_type: &str, nullable: bool) -> String {
    let base = match neutral_type {
        "int16" | "int32" | "int64" => "z.number()",
        "float32" | "float64" => "z.number()",
        "string" | "text" | "inet" | "interval" | "time" | "time_tz" => "z.string()",
        "bool" => "z.boolean()",
        "datetime" | "datetime_tz" => "z.date()",
        "date" => "z.string()",
        "uuid" => "z.string().uuid()",
        "json" => "z.unknown()",
        "decimal" => "z.string()",
        "bytes" => "z.instanceof(Buffer)",
        t if t.starts_with("enum::") => "z.string()",
        _ => "z.unknown()",
    };
    if nullable {
        format!("{base}.nullable()")
    } else {
        base.to_string()
    }
}

/// Render the plain TypeScript interface for a row.
///
/// Shared by every TypeScript backend so the shape cannot drift between them.
pub fn generate_ts_interface_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    generate_ts_interface_row_struct_with_base(struct_name, query_name, columns, None)
}

/// As [`generate_ts_interface_row_struct`], but extending `base` when the
/// target requires it (mysql2's `RowDataPacket`).
pub fn generate_ts_interface_row_struct_with_base(
    struct_name: &str,
    query_name: &str,
    columns: &[ResolvedColumn],
    base: Option<&str>,
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    match base {
        Some(base) => {
            let _ = writeln!(out, "export interface {} extends {} {{", struct_name, base);
        }
        None => {
            let _ = writeln!(out, "export interface {} {{", struct_name);
        }
    }
    for col in columns {
        let _ = writeln!(out, "\t{}: {};", col.field_name, col.full_type);
    }
    let _ = write!(out, "}}");
    out
}

/// Group the columns that an outer join can null out together.
///
/// Returns the groups in first-appearance order, keeping only those with at
/// least one discriminant — a column that was `NOT NULL` in the schema and so
/// can only be null when the join found no row. A group without a discriminant
/// carries no information a union could express, because every column in it was
/// independently nullable anyway.
fn discriminated_join_groups(columns: &[ResolvedColumn]) -> Vec<String> {
    let mut groups: Vec<String> = Vec::new();
    for col in columns {
        if let Some(group) = &col.join_group
            && !groups.contains(group)
            && columns
                .iter()
                .any(|c| c.join_group.as_ref() == Some(group) && c.is_join_discriminant())
        {
            groups.push(group.clone());
        }
    }
    groups
}

/// Render a row type that expresses outer-join nullability as a discriminated
/// union instead of independent per-column optionals.
///
/// For a `LEFT JOIN` where the joined relation projects at least one `NOT NULL`
/// column, the flat interface is sound but imprecise: it admits rows the query
/// can never produce. Given
///
/// ```sql
/// SELECT u.id, u.name, o.total, o.notes
/// FROM users u LEFT JOIN orders o ON u.id = o.user_id
/// ```
///
/// where `orders.total` is `NOT NULL` and `orders.notes` is not, a flat shape
/// admits `{ total: null, notes: "gift" }` — unreachable, because `total` is
/// null exactly when no order matched, and then `notes` is null too.
///
/// Columns from the inner side stay in a base object; each discriminated join
/// group contributes one matched/unmatched alternative.
///
/// Falls back to the plain interface when there is nothing to discriminate, so
/// callers can use this unconditionally.
/// `base` is intersected into the result when the target requires the row to
/// extend a driver type (mysql2's `RowDataPacket`). A union cannot use
/// `extends`, so it is expressed as an intersection instead.
pub fn generate_ts_union_row_struct(
    struct_name: &str,
    query_name: &str,
    columns: &[ResolvedColumn],
    base: Option<&str>,
) -> String {
    let groups = discriminated_join_groups(columns);
    if groups.is_empty() {
        return generate_ts_interface_row_struct_with_base(struct_name, query_name, columns, base);
    }

    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    match base {
        Some(base) => {
            let _ = writeln!(out, "export type {} = {} & {{", struct_name, base);
        }
        None => {
            let _ = writeln!(out, "export type {} = {{", struct_name);
        }
    }

    for col in columns.iter().filter(|c| c.join_group.is_none()) {
        let _ = writeln!(out, "\t{}: {};", col.field_name, col.full_type);
    }
    let _ = write!(out, "}}");

    for group in &groups {
        let members: Vec<&ResolvedColumn> = columns
            .iter()
            .filter(|c| c.join_group.as_ref() == Some(group))
            .collect();

        let _ = writeln!(out, " & (");

        // Matched: the join found a row, so each column takes its own
        // schema nullability.
        let _ = write!(out, "\t| {{ ");
        for (index, col) in members.iter().enumerate() {
            if index > 0 {
                let _ = write!(out, "; ");
            }
            let matched_type = if col.nullable_before_join {
                col.full_type.as_str()
            } else {
                col.lang_type.as_str()
            };
            let _ = write!(out, "{}: {}", col.field_name, matched_type);
        }
        let _ = writeln!(out, " }}");

        // Unmatched: no row on the outer side, so every projected column is
        // null together.
        let _ = write!(out, "\t| {{ ");
        for (index, col) in members.iter().enumerate() {
            if index > 0 {
                let _ = write!(out, "; ");
            }
            let _ = write!(out, "{}: null", col.field_name);
        }
        let _ = writeln!(out, " }}");

        let _ = write!(out, ")");
    }

    // A type alias needs the terminator; the interface form does not.
    let _ = write!(out, ";");
    out
}

/// Generate a Zod schema and inferred type for a row struct.
pub fn generate_zod_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    let schema_name = format!("{struct_name}Schema");
    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    let _ = writeln!(out, "export const {} = z.object({{", schema_name);
    for col in columns {
        let zod_type = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", col.field_name, zod_type);
    }
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = write!(out, "export type {} = z.infer<typeof {}>;", struct_name, schema_name);
    out
}

/// Map a ResolvedColumn to its Zod schema expression, handling enums properly.
fn column_to_zod(col: &ResolvedColumn) -> String {
    column_to_zod_with_nullable(col, col.nullable)
}

/// As [`column_to_zod`], but with an explicit nullability instead of
/// `col.nullable`.
///
/// Needed by [`generate_zod_union_row_struct`]: inside the "matched" branch
/// of a discriminated union, a join-group column's schema nullability is
/// `col.nullable_before_join` (its own nullability, independent of the
/// join), not `col.nullable` (which the analyzer has already widened to
/// `true` for every column in the group).
fn column_to_zod_with_nullable(col: &ResolvedColumn, nullable: bool) -> String {
    if col.neutral_type.starts_with("enum::") {
        let base = if col.lang_type.starts_with("enum::") {
            col.lang_type
                .strip_prefix("enum::")
                .unwrap_or(&col.lang_type)
                .to_string()
        } else {
            col.lang_type.clone()
        };
        let schema_name = format!("{}Schema", base);
        if nullable {
            format!("{schema_name}.nullable()")
        } else {
            schema_name
        }
    } else if col.neutral_type == "bytes" {
        // The runtime type of a binary column is backend-specific: `Buffer` for
        // the Node driver backends, `Uint8Array` for node:sqlite and
        // sqlite-wasm. Hardcoding `Buffer` mis-validates on those two and is
        // unresolvable in a browser, where `Buffer` does not exist at all.
        // `lang_type` already carries the manifest's mapping, so use it.
        let base = format!("z.instanceof({})", col.lang_type);
        if nullable { format!("{base}.nullable()") } else { base }
    } else {
        neutral_to_zod(&col.neutral_type, nullable)
    }
}

/// Render a Zod schema that expresses outer-join nullability as a
/// discriminated union instead of independent per-column optionals.
///
/// This is the Zod counterpart to [`generate_ts_union_row_struct`]: the
/// inferred type of the generated schema matches the shape that function
/// produces. Grouping is computed by the same [`discriminated_join_groups`]
/// helper so the two can never drift apart on which joins qualify.
///
/// Falls back to [`generate_zod_row_struct`] when there is nothing to
/// discriminate, so callers can use this unconditionally — matching the
/// fallback behavior of `generate_ts_union_row_struct`.
pub fn generate_zod_union_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    let groups = discriminated_join_groups(columns);
    if groups.is_empty() {
        return generate_zod_row_struct(struct_name, query_name, columns);
    }

    let schema_name = format!("{struct_name}Schema");
    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    let _ = writeln!(out, "export const {} = z.object({{", schema_name);
    for col in columns.iter().filter(|c| c.join_group.is_none()) {
        let zod_type = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", col.field_name, zod_type);
    }
    let _ = write!(out, "}})");

    for group in &groups {
        let members: Vec<&ResolvedColumn> = columns
            .iter()
            .filter(|c| c.join_group.as_ref() == Some(group))
            .collect();

        // Matched: the join found a row, so each column takes its own
        // pre-join schema nullability.
        let matched_fields: Vec<String> = members
            .iter()
            .map(|col| {
                format!(
                    "{}: {}",
                    col.field_name,
                    column_to_zod_with_nullable(col, col.nullable_before_join)
                )
            })
            .collect();
        // Unmatched: no row on the outer side, so every projected column is
        // null together.
        let unmatched_fields: Vec<String> = members
            .iter()
            .map(|col| format!("{}: z.null()", col.field_name))
            .collect();

        let _ = write!(
            out,
            ".and(z.union([z.object({{ {} }}), z.object({{ {} }})]))",
            matched_fields.join(", "),
            unmatched_fields.join(", "),
        );
    }
    let _ = writeln!(out, ";");
    let _ = writeln!(out);
    let _ = write!(out, "export type {} = z.infer<typeof {}>;", struct_name, schema_name);
    out
}

/// Generate paired child + parent TypeScript interfaces for a `:grouped` query.
///
/// Child interface is emitted first so the parent's `children: ChildType[]` field
/// resolves without a forward reference.
pub fn generate_grouped_interface_structs(
    child_struct_name: &str,
    parent_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/** Child row type for grouped query. */");
    let _ = writeln!(out, "export interface {child_struct_name} {{");
    for col in child_columns {
        let _ = writeln!(out, "\t{}: {};", col.field_name, col.full_type);
    }
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "/** Parent row type for grouped query. */");
    let _ = writeln!(out, "export interface {parent_struct_name} {{");
    for col in parent_columns {
        let _ = writeln!(out, "\t{}: {};", col.field_name, col.full_type);
    }
    let _ = writeln!(out, "\tchildren: {child_struct_name}[];");
    let _ = write!(out, "}}");
    out
}

/// Generate paired child + parent Zod schemas for a `:grouped` query.
///
/// Child schema is emitted first so the parent's `children: z.array(ChildSchema)`
/// reference resolves without a forward declaration.
pub fn generate_zod_grouped_structs(
    child_struct_name: &str,
    parent_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
) -> String {
    let child_schema = format!("{child_struct_name}Schema");
    let parent_schema = format!("{parent_struct_name}Schema");
    let mut out = String::new();
    let _ = writeln!(out, "/** Child row type for grouped query. */");
    let _ = writeln!(out, "export const {child_schema} = z.object({{");
    for col in child_columns {
        let zod = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", col.field_name, zod);
    }
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = writeln!(out, "export type {child_struct_name} = z.infer<typeof {child_schema}>;");
    let _ = writeln!(out);
    let _ = writeln!(out, "/** Parent row type for grouped query. */");
    let _ = writeln!(out, "export const {parent_schema} = z.object({{");
    for col in parent_columns {
        let zod = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", col.field_name, zod);
    }
    let _ = writeln!(out, "\tchildren: z.array({child_schema}),");
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = write!(
        out,
        "export type {parent_struct_name} = z.infer<typeof {parent_schema}>;"
    );
    out
}

/// Generate the client-side fold body for a `:grouped` query.
///
/// `row_access(sql_col_name, ts_full_type)` returns the TypeScript expression that
/// reads that column from the current `row` loop variable.  Examples:
/// - pg/mysql2 (rows are `Record<string, any>`): `|name, _| format!("row.{name}")`
/// - postgres.js/mssql/duckdb: `|name, ty| format!("row['{}'] as {}", name, ty)`
/// - Oracle (uppercase keys):  `|name, ty| format!("row['{}'] as {}", name.to_uppercase(), ty)`
///
/// The helper emits the fold loop into a string that is appended directly inside
/// the function body; the caller is responsible for surrounding braces.
pub fn generate_ts_grouped_fold_body(
    parent_struct_name: &str,
    _child_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
    key_col_name: &str,
    row_access: impl Fn(&str, &str) -> String,
) -> String {
    let key_type = parent_columns
        .iter()
        .find(|c| c.name == key_col_name)
        .map_or("unknown", |c| c.full_type.as_str());

    let mut out = String::new();
    let _ = writeln!(out, "\tconst result: {parent_struct_name}[] = [];");
    let _ = writeln!(out, "\tconst index = new Map<unknown, {parent_struct_name}>();");
    let _ = writeln!(out, "\tfor (const row of flatRows) {{");
    let _ = writeln!(out, "\t\tconst key = {};", row_access(key_col_name, key_type));
    let _ = writeln!(out, "\t\tlet parent = index.get(key);");
    let _ = writeln!(out, "\t\tif (!parent) {{");
    let _ = writeln!(out, "\t\t\tparent = {{");
    for col in parent_columns {
        let _ = writeln!(
            out,
            "\t\t\t\t{}: {},",
            col.field_name,
            row_access(&col.name, &col.full_type)
        );
    }
    let _ = writeln!(out, "\t\t\t\tchildren: [],");
    let _ = writeln!(out, "\t\t\t}};");
    let _ = writeln!(out, "\t\t\tindex.set(key, parent);");
    let _ = writeln!(out, "\t\t\tresult.push(parent);");
    let _ = writeln!(out, "\t\t}}");
    let _ = writeln!(out, "\t\tparent.children.push({{");
    for col in child_columns {
        let _ = writeln!(
            out,
            "\t\t\t{}: {},",
            col.field_name,
            row_access(&col.name, &col.full_type)
        );
    }
    let _ = writeln!(out, "\t\t}});");
    let _ = writeln!(out, "\t}}");
    let _ = writeln!(out, "\treturn result;");
    out
}

/// Generate a Zod enum schema from enum values.
pub fn generate_zod_enum(type_name: &str, values: &[String]) -> String {
    let schema_name = format!("{type_name}Schema");
    let mut out = String::new();
    let variants: Vec<String> = values.iter().map(|v| format!("\"{}\"", v)).collect();
    let _ = writeln!(out, "export const {} = z.enum([{}]);", schema_name, variants.join(", "));
    let _ = writeln!(out);
    let _ = write!(out, "export type {} = z.infer<typeof {}>;", type_name, schema_name);
    let _ = writeln!(out);
    let _ = writeln!(out);
    let _ = writeln!(out, "export const {} = {{", type_name);
    for value in values {
        let key = scythe_backend::naming::to_pascal_case(value);
        let _ = writeln!(out, "\t{}: \"{}\",", key, value);
    }
    let _ = write!(out, "}} as const;");
    out
}

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

    fn column(
        name: &str,
        lang_type: &str,
        nullable: bool,
        group: Option<&str>,
        nullable_before_join: bool,
    ) -> ResolvedColumn {
        ResolvedColumn {
            name: name.to_string(),
            field_name: name.to_string(),
            lang_type: lang_type.to_string(),
            full_type: if nullable {
                format!("{lang_type} | null")
            } else {
                lang_type.to_string()
            },
            neutral_type: "string".to_string(),
            sql_type: "text".to_string(),
            nullable,
            join_group: group.map(str::to_string),
            nullable_before_join,
        }
    }

    /// The example from the issue: `orders.total` is NOT NULL so it
    /// discriminates the join, while `orders.notes` is independently nullable.
    fn user_orders_columns() -> Vec<ResolvedColumn> {
        vec![
            column("id", "number", false, None, false),
            column("name", "string", false, None, false),
            column("total", "string", true, Some("o"), false),
            column("notes", "string", true, Some("o"), true),
        ]
    }

    #[test]
    fn emits_a_union_that_ties_the_outer_join_columns_together() {
        let out = generate_ts_union_row_struct("GetUserOrdersRow", "GetUserOrders", &user_orders_columns(), None);

        assert!(out.contains("export type GetUserOrdersRow = {"), "{out}");
        // Inner-side columns stay in the base object.
        assert!(out.contains("\tid: number;"), "{out}");
        assert!(out.contains("\tname: string;"), "{out}");
        // Matched: total is non-null, notes keeps its own nullability.
        assert!(out.contains("| { total: string; notes: string | null }"), "{out}");
        // Unmatched: the whole group is null together.
        assert!(out.contains("| { total: null; notes: null }"), "{out}");
        assert!(out.ends_with(");"), "type alias must be terminated: {out}");
    }

    /// Without a NOT NULL column on the outer side there is no discriminant,
    /// so the flat shape is already exact and a union would add nothing.
    #[test]
    fn falls_back_to_the_flat_interface_when_no_column_discriminates() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("notes", "string", true, Some("o"), true),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert!(out.contains("export interface R {"), "{out}");
        assert!(!out.contains(" & ("), "no union without a discriminant: {out}");
    }

    #[test]
    fn falls_back_to_the_flat_interface_when_there_is_no_outer_join() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("name", "string", false, None, false),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert_eq!(out, generate_ts_interface_row_struct("R", "Q", &columns));
    }

    /// mysql2 rows must extend RowDataPacket. A union cannot use `extends`, so
    /// the base is intersected instead.
    #[test]
    fn intersects_the_base_type_when_the_target_requires_one() {
        let out = generate_ts_union_row_struct("R", "Q", &user_orders_columns(), Some("RowDataPacket"));

        assert!(out.contains("export type R = RowDataPacket & {"), "{out}");
    }

    /// Two independently outer-joined relations each get their own
    /// match/no-match alternative rather than being conflated.
    #[test]
    fn emits_one_alternative_per_join_group() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("total", "string", true, Some("o"), false),
            column("addr", "string", true, Some("a"), false),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert!(out.contains("| { total: string }"), "{out}");
        assert!(out.contains("| { total: null }"), "{out}");
        assert!(out.contains("| { addr: string }"), "{out}");
        assert!(out.contains("| { addr: null }"), "{out}");
        assert_eq!(out.matches(" & (").count(), 2, "one group per relation: {out}");
    }

    #[test]
    fn escape_ts_template_literal_escapes_backtick_dollar_brace_and_backslash() {
        let out = escape_ts_template_literal(r"a`b${c}d\e");
        assert_eq!(out, r"a\`b\${c}d\\e");
    }

    /// Backslash must be escaped first: if `${` or `` ` `` were escaped
    /// before backslash, the backslash this pass inserts ahead of them
    /// would itself get doubled by the backslash pass, corrupting the
    /// escape sequence.
    #[test]
    fn escape_ts_template_literal_does_not_double_escape_inserted_backslashes() {
        let out = escape_ts_template_literal("`${x}");
        // Exactly one backslash ahead of each special character, not two.
        assert_eq!(out, r"\`\${x}");
    }

    #[test]
    fn escape_ts_template_literal_leaves_plain_sql_untouched() {
        let out = escape_ts_template_literal("SELECT id, name FROM users WHERE id = $1");
        assert_eq!(out, "SELECT id, name FROM users WHERE id = $1");
    }

    #[test]
    fn escape_ts_double_quoted_literal_escapes_quote_and_backslash() {
        let out = escape_ts_double_quoted_literal(r#"a"b\c"#);
        assert_eq!(out, r#"a\"b\\c"#);
    }

    #[test]
    fn parse_bool_option_accepts_true_spellings_case_insensitively() {
        for value in ["true", "True", "TRUE", "1", "yes", "Yes", "YES"] {
            assert!(
                parse_bool_option("outer_join_unions", value).unwrap(),
                "expected {value} to parse as true"
            );
        }
    }

    #[test]
    fn parse_bool_option_accepts_false_spellings_case_insensitively() {
        for value in ["false", "False", "FALSE", "0", "no", "No", "NO"] {
            assert!(
                !parse_bool_option("outer_join_unions", value).unwrap(),
                "expected {value} to parse as false"
            );
        }
    }

    /// This must fail before the fix: the old `matches!(value.as_str(), "true" | "1" | "yes")`
    /// silently mapped every one of these to `false` instead of reporting an error.
    #[test]
    fn parse_bool_option_rejects_unrecognized_values_with_an_error_naming_the_option() {
        for value in ["on", "maybe", ""] {
            let err =
                parse_bool_option("outer_join_unions", value).expect_err(&format!("expected '{value}' to be rejected"));
            let message = err.to_string();
            assert!(
                message.contains("outer_join_unions"),
                "error should name the option: {message}"
            );
            assert!(message.contains(value), "error should include the bad value: {message}");
        }
    }

    fn bytes_column(name: &str, lang_type: &str, nullable: bool) -> ResolvedColumn {
        ResolvedColumn {
            name: name.to_string(),
            field_name: name.to_string(),
            lang_type: lang_type.to_string(),
            full_type: if nullable {
                format!("{lang_type} | null")
            } else {
                lang_type.to_string()
            },
            neutral_type: "bytes".to_string(),
            sql_type: "bytea".to_string(),
            nullable,
            join_group: None,
            nullable_before_join: false,
        }
    }

    /// A binary column's runtime type is backend-specific. Hardcoding `Buffer`
    /// mis-validates on the backends whose driver yields `Uint8Array`, and is
    /// unresolvable in a browser where `Buffer` does not exist.
    #[test]
    fn test_zod_bytes_schema_follows_the_backend_runtime_type() {
        let buffer_schema =
            generate_zod_row_struct("GetBlobRow", "GetBlob", &[bytes_column("payload", "Buffer", false)]);
        assert!(
            buffer_schema.contains("z.instanceof(Buffer)"),
            "Buffer backends keep Buffer; got:\n{buffer_schema}"
        );

        let uint8_schema =
            generate_zod_row_struct("GetBlobRow", "GetBlob", &[bytes_column("payload", "Uint8Array", false)]);
        assert!(
            uint8_schema.contains("z.instanceof(Uint8Array)"),
            "Uint8Array backends must not emit Buffer; got:\n{uint8_schema}"
        );
        assert!(
            !uint8_schema.contains("Buffer"),
            "Uint8Array backends must not reference Buffer at all; got:\n{uint8_schema}"
        );
    }

    #[test]
    fn test_zod_bytes_schema_preserves_nullability() {
        let schema = generate_zod_row_struct("GetBlobRow", "GetBlob", &[bytes_column("payload", "Uint8Array", true)]);
        assert!(
            schema.contains("z.instanceof(Uint8Array).nullable()"),
            "nullable bytes must stay nullable; got:\n{schema}"
        );
    }

    /// The grouped Zod emitter used to call `neutral_to_zod` directly, which
    /// has no column context — so an enum column degraded to a bare
    /// `z.string()` and a bytes column always claimed `Buffer`.
    #[test]
    fn test_grouped_zod_structs_use_column_aware_schemas() {
        let mut enum_col = column("status", "UserStatus", false, None, false);
        enum_col.neutral_type = "enum::user_status".to_string();

        let grouped = generate_zod_grouped_structs(
            "GetUsersWithOrdersChildRow",
            "GetUsersWithOrdersRow",
            &[bytes_column("avatar", "Uint8Array", false)],
            &[enum_col],
        );

        assert!(
            grouped.contains("UserStatusSchema"),
            "grouped enum must use its enum schema, not z.string(); got:\n{grouped}"
        );
        assert!(
            grouped.contains("z.instanceof(Uint8Array)"),
            "grouped bytes must follow the backend type; got:\n{grouped}"
        );
    }
}