Skip to main content

bynk_check/checker/
d1.rs

1//! P4c (#2628): the checker's half of `bynk.cloudflare`'s `D1`.
2//!
3//! - **Literal-only SQL.** `all`/`first`/`run`'s SQL argument, and every
4//!   `SqlStatement`'s `sql`, must be a string literal (`bynk.types.sql_not_literal`),
5//!   so data reaches a statement only through its bound `SqlValue` parameters.
6//! - **`SqlStatement` stays in-process.** A decoded statement would carry SQL
7//!   that was never a literal, so the type is non-storable and non-boundary
8//!   (`bynk.types.sql_statement_at_boundary`), and no `Json` codec target.
9//! - **`Json.decodeSql[T]`'s row shape** (`bynk.types.sql_row_shape`): `T` is a
10//!   record of scalar columns, or a `List` of one.
11
12use super::*;
13
14/// The first-party record a `D1.batch` statement is.
15pub(crate) const SQL_STATEMENT: &str = "SqlStatement";
16
17/// The `D1` operations whose first argument is SQL text.
18const SQL_TEXT_OPS: &[&str] = &["all", "first", "run"];
19
20/// Hyperdrive H3 (#3320): the first-party record a `Postgres.transaction`
21/// statement is. It is held to the same rules as [`SQL_STATEMENT`].
22pub(crate) const PG_STATEMENT: &str = "PgStatement";
23
24/// Hyperdrive H5 (#3322): the first-party record a `MySql.transaction`
25/// statement is, held to the same rules.
26pub(crate) const MYSQL_STATEMENT: &str = "MySqlStatement";
27
28/// Whether `name`, in the project's type table, is `bynk.cloudflare`'s own
29/// `SqlStatement` or `PgStatement`, found by its declaration's file as the
30/// crypto key types are.
31pub(crate) fn is_sql_statement_type(name: &str, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
32    (name == SQL_STATEMENT || name == PG_STATEMENT || name == MYSQL_STATEMENT)
33        && types.get(name).is_some_and(|decl| {
34            crate::firstparty::unit(crate::firstparty::CLOUDFLARE_UNIT).is_some_and(|unit| {
35                decl.span.file == crate::project_model::firstparty_file_id(unit)
36            })
37        })
38}
39
40/// #3070: one literal SQL statement of a derived `D1` instance, as the project
41/// phase prepares it against the migrations' schema.
42#[derive(Debug, Clone)]
43pub struct D1SqlSite {
44    /// The capability the call is on (`Orders`), whose instance names the database.
45    pub cap: String,
46    /// The method (`all`, `first`, `run`, `select`, `firstAs`).
47    pub op: String,
48    /// The statement as SQLite sees it; for `select`/`firstAs` the composed
49    /// `SELECT <columns> <tail>`.
50    pub text: String,
51    /// The literal's span: where every diagnostic is reported.
52    pub span: Span,
53    /// For `select`/`firstAs`: the row type and its field names (the columns the
54    /// compiler wrote), so a missing one is reported against the type.
55    pub row: Option<(String, Vec<String>)>,
56    /// The number of values passed, when the list is a list literal.
57    pub passed: Option<usize>,
58    /// #3108: for `select`/`firstAs`, the literal's own decoded text and where it
59    /// begins in [`text`](Self::text) (a signed offset: the compiler's
60    /// `SELECT <columns> ` prefix, less the leading whitespace trimmed from the
61    /// literal), so an error offset in `text` maps back into the literal. `None`
62    /// when `text` is the literal itself.
63    pub literal: Option<(String, isize)>,
64    /// #3197: for a statement written inline in a `batch` list literal, the
65    /// batch (the list's start offset, which is unique per call) and the
66    /// statement's position in the list. A batch's statements are checked in
67    /// order, each against the schema the earlier ones leave. `None` for any
68    /// other call.
69    pub batch: Option<BatchPosition>,
70    /// #3147: for a statement read through `D1.peek`, the participant whose
71    /// database it reads (`shop.orders`) and its capability (`Orders`; `cap`
72    /// is the handle's own name). Such a statement must not write.
73    pub peek: Option<(String, String)>,
74}
75
76/// #3197: where a statement sits in its `batch` list literal.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct BatchPosition {
79    /// The list literal's start offset: identifies the batch call.
80    pub group: usize,
81    /// The statement's zero-based position in the list.
82    pub index: usize,
83}
84
85/// #3139: which value a name holds, on the way from a literal D1 read to the
86/// `Json.decodeSql` that decodes its rows.
87#[derive(Debug, Clone)]
88pub struct RowLink {
89    /// The statement whose rows these are.
90    pub site: D1SqlSite,
91    /// `false`: the read's whole `Result` (`let r <- Cap.all(…)`); `true`: the
92    /// text inside its `Ok` (`Ok(x)`, or `Ok(Some(x))` for `first`).
93    pub payload: bool,
94}
95
96/// #3139: a `Json.decodeSql[T](x)` linked to the statement `x`'s rows came from.
97#[derive(Debug, Clone)]
98pub struct D1DecodeSite {
99    pub site: D1SqlSite,
100    /// The row record decoded.
101    pub row: String,
102    /// The row's required fields: those not of an `Option` type.
103    pub required: Vec<String>,
104    /// The `decodeSql` call, where a missing column is reported.
105    pub span: Span,
106}
107
108/// The statement a recorded SQL argument names: a literal's own site, or the
109/// one a `const` carries.
110fn site_of(callee: Option<&Callee>) -> Option<&D1SqlSite> {
111    match callee? {
112        Callee::D1Sql(site) => Some(site),
113        Callee::Const(_, Some(site)) => Some(site),
114        _ => None,
115    }
116}
117
118/// #3139: after `let r <- Cap.all(<literal>, …)` (or `first`) binds `r`, link it
119/// to the statement. The `let … else` form binds a hidden name the same way.
120pub(crate) fn link_effect_let(l: &LetStmt, ctx: &mut Ctx) {
121    let ExprKind::MethodCall { method, args, .. } = &l.value.kind else {
122        return;
123    };
124    if !matches!(method.name.as_str(), "all" | "first") {
125        return;
126    }
127    let Some(sql) = args.first() else { return };
128    let Some(site) = site_of(ctx.callees.get(&sql.id)) else {
129        return;
130    };
131    if site.op != method.name {
132        return;
133    }
134    let site = site.clone();
135    let depth = ctx.scopes.len() - 1;
136    ctx.row_links.insert(
137        (depth, l.name.name.clone()),
138        RowLink {
139            site,
140            payload: false,
141        },
142    );
143}
144
145/// #3139: in `match r { Ok(x) => … }` (`Ok(Some(x))` for a `first`), where `r`
146/// holds a D1 read's `Result`, link the binder `x` to the same statement. Called
147/// in the arm's own scope, after the pattern bound its names.
148pub(crate) fn link_match_arm(discriminant: &Expr, pattern: &Pattern, ctx: &mut Ctx) {
149    let ExprKind::Ident(id) = &discriminant.kind else {
150        return;
151    };
152    let Some(link) = ctx.row_link(&id.name).filter(|l| !l.payload).cloned() else {
153        return;
154    };
155    // The payload pattern of `Ok(…)`, then through `Some(…)` for a `first`.
156    fn payload<'p>(p: &'p Pattern, variant: &str) -> Option<&'p Pattern> {
157        match p {
158            Pattern::Variant {
159                variant: v,
160                bindings,
161                type_name: None,
162                ..
163            } if v.name == variant && bindings.len() == 1 => Some(bindings[0].pattern()),
164            _ => None,
165        }
166    }
167    let Some(mut inner) = payload(pattern, "Ok") else {
168        return;
169    };
170    if link.site.op == "first" {
171        let Some(some) = payload(inner, "Some") else {
172            return;
173        };
174        inner = some;
175    }
176    let Pattern::Binding(x) = inner else { return };
177    let depth = ctx.scopes.len() - 1;
178    ctx.row_links.insert(
179        (depth, x.name.clone()),
180        RowLink {
181            site: link.site,
182            payload: true,
183        },
184    );
185}
186
187/// #3139: `Json.decodeSql[t](arg)` where `arg` is the text of a literal D1 read:
188/// record the pairing for the project phase. `t` has passed `check_row_shape`.
189pub(crate) fn record_decode(arg: &Expr, call_span: Span, t: TyId, ctx: &mut Ctx) {
190    let ExprKind::Ident(id) = &arg.kind else {
191        return;
192    };
193    let Some(link) = ctx.row_link(&id.name).filter(|l| l.payload).cloned() else {
194        return;
195    };
196    let row = match &*ctx.tys.get(t) {
197        Ty::List(r) => *r,
198        _ => t,
199    };
200    let Ty::Named { name, .. } = &*ctx.tys.get(row) else {
201        return;
202    };
203    let name = name.clone();
204    let Some(TypeBody::Record(record)) = ctx.input.types.get(&name).map(|d| &d.body) else {
205        return;
206    };
207    let required = record
208        .fields
209        .iter()
210        .filter(|f| !matches!(f.type_ref, TypeRef::Option(..)))
211        .map(|f| f.name.name.clone())
212        .collect();
213    ctx.callees.insert(
214        arg.id,
215        Callee::D1Decode(D1DecodeSite {
216            site: link.site,
217            row: name,
218            required,
219            span: call_span,
220        }),
221    );
222}
223
224/// The length of a list-literal argument; `None` when the list is a name, a
225/// call or anything whose length is not fixed by the text.
226fn literal_list_len(e: Option<&Expr>, ctx: &Ctx) -> Option<usize> {
227    match &e?.kind {
228        ExprKind::ListLit(items, ..) => Some(items.len()),
229        // #3108: a `let` bound to a list literal in scope.
230        ExprKind::Ident(id) => ctx.let_list_len(&id.name),
231        _ => None,
232    }
233}
234
235/// #3065: the text of a SQL argument that is fixed at compile time: a string
236/// literal, or a bare reference to a `String` constant whose value, following
237/// constant-to-constant references, is a plain string literal. A constant's
238/// initialiser is a closed static set (`consts::static_error`: no operators,
239/// calls or interpolation), so such a name can carry no run-time input, and the
240/// checker judges the very text the call sends. `None` for anything else: a
241/// parameter, a `let` binding (locals shadow a constant of the same name), a
242/// field, a call, or a constant not declared exactly `String`.
243pub(crate) fn sql_literal_text(e: &Expr, ctx: &Ctx) -> Option<String> {
244    match &e.kind {
245        ExprKind::StrLit(s) => Some(s.clone()),
246        ExprKind::Ident(id) if ctx.lookup(id.name.as_str()).is_none() => {
247            // A chain longer than the constants in scope is a cycle, already
248            // `bynk.resolve.const_cycle`; the bound keeps this total.
249            let start = ctx.input.consts.get(id.name.as_str())?;
250            let lit = crate::consts::chain_literal(
251                start,
252                BaseType::String,
253                ctx.input.consts.len(),
254                |n| ctx.input.consts.get(n),
255            )?;
256            match &lit.kind {
257                ExprKind::StrLit(s) => Some(s.clone()),
258                _ => None,
259            }
260        }
261        _ => None,
262    }
263}
264
265fn sql_not_literal(span: Span, what: &str) -> CompileError {
266    sql_not_literal_with(span, what, "`?1`, `?2`")
267}
268
269/// [`sql_not_literal`], naming the placeholders of the dialect the call is in
270/// (`$1`, `$2` for `Postgres`, #3318).
271fn sql_not_literal_with(span: Span, what: &str, placeholders: &str) -> CompileError {
272    CompileError::new(
273        "bynk.types.sql_not_literal",
274        span,
275        format!("{what} must be a string literal or a `String` constant bound to one"),
276    )
277    .with_note(format!(
278        "pass values as {placeholders}, … parameters in `params`, which are bound, never \
279         spliced into the text; SQL built at run time could be injected. A `const` \
280         `String` bound to a literal is accepted, since its value is fixed at compile time"
281    ))
282}
283
284/// A call to a derived instance of `D1`: its SQL argument must be a literal.
285/// Keyed on the resolved base, not the method name, so a user capability
286/// with an `all` operation is untouched.
287pub(crate) fn check_sql_argument(
288    derived_from: Option<&(String, String)>,
289    cap: &str,
290    method: &str,
291    args: &[Expr],
292    ctx: &mut Ctx,
293) {
294    let Some((unit, base)) = derived_from else {
295        return;
296    };
297    if unit != crate::firstparty::CLOUDFLARE_UNIT {
298        return;
299    }
300    // Hyperdrive H1 (#3318, ADR 0666 B): a `Postgres` statement's SQL is a
301    // literal too. It is not recorded as a site: the schema a site is prepared
302    // against is a D1 migration's SQLite, which says nothing of Postgres.
303    if base == "Postgres" && SQL_TEXT_OPS.contains(&method) {
304        if let Some(sql) = args.first() {
305            match sql_literal_text(sql, ctx) {
306                None => ctx.errors.push(sql_not_literal_with(
307                    sql.span,
308                    &format!("the SQL of `{cap}.{method}`"),
309                    "`$1`, `$2`",
310                )),
311                // Hyperdrive H4 (#3321): with a `schema.sql`, the text is checked.
312                Some(text) => check_pg_text(&text, sql.span, args.get(1), ctx),
313            }
314        }
315        return;
316    }
317    if base == "Postgres" && method == "transaction" {
318        check_pg_transaction(args.first(), ctx);
319        return;
320    }
321    // Hyperdrive H5 (#3322): a `MySql` statement is held to the same rules, with
322    // `?` placeholders and MySQL's parser for the `schema.sql` check.
323    if base == "MySql" && SQL_TEXT_OPS.contains(&method) {
324        if let Some(sql) = args.first() {
325            match sql_literal_text(sql, ctx) {
326                None => ctx.errors.push(sql_not_literal_with(
327                    sql.span,
328                    &format!("the SQL of `{cap}.{method}`"),
329                    "`?`",
330                )),
331                Some(text) => check_mysql_text(&text, sql.span, args.get(1), ctx),
332            }
333        }
334        return;
335    }
336    if base == "MySql" && method == "transaction" {
337        check_mysql_transaction(args.first(), ctx);
338        return;
339    }
340    if base != "D1" {
341        return;
342    }
343    if method == "batch" {
344        record_batch_sites(cap, args.first(), ctx);
345        return;
346    }
347    if !SQL_TEXT_OPS.contains(&method) {
348        return;
349    }
350    if let Some(sql) = args.first() {
351        if let Some(text) = sql_literal_text(sql, ctx) {
352            ctx.callees.insert(
353                sql.id,
354                Callee::D1Sql(D1SqlSite {
355                    cap: cap.to_string(),
356                    op: method.to_string(),
357                    text,
358                    span: sql.span,
359                    row: None,
360                    passed: literal_list_len(args.get(1), ctx),
361                    literal: None,
362                    batch: None,
363                    peek: None,
364                }),
365            );
366        } else {
367            ctx.errors.push(sql_not_literal(
368                sql.span,
369                &format!("the SQL of `{cap}.{method}`"),
370            ));
371        }
372    }
373}
374
375/// #3108: `batch([SqlStatement { sql: "…", params: […] }, …])`. Each statement
376/// written inline in the list literal is a site on the batch's own binding
377/// (a statement built elsewhere isn't tied to one, so it stays unchecked). A
378/// non-literal `sql` is already `bynk.types.sql_not_literal`, from
379/// [`check_statement_fields`].
380fn record_batch_sites(cap: &str, list: Option<&Expr>, ctx: &mut Ctx) {
381    let Some(Expr {
382        kind: ExprKind::ListLit(items, ..),
383        ..
384    }) = list
385    else {
386        return;
387    };
388    let group = list.map_or(0, |l| l.span.start);
389    for (index, item) in items.iter().enumerate() {
390        let ExprKind::RecordConstruction {
391            type_name, fields, ..
392        } = &item.kind
393        else {
394            continue;
395        };
396        if type_name.name != SQL_STATEMENT {
397            continue;
398        }
399        let field = |name: &str| {
400            fields
401                .iter()
402                .find(|f| f.name.name == name)
403                .and_then(|f| f.value.as_ref())
404        };
405        let Some(sql) = field("sql") else { continue };
406        let Some(text) = sql_literal_text(sql, ctx) else {
407            continue;
408        };
409        let passed = literal_list_len(field("params"), ctx);
410        ctx.callees.insert(
411            sql.id,
412            Callee::D1Sql(D1SqlSite {
413                cap: cap.to_string(),
414                op: "batch".to_string(),
415                text,
416                span: sql.span,
417                row: None,
418                passed,
419                literal: None,
420                batch: Some(BatchPosition { group, index }),
421                peek: None,
422            }),
423        );
424    }
425}
426
427/// Hyperdrive H4 (#3321, ADR 0799 G): the checks of a literal `Postgres`
428/// statement's text, when the project supplies a `schema.sql`; nothing without
429/// one. `params` is the call's parameter list, whose length is checked when it
430/// is written out.
431fn check_pg_text(text: &str, span: Span, params: Option<&Expr>, ctx: &mut Ctx) {
432    if !ctx.input.stability.policy.pg_sql {
433        return;
434    }
435    let passed = literal_list_len(params, ctx);
436    for problem in crate::pg_sql::check_statement(text, passed) {
437        ctx.errors.push(pg_problem(problem, span));
438    }
439}
440
441/// `Postgres.transaction([PgStatement { sql: "…", params: […] }, …])`: each
442/// statement written inline in the list literal is checked as a call's SQL is. A
443/// non-literal `sql` is already `bynk.types.sql_not_literal`, from
444/// [`check_statement_fields`]; a statement built elsewhere stays unchecked.
445fn check_pg_transaction(list: Option<&Expr>, ctx: &mut Ctx) {
446    let Some(Expr {
447        kind: ExprKind::ListLit(items, ..),
448        ..
449    }) = list
450    else {
451        return;
452    };
453    for item in items {
454        let ExprKind::RecordConstruction {
455            type_name, fields, ..
456        } = &item.kind
457        else {
458            continue;
459        };
460        if type_name.name != PG_STATEMENT {
461            continue;
462        }
463        let field = |name: &str| {
464            fields
465                .iter()
466                .find(|f| f.name.name == name)
467                .and_then(|f| f.value.as_ref())
468        };
469        let Some(sql) = field("sql") else { continue };
470        let Some(text) = sql_literal_text(sql, ctx) else {
471            continue;
472        };
473        check_pg_text(&text, sql.span, field("params"), ctx);
474    }
475}
476
477/// Hyperdrive H5 (#3322): [`check_pg_text`] for a `MySql` statement.
478fn check_mysql_text(text: &str, span: Span, params: Option<&Expr>, ctx: &mut Ctx) {
479    if !ctx.input.stability.policy.pg_sql {
480        return;
481    }
482    let passed = literal_list_len(params, ctx);
483    for problem in crate::mysql_sql::check_statement(text, passed) {
484        ctx.errors.push(mysql_problem(problem, span));
485    }
486}
487
488/// [`check_pg_transaction`] for `MySql.transaction([MySqlStatement { … }, …])`.
489fn check_mysql_transaction(list: Option<&Expr>, ctx: &mut Ctx) {
490    let Some(Expr {
491        kind: ExprKind::ListLit(items, ..),
492        ..
493    }) = list
494    else {
495        return;
496    };
497    for item in items {
498        let ExprKind::RecordConstruction {
499            type_name, fields, ..
500        } = &item.kind
501        else {
502            continue;
503        };
504        if type_name.name != MYSQL_STATEMENT {
505            continue;
506        }
507        let field = |name: &str| {
508            fields
509                .iter()
510                .find(|f| f.name.name == name)
511                .and_then(|f| f.value.as_ref())
512        };
513        let Some(sql) = field("sql") else { continue };
514        let Some(text) = sql_literal_text(sql, ctx) else {
515            continue;
516        };
517        check_mysql_text(&text, sql.span, field("params"), ctx);
518    }
519}
520
521/// The diagnostic for a problem with a `MySql` statement at its `span`.
522fn mysql_problem(problem: crate::pg_sql::PgSqlProblem, span: Span) -> CompileError {
523    use crate::pg_sql::PgSqlProblem;
524    match problem {
525        PgSqlProblem::Invalid(message) => CompileError::new(
526            "bynk.mysql.sql_invalid",
527            span,
528            format!("this may not be a MySQL statement: {message}"),
529        )
530        .with_note(
531            "a warning, not an error: the parser is a pure-Rust one, not MySQL's own, and can refuse valid SQL. It runs because the project has a `schema.sql`; delete that file to turn the check off",
532        ),
533        PgSqlProblem::ParamCount { expected, passed } => CompileError::new(
534            "bynk.mysql.sql_param_count",
535            span,
536            format!(
537                "the statement uses {expected} parameter{}, but {passed} {} passed",
538                if expected == 1 { "" } else { "s" },
539                if passed == 1 { "is" } else { "are" },
540            ),
541        )
542        .with_note(
543            "each `?` placeholder takes the next element of `params`, so the list needs as many elements as the statement has `?` outside string literals, quoted identifiers and comments",
544        ),
545    }
546}
547
548/// The diagnostic for a [`PgSqlProblem`](crate::pg_sql::PgSqlProblem) at the
549/// statement's `span`.
550fn pg_problem(problem: crate::pg_sql::PgSqlProblem, span: Span) -> CompileError {
551    use crate::pg_sql::PgSqlProblem;
552    match problem {
553        PgSqlProblem::Invalid(message) => CompileError::new(
554            "bynk.postgres.sql_invalid",
555            span,
556            format!("this may not be a Postgres statement: {message}"),
557        )
558        .with_note(
559            "a warning, not an error: the parser is a pure-Rust one, not Postgres' own, and can refuse valid SQL. It runs because the project has a `schema.sql`; delete that file to turn the check off",
560        ),
561        PgSqlProblem::ParamCount { expected, passed } => CompileError::new(
562            "bynk.postgres.sql_param_count",
563            span,
564            format!(
565                "the statement uses {expected} parameter{}, but {passed} {} passed",
566                if expected == 1 { "" } else { "s" },
567                if passed == 1 { "is" } else { "are" },
568            ),
569        )
570        .with_note(
571            "a `$n` placeholder takes the n-th element of `params`, so the list needs as many elements as the highest `$n`",
572        ),
573    }
574}
575
576/// A `SqlStatement { … }` construction, or a spread over one that overrides
577/// `sql`: the field's value must be a literal. A shorthand `sql` field reads a
578/// binding, so it is not one. A spread that keeps `sql` copies a statement
579/// that was itself built from a literal.
580pub(crate) fn check_statement_fields(ty: TyId, fields: &[FieldInit], ctx: &mut Ctx) {
581    let statement = match &*ctx.tys.get(ty) {
582        Ty::Named {
583            name,
584            kind: NamedKind::Record,
585            ..
586        } if is_sql_statement_type(name, &ctx.input.types) => name.clone(),
587        _ => return,
588    };
589    for f in fields.iter().filter(|f| f.name.name == "sql") {
590        let literal = f
591            .value
592            .as_ref()
593            .is_some_and(|v| sql_literal_text(v, ctx).is_some());
594        if !literal {
595            let span = f.value.as_ref().map_or(f.name.span, |v| v.span);
596            let what = format!("a `{statement}`'s `sql`");
597            ctx.errors.push(if statement == PG_STATEMENT {
598                sql_not_literal_with(span, &what, "`$1`, `$2`")
599            } else if statement == MYSQL_STATEMENT {
600                sql_not_literal_with(span, &what, "`?`")
601            } else {
602                sql_not_literal(span, &what)
603            });
604        }
605    }
606}
607
608/// The diagnostic for a `SqlStatement` or `PgStatement` (`statement`) in a
609/// storable or boundary position.
610pub(crate) fn statement_at_boundary(span: Span, what: &str, statement: &str) -> CompileError {
611    CompileError::new(
612        "bynk.types.sql_statement_at_boundary",
613        span,
614        format!(
615            "a `{statement}` cannot appear in {what} — a statement received or restored from outside would carry SQL that was never a literal"
616        ),
617    )
618    .with_note("send or store the values, and build the statement where it runs")
619}
620
621/// The statement type (`SqlStatement` or `PgStatement`) a `Json` codec target
622/// is, or holds. A user type cannot hold one (its declaration is refused), so
623/// only the built-in containers need looking through.
624pub(crate) fn carried_statement(
625    t: TyId,
626    types: &HashMap<String, Arc<TypeDecl>>,
627    tys: &Types,
628) -> Option<String> {
629    match &*tys.get(t) {
630        Ty::Named { name, args, .. } => {
631            if is_sql_statement_type(name, types) {
632                Some(name.clone())
633            } else {
634                args.iter().find_map(|a| carried_statement(*a, types, tys))
635            }
636        }
637        Ty::Result(a, b) | Ty::Map(a, b) => {
638            carried_statement(*a, types, tys).or_else(|| carried_statement(*b, types, tys))
639        }
640        Ty::Option(a) | Ty::List(a) | Ty::Set(a) => carried_statement(*a, types, tys),
641        _ => None,
642    }
643}
644
645/// The typed reads of a derived `D1` instance, which the compiler lowers over
646/// `all`/`first` (#2865); they are not declared operations of the capability.
647pub(crate) fn is_typed_read(derived_from: Option<&(String, String)>, method: &str) -> bool {
648    matches!(derived_from, Some((unit, base)) if unit == crate::firstparty::CLOUDFLARE_UNIT && matches!(base.as_str(), "D1" | "Postgres" | "MySql"))
649        && matches!(method, "select" | "firstAs")
650}
651
652/// Hyperdrive H3 (#3320): whether the derived instance is a `Postgres` one, so
653/// its typed reads use `PgValue`, `PgReadError` and Postgres' column types.
654pub(crate) fn is_postgres(derived_from: Option<&(String, String)>) -> bool {
655    matches!(derived_from, Some((unit, base)) if unit == crate::firstparty::CLOUDFLARE_UNIT && base == "Postgres")
656}
657
658/// Hyperdrive H5 (#3322): whether the derived instance is a `MySql` one, so its
659/// typed reads use `MySqlValue`, `MySqlReadError` and MySQL's column rules, and
660/// quote a column with backticks.
661pub(crate) fn is_mysql(derived_from: Option<&(String, String)>) -> bool {
662    matches!(derived_from, Some((unit, base)) if unit == crate::firstparty::CLOUDFLARE_UNIT && base == "MySql")
663}
664
665/// The column list the compiler writes for a row record: each field's name as
666/// a quoted identifier (an embedded `"` doubled), in declaration order.
667pub fn select_columns(row: &str, types: &HashMap<String, Arc<TypeDecl>>) -> String {
668    select_columns_quoted(row, types, '"')
669}
670
671/// [`select_columns`] for a dialect's identifier quote: `"` (SQLite, Postgres)
672/// or a backtick (MySQL), doubled where it occurs in a name.
673pub fn select_columns_quoted(
674    row: &str,
675    types: &HashMap<String, Arc<TypeDecl>>,
676    quote: char,
677) -> String {
678    match types.get(row).map(|d| &d.body) {
679        Some(TypeBody::Record(record)) => record
680            .fields
681            .iter()
682            .map(|f| {
683                let doubled = format!("{quote}{quote}");
684                format!("{quote}{}{quote}", f.name.name.replace(quote, &doubled))
685            })
686            .collect::<Vec<_>>()
687            .join(", "),
688        _ => String::new(),
689    }
690}
691
692/// Whether a literal tail fails to start at `FROM` (case-insensitive, after
693/// whitespace): the compiler writes `SELECT` and the column list ahead of it.
694fn begins_without_from(tail: &str) -> bool {
695    let t = tail.trim_start();
696    !t.get(..4).is_some_and(|p| p.eq_ignore_ascii_case("from"))
697        || t[4..]
698            .chars()
699            .next()
700            .is_some_and(|c| c.is_alphanumeric() || c == '_')
701}
702
703/// Whether a literal tail itself begins with the `SELECT` keyword.
704fn begins_with_select(tail: &str) -> bool {
705    let t = tail.trim_start();
706    t.get(..6).is_some_and(|p| p.eq_ignore_ascii_case("select"))
707        && !t[6..]
708            .chars()
709            .next()
710            .is_some_and(|c| c.is_alphanumeric() || c == '_')
711}
712
713/// `D1.select[T](tail, params)` / `D1.firstAs[T](tail, params)` on a derived
714/// instance (#2865): `T` is a row record, the tail a string literal from
715/// `FROM` on. Records the lowering (`Callee::D1Select`) and types the call
716/// `Effect[Result[List[T], SqlReadError]]` (`firstAs`: `Option[T]`).
717#[allow(clippy::too_many_arguments)]
718pub(crate) fn check_typed_read(
719    derived_from: Option<&(String, String)>,
720    cap: &str,
721    method: &Ident,
722    type_args: &[TypeRef],
723    args: &[Expr],
724    span: Span,
725    expr_id: ExprId,
726    ctx: &mut Ctx,
727) -> Option<TyId> {
728    let tys = ctx.tys;
729    if let Some((unit, base)) = derived_from {
730        super::calls::refuse_experimental(
731            &format!("{unit}.{base}.{}", method.name),
732            method.span,
733            ctx,
734        );
735    }
736    let pg = is_postgres(derived_from);
737    let mysql = is_mysql(derived_from);
738    let name = format!("{cap}.{}", method.name);
739    let bail = |ctx: &mut Ctx| {
740        for a in args {
741            let _ = type_of(a, None, ctx);
742        }
743        None
744    };
745    if type_args.len() != 1 {
746        ctx.errors.push(CompileError::new(
747            "bynk.generics.type_arg_mismatch",
748            span,
749            format!(
750                "`{name}` takes exactly one type argument (the row type), got {}",
751                type_args.len()
752            ),
753        ));
754        return bail(ctx);
755    }
756    if args.len() != 2 {
757        ctx.errors.push(CompileError::new(
758            "bynk.capability.op_arity",
759            span,
760            format!(
761                "capability operation `{name}` expects 2 argument(s), but {} were given",
762                args.len()
763            ),
764        ));
765        return bail(ctx);
766    }
767    let Some(t) = resolve_expr_type_ref(&type_args[0], ctx) else {
768        return bail(ctx);
769    };
770    // The first-party `SqlValue` / `SqlReadError`, which the consumer sees
771    // through `bynk.cloudflare`'s transparent exports.
772    let named = |n: &str, ctx: &Ctx| {
773        ctx.input.types.contains_key(n).then(|| {
774            tys.intern(Ty::Named {
775                name: n.to_string(),
776                kind: NamedKind::Sum,
777                args: Vec::new(),
778            })
779        })
780    };
781    let (value_name, read_name) = if pg {
782        ("PgValue", "PgReadError")
783    } else if mysql {
784        ("MySqlValue", "MySqlReadError")
785    } else {
786        ("SqlValue", "SqlReadError")
787    };
788    let (Some(value_ty), Some(read_err)) = (named(value_name, ctx), named(read_name, ctx)) else {
789        ctx.errors.push(CompileError::new(
790            "bynk.capability.unknown_operation",
791            span,
792            format!("`{name}` needs `bynk.cloudflare`'s `{value_name}` and `{read_name}` in scope"),
793        ));
794        return bail(ctx);
795    };
796    let mut ok = true;
797    let as_list = matches!(&*tys.get(t), Ty::List(_));
798    let shape = if as_list {
799        Err(format!(
800            "`{}` is not a row record; `{}` already returns a `List` of rows",
801            t.display(tys),
802            method.name
803        ))
804    } else {
805        check_row_shape_for(t, &ctx.input.types, tys, pg).and_then(|()| match &*tys.get(t) {
806            Ty::Named { name, .. } if select_columns(name, &ctx.input.types).is_empty() => {
807                Err(format!("`{name}` has no fields to select"))
808            }
809            _ => Ok(()),
810        })
811    };
812    if let Err(why) = shape {
813        ctx.errors.push(
814            CompileError::new(
815                "bynk.types.sql_row_shape",
816                type_args[0].span(),
817                format!("`{name}` reads SQL rows, but {why}"),
818            )
819            .with_note(if pg {
820                "the row is a record whose fields are `Int`, `Float`, `String`, `Bool`, \
821                 `Bytes`, `Decimal` or `Instant` (or a refined or opaque type over one, or an \
822                 `Option` of either)"
823            } else if mysql {
824                "the row is a record whose fields are `Int`, `Float`, `String`, `Bool`, \
825                 `Bytes` or `Decimal` (or a refined or opaque type over one, or an `Option` \
826                 of either); a MySQL date or time arrives as text without a zone, so read it \
827                 as a `String`"
828            } else {
829                "the row is a record whose fields are `Int`, `Float`, `String`, `Bool` or \
830                 `Bytes` (or a refined or opaque type over one, or an `Option` of either)"
831            }),
832        );
833        ok = false;
834    }
835    let mut sql = None;
836    let tail_text = sql_literal_text(&args[0], ctx);
837    match tail_text.as_ref() {
838        Some(tail) => {
839            // A constant tail is read at compile time (the composed SQL is
840            // recorded below); still type the name so hover and references
841            // see it.
842            if matches!(args[0].kind, ExprKind::Ident(_)) {
843                let _ = type_of(&args[0], None, ctx);
844            }
845            if begins_with_select(tail) {
846                ctx.errors.push(
847                    CompileError::new(
848                        "bynk.types.select_tail_has_select",
849                        args[0].span,
850                        format!("the SQL of `{name}` must start at `FROM`, not `SELECT`"),
851                    )
852                    .with_note(
853                        "the compiler writes `SELECT` and the column list from the row type; \
854                         use `all` and `Json.decodeSql` to spell the columns yourself",
855                    ),
856                );
857                ok = false;
858            } else if begins_without_from(tail) {
859                ctx.errors.push(
860                    CompileError::new(
861                        "bynk.types.select_tail_has_select",
862                        args[0].span,
863                        format!("the SQL of `{name}` must start at `FROM`"),
864                    )
865                    .with_note(
866                        "the compiler writes `SELECT` and the column list from the row type, \
867                         so the literal continues from `FROM`; use `all` and `Json.decodeSql` \
868                         for a `WITH` or parenthesised query",
869                    ),
870                );
871                ok = false;
872            } else if ok && let Ty::Named { name: row, .. } = &*tys.get(t) {
873                let cols =
874                    select_columns_quoted(row, &ctx.input.types, if mysql { '`' } else { '"' });
875                sql = Some(format!("SELECT {cols} {}", tail.trim_start()));
876            }
877        }
878        None => {
879            ctx.errors.push(sql_not_literal_with(
880                args[0].span,
881                &format!("the SQL of `{cap}.{}`", method.name),
882                if pg {
883                    "`$1`, `$2`"
884                } else if mysql {
885                    "`?`"
886                } else {
887                    "`?1`, `?2`"
888                },
889            ));
890            // The tail is not an ordinary argument here; still type it for hover.
891            let _ = type_of(&args[0], None, ctx);
892            ok = false;
893        }
894    }
895    let params_ty = tys.intern(Ty::List(value_ty));
896    if let Some(actual) = type_of(&args[1], Some(params_ty), ctx)
897        && !compatible(actual, params_ty, tys)
898    {
899        ctx.errors.push(CompileError::new(
900            "bynk.types.argument_mismatch",
901            args[1].span,
902            format!(
903                "argument 2 to capability `{name}` has type `{}`, but parameter expects `{}`",
904                actual.display(tys),
905                params_ty.display(tys)
906            ),
907        ));
908    }
909    let first = method.name == "firstAs";
910    // #3108: where the literal begins in the composed text, for sub-literal spans.
911    let select_literal = match (&sql, &tail_text) {
912        (Some(composed), Some(tail)) => {
913            let trimmed = tail.len() - tail.trim_start().len();
914            let prefix = composed.len() - (tail.len() - trimmed);
915            Some((tail.clone(), prefix as isize - trimmed as isize))
916        }
917        _ => None,
918    };
919    let sql = sql.filter(|_| ok)?;
920    // A `Postgres` read is not recorded as a site: the schema a site is
921    // prepared against is a D1 migration's SQLite, which says nothing of
922    // Postgres (as for `all`, `first` and `run`).
923    if !pg
924        && !mysql
925        && let Ty::Named { name: row, .. } = &*tys.get(t)
926        && let Some(TypeBody::Record(record)) = ctx.input.types.get(row).map(|d| &d.body)
927    {
928        ctx.callees.insert(
929            args[0].id,
930            Callee::D1Sql(D1SqlSite {
931                cap: cap.to_string(),
932                op: method.name.clone(),
933                text: sql.clone(),
934                span: args[0].span,
935                row: Some((
936                    row.clone(),
937                    record.fields.iter().map(|f| f.name.name.clone()).collect(),
938                )),
939                passed: literal_list_len(args.get(1), ctx),
940                literal: select_literal,
941                batch: None,
942                peek: None,
943            }),
944        );
945    }
946    ctx.callees.insert(
947        expr_id,
948        Callee::D1Select {
949            cap: cap.to_string(),
950            row: t,
951            sql,
952            first,
953            pg,
954            mysql,
955        },
956    );
957    let rows = if first {
958        tys.intern(Ty::Option(t))
959    } else {
960        tys.intern(Ty::List(t))
961    };
962    Some(tys.intern(Ty::Effect(tys.intern(Ty::Result(rows, read_err)))))
963}
964
965/// `Json.decodeSql[T]`: `T` must be a row record, or a `List` of one. `Err`
966/// carries the reason, for `bynk.types.sql_row_shape`.
967pub(crate) fn check_row_shape(
968    t: TyId,
969    types: &HashMap<String, Arc<TypeDecl>>,
970    tys: &Types,
971) -> Result<(), String> {
972    check_row_shape_for(t, types, tys, false)
973}
974
975/// [`check_row_shape`] for a dialect: a `Postgres` row (`pg`) may also hold an
976/// `Instant`, which a `timestamptz` column arrives as (#3320).
977pub(crate) fn check_row_shape_for(
978    t: TyId,
979    types: &HashMap<String, Arc<TypeDecl>>,
980    tys: &Types,
981    pg: bool,
982) -> Result<(), String> {
983    let row = match &*tys.get(t) {
984        Ty::List(r) => *r,
985        _ => t,
986    };
987    let (name, args) = match &*tys.get(row) {
988        Ty::Named {
989            name,
990            kind: NamedKind::Record,
991            args,
992        } => (name.clone(), args.clone()),
993        _ => {
994            return Err(format!(
995                "`{}` is not a row record or a `List` of one",
996                row.display(tys)
997            ));
998        }
999    };
1000    if !args.is_empty() {
1001        return Err(format!("`{name}` is generic; a row record is not"));
1002    }
1003    let Some(TypeBody::Record(record)) = types.get(&name).map(|d| &d.body) else {
1004        return Err(format!("`{name}` is not a row record"));
1005    };
1006    for f in &record.fields {
1007        if !is_column(&f.type_ref, types, pg) {
1008            return Err(format!(
1009                "field `{}` of `{name}` is not a column type",
1010                f.name.name
1011            ));
1012        }
1013    }
1014    Ok(())
1015}
1016
1017/// A type a SQLite column decodes to: a scalar (`Bytes` from base64), a
1018/// refined or opaque type over one, or an `Option` of either.
1019fn is_column(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>, pg: bool) -> bool {
1020    match r {
1021        TypeRef::Option(inner, _) => {
1022            !matches!(**inner, TypeRef::Option(..)) && is_column(inner, types, pg)
1023        }
1024        TypeRef::Base(b, _) => is_column_base(*b, pg),
1025        TypeRef::Named(id) => types.get(&id.name).is_some_and(|d| match &d.body {
1026            TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. } => {
1027                is_column_base(*base, pg)
1028            }
1029            _ => false,
1030        }),
1031        _ => false,
1032    }
1033}
1034
1035fn is_column_base(b: BaseType, pg: bool) -> bool {
1036    match b {
1037        BaseType::Duration => false,
1038        BaseType::Instant => pg,
1039        _ => true,
1040    }
1041}
1042
1043/// The names of `T`'s row fields that decode as `Bool` (directly, through an
1044/// `Option`, or under a refined or opaque type), for `Json.decodeSql`'s pass
1045/// over SQLite's `0`/`1`. `T` has passed `check_row_shape`.
1046pub fn row_bool_fields(row: &str, types: &HashMap<String, Arc<TypeDecl>>) -> Vec<String> {
1047    row_base_fields(row, types, BaseType::Bool)
1048}
1049
1050/// The names of `T`'s row fields whose type is `base` (directly, through an
1051/// `Option`, or under a refined or opaque type): the columns a dialect's pass
1052/// over the parsed rows converts before the codec runs (`Bool` for SQLite's
1053/// `0`/`1`; `Int` and `Instant` for Postgres' text forms, #3320).
1054pub fn row_base_fields(
1055    row: &str,
1056    types: &HashMap<String, Arc<TypeDecl>>,
1057    base: BaseType,
1058) -> Vec<String> {
1059    fn is_base(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>, want: BaseType) -> bool {
1060        match r {
1061            TypeRef::Option(inner, _) => is_base(inner, types, want),
1062            TypeRef::Base(b, _) => *b == want,
1063            TypeRef::Named(id) => types.get(&id.name).is_some_and(|d| match &d.body {
1064                TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. } => *base == want,
1065                _ => false,
1066            }),
1067            _ => false,
1068        }
1069    }
1070    match types.get(row).map(|d| &d.body) {
1071        Some(TypeBody::Record(record)) => record
1072            .fields
1073            .iter()
1074            .filter(|f| is_base(&f.type_ref, types, base))
1075            .map(|f| f.name.name.clone())
1076            .collect(),
1077        _ => Vec::new(),
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tail_tests {
1083    use super::*;
1084
1085    #[test]
1086    fn select_prefix_is_boundary_safe() {
1087        assert!(begins_with_select("select * from t"));
1088        assert!(begins_with_select("  SELECT x"));
1089        assert!(!begins_with_select("selected_x from t"));
1090        assert!(!begins_with_select("éé"));
1091        assert!(!begins_with_select("sélect"));
1092    }
1093
1094    #[test]
1095    fn tail_must_start_at_from() {
1096        assert!(!begins_without_from("FROM t"));
1097        assert!(!begins_without_from("  from t"));
1098        assert!(begins_without_from("WITH x AS (SELECT 1) SELECT * FROM x"));
1099        assert!(begins_without_from("(SELECT 1)"));
1100        assert!(begins_without_from("fromage"));
1101        assert!(begins_without_from("éé"));
1102    }
1103}