Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/cli/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ void db execute --file <path>
void db execute --remote <sql>
```

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`:

Expand Down
43 changes: 34 additions & 9 deletions packages/void/src/cli/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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);
Expand Down Expand Up @@ -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<Record<string, unknown>>;
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<Record<string, unknown>>;
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 {
Expand Down
2 changes: 2 additions & 0 deletions packages/void/src/migrations/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { collectMigrations } from './collect.ts';
import { classifyMigration } from './plan.ts';

type SqliteStatement<T = unknown> = {
/** True when the statement returns rows (SELECT, PRAGMA reads, EXPLAIN, RETURNING). */
readonly reader: boolean;
get(...params: Array<unknown>): T | undefined;
all(...params: Array<unknown>): Array<T>;
run(...params: Array<unknown>): unknown;
Expand Down
105 changes: 105 additions & 0 deletions packages/void/test/unit/db-commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
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;

Expand All @@ -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-'));
Expand All @@ -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', () => {
Expand Down
Loading