scythe-codegen 0.17.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
use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{enum_type_name, enum_variant_name, fn_name};
use std::collections::HashMap;
use std::fmt::Write;

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

use crate::GeneratedCode;
use crate::backend_options::reject_unknown_options;
use crate::backend_trait::{CodegenBackend, GroupedQueryFn, ResolvedColumn, ResolvedParam};
use crate::backends::php_common::{
    RECORD_NOT_FOUND_EXCEPTION_CLASS, nested_json_column_expr, param_docblock_type,
    record_not_found_exception_class_def, write_promoted_property,
};

const DEFAULT_MANIFEST_PG: &str = include_str!("../../manifests/php-amphp.toml");
const DEFAULT_MANIFEST_MYSQL: &str = include_str!("../../manifests/php-amphp.mysql.toml");

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

/// ~keep The handle every generated function takes. This was `\Amp\Sql\SqlConnectionPool`,
/// which a single connection does not satisfy -- and on MySQL a pool is the wrong thing to
/// pass: `GetLastInsertUser` resolves `LAST_INSERT_ID()`, which is scoped to the connection
/// that ran the INSERT, so a pool routes the follow-up SELECT to a different connection and
/// it finds no row. `SqlExecutor` is the narrowest interface carrying the `prepare()` the
/// generated code actually calls, and both `MysqlConnectionPool` and `SocketMysqlConnection`
/// implement it (as do the PostgreSQL pair), so callers may pass either. Widening only --
/// existing callers passing a pool are unaffected.
const AMPHP_HANDLE_TYPE: &str = "\\Amp\\Sql\\SqlExecutor";

pub struct PhpAmphpBackend {
    manifest: BackendManifest,
    namespace: String,
    /// Canonical engine string, kept (like `java-jdbc`/`kotlin-jdbc`) so
    /// `generate_query_fn`/`generate_grouped_query_fn` can resolve the
    /// [`SqlDialect`] the SQL-text pipeline needs (board #148) -- `new` only had
    /// this as a local before.
    engine: String,
}

impl PhpAmphpBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        let default_toml = match engine {
            "postgresql" | "postgres" | "pg" => DEFAULT_MANIFEST_PG,
            "mysql" | "mariadb" => DEFAULT_MANIFEST_MYSQL,
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InvalidConfig,
                    format!("unsupported engine '{}' for php-amphp backend", engine),
                ));
            }
        };
        let manifest = super::parse_manifest(default_toml)?;
        Ok(Self {
            manifest,
            namespace: "App\\Generated".to_string(),
            engine: engine.to_string(),
        })
    }
}

/// Build the PHP expression that converts a raw AMPHP column value to the
/// type the manifest declares for it.
///
/// Keyed on `lang_type` -- the manifest's own declaration for this column --
/// rather than on `neutral_type`. The previous table matched on
/// `neutral_type` and hardcoded `json` and `decimal` into the `(string) `
/// arm, which held only by coincidence: `php-amphp.toml` declares
/// `json = "array"` while `php-amphp.mysql.toml` declares `json = "string"`.
/// A cast keyed on the neutral type alone cannot see that difference -- it
/// produced a `(string) ` cast against a property the same manifest had just
/// declared `array`. See #198.
///
/// Container types (`array<...>`, `range<...>`, `json_typed<...>`) resolve
/// `lang_type` to the same base string a scalar could (a bare PostgreSQL
/// array column and the `json` scalar both resolve to `"array"`), so they are
/// excluded up front by `neutral_type` rather than by `lang_type`: nothing
/// here parses a PostgreSQL array literal or unpacks a manifest-declared
/// struct, so no cast or decode of a container column can be correct in
/// general, and guessing from `lang_type` alone would decode a real array
/// column's `{a,b,c}` literal as JSON and silently get back `null`.
fn php_convert_column(neutral_type: &str, lang_type: &str, value_expr: &str) -> String {
    if neutral_type.contains('<') {
        return value_expr.to_string();
    }
    match lang_type {
        "int" => format!("(int) {value_expr}"),
        "float" => format!("(float) {value_expr}"),
        "bool" => format!("(bool) {value_expr}"),
        "string" => format!("(string) {value_expr}"),
        "array" => format!("json_decode({value_expr}, true)"),
        _ => value_expr.to_string(),
    }
}

