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', () => {