From c908a517c8c911023e4359f7b05f553c04edc601 Mon Sep 17 00:00:00 2001 From: Jin Xu Date: Sun, 8 Nov 2026 09:12:14 +0800 Subject: [PATCH 1/3] Add a mode that refuses a query string with more than one statement CovenantSQL checks each query before its miners run it, but SQLite splits a string into statements by its own lexical rules, so a second statement that the checker parses differently, for example inside what it takes for a comment, runs unchecked. With SQLiteDriver.SingleStatement set, prepare checks the rest of the string after the first statement byte by byte, following the tokenizer of the bundled SQLite, and refuses anything but whitespace, comments and semicolons with ErrMultipleStatements. The rest is never prepared on the connection, and the C fast path of Exec without arguments, which steps each statement before Go sees the rest, is not used. Exec, Query, Prepare, transactions and the statement cache all go through prepare. The default keeps running batches. --- README.md | 1 + sqlite3.go | 43 ++++++- sqlite3_single_statement.go | 52 +++++++++ sqlite3_single_statement_test.go | 186 +++++++++++++++++++++++++++++++ static_mock.go | 5 +- 5 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 sqlite3_single_statement.go create mode 100644 sqlite3_single_statement_test.go diff --git a/README.md b/README.md index 5adbf156..1537adfc 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ Without a current time, a column declared `NOT NULL DEFAULT CURRENT_TIMESTAMP` c - `sqlite3.go` defines the SQLCipher compile options, turns off the default logging of SQLCipher to stderr, and adds the `_crypto_key` DSN parameter. - `Exec` without arguments reports missing arguments again, which go-sqlite3 v1.14.52 does not. - `sqlite3_nocurrenttime.go` adds the `nocurrenttime` VFS, and `sqlite3_opt_omit_localtime.go` the `sqlite_omit_localtime` tag. +- `SQLiteDriver.SingleStatement` refuses a query string that holds more than one statement with `ErrMultipleStatements`, before any of it runs. - `sqlite3_opt_icu.go` adds the libraries that a static link of ICU needs. - The CIFuzz workflow, which builds the OSS-Fuzz project of go-sqlite3, is removed. diff --git a/sqlite3.go b/sqlite3.go index fd1712fb..8c9ddee5 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -483,6 +483,17 @@ const ( type SQLiteDriver struct { Extensions []string ConnectHook func(*SQLiteConn) error + // SingleStatement makes the connections refuse, with + // ErrMultipleStatements, a query string that holds more than one SQL + // statement, in Exec, Query and Prepare alike. Leading empty statements + // and trailing semicolons, whitespace and comments are allowed. The + // check runs when the first statement is prepared: no statement of a + // refused string is stepped, and the rest of the string is never + // compiled on the connection. A statement that acts when it is + // prepared, such as PRAGMA case_sensitive_like or SQLCipher's PRAGMA + // key and rekey, still acts when it is the first statement of a + // refused string. + SingleStatement bool } // SQLiteConn implements driver.Conn. @@ -509,6 +520,8 @@ type SQLiteConn struct { // only field safe to read without the lock. stmtCache []*SQLiteStmt stmtCacheEnabled bool + // singleStatement is SQLiteDriver.SingleStatement, immutable after Open. + singleStatement bool } // SQLiteTx implements driver.Tx. @@ -1064,8 +1077,9 @@ func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, err } func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - // Fast path: no args, no context cancellation → single CGO call per statement - if len(args) == 0 && ctx.Done() == nil { + // Fast path: no args, no context cancellation → single CGO call per statement. + // It steps each statement before Go sees the rest of the string. + if len(args) == 0 && ctx.Done() == nil && !c.singleStatement { return c.execNoArgs(query) } @@ -1752,7 +1766,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) { } // Create connection to SQLite - conn := &SQLiteConn{db: db, loc: loc, txlock: txlock} + conn := &SQLiteConn{db: db, loc: loc, txlock: txlock, singleStatement: d.SingleStatement} if stmtCacheSize > 0 { conn.stmtCache = make([]*SQLiteStmt, 0, stmtCacheSize) conn.stmtCacheEnabled = true @@ -2201,7 +2215,28 @@ func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, er return nil, c.lastError() } var t string - if tail != nil && *tail != '\000' { + if c.singleStatement { + // Check the rest of the string as SQLite reads it, and never prepare + // it once a statement has been prepared. + for { + var rest string + if tail != nil { + rest = query[uintptr(unsafe.Pointer(tail))-uintptr(unsafe.Pointer(pquery)):] + } + if onlySQLiteTrivia(rest) { + break + } + if s != nil { + C.sqlite3_finalize(s) + return nil, ErrMultipleStatements + } + // Only empty statements so far: the rest starts with the first one. + rv = C._sqlite3_prepare_v2_internal(c.db, tail, C.int(len(rest)), &s, &tail) + if rv != C.SQLITE_OK { + return nil, c.lastError() + } + } + } else if tail != nil && *tail != '\000' { t = strings.TrimSpace(C.GoString(tail)) } ss := &SQLiteStmt{c: c, s: s, t: t} diff --git a/sqlite3_single_statement.go b/sqlite3_single_statement.go new file mode 100644 index 00000000..2cbc7e12 --- /dev/null +++ b/sqlite3_single_statement.go @@ -0,0 +1,52 @@ +package sqlite3 + +import ( + "errors" + "strings" +) + +// ErrMultipleStatements is returned in single-statement mode, see +// SQLiteDriver.SingleStatement, for a query string that holds more than +// one SQL statement. +var ErrMultipleStatements = errors.New("sqlite3: more than one statement in the query") + +// onlySQLiteTrivia reports whether the tokenizer of the bundled SQLite, +// sqlite3GetToken in sqlite3-binding.c, finds nothing in s but whitespace, +// comments and semicolons, that is, no further statement. +func onlySQLiteTrivia(s string) bool { + for i := 0; i < len(s); { + switch c := s[i]; { + case c == 0: + // SQLite reads no further than a NUL. + return true + case c == ';': + i++ + case c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r': + // A space token starts with one of these, not '\v', and goes on + // over sqlite3Isspace, which includes '\v'. + for i++; i < len(s) && (s[i] == ' ' || s[i] >= '\t' && s[i] <= '\r'); i++ { + } + case strings.HasPrefix(s[i:], "--"): + // Up to a LF or the end. + j := strings.IndexAny(s[i:], "\n\x00") + if j < 0 { + return true + } + i += j + case strings.HasPrefix(s[i:], "/*") && i+2 < len(s) && s[i+2] != 0: + // Up to the first "*/" or the end; comments do not nest. A "/*" + // at the very end is a slash and a star, not a comment. + j := strings.Index(s[i+2:], "*/") + if n := strings.IndexByte(s[i+2:], 0); j < 0 || n >= 0 && n < j { + return true + } + i += 2 + j + 2 + case strings.HasPrefix(s[i:], "\xef\xbb\xbf"): + // A UTF-8 byte order mark is a space token. + i += 3 + default: + return false + } + } + return true +} diff --git a/sqlite3_single_statement_test.go b/sqlite3_single_statement_test.go new file mode 100644 index 00000000..17f344a2 --- /dev/null +++ b/sqlite3_single_statement_test.go @@ -0,0 +1,186 @@ +//go:build cgo + +package sqlite3 + +import ( + "context" + "database/sql" + "errors" + "testing" +) + +func init() { + sql.Register("sqlite3_single_statement", &SQLiteDriver{SingleStatement: true}) +} + +func openSingleStatement(t *testing.T, dsn string) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite3_single_statement", dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + // One connection, so that a PRAGMA would show on the next query. + db.SetMaxOpenConns(1) + if _, err := db.Exec("CREATE TABLE r (v); CREATE TABLE s (v)"); !errors.Is(err, ErrMultipleStatements) { + t.Fatalf("batch error = %v, want ErrMultipleStatements", err) + } + for _, q := range []string{"CREATE TABLE r (v)", "CREATE TABLE s (v)"} { + if _, err := db.Exec(q); err != nil { + t.Fatal(err) + } + } + return db +} + +// singleStatementCalls runs query, with args, through every way the driver +// executes a string, and returns their errors. +func singleStatementCalls(db *sql.DB, query string, args ...any) map[string]error { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + errs := map[string]error{} + _, errs["Exec"] = db.Exec(query, args...) + _, errs["ExecContext"] = db.ExecContext(ctx, query, args...) + for name, run := range map[string]func() (*sql.Rows, error){ + "Query": func() (*sql.Rows, error) { return db.Query(query, args...) }, + "QueryContext": func() (*sql.Rows, error) { return db.QueryContext(ctx, query, args...) }, + } { + rows, err := run() + if err == nil { + for rows.Next() { + } + err = rows.Err() + rows.Close() + } + errs[name] = err + } + for name, prepare := range map[string]func() (*sql.Stmt, error){ + "Prepare": func() (*sql.Stmt, error) { return db.Prepare(query) }, + "PrepareContext": func() (*sql.Stmt, error) { return db.PrepareContext(ctx, query) }, + } { + stmt, err := prepare() + if err == nil { + _, err = stmt.Exec(args...) + stmt.Close() + } + errs[name] = err + } + tx, err := db.BeginTx(ctx, nil) + if err == nil { + if _, err = tx.Exec(query, args...); err == nil { + err = tx.Commit() + } else { + tx.Rollback() + } + } + errs["Tx"] = err + return errs +} + +func TestSingleStatement(t *testing.T) { + for _, dsn := range []string{":memory:", ":memory:?_stmt_cache_size=8"} { + t.Run(dsn, func(t *testing.T) { + db := openSingleStatement(t, dsn) + count := func() (n int) { + t.Helper() + if err := db.QueryRow("SELECT count(*) FROM r").Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + + for _, q := range []struct { + query string + args []any + }{ + {"INSERT INTO r VALUES (1); INSERT INTO r VALUES (2)", nil}, + {"INSERT INTO r VALUES (?); INSERT INTO r VALUES (?)", []any{1, 2}}, + {"INSERT INTO r VALUES (1); x", nil}, + {"INSERT INTO r VALUES (1); /* outer /* inner */ SELECT 2; -- */", nil}, + {"INSERT INTO r VALUES (1); /*", nil}, + {"INSERT INTO r VALUES (1);\v", nil}, + {"CREATE TABLE d (v); SELECT 1", nil}, + {"; INSERT INTO r VALUES (1); SELECT 2", nil}, + } { + for call, err := range singleStatementCalls(db, q.query, q.args...) { + if !errors.Is(err, ErrMultipleStatements) { + t.Errorf("%s(%q): error = %v, want ErrMultipleStatements", call, q.query, err) + } + } + } + if n := count(); n != 0 { + t.Errorf("refused strings inserted %d rows", n) + } + var tables int + if err := db.QueryRow("SELECT count(*) FROM sqlite_schema WHERE name = 'd'").Scan(&tables); err != nil || tables != 0 { + t.Errorf("refused string created table d: %d, %v", tables, err) + } + + for _, query := range []string{ + "INSERT INTO r VALUES (?);", + "INSERT INTO r VALUES (?) ;; ", + "; /* c */ ; INSERT INTO r VALUES (?);", + "INSERT INTO r VALUES (?); --x", + "INSERT INTO r VALUES (?); /*x", + "INSERT INTO r VALUES (?); \v", + "INSERT INTO r VALUES (?);\xef\xbb\xbf", + } { + before := count() + for call, err := range singleStatementCalls(db, query, 1) { + if err != nil { + t.Errorf("%s(%q): %v", call, query, err) + } + } + // Exec, ExecContext, Prepare, PrepareContext and Tx insert; + // Query and QueryContext do too, as they step the INSERT. + if n := count() - before; n != 7 { + t.Errorf("%q inserted %d rows, want 7", query, n) + } + } + + before := count() + if _, err := db.Exec("CREATE TRIGGER tr AFTER INSERT ON s BEGIN INSERT INTO r VALUES (1); INSERT INTO r VALUES (2); END;"); err != nil { + t.Fatal(err) + } + if _, err := db.Exec("INSERT INTO s VALUES (1)"); err != nil { + t.Fatal(err) + } + if n := count() - before; n != 2 { + t.Errorf("the trigger inserted %d rows, want 2", n) + } + }) + } +} + +// TestSingleStatementTailNotPrepared checks that the rest of a refused +// string is not compiled: PRAGMA case_sensitive_like acts when it is +// prepared. +func TestSingleStatementTailNotPrepared(t *testing.T) { + db := openSingleStatement(t, ":memory:") + if _, err := db.Query("SELECT 1; PRAGMA case_sensitive_like=1"); !errors.Is(err, ErrMultipleStatements) { + t.Fatalf("error = %v, want ErrMultipleStatements", err) + } + var like bool + if err := db.QueryRow("SELECT 'a' LIKE 'A'").Scan(&like); err != nil { + t.Fatal(err) + } + if !like { + t.Error("LIKE became case sensitive") + } +} + +func TestSingleStatementOffRunsBatches(t *testing.T) { + db, err := sql.Open("sqlite3", ":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + db.SetMaxOpenConns(1) + if _, err := db.Exec("CREATE TABLE r (v); INSERT INTO r VALUES (1); INSERT INTO r VALUES (2)"); err != nil { + t.Fatal(err) + } + var n int + if err := db.QueryRow("SELECT count(*) FROM r").Scan(&n); err != nil || n != 2 { + t.Errorf("count = %d, %v, want 2", n, err) + } +} diff --git a/static_mock.go b/static_mock.go index 17248686..f5839201 100644 --- a/static_mock.go +++ b/static_mock.go @@ -21,8 +21,9 @@ func init() { type ( SQLiteDriver struct { - Extensions []string - ConnectHook func(*SQLiteConn) error + Extensions []string + ConnectHook func(*SQLiteConn) error + SingleStatement bool } SQLiteConn struct{} ) From bf2b3c95380b5fc88cb9a9efe50312852b23e9b0 Mon Sep 17 00:00:00 2001 From: Jin Xu Date: Sun, 8 Nov 2026 09:21:17 +0800 Subject: [PATCH 2/3] Check the rest once and scan block comments in linear time SQLite skips leading empty statements itself and stops after the first statement, so one check of the rest after the first prepare is enough; prepare no longer prepares the rest after an empty statement. The block comment scan searched the whole rest of the string for a NUL at every comment, which is quadratic in the number of comments. It now searches the comment only. The README no longer says nothing of a refused string runs: a first statement that acts when it is prepared still does. The tests check that Query and Prepare refuse the string themselves, and cover a line comment followed by a second statement, CR in a line comment, a semicolon in a string literal and a NUL. --- README.md | 2 +- sqlite3.go | 28 +++++++++------------------- sqlite3_single_statement.go | 2 +- sqlite3_single_statement_test.go | 12 ++++++++---- 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 1537adfc..85e0fb6b 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Without a current time, a column declared `NOT NULL DEFAULT CURRENT_TIMESTAMP` c - `sqlite3.go` defines the SQLCipher compile options, turns off the default logging of SQLCipher to stderr, and adds the `_crypto_key` DSN parameter. - `Exec` without arguments reports missing arguments again, which go-sqlite3 v1.14.52 does not. - `sqlite3_nocurrenttime.go` adds the `nocurrenttime` VFS, and `sqlite3_opt_omit_localtime.go` the `sqlite_omit_localtime` tag. -- `SQLiteDriver.SingleStatement` refuses a query string that holds more than one statement with `ErrMultipleStatements`, before any of it runs. +- `SQLiteDriver.SingleStatement` refuses a query string that holds more than one statement with `ErrMultipleStatements`, without stepping it or preparing its second statement. - `sqlite3_opt_icu.go` adds the libraries that a static link of ICU needs. - The CIFuzz workflow, which builds the OSS-Fuzz project of go-sqlite3, is removed. diff --git a/sqlite3.go b/sqlite3.go index 8c9ddee5..8ff8c373 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -2216,25 +2216,15 @@ func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, er } var t string if c.singleStatement { - // Check the rest of the string as SQLite reads it, and never prepare - // it once a statement has been prepared. - for { - var rest string - if tail != nil { - rest = query[uintptr(unsafe.Pointer(tail))-uintptr(unsafe.Pointer(pquery)):] - } - if onlySQLiteTrivia(rest) { - break - } - if s != nil { - C.sqlite3_finalize(s) - return nil, ErrMultipleStatements - } - // Only empty statements so far: the rest starts with the first one. - rv = C._sqlite3_prepare_v2_internal(c.db, tail, C.int(len(rest)), &s, &tail) - if rv != C.SQLITE_OK { - return nil, c.lastError() - } + // SQLite skips leading empty statements and stops after the first + // statement. Check the rest as SQLite reads it, without preparing it. + var rest string + if tail != nil { + rest = query[uintptr(unsafe.Pointer(tail))-uintptr(unsafe.Pointer(pquery)):] + } + if !onlySQLiteTrivia(rest) { + C.sqlite3_finalize(s) + return nil, ErrMultipleStatements } } else if tail != nil && *tail != '\000' { t = strings.TrimSpace(C.GoString(tail)) diff --git a/sqlite3_single_statement.go b/sqlite3_single_statement.go index 2cbc7e12..bc5d0463 100644 --- a/sqlite3_single_statement.go +++ b/sqlite3_single_statement.go @@ -37,7 +37,7 @@ func onlySQLiteTrivia(s string) bool { // Up to the first "*/" or the end; comments do not nest. A "/*" // at the very end is a slash and a star, not a comment. j := strings.Index(s[i+2:], "*/") - if n := strings.IndexByte(s[i+2:], 0); j < 0 || n >= 0 && n < j { + if j < 0 || strings.IndexByte(s[i+2:i+2+j], 0) >= 0 { return true } i += 2 + j + 2 diff --git a/sqlite3_single_statement_test.go b/sqlite3_single_statement_test.go index 17f344a2..0fc8cf85 100644 --- a/sqlite3_single_statement_test.go +++ b/sqlite3_single_statement_test.go @@ -46,24 +46,24 @@ func singleStatementCalls(db *sql.DB, query string, args ...any) map[string]erro "QueryContext": func() (*sql.Rows, error) { return db.QueryContext(ctx, query, args...) }, } { rows, err := run() + errs[name] = err if err == nil { for rows.Next() { } - err = rows.Err() + errs[name+" rows"] = rows.Err() rows.Close() } - errs[name] = err } for name, prepare := range map[string]func() (*sql.Stmt, error){ "Prepare": func() (*sql.Stmt, error) { return db.Prepare(query) }, "PrepareContext": func() (*sql.Stmt, error) { return db.PrepareContext(ctx, query) }, } { stmt, err := prepare() + errs[name] = err if err == nil { - _, err = stmt.Exec(args...) + _, errs[name+" Exec"] = stmt.Exec(args...) stmt.Close() } - errs[name] = err } tx, err := db.BeginTx(ctx, nil) if err == nil { @@ -97,6 +97,7 @@ func TestSingleStatement(t *testing.T) { {"INSERT INTO r VALUES (?); INSERT INTO r VALUES (?)", []any{1, 2}}, {"INSERT INTO r VALUES (1); x", nil}, {"INSERT INTO r VALUES (1); /* outer /* inner */ SELECT 2; -- */", nil}, + {"INSERT INTO r VALUES (1); --x\nSELECT 2", nil}, {"INSERT INTO r VALUES (1); /*", nil}, {"INSERT INTO r VALUES (1);\v", nil}, {"CREATE TABLE d (v); SELECT 1", nil}, @@ -124,6 +125,9 @@ func TestSingleStatement(t *testing.T) { "INSERT INTO r VALUES (?); /*x", "INSERT INTO r VALUES (?); \v", "INSERT INTO r VALUES (?);\xef\xbb\xbf", + "INSERT INTO r VALUES (?); --x\rSELECT 2", + "INSERT INTO r VALUES (? || '; SELECT 2');", + "INSERT INTO r VALUES (?);\x00SELECT 2", } { before := count() for call, err := range singleStatementCalls(db, query, 1) { From ca5f6aec29bcef1d978982cf75e19b1e52fa8db6 Mon Sep 17 00:00:00 2001 From: Jin Xu Date: Sun, 8 Nov 2026 09:48:07 +0800 Subject: [PATCH 3/3] Test accepted strings without arguments and with a cancelled context The accepted strings were only run with an argument, so Exec without arguments, which would otherwise take the C fast path, was not tested with them. Run each also without arguments. Cancel the context during and after a call, and check that nothing beyond the first statement ran. Note in the README that unkeyed SQLiteDriver literals must switch to field names, as the struct has a new field. --- README.md | 2 +- sqlite3_single_statement_test.go | 64 +++++++++++++++++++++++++++----- 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 85e0fb6b..14084000 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Without a current time, a column declared `NOT NULL DEFAULT CURRENT_TIMESTAMP` c - `sqlite3.go` defines the SQLCipher compile options, turns off the default logging of SQLCipher to stderr, and adds the `_crypto_key` DSN parameter. - `Exec` without arguments reports missing arguments again, which go-sqlite3 v1.14.52 does not. - `sqlite3_nocurrenttime.go` adds the `nocurrenttime` VFS, and `sqlite3_opt_omit_localtime.go` the `sqlite_omit_localtime` tag. -- `SQLiteDriver.SingleStatement` refuses a query string that holds more than one statement with `ErrMultipleStatements`, without stepping it or preparing its second statement. +- `SQLiteDriver.SingleStatement` refuses a query string that holds more than one statement with `ErrMultipleStatements`, without stepping it or preparing its second statement. Unkeyed `SQLiteDriver` literals, such as `SQLiteDriver{nil, nil}`, must switch to field names. - `sqlite3_opt_icu.go` adds the libraries that a static link of ICU needs. - The CIFuzz workflow, which builds the OSS-Fuzz project of go-sqlite3, is removed. diff --git a/sqlite3_single_statement_test.go b/sqlite3_single_statement_test.go index 0fc8cf85..b3dfa3aa 100644 --- a/sqlite3_single_statement_test.go +++ b/sqlite3_single_statement_test.go @@ -6,7 +6,9 @@ import ( "context" "database/sql" "errors" + "strings" "testing" + "time" ) func init() { @@ -129,16 +131,24 @@ func TestSingleStatement(t *testing.T) { "INSERT INTO r VALUES (? || '; SELECT 2');", "INSERT INTO r VALUES (?);\x00SELECT 2", } { - before := count() - for call, err := range singleStatementCalls(db, query, 1) { - if err != nil { - t.Errorf("%s(%q): %v", call, query, err) + for _, q := range []struct { + query string + args []any + }{ + {query, []any{1}}, + {strings.ReplaceAll(query, "?", "1"), nil}, + } { + before := count() + for call, err := range singleStatementCalls(db, q.query, q.args...) { + if err != nil { + t.Errorf("%s(%q): %v", call, q.query, err) + } + } + // Exec, ExecContext, Prepare, PrepareContext and Tx insert; + // Query and QueryContext do too, as they step the INSERT. + if n := count() - before; n != 7 { + t.Errorf("%q inserted %d rows, want 7", q.query, n) } - } - // Exec, ExecContext, Prepare, PrepareContext and Tx insert; - // Query and QueryContext do too, as they step the INSERT. - if n := count() - before; n != 7 { - t.Errorf("%q inserted %d rows, want 7", query, n) } } @@ -156,6 +166,42 @@ func TestSingleStatement(t *testing.T) { } } +// TestSingleStatementCancel cancels the context of a call during and after +// it, and checks that nothing beyond the first statement ran. +func TestSingleStatementCancel(t *testing.T) { + db := openSingleStatement(t, ":memory:") + counts := func() (r, s int) { + t.Helper() + if err := db.QueryRow("SELECT (SELECT count(*) FROM r), (SELECT count(*) FROM s)").Scan(&r, &s); err != nil { + t.Fatal(err) + } + return r, s + } + const slow = "INSERT INTO r WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT x FROM c LIMIT 100000000" + + for _, q := range []string{slow + "; INSERT INTO s VALUES (1)", slow + "; -- INSERT INTO s VALUES (1)"} { + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + _, err := db.ExecContext(ctx, q) + <-ctx.Done() + if err == nil { + t.Errorf("%q: no error", q) + } + if r, s := counts(); r != 0 || s != 0 { + t.Errorf("%q: r has %d rows and s %d, want none", q, r, s) + } + } + + ctx, cancel := context.WithCancel(context.Background()) + if _, err := db.ExecContext(ctx, "INSERT INTO r VALUES (1); -- INSERT INTO s VALUES (1)"); err != nil { + t.Fatal(err) + } + cancel() + if r, s := counts(); r != 1 || s != 0 { + t.Errorf("r has %d rows and s %d, want 1 and 0", r, s) + } +} + // TestSingleStatementTailNotPrepared checks that the rest of a refused // string is not compiled: PRAGMA case_sensitive_like acts when it is // prepared.