/// Return the PHP value expression for decoding a single column from `$row`.
///
/// Used when building the `$parentArgs` dictionary in the grouped-query fold so
/// that parent field values are decoded with the same casts and enum/datetime
/// conversions as the regular `fromRow` factory.
fn php_row_expr(c: &ResolvedColumn) -> String {
    if let Some(value) = nested_json_column_expr(c, &format!("$row['{}']", c.name)) {
        return value;
    }
    let is_enum = c.neutral_type.starts_with("enum::");
    let is_composite = c.neutral_type.starts_with("composite::");
    let is_datetime = matches!(
        c.neutral_type.as_str(),
        "date" | "time" | "time_tz" | "datetime" | "datetime_tz"
    );
    if is_enum {
        if c.nullable {
            format!(
                "$row['{}'] !== null ? {}::from($row['{}']) : null",
                c.name, c.lang_type, c.name
            )
        } else {
            format!("{}::from($row['{}'])", c.lang_type, c.name)
        }
    } else if is_composite {
        // ~keep board #220: `fromText` already returns null for a null column, so no ternary
        // guard is needed here regardless of `c.nullable` -- unlike enum's `::from`/datetime's
        // `new \DateTimeImmutable`, both of which throw on null and must be guarded above.
        format!("{}::fromText($row['{}'])", c.lang_type, c.name)
    } else if is_datetime {
        if c.nullable {
            format!(
                "$row['{}'] !== null ? new \\DateTimeImmutable($row['{}']) : null",
                c.name, c.name
            )
        } else {
            format!("new \\DateTimeImmutable($row['{}'])", c.name)
        }
    } else {
        let value_expr = format!("$row['{}']", c.name);
        let converted = php_convert_column(&c.neutral_type, &c.lang_type, &value_expr);
        if c.nullable {
            format!("$row['{}'] !== null ? {} : null", c.name, converted)
        } else {
            converted
        }
    }
}

/// Write a `fromRow(array $row): self` static factory method for the given columns.
///
/// The output is byte-identical to what [`PhpAmphpBackend::generate_row_struct`] emits
/// for the same columns, keeping child struct `fromRow` consistent with regular row structs.
fn write_php_from_row_method(out: &mut String, columns: &[ResolvedColumn]) {
    let _ = writeln!(out, "    public static function fromRow(array $row): self {{");
    let _ = writeln!(out, "        return new self(");
    for c in columns.iter() {
        let sep = ",";
        if let Some(value) = nested_json_column_expr(c, &format!("$row['{}']", c.name)) {
            let _ = writeln!(out, "            {}: {}{}", c.field_name, value, sep);
            continue;
        }
        let is_enum = c.neutral_type.starts_with("enum::");
        let is_composite = c.neutral_type.starts_with("composite::");
        let is_datetime = matches!(
            c.neutral_type.as_str(),
            "date" | "time" | "time_tz" | "datetime" | "datetime_tz"
        );
        if is_enum {
            let enum_type = &c.lang_type;
            if c.nullable {
                let _ = writeln!(
                    out,
                    "            {}: $row['{}'] !== null ? {}::from($row['{}']) : null{}",
                    c.field_name, c.name, enum_type, c.name, sep
                );
            } else {
                let _ = writeln!(
                    out,
                    "            {}: {}::from($row['{}']){}",
                    c.field_name, enum_type, c.name, sep
                );
            }
        } else if is_composite {
            let _ = writeln!(
                out,
                "            {}: {}::fromText($row['{}']){}",
                c.field_name, c.lang_type, c.name, sep
            );
        } else if is_datetime {
            if c.nullable {
                let _ = writeln!(
                    out,
                    "            {}: $row['{}'] !== null ? new \\DateTimeImmutable($row['{}']) : null{}",
                    c.field_name, c.name, c.name, sep
                );
            } else {
                let _ = writeln!(
                    out,
                    "            {}: new \\DateTimeImmutable($row['{}']){}",
                    c.field_name, c.name, sep
                );
            }
        } else {
            let value_expr = format!("$row['{}']", c.name);
            let converted = php_convert_column(&c.neutral_type, &c.lang_type, &value_expr);
            if c.nullable {
                let _ = writeln!(
                    out,
                    "            {}: $row['{}'] !== null ? {} : null{}",
                    c.field_name, c.name, converted, sep
                );
            } else {
                let _ = writeln!(out, "            {}: {}{}", c.field_name, converted, sep);
            }
        }
    }
    let _ = writeln!(out, "        );");
    let _ = writeln!(out, "    }}");
}

