Skip to main content

scythe_codegen/backends/
mod.rs

1pub(crate) mod csharp_microsoft_sqlite;
2pub(crate) mod csharp_mysqlconnector;
3pub(crate) mod csharp_npgsql;
4pub(crate) mod csharp_oracle;
5pub(crate) mod csharp_snowflake;
6pub(crate) mod csharp_sqlclient;
7pub(crate) mod elixir_common;
8pub(crate) mod elixir_ecto;
9pub(crate) mod elixir_exqlite;
10pub(crate) mod elixir_jamdb;
11pub(crate) mod elixir_myxql;
12pub(crate) mod elixir_postgrex;
13pub(crate) mod elixir_tds;
14pub(crate) mod go_common;
15pub(crate) mod go_database_sql;
16pub(crate) mod go_godror;
17pub(crate) mod go_gosnowflake;
18pub(crate) mod go_pgx;
19pub(crate) mod java_jdbc;
20pub(crate) mod java_r2dbc;
21pub(crate) mod jvm_common;
22pub(crate) mod kotlin_exposed;
23pub(crate) mod kotlin_jdbc;
24pub(crate) mod kotlin_r2dbc;
25pub(crate) mod php_amphp;
26pub(crate) mod php_common;
27pub(crate) mod php_pdo;
28pub(crate) mod python_aiomysql;
29pub(crate) mod python_aiosqlite;
30pub(crate) mod python_asyncpg;
31pub(crate) mod python_common;
32pub(crate) mod python_duckdb;
33pub(crate) mod python_oracledb;
34pub(crate) mod python_psycopg3;
35pub(crate) mod python_pyodbc;
36pub(crate) mod python_snowflake;
37pub(crate) mod ruby_mysql2;
38pub(crate) mod ruby_oci8;
39pub(crate) mod ruby_pg;
40pub(crate) mod ruby_rbs;
41pub(crate) mod ruby_sqlite3;
42pub(crate) mod ruby_tiny_tds;
43pub(crate) mod ruby_trilogy;
44pub(crate) mod rust_sibyl;
45pub(crate) mod rust_tiberius;
46pub(crate) mod sqlx;
47pub(crate) mod tokio_postgres;
48pub(crate) mod typescript_better_sqlite3;
49pub(crate) mod typescript_common;
50pub(crate) mod typescript_duckdb;
51pub(crate) mod typescript_kysely;
52pub(crate) mod typescript_mssql;
53pub(crate) mod typescript_mysql2;
54pub(crate) mod typescript_node_sqlite;
55pub(crate) mod typescript_oracledb;
56pub(crate) mod typescript_pg;
57pub(crate) mod typescript_postgres;
58pub(crate) mod typescript_snowflake;
59pub(crate) mod typescript_wasm_sqlite;
60
61use scythe_backend::manifest::BackendManifest;
62use scythe_backend::naming::NamingConfig;
63use scythe_core::SqlDialect;
64use scythe_core::analyzer::AnalyzedParam;
65use scythe_core::errors::{ErrorCode, ScytheError};
66
67use crate::backend_trait::{CodegenBackend, ResolvedParam};
68
69/// Parse a backend's compiled-in manifest.
70///
71/// Manifest selection is a pure function of (backend, engine). There is
72/// deliberately no filesystem lookup here: generated output must not depend
73/// on the process working directory (#82).
74pub(crate) fn parse_manifest(manifest_toml: &str) -> Result<BackendManifest, ScytheError> {
75    toml::from_str(manifest_toml).map_err(|e| ScytheError::new(ErrorCode::InternalError, format!("manifest: {e}")))
76}
77
78/// Validate and apply the `field_case` backend option, writing it into a
79/// backend's `NamingConfig`.
80///
81/// Shared by the five driver-level Java and Kotlin backends (`java-jdbc`,
82/// `java-r2dbc`, `kotlin-jdbc`, `kotlin-r2dbc`, `kotlin-exposed`). Unlike the
83/// TypeScript backends' `field_case` (see `typescript_common::TsFieldCase`),
84/// none of these five need a companion runtime remap: every row they build
85/// comes from an explicit `ResultSet`/`Row` getter call keyed by the raw SQL
86/// column name (`ResolvedColumn::name`), with `ResolvedColumn::field_name`
87/// used only as the emitted record/data-class property name -- see e.g.
88/// `java_jdbc::col_rs_expr`, which reads `rs.getX(col.name)` and assigns it
89/// positionally into a constructor whose declared parameter is `col.field_name`.
90/// Renaming the property therefore never changes what key the driver is
91/// asked to look up. `resolve::resolve_columns` is what performs the actual
92/// rename (and rejects same-query collisions) once this sets
93/// `NamingConfig.field_case`.
94pub(crate) fn apply_field_case_option(
95    naming: &mut NamingConfig,
96    backend_name: &str,
97    value: &str,
98) -> Result<(), ScytheError> {
99    match value {
100        "snake_case" | "camelCase" => {
101            naming.field_case = value.to_string();
102            Ok(())
103        }
104        other => Err(ScytheError::new(
105            ErrorCode::InvalidConfig,
106            format!("{backend_name}: invalid field_case '{other}' (expected 'snake_case' or 'camelCase')"),
107        )),
108    }
109}
110
111/// Whether a backend built for `engine` may emit nested-aggregate structs.
112///
113/// The four opted-in backends (`rust-sqlx`, `rust-tokio-postgres`, `go-pgx`,
114/// `python-psycopg3`) all also serve `redshift`, and `rust-sqlx` serves
115/// MySQL/MariaDB/SQLite besides. `json_agg` and `row_to_json` are PostgreSQL
116/// functions; Redshift has neither. The analyzer already declines to infer a
117/// nested type for a Redshift catalog, but the backend cannot rely on that
118/// alone — it also selects a *different manifest* per engine, and the
119/// Redshift manifests deliberately do not declare the `json_nested`
120/// container. Opting in there would resolve the column against a container
121/// the manifest never defines.
122///
123/// Kept as one predicate so all four backends answer the question the same
124/// way instead of each spelling out its own engine list.
125pub(crate) fn engine_supports_nested_aggregates(engine: &str) -> bool {
126    matches!(engine, "postgresql" | "postgres" | "pg")
127}
128
129/// The ADO.NET accessor a `csharp-*` backend must use for a column whose
130/// neutral type its driver-specific accessor table does not name.
131///
132/// `DbDataReader.GetValue` is declared to return `object`, so a record field
133/// the manifest declared as anything else -- `List<{T}>` for an `array`,
134/// `byte[]` for `bytes`, a composite record, `{T}` for `json_typed` -- does
135/// not bind to it. The compiler rejects the constructor call outright:
136///
137/// ```text
138/// error CS1503: Argument 2: cannot convert from 'object' to
139/// 'System.Collections.Generic.List<string>'
140/// ```
141///
142/// `DbDataReader.GetFieldValue<T>` is the typed path every ADO.NET provider
143/// inherits, and it returns `T` by signature. Naming the manifest's own
144/// declared type as `T` therefore makes the reader agree with the declaration
145/// by construction, rather than by a second hand-maintained table that can
146/// drift away from the manifest -- which is precisely how this defect
147/// (issue #155) survived in five backends at once.
148///
149/// The typed path is not merely a compile-time trick: verified against a live
150/// PostgreSQL 17 server through Npgsql 8, `GetFieldValue<List<string>>` reads
151/// a `text[]`, `GetFieldValue<TimeSpan>` an `interval`,
152/// `GetFieldValue<System.Net.IPAddress>` an `inet` and
153/// `GetFieldValue<byte[]>` a `bytea`. Degrading the *manifest* to whatever
154/// `GetValue`/`GetString` happens to return would throw away types the driver
155/// can genuinely produce.
156pub(crate) fn csharp_typed_reader_method(lang_type: &str) -> String {
157    format!("GetFieldValue<{lang_type}>")
158}
159
160/// A classified span of SQL text produced by [`tokenize_sql`].
161///
162/// One lexer pass drives both comment-stripping (`clean_sql`,
163/// `clean_sql_oneline`) and placeholder-rewriting (`rewrite_pg_placeholders`)
164/// -- see #186 and board #148, where two independent character scanners each got
165/// string/comment handling wrong in a different way. `Code` spans are the
166/// only spans either consumer may rewrite; every other span is opaque SQL
167/// text that must be reproduced byte-for-byte (module the caller's own
168/// whitespace joining).
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170enum SqlSpanKind {
171    /// Ordinary SQL: identifiers, keywords, operators, placeholders.
172    Code,
173    /// A `'...'` string literal, with `''` as the escape for an embedded quote.
174    SingleQuoted,
175    /// A `"..."` quoted identifier, with `""` as the escape for an embedded quote.
176    DoubleQuoted,
177    /// A PostgreSQL `$$...$$` or `$tag$...$tag$` dollar-quoted string.
178    DollarQuoted,
179    /// A MySQL/MariaDB `` `...` `` quoted identifier, with `` `` `` as the
180    /// escape for an embedded backtick. Only ever produced when the caller's
181    /// dialect is [`SqlDialect::MySQL`] (board #148 item 2).
182    Backtick,
183    /// An MSSQL `[...]` delimited identifier, with `]]` as the escape for an
184    /// embedded `]`. Only ever produced when the caller's dialect is
185    /// [`SqlDialect::MsSql`] (board #148 item 4) -- gating on dialect is what keeps
186    /// this from misreading PostgreSQL array-subscript syntax (`arr[1]`).
187    Bracketed,
188    /// A `-- ...` comment, running to end of line (the newline itself is not
189    /// part of the span).
190    LineComment,
191    /// A `/* ... */` comment. PostgreSQL nests these, so this tracks nesting
192    /// depth; an unterminated comment consumes to end of input.
193    BlockComment,
194}
195
196/// Tokenize `sql` into a sequence of classified spans whose text
197/// concatenates back to exactly `sql`.
198///
199/// This is the single source of truth for "is this character part of a
200/// string/identifier/comment, or is it live SQL". `dialect` gates the lexical
201/// forms that cannot be told apart from the text alone without knowing the
202/// target engine: MySQL/MariaDB backtick identifiers and `#` line comments
203/// (only under [`SqlDialect::MySQL`]), and MSSQL `[bracketed]` identifiers
204/// (only under [`SqlDialect::MsSql`]) -- `#` in particular collides with
205/// PostgreSQL's `#>`/`#>>` JSON operators, and `[`/`]` collide with
206/// PostgreSQL array-subscript syntax, so neither can be recognized
207/// dialect-blind (board #148).
208fn tokenize_sql(sql: &str, dialect: SqlDialect) -> Vec<(SqlSpanKind, String)> {
209    let chars: Vec<char> = sql.chars().collect();
210    let len = chars.len();
211    let mut spans: Vec<(SqlSpanKind, String)> = Vec::new();
212    let mut code_buf = String::new();
213    let mut i = 0;
214
215    while i < len {
216        let c = chars[i];
217
218        if c == '-' && i + 1 < len && chars[i + 1] == '-' {
219            flush_code_buf(&mut code_buf, &mut spans);
220            let start = i;
221            i += 2;
222            while i < len && chars[i] != '\n' {
223                i += 1;
224            }
225            spans.push((SqlSpanKind::LineComment, chars[start..i].iter().collect()));
226            continue;
227        }
228
229        if c == '/' && i + 1 < len && chars[i + 1] == '*' {
230            flush_code_buf(&mut code_buf, &mut spans);
231            let start = i;
232            i += 2;
233            let mut depth = 1u32;
234            while i < len && depth > 0 {
235                if chars[i] == '/' && i + 1 < len && chars[i + 1] == '*' {
236                    depth += 1;
237                    i += 2;
238                } else if chars[i] == '*' && i + 1 < len && chars[i + 1] == '/' {
239                    depth -= 1;
240                    i += 2;
241                } else {
242                    i += 1;
243                }
244            }
245            spans.push((SqlSpanKind::BlockComment, chars[start..i].iter().collect()));
246            continue;
247        }
248
249        if c == '\'' {
250            flush_code_buf(&mut code_buf, &mut spans);
251            let start = i;
252            i += 1;
253            while i < len {
254                if chars[i] == '\'' {
255                    if i + 1 < len && chars[i + 1] == '\'' {
256                        i += 2;
257                        continue;
258                    }
259                    i += 1;
260                    break;
261                }
262                i += 1;
263            }
264            spans.push((SqlSpanKind::SingleQuoted, chars[start..i].iter().collect()));
265            continue;
266        }
267
268        if c == '"' {
269            flush_code_buf(&mut code_buf, &mut spans);
270            let start = i;
271            i += 1;
272            while i < len {
273                if chars[i] == '"' {
274                    if i + 1 < len && chars[i + 1] == '"' {
275                        i += 2;
276                        continue;
277                    }
278                    i += 1;
279                    break;
280                }
281                i += 1;
282            }
283            spans.push((SqlSpanKind::DoubleQuoted, chars[start..i].iter().collect()));
284            continue;
285        }
286
287        if c == '`' && dialect == SqlDialect::MySQL {
288            flush_code_buf(&mut code_buf, &mut spans);
289            let start = i;
290            i += 1;
291            while i < len {
292                if chars[i] == '`' {
293                    if i + 1 < len && chars[i + 1] == '`' {
294                        i += 2;
295                        continue;
296                    }
297                    i += 1;
298                    break;
299                }
300                i += 1;
301            }
302            spans.push((SqlSpanKind::Backtick, chars[start..i].iter().collect()));
303            continue;
304        }
305
306        if c == '#' && dialect == SqlDialect::MySQL {
307            flush_code_buf(&mut code_buf, &mut spans);
308            let start = i;
309            while i < len && chars[i] != '\n' {
310                i += 1;
311            }
312            spans.push((SqlSpanKind::LineComment, chars[start..i].iter().collect()));
313            continue;
314        }
315
316        if c == '[' && dialect == SqlDialect::MsSql {
317            flush_code_buf(&mut code_buf, &mut spans);
318            let start = i;
319            i += 1;
320            while i < len {
321                if chars[i] == ']' {
322                    if i + 1 < len && chars[i + 1] == ']' {
323                        i += 2;
324                        continue;
325                    }
326                    i += 1;
327                    break;
328                }
329                i += 1;
330            }
331            spans.push((SqlSpanKind::Bracketed, chars[start..i].iter().collect()));
332            continue;
333        }
334
335        if c == '$'
336            && let Some(open_end) = match_dollar_quote_open(&chars, i)
337        {
338            flush_code_buf(&mut code_buf, &mut spans);
339            let start = i;
340            let delim: Vec<char> = chars[i..open_end].to_vec();
341            let mut j = open_end;
342            let mut found = false;
343            while j < len {
344                if chars[j] == '$' && j + delim.len() <= len && chars[j..j + delim.len()] == delim[..] {
345                    j += delim.len();
346                    found = true;
347                    break;
348                }
349                j += 1;
350            }
351            if !found {
352                j = len;
353            }
354            spans.push((SqlSpanKind::DollarQuoted, chars[start..j].iter().collect()));
355            i = j;
356            continue;
357        }
358
359        code_buf.push(c);
360        i += 1;
361    }
362
363    flush_code_buf(&mut code_buf, &mut spans);
364    spans
365}
366
367fn flush_code_buf(code_buf: &mut String, spans: &mut Vec<(SqlSpanKind, String)>) {
368    if !code_buf.is_empty() {
369        spans.push((SqlSpanKind::Code, std::mem::take(code_buf)));
370    }
371}
372
373/// If `chars[i]` (a `$`) opens a dollar-quote delimiter (`$$` or `$tag$`),
374/// return the index just past the opening delimiter. A tag follows SQL
375/// identifier rules (must not start with a digit), which is exactly what
376/// keeps this from misfiring on a `$1`-style placeholder.
377fn match_dollar_quote_open(chars: &[char], i: usize) -> Option<usize> {
378    let mut j = i + 1;
379    if j < chars.len() && chars[j] == '$' {
380        return Some(j + 1);
381    }
382    let tag_start = j;
383    while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
384        j += 1;
385    }
386    if j > tag_start && j < chars.len() && chars[j] == '$' && !chars[tag_start].is_ascii_digit() {
387        return Some(j + 1);
388    }
389    None
390}
391
392/// Strip SQL comments, trailing semicolons, and excess whitespace.
393/// Preserves newlines between lines.
394///
395/// Dialect-blind: kept for the call sites this multi-agent change did not
396/// reach (see [`clean_sql_dialect`] for the dialect-aware replacement, which
397/// every owned call site now uses). Passing `SqlDialect::PostgreSQL` into
398/// [`tokenize_sql`] here gates off the MySQL backtick/`#` and MSSQL bracket
399/// handling, reproducing this function's pre-board #148 behaviour exactly.
400pub(crate) fn clean_sql(sql: &str) -> String {
401    clean_sql_lines(sql, SqlDialect::PostgreSQL)
402        .join("\n")
403        .trim()
404        .trim_end_matches(';')
405        .trim()
406        .to_string()
407}
408
409/// Like clean_sql but joins lines with spaces (for languages that embed SQL inline).
410/// Dialect-blind; see [`clean_sql`]'s doc comment.
411pub(crate) fn clean_sql_oneline(sql: &str) -> String {
412    clean_sql_lines(sql, SqlDialect::PostgreSQL)
413        .join(" ")
414        .trim()
415        .trim_end_matches(';')
416        .trim()
417        .to_string()
418}
419
420/// Dialect-aware [`clean_sql`]: recognizes MySQL backtick identifiers/`#`
421/// comments and MSSQL `[bracketed]` identifiers per `dialect` (board #148).
422///
423/// ~keep No production caller yet: the four backends migrated to the
424/// dialect-aware pipeline all embed SQL as a single line and so reach for
425/// [`clean_sql_oneline_dialect`]. The multiline form is what the ~44
426/// still-unmigrated backends will need, and its tests below pin the MySQL
427/// backtick / `#`-comment and MSSQL bracket behaviour that only this
428/// signature exercises. `expect`, not `allow`, deliberately: it becomes a
429/// hard error the moment a caller appears, so the attribute cannot outlive
430/// the reason for it.
431#[cfg_attr(
432    not(test),
433    expect(dead_code, reason = "staged board #148 migration; see doc comment")
434)]
435pub(crate) fn clean_sql_dialect(sql: &str, dialect: SqlDialect) -> String {
436    clean_sql_lines(sql, dialect)
437        .join("\n")
438        .trim()
439        .trim_end_matches(';')
440        .trim()
441        .to_string()
442}
443
444/// Dialect-aware [`clean_sql_oneline`]; see [`clean_sql_dialect`].
445pub(crate) fn clean_sql_oneline_dialect(sql: &str, dialect: SqlDialect) -> String {
446    clean_sql_lines(sql, dialect)
447        .join(" ")
448        .trim()
449        .trim_end_matches(';')
450        .trim()
451        .to_string()
452}
453
454/// Split `sql` into lines with every comment (`--` and `/* */`, string- and
455/// dollar-quote-aware) removed, dropping any line whose content was entirely
456/// a comment.
457///
458/// A line is dropped only when a comment is what emptied it -- a line that
459/// was already blank in the source (no comment token touched it) is kept,
460/// matching the previous behaviour of the naive `starts_with("--")` filter
461/// for every case that filter got right. This is what lets a mid-line
462/// trailing comment (board #148) be stripped without deleting the rest of the
463/// query, while a `-- @name Foo` header line still disappears instead of
464/// leaving a blank line behind (every generated fixture depends on that).
465fn clean_sql_lines(sql: &str, dialect: SqlDialect) -> Vec<String> {
466    let normalized = sql.replace("\r\n", "\n");
467    let spans = tokenize_sql(&normalized, dialect);
468
469    let mut lines: Vec<String> = vec![String::new()];
470    let mut touched_by_comment: Vec<bool> = vec![false];
471
472    for (kind, text) in &spans {
473        let is_comment = matches!(kind, SqlSpanKind::LineComment | SqlSpanKind::BlockComment);
474        for ch in text.chars() {
475            if ch == '\n' {
476                if is_comment {
477                    *touched_by_comment.last_mut().expect("at least one line") = true;
478                }
479                lines.push(String::new());
480                touched_by_comment.push(false);
481            } else if is_comment {
482                *touched_by_comment.last_mut().expect("at least one line") = true;
483            } else {
484                lines.last_mut().expect("at least one line").push(ch);
485            }
486        }
487    }
488
489    lines
490        .into_iter()
491        .zip(touched_by_comment)
492        .filter(|(kept, touched)| !(*touched && kept.trim().is_empty()))
493        .map(|(kept, _)| kept)
494        .collect()
495}
496
497/// Rewrite SQL for optional parameters.
498///
499/// For each optional param, finds `column = $N` (or `column <> $N`, `column != $N`)
500/// and rewrites to `($N IS NULL OR column = $N)`. This allows callers to pass NULL
501/// to skip a filter condition at runtime.
502///
503/// This operates on the raw SQL before any backend-specific placeholder rewriting.
504pub(crate) fn rewrite_optional_params(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
505    if optional_params.is_empty() {
506        return sql.to_string();
507    }
508
509    let mut result = sql.to_string();
510
511    for opt_name in optional_params {
512        let Some(param) = params.iter().find(|p| p.name == *opt_name) else {
513            continue;
514        };
515        let placeholder = format!("${}", param.position);
516
517        for op in &[
518            ">=",
519            "<=",
520            "<>",
521            "!=",
522            ">",
523            "<",
524            "=",
525            "NOT ILIKE",
526            "not ilike",
527            "NOT LIKE",
528            "not like",
529            "ILIKE",
530            "ilike",
531            "LIKE",
532            "like",
533        ] {
534            result = rewrite_comparison(&result, &placeholder, op);
535        }
536    }
537
538    result
539}
540
541/// The PostgreSQL cast suffix for an optional parameter's neutral type.
542///
543/// `@optional` rewrites `col = $1` to `($1 IS NULL OR col = $1)`. The `IS
544/// NULL` arm gives the placeholder no type context, so PostgreSQL rejects the
545/// query with `could not determine data type of parameter $1`. Typing the
546/// first occurrence (`$1::text`) types the parameter for the whole statement.
547/// Returns `None` for a neutral type with no safe spelling, in which case the
548/// untyped rewrite is left as-is (#298).
549fn pg_cast_suffix(neutral_type: &str) -> Option<String> {
550    use scythe_core::analyzer::neutral_to_sql_label;
551
552    if let Some(enum_name) = neutral_type.strip_prefix("enum::") {
553        return Some(enum_name.to_string());
554    }
555    if let Some(composite_name) = neutral_type.strip_prefix("composite::") {
556        // Composite parameters are bound as their text form (`encode{Name}`).
557        return Some(format!("text::{composite_name}"));
558    }
559    if neutral_type.starts_with("json_typed<") {
560        return Some("jsonb".to_string());
561    }
562    if let Some(inner) = neutral_type
563        .strip_prefix("array<")
564        .and_then(|rest| rest.strip_suffix('>'))
565    {
566        let element = match inner {
567            "json" | "json_array" => "jsonb".to_string(),
568            other => neutral_to_sql_label(other).to_string(),
569        };
570        return Some(format!("{element}[]"));
571    }
572    match neutral_type {
573        "json" => Some("jsonb".to_string()),
574        "json_array" => Some("jsonb[]".to_string()),
575        "bool" | "int16" | "int32" | "int64" | "float32" | "float64" | "string" | "bytes" | "uuid" | "decimal"
576        | "date" | "time" | "time_tz" | "datetime" | "datetime_tz" | "interval" | "inet" => {
577            Some(neutral_to_sql_label(neutral_type).to_string())
578        }
579        _ => None,
580    }
581}
582
583/// PostgreSQL variant of [`rewrite_optional_params`] that types the placeholder
584/// it introduces: `($1::text IS NULL OR col = $1)` (#298).
585pub(crate) fn rewrite_optional_params_pg(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
586    if optional_params.is_empty() {
587        return sql.to_string();
588    }
589
590    let mut result = sql.to_string();
591
592    for opt_name in optional_params {
593        let Some(param) = params.iter().find(|p| p.name == *opt_name) else {
594            continue;
595        };
596        let placeholder = format!("${}", param.position);
597        let cast = pg_cast_suffix(&param.neutral_type);
598
599        for op in &[
600            ">=",
601            "<=",
602            "<>",
603            "!=",
604            ">",
605            "<",
606            "=",
607            "NOT ILIKE",
608            "not ilike",
609            "NOT LIKE",
610            "not like",
611            "ILIKE",
612            "ilike",
613            "LIKE",
614            "like",
615        ] {
616            result = rewrite_comparison_typed(&result, &placeholder, op, cast.as_deref());
617        }
618    }
619
620    result
621}
622
623/// Rewrite a single `column <op> $N` pattern to `($N IS NULL OR column <op> $N)`.
624/// Handles both `column <op> $N` and `$N <op> column` orderings.
625fn rewrite_comparison(sql: &str, placeholder: &str, op: &str) -> String {
626    rewrite_comparison_typed(sql, placeholder, op, None)
627}
628
629/// [`rewrite_comparison`] with an optional cast on the `IS NULL` occurrence of
630/// the placeholder.
631fn rewrite_comparison_typed(sql: &str, placeholder: &str, op: &str, cast: Option<&str>) -> String {
632    let typed_placeholder = match cast {
633        Some(cast) => format!("{placeholder}::{cast}"),
634        None => placeholder.to_string(),
635    };
636    let mut result = String::with_capacity(sql.len() + 32);
637    let chars: Vec<char> = sql.chars().collect();
638    let len = chars.len();
639    let mut i = 0;
640
641    while i < len {
642        if let Some((_start, col, end)) = try_match_col_op_ph(&chars, i, op, placeholder) {
643            result.push_str(&format!("({typed_placeholder} IS NULL OR {col} {op} {placeholder})"));
644            i = end;
645            continue;
646        }
647
648        if let Some((end, col)) = try_match_ph_op_col(&chars, i, op, placeholder) {
649            result.push_str(&format!("({typed_placeholder} IS NULL OR {col} {op} {placeholder})"));
650            i = end;
651            continue;
652        }
653
654        result.push(chars[i]);
655        i += 1;
656    }
657
658    result
659}
660
661/// Keywords that `is_ident_char` would happily scan as a column name but
662/// that can never actually be one in this position. Without this check, a
663/// compound operator like `NOT LIKE` gets misread: the scanner captures
664/// `NOT` as "the column" and matches `LIKE` as "the operator", producing
665/// `col NOT ($N IS NULL OR LIKE $N)` -- invalid SQL that silently drops the
666/// real column (#186 item 3). This also guards against a second rewrite
667/// pass (e.g. plain `LIKE` running after `NOT LIKE` already matched) seeing
668/// the literal word `NOT` it just emitted and matching on that.
669fn is_reserved_non_column_keyword(ident: &str) -> bool {
670    matches!(
671        ident.to_ascii_uppercase().as_str(),
672        "NOT" | "AND" | "OR" | "IS" | "NULL"
673    )
674}
675
676/// Match `op`, split on whitespace, against `chars` starting at `j`,
677/// tolerating any amount of whitespace between words of a compound operator
678/// (`NOT LIKE`, `NOT ILIKE`). Single-word operators degenerate to an exact
679/// literal match, same as before. Returns the index just past the match.
680fn match_op_tokens(chars: &[char], mut j: usize, op: &str) -> Option<usize> {
681    for (idx, word) in op.split_whitespace().enumerate() {
682        if idx > 0 {
683            let ws_start = j;
684            while j < chars.len() && chars[j].is_whitespace() {
685                j += 1;
686            }
687            if j == ws_start {
688                return None;
689            }
690        }
691        let word_chars: Vec<char> = word.chars().collect();
692        if j + word_chars.len() > chars.len() {
693            return None;
694        }
695        for (k, wc) in word_chars.iter().enumerate() {
696            if chars[j + k] != *wc {
697                return None;
698            }
699        }
700        j += word_chars.len();
701    }
702    Some(j)
703}
704
705/// Try to match `identifier <ws>* <op> <ws>* placeholder` starting at position `i`.
706/// Returns `(match_start, column_name, match_end)` if found.
707fn try_match_col_op_ph(chars: &[char], i: usize, op: &str, placeholder: &str) -> Option<(usize, String, usize)> {
708    if !is_ident_char(chars[i]) {
709        return None;
710    }
711    if i > 0 && is_ident_char(chars[i - 1]) {
712        return None;
713    }
714
715    let ident_start = i;
716    let mut j = i;
717    while j < chars.len() && is_ident_char(chars[j]) {
718        j += 1;
719    }
720    let ident: String = chars[ident_start..j].iter().collect();
721    if is_reserved_non_column_keyword(&ident) {
722        return None;
723    }
724
725    while j < chars.len() && chars[j].is_whitespace() {
726        j += 1;
727    }
728
729    j = match_op_tokens(chars, j, op)?;
730
731    while j < chars.len() && chars[j].is_whitespace() {
732        j += 1;
733    }
734
735    let ph_chars: Vec<char> = placeholder.chars().collect();
736    if j + ph_chars.len() > chars.len() {
737        return None;
738    }
739    for (k, pc) in ph_chars.iter().enumerate() {
740        if chars[j + k] != *pc {
741            return None;
742        }
743    }
744    j += ph_chars.len();
745
746    if j < chars.len() && chars[j].is_ascii_digit() {
747        return None;
748    }
749
750    Some((i, ident, j))
751}
752
753/// Try to match `placeholder <ws>* <op> <ws>* identifier` starting at position `i`.
754/// Returns `(match_end, column_name)` if found.
755fn try_match_ph_op_col(chars: &[char], i: usize, op: &str, placeholder: &str) -> Option<(usize, String)> {
756    let ph_chars: Vec<char> = placeholder.chars().collect();
757    if i + ph_chars.len() > chars.len() {
758        return None;
759    }
760
761    if i > 0 && (chars[i - 1] == '$' || chars[i - 1].is_ascii_digit()) {
762        return None;
763    }
764
765    for (k, pc) in ph_chars.iter().enumerate() {
766        if chars[i + k] != *pc {
767            return None;
768        }
769    }
770    let mut j = i + ph_chars.len();
771
772    if j < chars.len() && chars[j].is_ascii_digit() {
773        return None;
774    }
775
776    while j < chars.len() && chars[j].is_whitespace() {
777        j += 1;
778    }
779
780    j = match_op_tokens(chars, j, op)?;
781
782    while j < chars.len() && chars[j].is_whitespace() {
783        j += 1;
784    }
785
786    if j >= chars.len() || !is_ident_char(chars[j]) {
787        return None;
788    }
789    let ident_start = j;
790    while j < chars.len() && is_ident_char(chars[j]) {
791        j += 1;
792    }
793    let ident: String = chars[ident_start..j].iter().collect();
794
795    if is_reserved_non_column_keyword(&ident) {
796        return None;
797    }
798
799    Some((j, ident))
800}
801
802/// Clean SQL and apply optional parameter rewriting.
803/// Dialect-blind; see [`clean_sql`]'s doc comment.
804pub(crate) fn clean_sql_with_optional(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
805    let cleaned = clean_sql(sql);
806    rewrite_optional_params(&cleaned, optional_params, params)
807}
808
809/// PostgreSQL [`clean_sql_with_optional`]: types the placeholder it
810/// introduces so `IS NULL` does not leave it untyped (#298).
811pub(crate) fn clean_sql_with_optional_pg(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
812    let cleaned = clean_sql(sql);
813    rewrite_optional_params_pg(&cleaned, optional_params, params)
814}
815
816/// Clean SQL (oneline) and apply optional parameter rewriting.
817/// Dialect-blind; see [`clean_sql`]'s doc comment.
818pub(crate) fn clean_sql_oneline_with_optional(
819    sql: &str,
820    optional_params: &[String],
821    params: &[AnalyzedParam],
822) -> String {
823    let cleaned = clean_sql_oneline(sql);
824    rewrite_optional_params(&cleaned, optional_params, params)
825}
826
827/// Dialect-aware [`clean_sql_oneline_with_optional`]; see [`clean_sql_dialect`].
828pub(crate) fn clean_sql_oneline_with_optional_dialect(
829    sql: &str,
830    dialect: SqlDialect,
831    optional_params: &[String],
832    params: &[AnalyzedParam],
833) -> String {
834    let cleaned = clean_sql_oneline_dialect(sql, dialect);
835    rewrite_optional_params(&cleaned, optional_params, params)
836}
837
838fn is_ident_char(c: char) -> bool {
839    c.is_alphanumeric() || c == '_' || c == '.'
840}
841
842/// Rewrite SQL placeholders (`$N` or `?`) to a target format.
843///
844/// Skips placeholders inside single-/double-quoted and dollar-quoted spans,
845/// and inside comments (see [`tokenize_sql`]). The `formatter` closure
846/// receives the parameter number (1-based) and returns the replacement.
847///
848/// Dialect-blind, kept for the call sites this multi-agent change did not
849/// reach: whether a bare `?` is a placeholder is decided by scanning the code
850/// spans for a `$`-followed-by-digit occurrence, and treating a bare `?` as a
851/// placeholder only when none exists. That heuristic has a known gap --
852/// [`rewrite_placeholders_indexed`]'s doc comment explains why, and is what
853/// every owned call site now uses instead.
854///
855/// `?|`, `?&`, `?-`, `?-|`, `?||`, and `@?` are multi-character PostgreSQL
856/// operators (JSONB key/path existence, geometric comparisons) that are
857/// **never** valid placeholder syntax in any dialect this crate targets, so
858/// [`rewrite_code_span_placeholders`] recognizes and skips them unconditionally
859/// -- independent of the `$N` heuristic above, and correct even for a
860/// zero-placeholder query that has no `$N` to anchor that heuristic on.
861pub(crate) fn rewrite_pg_placeholders(sql: &str, formatter: impl Fn(u32) -> String) -> String {
862    let spans = tokenize_sql(sql, SqlDialect::PostgreSQL);
863    let uses_dollar_placeholders = spans
864        .iter()
865        .any(|(kind, text)| *kind == SqlSpanKind::Code && code_span_has_dollar_number(text));
866
867    let mut result = String::with_capacity(sql.len());
868    let mut positional_counter: u32 = 0;
869    let mut occurrences: Vec<u32> = Vec::new();
870    for (kind, text) in &spans {
871        if *kind == SqlSpanKind::Code {
872            rewrite_code_span_placeholders(
873                text,
874                !uses_dollar_placeholders,
875                &formatter,
876                &mut positional_counter,
877                &mut result,
878                &mut occurrences,
879            );
880        } else {
881            result.push_str(text);
882        }
883    }
884    result
885}
886
887/// Whether a bare `?` can ever be a placeholder under `dialect`, decided from
888/// the dialect alone -- replacing the `$N`-occurrence heuristic in
889/// [`rewrite_pg_placeholders`] (board #148 item 1, #186).
890///
891/// Verified against sqlparser 0.62's own tokenizer (`src/tokenizer.rs`,
892/// the `'?' if self.dialect.supports_geometric_types()` arm, with the
893/// source comment "Postgres uses ? for jsonb operators, not prepared
894/// statements"): `PostgreSqlDialect` is the only builtin dialect that
895/// overrides `supports_geometric_types()` to `true` (`dialect/postgresql.rs`),
896/// so it is the only dialect whose tokenizer never emits `Token::Placeholder`
897/// for a lone `?` -- it always emits `Token::Question` or one of the
898/// JSONB/geometric operator tokens instead. A PostgreSQL query containing
899/// `data ? 'active'` therefore never held a placeholder in the first place,
900/// with or without another `$N` elsewhere in the query, and no
901/// parameter-count heuristic is needed to tell the two apart. Every other
902/// dialect this crate targets (MySQL, SQLite, MsSql, Oracle, Snowflake) uses
903/// bare `?` as its native positional placeholder syntax and has no
904/// JSONB-style operator that collides with it.
905fn dialect_allows_bare_question_mark_placeholder(dialect: SqlDialect) -> bool {
906    !matches!(dialect, SqlDialect::PostgreSQL)
907}
908
909/// Dialect-aware rewrite of SQL placeholders (`$N` or bare `?`), returning
910/// both the rewritten SQL and, for each placeholder occurrence rewritten (in
911/// textual order, including repeats), the `$N`/`?N` position number it
912/// resolved to.
913///
914/// Unlike [`rewrite_pg_placeholders`], whether a bare `?` is a placeholder is
915/// decided from `dialect` alone via
916/// [`dialect_allows_bare_question_mark_placeholder`], never from whether the
917/// query happens to also contain a `$N`.
918///
919/// The returned position list is what lets a caller bind per SQL-text
920/// occurrence instead of per declared parameter (GH #149): `$2 ... $1`
921/// binds out of declaration order, a repeated `$1` produces two occurrences
922/// of position `1`, and an `@optional` rewrite (`($1 IS NULL OR col = $1)`)
923/// likewise produces two occurrences of the same position -- all three need
924/// one bind per occurrence, not one bind per unique parameter, or the
925/// generated code either swaps arguments or throws a parameter-count
926/// mismatch at runtime.
927pub(crate) fn rewrite_placeholders_indexed(
928    sql: &str,
929    dialect: SqlDialect,
930    formatter: impl Fn(u32) -> String,
931) -> (String, Vec<u32>) {
932    let spans = tokenize_sql(sql, dialect);
933    let bare_question_is_placeholder = dialect_allows_bare_question_mark_placeholder(dialect);
934
935    let mut result = String::with_capacity(sql.len());
936    let mut positional_counter: u32 = 0;
937    let mut occurrences: Vec<u32> = Vec::new();
938    for (kind, text) in &spans {
939        if *kind == SqlSpanKind::Code {
940            rewrite_code_span_placeholders(
941                text,
942                bare_question_is_placeholder,
943                &formatter,
944                &mut positional_counter,
945                &mut result,
946                &mut occurrences,
947            );
948        } else {
949            result.push_str(text);
950        }
951    }
952    (result, occurrences)
953}
954
955/// Resolve the [`ResolvedParam`] that a [`rewrite_placeholders_indexed`]
956/// occurrence position refers to.
957///
958/// `resolve::resolve_params` builds `resolved` from `analyzed_params` in the
959/// same order (one output per input, positionally), so the index into one
960/// slice is the index into the other; `analyzed_params[i].position` is the
961/// actual `$N` the analyzer resolved parameter `i` to. This is what lets a
962/// backend bind an occurrence's own position back to a concrete parameter
963/// instead of assuming SQL-declaration order matches bind order (#149): a
964/// repeated `$1`, an out-of-order `$2 ... $1`, and an `@optional` rewrite all
965/// resolve correctly through this lookup because it is driven by the
966/// occurrence's own position, never by loop index.
967///
968/// Panics if `position` is not among `analyzed_params` -- every position
969/// [`rewrite_placeholders_indexed`] returns came from the same SQL text the
970/// analyzer walked to build `analyzed_params`, so a miss here means the two
971/// disagree about what that SQL contains, which is a scythe bug, not
972/// something a caller can recover from.
973pub(crate) fn resolved_param_for_position<'a>(
974    analyzed_params: &[AnalyzedParam],
975    resolved: &'a [ResolvedParam],
976    position: u32,
977) -> &'a ResolvedParam {
978    let idx = analyzed_params
979        .iter()
980        .position(|p| p.position == i64::from(position))
981        .unwrap_or_else(|| panic!("no analyzed parameter at position {position}; analyzed_params={analyzed_params:?}"));
982    &resolved[idx]
983}
984
985/// ~keep Rewrite live SQL placeholders and append PostgreSQL casts derived from their resolved types.
986pub(crate) fn rewrite_pg_typed_placeholders(
987    sql: &str,
988    analyzed_params: &[AnalyzedParam],
989    resolved_params: &[ResolvedParam],
990    cast_enums: bool,
991    formatter: impl Fn(u32) -> String,
992) -> (String, Vec<u32>) {
993    rewrite_placeholders_indexed(sql, SqlDialect::PostgreSQL, |position| {
994        let mut placeholder = formatter(position);
995        let param = resolved_param_for_position(analyzed_params, resolved_params, position);
996        if cast_enums && let Some(enum_type) = param.neutral_type.strip_prefix("enum::") {
997            placeholder.push_str("::");
998            placeholder.push_str(enum_type);
999        } else if let Some(composite_type) = param.neutral_type.strip_prefix("composite::") {
1000            placeholder.push_str("::text::");
1001            placeholder.push_str(composite_type);
1002        }
1003        placeholder
1004    })
1005}
1006
1007/// Whether `text` (a `Code`-span substring, guaranteed free of strings and
1008/// comments) contains a `$` immediately followed by an ASCII digit.
1009fn code_span_has_dollar_number(text: &str) -> bool {
1010    let chars: Vec<char> = text.chars().collect();
1011    (0..chars.len()).any(|i| chars[i] == '$' && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()))
1012}
1013
1014/// Multi-character PostgreSQL operators built on `?` or `@?` that are never
1015/// placeholder syntax in any dialect this crate targets -- JSONB key-array
1016/// existence (`?|`, `?&`) and jsonpath existence (`@?`), plus the geometric
1017/// comparison operators (`?-`, `?-|`, `?||`). Longer operators are listed
1018/// before the shorter operators they prefix (`?-|` before `?-`, `?||` before
1019/// `?|`) so the greedy match in [`match_unambiguous_operator`] picks the
1020/// longest one, not "the first two characters".
1021const UNAMBIGUOUS_OPERATORS: [&str; 6] = ["?-|", "?||", "?|", "?&", "?-", "@?"];
1022
1023/// If `chars[i..]` starts with one of [`UNAMBIGUOUS_OPERATORS`], return its
1024/// length so the caller can copy it through untouched.
1025fn match_unambiguous_operator(chars: &[char], i: usize) -> Option<usize> {
1026    UNAMBIGUOUS_OPERATORS.iter().find_map(|op| {
1027        let op_chars: Vec<char> = op.chars().collect();
1028        let end = i + op_chars.len();
1029        (end <= chars.len() && chars[i..end] == op_chars[..]).then_some(op_chars.len())
1030    })
1031}
1032
1033/// Rewrite `$N` and (when `bare_question_is_placeholder` is true) bare `?`
1034/// placeholders within a single `Code` span, appending the result to `out`,
1035/// advancing `counter` for each `?` consumed, and recording each rewritten
1036/// occurrence's resolved position (in output order) into `occurrences`.
1037///
1038/// Shared by [`rewrite_pg_placeholders`] (which computes
1039/// `bare_question_is_placeholder` from the `$N`-occurrence heuristic and
1040/// discards `occurrences`) and [`rewrite_placeholders_indexed`] (which
1041/// computes it from the dialect and returns `occurrences`) -- the actual
1042/// rewriting is one implementation; only how the two callers decide whether a
1043/// bare `?` counts differs. The multi-character operators in
1044/// [`UNAMBIGUOUS_OPERATORS`] have no such ambiguity and are always passed
1045/// through, regardless of `bare_question_is_placeholder`.
1046fn rewrite_code_span_placeholders(
1047    text: &str,
1048    bare_question_is_placeholder: bool,
1049    formatter: &impl Fn(u32) -> String,
1050    counter: &mut u32,
1051    out: &mut String,
1052    occurrences: &mut Vec<u32>,
1053) {
1054    let chars: Vec<char> = text.chars().collect();
1055    let len = chars.len();
1056    let mut i = 0;
1057    while i < len {
1058        if let Some(op_len) = match_unambiguous_operator(&chars, i) {
1059            out.extend(&chars[i..i + op_len]);
1060            i += op_len;
1061            continue;
1062        }
1063
1064        let ch = chars[i];
1065        if ch == '$' && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
1066            let mut j = i + 1;
1067            let mut num_str = String::new();
1068            while j < len && chars[j].is_ascii_digit() {
1069                num_str.push(chars[j]);
1070                j += 1;
1071            }
1072            let num: u32 = num_str.parse().unwrap_or(0);
1073            out.push_str(&formatter(num));
1074            occurrences.push(num);
1075            i = j;
1076        } else if ch == '?' && bare_question_is_placeholder && !chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
1077            *counter += 1;
1078            out.push_str(&formatter(*counter));
1079            occurrences.push(*counter);
1080            i += 1;
1081        } else {
1082            out.push(ch);
1083            i += 1;
1084        }
1085    }
1086}
1087
1088/// Get a backend by name and database engine.
1089///
1090/// The `engine` parameter (e.g., "postgresql", "mysql", "sqlite") determines
1091/// which manifest is loaded for type mappings. PG-only backends reject non-PG engines.
1092pub fn get_backend(name: &str, engine: &str) -> Result<Box<dyn CodegenBackend>, ScytheError> {
1093    let canonical_engine = normalize_engine(engine);
1094    let backend: Box<dyn CodegenBackend> = match name {
1095        "rust-sqlx" | "sqlx" | "rust" => Box::new(sqlx::SqlxBackend::new(canonical_engine)?),
1096        "rust-tokio-postgres" | "tokio-postgres" => {
1097            Box::new(tokio_postgres::TokioPostgresBackend::new(canonical_engine)?)
1098        }
1099        "python-psycopg3" | "python" => Box::new(python_psycopg3::PythonPsycopg3Backend::new(canonical_engine)?),
1100        "python-asyncpg" => Box::new(python_asyncpg::PythonAsyncpgBackend::new(canonical_engine)?),
1101        "python-aiomysql" => Box::new(python_aiomysql::PythonAiomysqlBackend::new(canonical_engine)?),
1102        "python-aiosqlite" => Box::new(python_aiosqlite::PythonAiosqliteBackend::new(canonical_engine)?),
1103        "python-duckdb" => Box::new(python_duckdb::PythonDuckdbBackend::new(canonical_engine)?),
1104        "typescript-postgres" | "ts" | "typescript" => {
1105            Box::new(typescript_postgres::TypescriptPostgresBackend::new(canonical_engine)?)
1106        }
1107        "javascript-postgres" => Box::new(typescript_postgres::TypescriptPostgresBackend::new_js(
1108            canonical_engine,
1109        )?),
1110        "typescript-pg" => Box::new(typescript_pg::TypescriptPgBackend::new(canonical_engine)?),
1111        "javascript-pg" => Box::new(typescript_pg::TypescriptPgBackend::new_js(canonical_engine)?),
1112        "typescript-mysql2" => Box::new(typescript_mysql2::TypescriptMysql2Backend::new(canonical_engine)?),
1113        "javascript-mysql2" => Box::new(typescript_mysql2::TypescriptMysql2Backend::new_js(canonical_engine)?),
1114        "typescript-better-sqlite3" => Box::new(typescript_better_sqlite3::TypescriptBetterSqlite3Backend::new(
1115            canonical_engine,
1116        )?),
1117        "javascript-better-sqlite3" => Box::new(typescript_better_sqlite3::TypescriptBetterSqlite3Backend::new_js(
1118            canonical_engine,
1119        )?),
1120        "typescript-duckdb" => Box::new(typescript_duckdb::TypescriptDuckdbBackend::new(canonical_engine)?),
1121        "javascript-duckdb" => Box::new(typescript_duckdb::TypescriptDuckdbBackend::new_js(canonical_engine)?),
1122        "typescript-node-sqlite" => Box::new(typescript_node_sqlite::TypescriptNodeSqliteBackend::new(
1123            canonical_engine,
1124        )?),
1125        "javascript-node-sqlite" => Box::new(typescript_node_sqlite::TypescriptNodeSqliteBackend::new_js(
1126            canonical_engine,
1127        )?),
1128        "typescript-wasm-sqlite" => Box::new(typescript_wasm_sqlite::TypescriptWasmSqliteBackend::new(
1129            canonical_engine,
1130        )?),
1131        "javascript-wasm-sqlite" => Box::new(typescript_wasm_sqlite::TypescriptWasmSqliteBackend::new_js(
1132            canonical_engine,
1133        )?),
1134        "typescript-kysely" | "kysely" => Box::new(typescript_kysely::TypescriptKyselyBackend::new(canonical_engine)?),
1135        "go-database-sql" => Box::new(go_database_sql::GoDatabaseSqlBackend::new(canonical_engine)?),
1136        "go-pgx" | "go" => Box::new(go_pgx::GoPgxBackend::new(canonical_engine)?),
1137        "java-jdbc" | "java" => Box::new(java_jdbc::JavaJdbcBackend::new(canonical_engine)?),
1138        "java-r2dbc" | "r2dbc-java" => Box::new(java_r2dbc::JavaR2dbcBackend::new(canonical_engine)?),
1139        "kotlin-exposed" | "exposed" => Box::new(kotlin_exposed::KotlinExposedBackend::new(canonical_engine)?),
1140        "kotlin-jdbc" | "kotlin" | "kt" => Box::new(kotlin_jdbc::KotlinJdbcBackend::new(canonical_engine)?),
1141        "kotlin-r2dbc" | "r2dbc-kotlin" => Box::new(kotlin_r2dbc::KotlinR2dbcBackend::new(canonical_engine)?),
1142        "csharp-npgsql" | "csharp" | "c#" | "dotnet" => {
1143            Box::new(csharp_npgsql::CsharpNpgsqlBackend::new(canonical_engine)?)
1144        }
1145        "csharp-mysqlconnector" => Box::new(csharp_mysqlconnector::CsharpMysqlConnectorBackend::new(
1146            canonical_engine,
1147        )?),
1148        "csharp-microsoft-sqlite" => Box::new(csharp_microsoft_sqlite::CsharpMicrosoftSqliteBackend::new(
1149            canonical_engine,
1150        )?),
1151        "elixir-postgrex" | "elixir" | "ex" => Box::new(elixir_postgrex::ElixirPostgrexBackend::new(canonical_engine)?),
1152        "elixir-ecto" | "ecto" => Box::new(elixir_ecto::ElixirEctoBackend::new(canonical_engine)?),
1153        "elixir-myxql" => Box::new(elixir_myxql::ElixirMyxqlBackend::new(canonical_engine)?),
1154        "elixir-exqlite" => Box::new(elixir_exqlite::ElixirExqliteBackend::new(canonical_engine)?),
1155        "ruby-pg" | "ruby" | "rb" => Box::new(ruby_pg::RubyPgBackend::new(canonical_engine)?),
1156        "ruby-mysql2" => Box::new(ruby_mysql2::RubyMysql2Backend::new(canonical_engine)?),
1157        "ruby-sqlite3" => Box::new(ruby_sqlite3::RubySqlite3Backend::new(canonical_engine)?),
1158        "ruby-trilogy" | "trilogy" => Box::new(ruby_trilogy::RubyTrilogyBackend::new(canonical_engine)?),
1159        "php-pdo" | "php" => Box::new(php_pdo::PhpPdoBackend::new(canonical_engine)?),
1160        "php-amphp" | "amphp" => Box::new(php_amphp::PhpAmphpBackend::new(canonical_engine)?),
1161        "rust-tiberius" | "tiberius" => Box::new(rust_tiberius::RustTiberiusBackend::new(canonical_engine)?),
1162        "python-pyodbc" | "pyodbc" => Box::new(python_pyodbc::PythonPyodbcBackend::new(canonical_engine)?),
1163        "typescript-mssql" | "tedious" => Box::new(typescript_mssql::TypescriptMssqlBackend::new(canonical_engine)?),
1164        "javascript-mssql" => Box::new(typescript_mssql::TypescriptMssqlBackend::new_js(canonical_engine)?),
1165        "csharp-sqlclient" => Box::new(csharp_sqlclient::CsharpSqlClientBackend::new(canonical_engine)?),
1166        "ruby-tiny-tds" | "tiny-tds" | "tiny_tds" => {
1167            Box::new(ruby_tiny_tds::RubyTinyTdsBackend::new(canonical_engine)?)
1168        }
1169        "elixir-tds" | "tds" => Box::new(elixir_tds::ElixirTdsBackend::new(canonical_engine)?),
1170        "rust-sibyl" | "sibyl" => Box::new(rust_sibyl::RustSibylBackend::new(canonical_engine)?),
1171        "python-oracledb" | "oracledb" => Box::new(python_oracledb::PythonOracledbBackend::new(canonical_engine)?),
1172        "typescript-oracledb" => Box::new(typescript_oracledb::TypescriptOracledbBackend::new(canonical_engine)?),
1173        "javascript-oracledb" => Box::new(typescript_oracledb::TypescriptOracledbBackend::new_js(
1174            canonical_engine,
1175        )?),
1176        "go-godror" | "godror" => Box::new(go_godror::GoGodrorBackend::new(canonical_engine)?),
1177        "csharp-oracle" => Box::new(csharp_oracle::CsharpOracleBackend::new(canonical_engine)?),
1178        "ruby-oci8" | "oci8" => Box::new(ruby_oci8::RubyOci8Backend::new(canonical_engine)?),
1179        "elixir-jamdb" | "jamdb" => Box::new(elixir_jamdb::ElixirJamdbBackend::new(canonical_engine)?),
1180        "python-snowflake" => Box::new(python_snowflake::PythonSnowflakeBackend::new(canonical_engine)?),
1181        "typescript-snowflake" => Box::new(typescript_snowflake::TypescriptSnowflakeBackend::new(canonical_engine)?),
1182        "javascript-snowflake" => Box::new(typescript_snowflake::TypescriptSnowflakeBackend::new_js(
1183            canonical_engine,
1184        )?),
1185        "go-gosnowflake" | "gosnowflake" => Box::new(go_gosnowflake::GoGosnowflakeBackend::new(canonical_engine)?),
1186        "csharp-snowflake" => Box::new(csharp_snowflake::CsharpSnowflakeBackend::new(canonical_engine)?),
1187        _ => {
1188            return Err(ScytheError::new(
1189                ErrorCode::InvalidConfig,
1190                format!("unknown backend: {}", name),
1191            ));
1192        }
1193    };
1194
1195    if !backend
1196        .supported_engines()
1197        .iter()
1198        .any(|e| normalize_engine(e) == canonical_engine)
1199    {
1200        return Err(ScytheError::new(
1201            ErrorCode::InvalidConfig,
1202            format!(
1203                "backend '{}' does not support engine '{}'. Supported: {:?}",
1204                name,
1205                engine,
1206                backend.supported_engines()
1207            ),
1208        ));
1209    }
1210
1211    Ok(backend)
1212}
1213
1214/// Normalize engine name to canonical form.
1215///
1216/// Public so callers outside this crate (e.g. `scythe-cli`) can classify a
1217/// `[[sql]]` block's configured engine without duplicating the alias table —
1218/// for example, to decide whether a block is PostgreSQL-wire-compatible
1219/// before attempting live-database verification.
1220pub fn normalize_engine(engine: &str) -> &str {
1221    match engine {
1222        "postgresql" | "postgres" | "pg" | "cockroachdb" | "crdb" => "postgresql",
1223        "mysql" => "mysql",
1224        "mariadb" => "mariadb",
1225        "sqlite" | "sqlite3" => "sqlite",
1226        "duckdb" => "duckdb",
1227        "mssql" | "sqlserver" | "tsql" => "mssql",
1228        "oracle" => "oracle",
1229        "snowflake" => "snowflake",
1230        "redshift" => "redshift",
1231        other => other,
1232    }
1233}
1234
1235/// Exact-value characterization tests for `clean_sql`, `clean_sql_oneline`,
1236/// and `rewrite_pg_placeholders`, kept in their own file so the pinned
1237/// behaviour is readable as a specification for the planned dialect-aware
1238/// tokenizer.
1239#[cfg(test)]
1240mod sql_text_characterization_tests;
1241
1242#[cfg(test)]
1243mod tests {
1244    use super::*;
1245
1246    fn param(name: &str, position: i64) -> AnalyzedParam {
1247        AnalyzedParam {
1248            name: name.to_string(),
1249            neutral_type: "string".to_string(),
1250            nullable: true,
1251            position,
1252            source_relation: None,
1253        }
1254    }
1255
1256    fn resolved_param(name: &str, neutral_type: &str) -> ResolvedParam {
1257        ResolvedParam {
1258            name: name.to_string(),
1259            field_name: name.to_string(),
1260            lang_type: "String".to_string(),
1261            full_type: "String".to_string(),
1262            borrowed_type: "&str".to_string(),
1263            neutral_type: neutral_type.to_string(),
1264            nullable: false,
1265        }
1266    }
1267
1268    #[test]
1269    fn typed_placeholder_casts_only_rewrite_live_tokens_and_keep_number_boundaries() {
1270        let analyzed: Vec<AnalyzedParam> = (1..=10)
1271            .map(|position| param(&format!("p{position}"), position))
1272            .collect();
1273        let resolved: Vec<ResolvedParam> = (1..=10)
1274            .map(|position| {
1275                let neutral_type = match position {
1276                    1 => "composite::address",
1277                    10 => "enum::status",
1278                    _ => "string",
1279                };
1280                resolved_param(&format!("p{position}"), neutral_type)
1281            })
1282            .collect();
1283        let sql = "SELECT $1, $10, '$1', \"$10\", $$ $1 $10 $$ -- $1\n/* $10 */ WHERE x = $2";
1284
1285        let (rewritten, occurrences) =
1286            rewrite_pg_typed_placeholders(sql, &analyzed, &resolved, true, |position| format!("@p{position}"));
1287
1288        assert_eq!(
1289            rewritten,
1290            "SELECT @p1::text::address, @p10::status, '$1', \"$10\", $$ $1 $10 $$ -- $1\n/* $10 */ WHERE x = @p2"
1291        );
1292        assert_eq!(occurrences, vec![1, 10, 2]);
1293    }
1294
1295    /// Structural guard for #82: no source file under `src/backends` may
1296    /// reference a manifest path relative to the process working directory,
1297    /// however that reference is spelled. This catches a reintroduction of
1298    /// the filesystem-lookup pattern written differently from the original
1299    /// (different variable names, a helper function, etc.) that a simple
1300    /// function-name grep for the old `load_or_default_manifest` helper would
1301    /// miss.
1302    ///
1303    /// The forbidden needle is built at runtime, not written as a literal
1304    /// here, so this check does not trip over its own source describing what
1305    /// it looks for.
1306    #[test]
1307    fn test_no_backends_relative_manifest_path_literals() {
1308        let root = concat!(env!("CARGO_MANIFEST_DIR"), "/src/backends");
1309        let word: String = format!("backend{}", "s/");
1310        let needle: String = format!("{}{}", '"', word);
1311
1312        let mut offenders = Vec::new();
1313        collect_rs_files(std::path::Path::new(root), &mut offenders);
1314
1315        let offenders: Vec<_> = offenders
1316            .into_iter()
1317            .filter(|path| {
1318                let contents = std::fs::read_to_string(path).expect("failed to read source file");
1319                contents.contains(&needle)
1320            })
1321            .collect();
1322
1323        assert!(
1324            offenders.is_empty(),
1325            "found a working-directory-relative manifest path literal in: {offenders:?} (#82 regression \
1326             -- manifest selection must be a pure function of (backend, engine), no filesystem lookup)"
1327        );
1328    }
1329
1330    /// Recursively collect every `.rs` file path under `dir`.
1331    fn collect_rs_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
1332        let entries = std::fs::read_dir(dir).expect("failed to read backends dir");
1333        for entry in entries {
1334            let entry = entry.expect("failed to read dir entry");
1335            let path = entry.path();
1336            if path.is_dir() {
1337                collect_rs_files(&path, out);
1338            } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
1339                out.push(path);
1340            }
1341        }
1342    }
1343
1344    /// Documents the engine-blind collision the deleted CWD-relative lookup
1345    /// would have caused: two backends sharing a backend-name-only manifest
1346    /// path (`backends/<name>/manifest.toml`) but supporting different
1347    /// engines would have silently shared one manifest file on disk. Pure
1348    /// `(backend, engine)` selection must not exhibit this collision.
1349    #[test]
1350    fn test_get_backend_rust_sqlx_mysql_has_no_postgresql_scalars() {
1351        let backend = get_backend("rust-sqlx", "mysql").expect("rust-sqlx should support mysql");
1352        let scalars = &backend.manifest().types.scalars;
1353        assert_ne!(
1354            scalars.get("uuid").map(String::as_str),
1355            Some("uuid::Uuid"),
1356            "rust-sqlx/mysql manifest should not carry the PostgreSQL-specific 'uuid' mapping"
1357        );
1358        assert_ne!(
1359            scalars.get("inet").map(String::as_str),
1360            Some("ipnetwork::IpNetwork"),
1361            "rust-sqlx/mysql manifest should not carry the PostgreSQL-specific 'inet' mapping"
1362        );
1363    }
1364
1365    #[test]
1366    fn test_get_backend_java_jdbc_sqlite_has_no_postgresql_scalars() {
1367        let backend = get_backend("java-jdbc", "sqlite").expect("java-jdbc should support sqlite");
1368        let scalars = &backend.manifest().types.scalars;
1369        assert_ne!(
1370            scalars.get("uuid").map(String::as_str),
1371            Some("java.util.UUID"),
1372            "java-jdbc/sqlite manifest should not carry the PostgreSQL-specific 'uuid' mapping"
1373        );
1374        assert_ne!(
1375            scalars.get("decimal").map(String::as_str),
1376            Some("java.math.BigDecimal"),
1377            "java-jdbc/sqlite manifest should not carry the PostgreSQL-specific 'decimal' mapping"
1378        );
1379    }
1380
1381    #[test]
1382    fn test_normalize_engine_cockroachdb() {
1383        assert_eq!(normalize_engine("cockroachdb"), "postgresql");
1384        assert_eq!(normalize_engine("crdb"), "postgresql");
1385    }
1386
1387    #[test]
1388    fn test_get_backend_cockroachdb_with_pg_backends() {
1389        let pg_backends = [
1390            "rust-sqlx",
1391            "rust-tokio-postgres",
1392            "python-psycopg3",
1393            "python-asyncpg",
1394            "typescript-postgres",
1395            "typescript-pg",
1396            "typescript-kysely",
1397            "go-pgx",
1398            "ruby-pg",
1399            "elixir-postgrex",
1400            "csharp-npgsql",
1401            "php-pdo",
1402            "php-amphp",
1403        ];
1404        for backend_name in &pg_backends {
1405            let result = get_backend(backend_name, "cockroachdb");
1406            assert!(
1407                result.is_ok(),
1408                "backend '{}' should accept cockroachdb engine, got: {:?}",
1409                backend_name,
1410                result.err()
1411            );
1412        }
1413    }
1414
1415    #[test]
1416    fn test_get_backend_crdb_alias() {
1417        let result = get_backend("rust-sqlx", "crdb");
1418        assert!(result.is_ok(), "rust-sqlx should accept 'crdb' engine alias");
1419    }
1420
1421    #[test]
1422    fn test_normalize_engine_duckdb() {
1423        assert_eq!(normalize_engine("duckdb"), "duckdb");
1424    }
1425
1426    #[test]
1427    fn test_get_backend_duckdb_with_compatible_backends() {
1428        let duckdb_backends = [
1429            "python-duckdb",
1430            "typescript-duckdb",
1431            "go-database-sql",
1432            "java-jdbc",
1433            "kotlin-jdbc",
1434        ];
1435        for backend_name in &duckdb_backends {
1436            let result = get_backend(backend_name, "duckdb");
1437            assert!(
1438                result.is_ok(),
1439                "backend '{}' should accept duckdb engine, got: {:?}",
1440                backend_name,
1441                result.err()
1442            );
1443        }
1444    }
1445
1446    #[test]
1447    fn test_get_backend_duckdb_rejected_by_pg_only() {
1448        let result = get_backend("rust-sqlx", "duckdb");
1449        assert!(result.is_err(), "rust-sqlx should reject duckdb engine");
1450    }
1451
1452    #[test]
1453    fn test_rewrite_simple_equality() {
1454        let sql = "SELECT * FROM users WHERE status = $1";
1455        let params = vec![param("status", 1)];
1456        let result = rewrite_optional_params(sql, &["status".to_string()], &params);
1457        assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR status = $1)");
1458    }
1459
1460    /// #298: PostgreSQL cannot infer a parameter's type from `IS NULL`, so the
1461    /// rewrite types its first occurrence.
1462    #[test]
1463    fn test_rewrite_pg_simple_equality_casts_the_placeholder() {
1464        let sql = "SELECT * FROM users WHERE status = $1";
1465        let params = vec![param("status", 1)];
1466        let result = rewrite_optional_params_pg(sql, &["status".to_string()], &params);
1467        assert_eq!(result, "SELECT * FROM users WHERE ($1::text IS NULL OR status = $1)");
1468    }
1469
1470    #[test]
1471    fn test_rewrite_pg_casts_enum_array_and_json_but_not_unknown() {
1472        let mut enum_param = param("status", 1);
1473        enum_param.neutral_type = "enum::user_status".to_string();
1474        assert_eq!(
1475            rewrite_optional_params_pg(
1476                "SELECT * FROM users WHERE status = $1",
1477                &["status".to_string()],
1478                &[enum_param]
1479            ),
1480            "SELECT * FROM users WHERE ($1::user_status IS NULL OR status = $1)"
1481        );
1482
1483        let mut array_param = param("ids", 1);
1484        array_param.neutral_type = "array<int32>".to_string();
1485        assert_eq!(
1486            rewrite_optional_params_pg(
1487                "SELECT * FROM users WHERE id = $1",
1488                &["ids".to_string()],
1489                &[array_param]
1490            ),
1491            "SELECT * FROM users WHERE ($1::integer[] IS NULL OR id = $1)"
1492        );
1493
1494        let mut json_param = param("doc", 1);
1495        json_param.neutral_type = "json".to_string();
1496        assert_eq!(
1497            rewrite_optional_params_pg(
1498                "SELECT * FROM users WHERE doc = $1",
1499                &["doc".to_string()],
1500                &[json_param]
1501            ),
1502            "SELECT * FROM users WHERE ($1::jsonb IS NULL OR doc = $1)"
1503        );
1504
1505        let mut unknown_param = param("mystery", 1);
1506        unknown_param.neutral_type = "unknown".to_string();
1507        assert_eq!(
1508            rewrite_optional_params_pg(
1509                "SELECT * FROM users WHERE mystery = $1",
1510                &["mystery".to_string()],
1511                &[unknown_param]
1512            ),
1513            "SELECT * FROM users WHERE ($1 IS NULL OR mystery = $1)"
1514        );
1515    }
1516
1517    #[test]
1518    fn test_rewrite_qualified_column() {
1519        let sql = "SELECT * FROM users u WHERE u.status = $1";
1520        let params = vec![param("status", 1)];
1521        let result = rewrite_optional_params(sql, &["status".to_string()], &params);
1522        assert_eq!(result, "SELECT * FROM users u WHERE ($1 IS NULL OR u.status = $1)");
1523    }
1524
1525    #[test]
1526    fn test_rewrite_multiple_optional() {
1527        let sql = "SELECT * FROM users WHERE status = $1 AND name = $2";
1528        let params = vec![param("status", 1), param("name", 2)];
1529        let result = rewrite_optional_params(sql, &["status".to_string(), "name".to_string()], &params);
1530        assert_eq!(
1531            result,
1532            "SELECT * FROM users WHERE ($1 IS NULL OR status = $1) AND ($2 IS NULL OR name = $2)"
1533        );
1534    }
1535
1536    #[test]
1537    fn test_rewrite_mixed_optional_required() {
1538        let sql = "SELECT * FROM users WHERE id = $1 AND status = $2";
1539        let params = vec![param("id", 1), param("status", 2)];
1540        let result = rewrite_optional_params(sql, &["status".to_string()], &params);
1541        assert_eq!(
1542            result,
1543            "SELECT * FROM users WHERE id = $1 AND ($2 IS NULL OR status = $2)"
1544        );
1545    }
1546
1547    #[test]
1548    fn test_rewrite_like_operator() {
1549        let sql = "SELECT * FROM users WHERE name LIKE $1";
1550        let params = vec![param("name", 1)];
1551        let result = rewrite_optional_params(sql, &["name".to_string()], &params);
1552        assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR name LIKE $1)");
1553    }
1554
1555    #[test]
1556    fn test_rewrite_ilike_operator() {
1557        let sql = "SELECT * FROM users WHERE name ILIKE $1";
1558        let params = vec![param("name", 1)];
1559        let result = rewrite_optional_params(sql, &["name".to_string()], &params);
1560        assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR name ILIKE $1)");
1561    }
1562
1563    #[test]
1564    fn test_rewrite_comparison_operators() {
1565        let sql = "SELECT * FROM users WHERE age >= $1";
1566        let params = vec![param("age", 1)];
1567        let result = rewrite_optional_params(sql, &["age".to_string()], &params);
1568        assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR age >= $1)");
1569    }
1570
1571    #[test]
1572    fn test_rewrite_less_than() {
1573        let sql = "SELECT * FROM users WHERE age < $1";
1574        let params = vec![param("age", 1)];
1575        let result = rewrite_optional_params(sql, &["age".to_string()], &params);
1576        assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR age < $1)");
1577    }
1578
1579    #[test]
1580    fn test_no_rewrite_without_optional() {
1581        let sql = "SELECT * FROM users WHERE status = $1";
1582        let params = vec![param("status", 1)];
1583        let result = rewrite_optional_params(sql, &[], &params);
1584        assert_eq!(result, sql);
1585    }
1586
1587    #[test]
1588    fn test_rewrite_not_equal() {
1589        let sql = "SELECT * FROM users WHERE status <> $1";
1590        let params = vec![param("status", 1)];
1591        let result = rewrite_optional_params(sql, &["status".to_string()], &params);
1592        assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR status <> $1)");
1593    }
1594
1595    #[test]
1596    fn test_rewrite_does_not_match_similar_placeholder() {
1597        let sql = "SELECT * FROM users WHERE status = $10";
1598        let params = vec![param("status", 1)];
1599        let result = rewrite_optional_params(sql, &["status".to_string()], &params);
1600        assert_eq!(result, sql);
1601    }
1602
1603    #[test]
1604    fn test_normalize_engine_mariadb() {
1605        assert_eq!(normalize_engine("mariadb"), "mariadb");
1606    }
1607
1608    #[test]
1609    fn test_get_backend_mariadb_with_mysql_backends() {
1610        let mariadb_backends = [
1611            "rust-sqlx",
1612            "python-aiomysql",
1613            "typescript-mysql2",
1614            "go-database-sql",
1615            "java-jdbc",
1616            "java-r2dbc",
1617            "kotlin-jdbc",
1618            "kotlin-r2dbc",
1619            "csharp-mysqlconnector",
1620            "elixir-myxql",
1621            "ruby-mysql2",
1622            "ruby-trilogy",
1623            "php-pdo",
1624            "php-amphp",
1625        ];
1626        for backend_name in &mariadb_backends {
1627            let result = get_backend(backend_name, "mariadb");
1628            assert!(
1629                result.is_ok(),
1630                "backend '{}' should accept mariadb engine, got: {:?}",
1631                backend_name,
1632                result.err()
1633            );
1634        }
1635    }
1636
1637    // -----------------------------------------------------------------
1638    // SQL lexer / rewriting tests (board #148, #186, #149-adjacent).
1639    //
1640    // These pin down the behaviour of `clean_sql`, `clean_sql_oneline`, and
1641    // `rewrite_pg_placeholders` against a real SQL lexer instead of the
1642    // character-scanning implementation these functions previously had.
1643    // Written before the lexer existed, to prove each defect is real.
1644    // -----------------------------------------------------------------
1645
1646    #[test]
1647    fn test_clean_sql_oneline_strips_mid_line_comment_but_keeps_rest_of_query() {
1648        let sql = "SELECT id, name\nFROM users\nWHERE id > $1 -- skip low ids\n  AND name IS NOT NULL;";
1649        let result = clean_sql_oneline(sql);
1650        assert!(
1651            result.contains("AND name IS NOT NULL"),
1652            "mid-line comment must not swallow the rest of the query, got: {result:?}"
1653        );
1654        assert!(
1655            !result.contains("--"),
1656            "comment marker must be stripped, got: {result:?}"
1657        );
1658    }
1659
1660    #[test]
1661    fn test_clean_sql_strips_mid_line_comment_but_keeps_rest_of_query() {
1662        let sql = "SELECT id\nFROM users\nWHERE id > $1 -- skip low ids\nAND active = true;";
1663        let result = clean_sql(sql);
1664        assert!(result.contains("AND active = true"), "got: {result:?}");
1665        assert!(!result.contains("--"), "got: {result:?}");
1666    }
1667
1668    #[test]
1669    fn test_clean_sql_preserves_double_dash_inside_single_quoted_string() {
1670        let sql = "SELECT * FROM t WHERE label = 'a -- not a comment' AND id = $1;";
1671        let result = clean_sql_oneline(sql);
1672        assert!(result.contains("'a -- not a comment'"), "got: {result:?}");
1673        assert!(result.contains("id = $1"), "got: {result:?}");
1674    }
1675
1676    #[test]
1677    fn test_clean_sql_preserves_double_dash_inside_double_quoted_identifier() {
1678        let sql = "SELECT \"weird--col\" FROM t WHERE id = $1;";
1679        let result = clean_sql_oneline(sql);
1680        assert!(result.contains("\"weird--col\""), "got: {result:?}");
1681    }
1682
1683    #[test]
1684    fn test_clean_sql_preserves_double_dash_inside_dollar_quoted_string() {
1685        let sql = "SELECT $$has -- inside$$ AS x FROM t WHERE id = $1;";
1686        let result = clean_sql_oneline(sql);
1687        assert!(result.contains("$$has -- inside$$"), "got: {result:?}");
1688    }
1689
1690    #[test]
1691    fn test_clean_sql_strips_nested_block_comments() {
1692        let sql = "SELECT id /* outer /* inner */ still outer */ FROM t WHERE id = $1;";
1693        let result = clean_sql_oneline(sql);
1694        assert!(!result.contains("outer"), "got: {result:?}");
1695        assert!(!result.contains("inner"), "got: {result:?}");
1696        assert!(result.contains("SELECT id"), "got: {result:?}");
1697        assert!(result.contains("FROM t WHERE id = $1"), "got: {result:?}");
1698    }
1699
1700    #[test]
1701    fn test_clean_sql_unterminated_block_comment_consumes_to_end_without_panicking() {
1702        let sql = "SELECT id FROM t /* oops forgot to close";
1703        let result = clean_sql_oneline(sql);
1704        assert_eq!(result, "SELECT id FROM t");
1705    }
1706
1707    #[test]
1708    fn test_clean_sql_drops_lines_that_are_only_a_header_comment() {
1709        // Regression guard: header comment lines (`-- @name ...`) must be
1710        // deleted entirely, not replaced by a blank line -- every generated
1711        // fixture depends on this.
1712        let sql = "-- @name Foo\n-- @returns :many\nSELECT id FROM t WHERE id = $1;";
1713        let result = clean_sql(sql);
1714        assert_eq!(result, "SELECT id FROM t WHERE id = $1");
1715    }
1716
1717    #[test]
1718    fn test_rewrite_pg_placeholders_preserves_dollar_quoted_body() {
1719        let sql =
1720            "SELECT id FROM t WHERE body = $$literal -- not comment, ' quote, $1 not a placeholder$$ AND id = $2;";
1721        let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1722        assert!(
1723            result.contains("$$literal -- not comment, ' quote, $1 not a placeholder$$"),
1724            "dollar-quoted body must survive untouched, got: {result:?}"
1725        );
1726        assert!(result.contains("id = @p2"), "got: {result:?}");
1727    }
1728
1729    #[test]
1730    fn test_rewrite_pg_placeholders_handles_escaped_single_quotes() {
1731        let sql = "SELECT id FROM t WHERE label = 'it''s $1 not a placeholder' AND id = $2;";
1732        let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1733        assert!(result.contains("'it''s $1 not a placeholder'"), "got: {result:?}");
1734        assert!(result.contains("id = @p2"), "got: {result:?}");
1735    }
1736
1737    #[test]
1738    fn test_rewrite_pg_placeholders_preserves_jsonb_operators() {
1739        let sql = "SELECT id FROM docs WHERE data ? 'mykey' AND tags ?| array['a','b'] AND tags ?& array['a','b'] AND id = $1;";
1740        let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1741        assert!(result.contains("data ? 'mykey'"), "got: {result:?}");
1742        assert!(result.contains("tags ?| array"), "got: {result:?}");
1743        assert!(result.contains("tags ?& array"), "got: {result:?}");
1744        assert!(result.contains("id = @p1"), "got: {result:?}");
1745    }
1746
1747    /// Coordinator repro: a JSONB query with *zero* `$N` placeholders, so the
1748    /// `uses_dollar_placeholders` heuristic has nothing to anchor on. `?|`
1749    /// and `?&` are unambiguous -- never placeholder syntax in any dialect
1750    /// this crate targets -- so they must survive regardless of that
1751    /// heuristic. The bare `?` (`data ? 'active'`) is genuinely ambiguous
1752    /// without dialect information and is intentionally still rewritten
1753    /// here; see the residual-limitation comment on
1754    /// `rewrite_code_span_placeholders`.
1755    #[test]
1756    fn test_rewrite_pg_placeholders_preserves_jsonb_multi_char_operators_with_zero_dollar_placeholders() {
1757        let sql = "SELECT * FROM docs WHERE data ? 'active' AND tags ?| ARRAY['a'] AND meta ?& ARRAY['b']";
1758        let result = rewrite_pg_placeholders(sql, |n| format!("${n}"));
1759        assert!(result.contains("tags ?| ARRAY['a']"), "got: {result:?}");
1760        assert!(result.contains("meta ?& ARRAY['b']"), "got: {result:?}");
1761    }
1762
1763    #[test]
1764    fn test_rewrite_pg_placeholders_preserves_geometry_operators() {
1765        let sql = "SELECT id FROM shapes WHERE line1 ?- line2 AND line1 ?-| line2 AND line1 ?|| line2 AND id = $1;";
1766        let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1767        assert!(result.contains("line1 ?- line2"), "got: {result:?}");
1768        assert!(result.contains("line1 ?-| line2"), "got: {result:?}");
1769        assert!(result.contains("line1 ?|| line2"), "got: {result:?}");
1770        assert!(result.contains("id = @p1"), "got: {result:?}");
1771    }
1772
1773    #[test]
1774    fn test_rewrite_pg_placeholders_preserves_operators_mixed_with_dollar_placeholder() {
1775        let sql = "SELECT id FROM docs WHERE tags ?| ARRAY['a'] AND doc @? '$.a' AND id = $1;";
1776        let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1777        assert!(result.contains("tags ?| ARRAY['a']"), "got: {result:?}");
1778        assert!(result.contains("doc @? '$.a'"), "got: {result:?}");
1779        assert!(result.contains("id = @p1"), "got: {result:?}");
1780    }
1781
1782    #[test]
1783    fn test_rewrite_pg_placeholders_number_boundary() {
1784        let sql = "SELECT $1, $10, $1x";
1785        let result = rewrite_pg_placeholders(sql, |n| format!("P{n}"));
1786        assert_eq!(result, "SELECT P1, P10, P1x");
1787    }
1788
1789    #[test]
1790    fn test_rewrite_pg_placeholders_ignores_question_mark_inside_string_literal() {
1791        let sql = "SELECT id FROM t WHERE note = 'is this a question?' AND age > ?;";
1792        let result = rewrite_pg_placeholders(sql, |n| format!("${n}"));
1793        assert!(result.contains("'is this a question?'"), "got: {result:?}");
1794        assert!(result.contains("age > $1"), "got: {result:?}");
1795    }
1796
1797    #[test]
1798    fn test_clean_sql_handles_non_ascii_in_comment_and_string() {
1799        let sql = "SELECT name -- 名前を取得 comment\nFROM t WHERE label = 'héllo wörld' AND id = $1;";
1800        let result = clean_sql_oneline(sql);
1801        assert!(!result.contains('名'), "got: {result:?}");
1802        assert!(result.contains("'héllo wörld'"), "got: {result:?}");
1803        assert!(result.contains("id = $1"), "got: {result:?}");
1804    }
1805
1806    #[test]
1807    fn test_clean_sql_handles_crlf_line_endings() {
1808        let sql = "SELECT id\r\nFROM users\r\n-- a comment\r\nWHERE id = $1;";
1809        let result = clean_sql(sql);
1810        assert!(!result.contains('\r'), "got: {result:?}");
1811        assert!(!result.contains("-- a comment"), "got: {result:?}");
1812        assert_eq!(result, "SELECT id\nFROM users\nWHERE id = $1");
1813    }
1814
1815    #[test]
1816    fn test_rewrite_optional_params_handles_not_like() {
1817        let sql = "SELECT id FROM t WHERE name NOT LIKE $1";
1818        let params = vec![param("name", 1)];
1819        let result = rewrite_optional_params(sql, &["name".to_string()], &params);
1820        assert_eq!(result, "SELECT id FROM t WHERE ($1 IS NULL OR name NOT LIKE $1)");
1821    }
1822
1823    // -----------------------------------------------------------------
1824    // Dialect-aware tokenizer / placeholder tests (board #148, GH #149).
1825    //
1826    // These exercise `rewrite_placeholders_indexed` and `clean_sql_dialect`/
1827    // `clean_sql_oneline_dialect` directly -- the dialect-driven replacements
1828    // every owned backend (java-jdbc, kotlin-jdbc, kotlin-exposed, php-amphp)
1829    // now calls instead of the heuristic-based `rewrite_pg_placeholders`/
1830    // `clean_sql`/`clean_sql_oneline`. Each test states, in its doc comment or
1831    // inline, what the OLD (heuristic-based, dialect-blind) code produced for
1832    // the same input.
1833    // -----------------------------------------------------------------
1834
1835    /// The headline board #148 defect, reproduced against both the OLD heuristic
1836    /// entry point and the NEW dialect-driven one on the exact same input.
1837    /// `rewrite_pg_placeholders` (unchanged, kept for callers this change did
1838    /// not reach) has no `$N` to anchor its heuristic on, so it guesses "no
1839    /// dollar placeholders exist -> bare `?` is positional" and corrupts the
1840    /// JSONB key-existence operator into a placeholder reference:
1841    /// `WHERE data $1 'active'`. `rewrite_placeholders_indexed` under
1842    /// `SqlDialect::PostgreSQL` is told the dialect directly and never
1843    /// rewrites it, with zero occurrences recorded.
1844    #[test]
1845    fn test_bare_question_mark_is_never_a_placeholder_under_postgresql_even_with_zero_dollar_placeholders() {
1846        let sql = "SELECT * FROM docs WHERE data ? 'active'";
1847
1848        let old_result = rewrite_pg_placeholders(sql, |n| format!("${n}"));
1849        assert_eq!(
1850            old_result, "SELECT * FROM docs WHERE data $1 'active'",
1851            "pins the OLD heuristic's corruption of the JSONB operator"
1852        );
1853
1854        let (new_result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::PostgreSQL, |n| format!("${n}"));
1855        assert_eq!(
1856            new_result, sql,
1857            "dialect-driven rewrite must leave the JSONB operator untouched"
1858        );
1859        assert!(
1860            occurrences.is_empty(),
1861            "no placeholder was ever present; got: {occurrences:?}"
1862        );
1863    }
1864
1865    /// Same bare `?`, but under a dialect that genuinely uses it as a
1866    /// positional placeholder -- proving the decision is dialect-driven, not
1867    /// "always leave `?` alone now".
1868    #[test]
1869    fn test_bare_question_mark_is_a_placeholder_under_mysql() {
1870        let sql = "SELECT * FROM docs WHERE data ? 'active'";
1871        let (result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::MySQL, |n| format!("${n}"));
1872        assert_eq!(result, "SELECT * FROM docs WHERE data $1 'active'");
1873        assert_eq!(occurrences, vec![1]);
1874    }
1875
1876    /// GH #149: `$2` declared before `$1` in the SQL text must report its
1877    /// own position at each occurrence, in textual order -- this is what lets
1878    /// a backend bind per SQL-text occurrence instead of assuming declaration
1879    /// order.
1880    #[test]
1881    fn test_rewrite_placeholders_indexed_returns_positions_in_textual_order_out_of_order() {
1882        let (result, occurrences) =
1883            rewrite_placeholders_indexed("WHERE b = $2 AND a = $1", SqlDialect::PostgreSQL, |_| "?".to_string());
1884        assert_eq!(result, "WHERE b = ? AND a = ?");
1885        assert_eq!(occurrences, vec![2, 1]);
1886    }
1887
1888    /// GH #149: a repeated `$1` must report position `1` twice, once per
1889    /// occurrence -- not collapse to a single entry the way a per-declared-
1890    /// parameter bind loop would.
1891    #[test]
1892    fn test_rewrite_placeholders_indexed_repeated_placeholder_reports_one_occurrence_per_use() {
1893        let (result, occurrences) =
1894            rewrite_placeholders_indexed("WHERE a = $1 OR b = $1", SqlDialect::PostgreSQL, |_| "?".to_string());
1895        assert_eq!(result, "WHERE a = ? OR b = ?");
1896        assert_eq!(occurrences, vec![1, 1]);
1897    }
1898
1899    /// board #148 item 2/#186: a MySQL backtick-quoted identifier containing a bare
1900    /// `?` must not have the `?` inside it rewritten, and the identifier's own
1901    /// characters must not desynchronize the *later* placeholder's number.
1902    /// Matches the `WRONG:`-documented expectation in
1903    /// `sql_text_characterization_tests.rs`'s
1904    /// `question_mark_inside_a_mysql_backtick_identifier_is_rewritten_as_a_placeholder`.
1905    #[test]
1906    fn test_mysql_backtick_identifier_is_not_corrupted_by_bare_question_mark() {
1907        let sql = "SELECT `a?b` FROM t WHERE c = ?";
1908        let (result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::MySQL, |n| format!("[P{n}]"));
1909        assert_eq!(result, "SELECT `a?b` FROM t WHERE c = [P1]");
1910        assert_eq!(occurrences, vec![1]);
1911    }
1912
1913    /// board #148 item 4: same as above for an MSSQL `[bracketed]` identifier.
1914    #[test]
1915    fn test_mssql_bracket_identifier_is_not_corrupted_by_bare_question_mark() {
1916        let sql = "SELECT [a?b] FROM t WHERE c = ?";
1917        let (result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::MsSql, |n| format!("[P{n}]"));
1918        assert_eq!(result, "SELECT [a?b] FROM t WHERE c = [P1]");
1919        assert_eq!(occurrences, vec![1]);
1920    }
1921
1922    /// board #148 item 2: a MySQL backtick identifier containing `-- ` must not be
1923    /// read as opening a line comment. Matches the `clean_sql_dialect`
1924    /// counterpart of the `WRONG:`-documented
1925    /// `clean_sql_treats_a_double_dash_inside_a_mysql_backtick_identifier_as_a_comment`
1926    /// characterization test (which pins the OLD, dialect-blind `clean_sql`'s
1927    /// corruption of the same input to `"SELECT \`a"`).
1928    #[test]
1929    fn test_clean_sql_dialect_mysql_backtick_preserves_double_dash_inside() {
1930        let sql = "SELECT `a -- b` FROM t";
1931        assert_eq!(
1932            clean_sql(sql),
1933            "SELECT `a",
1934            "pins the OLD dialect-blind clean_sql's corruption"
1935        );
1936        assert_eq!(clean_sql_dialect(sql, SqlDialect::MySQL), sql);
1937    }
1938
1939    /// board #148 item 4: same as above for an MSSQL `[bracketed]` identifier.
1940    #[test]
1941    fn test_clean_sql_dialect_mssql_bracket_preserves_double_dash_inside() {
1942        let sql = "SELECT [a -- b] FROM t";
1943        assert_eq!(
1944            clean_sql(sql),
1945            "SELECT [a",
1946            "pins the OLD dialect-blind clean_sql's corruption"
1947        );
1948        assert_eq!(clean_sql_dialect(sql, SqlDialect::MsSql), sql);
1949    }
1950
1951    /// board #148 item 3: MySQL `#` line comments were deliberately unrecognized
1952    /// dialect-blind (`#` collides with PostgreSQL's `#>`/`#>>` JSON
1953    /// operators), so the OLD `clean_sql` leaves the whole comment in the
1954    /// output. Under `SqlDialect::MySQL` it must be stripped like `--`.
1955    #[test]
1956    fn test_clean_sql_dialect_mysql_hash_comment_is_stripped() {
1957        let sql = "SELECT 1 # note\nFROM t";
1958        assert_eq!(
1959            clean_sql(sql),
1960            "SELECT 1 # note\nFROM t",
1961            "pins the OLD dialect-blind clean_sql leaving the # comment in place"
1962        );
1963        // WRONG-adjacent (matches the pre-existing `--` wart pinned by
1964        // `clean_sql_strips_a_trailing_line_comment_but_leaves_the_space_before_it`
1965        // in sql_text_characterization_tests.rs): stripping a trailing
1966        // comment does not also strip the space that preceded it.
1967        assert_eq!(clean_sql_dialect(sql, SqlDialect::MySQL), "SELECT 1 \nFROM t");
1968    }
1969
1970    /// The oneline variant of the `#` test above, since every owned backend
1971    /// calls `clean_sql_oneline_dialect` (or its `_with_optional` wrapper),
1972    /// never `clean_sql_dialect`, to flatten SQL into one embedded literal.
1973    #[test]
1974    fn test_clean_sql_oneline_dialect_mysql_hash_comment_is_stripped() {
1975        let sql = "SELECT 1 # note\nFROM t";
1976        assert_eq!(clean_sql_oneline_dialect(sql, SqlDialect::MySQL), "SELECT 1  FROM t");
1977    }
1978
1979    /// PostgreSQL's `#>`/`#>>` JSON operators are exactly why `#` cannot be
1980    /// treated as a comment dialect-blind -- confirm they still survive
1981    /// untouched under `SqlDialect::PostgreSQL`.
1982    #[test]
1983    fn test_clean_sql_dialect_postgresql_hash_is_not_a_comment() {
1984        let sql = "SELECT data #> '{a,b}' AS x FROM t";
1985        assert_eq!(clean_sql_dialect(sql, SqlDialect::PostgreSQL), sql);
1986    }
1987}