From eb919dff6844998d123c05e5cc7a4903ce1bec64 Mon Sep 17 00:00:00 2001 From: 0froq Date: Tue, 17 Nov 2026 14:08:25 +0800 Subject: [PATCH 1/3] fix(cli): print rows for every returning statement in `db execute` Local `void db execute` printed results only when the SQL started with `SELECT`, so `WITH`, `PRAGMA`, `EXPLAIN` and `RETURNING` succeeded silently. The remote D1, PostgreSQL and MySQL paths already print rows for any statement that returns them. Ask better-sqlite3 whether the prepared statement reads rows instead of matching the statement text, and leave a multi-statement script on `exec()`, which reports no rows. --- docs/reference/cli/database.md | 2 +- packages/void/src/cli/db.ts | 43 ++++++-- packages/void/src/migrations/runner.ts | 2 + packages/void/test/unit/db-commands.test.ts | 105 ++++++++++++++++++++ 4 files changed, 142 insertions(+), 10 deletions(-) diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 7357d978e..230fa046e 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -55,7 +55,7 @@ void db execute --file void db execute --remote ``` -Run ad-hoc SQL against the database. Provide SQL inline or from a file. SELECT queries display results as a formatted table; other statements execute silently. +Run ad-hoc SQL against the database. Provide SQL inline or from a file. A statement that returns rows prints them as a formatted table, and statements that change data print nothing. SQL with several statements runs as a script without printed results. By default, targets the local database. Pass `--remote` to run against the deployed database selected in `.void/project.json`: diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 5e406876c..60d71c753 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -823,8 +823,7 @@ async function runSeed( * in either form, because PostgreSQL executes the analyzed statement. */ function isSafeStatement(sql: string): boolean { - const decommented = sql.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/--[^\n]*/g, ' '); - const stripped = decommented.replace(/;\s*$/, ''); + const stripped = stripSqlDecoration(sql); if (stripped.includes(';')) { return false; } @@ -844,6 +843,22 @@ function isSafeStatement(sql: string): boolean { return false; } +/** Strip comments and a trailing semicolon so statement classification ignores decoration. */ +function stripSqlDecoration(sql: string): string { + return sql + .replace(/\/\*[\s\S]*?\*\//g, ' ') + .replace(/--[^\n]*/g, ' ') + .replace(/;\s*$/, ''); +} + +/** + * True when `sql` holds more than one statement. This reads a semicolon inside a literal as a + * second statement, which only costs a script-style run. + */ +function hasMultipleStatements(sql: string): boolean { + return stripSqlDecoration(sql).includes(';'); +} + /** * Fetch a project's remote PostgreSQL connection string from the platform. * Exits with a friendly message when the URL has never been stored (404); @@ -1092,15 +1107,25 @@ async function runExecute( const db = await openSqliteDatabase(dbPath); try { - const trimmed = sql.trimStart(); - if (/^SELECT\b/i.test(trimmed)) { - const rows = db.prepare(sql).all() as Array>; - if (rows.length === 0) { - log.info('No rows returned.'); + try { + const statement = db.prepare(sql); + // `reader` is the statement's own answer to "returns rows": SELECT, WITH ... SELECT, + // PRAGMA reads, EXPLAIN and RETURNING. Writes and DDL run silently, like every other + // target. + if (statement.reader) { + const rows = statement.all() as Array>; + if (rows.length > 0) { + printTable(rows); + } } else { - printTable(rows); + statement.run(); + } + } catch (error) { + // prepare() takes one statement at a time and exec() reports nothing back, so a + // script runs without printed results. + if (!hasMultipleStatements(sql)) { + throw error; } - } else { db.exec(sql); } } finally { diff --git a/packages/void/src/migrations/runner.ts b/packages/void/src/migrations/runner.ts index 1e7466702..94bdda09f 100644 --- a/packages/void/src/migrations/runner.ts +++ b/packages/void/src/migrations/runner.ts @@ -6,6 +6,8 @@ import { collectMigrations } from './collect.ts'; import { classifyMigration } from './plan.ts'; type SqliteStatement = { + /** True when the statement returns rows (SELECT, PRAGMA reads, EXPLAIN, RETURNING). */ + readonly reader: boolean; get(...params: Array): T | undefined; all(...params: Array): Array; run(...params: Array): unknown; diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index 65a83a4d8..e4f084dba 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -583,6 +583,24 @@ describe('void db export', () => { }); }); +/** A project whose local D1 database is a real SQLite file, opened by the unmocked runner. */ +async function createLocalSqliteProject(): Promise { + const root = mkdtempSync(join(tmpdir(), 'void-execute-sqlite-')); + rootsToClean.push(root); + writeFileSync(join(root, 'void.json'), JSON.stringify({})); + const dbPath = join(root, '.void', 'local.sqlite'); + mkdirSync(join(root, '.void'), { recursive: true }); + mockGetMiniflareDatabasePath.mockReturnValue(dbPath); + const { openSqliteDatabase } = await import('../../src/migrations/runner.ts'); + const db = await openSqliteDatabase(dbPath); + try { + db.exec('CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)'); + } finally { + db.close(); + } + return root; +} + describe('void db execute', () => { let runDbCommand: typeof import('../../src/cli/db.ts').runDbCommand; @@ -594,11 +612,22 @@ describe('void db execute', () => { afterEach(() => { vi.restoreAllMocks(); + mockGetMiniflareDatabasePath.mockReset(); + mockOpenSqliteDatabase.mockReset(); for (const root of rootsToClean.splice(0, rootsToClean.length)) { rmSync(root, { recursive: true, force: true }); } }); + // `runDbCommand` opens with a blank line, so only non-empty calls carry a table. + function tableOutput(): string { + return vi + .mocked(console.log) + .mock.calls.map((call) => String(call[0] ?? '')) + .filter((line) => line.length > 0) + .join('\n'); + } + it('reads an absolute --file path as given', async () => { const root = mkdtempSync(join(tmpdir(), 'void-execute-abs-')); const elsewhere = mkdtempSync(join(tmpdir(), 'void-execute-sql-')); @@ -625,6 +654,82 @@ describe('void db execute', () => { expect(mockPgQuery).toHaveBeenCalledWith('UPDATE users SET id = id;'); }); + + it('SQLite: prints rows for any single statement that returns them', async () => { + const root = await createLocalSqliteProject(); + const reads: Array<[string, RegExp]> = [ + ['-- leading comment\nSELECT 1 AS value', /value/], + ['WITH example AS (SELECT 1 AS value) SELECT value FROM example', /value/], + ['PRAGMA database_list', /main/], + ['EXPLAIN QUERY PLAN SELECT 1', /SCAN|CONSTANT ROW/i], + ["INSERT INTO items (name) VALUES ('first') RETURNING id, name", /first/], + ]; + + for (const [sql, pattern] of reads) { + vi.mocked(console.log).mockClear(); + await runDbCommand(root, { action: 'execute', command: sql }); + expect(tableOutput(), sql).toMatch(pattern); + } + }); + + it('SQLite: keeps a single statement whose literal holds a semicolon', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { action: 'execute', command: "SELECT 'a;b' AS value" }); + + expect(tableOutput()).toMatch(/a;b/); + }); + + it('SQLite: runs a trigger whose body holds semicolons', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: + 'CREATE TRIGGER items_touch AFTER INSERT ON items BEGIN UPDATE items SET name = name WHERE id = new.id; END;', + }); + + expect(tableOutput()).toBe(''); + await runDbCommand(root, { + action: 'execute', + command: "SELECT name FROM sqlite_master WHERE type = 'trigger'", + }); + expect(tableOutput()).toMatch(/items_touch/); + }); + + it('SQLite: prints no table for writes, DDL and empty results', async () => { + const root = await createLocalSqliteProject(); + + for (const sql of [ + "INSERT INTO items (name) VALUES ('second')", + 'CREATE TABLE extra (id INTEGER)', + 'SELECT * FROM items WHERE id < 0', + ]) { + vi.mocked(console.log).mockClear(); + mockLog.info.mockClear(); + await runDbCommand(root, { action: 'execute', command: sql }); + expect(tableOutput(), sql).toBe(''); + expect(mockLog.info, sql).not.toHaveBeenCalled(); + } + }); + + it('SQLite: runs a multi-statement script without printing results', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: "INSERT INTO items (name) VALUES ('script'); SELECT name FROM items;", + }); + + expect(tableOutput()).toBe(''); + const { openSqliteDatabase } = await import('../../src/migrations/runner.ts'); + const db = await openSqliteDatabase(join(root, '.void', 'local.sqlite')); + try { + expect(db.prepare('SELECT name FROM items ORDER BY id').all()).toEqual([{ name: 'script' }]); + } finally { + db.close(); + } + }); }); describe('void db status', () => { From f2ff6f8a8d353c50878d7b7b6f094b0d930499b3 Mon Sep 17 00:00:00 2001 From: 0froq Date: Tue, 17 Nov 2026 21:24:43 +0800 Subject: [PATCH 2/3] fix(cli): decide scripts from the prepare result Telling a script from a single statement by scanning the SQL text replayed a partially applied write, because the catch also wrapped execution, and missed statement separators behind literals such as '--' or '/*'. Ask better-sqlite3 instead: it refuses SQL that holds no statement or more than one with a RangeError before running anything, so only that refusal falls back to exec(). --- packages/void/src/cli/db.ts | 58 ++++++++--------- packages/void/src/migrations/runner.ts | 4 +- packages/void/test/unit/db-commands.test.ts | 70 +++++++++++++++++++++ 3 files changed, 101 insertions(+), 31 deletions(-) diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 60d71c753..1c6165a55 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -30,6 +30,7 @@ import { writeJournal, } from '../migrations/collect.ts'; import type { MySqlClient } from '../migrations/runner-mysql.ts'; +import type { SqliteDatabase, SqliteStatement } from '../migrations/runner.ts'; import { assertJournalCoherence, validateMigrations } from '../migrations/validate.ts'; import { detectFramework } from '../plugin-inference.ts'; import { readProjectPaths } from '../project-paths.ts'; @@ -823,7 +824,8 @@ async function runSeed( * in either form, because PostgreSQL executes the analyzed statement. */ function isSafeStatement(sql: string): boolean { - const stripped = stripSqlDecoration(sql); + const decommented = sql.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/--[^\n]*/g, ' '); + const stripped = decommented.replace(/;\s*$/, ''); if (stripped.includes(';')) { return false; } @@ -843,20 +845,25 @@ function isSafeStatement(sql: string): boolean { return false; } -/** Strip comments and a trailing semicolon so statement classification ignores decoration. */ -function stripSqlDecoration(sql: string): string { - return sql - .replace(/\/\*[\s\S]*?\*\//g, ' ') - .replace(/--[^\n]*/g, ' ') - .replace(/;\s*$/, ''); -} - /** - * True when `sql` holds more than one statement. This reads a semicolon inside a literal as a - * second statement, which only costs a script-style run. + * Prepare one statement. better-sqlite3 refuses SQL that holds no statement or more than one + * with a `RangeError`, before it runs anything (`src/objects/statement.cpp`). Those are the + * only errors this call can raise that way, so the caller runs the same text through + * `exec()`, which handles a script and reports no rows. Execution errors never come back + * here, so nothing is replayed. */ -function hasMultipleStatements(sql: string): boolean { - return stripSqlDecoration(sql).includes(';'); +function prepareSingleStatement( + db: SqliteDatabase, + sql: string, +): SqliteStatement> | undefined { + try { + return db.prepare>(sql); + } catch (error) { + if (error instanceof RangeError) { + return undefined; + } + throw error; + } } /** @@ -1107,26 +1114,19 @@ async function runExecute( const db = await openSqliteDatabase(dbPath); try { - try { - const statement = db.prepare(sql); + const statement = prepareSingleStatement(db, sql); + if (!statement) { + db.exec(sql); + } else if (statement.reader) { // `reader` is the statement's own answer to "returns rows": SELECT, WITH ... SELECT, // PRAGMA reads, EXPLAIN and RETURNING. Writes and DDL run silently, like every other // target. - if (statement.reader) { - const rows = statement.all() as Array>; - if (rows.length > 0) { - printTable(rows); - } - } else { - statement.run(); - } - } catch (error) { - // prepare() takes one statement at a time and exec() reports nothing back, so a - // script runs without printed results. - if (!hasMultipleStatements(sql)) { - throw error; + const rows = statement.all(); + if (rows.length > 0) { + printTable(rows); } - db.exec(sql); + } else { + statement.run(); } } finally { db.close(); diff --git a/packages/void/src/migrations/runner.ts b/packages/void/src/migrations/runner.ts index 94bdda09f..2b469e6ee 100644 --- a/packages/void/src/migrations/runner.ts +++ b/packages/void/src/migrations/runner.ts @@ -5,7 +5,7 @@ import { hasPackageDependency, readNearestPackageJson } from '../shared/package- import { collectMigrations } from './collect.ts'; import { classifyMigration } from './plan.ts'; -type SqliteStatement = { +export type SqliteStatement = { /** True when the statement returns rows (SELECT, PRAGMA reads, EXPLAIN, RETURNING). */ readonly reader: boolean; get(...params: Array): T | undefined; @@ -18,7 +18,7 @@ type SqliteTransaction = { immediate(): T; }; -type SqliteDatabase = { +export type SqliteDatabase = { prepare(sql: string): SqliteStatement; exec(sql: string): void; close(): void; diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index e4f084dba..617c2333d 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -697,6 +697,76 @@ describe('void db execute', () => { expect(tableOutput()).toMatch(/items_touch/); }); + it('SQLite: runs a script whose literals hold comment markers', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: + "INSERT INTO items (name) VALUES ('--');\nINSERT INTO items (name) VALUES ('plain--');", + }); + await runDbCommand(root, { + action: 'execute', + command: "INSERT INTO items (name) VALUES ('/*');\nINSERT INTO items (name) VALUES ('*/');", + }); + + expect(tableOutput()).toBe(''); + await runDbCommand(root, { action: 'execute', command: 'SELECT name FROM items ORDER BY id' }); + expect(tableOutput()).toContain('plain--'); + expect(tableOutput()).toContain('/*'); + const { openSqliteDatabase } = await import('../../src/migrations/runner.ts'); + const db = await openSqliteDatabase(join(root, '.void', 'local.sqlite')); + try { + const rows = db.prepare('SELECT name FROM items ORDER BY id').all() as Array<{ + name: string; + }>; + expect(rows.map((row) => row.name)).toEqual(['--', 'plain--', '/*', '*/']); + } finally { + db.close(); + } + }); + + it('SQLite: a failing single statement runs once', async () => { + const root = await createLocalSqliteProject(); + await runDbCommand(root, { + action: 'execute', + command: 'CREATE TABLE counters (id INTEGER PRIMARY KEY, hits INTEGER, label TEXT UNIQUE)', + }); + await runDbCommand(root, { + action: 'execute', + command: "INSERT INTO counters (id, hits, label) VALUES (1, 0, 'one'), (2, 0, 'two')", + }); + + await expect( + runDbCommand(root, { + action: 'execute', + command: "UPDATE OR FAIL counters SET hits = hits + 1, label = 'done;x' WHERE id IN (1, 2)", + }), + ).rejects.toThrow(/UNIQUE constraint failed/); + + const { openSqliteDatabase } = await import('../../src/migrations/runner.ts'); + const db = await openSqliteDatabase(join(root, '.void', 'local.sqlite')); + try { + const rows = db.prepare('SELECT id, hits, label FROM counters ORDER BY id').all(); + // FAIL keeps the row it already updated, and the failed statement is not replayed. + expect(rows).toEqual([ + { id: 1, hits: 1, label: 'done;x' }, + { id: 2, hits: 0, label: 'two' }, + ]); + } finally { + db.close(); + } + }); + + it('SQLite: SQL without a statement is a no-op', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { action: 'execute', command: '-- nothing to run' }); + + expect(tableOutput()).toBe(''); + expect(mockLog.error).not.toHaveBeenCalled(); + }); + it('SQLite: prints no table for writes, DDL and empty results', async () => { const root = await createLocalSqliteProject(); From 16a8814f2f7cda6d9ebea31a4eac93d3d4c23f40 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Wed, 18 Nov 2026 09:28:15 +0900 Subject: [PATCH 3/3] Run local SQLite statements to completion. --- packages/void/src/cli/db.ts | 6 ++---- packages/void/test/unit/db-commands.test.ts | 24 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 1c6165a55..f33c50a7f 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -1115,9 +1115,7 @@ async function runExecute( const db = await openSqliteDatabase(dbPath); try { const statement = prepareSingleStatement(db, sql); - if (!statement) { - db.exec(sql); - } else if (statement.reader) { + if (statement?.reader) { // `reader` is the statement's own answer to "returns rows": SELECT, WITH ... SELECT, // PRAGMA reads, EXPLAIN and RETURNING. Writes and DDL run silently, like every other // target. @@ -1126,7 +1124,7 @@ async function runExecute( printTable(rows); } } else { - statement.run(); + db.exec(sql); } } finally { db.close(); diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index 617c2333d..29e0a2852 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -758,6 +758,30 @@ describe('void db execute', () => { } }); + it('SQLite: incremental vacuum reclaims the requested number of pages', async () => { + const root = await createLocalSqliteProject(); + const { openSqliteDatabase } = await import('../../src/migrations/runner.ts'); + const db = await openSqliteDatabase(join(root, '.void', 'local.sqlite')); + try { + db.exec(` + PRAGMA page_size = 4096; + PRAGMA auto_vacuum = INCREMENTAL; + VACUUM; + INSERT INTO items (name) VALUES (zeroblob(262144)); + DELETE FROM items; + `); + const freelist = db.prepare<{ freelist_count: number }>('PRAGMA freelist_count'); + const before = freelist.get()!.freelist_count; + expect(before).toBeGreaterThanOrEqual(20); + + await runDbCommand(root, { action: 'execute', command: 'PRAGMA incremental_vacuum(20)' }); + + expect(freelist.get()!.freelist_count).toBe(before - 20); + } finally { + db.close(); + } + }); + it('SQLite: SQL without a statement is a no-op', async () => { const root = await createLocalSqliteProject();