SQLite: executing a multi-statement string is quadratic in its length, because every `sqlite3_prepare_v3` call copies the whole remaining tail
I have found these related issues/pull requests
None report this. Nearby: #4133 (slow migrations under sqlx::test, a different fix) and #3662 / #3700 (an earlier bug in the same statement loop).
Description
Executing a string of N statements through raw_sql or a multi-statement query costs O(N × length), all of it in memmove.
VirtualStatement::new stores the query without a NUL terminator, and prepare() hands each remaining tail to sqlite3_prepare_v3 with nByte = tail.len(). When the last byte isn't NUL, SQLite copies the whole input before parsing it (sqlite3DbStrNDup in sqlite3Prepare), so statement k copies everything after it. The sqlite3_prepare docs recommend passing a NUL-terminated string with nByte counting the terminator.
We hit it applying a 17.6 MB, ~55k-statement script with raw_sql: ~13 s, against 0.4 s in the sqlite3 CLI. A profile puts 88% of samples in sqlite3DbStrNDup → memmove.
Reproduction steps
[dependencies]
sqlx = { version = "=0.9.0", default-features = false, features = ["runtime-tokio", "sqlite"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }use std::time::Instant;
use sqlx::{AssertSqlSafe, Connection, SqliteConnection};
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
for n in [5_000, 10_000, 20_000, 40_000, 80_000] {
let script: String = (0..n)
.map(|i| format!("INSERT INTO t (id, note) VALUES ({i}, 'row {i:0>8} padding padding padding padding padding padding');\n"))
.collect();
let mut conn = SqliteConnection::connect("sqlite::memory:").await?;
sqlx::raw_sql("CREATE TABLE t (id INTEGER PRIMARY KEY, note TEXT)")
.execute(&mut conn)
.await?;
let start = Instant::now();
sqlx::raw_sql(AssertSqlSafe(script.as_str())).execute(&mut conn).await?;
println!("{n:>6} statements: {:?}", start.elapsed());
}
Ok(())
}cargo run --release on 0.9.0: each doubling costs ~4×. Split into 64 KiB chunks, the same 80,000 statements take 222 ms.
5000 statements: 46.59ms
10000 statements: 91.39ms
20000 statements: 345.58ms
40000 statements: 1.29s
80000 statements: 4.78sSuggested fix
Keep a NUL at the end of the owned buffer; every tail advance produces still ends with it, so SQLite never copies. The loop then ends when only the terminator is left:
--- a/sqlx-sqlite/src/statement/virtual.rs
+++ b/sqlx-sqlite/src/statement/virtual.rs
@@ -65,7 +65,11 @@
Ok(Self {
persistent,
- tail: Bytes::from(String::from(query)),
+ // NUL-terminated, and every tail keeps that terminator: SQLite copies
+ // the whole input before parsing it whenever the last byte it is
+ // handed is not NUL, which makes a script of N statements cost
+ // O(N * len) bytes of copying.
+ tail: Bytes::from(format!("{query}\0")),
handles: SmallVec::with_capacity(1),
index: None,
columns: SmallVec::with_capacity(1),
@@ -84,7 +88,7 @@
.or(Some(0));
while self.handles.len() <= self.index.unwrap_or(0) {
- if self.tail.is_empty() {
+ if is_exhausted(&self.tail) {
return Ok(None);
}
@@ -141,6 +145,11 @@
}
}
+/// Whether nothing but the NUL terminator is left to prepare.
+fn is_exhausted(tail: &[u8]) -> bool {
+ tail.len() <= 1
+}
+
fn prepare(
conn: *mut sqlite3,
query: &mut Bytes,
@@ -159,7 +168,7 @@
flags |= SQLITE_PREPARE_PERSISTENT as u32;
}
- while !query.is_empty() {
+ while !is_exhausted(query) {
let mut statement_handle: *mut sqlite3_stmt = null_mut();
let mut tail: *const c_char = null();
With it, the repro is linear (80,000 statements in 200 ms) and our 17.6 MB script drops from ~13 s to ~1.4 s.
A related hang today. On 0.9.0, any query containing a NUL byte never returns: "SELECT 1;\0SELECT 2", "SELECT 1;\0" and "\0" all spin the worker thread, because SQLite prepares nothing and the tail never advances. The patch above doesn't change that, so I'd fix it in the same PR: reject a NUL byte in VirtualStatement::new with an error, and have prepare() error instead of looping when SQLite consumes nothing.
Shall I open a PR? It would include this change, the NUL fix, a regression test asserting every tail passed to sqlite3_prepare_v3 ends in NUL (a timing test would be flaky), tests/sqlite cases for trailing whitespace, a trailing comment, a comment-only string and embedded NULs, and a full ./x.py run including --clippy.
SQLx version
0.9.0 (unchanged on main)
Enabled SQLx features
runtime-tokio, sqlite
Database server and version
SQLite 3.51.3 (bundled, libsqlite3-sys 0.37.0)
Operating system
macOS 26 (arm64); also Debian bookworm aarch64
Rust version
rustc 1.97.1 (8bab26f4f 2026-07-14)
Source: transact-rs/sqlx