Skip to main content

bynk_check/
d1_sql.rs

1//! #3070: a `D1` call's literal SQL, checked against the schema its binding's
2//! migrations build.
3//!
4//! [`D1Sql::build`] applies each database's migrations, in order, to a fresh
5//! in-memory SQLite (a bundled one, so every machine and CI agree), once per
6//! run. The checker records each literal statement as a
7//! [`D1SqlSite`](crate::checker::D1SqlSite) (a [`Callee::D1Sql`](crate::checker::Callee::D1Sql) entry
8//! under the SQL argument's id); [`D1Sql::check_unit`] then `prepare`s each one
9//! against its database. `prepare` executes nothing, so the check is cheap and
10//! has no side effects. Reported:
11//!
12//! - `bynk.d1.sql_invalid`: the statement doesn't prepare (a syntax error, an
13//!   unknown table or column);
14//! - `bynk.d1.sql_param_count`: the SQL's parameter count
15//!   (`sqlite3_bind_parameter_count`, the rule the test D1 refuses a mismatch
16//!   by, #3003) differs from the list literal passed;
17//! - `bynk.d1.select_field_missing`: a `select[T]` field with no column;
18//! - `bynk.d1.migration_invalid` (warning): a migration that doesn't apply; the
19//!   database's statements are then not checked, since each would only echo it.
20//!
21//! A database with no migrations directory has no schema, so `sql_invalid` and
22//! `select_field_missing` have nothing to check against; but the parameter
23//! count is a property of the SQL text, so `parameter_count` (a scanner that
24//! mirrors SQLite's) still checks it (#3126). A database whose migrations
25//! failed is skipped entirely, as each statement would only echo that warning.
26//! #3197: the statements of a literal `batch` list run in order, so each is
27//! prepared against the schema the earlier ones leave: inside a savepoint on the
28//! schema connection, a statement that prepares and is DDL (`CREATE`, `DROP`,
29//! `ALTER`) is also executed, and the savepoint is rolled back when the batch
30//! has been checked, on every path, so the shared schema is never left changed.
31//! Never stricter than the test tier is the aim, since that tier runs the same
32//! migrations on Node's own SQLite.
33//!
34//! On `wasm32` (the playground) there is no migrations folder and no SQLite:
35//! [`D1Sql::build`] returns `None`.
36
37#[cfg(not(target_arch = "wasm32"))]
38pub use native::D1Sql;
39#[cfg(target_arch = "wasm32")]
40pub use stub::D1Sql;
41
42#[cfg(target_arch = "wasm32")]
43mod stub {
44    use std::collections::HashMap;
45    use std::sync::Arc;
46
47    use bynk_syntax::ast::ExprId;
48    use bynk_syntax::error::CompileError;
49
50    use crate::checker::Callee;
51    use crate::d1_migrations::D1Migrations;
52    use crate::project_model::ErrorSink;
53    use crate::symbols::UnitTable;
54    use bynk_project::worker_layout::WorkerLayout;
55
56    #[derive(Debug)]
57    pub struct D1Sql;
58
59    impl D1Sql {
60        /// There is no schema on `wasm32`, so nothing differs between builds.
61        pub fn digest(&self) -> u64 {
62            0
63        }
64
65        pub fn build(_: &D1Migrations, _: &WorkerLayout, _: &mut ErrorSink) -> Option<Arc<D1Sql>> {
66            None
67        }
68        pub fn check_unit(
69            &self,
70            _: &str,
71            _: &UnitTable,
72            _: &HashMap<ExprId, Callee>,
73            _: Option<&str>,
74        ) -> Vec<CompileError> {
75            Vec::new()
76        }
77        pub fn check_peek_sites(
78            &self,
79            _: &HashMap<String, UnitTable>,
80            _: &HashMap<ExprId, Callee>,
81            _: Option<&str>,
82        ) -> Vec<CompileError> {
83            Vec::new()
84        }
85    }
86}
87
88#[cfg(not(target_arch = "wasm32"))]
89mod native {
90    use std::collections::{BTreeMap, HashMap};
91    use std::path::PathBuf;
92    use std::sync::{Arc, Mutex};
93
94    use bynk_project::assets::PROJECT_MIGRATIONS_DIR;
95    use bynk_syntax::ast::ExprId;
96    use bynk_syntax::error::CompileError;
97    use bynk_syntax::span::Span;
98    use rusqlite::{Connection, DropBehavior, config::DbConfig};
99
100    use crate::checker::Callee;
101    use crate::checker::{D1DecodeSite, D1SqlSite};
102    use crate::d1_migrations::{D1Migrations, d1_database_name, is_d1};
103    use crate::project_model::ErrorSink;
104    use crate::symbols::UnitTable;
105    use bynk_project::worker_layout::WorkerLayout;
106
107    use super::parameter_count;
108
109    /// The schema each migrated database builds, ready to `prepare` against.
110    pub struct D1Sql {
111        /// Database name → its connection. A database whose migrations failed,
112        /// or that has none, has no entry.
113        pub(super) schemas: HashMap<String, Arc<Mutex<Connection>>>,
114        /// The databases that have migration files, whether or not they applied.
115        /// A database in neither map has no migrations, and only its parameter
116        /// counts are checked (#3126).
117        pub(super) migrated: std::collections::HashSet<String>,
118        /// A hash of every database's name and migration contents, in order: what
119        /// a file's check read of this value (the language server's file-check
120        /// digest takes it, #3243). `Debug` prints only the database names, so it
121        /// is not enough to tell two builds apart.
122        digest: u64,
123        /// #3562: which Worker each context's database belongs to.
124        layout: WorkerLayout,
125    }
126
127    impl std::fmt::Debug for D1Sql {
128        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129            f.debug_struct("D1Sql")
130                .field("databases", &self.schemas.keys().collect::<Vec<_>>())
131                .finish()
132        }
133    }
134
135    /// One database's schema: its migrations applied in order to a fresh
136    /// in-memory SQLite. `None` (with a `migration_invalid` warning) when one
137    /// doesn't apply.
138    fn build_database(
139        database: &str,
140        files: &[crate::d1_migrations::MigrationFile],
141        errors: &mut ErrorSink,
142    ) -> Option<Connection> {
143        let conn = Connection::open_in_memory().ok()?;
144        conn.execute_batch(TRACKING_TABLE).ok()?;
145        for file in files {
146            if let Err(e) = conn.execute_batch(&file.sql) {
147                let key = format!("{PROJECT_MIGRATIONS_DIR}/{database}/{}", file.name);
148                errors.push_for(
149                    Some(&PathBuf::from(&key)),
150                    CompileError::new(
151                        "bynk.d1.migration_invalid",
152                        Span::default(),
153                        format!("migration `{key}` doesn't apply: {e}"),
154                    )
155                    .with_note(format!(
156                        "applied in order to an empty in-memory SQLite; the SQL of `{database}` is not checked against its schema until this applies"
157                    )),
158                );
159                return None;
160            }
161        }
162        // A double-quoted name that matches no column silently becomes a
163        // string literal (SQLite's `DQS` fallback), so a misspelt column
164        // would prepare, and `select[T]`'s quoted column list would
165        // never miss. Off for statements; migrations ran with it on.
166        let _ = conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DQS_DML, false);
167        Some(conn)
168    }
169
170    /// Wrangler's tracking table, which a statement could read (`bynk revert`
171    /// does), created before the migrations run as `wrangler d1 migrations`
172    /// does.
173    const TRACKING_TABLE: &str = "CREATE TABLE IF NOT EXISTS d1_migrations(\
174        id INTEGER PRIMARY KEY AUTOINCREMENT, \
175        name TEXT UNIQUE, \
176        applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)";
177
178    /// #3108: the schemas built so far in this process, by a hash of the database's
179    /// name and migration contents. The language server analyses the project on
180    /// every edit; a schema is rebuilt only when its migrations changed. A
181    /// connection is only ever prepared against (never written), so sharing one
182    /// between analyses is safe. Bounded: past [`CACHE_LIMIT`] entries it starts
183    /// over, so edited migrations' stale schemas don't pile up.
184    static SCHEMA_CACHE: Mutex<Option<HashMap<u64, CachedSchema>>> = Mutex::new(None);
185
186    /// A cached schema with the migration contents it was built from, compared
187    /// on a hit so a hash collision can't reuse another database's schema.
188    struct CachedSchema {
189        contents: Vec<(String, String)>,
190        conn: Arc<Mutex<Connection>>,
191    }
192
193    fn migration_contents(files: &[crate::d1_migrations::MigrationFile]) -> Vec<(String, String)> {
194        files
195            .iter()
196            .map(|f| (f.name.clone(), f.sql.clone()))
197            .collect()
198    }
199    const CACHE_LIMIT: usize = 64;
200
201    fn migrations_key(database: &str, files: &[crate::d1_migrations::MigrationFile]) -> u64 {
202        use std::hash::{Hash, Hasher};
203        let mut h = std::collections::hash_map::DefaultHasher::new();
204        database.hash(&mut h);
205        for file in files {
206            file.name.hash(&mut h);
207            file.sql.hash(&mut h);
208        }
209        h.finish()
210    }
211
212    /// A hash of every database's name and migration files, in database order.
213    fn migrations_digest(migrations: &D1Migrations) -> u64 {
214        use std::hash::{Hash, Hasher};
215        let mut h = std::collections::hash_map::DefaultHasher::new();
216        for (database, files) in migrations {
217            database.hash(&mut h);
218            files.len().hash(&mut h);
219            for file in files {
220                file.name.hash(&mut h);
221                file.sql.hash(&mut h);
222            }
223        }
224        h.finish()
225    }
226
227    impl D1Sql {
228        /// What a check read of this value: see the field's note.
229        pub fn digest(&self) -> u64 {
230            self.digest
231        }
232
233        /// Apply every database's migrations to its own in-memory SQLite. One
234        /// that fails is reported as a warning at its file, and the database is
235        /// left out. Always `Some`: a database with no migrations still has its
236        /// parameter counts checked (#3126).
237        pub fn build(
238            migrations: &D1Migrations,
239            layout: &WorkerLayout,
240            errors: &mut ErrorSink,
241        ) -> Option<Arc<D1Sql>> {
242            let mut schemas = HashMap::new();
243            let mut migrated = std::collections::HashSet::new();
244            for (database, files) in migrations {
245                if files.is_empty() {
246                    continue;
247                }
248                migrated.insert(database.clone());
249                let key = migrations_key(database, files);
250                let contents = migration_contents(files);
251                // A poisoned lock (a panic elsewhere) is recovered, not treated as
252                // a miss forever: the cache holds only complete entries.
253                let cached = SCHEMA_CACHE
254                    .lock()
255                    .unwrap_or_else(|e| e.into_inner())
256                    .as_ref()
257                    .and_then(|c| c.get(&key))
258                    .filter(|hit| hit.contents == contents)
259                    .map(|hit| hit.conn.clone());
260                if let Some(conn) = cached {
261                    schemas.insert(database.clone(), conn);
262                    continue;
263                }
264                let Some(conn) = build_database(database, files, errors) else {
265                    continue;
266                };
267                let conn = Arc::new(Mutex::new(conn));
268                {
269                    let mut cache = SCHEMA_CACHE.lock().unwrap_or_else(|e| e.into_inner());
270                    let cache = cache.get_or_insert_with(HashMap::new);
271                    if cache.len() >= CACHE_LIMIT {
272                        cache.clear();
273                    }
274                    cache.insert(
275                        key,
276                        CachedSchema {
277                            contents,
278                            conn: conn.clone(),
279                        },
280                    );
281                }
282                schemas.insert(database.clone(), conn);
283            }
284            let digest = migrations_digest(migrations);
285            Some(Arc::new(D1Sql {
286                schemas,
287                migrated,
288                digest,
289                layout: layout.clone(),
290            }))
291        }
292
293        /// #3147: check every `D1.peek` read the callees recorded, each against
294        /// its own participant's migrations; and refuse one that would write,
295        /// as the prepared statement's `readonly` flag says.
296        pub fn check_peek_sites(
297            &self,
298            unit_tables: &HashMap<String, UnitTable>,
299            callees: &HashMap<ExprId, Callee>,
300            source: Option<&str>,
301        ) -> Vec<CompileError> {
302            let mut sites: BTreeMap<(usize, usize), &D1SqlSite> = BTreeMap::new();
303            for callee in callees.values() {
304                let site: &D1SqlSite = match callee {
305                    Callee::D1Sql(site) => site,
306                    Callee::Const(_, Some(site)) => site,
307                    _ => continue,
308                };
309                if site.peek.is_some() {
310                    sites.insert((site.span.start, site.span.end), site);
311                }
312            }
313            let mut out = Vec::new();
314            for site in sites.values() {
315                let Some((participant, cap)) = site.peek.as_ref() else {
316                    continue;
317                };
318                let Some(instance) = unit_tables
319                    .get(participant)
320                    .and_then(|t| t.derived.get(cap))
321                    .filter(|d| is_d1(d))
322                else {
323                    continue;
324                };
325                let database = d1_database_name(&self.layout.dir(participant), &instance.binding);
326                let Some(conn) = self.schemas.get(&database) else {
327                    continue;
328                };
329                let conn = conn.lock().unwrap_or_else(|e| e.into_inner());
330                if let Some(err) = check_site(&conn, site, &database, source) {
331                    out.push(err);
332                } else if !crate::checker::peek::begins_with_write(&site.text)
333                    && conn.prepare(&site.text).is_ok_and(|stmt| !stmt.readonly())
334                {
335                    out.push(
336                        CompileError::new(
337                            "bynk.test.peek_write",
338                            site.span,
339                            format!(
340                                "the SQL of `D1.peek` reads, but this statement of {} would write",
341                                site_name(site)
342                            ),
343                        )
344                        .with_note(
345                            "a peeked database is read-only: a case makes the app write by driving the app",
346                        ),
347                    );
348                }
349            }
350            out
351        }
352
353        /// Check every literal statement the unit's call sites recorded.
354        pub fn check_unit(
355            &self,
356            unit: &str,
357            table: &UnitTable,
358            callees: &HashMap<ExprId, Callee>,
359            // The source of the file the sites are in, to point an error inside
360            // the SQL literal; `None` reports at the whole argument.
361            source: Option<&str>,
362        ) -> Vec<CompileError> {
363            // A deterministic order: by position in the source.
364            let mut sites: BTreeMap<(usize, usize), &D1SqlSite> = BTreeMap::new();
365            let mut decodes: BTreeMap<(usize, usize), &D1DecodeSite> = BTreeMap::new();
366            for callee in callees.values() {
367                // #3139: a `Json.decodeSql` linked to a statement's rows.
368                if let Callee::D1Decode(d) = callee {
369                    decodes.insert((d.span.start, d.span.end), d);
370                    continue;
371                }
372                // A `const` SQL argument's entry is `Const`, which keeps the site.
373                let site: &D1SqlSite = match callee {
374                    Callee::D1Sql(site) => site,
375                    Callee::Const(_, Some(site)) => site,
376                    _ => continue,
377                };
378                // #3147: a `D1.peek` read belongs to its participant's database,
379                // checked by `check_peek_sites`.
380                if site.peek.is_some() {
381                    continue;
382                }
383                sites.insert((site.span.start, site.span.end), site);
384            }
385            let worker = self.layout.dir(unit);
386            let mut out = Vec::new();
387            // #3197: a batch is checked as a whole, the first time one of its
388            // statements is reached (they are contiguous in source order).
389            let mut batches_done: std::collections::HashSet<(String, usize)> =
390                std::collections::HashSet::new();
391            for site in sites.values() {
392                let Some(instance) = table.derived.get(&site.cap).filter(|d| is_d1(d)) else {
393                    continue;
394                };
395                let database = d1_database_name(&worker, &instance.binding);
396                let Some(conn) = self.schemas.get(&database) else {
397                    // No schema: checked for its parameter count alone, unless
398                    // the database has migrations that failed (their warning
399                    // already stands for every statement).
400                    if !self.migrated.contains(&database)
401                        && let Some(err) =
402                            parameter_count(&site.text).and_then(|used| count_error(site, used))
403                    {
404                        out.push(err);
405                    }
406                    continue;
407                };
408                let mut conn = conn.lock().unwrap_or_else(|e| e.into_inner());
409                if let Some(position) = site.batch {
410                    if batches_done.insert((database.clone(), position.group)) {
411                        let members: Vec<&D1SqlSite> = sites
412                            .values()
413                            .copied()
414                            .filter(|s| s.batch.is_some_and(|b| b.group == position.group))
415                            .filter(|s| s.cap == site.cap)
416                            .collect();
417                        out.extend(check_batch(&mut conn, &members, &database, source));
418                    }
419                    continue;
420                }
421                if let Some(err) = check_site(&conn, site, &database, source) {
422                    out.push(err);
423                }
424            }
425            // #3139: each linked decode's required fields against the columns
426            // of the statement the rows came from (nothing to check without a
427            // schema, or when the statement itself doesn't prepare: that is
428            // already reported at its site).
429            for d in decodes.values() {
430                let Some(instance) = table.derived.get(&d.site.cap).filter(|i| is_d1(i)) else {
431                    continue;
432                };
433                let database = d1_database_name(&worker, &instance.binding);
434                let Some(conn) = self.schemas.get(&database) else {
435                    continue;
436                };
437                let conn = conn.lock().unwrap_or_else(|e| e.into_inner());
438                out.extend(check_decode(&conn, d));
439            }
440            out
441        }
442    }
443
444    /// The column a `no such column: x` message names, bare of any `table.` or
445    /// quotes (SQLite adds a hint after a double-quoted one).
446    fn missing_column(msg: &str) -> Option<&str> {
447        let name = msg.strip_prefix("no such column: ")?;
448        let name = name.split(" - ").next().unwrap_or(name).trim();
449        let name = name.rsplit('.').next().unwrap_or(name);
450        Some(name.trim_matches('"'))
451    }
452
453    /// #3108: the span of the token SQLite refused, inside the SQL literal, or
454    /// `None` (the whole argument is reported) when the offset is unknown, lies
455    /// in the compiler's generated `select` prefix, or can't be mapped back
456    /// into the source with certainty.
457    pub(super) fn error_span(source: &str, site: &D1SqlSite, offset: i32) -> Option<Span> {
458        let offset = usize::try_from(offset).ok()?;
459        let (decoded, origin) = match &site.literal {
460            Some((lit, origin)) => (lit.as_str(), *origin),
461            None => (site.text.as_str(), 0),
462        };
463        let at = usize::try_from(offset as isize - origin).ok()?;
464        super::literal_subspan(source, site.span, decoded, at)
465    }
466
467    /// #3197: one literal `batch` list's statements, in order, each prepared
468    /// against the schema the earlier ones leave. The work happens inside a
469    /// savepoint whose guard rolls back (and releases) when it drops, so the
470    /// cached schema connection comes out unchanged on every path, an early
471    /// return or a panic included. Only DDL is executed: DML can fail on its
472    /// parameters or a constraint, and never changes the schema. A statement
473    /// that doesn't prepare is reported with its position in the list and
474    /// leaves the schema as it was; checking goes on with the next one.
475    ///
476    /// A DDL statement that doesn't prepare isn't applied, so a later statement
477    /// that depends on it (a failed `CREATE`, then an `INSERT` into the table it
478    /// would have made) is reported too. That is accepted rather than
479    /// suppressed: at run time the batch stops at the first failure, so the
480    /// first error is the one to fix, and later ones go once it is fixed.
481    pub(super) fn check_batch(
482        conn: &mut Connection,
483        members: &[&D1SqlSite],
484        database: &str,
485        source: Option<&str>,
486    ) -> Vec<CompileError> {
487        let mut out = Vec::new();
488        let Ok(mut savepoint) = conn.savepoint() else {
489            // No savepoint to work in: check each against the migrated schema.
490            for site in members {
491                out.extend(check_site(conn, site, database, source));
492            }
493            return out;
494        };
495        savepoint.set_drop_behavior(DropBehavior::Rollback);
496        for site in members {
497            match check_site(&savepoint, site, database, source) {
498                Some(err) => {
499                    let index = site.batch.map_or(0, |b| b.index) + 1;
500                    out.push(err.with_note(format!(
501                        "statement {index} of the batch; a batch's statements run in order, so each is checked against the schema the earlier ones leave"
502                    )));
503                }
504                None => apply_ddl(&savepoint, &site.text),
505            }
506        }
507        out
508    }
509
510    /// Whether `sql` begins (past whitespace and comments) with a schema
511    /// statement.
512    pub(super) fn is_ddl(sql: &str) -> bool {
513        let mut rest = sql;
514        loop {
515            rest = rest.trim_start();
516            if let Some(after) = rest.strip_prefix("--") {
517                rest = after.split_once('\n').map_or("", |(_, tail)| tail);
518            } else if let Some(after) = rest.strip_prefix("/*") {
519                rest = after.split_once("*/").map_or("", |(_, tail)| tail);
520            } else {
521                break;
522            }
523        }
524        let word: String = rest
525            .chars()
526            .take_while(|c| c.is_ascii_alphabetic())
527            .collect::<String>()
528            .to_ascii_uppercase();
529        matches!(word.as_str(), "CREATE" | "DROP" | "ALTER")
530    }
531
532    /// Execute `sql` when it is DDL, so the next statement of the batch sees its
533    /// effect. A failure to execute leaves the schema as it was.
534    fn apply_ddl(conn: &Connection, sql: &str) {
535        if !is_ddl(sql) {
536            return;
537        }
538        if let Ok(mut stmt) = conn.prepare(sql)
539            && stmt.parameter_count() == 0
540        {
541            let _ = stmt.execute([]);
542        }
543    }
544
545    fn check_site(
546        conn: &Connection,
547        site: &D1SqlSite,
548        database: &str,
549        source: Option<&str>,
550    ) -> Option<CompileError> {
551        let what = site_name(site);
552        let stmt = match conn.prepare(&site.text) {
553            Ok(stmt) => stmt,
554            Err(e) => {
555                let (msg, offset) = match &e {
556                    rusqlite::Error::SqlInputError { msg, offset, .. } => (msg.clone(), *offset),
557                    other => (other.to_string(), -1),
558                };
559                if let Some((row, fields)) = &site.row
560                    && let Some(col) = missing_column(&msg)
561                    && fields.iter().any(|f| f == col)
562                {
563                    return Some(
564                        CompileError::new(
565                            "bynk.d1.select_field_missing",
566                            site.span,
567                            format!("`{row}` has a field `{col}`, but the query has no column `{col}`"),
568                        )
569                        .with_note(format!(
570                            "{what} selects every field of `{row}` by name; rename the column in the tail (`AS {col}`), rename the field, or use `all` and `Json.decodeSql` to write the columns yourself"
571                        )),
572                    );
573                }
574                let span = source
575                    .and_then(|src| error_span(src, site, offset))
576                    .unwrap_or(site.span);
577                return Some(
578                    CompileError::new(
579                        "bynk.d1.sql_invalid",
580                        span,
581                        format!("the SQL of {what} doesn't prepare: {msg}"),
582                    )
583                    .with_note(format!(
584                        "checked against the migrations of `{database}`, applied to an empty in-memory SQLite"
585                    )),
586                );
587            }
588        };
589        count_error(site, stmt.parameter_count())
590    }
591
592    /// How an error names a statement's call: `Orders.all`, or for a read
593    /// through `D1.peek` (#3147), `D1.peek(shop.orders.Orders).all`.
594    fn site_name(site: &D1SqlSite) -> String {
595        match &site.peek {
596            Some((participant, cap)) => format!("`D1.peek({participant}.{cap}).{}`", site.op),
597            None => format!("`{}.{}`", site.cap, site.op),
598        }
599    }
600
601    /// #3139: the required fields of the decoded row with no result column in the
602    /// statement the rows came from, one `select_field_missing` each.
603    fn check_decode(conn: &Connection, d: &D1DecodeSite) -> Vec<CompileError> {
604        let Ok(stmt) = conn.prepare(&d.site.text) else {
605            return Vec::new();
606        };
607        let columns: Vec<&str> = stmt.column_names().collect();
608        let what = format!("`{}.{}`", d.site.cap, d.site.op);
609        d.required
610            .iter()
611            .filter(|f| !columns.contains(&f.as_str()))
612            .map(|f| {
613                CompileError::new(
614                    "bynk.d1.select_field_missing",
615                    d.span,
616                    format!(
617                        "`{}` has a field `{f}`, but the statement of {what} has no column `{f}`",
618                        d.row
619                    ),
620                )
621                .with_note(
622                    "`Json.decodeSql` reads columns by name; alias the column in the SQL (`… AS name`) or rename the field",
623                )
624            })
625            .collect()
626    }
627
628    /// `bynk.d1.sql_param_count` when the SQL uses `used` parameters and the
629    /// list literal passes a different number.
630    fn count_error(site: &D1SqlSite, used: usize) -> Option<CompileError> {
631        let what = site_name(site);
632        let passed = site.passed?;
633        (used != passed).then(|| {
634            CompileError::new(
635                "bynk.d1.sql_param_count",
636                site.span,
637                format!(
638                    "the SQL of {what} takes {used} parameter{}, but the list passes {passed}",
639                    if used == 1 { "" } else { "s" }
640                ),
641            )
642            .with_note(
643                "`?N` names the Nth value (the highest `N` is the count) and a bare `?` the next; D1 refuses a statement bound to a different number of values",
644            )
645        })
646    }
647}
648
649/// #3126: how many parameters `sql` binds, by SQLite's rule
650/// (`sqlite3_bind_parameter_count`), without a schema: `?NNN` is `NNN`, a bare
651/// `?` the next number after the highest so far, the count the highest index,
652/// and a named parameter (`:a`, `@a`, `$a`) takes the next number the first
653/// time its name is seen. `None` for an index SQLite refuses (`?0`, past 32766). Quoted text (`'…'`, `"…"`, `` `…` ``, `[…]`) and
654/// comments hold none. It mirrors `sqlParameters` in the test tier's runtime
655/// (`bynk-emit/runtime/src/storage.ts`, #3043), which is the baseline for the
656/// named forms; the `agrees_with_sqlite` test pins it against `rusqlite`.
657#[cfg(not(target_arch = "wasm32"))]
658pub(crate) fn parameter_count(sql: &str) -> Option<usize> {
659    let b = sql.as_bytes();
660    let n = b.len();
661    let mut count = 0usize;
662    let mut names: std::collections::HashSet<&[u8]> = std::collections::HashSet::new();
663    let mut i = 0;
664    // Skip a quoted run starting at `i`; `doubled` when the close doubles to escape.
665    let skip = |i: &mut usize, close: u8, doubled: bool| {
666        *i += 1;
667        while *i < n {
668            if b[*i] == close {
669                if doubled && b.get(*i + 1) == Some(&close) {
670                    *i += 2;
671                } else {
672                    break;
673                }
674            } else {
675                *i += 1;
676            }
677        }
678        *i += 1;
679    };
680    // SQLite's tokenizer takes every byte >= 0x80 as part of an identifier.
681    let is_word = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'$' || c >= 0x80;
682    while i < n {
683        let c = b[i];
684        match c {
685            b'\'' | b'"' | b'`' => skip(&mut i, c, true),
686            b'[' => skip(&mut i, b']', false),
687            b'-' if b.get(i + 1) == Some(&b'-') => {
688                while i < n && b[i] != b'\n' {
689                    i += 1;
690                }
691            }
692            b'/' if b.get(i + 1) == Some(&b'*') => {
693                i = match sql[i + 2..].find("*/") {
694                    Some(end) => i + 2 + end + 2,
695                    None => n,
696                };
697            }
698            b'?' => {
699                i += 1;
700                let start = i;
701                while i < n && b[i].is_ascii_digit() {
702                    i += 1;
703                }
704                if i > start {
705                    // SQLite refuses `?0` and an index past its limit (32766) as
706                    // a syntax error, so there is no count to compare.
707                    match sql[start..i].parse::<usize>() {
708                        Ok(index) if (1..=32766).contains(&index) => count = count.max(index),
709                        _ => return None,
710                    }
711                } else {
712                    count = count.saturating_add(1);
713                }
714            }
715            // `$` continues an identifier (`a$b`); `:` and `@` always start a parameter.
716            b':' | b'@' | b'$' if c != b'$' || !(i > 0 && is_word(b[i - 1])) => {
717                let start = i;
718                i += 1;
719                while i < n && is_word(b[i]) {
720                    i += 1;
721                }
722                if i - start > 1 && names.insert(&b[start..i]) {
723                    count = count.saturating_add(1);
724                }
725            }
726            _ => i += 1,
727        }
728    }
729    Some(count)
730}
731
732/// The source span of the token starting at byte `at` of a string literal's
733/// decoded value `decoded`, for the literal token `lit` in `source`.
734///
735/// The decoded bytes are aligned with the lexeme's: an escape (`\\n`, `\\"`, `\\u{…}`)
736/// stands for one decoded character, and bytes the decoder drops (a multi-line
737/// literal's indent) are skipped. The alignment is *verified*: the lexeme text
738/// at the mapped range must equal the decoded token, so a form the alignment
739/// gets wrong (or can't handle: raw-looking oddities, a `const`'s use site,
740/// which isn't a literal) gives `None`, never a wrong span.
741#[cfg(not(target_arch = "wasm32"))]
742pub(crate) fn literal_subspan(
743    source: &str,
744    lit: bynk_syntax::span::Span,
745    decoded: &str,
746    at: usize,
747) -> Option<bynk_syntax::span::Span> {
748    use bynk_syntax::span::Span;
749    let lexeme = source.get(lit.start..lit.end)?;
750    let bytes = lexeme.as_bytes();
751    // Where the value's text begins: past the opening quote (and a raw literal's
752    // `r` and hashes), or, for a multi-line literal, past the opener's line.
753    let raw = bytes.first() == Some(&b'r');
754    let quote = lexeme.find('"')?;
755    if bytes[..quote].iter().any(|b| !matches!(b, b'r' | b'#')) {
756        return None;
757    }
758    let mut i = if lexeme[quote..].starts_with("\"\"\"") {
759        quote + lexeme[quote..].find('\n')? + 1
760    } else {
761        quote + 1
762    };
763    // The token: a quoted name, or a run of word characters, or one character.
764    let tok_end = {
765        let rest = decoded.get(at..)?;
766        let mut chars = rest.char_indices();
767        let (_, first) = chars.next()?;
768        let len = if first == '"' {
769            rest[1..].find('"').map_or(1, |n| n + 2)
770        } else if first.is_alphanumeric() || first == '_' {
771            rest.char_indices()
772                .find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
773                .map_or(rest.len(), |(n, _)| n)
774        } else {
775            first.len_utf8()
776        };
777        at + len
778    };
779    let token = decoded.get(at..tok_end)?;
780    let mut start = None;
781    let mut end = 0;
782    for (idx, c) in decoded.char_indices() {
783        if idx >= tok_end {
784            break;
785        }
786        // Advance to the lexeme byte that spells `c`.
787        let found = loop {
788            let rest = lexeme.get(i..)?;
789            let mut it = rest.chars();
790            let head = it.next()?;
791            if head == '\\' && !raw {
792                let (decoded_char, len) = unescape(rest)?;
793                if decoded_char == c {
794                    break (i, len);
795                }
796                i += len;
797            } else if head == c {
798                break (i, head.len_utf8());
799            } else {
800                i += head.len_utf8();
801            }
802        };
803        if idx == at {
804            start = Some(found.0);
805        }
806        end = found.0 + found.1;
807        i = end;
808    }
809    let (start, end) = (start?, end);
810    (lexeme.get(start..end)? == token)
811        .then(|| Span::new_in(lit.file, lit.start + start, lit.start + end))
812}
813
814/// The character an escape at the head of `s` (which starts with `\`) denotes,
815/// and the escape's length in bytes.
816#[cfg(not(target_arch = "wasm32"))]
817fn unescape(s: &str) -> Option<(char, usize)> {
818    let b = s.as_bytes();
819    Some(match *b.get(1)? {
820        b'n' => ('\n', 2),
821        b't' => ('\t', 2),
822        b'r' => ('\r', 2),
823        b'0' => ('\0', 2),
824        b'\\' => ('\\', 2),
825        b'"' => ('"', 2),
826        b'\'' => ('\'', 2),
827        b'u' => {
828            let close = s.find('}')?;
829            let hex = s.get(3..close)?;
830            (
831                char::from_u32(u32::from_str_radix(hex, 16).ok()?)?,
832                close + 1,
833            )
834        }
835        _ => return None,
836    })
837}
838
839#[cfg(all(test, not(target_arch = "wasm32")))]
840mod tests {
841    use super::*;
842    use crate::d1_migrations::{D1Migrations, MigrationFile};
843    use crate::project_model::ErrorSink;
844    use rusqlite::Connection;
845
846    fn migrations(files: &[(&str, &str)]) -> D1Migrations {
847        let mut m = D1Migrations::new();
848        m.insert(
849            "demo-orders".to_string(),
850            files
851                .iter()
852                .map(|(name, sql)| MigrationFile {
853                    name: name.to_string(),
854                    sql: sql.to_string(),
855                })
856                .collect(),
857        );
858        m
859    }
860
861    #[test]
862    fn a_migration_that_fails_warns_once_and_drops_the_database() {
863        let mut errors = ErrorSink::new();
864        let built = D1Sql::build(
865            &migrations(&[
866                ("0001_a.sql", "CREATE TABLE t (id TEXT);"),
867                ("0002_b.sql", "ALTER TABLE t ADD COLUMN;"),
868                ("0003_c.sql", "CREATE TABLE u (id TEXT);"),
869            ]),
870            &bynk_project::worker_layout::WorkerLayout::identity(),
871            &mut errors,
872        );
873        let built = built.expect("built");
874        assert!(
875            built.schemas.is_empty(),
876            "no database left to check against"
877        );
878        assert_eq!(
879            built.migrated.len(),
880            1,
881            "but it is still known to be migrated"
882        );
883        assert!(errors.is_empty(), "a warning, not an error");
884        let warnings = errors.into_warnings();
885        assert_eq!(warnings.len(), 1);
886        assert_eq!(warnings[0].error.category, "bynk.d1.migration_invalid");
887    }
888
889    #[test]
890    fn migrations_see_the_tracking_table_and_later_files_see_earlier_ones() {
891        let mut errors = ErrorSink::new();
892        let built = D1Sql::build(
893            &migrations(&[
894                ("0001_a.sql", "CREATE TABLE t (id TEXT);"),
895                (
896                    "0002_b.sql",
897                    "INSERT INTO t VALUES (\"a\"); SELECT name FROM d1_migrations;",
898                ),
899            ]),
900            &bynk_project::worker_layout::WorkerLayout::identity(),
901            &mut errors,
902        );
903        assert!(built.is_some());
904        assert!(errors.into_warnings().is_empty());
905    }
906
907    /// The parameter count is SQLite's own (`sqlite3_bind_parameter_count`),
908    /// the rule the test D1's `sqlParameters` mirrors (#3003), so the two agree
909    /// on the cases #3043 pinned.
910    #[test]
911    fn the_parameter_count_follows_sqlites_rule() {
912        let conn = Connection::open_in_memory().unwrap();
913        conn.execute_batch("CREATE TABLE t (a, b, c)").unwrap();
914        let count = |sql: &str| conn.prepare(sql).unwrap().parameter_count();
915        assert_eq!(count("SELECT * FROM t WHERE a = ?1 AND b = ?2"), 2);
916        assert_eq!(
917            count("SELECT * FROM t WHERE a = ?1 OR b = ?1"),
918            1,
919            "repeated ?1"
920        );
921        assert_eq!(count("SELECT * FROM t WHERE a = ?3"), 3, "the highest ?N");
922        assert_eq!(count("SELECT * FROM t WHERE a = ? AND b = ?"), 2, "bare ?");
923        assert_eq!(
924            count("SELECT * FROM t WHERE a = ?2 AND b = ?"),
925            3,
926            "bare ? after ?2"
927        );
928        assert_eq!(count("SELECT '?1' FROM t"), 0, "quoted");
929        assert_eq!(count("SELECT * FROM t -- ?1\nWHERE a = ?1"), 1, "comment");
930        assert_eq!(
931            count("SELECT * FROM t /* ?5 */ WHERE a = ?1"),
932            1,
933            "block comment"
934        );
935    }
936
937    /// #3126: the scanner agrees with SQLite's own count on a corpus (the
938    /// cases #3043 pinned, plus the quoting forms and named parameters).
939    #[test]
940    fn the_scanner_agrees_with_sqlite() {
941        let conn = Connection::open_in_memory().unwrap();
942        conn.execute_batch("CREATE TABLE t (a, b, c)").unwrap();
943        let corpus = [
944            "SELECT * FROM t",
945            "SELECT * FROM t WHERE a = ?1 AND b = ?2",
946            "SELECT * FROM t WHERE a = ?1 OR b = ?1",
947            "SELECT * FROM t WHERE a = ?3",
948            "SELECT * FROM t WHERE a = ? AND b = ?",
949            "SELECT * FROM t WHERE a = ?2 AND b = ?",
950            "SELECT * FROM t WHERE a = ? AND b = ?5 AND c = ?",
951            "SELECT '?1' FROM t",
952            "SELECT 'it''s ?1' FROM t WHERE a = ?1",
953            "SELECT \"?1\" AS \"?2\" FROM t",
954            "SELECT `?1` FROM (SELECT 1 AS `?1`) WHERE 1 = ?1",
955            "SELECT [?1] FROM (SELECT 1 AS [?1]) WHERE 1 = ?1",
956            "SELECT * FROM t -- ?1\nWHERE a = ?1",
957            "SELECT * FROM t /* ?5 */ WHERE a = ?1",
958            "SELECT * FROM t WHERE a = ?1 /* unterminated ?9",
959            "SELECT * FROM t WHERE a = :x AND b = :x AND c = :y",
960            "SELECT * FROM t WHERE a = @x AND b = $y",
961            "SELECT * FROM t WHERE a = ?1 AND b = :x",
962            "SELECT * FROM t WHERE a = :x AND b = ?",
963            "SELECT * FROM t WHERE a = ?01 AND b = ?1",
964            "INSERT INTO t VALUES (?, ?, ?)",
965            "INSERT INTO t VALUES (?1, ?2, ?3) -- ?4",
966            "SELECT * FROM t WHERE a = :café AND b = :cafè",
967            "SELECT * FROM t WHERE a = :é",
968        ];
969        for sql in corpus {
970            let want = conn.prepare(sql).unwrap().parameter_count();
971            assert_eq!(super::parameter_count(sql), Some(want), "{sql}");
972        }
973        // An index SQLite refuses has no count (it is a syntax error there).
974        for sql in [
975            "SELECT ?0",
976            "SELECT ?32767",
977            "SELECT ?99999999999999999999999",
978        ] {
979            assert!(conn.prepare(sql).is_err(), "{sql}");
980            assert_eq!(super::parameter_count(sql), None, "{sql}");
981        }
982    }
983
984    #[test]
985    fn a_database_without_migrations_is_checked_for_its_parameter_count_alone() {
986        let mut errors = ErrorSink::new();
987        let built = D1Sql::build(
988            &migrations(&[]),
989            &bynk_project::worker_layout::WorkerLayout::identity(),
990            &mut errors,
991        )
992        .expect("always built");
993        assert!(built.schemas.is_empty() && built.migrated.is_empty());
994    }
995
996    #[test]
997    fn a_double_quoted_unknown_name_is_not_a_string() {
998        let mut errors = ErrorSink::new();
999        let built = D1Sql::build(
1000            &migrations(&[("0001_a.sql", "CREATE TABLE t (id TEXT);")]),
1001            &bynk_project::worker_layout::WorkerLayout::identity(),
1002            &mut errors,
1003        )
1004        .expect("applies");
1005        let conn = built.schemas["demo-orders"].lock().unwrap();
1006        assert!(conn.prepare("SELECT \"nope\" FROM t").is_err());
1007        assert!(conn.prepare("SELECT \"id\" FROM t").is_ok());
1008    }
1009
1010    /// #3108: the token at a decoded offset, found again in the literal's source.
1011    fn sub(source: &str, decoded: &str, needle: &str) -> Option<String> {
1012        let lit_start = source.find(['"', 'r']).unwrap();
1013        let lit_end = source.rfind(['"', '#']).unwrap() + 1;
1014        let at = decoded.find(needle).unwrap();
1015        let lit = bynk_syntax::span::Span::new(lit_start, lit_end);
1016        literal_subspan(source, lit, decoded, at).map(|s| source[s.start..s.end].to_string())
1017    }
1018
1019    #[test]
1020    fn a_token_is_found_in_a_plain_literal_with_escapes() {
1021        let src = r#"f("SELECT a,\n b FROM \"t\" WHERE stauts = ?1")"#;
1022        let decoded = "SELECT a,\n b FROM \"t\" WHERE stauts = ?1";
1023        assert_eq!(sub(src, decoded, "stauts").as_deref(), Some("stauts"));
1024        assert_eq!(sub(src, decoded, "b FROM").as_deref(), Some("b"));
1025    }
1026
1027    #[test]
1028    fn a_token_is_found_in_a_multi_line_literal_past_its_indent_and_tag() {
1029        let src = "f(\"\"\"sql\n\t\tselect id\n\t\tFROM orders\n\t\tWHERE stauts = ?1\n\t\t\"\"\")";
1030        let decoded = "select id\nFROM orders\nWHERE stauts = ?1";
1031        assert_eq!(sub(src, decoded, "stauts").as_deref(), Some("stauts"));
1032        assert_eq!(sub(src, decoded, "select").as_deref(), Some("select"));
1033    }
1034
1035    #[test]
1036    fn a_raw_literal_maps_through_unescaped() {
1037        let src = r##"f(r#"SELECT \n FROM t WHERE stauts = 1"#)"##;
1038        let decoded = r"SELECT \n FROM t WHERE stauts = 1";
1039        assert_eq!(sub(src, decoded, "stauts").as_deref(), Some("stauts"));
1040    }
1041
1042    #[test]
1043    fn a_mapping_that_cannot_be_verified_falls_back() {
1044        // Not a literal at all (a `const`'s use site): no quote to start from.
1045        let lit = bynk_syntax::span::Span::new(2, 8);
1046        assert_eq!(literal_subspan("f(CONSTX)", lit, "SELECT x", 0), None);
1047    }
1048
1049    /// #3108: an unchanged database's schema is built once and shared; a changed
1050    /// migration builds a new one.
1051    #[test]
1052    fn a_schema_is_cached_until_its_migrations_change() {
1053        let build = |sql: &str| {
1054            let mut errors = ErrorSink::new();
1055            D1Sql::build(
1056                &migrations(&[("0001_a.sql", sql)]),
1057                &bynk_project::worker_layout::WorkerLayout::identity(),
1058                &mut errors,
1059            )
1060            .expect("applies")
1061        };
1062        let a = build("CREATE TABLE cache_probe (id TEXT);");
1063        let b = build("CREATE TABLE cache_probe (id TEXT);");
1064        assert!(
1065            std::sync::Arc::ptr_eq(&a.schemas["demo-orders"], &b.schemas["demo-orders"]),
1066            "the same migrations reuse the built schema"
1067        );
1068        let c = build("CREATE TABLE cache_probe (id TEXT, more TEXT);");
1069        assert!(!std::sync::Arc::ptr_eq(
1070            &a.schemas["demo-orders"],
1071            &c.schemas["demo-orders"]
1072        ));
1073        assert!(
1074            c.schemas["demo-orders"]
1075                .lock()
1076                .unwrap()
1077                .prepare("SELECT more FROM cache_probe")
1078                .is_ok(),
1079            "the edited migration's columns are there"
1080        );
1081    }
1082
1083    /// A migration that fails is not cached: it warns on every build.
1084    #[test]
1085    fn a_failing_migration_still_warns_each_time() {
1086        for _ in 0..2 {
1087            let mut errors = ErrorSink::new();
1088            let built = D1Sql::build(
1089                &migrations(&[("0001_a.sql", "NOT SQL AT ALL;")]),
1090                &bynk_project::worker_layout::WorkerLayout::identity(),
1091                &mut errors,
1092            );
1093            assert!(built.expect("built").schemas.is_empty());
1094            assert_eq!(errors.into_warnings().len(), 1);
1095        }
1096    }
1097
1098    fn site(
1099        text: &str,
1100        literal: Option<(&str, isize)>,
1101        span: (usize, usize),
1102    ) -> crate::checker::D1SqlSite {
1103        crate::checker::D1SqlSite {
1104            cap: "Orders".into(),
1105            op: "select".into(),
1106            text: text.into(),
1107            span: bynk_syntax::span::Span::new(span.0, span.1),
1108            row: None,
1109            passed: None,
1110            literal: literal.map(|(l, o)| (l.to_string(), o)),
1111            batch: None,
1112            peek: None,
1113        }
1114    }
1115
1116    /// An offset in the compiler's generated `SELECT <columns>` prefix isn't in
1117    /// the author's literal: the whole argument is reported.
1118    #[test]
1119    fn an_error_in_the_generated_select_prefix_falls_back() {
1120        let source = r#"f("FROM t WHERE x = 1")"#;
1121        let text = "SELECT \"id\" FROM t WHERE x = 1";
1122        let site = site(text, Some(("FROM t WHERE x = 1", 12)), (2, 22));
1123        // Offset 7 is the `"id"` the compiler wrote; offset 25 is `x` in the tail.
1124        assert_eq!(super::native::error_span(source, &site, 7), None);
1125        let span = super::native::error_span(source, &site, 25).expect("in the tail");
1126        assert_eq!(&source[span.start..span.end], "x");
1127    }
1128
1129    /// A quoted identifier written with escaped quotes can't be mapped
1130    /// verbatim; it falls back rather than point at the wrong text.
1131    #[test]
1132    fn an_escaped_quoted_identifier_falls_back() {
1133        let source = r#"f("SELECT \"nope\" FROM t")"#;
1134        let decoded = "SELECT \"nope\" FROM t";
1135        let lit = bynk_syntax::span::Span::new(2, source.len() - 1);
1136        assert_eq!(literal_subspan(source, lit, decoded, 7), None);
1137    }
1138
1139    /// #3197: a statement of a `batch`, at `index`, in the batch at `group`.
1140    fn batch_site(text: &str, index: usize) -> crate::checker::D1SqlSite {
1141        crate::checker::D1SqlSite {
1142            op: "batch".into(),
1143            batch: Some(crate::checker::BatchPosition { group: 7, index }),
1144            peek: None,
1145            // A distinct span per statement, as in source.
1146            ..site(text, None, (index * 100, index * 100 + 50))
1147        }
1148    }
1149
1150    /// Check one batch's statements against a database built from `migration`;
1151    /// returns the diagnostics and the (shared, cached) schema connection.
1152    fn check_batch_of(
1153        migration: &str,
1154        statements: &[&str],
1155    ) -> (
1156        Vec<bynk_syntax::error::CompileError>,
1157        std::sync::Arc<std::sync::Mutex<Connection>>,
1158    ) {
1159        let mut errors = ErrorSink::new();
1160        let built = D1Sql::build(
1161            &migrations(&[("0001_a.sql", migration)]),
1162            &bynk_project::worker_layout::WorkerLayout::identity(),
1163            &mut errors,
1164        )
1165        .expect("applies");
1166        let conn = built.schemas["demo-orders"].clone();
1167        let sites: Vec<_> = statements
1168            .iter()
1169            .enumerate()
1170            .map(|(i, text)| batch_site(text, i))
1171            .collect();
1172        let members: Vec<&crate::checker::D1SqlSite> = sites.iter().collect();
1173        let out = super::native::check_batch(
1174            &mut conn.lock().unwrap_or_else(|e| e.into_inner()),
1175            &members,
1176            "demo-orders",
1177            None,
1178        );
1179        (out, conn)
1180    }
1181
1182    fn tables(conn: &std::sync::Arc<std::sync::Mutex<Connection>>) -> Vec<String> {
1183        let conn = conn.lock().unwrap_or_else(|e| e.into_inner());
1184        let mut stmt = conn
1185            .prepare("SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name")
1186            .unwrap();
1187        stmt.query_map([], |row| row.get::<_, String>(0))
1188            .unwrap()
1189            .map(Result::unwrap)
1190            .collect()
1191    }
1192
1193    /// #3197: `DROP`, then `CREATE` of the same table, then an `INSERT` into it
1194    /// is a valid batch: the `CREATE` runs after the `DROP`.
1195    #[test]
1196    fn a_batch_may_drop_then_recreate_a_table() {
1197        let (out, _) = check_batch_of(
1198            "CREATE TABLE b3197_books (isbn, title);",
1199            &[
1200                "DROP TABLE b3197_books",
1201                "CREATE TABLE b3197_books (isbn, title, author, pages, finished)",
1202                "INSERT INTO b3197_books VALUES ('x', 'Notes', 'Anon', 10, 2)",
1203            ],
1204        );
1205        assert!(out.is_empty(), "{out:?}");
1206    }
1207
1208    /// #3197: a table created earlier in the batch exists for a later statement.
1209    #[test]
1210    fn a_batch_may_use_a_table_it_creates() {
1211        let (out, _) = check_batch_of(
1212            "CREATE TABLE b3197_other (id);",
1213            &[
1214                "CREATE TABLE b3197_fresh (id, name)",
1215                "INSERT INTO b3197_fresh VALUES (1, 'a')",
1216                "ALTER TABLE b3197_fresh ADD COLUMN extra",
1217                "UPDATE b3197_fresh SET extra = 'x' WHERE id = ?1",
1218            ],
1219        );
1220        assert!(out.is_empty(), "{out:?}");
1221    }
1222
1223    /// #3197: a genuinely invalid statement after DDL is still refused, at that
1224    /// statement's own span, naming its position, and a later valid one is not.
1225    #[test]
1226    fn an_invalid_statement_after_ddl_is_refused_at_its_element() {
1227        let (out, _) = check_batch_of(
1228            "CREATE TABLE b3197_t (id);",
1229            &[
1230                "CREATE TABLE b3197_u (id)",
1231                "INSERT INTO b3197_u (nope) VALUES (1)",
1232                "INSERT INTO b3197_u (id) VALUES (1)",
1233            ],
1234        );
1235        assert_eq!(out.len(), 1, "{out:?}");
1236        assert_eq!(out[0].category, "bynk.d1.sql_invalid");
1237        assert!(out[0].message.contains("nope"), "{}", out[0].message);
1238        assert_eq!((out[0].span.start, out[0].span.end), (100, 150));
1239        assert!(
1240            out[0]
1241                .notes
1242                .iter()
1243                .any(|n| n.contains("statement 2 of the batch")),
1244            "{:?}",
1245            out[0].notes
1246        );
1247    }
1248
1249    /// #3197: a statement that doesn't prepare doesn't change the schema, so a
1250    /// later statement still sees the table as it was.
1251    #[test]
1252    fn a_failing_ddl_statement_leaves_the_schema_alone() {
1253        let (out, _) = check_batch_of(
1254            "CREATE TABLE b3197_k (id);",
1255            &[
1256                "CREATE TABLE b3197_k (id)",      // already exists: refused
1257                "INSERT INTO b3197_k VALUES (1)", // still the migrated table
1258            ],
1259        );
1260        assert_eq!(out.len(), 1, "{out:?}");
1261        assert!(
1262            out[0].message.contains("already exists"),
1263            "{}",
1264            out[0].message
1265        );
1266    }
1267
1268    /// #3197: the cached schema connection comes out of a batch unchanged, so
1269    /// the next batch, or a single statement, sees the migrated schema: the
1270    /// dropped table is back and the created one is gone. Rolled back even
1271    /// when a statement is refused part-way.
1272    #[test]
1273    fn the_cached_schema_is_unchanged_after_a_batch() {
1274        let migration = "CREATE TABLE b3197_keep (id, name);";
1275        let before = {
1276            let (_, conn) = check_batch_of(migration, &[]);
1277            tables(&conn)
1278        };
1279        assert!(before.contains(&"b3197_keep".to_string()), "{before:?}");
1280        let (out, conn) = check_batch_of(
1281            migration,
1282            &[
1283                "DROP TABLE b3197_keep",
1284                "CREATE TABLE b3197_made (id)",
1285                "SELECT nope FROM b3197_made", // refused part-way
1286                "ALTER TABLE b3197_made ADD COLUMN more",
1287            ],
1288        );
1289        assert_eq!(out.len(), 1, "{out:?}");
1290        assert_eq!(tables(&conn), before, "the migrated schema is untouched");
1291        // A separate statement sees the original schema, and a second batch
1292        // starts from it too.
1293        let c = conn.lock().unwrap_or_else(|e| e.into_inner());
1294        assert!(c.prepare("SELECT name FROM b3197_keep").is_ok());
1295        assert!(c.prepare("SELECT id FROM b3197_made").is_err());
1296        drop(c);
1297        let (again, _) = check_batch_of(migration, &["INSERT INTO b3197_keep VALUES (1, 'a')"]);
1298        assert!(again.is_empty(), "{again:?}");
1299    }
1300
1301    /// DML is never executed; only DDL is recognised, past comments.
1302    #[test]
1303    fn only_schema_statements_are_executed() {
1304        use super::native::is_ddl;
1305        for ddl in [
1306            "CREATE TABLE t (a)",
1307            "  drop table t",
1308            "-- note\nALTER TABLE t ADD c",
1309            "/* x */ CREATE INDEX i ON t (a)",
1310        ] {
1311            assert!(is_ddl(ddl), "{ddl}");
1312        }
1313        for other in [
1314            "INSERT INTO t VALUES (1)",
1315            "UPDATE t SET a = 1",
1316            "SELECT 1",
1317            "PRAGMA x",
1318            "",
1319        ] {
1320            assert!(!is_ddl(other), "{other}");
1321        }
1322    }
1323}