impl CodegenBackend for PhpAmphpBackend {
    fn name(&self) -> &str {
        "php-amphp"
    }

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

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

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

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

        if let Some(ns) = options.get("namespace") {
            self.namespace = ns.clone();
        }
        Ok(())
    }

    fn file_preamble(&self) -> String {
        "<?php\n".to_string()
    }

    fn file_header(&self) -> String {
        let ns = if self.namespace.is_empty() {
            String::new()
        } else {
            format!("namespace {};\n\n", self.namespace)
        };
        format!(
            "declare(strict_types=1);\n\n{ns}{}",
            record_not_found_exception_class_def()
        )
    }

    fn file_header_for_results(&self, generated: &[GeneratedCode]) -> String {
        // ~keep Each composite's `fromText` calls the shared parser, which is declared exactly
        // once per file rather than copied into every composite class -- see
        // `php_common::PHP_COMPOSITE_PARSER_CLASS`. Gated on an actual call site so a file with
        // no composite column does not carry a class nothing references.
        format!(
            "{}{}",
            self.file_header(),
            super::php_common::composite_parser_class_if_used(generated)
        )
    }

    fn query_class_header(&self) -> String {
        "final class Queries {".to_string()
    }

    fn file_footer(&self) -> String {
        "}".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, "readonly class {} {{", struct_name);
        let _ = writeln!(out, "    public function __construct(");
        for c in columns.iter() {
            write_promoted_property(&mut out, c, &self.manifest)?;
        }
        let _ = writeln!(out, "    ) {{}}");
        let _ = writeln!(out);

        write_php_from_row_method(&mut out, columns);
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_query_fn(
        &self,
        analyzed: &AnalyzedQuery,
        struct_name: &str,
        _columns: &[ResolvedColumn],
        params: &[ResolvedParam],
    ) -> Result<String, ScytheError> {
        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let dialect = SqlDialect::from_str(&self.engine).unwrap_or_default();
        let cleaned_sql = super::clean_sql_oneline_with_optional_dialect(
            &analyzed.sql,
            dialect,
            &analyzed.optional_params,
            &analyzed.params,
        );
        let (rewritten_sql, occurrences) = super::rewrite_placeholders_indexed(&cleaned_sql, dialect, |position| {
            let placeholder = "?".to_string();
            let param = super::resolved_param_for_position(&analyzed.params, params, position);
            if self.engine == "postgresql" {
                param
                    .neutral_type
                    .strip_prefix("composite::")
                    .map_or(placeholder.clone(), |sql_type| format!("?::text::{sql_type}"))
            } else {
                placeholder
            }
        });
        let sql = crate::sql_literal::escape_php_single_quoted(&rewritten_sql);
        let mut out = String::new();

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

        if matches!(analyzed.command, QueryCommand::Batch) {
            let batch_fn_name = format!("{}Batch", func_name);
            let _ = writeln!(out, "    /**");
            let _ = writeln!(out, "     * @param {AMPHP_HANDLE_TYPE} $pool");
            let _ = writeln!(out, "     * @param array<int, array<int, mixed>> $items");
            let _ = writeln!(out, "     * @return void");
            let _ = writeln!(out, "     */");
            let _ = writeln!(
                out,
                "    public static function {}({AMPHP_HANDLE_TYPE} $pool, array $items): void {{",
                batch_fn_name
            );
            let _ = writeln!(out, "        $transaction = $pool->beginTransaction();");
            let _ = writeln!(out, "        try {{");
            let _ = writeln!(out, "            $stmt = $transaction->prepare('{}');", sql);
            let _ = writeln!(out, "            foreach ($items as $item) {{");
            if params.is_empty() {
                let _ = writeln!(out, "                $stmt->execute([]);");
            } else {
                let bindings = params
                    .iter()
                    .enumerate()
                    .map(|(index, param)| php_param_value(param, &format!("$item[{index}]")))
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "                $stmt->execute([{}]);", bindings);
            }
            let _ = writeln!(out, "            }}");
            let _ = writeln!(out, "            $transaction->commit();");
            let _ = writeln!(out, "        }} catch (\\Throwable $e) {{");
            let _ = writeln!(out, "            $transaction->rollback();");
            let _ = writeln!(out, "            throw $e;");
            let _ = writeln!(out, "        }}");
            let _ = write!(out, "    }}");
            return Ok(out);
        }

        let return_type = match &analyzed.command {
            // `:one` throws `RecordNotFoundException` instead of returning `null` on a
            // missing row (see the body match below), so its declared return type is
            // non-nullable -- see `php_pdo.rs`'s identical arm for why.
            QueryCommand::One => struct_name.to_string(),
            QueryCommand::Opt => format!("?{}", struct_name),
            QueryCommand::Many => "\\Generator".to_string(),
            QueryCommand::Exec => "void".to_string(),
            QueryCommand::ExecResult | QueryCommand::ExecRows => "int".to_string(),
            QueryCommand::Batch => unreachable!(),
            QueryCommand::Grouped => {
                unreachable!("Grouped is routed through generate_grouped_query_fn, not generate_query_fn")
            }
        };

        let _ = writeln!(out, "    /**");
        let _ = writeln!(out, "     * @param {AMPHP_HANDLE_TYPE} $pool");
        for p in params {
            let _ = writeln!(
                out,
                "     * @param {} ${}",
                param_docblock_type(p, &self.manifest)?,
                p.field_name
            );
        }
        match &analyzed.command {
            QueryCommand::One => {
                let _ = writeln!(out, "     * @return {}", struct_name);
                let _ = writeln!(out, "     * @throws {}", RECORD_NOT_FOUND_EXCEPTION_CLASS);
            }
            QueryCommand::Opt => {
                let _ = writeln!(out, "     * @return {}|null", struct_name);
            }
            QueryCommand::Many => {
                let _ = writeln!(out, "     * @return \\Generator<int, {}, mixed, void>", struct_name);
            }
            QueryCommand::Exec => {
                let _ = writeln!(out, "     * @return void");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "     * @return int");
            }
            QueryCommand::Batch => unreachable!(),
            QueryCommand::Grouped => {
                unreachable!("Grouped is routed through generate_grouped_query_fn, not generate_query_fn")
            }
        }
        let _ = writeln!(out, "     */");

        let _ = writeln!(
            out,
            "    public static function {}({AMPHP_HANDLE_TYPE} $pool{}{}): {} {{",
            func_name, sep, param_list, return_type
        );

        // NOTE: This prepares the statement on every call for simplicity.
        if occurrences.is_empty() {
            let _ = writeln!(out, "        $result = $pool->prepare('{}')->execute([]);", sql);
        } else {
            let bindings = occurrences
                .iter()
                .map(|&position| {
                    let p = super::resolved_param_for_position(&analyzed.params, params, position);
                    php_param_value(p, &format!("${}", p.field_name))
                })
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(
                out,
                "        $result = $pool->prepare('{}')->execute([{}]);",
                sql, bindings
            );
        }

        match &analyzed.command {
            QueryCommand::One => {
                let _ = writeln!(out, "        foreach ($result as $row) {{");
                let _ = writeln!(out, "            return {}::fromRow($row);", struct_name);
                let _ = writeln!(out, "        }}");
                let _ = writeln!(
                    out,
                    "        throw new {}('{}: no row found');",
                    RECORD_NOT_FOUND_EXCEPTION_CLASS, func_name
                );
            }
            QueryCommand::Opt => {
                let _ = writeln!(out, "        foreach ($result as $row) {{");
                let _ = writeln!(out, "            return {}::fromRow($row);", struct_name);
                let _ = writeln!(out, "        }}");
                let _ = writeln!(out, "        return null;");
            }
            QueryCommand::Many => {
                let _ = writeln!(out, "        foreach ($result as $row) {{");
                let _ = writeln!(out, "            yield {}::fromRow($row);", struct_name);
                let _ = writeln!(out, "        }}");
            }
            QueryCommand::Exec => {}
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(out, "        return $result->getRowCount();");
            }
            QueryCommand::Batch => unreachable!(),
            QueryCommand::Grouped => {
                unreachable!("Grouped is routed through generate_grouped_query_fn, not generate_query_fn")
            }
        }

        let _ = write!(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, "readonly class {} {{", child_struct_name);
        let _ = writeln!(out, "    public function __construct(");
        for c in child_columns.iter() {
            write_promoted_property(&mut out, c, &self.manifest)?;
        }
        let _ = writeln!(out, "    ) {{}}");
        let _ = writeln!(out);
        write_php_from_row_method(&mut out, child_columns);
        let _ = write!(out, "}}");

        let _ = writeln!(out);
        let _ = writeln!(out);

        let _ = writeln!(out, "readonly class {} {{", parent_struct_name);
        let _ = writeln!(out, "    public function __construct(");
        for c in parent_columns.iter() {
            write_promoted_property(&mut out, c, &self.manifest)?;
        }
        let _ = writeln!(out, "        /** @var {}[] */", child_struct_name);
        let _ = writeln!(out, "        public array $children,");
        let _ = writeln!(out, "    ) {{}}");
        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 params = request.params;
        let key_column = request.key_column;

        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let dialect = SqlDialect::from_str(&self.engine).unwrap_or_default();
        let cleaned_sql = super::clean_sql_oneline_with_optional_dialect(
            &analyzed.sql,
            dialect,
            &analyzed.optional_params,
            &analyzed.params,
        );
        let (rewritten_sql, occurrences) = super::rewrite_placeholders_indexed(&cleaned_sql, dialect, |position| {
            let param = super::resolved_param_for_position(&analyzed.params, params, position);
            if self.engine == "postgresql" {
                param
                    .neutral_type
                    .strip_prefix("composite::")
                    .map_or_else(|| "?".to_string(), |sql_type| format!("?::text::{sql_type}"))
            } else {
                "?".to_string()
            }
        });
        let sql = crate::sql_literal::escape_php_single_quoted(&rewritten_sql);
        let mut out = String::new();

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

        let _ = writeln!(out, "    /**");
        let _ = writeln!(out, "     * @param {AMPHP_HANDLE_TYPE} $pool");
        for p in params {
            let _ = writeln!(
                out,
                "     * @param {} ${}",
                param_docblock_type(p, &self.manifest)?,
                p.field_name
            );
        }
        let _ = writeln!(out, "     * @return {}[]", parent_struct_name);
        let _ = writeln!(out, "     */");

        let _ = writeln!(
            out,
            "    public static function {}({AMPHP_HANDLE_TYPE} $pool{}{}): array {{",
            func_name, sep, param_list
        );

        if occurrences.is_empty() {
            let _ = writeln!(out, "        $resultSet = $pool->prepare('{}')->execute([]);", sql);
        } else {
            let bindings = occurrences
                .iter()
                .map(|&position| {
                    let p = super::resolved_param_for_position(&analyzed.params, params, position);
                    php_param_value(p, &format!("${}", p.field_name))
                })
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(
                out,
                "        $resultSet = $pool->prepare('{}')->execute([{}]);",
                sql, bindings
            );
        }

        let _ = writeln!(out, "        /** @var array<int|string, int> $parentIndex */");
        let _ = writeln!(out, "        $parentIndex = [];");
        let _ = writeln!(out, "        /** @var array<int, array<string, mixed>> $parentArgs */");
        let _ = writeln!(out, "        $parentArgs = [];");
        let _ = writeln!(
            out,
            "        /** @var array<int, {}[]> $childrenMap */",
            child_struct_name
        );
        let _ = writeln!(out, "        $childrenMap = [];");

        let _ = writeln!(out, "        foreach ($resultSet as $row) {{");
        let _ = writeln!(out, "            $key = $row['{}'];", key_column);
        let _ = writeln!(out, "            if (!isset($parentIndex[$key])) {{");
        let _ = writeln!(out, "                $pos = count($parentArgs);");
        let _ = writeln!(out, "                $parentIndex[$key] = $pos;");
        let _ = writeln!(out, "                $parentArgs[] = [");
        for c in parent_columns {
            let expr = php_row_expr(c);
            let _ = writeln!(out, "                    '{}' => {},", c.field_name, expr);
        }
        let _ = writeln!(out, "                ];");
        let _ = writeln!(out, "                $childrenMap[] = [];");
        let _ = writeln!(out, "            }}");
        let _ = writeln!(out, "            $pos = $parentIndex[$key];");
        let _ = writeln!(
            out,
            "            $childrenMap[$pos][] = {}::fromRow($row);",
            child_struct_name
        );
        let _ = writeln!(out, "        }}");

        let _ = writeln!(out, "        $result = [];");
        let _ = writeln!(out, "        foreach ($parentArgs as $pos => $args) {{");
        let _ = writeln!(
            out,
            "            $result[] = new {}(...$args, children: $childrenMap[$pos]);",
            parent_struct_name
        );
        let _ = writeln!(out, "        }}");
        let _ = writeln!(out, "        return $result;");
        let _ = write!(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 {}: string {{", type_name);
        for value in &enum_info.values {
            let variant = enum_variant_name(value, &self.manifest.naming);
            let _ = writeln!(out, "    case {} = \"{}\";", variant, value);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        if self.manifest.backend.engine == "postgresql" {
            crate::backends::php_common::generate_nested_composite_def(composite, &self.manifest)
        } else {
            crate::backends::php_common::generate_composite_def(composite, &self.manifest)
        }
    }

    fn generate_nested_struct_def(
        &self,
        nested: &scythe_core::analyzer::NestedStructInfo,
    ) -> Result<Option<String>, ScytheError> {
        if self.manifest.backend.engine != "postgresql" {
            return Ok(None);
        }
        crate::backends::php_common::generate_nested_struct_def(nested, &self.manifest).map(Some)
    }

    fn generate_composite_def_for_nested(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        crate::backends::php_common::generate_nested_composite_def(composite, &self.manifest)
    }
}

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

    fn make_grouped_query() -> AnalyzedQuery {
        let parent_cols = vec![
            AnalyzedColumn {
                name: "id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "name".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "email".to_string(),
                neutral_type: "string".to_string(),
                nullable: false,
                ..Default::default()
            },
        ];
        let child_cols = vec![
            AnalyzedColumn {
                name: "order_id".to_string(),
                neutral_type: "int32".to_string(),
                nullable: false,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "total".to_string(),
                neutral_type: "decimal".to_string(),
                nullable: true,
                ..Default::default()
            },
            AnalyzedColumn {
                name: "order_date".to_string(),
                neutral_type: "datetime".to_string(),
                nullable: false,
                ..Default::default()
            },
        ];
        let all_cols = [parent_cols.clone(), child_cols.clone()].concat();
        AnalyzedQuery::build(|aq| {
            aq.name = "GetUsersWithOrders".to_string();
            aq.command = QueryCommand::Grouped;
            aq.sql = "SELECT u.id, u.name, u.email, o.id AS order_id, o.total, o.created_at AS order_date\nFROM users u\nJOIN 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_php_amphp_structs() {
        let backend = PhpAmphpBackend::new("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("readonly class GetUsersWithOrdersChildRow"),
            "missing child class; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("public static function fromRow"),
            "child missing fromRow; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("readonly class GetUsersWithOrdersRow"),
            "missing parent class; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("public array $children"),
            "parent missing children field; got:\n{row_struct}"
        );
        assert!(
            row_struct.contains("@var GetUsersWithOrdersChildRow[]"),
            "parent missing @var annotation for children; got:\n{row_struct}"
        );
        let child_pos = row_struct.find("readonly class GetUsersWithOrdersChildRow").unwrap();
        let parent_pos = row_struct.find("readonly class GetUsersWithOrdersRow").unwrap();
        assert!(child_pos < parent_pos, "child must precede parent; got:\n{row_struct}");
    }

    #[test]
    fn test_grouped_php_amphp_query_fn() {
        let backend = PhpAmphpBackend::new("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("getUsersWithOrders"),
            "missing function name; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("\\Amp\\Sql\\SqlExecutor $pool"),
            "missing Amp pool parameter; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("): array"),
            "wrong return type (expected array); got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("$parentIndex"),
            "missing fold index; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("$childrenMap"),
            "missing children map; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("foreach ($resultSet as $row)"),
            "must use foreach over resultSet; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("GetUsersWithOrdersChildRow::fromRow($row)"),
            "must fold children via fromRow; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("new GetUsersWithOrdersRow(...$args, children: $childrenMap[$pos])"),
            "must build parent with named-arg spread; got:\n{query_fn}"
        );
        assert!(
            query_fn.contains("return $result"),
            "must return result array; got:\n{query_fn}"
        );
    }

    #[test]
    fn test_php_amphp_nested_json_agg_emits_typed_objects() {
        use scythe_core::analyzer::{NestedFieldInfo, NestedStructInfo};

        let query = AnalyzedQuery::build(|analyzed| {
            analyzed.name = "GetUserOrders".to_string();
            analyzed.command = QueryCommand::Many;
            analyzed.sql = "SELECT jsonb_agg(o.*) AS orders FROM orders o".to_string();
            analyzed.columns = vec![scythe_core::analyzer::AnalyzedColumn {
                name: "orders".to_string(),
                neutral_type: "json_nested<array<GetUserOrdersRowOrders>>".to_string(),
                nullable: true,
                ..Default::default()
            }];
            analyzed.nested_structs = vec![NestedStructInfo {
                name: "get_user_orders_row_orders".to_string(),
                fields: vec![NestedFieldInfo {
                    name: "createdAt".to_string(),
                    neutral_type: "datetime_tz".to_string(),
                    nullable: false,
                }],
            }];
        });
        let backend = PhpAmphpBackend::new("postgresql").unwrap();
        let result = crate::generate_with_backend(&query, &backend).unwrap();
        let row_struct = result.row_struct.as_deref().unwrap();

        assert!(result.degraded_nested_structs.is_empty(), "{result:#?}");
        assert_eq!(result.nested_struct_defs.len(), 1, "{result:#?}");
        assert!(
            row_struct.contains("GetUserOrdersRowOrders::fromJson($item)"),
            "{row_struct}"
        );
        assert!(row_struct.contains("JSON_THROW_ON_ERROR"), "{row_struct}");
    }
}