Placeholder compilation for portable SQL.
User-facing SQL uses ? (positional) or :name (named) placeholders.
compile rewrites them for a driver's placeholder style — "dollar"
($1, $2, ..., PostgreSQL) or "question" (?, MySQL/SQLite) — while
leaving string literals, quoted identifiers, comments, PostgreSQL
::type casts, and dollar-quoted strings untouched.
?? escapes a literal ? (for PostgreSQL's JSONB operators, write
??, ??|, ??&). Named placeholders start with a letter or
underscore, so array slices like arr[1:3] pass through unchanged.
Dialect-specific syntax is enabled by the optional third argument
("pg", "mysql", "sqlite"): MySQL adds backslash escapes inside
strings and # line comments. Backtick identifier quoting is handled
for the "question" style (MySQL native, SQLite-compatible), and
dollar-quoted strings for the "dollar" style.
Functions
compile
fn (sql: Str, style: Str): Map
fn (sql: Str, style: Str, dialect: Str): Map
Compile ? / :name placeholders in sql for a driver placeholder
style. Returns {sql: Str, names: Vec, count: Int} where names has
one entry per bound parameter position — the parameter name for named
placeholders, null for positional ?.
For the "dollar" style, repeated :name placeholders reuse the same
$N position. For the "question" style every occurrence becomes its
own ? (the binder repeats the value).
Mixing ? and :name in one statement returns an error. ?? emits a
literal ? and binds nothing (PostgreSQL JSONB operators: ??,
??|, ??&).
Skipped regions: '...' strings (with '' escapes, plus \\
escapes for the "mysql" dialect), "..." identifiers, `...`
identifiers (question style), -- line comments (# too for
"mysql"), /* ... */ block comments (nested), ::type casts, and
$$ ... $$ / $tag$ ... $tag$ dollar-quoted strings (dollar style).
The optional dialect argument ("pg", "mysql", "sqlite")
enables the dialect-specific lexing above; the two-argument form uses
the style's defaults.
Example
::sql::compile/compile("SELECT * FROM users WHERE id = ? AND active = ?", "dollar")
// => {sql: "SELECT * FROM users WHERE id = $1 AND active = $2", names: [null, null], count: 2}
::sql::compile/compile("UPDATE users SET name = :name WHERE id = :id", "dollar")
// => {sql: "UPDATE users SET name = $1 WHERE id = $2", names: ["name", "id"], count: 2}