From d516c06ed128135ec00b4956d120b6357f0f28e0 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 13:51:06 +0530 Subject: [PATCH 01/11] feat(cli): add `--json` to `void db execute` `void db execute --json` writes a JSON array with one D1-shaped `{ results, success, meta }` entry per statement to stdout, matching `wrangler d1 execute --json`. Prompts, warnings and errors go to stderr, and the success line is left out. - Local SQLite runs the SQL statement by statement. The shared SQL tokenizer cuts at top-level semicolons, and a piece SQLite reports as incomplete input (a trigger body) continues into the next one. - Direct Cloudflare D1 keeps each statement's result instead of merging their rows. - PostgreSQL and MySQL read each statement's result from the driver. - A direct D1 import (a file over 100 KB) and several statements through the Void platform proxy are refused before anything runs, since neither can return every statement's rows. Table output without `--json` is unchanged. Fixes #912 Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 43 ++++- packages/void/src/cli/cli-main.ts | 3 +- .../void/src/cli/cloudflare-operations.ts | 36 ++-- packages/void/src/cli/db-args.ts | 22 ++- packages/void/src/cli/db-execute-results.ts | 162 ++++++++++++++++ packages/void/src/cli/db.ts | 181 ++++++++++++------ packages/void/src/cli/help.ts | 8 + .../test/unit/cloudflare-operations.test.ts | 28 +++ packages/void/test/unit/db-args.test.ts | 16 ++ packages/void/test/unit/db-commands.test.ts | 148 ++++++++++++++ .../void/test/unit/db-execute-remote.test.ts | 142 ++++++++++++++ .../void/test/unit/db-execute-results.test.ts | 63 ++++++ 12 files changed, 768 insertions(+), 84 deletions(-) create mode 100644 packages/void/src/cli/db-execute-results.ts create mode 100644 packages/void/test/unit/db-execute-results.test.ts diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 53535aced..625bb10d0 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -50,13 +50,13 @@ Programmatic seed modules must export either a default function or a named `seed ## `void db execute` {#void-db-execute} ``` -void db execute -void db execute --file -void db execute --remote [--yes] -void db execute --remote --file [--yes] +void db execute [--json] +void db execute --file [--json] +void db execute --remote [--yes] [--json] +void db execute --remote --file [--yes] [--json] ``` -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. +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. Pass `--json` to get every statement's rows. By default, targets the local database. Pass `--remote` to run against the deployed database selected in `.void/project.json`: @@ -69,6 +69,39 @@ On direct Cloudflare D1 deployments, a `--file` larger than 100 KB runs as a D1 For destructive statements (`DELETE`, `UPDATE`, `DROP`, etc.) when running in a TTY, you will be prompted to confirm before the query is sent to the deployed database. A TTY also asks before a D1 import, whatever the file contains. Pass `--yes` to skip the prompt. Non-TTY environments (CI) never prompt, so `--yes` is optional there. +### JSON output {#void-db-execute-json} + +Pass `--json` to read results from a script. stdout receives only a JSON array with one entry per statement, including statements in SQL with several statements. Prompts, warnings and errors go to stderr, and a failure exits with a non-zero status. + +```sh +void db execute --json "select count(*) as total from users; select id from users limit 1" +``` + +```json +[ + { + "results": [{ "total": 2 }], + "success": true, + "meta": { "changes": 0, "last_row_id": 0, "duration": 0.04 } + }, + { + "results": [{ "id": 1 }], + "success": true, + "meta": { "changes": 0, "last_row_id": 0, "duration": 0.02 } + } +] +``` + +Each entry has the same shape as a D1 result and as an entry of `wrangler d1 execute --json`: + +- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. +- `success`: `true` for a statement that ran. +- `meta`: what the database reports about the statement. D1 databases report D1's metadata, such as `changes` and `last_row_id` (locally `changes`, `last_row_id` and `duration`). PostgreSQL reports `command` and `rowCount`, and MySQL reports `affectedRows` and `insertId` for a statement that changes data. + +If a statement fails, stdout stays empty. + +`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command. + ## `void db migrate` {#void-db-migrate} ``` diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index bd08dbc28..366c3fa79 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -105,7 +105,8 @@ async function runSubcommandGroup( : platformMessage, ); } else { - log.error(message); + // A command printing JSON keeps stdout for its result. + log.error(message, args.includes('--json') ? { output: process.stderr } : undefined); } process.exit(1); } diff --git a/packages/void/src/cli/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index b879cf826..d4b120275 100644 --- a/packages/void/src/cli/cloudflare-operations.ts +++ b/packages/void/src/cli/cloudflare-operations.ts @@ -16,6 +16,7 @@ import type { CloudflareVersionMetadata } from '@void/deploy-cloudflare'; import { join } from 'pathslash'; import { materializeCloudflareConfig, persistCloudflareConfig } from '../cloudflare-config.ts'; import { createCloudflareProcessRunner } from './cloudflare-process.ts'; +import type { StatementResult } from './db-execute-results.ts'; import { findAmbientConfigOverride, findWranglerCiOverrideDotenvFile } from './deploy-transport.ts'; import { Buffer } from './node-buffer.ts'; import { getErrorMessage } from './output.ts'; @@ -239,10 +240,19 @@ export async function importCloudflareD1Sql( ); } +/** Every row the SQL returned, with the rows of all its statements in one list. */ export async function executeCloudflareD1Sql( context: CloudflareD1Context, sql: string, ): Promise>> { + return (await executeCloudflareD1Statements(context, sql)).flatMap((result) => result.results); +} + +/** D1's result for each statement in the SQL, in order. */ +export async function executeCloudflareD1Statements( + context: CloudflareD1Context, + sql: string, +): Promise> { const execute = (source: { sql: string } | { file: string }) => run(context.operation, { type: 'd1.execute', @@ -259,22 +269,22 @@ export async function executeCloudflareD1Sql( if (!Array.isArray(parsed)) { throw new Error('Cloudflare D1 execute returned an unexpected response.'); } - const rows: Array> = []; - for (const item of parsed) { + return parsed.map((item) => { if (typeof item !== 'object' || item === null) { throw new Error('Cloudflare D1 execute returned a malformed result.'); } - const resultRows = (item as Record).results; - if (!Array.isArray(resultRows)) { - continue; - } - for (const row of resultRows) { - if (typeof row === 'object' && row !== null && !Array.isArray(row)) { - rows.push(row as Record); - } - } - } - return rows; + const { results, success, meta } = item as Record; + return { + results: Array.isArray(results) + ? results.filter( + (row): row is Record => + typeof row === 'object' && row !== null && !Array.isArray(row), + ) + : [], + success: success !== false, + meta: typeof meta === 'object' && meta !== null ? (meta as Record) : {}, + }; + }); } export async function readCloudflareD1Migrations( diff --git a/packages/void/src/cli/db-args.ts b/packages/void/src/cli/db-args.ts index 5fb1cdaaf..775ab77c1 100644 --- a/packages/void/src/cli/db-args.ts +++ b/packages/void/src/cli/db-args.ts @@ -19,6 +19,7 @@ export const dbSubcommands: Array = [ flags: [ { name: '--remote', description: 'Run against the deployed database' }, { name: '--yes', description: 'Skip the confirmation prompt' }, + { name: '--json', description: "Print each statement's results as JSON" }, ], }, { @@ -85,7 +86,14 @@ export type DbArgs = | { action: 'status' } | { action: 'reset'; yes?: boolean } | { action: 'seed'; file?: string; yes?: boolean } - | { action: 'execute'; command?: string; file?: string; remote?: boolean; yes?: boolean } + | { + action: 'execute'; + command?: string; + file?: string; + remote?: boolean; + yes?: boolean; + json?: boolean; + } | { action: 'migrate'; remote?: boolean } | { action: 'studio'; remote?: boolean } | { @@ -137,7 +145,7 @@ const ACTION_FLAGS: Record> = { status: [], reset: ['yes'], seed: ['file', 'yes'], - execute: ['file', 'remote', 'yes'], + execute: ['file', 'remote', 'yes', 'json'], migrate: ['remote'], studio: ['remote'], 'set-url': [], @@ -197,6 +205,7 @@ export function parseDbArgs(args: Array): DbArgs { region: { type: 'string' }, 'local-only': { type: 'boolean' }, yes: { type: 'boolean' }, + json: { type: 'boolean' }, bookmark: { type: 'string' }, timestamp: { type: 'string' }, platform: { type: 'string' }, @@ -238,7 +247,14 @@ export function parseDbArgs(args: Array): DbArgs { if (command && values.file) { throw new Error('db: Provide either SQL inline or --file, not both.'); } - return { action, command, file: values.file, remote: values.remote, yes: values.yes }; + return { + action, + command, + file: values.file, + remote: values.remote, + yes: values.yes, + json: values.json, + }; } case 'migrate': case 'studio': diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts new file mode 100644 index 000000000..309dd3367 --- /dev/null +++ b/packages/void/src/cli/db-execute-results.ts @@ -0,0 +1,162 @@ +import { tokenizeSql } from '@void/deploy-core'; +import type { SqliteDatabase } from '../migrations/runner.ts'; + +/** + * One statement's outcome for `void db execute --json`. The shape follows D1's result + * objects, which `wrangler d1 execute --json` also prints, so a script can read either tool. + */ +export type StatementResult = { + results: Array>; + success: boolean; + meta: Record; +}; + +/** Serialize results for stdout. Binary values print as byte arrays, the way D1 returns BLOBs. */ +export function formatStatementResults(results: Array): string { + return JSON.stringify( + results.map((result) => ({ + ...result, + results: result.results.map((row) => + Object.fromEntries( + Object.entries(row).map(([column, value]) => [ + column, + value instanceof Uint8Array ? Array.from(value) : value, + ]), + ), + ), + })), + null, + 2, + ); +} + +/** + * Cut SQL after each `;` outside literals and comments. A trigger's `BEGIN ... END` body holds + * semicolons of its own, so a piece can end inside a statement; the caller joins pieces until + * SQLite accepts them. + */ +function* sqlPieces(sql: string): Generator { + let start = 0; + for (const segment of tokenizeSql(sql)) { + if (segment.kind !== 'sql') { + continue; + } + for (let index = segment.start; index < segment.end; index++) { + if (sql[index] === ';') { + yield sql.slice(start, index + 1); + start = index + 1; + } + } + } + yield sql.slice(start); +} + +function isIncompleteInput(error: unknown): boolean { + return error instanceof Error && error.message === 'incomplete input'; +} + +/** + * Run SQL statement by statement and keep each one's rows. Like `exec()`, every statement + * commits on its own unless the SQL opens a transaction, and a failing statement stops the run + * after the ones before it took effect. + * + * SQLite decides where a statement ends: a piece it reports as incomplete input continues + * into the next one. better-sqlite3 refuses SQL without a statement (whitespace or comments + * only) with a `RangeError`, and that piece is skipped. + */ +export function runSqliteStatements(db: SqliteDatabase, sql: string): Array { + const counters = db.prepare<{ changes: number; last_row_id: number; total: number }>( + 'SELECT changes() AS changes, last_insert_rowid() AS last_row_id, total_changes() AS total', + ); + // A scalar SELECT always returns one row. + const readCounters = () => counters.get() ?? { changes: 0, last_row_id: 0, total: 0 }; + const results: Array = []; + let pending = ''; + for (const piece of sqlPieces(sql)) { + pending += piece; + let statement; + try { + statement = db.prepare>(pending); + } catch (error) { + if (isIncompleteInput(error)) { + continue; + } + if (error instanceof RangeError) { + pending = ''; + continue; + } + throw error; + } + pending = ''; + const before = readCounters().total; + const started = performance.now(); + let rows: Array> = []; + if (statement.reader) { + rows = statement.all(); + } else { + statement.run(); + } + const duration = performance.now() - started; + const after = readCounters(); + results.push({ + results: rows, + success: true, + meta: { + // `changes()` keeps the last write's count, so a statement that wrote nothing reports 0. + changes: after.total === before ? 0 : after.changes, + last_row_id: after.last_row_id, + duration, + }, + }); + } + if (pending.trim()) { + // SQL that ends inside a statement: let SQLite report the incomplete input. + db.prepare(pending); + } + return results; +} + +type PgResult = { + command?: string | null; + rowCount?: number | null; + rows?: Array>; +}; + +/** node-postgres returns one result for one statement and an array for several. */ +export function pgStatementResults(result: PgResult | Array): Array { + return (Array.isArray(result) ? result : [result]).map((item) => ({ + results: item.rows ?? [], + success: true, + meta: { command: item.command ?? null, rowCount: item.rowCount ?? null }, + })); +} + +function mySqlStatementResult(value: unknown): StatementResult { + if (Array.isArray(value)) { + return { results: value as Array>, success: true, meta: {} }; + } + const header = (typeof value === 'object' && value !== null ? value : {}) as Record< + string, + unknown + >; + return { + results: [], + success: true, + meta: { affectedRows: header.affectedRows ?? 0, insertId: header.insertId ?? 0 }, + }; +} + +/** + * mysql2 returns `[rows, fields]`. With several statements, `rows` holds one entry per + * statement (rows, or a result header for a write), and `fields` holds each statement's + * column list, or `undefined` for a write. One statement's `fields` lists column objects. + */ +export function mySqlStatementResults(rows: unknown, fields: unknown): Array { + const severalStatements = + Array.isArray(rows) && + Array.isArray(fields) && + fields.some((entry) => entry === undefined || Array.isArray(entry)); + return severalStatements + ? (rows as Array).map(mySqlStatementResult) + : [mySqlStatementResult(rows)]; +} diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 89f43d566..60911db32 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -9,10 +9,13 @@ import { writeFileSync, } from 'node:fs'; import { createRequire } from 'node:module'; +import type { Writable } from 'node:stream'; import { pathToFileURL } from 'node:url'; +import { isSingleStatement } from '@void/deploy-core'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createJiti } from 'jiti'; import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; +import type { QueryResult } from 'pg'; import { readConfig, getDatabaseCasing, @@ -45,6 +48,13 @@ import { } from './cf-access.ts'; import { PlatformApiError, PlatformClient } from './client.ts'; import type { DbArgs } from './db-args.ts'; +import { + formatStatementResults, + mySqlStatementResults, + pgStatementResults, + runSqliteStatements, +} from './db-execute-results.ts'; +import type { StatementResult } from './db-execute-results.ts'; import { assertPgExportableSchema, exportPgConstraints, @@ -187,8 +197,8 @@ function validatePendingMigrations( } export async function runDbCommand(root: string, args: DbArgs): Promise { - // Keep raw SQL exports clean for piping into other tools. - if (!(args.action === 'export' && !args.output)) { + // Keep raw SQL exports and JSON results clean for piping into other tools. + if (!(args.action === 'export' && !args.output) && !(args.action === 'execute' && args.json)) { console.log(); } @@ -205,7 +215,7 @@ export async function runDbCommand(root: string, args: DbArgs): Promise { } else if (args.action === 'seed') { await runSeed(root, args.file, dialect, args.yes); } else if (args.action === 'execute') { - await runExecute(root, args.command, args.file, dialect, args.remote, args.yes); + await runExecute(root, args, dialect); } else if (args.action === 'migrate') { await runMigrate(root, dialect, args.remote); } else if (args.action === 'studio') { @@ -877,7 +887,11 @@ function prepareSingleStatement( * Exits with a friendly message when the URL has never been stored (404); * other errors propagate so the caller's top-level handler can report them. */ -async function fetchRemoteDatabaseUrl(client: PlatformClient, projectId: string): Promise { +async function fetchRemoteDatabaseUrl( + client: PlatformClient, + projectId: string, + messages: { output?: Writable } = {}, +): Promise { try { const result = await client.getDatabaseUrl(projectId); return result.url; @@ -885,6 +899,7 @@ async function fetchRemoteDatabaseUrl(client: PlatformClient, projectId: string) if (err instanceof PlatformApiError && err.status === 404) { log.error( "This project's database URL isn't stored on the platform yet. Run `void db set-url` once to populate it, then retry.", + messages, ); process.exit(1); } @@ -892,18 +907,28 @@ async function fetchRemoteDatabaseUrl(client: PlatformClient, projectId: string) } } -async function executeExternalRemoteSql( +/** + * Run SQL on a PostgreSQL or MySQL database. Both drivers return one result per statement, so + * `--json` prints every statement; the table prints only a single statement's rows. + */ +async function executeExternalSql( dialect: Exclude, dbUrl: string, sql: string, + json: boolean, ): Promise { if (dialect === 'postgresql') { const { Client } = await import('pg'); const pgClient = new Client({ connectionString: dbUrl }); await pgClient.connect(); try { - const result = await pgClient.query>(sql); - if (result.rows && result.rows.length > 0) { + // node-postgres resolves to an array of results when the SQL holds several statements. + const result: + | QueryResult> + | Array>> = await pgClient.query(sql); + if (json) { + printStatementResults(pgStatementResults(result)); + } else if (!Array.isArray(result) && result.rows.length > 0) { printTable(result.rows); } } finally { @@ -914,8 +939,10 @@ async function executeExternalRemoteSql( const { createConnection } = await import('mysql2/promise'); const mySqlClient = await createConnection({ uri: dbUrl, multipleStatements: true }); try { - const [rows] = await mySqlClient.query(sql); - if (Array.isArray(rows) && rows.length > 0) { + const [rows, fields] = await mySqlClient.query(sql); + if (json) { + printStatementResults(mySqlStatementResults(rows, fields)); + } else if (Array.isArray(rows) && rows.length > 0) { printTable(rows as Array>); } } finally { @@ -923,6 +950,10 @@ async function executeExternalRemoteSql( } } +function printStatementResults(results: Array): void { + console.log(formatStatementResults(results)); +} + /** * Prompt the user to confirm a destructive remote query when running in a TTY. * `always` asks even for read-only SQL, and `yes` (`--yes`) never asks. Returns true if @@ -930,7 +961,11 @@ async function executeExternalRemoteSql( */ async function confirmDestructiveRemote( sql: string, - { always = false, yes = false }: { always?: boolean; yes?: boolean } = {}, + { + always = false, + yes = false, + output, + }: { always?: boolean; yes?: boolean; output?: Writable } = {}, ): Promise { if (yes || (!always && isSafeStatement(sql))) { return true; @@ -940,6 +975,7 @@ async function confirmDestructiveRemote( } const ok = await confirm({ message: 'This will run against your deployed database. Continue?', + output, }); if (isCancel(ok) || !ok) { return false; @@ -951,14 +987,20 @@ async function confirmDestructiveRemote( // that limit on the query API, which prints rows; a larger dump runs as a D1 import (up to 5 GB). const D1_MAX_SQL_STATEMENT_BYTES = 100_000; +type ExecuteArgs = Omit, 'action'>; + async function runExecute( root: string, - command: string | undefined, - file: string | undefined, + { command, file, remote, yes, json = false }: ExecuteArgs, dialect: DatabaseDialect, - remote?: boolean, - yes?: boolean, ): Promise { + // With --json, stdout carries only the results: prompts and messages go to stderr. + const messages = json ? { output: process.stderr } : {}; + const finish = () => { + if (!json) { + printSuccess('SQL executed successfully.'); + } + }; const readSql = () => { if (file) { return readFileSync(resolve(root, file), 'utf8'); @@ -977,22 +1019,37 @@ async function runExecute( dialect === 'sqlite' && file !== undefined && Buffer.byteLength(sql) > D1_MAX_SQL_STATEMENT_BYTES; + if (bulkImport && json) { + throw new Error( + `db: ${file} is larger than 100 KB, so Void would run it as a D1 import, which returns no results. Run it without --json.`, + ); + } if (bulkImport) { log.warn( `${file} is larger than 100 KB, so Void runs it as a D1 import. The database cannot serve queries until the import finishes, and query rows are not printed.`, ); } - const shouldProceed = await confirmDestructiveRemote(sql, { always: bulkImport, yes }); + const shouldProceed = await confirmDestructiveRemote(sql, { + always: bulkImport, + yes, + ...messages, + }); if (!shouldProceed) { - log.info('Cancelled.'); + log.info('Cancelled.', messages); process.exit(0); } if (dialect === 'sqlite') { - const { executeCloudflareD1Sql, importCloudflareD1Sql, resolveCloudflareD1Context } = - await import('./cloudflare-operations.ts'); + const { + executeCloudflareD1Sql, + executeCloudflareD1Statements, + importCloudflareD1Sql, + resolveCloudflareD1Context, + } = await import('./cloudflare-operations.ts'); const context = resolveCloudflareD1Context(root, configuredD1Binding(root)); if (bulkImport) { await importCloudflareD1Sql(context, sql); + } else if (json) { + printStatementResults(await executeCloudflareD1Statements(context, sql)); } else { const rows = await executeCloudflareD1Sql(context, sql); if (rows.length > 0) { @@ -1004,40 +1061,48 @@ async function runExecute( if (!dbUrl) { log.error( 'DATABASE_URL is required in the shell for a direct Cloudflare remote database command.', + messages, ); process.exit(1); } - await executeExternalRemoteSql(dialect, dbUrl, sql); + await executeExternalSql(dialect, dbUrl, sql, json); } - printSuccess('SQL executed successfully.'); + finish(); return; } const token = getToken(root); if (!token) { - log.error('Not logged in. Run `void account login` first.'); + log.error('Not logged in. Run `void account login` first.', messages); process.exit(1); } const projectConfig = readProjectConfig(root); if (!projectConfig) { - log.error('No project linked. Run `void deploy` first or link a project.'); + log.error('No project linked. Run `void deploy` first or link a project.', messages); process.exit(1); } - const shouldProceed = await confirmDestructiveRemote(sql, { yes }); + // The platform proxy returns the first statement's result only. + if (json && dialect === 'sqlite' && !isSingleStatement(sql)) { + throw new Error( + 'db: `void db execute --remote --json` runs one statement at a time on a Void platform D1 database. Run each statement separately.', + ); + } + + const shouldProceed = await confirmDestructiveRemote(sql, { yes, ...messages }); if (!shouldProceed) { - log.info('Cancelled.'); + log.info('Cancelled.', messages); process.exit(0); } if (dialect !== 'sqlite') { // External database: fetch the connection string from the platform, then connect directly. const client = new PlatformClient(token, { root }); - const dbUrl = await fetchRemoteDatabaseUrl(client, projectConfig.projectId); + const dbUrl = await fetchRemoteDatabaseUrl(client, projectConfig.projectId, messages); - await executeExternalRemoteSql(dialect, dbUrl, sql); - printSuccess('SQL executed successfully.'); + await executeExternalSql(dialect, dbUrl, sql, json); + finish(); return; } @@ -1097,43 +1162,31 @@ async function runExecute( if (!res.ok) { const text = await res.text().catch(() => res.statusText); - log.error(`db: Proxy request failed with ${res.status}: '${text}'.`); + log.error(`db: Proxy request failed with ${res.status}: '${text}'.`, messages); process.exit(1); } const data = await res.json<{ results?: Array>; success?: boolean; + meta?: Record; }>(); const rows = data.results ?? []; - if (rows.length > 0) { + if (json) { + printStatementResults([ + { results: rows, success: data.success !== false, meta: data.meta ?? {} }, + ]); + } else if (rows.length > 0) { printTable(rows); } - printSuccess('SQL executed successfully.'); - return; - } - - if (dialect === 'postgresql') { - const sql = readSql(); - await withPgClient(root, async (client) => { - const result = await client.query(sql); - if (result.rows && result.rows.length > 0) { - printTable(result.rows); - } - }); - printSuccess('SQL executed successfully.'); + finish(); return; } - if (dialect === 'mysql') { + if (dialect !== 'sqlite') { const sql = readSql(); - await withMySqlClient(root, async (client) => { - const rows = await client.query(sql); - if (rows.length > 0) { - printTable(rows); - } - }); - printSuccess('SQL executed successfully.'); + await executeExternalSql(dialect, getLocalDatabaseUrl(root, dialect), sql, json); + finish(); return; } @@ -1141,7 +1194,7 @@ async function runExecute( const { databasePath: dbPath } = getLocalD1Target(root); if (!existsSync(dbPath)) { - log.error('No local database found. Start the dev server first.'); + log.error('No local database found. Start the dev server first.', messages); process.exit(1); } @@ -1149,22 +1202,26 @@ async function runExecute( const db = await openSqliteDatabase(dbPath); try { - const statement = prepareSingleStatement(db, sql); - 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. - const rows = statement.all(); - if (rows.length > 0) { - printTable(rows); - } + if (json) { + printStatementResults(runSqliteStatements(db, sql)); } else { - db.exec(sql); + const statement = prepareSingleStatement(db, sql); + 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. + const rows = statement.all(); + if (rows.length > 0) { + printTable(rows); + } + } else { + db.exec(sql); + } } } finally { db.close(); } - printSuccess('SQL executed successfully.'); + finish(); } function printTable(rows: Array>): void { diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index fd689f1a4..7330e7506 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -1285,6 +1285,10 @@ const HELP_TREE = { 'Run against the deployed database (D1 via proxy; PostgreSQL via direct connection)', }, { command: '--yes', description: 'Skip the confirmation prompt for --remote' }, + { + command: '--json', + description: "Write each statement's results to stdout as JSON", + }, ], examples: [ { command: 'void db execute "select * from users"', description: 'Run inline SQL' }, @@ -1293,6 +1297,10 @@ const HELP_TREE = { command: 'void db execute --remote "select count(*) from users"', description: 'Query the deployed database', }, + { + command: 'void db execute --json "select count(*) as total from users"', + description: 'Print the results as JSON for a script', + }, ], }, migrate: { diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index f3f51b77c..83f80a398 100644 --- a/packages/void/test/unit/cloudflare-operations.test.ts +++ b/packages/void/test/unit/cloudflare-operations.test.ts @@ -8,6 +8,7 @@ import { changeCloudflareDomain, deleteCloudflareSecret, executeCloudflareD1Sql, + executeCloudflareD1Statements, importCloudflareD1Sql, applyCloudflareD1Migrations, listCloudflareDomains, @@ -578,6 +579,33 @@ describe('Cloudflare D1 operations', () => { }); }); + it("keeps each D1 statement's result apart", async () => { + const root = project(`{ + "name": "my-worker", + "account_id": "account-1", + "d1_databases": [{ "binding": "DB", "database_name": "my-data", "database_id": "11111111-2222-3333-4444-555555555555" }] +}\n`); + const runner = vi.fn().mockReturnValue( + ok([ + { success: true, results: [{ a: 1 }], meta: { changes: 0, duration: 0.1 } }, + { success: true, results: [{ b: 2 }], meta: { changes: 0, duration: 0.2 } }, + { success: true, meta: { changes: 3 } }, + ]), + ); + const ctx = resolveCloudflareD1Context(root, 'DB', runner); + await expect( + executeCloudflareD1Statements(ctx, 'select 1 as a; select 2 as b'), + ).resolves.toEqual([ + { results: [{ a: 1 }], success: true, meta: { changes: 0, duration: 0.1 } }, + { results: [{ b: 2 }], success: true, meta: { changes: 0, duration: 0.2 } }, + { results: [], success: true, meta: { changes: 3 } }, + ]); + await expect(executeCloudflareD1Sql(ctx, 'select 1 as a; select 2 as b')).resolves.toEqual([ + { a: 1 }, + { b: 2 }, + ]); + }); + it.each([ { fail: false, bulk: true }, { fail: true, bulk: true }, diff --git a/packages/void/test/unit/db-args.test.ts b/packages/void/test/unit/db-args.test.ts index e9f84c185..efbaa1b7e 100644 --- a/packages/void/test/unit/db-args.test.ts +++ b/packages/void/test/unit/db-args.test.ts @@ -63,6 +63,22 @@ describe('parseDbArgs', () => { }); }); + it('parses execute with --json', () => { + expect(parseDbArgs(['execute', '--json', 'SELECT 1'])).toEqual({ + action: 'execute', + command: 'SELECT 1', + file: undefined, + remote: undefined, + json: true, + }); + }); + + it('rejects --json outside execute', () => { + expect(() => parseDbArgs(['migrate', '--json'])).toThrow( + 'db: `void db migrate` does not support --json.', + ); + }); + it('errors on execute with no SQL and no --file', () => { expect(() => parseDbArgs(['execute'])).toThrow( 'db: Usage: void db execute or void db execute --file .', diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index 6e858c296..f60456e73 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -827,6 +827,154 @@ describe('void db execute', () => { db.close(); } }); + + describe('SQLite --json', () => { + // With --json, console.log writes the results and nothing else, not even a blank line. + function jsonOutput(): Array<{ + results: Array>; + success: boolean; + meta: Record; + }> { + const calls = vi.mocked(console.log).mock.calls; + expect(calls).toHaveLength(1); + return JSON.parse(String(calls[0][0])) as ReturnType; + } + + async function readItems(root: string): Promise> { + const { openSqliteDatabase } = await import('../../src/migrations/runner.ts'); + const db = await openSqliteDatabase(join(root, '.void', 'local.sqlite')); + try { + return db.prepare('SELECT name FROM items ORDER BY id').all(); + } finally { + db.close(); + } + } + + it('prints each statement of a script with its rows and changes', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: + "INSERT INTO items (name) VALUES ('a'), ('b'); SELECT name FROM items ORDER BY id; " + + 'SELECT 2 AS two; CREATE TABLE extra (id INTEGER); -- trailing comment', + json: true, + }); + + const results = jsonOutput(); + expect(results.map((result) => result.results)).toEqual([ + [], + [{ name: 'a' }, { name: 'b' }], + [{ two: 2 }], + [], + ]); + expect(results.map((result) => result.success)).toEqual([true, true, true, true]); + expect(results.map((result) => result.meta.changes)).toEqual([2, 0, 0, 0]); + expect(results[0].meta.last_row_id).toBe(2); + expect(results[0].meta.duration).toEqual(expect.any(Number)); + expect(mockLog.info).not.toHaveBeenCalled(); + const { outro } = await import('@voidzero-dev/vite-plus-prompts'); + expect(outro).not.toHaveBeenCalled(); + }); + + it('keeps NULL, text, numbers, newlines and blobs apart', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: + "SELECT NULL AS a, 'NULL' AS b, 1 AS c, '1' AS d, 'x' || char(10) || 'y' AS e, x'00ff' AS f", + json: true, + }); + + expect(jsonOutput()[0].results).toEqual([ + { a: null, b: 'NULL', c: 1, d: '1', e: 'x\ny', f: [0, 255] }, + ]); + }); + + it('counts the rows a RETURNING statement wrote', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: "INSERT INTO items (name) VALUES ('r') RETURNING id, name", + json: true, + }); + + const [result] = jsonOutput(); + expect(result.results).toEqual([{ id: 1, name: 'r' }]); + expect(result.meta).toMatchObject({ changes: 1, last_row_id: 1 }); + }); + + it('splits only between statements, not inside literals, comments or a trigger body', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: [ + 'CREATE TABLE log (entry TEXT);', + 'CREATE TRIGGER items_log AFTER INSERT ON items BEGIN', + " INSERT INTO log VALUES ('a;b');", + ' INSERT INTO log VALUES (new.name);', + 'END;', + "/* ; */ INSERT INTO items (name) VALUES ('c;d'); -- ;", + 'SELECT entry AS "x;y" FROM log ORDER BY rowid;', + ].join('\n'), + json: true, + }); + + const results = jsonOutput(); + expect(results).toHaveLength(4); + expect(results[3].results).toEqual([{ 'x;y': 'a;b' }, { 'x;y': 'c;d' }]); + // A trigger's writes do not count toward the statement's own changes. + expect(results[2].meta.changes).toBe(1); + }); + + it('stops at a failing statement after the ones before it took effect', async () => { + const root = await createLocalSqliteProject(); + + await expect( + runDbCommand(root, { + action: 'execute', + command: "INSERT INTO items (name) VALUES ('kept'); SELECT * FROM missing; SELECT 1", + json: true, + }), + ).rejects.toThrow('no such table: missing'); + + expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + expect(await readItems(root)).toEqual([{ name: 'kept' }]); + }); + + it('reports SQL that ends inside a statement', async () => { + const root = await createLocalSqliteProject(); + + await expect( + runDbCommand(root, { action: 'execute', command: 'SELECT 1; SELECT (2', json: true }), + ).rejects.toThrow('incomplete input'); + expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + }); + + it('prints an empty array for SQL without a statement', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { action: 'execute', command: '-- nothing to run', json: true }); + + expect(jsonOutput()).toEqual([]); + }); + + it('runs a script that opens and commits its own transaction', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: "BEGIN; INSERT INTO items (name) VALUES ('tx'); COMMIT;", + json: true, + }); + + expect(jsonOutput()).toHaveLength(3); + expect(await readItems(root)).toEqual([{ name: 'tx' }]); + }); + }); }); describe('void db status', () => { diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index 220147383..f1a71e068 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -9,9 +9,13 @@ const mockExecuteD1 = vi.fn(); const mockImportD1 = vi.fn(); +const mockExecuteD1Statements = + vi.fn(); const mockD1Context = { binding: 'DB' }; vi.mock('../../src/cli/cloudflare-operations.ts', () => ({ executeCloudflareD1Sql: (...args: Parameters) => mockExecuteD1(...args), + executeCloudflareD1Statements: (...args: Parameters) => + mockExecuteD1Statements(...args), importCloudflareD1Sql: (...args: Parameters) => mockImportD1(...args), resolveCloudflareD1Context: () => mockD1Context, })); @@ -580,6 +584,116 @@ describe('void db execute --remote (D1)', () => { expect(mockImportD1).toHaveBeenCalledWith(mockD1Context, sql); }); + describe('--json', () => { + // With --json, console.log writes the results and nothing else. + const jsonOutput = () => { + const calls = vi.mocked(console.log).mock.calls; + expect(calls).toHaveLength(1); + return JSON.parse(String(calls[0][0])) as unknown; + }; + + it('prints each direct D1 statement result as JSON without the success line', async () => { + mockReadDeploymentPlatform.mockReturnValue('cloudflare'); + const results = [ + { results: [{ a: 1 }], success: true, meta: { changes: 0 } }, + { results: [{ b: 'x' }], success: true, meta: { changes: 0 } }, + ]; + mockExecuteD1Statements.mockResolvedValue(results); + const sql = 'select 1 as a; select 2 as b'; + + await runDbCommand(createProjectRoot(), { + action: 'execute', + command: sql, + remote: true, + json: true, + }); + + expect(mockExecuteD1Statements).toHaveBeenCalledWith(mockD1Context, sql); + expect(mockExecuteD1).not.toHaveBeenCalled(); + expect(jsonOutput()).toEqual(results); + const { outro } = await import('@voidzero-dev/vite-plus-prompts'); + expect(outro).not.toHaveBeenCalled(); + }); + + it('asks on stderr before a destructive direct D1 statement in a TTY', async () => { + mockReadDeploymentPlatform.mockReturnValue('cloudflare'); + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true }); + mockExecuteD1Statements.mockResolvedValue([{ results: [], success: true, meta: {} }]); + + await runDbCommand(createProjectRoot(), { + action: 'execute', + command: 'DELETE FROM users', + remote: true, + json: true, + }); + + expect(mockConfirm).toHaveBeenCalledWith(expect.objectContaining({ output: process.stderr })); + expect(jsonOutput()).toEqual([{ results: [], success: true, meta: {} }]); + }); + + it('refuses a direct D1 import, which returns no results, before asking or importing', async () => { + const root = directD1File(selectOfSize(D1_STATEMENT_LIMIT + 1), true); + + await expect( + runDbCommand(root, { action: 'execute', file: 'input.sql', remote: true, json: true }), + ).rejects.toThrow('Run it without --json.'); + + expect(mockConfirm).not.toHaveBeenCalled(); + expect(mockImportD1).not.toHaveBeenCalled(); + expect(mockExecuteD1Statements).not.toHaveBeenCalled(); + expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + }); + + it("prints the platform proxy's D1 result as a one-statement array", async () => { + const meta = { changes: 0, duration: 0.2, rows_read: 1 }; + fetchMock.mockResolvedValueOnce( + jsonResponse({ results: [{ id: 1, name: null }], success: true, meta }), + ); + + await runDbCommand(createProjectRoot(), { + action: 'execute', + command: 'SELECT id, name FROM users', + remote: true, + json: true, + }); + + expect(jsonOutput()).toEqual([{ results: [{ id: 1, name: null }], success: true, meta }]); + }); + + it('refuses several statements through the platform proxy before sending them', async () => { + await expect( + runDbCommand(createProjectRoot(), { + action: 'execute', + command: 'SELECT 1; SELECT 2', + remote: true, + json: true, + }), + ).rejects.toThrow('Run each statement separately.'); + + expect(fetchMock).not.toHaveBeenCalled(); + expect(mockConfirm).not.toHaveBeenCalled(); + }); + + it('writes errors to stderr and leaves stdout empty', async () => { + mockGetToken.mockReturnValue(null); + + await expect( + runDbCommand(createProjectRoot(), { + action: 'execute', + command: 'SELECT 1', + remote: true, + json: true, + }), + ).rejects.toThrow('process.exit:1'); + + const { log: clackLog } = await import('@voidzero-dev/vite-plus-prompts'); + expect(clackLog.error).toHaveBeenCalledWith(expect.stringContaining('Not logged in'), { + output: process.stderr, + }); + expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + }); + }); + it('runs execute without --remote against the local database, not the proxy', async () => { const root = createProjectRoot(); // No local database exists, so the local path exits. @@ -697,4 +811,32 @@ describe('void db execute --remote (PostgreSQL)', () => { }), ).rejects.toThrow(PlatformApiError); }); + + it('prints every statement of a multi-statement query with --json', async () => { + const root = createProjectRoot({ database: 'pg' }); + mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); + // node-postgres resolves to an array of results for several statements. + mockPgQuery.mockResolvedValue([ + { command: 'UPDATE', rowCount: 2, rows: [] }, + { command: 'SELECT', rowCount: 1, rows: [{ id: 1, name: null }] }, + ] as never); + + await runDbCommand(root, { + action: 'execute', + command: 'UPDATE users SET name = NULL; SELECT id, name FROM users WHERE id = 1', + remote: true, + json: true, + }); + + const calls = vi.mocked(console.log).mock.calls; + expect(calls).toHaveLength(1); + expect(JSON.parse(String(calls[0][0]))).toEqual([ + { results: [], success: true, meta: { command: 'UPDATE', rowCount: 2 } }, + { + results: [{ id: 1, name: null }], + success: true, + meta: { command: 'SELECT', rowCount: 1 }, + }, + ]); + }); }); diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts new file mode 100644 index 000000000..0588d5cf9 --- /dev/null +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + formatStatementResults, + mySqlStatementResults, + pgStatementResults, +} from '../../src/cli/db-execute-results.ts'; +import { Buffer } from '../../src/cli/node-buffer.ts'; + +describe('db execute --json results', () => { + it('prints binary values as byte arrays', () => { + const output = formatStatementResults([ + { + results: [{ data: Buffer.from([0, 255]), bytes: new Uint8Array([7]), text: 'x' }], + success: true, + meta: {}, + }, + ]); + expect(JSON.parse(output)).toEqual([ + { results: [{ data: [0, 255], bytes: [7], text: 'x' }], success: true, meta: {} }, + ]); + }); + + it('reads one or several node-postgres results', () => { + expect(pgStatementResults({ command: 'SELECT', rowCount: 1, rows: [{ a: 1 }] })).toEqual([ + { results: [{ a: 1 }], success: true, meta: { command: 'SELECT', rowCount: 1 } }, + ]); + expect( + pgStatementResults([ + { command: 'CREATE', rowCount: null, rows: [] }, + { command: 'SELECT', rowCount: 0, rows: [] }, + ]), + ).toEqual([ + { results: [], success: true, meta: { command: 'CREATE', rowCount: null } }, + { results: [], success: true, meta: { command: 'SELECT', rowCount: 0 } }, + ]); + }); + + // The shapes mysql2 resolves `query()` to, as `[rows, fields]`. + const field = { name: 'a', columnType: 3 }; + const header = { fieldCount: 0, affectedRows: 2, insertId: 5, info: '', serverStatus: 2 }; + + it('reads a single MySQL statement', () => { + expect(mySqlStatementResults([{ a: 1 }], [field])).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + ]); + expect(mySqlStatementResults([], [field])).toEqual([{ results: [], success: true, meta: {} }]); + expect(mySqlStatementResults(header, undefined)).toEqual([ + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it('reads each MySQL statement of a multi-statement query', () => { + expect(mySqlStatementResults([header, [{ a: 1 }], []], [undefined, [field], [field]])).toEqual([ + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ a: 1 }], success: true, meta: {} }, + { results: [], success: true, meta: {} }, + ]); + expect(mySqlStatementResults([[{ a: 1 }], [{ a: 2 }]], [[field], [field]])).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + { results: [{ a: 2 }], success: true, meta: {} }, + ]); + }); +}); From 9cbf6e91629da6cfa2fb464d4e8e76615adc720d Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 14:11:59 +0530 Subject: [PATCH 02/11] fix(cli): keep `void db execute --json` values and statements exact - Read SQLite integers as BigInt and MySQL BIGINTs with supportBigNumbers; integers past 2^53 print as strings of their digits. - Print Infinity, -Infinity and NaN as strings instead of null. - Serialize bytes at any depth, so bytea[] elements print as byte arrays. - Split SQLite SQL the way sqlite3_complete() does, so a CREATE TRIGGER is one statement locally and through the platform proxy. - Group a MySQL CALL's result sets and header into one entry. - Leave out PostgreSQL's empty-query result. - Do not open a subcommand menu when --json is passed. Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 4 +- packages/void/src/cli/cli-main.ts | 7 +- packages/void/src/cli/db-execute-results.ts | 311 +++++++++++++----- packages/void/src/cli/db.ts | 13 +- packages/void/src/migrations/runner.ts | 2 + packages/void/test/unit/db-commands.test.ts | 32 ++ .../void/test/unit/db-execute-remote.test.ts | 63 +++- .../void/test/unit/db-execute-results.test.ts | 136 +++++++- 8 files changed, 475 insertions(+), 93 deletions(-) diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 625bb10d0..fde1cb496 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -94,13 +94,13 @@ void db execute --json "select count(*) as total from users; select id from user Each entry has the same shape as a D1 result and as an entry of `wrangler d1 execute --json`: -- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. +- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. - `success`: `true` for a statement that ran. - `meta`: what the database reports about the statement. D1 databases report D1's metadata, such as `changes` and `last_row_id` (locally `changes`, `last_row_id` and `duration`). PostgreSQL reports `command` and `rowCount`, and MySQL reports `affectedRows` and `insertId` for a statement that changes data. If a statement fails, stdout stays empty. -`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command. +`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command; a `CREATE TRIGGER` counts as one statement. ## `void db migrate` {#void-db-migrate} diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 366c3fa79..43e1fdcb4 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -63,7 +63,12 @@ async function runSubcommandGroup( .slice(1) .some((arg) => subcommands.some(({ name }) => name === arg)); try { - if ((!sub || (sub.startsWith('-') && !hasNamedSubcommand)) && process.stdin.isTTY) { + // The menu draws on stdout, which --json keeps for its result. + if ( + (!sub || (sub.startsWith('-') && !hasNamedSubcommand)) && + process.stdin.isTTY && + !args.includes('--json') + ) { const { promptSubcommand } = await import('./subcommand-prompt.ts'); if (command === 'platform' && !sub) { log.info( diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index 309dd3367..04a7725cb 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -11,83 +11,141 @@ export type StatementResult = { meta: Record; }; -/** Serialize results for stdout. Binary values print as byte arrays, the way D1 returns BLOBs. */ +/** A value as JSON.stringify hands it to a replacer, after any `toJSON()`. */ +type JsonValue = + | string + | number + | boolean + | null + | undefined + | Array + | { [key: string]: JsonValue }; + +const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER); +const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER); + +/** + * Write values JSON cannot hold as-is without changing them. `this[key]` is the value before + * `toJSON()`, so a Buffer is still a Buffer here, at any depth (a `bytea[]` element too). + */ +function jsonValue(this: unknown, key: string, value: JsonValue): JsonValue { + const raw = (this as Record)[key]; + // Bytes print as byte arrays, the way D1 returns BLOBs. + if (raw instanceof Uint8Array) { + return Array.from(raw); + } + // An integer past 2^53 would round as a JSON number, so it prints as a string of its digits, + // like mysql2's `supportBigNumbers`. + if (typeof raw === 'bigint') { + return raw >= MIN_SAFE && raw <= MAX_SAFE ? Number(raw) : raw.toString(); + } + // JSON has no Infinity or NaN, and JSON.stringify would print them as null, which reads as + // SQL NULL. PostgreSQL's own JSON functions write them as these strings. + if (typeof raw === 'number' && !Number.isFinite(raw)) { + return String(raw); + } + return value; +} + +/** Serialize results for stdout. */ export function formatStatementResults(results: Array): string { - return JSON.stringify( - results.map((result) => ({ - ...result, - results: result.results.map((row) => - Object.fromEntries( - Object.entries(row).map(([column, value]) => [ - column, - value instanceof Uint8Array ? Array.from(value) : value, - ]), - ), - ), - })), - null, - 2, - ); + return JSON.stringify(results, jsonValue, 2); } +type StatementRange = { start: number; end: number }; + /** - * Cut SQL after each `;` outside literals and comments. A trigger's `BEGIN ... END` body holds - * semicolons of its own, so a piece can end inside a statement; the caller joins pieces until - * SQLite accepts them. + * Find each statement in SQLite SQL the way `sqlite3_complete()` does: a statement ends at a + * top-level `;`, except that `CREATE [TEMP] TRIGGER` runs until `; END ;`, since its body holds + * semicolons of its own. Ranges hold no statement when they are only whitespace and comments, + * and those are left out. The last range may lack its `;`; SQLite decides whether it is complete. */ -function* sqlPieces(sql: string): Generator { +export function sqliteStatementRanges(sql: string): Array { + // States and transitions from SQLite's complete.c (whitespace and comments change nothing): + // 0 nothing yet, 1 between statements, 2 a statement, 3 after EXPLAIN, 4 after CREATE [TEMP], + // 5 a trigger, 6 a trigger after `;`, 7 a trigger after `; END`. + // Token order: semicolon, other, EXPLAIN, CREATE, TEMP, TRIGGER, END. + const START = 1; + const transitions: Array> = [ + [1, 2, 3, 4, 2, 2, 2], + [1, 2, 3, 4, 2, 2, 2], + [1, 2, 2, 2, 2, 2, 2], + [1, 3, 2, 4, 2, 2, 2], + [1, 2, 2, 2, 4, 5, 2], + [6, 5, 5, 5, 5, 5, 5], + [6, 5, 5, 5, 5, 5, 7], + [1, 5, 5, 5, 5, 5, 5], + ]; + const keywords = new Map([ + ['explain', 2], + ['create', 3], + ['temp', 4], + ['temporary', 4], + ['trigger', 5], + ['end', 6], + ]); + const ranges: Array = []; + let state = 0; let start = 0; + let hasStatement = false; + const advance = (token: number, index: number) => { + const next = transitions[state][token]; + if (token === 0 && next === START) { + if (hasStatement) { + ranges.push({ start, end: index + 1 }); + } + start = index + 1; + hasStatement = false; + } else if (token !== 0) { + hasStatement = true; + } + state = next; + }; for (const segment of tokenizeSql(sql)) { + if (segment.kind === 'line-comment' || segment.kind === 'block-comment') { + continue; + } if (segment.kind !== 'sql') { + advance(1, segment.start); continue; } - for (let index = segment.start; index < segment.end; index++) { - if (sql[index] === ';') { - yield sql.slice(start, index + 1); - start = index + 1; + const text = sql.slice(segment.start, segment.end); + for (const match of text.matchAll(/;|\s+|[\w$\u0080-￿]+|./gu)) { + const [token] = match; + if (token === ';') { + advance(0, segment.start + match.index); + } else if (!/^\s/u.test(token)) { + advance(keywords.get(token.toLowerCase()) ?? 1, segment.start + match.index); } } } - yield sql.slice(start); + if (hasStatement) { + ranges.push({ start, end: sql.length }); + } + return ranges; } -function isIncompleteInput(error: unknown): boolean { - return error instanceof Error && error.message === 'incomplete input'; +/** Split SQLite SQL into its statements. See `sqliteStatementRanges`. */ +export function splitSqliteStatements(sql: string): Array { + return sqliteStatementRanges(sql).map(({ start, end }) => sql.slice(start, end)); } /** * Run SQL statement by statement and keep each one's rows. Like `exec()`, every statement * commits on its own unless the SQL opens a transaction, and a failing statement stops the run - * after the ones before it took effect. - * - * SQLite decides where a statement ends: a piece it reports as incomplete input continues - * into the next one. better-sqlite3 refuses SQL without a statement (whitespace or comments - * only) with a `RangeError`, and that piece is skipped. + * after the ones before it took effect. Integers are read exactly, as BigInt. */ export function runSqliteStatements(db: SqliteDatabase, sql: string): Array { - const counters = db.prepare<{ changes: number; last_row_id: number; total: number }>( - 'SELECT changes() AS changes, last_insert_rowid() AS last_row_id, total_changes() AS total', - ); + const counters = db + .prepare<{ changes: bigint; last_row_id: bigint; total: bigint }>( + 'SELECT changes() AS changes, last_insert_rowid() AS last_row_id, total_changes() AS total', + ) + .safeIntegers(true); // A scalar SELECT always returns one row. - const readCounters = () => counters.get() ?? { changes: 0, last_row_id: 0, total: 0 }; + const readCounters = () => counters.get() ?? { changes: 0n, last_row_id: 0n, total: 0n }; const results: Array = []; - let pending = ''; - for (const piece of sqlPieces(sql)) { - pending += piece; - let statement; - try { - statement = db.prepare>(pending); - } catch (error) { - if (isIncompleteInput(error)) { - continue; - } - if (error instanceof RangeError) { - pending = ''; - continue; - } - throw error; - } - pending = ''; + for (const statementSql of splitSqliteStatements(sql)) { + const statement = db.prepare>(statementSql).safeIntegers(true); const before = readCounters().total; const started = performance.now(); let rows: Array> = []; @@ -109,10 +167,6 @@ export function runSqliteStatements(db: SqliteDatabase, sql: string): Array>; }; -/** node-postgres returns one result for one statement and an array for several. */ +/** + * node-postgres returns one result for one statement and an array for several. SQL without a + * statement returns an empty-query result with no command, which is left out. + */ export function pgStatementResults(result: PgResult | Array): Array { - return (Array.isArray(result) ? result : [result]).map((item) => ({ - results: item.rows ?? [], - success: true, - meta: { command: item.command ?? null, rowCount: item.rowCount ?? null }, - })); + return (Array.isArray(result) ? result : [result]) + .filter((item) => item.command !== null && item.command !== undefined) + .map((item) => ({ + results: item.rows ?? [], + success: true, + meta: { command: item.command, rowCount: item.rowCount ?? null }, + })); } -function mySqlStatementResult(value: unknown): StatementResult { - if (Array.isArray(value)) { - return { results: value as Array>, success: true, meta: {} }; - } +/** A write's result header. `insertId` is a string past 2^53 with `supportBigNumbers`. */ +type MySqlHeaderMeta = { affectedRows: number | string; insertId: number | string }; + +function mySqlCount(field: unknown): number | string { + return typeof field === 'number' || typeof field === 'string' ? field : 0; +} + +function mySqlHeaderMeta(value: unknown): MySqlHeaderMeta { const header = (typeof value === 'object' && value !== null ? value : {}) as Record< string, unknown >; - return { - results: [], - success: true, - meta: { affectedRows: header.affectedRows ?? 0, insertId: header.insertId ?? 0 }, + return { affectedRows: mySqlCount(header.affectedRows), insertId: mySqlCount(header.insertId) }; +} + +function mySqlStatementResult(value: unknown): StatementResult { + return Array.isArray(value) + ? { results: value as Array>, success: true, meta: {} } + : { results: [], success: true, meta: mySqlHeaderMeta(value) }; +} + +/** + * Tell which MySQL statements are `CALL`s. Statements end at top-level semicolons; a stored + * program body (`BEGIN ... END`) and a `CASE ... END` hold semicolons or an `END` of their own, + * so they nest. `END IF`, `END LOOP`, `END WHILE` and `END REPEAT` close blocks that sit inside + * a `BEGIN`, so they do not change the depth. A `BEGIN` that opens a top-level statement starts + * a transaction, not a block. + */ +export function mySqlCallStatements(sql: string): Array { + const calls: Array = []; + let depth = 0; + let firstWord: string | undefined; + // Set right after an END that closed a block, so a following IF, LOOP, WHILE, REPEAT or CASE + // reads as part of that END. + let afterEnd = false; + const finish = () => { + if (firstWord !== undefined) { + calls.push(firstWord === 'call'); + } + firstWord = undefined; + afterEnd = false; }; + for (const segment of tokenizeSql(sql)) { + if (segment.kind === 'line-comment' || segment.kind === 'block-comment') { + continue; + } + if (segment.kind !== 'sql') { + firstWord ??= ''; + afterEnd = false; + continue; + } + const text = sql.slice(segment.start, segment.end); + for (const [token] of text.matchAll(/;|\s+|[\w$\u0080-￿]+|./gu)) { + if (/^\s/u.test(token)) { + continue; + } + const word = token.toLowerCase(); + if (word === ';') { + afterEnd = false; + if (depth === 0) { + finish(); + } + continue; + } + const closedBlock = afterEnd; + afterEnd = false; + if (closedBlock && /^(?:if|loop|while|repeat)$/.test(word)) { + // That END closed an IF or loop, which never opened a level, so restore it. + depth++; + } else if (closedBlock && word === 'case') { + // END CASE closes the CASE that opened a level. + } else if (word === 'case' || (word === 'begin' && (depth > 0 || firstWord !== undefined))) { + depth++; + } else if (word === 'end' && depth > 0) { + depth--; + afterEnd = true; + } + firstWord ??= word; + } + } + finish(); + return calls; } /** - * mysql2 returns `[rows, fields]`. With several statements, `rows` holds one entry per - * statement (rows, or a result header for a write), and `fields` holds each statement's - * column list, or `undefined` for a write. One statement's `fields` lists column objects. + * mysql2 returns `[rows, fields]`. With several result sets, `rows` holds one entry per result + * (rows, or a result header for a write) and `fields` holds each one's column list, or + * `undefined` for a header. A `CALL` returns each result set of the procedure and then its own + * header, so those entries are grouped under the `CALL`, its rows in order. */ -export function mySqlStatementResults(rows: unknown, fields: unknown): Array { - const severalStatements = +export function mySqlStatementResults( + rows: unknown, + fields: unknown, + sql: string, +): Array { + const severalResults = Array.isArray(rows) && Array.isArray(fields) && fields.some((entry) => entry === undefined || Array.isArray(entry)); - return severalStatements - ? (rows as Array).map(mySqlStatementResult) - : [mySqlStatementResult(rows)]; + if (!severalResults) { + return [mySqlStatementResult(rows)]; + } + const entries = rows as Array; + const grouped: Array = []; + let index = 0; + let matched = true; + for (const isCall of mySqlCallStatements(sql)) { + if (!isCall) { + matched &&= index < entries.length; + grouped.push(mySqlStatementResult(entries[index++])); + continue; + } + const sets: Array>> = []; + while (index < entries.length && Array.isArray(entries[index])) { + sets.push(entries[index++] as Array>); + } + matched &&= index < entries.length; + grouped.push({ results: sets.flat(), success: true, meta: mySqlHeaderMeta(entries[index++]) }); + } + // When the statements and results do not line up (SQL this scan reads differently from + // MySQL), print one entry per result rather than guess. + return matched && index === entries.length ? grouped : entries.map(mySqlStatementResult); } diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 60911db32..d1e298712 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -11,7 +11,6 @@ import { import { createRequire } from 'node:module'; import type { Writable } from 'node:stream'; import { pathToFileURL } from 'node:url'; -import { isSingleStatement } from '@void/deploy-core'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createJiti } from 'jiti'; import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; @@ -53,6 +52,7 @@ import { mySqlStatementResults, pgStatementResults, runSqliteStatements, + splitSqliteStatements, } from './db-execute-results.ts'; import type { StatementResult } from './db-execute-results.ts'; import { @@ -937,11 +937,16 @@ async function executeExternalSql( return; } const { createConnection } = await import('mysql2/promise'); - const mySqlClient = await createConnection({ uri: dbUrl, multipleStatements: true }); + const mySqlClient = await createConnection({ + uri: dbUrl, + multipleStatements: true, + // BIGINT values past 2^53 arrive as strings instead of rounded numbers. + ...(json ? { supportBigNumbers: true, bigNumberStrings: false } : {}), + }); try { const [rows, fields] = await mySqlClient.query(sql); if (json) { - printStatementResults(mySqlStatementResults(rows, fields)); + printStatementResults(mySqlStatementResults(rows, fields, sql)); } else if (Array.isArray(rows) && rows.length > 0) { printTable(rows as Array>); } @@ -1084,7 +1089,7 @@ async function runExecute( } // The platform proxy returns the first statement's result only. - if (json && dialect === 'sqlite' && !isSingleStatement(sql)) { + if (json && dialect === 'sqlite' && splitSqliteStatements(sql).length > 1) { throw new Error( 'db: `void db execute --remote --json` runs one statement at a time on a Void platform D1 database. Run each statement separately.', ); diff --git a/packages/void/src/migrations/runner.ts b/packages/void/src/migrations/runner.ts index 10dd2cf5b..b14738040 100644 --- a/packages/void/src/migrations/runner.ts +++ b/packages/void/src/migrations/runner.ts @@ -12,6 +12,8 @@ export type SqliteStatement = { get(...params: Array): T | undefined; all(...params: Array): Array; run(...params: Array): void; + /** Read INTEGER columns as BigInt, so values past 2^53 keep every digit. */ + safeIntegers(toggle?: boolean): SqliteStatement; }; type SqliteTransaction = { diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index f60456e73..b69fbe6b9 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -892,6 +892,38 @@ describe('void db execute', () => { ]); }); + it('keeps every digit of integers past 2^53, in rows and in last_row_id', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: + "INSERT INTO items (id, name) VALUES (9007199254740993, 'big'); " + + 'SELECT id, 9007199254740991 AS safe, -9223372036854775808 AS low FROM items', + json: true, + }); + + const [insert, select] = jsonOutput(); + expect(insert.meta.last_row_id).toBe('9007199254740993'); + expect(select.results).toEqual([ + { id: '9007199254740993', safe: 9_007_199_254_740_991, low: '-9223372036854775808' }, + ]); + }); + + it('tells an infinite REAL apart from NULL', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: 'SELECT 1e999 AS up, -1e999 AS down, NULL AS missing', + json: true, + }); + + expect(jsonOutput()[0].results).toEqual([ + { up: 'Infinity', down: '-Infinity', missing: null }, + ]); + }); + it('counts the rows a RETURNING statement wrote', async () => { const root = await createLocalSqliteProject(); diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index f1a71e068..45ec27301 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -83,6 +83,19 @@ vi.mock('pg', () => ({ }, })); +const mockMySqlQuery = vi.fn<(sql: string) => Promise<[unknown, unknown]>>(() => + Promise.resolve([[], []]), +); +const mockMySqlCreateConnection = vi.fn((_options: Record) => ({ + query: mockMySqlQuery, + end: () => Promise.resolve(), +})); + +vi.mock('mysql2/promise', () => ({ + createConnection: (options: Record) => + Promise.resolve(mockMySqlCreateConnection(options)), +})); + const fetchMock = vi.fn(); let originalFetch: typeof globalThis.fetch | undefined; @@ -105,11 +118,15 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ const roots: Array = []; -function createProjectRoot(options: { database?: 'pg'; d1Binding?: string } = {}): string { +function createProjectRoot( + options: { database?: 'pg' | 'mysql'; d1Binding?: string } = {}, +): string { const root = mkdtempSync(join(tmpdir(), 'void-db-execute-remote-')); roots.push(root); - const voidConfig: Record = options.database === 'pg' ? { database: 'pg' } : {}; + const voidConfig: Record = options.database + ? { database: options.database } + : {}; if (options.d1Binding) { voidConfig.inference = { bindings: { db: options.d1Binding } }; } @@ -674,6 +691,23 @@ describe('void db execute --remote (D1)', () => { expect(mockConfirm).not.toHaveBeenCalled(); }); + it('sends one CREATE TRIGGER, whose body holds semicolons, through the platform proxy', async () => { + fetchMock.mockResolvedValueOnce(jsonResponse({ results: [], success: true, meta: {} })); + const sql = + "CREATE TRIGGER log_users AFTER INSERT ON users BEGIN INSERT INTO log VALUES ('a;b'); UPDATE users SET seen = 1; END;"; + + await runDbCommand(createProjectRoot(), { + action: 'execute', + command: sql, + remote: true, + json: true, + }); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({ sql }); + expect(jsonOutput()).toEqual([{ results: [], success: true, meta: {} }]); + }); + it('writes errors to stderr and leaves stdout empty', async () => { mockGetToken.mockReturnValue(null); @@ -812,6 +846,31 @@ describe('void db execute --remote (PostgreSQL)', () => { ).rejects.toThrow(PlatformApiError); }); + it('reads MySQL BIGINT values past 2^53 as strings with --json only', async () => { + const root = createProjectRoot({ database: 'mysql' }); + mockGetDatabaseUrl.mockResolvedValue({ url: 'mysql://host/db' }); + mockMySqlQuery.mockResolvedValue([[{ id: '9007199254740993' }], [{ name: 'id' }]]); + + await runDbCommand(root, { + action: 'execute', + command: 'SELECT id FROM users', + remote: true, + json: true, + }); + + expect(mockMySqlCreateConnection).toHaveBeenLastCalledWith( + expect.objectContaining({ supportBigNumbers: true, bigNumberStrings: false }), + ); + expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + { results: [{ id: '9007199254740993' }], success: true, meta: {} }, + ]); + + await runDbCommand(root, { action: 'execute', command: 'SELECT id FROM users', remote: true }); + expect(mockMySqlCreateConnection).toHaveBeenLastCalledWith( + expect.not.objectContaining({ supportBigNumbers: true }), + ); + }); + it('prints every statement of a multi-statement query with --json', async () => { const root = createProjectRoot({ database: 'pg' }); mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index 0588d5cf9..add09af02 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from 'vite-plus/test'; import { formatStatementResults, + mySqlCallStatements, mySqlStatementResults, pgStatementResults, + splitSqliteStatements, } from '../../src/cli/db-execute-results.ts'; import { Buffer } from '../../src/cli/node-buffer.ts'; @@ -20,6 +22,49 @@ describe('db execute --json results', () => { ]); }); + it('prints bytes inside arrays as byte arrays', () => { + const output = formatStatementResults([ + { results: [{ files: [Buffer.from([1, 2]), null] }], success: true, meta: {} }, + ]); + expect(JSON.parse(output)).toEqual([ + { results: [{ files: [[1, 2], null] }], success: true, meta: {} }, + ]); + }); + + it('keeps every digit of integers past 2^53', () => { + const output = formatStatementResults([ + { + results: [{ big: 9_007_199_254_740_993n, low: -9_007_199_254_740_993n, small: 42n }], + success: true, + meta: { last_row_id: 9_007_199_254_740_993n, changes: 1n }, + }, + ]); + expect(JSON.parse(output)).toEqual([ + { + results: [{ big: '9007199254740993', low: '-9007199254740993', small: 42 }], + success: true, + meta: { last_row_id: '9007199254740993', changes: 1 }, + }, + ]); + }); + + it('tells infinite and NaN values apart from NULL', () => { + const output = formatStatementResults([ + { + results: [{ up: Infinity, down: -Infinity, nan: Number.NaN, missing: null }], + success: true, + meta: {}, + }, + ]); + expect(JSON.parse(output)).toEqual([ + { + results: [{ up: 'Infinity', down: '-Infinity', nan: 'NaN', missing: null }], + success: true, + meta: {}, + }, + ]); + }); + it('reads one or several node-postgres results', () => { expect(pgStatementResults({ command: 'SELECT', rowCount: 1, rows: [{ a: 1 }] })).toEqual([ { results: [{ a: 1 }], success: true, meta: { command: 'SELECT', rowCount: 1 } }, @@ -35,29 +80,110 @@ describe('db execute --json results', () => { ]); }); + it('leaves out the empty-query result of SQL without a statement', () => { + expect(pgStatementResults({ command: null, rowCount: null, rows: [] })).toEqual([]); + }); + + it('splits SQLite SQL where SQLite ends each statement', () => { + expect(splitSqliteStatements("SELECT ';'; -- a;\nSELECT 2 /* ; */;; SELECT 3")).toEqual([ + "SELECT ';';", + ' -- a;\nSELECT 2 /* ; */;', + ' SELECT 3', + ]); + expect(splitSqliteStatements('-- only a comment;\n')).toEqual([]); + const trigger = + 'CREATE TEMP TRIGGER t AFTER INSERT ON a BEGIN UPDATE a SET x = CASE WHEN 1 THEN 2 END; DELETE FROM b; END;'; + expect(splitSqliteStatements(`${trigger} SELECT 1;`)).toEqual([trigger, ' SELECT 1;']); + expect( + splitSqliteStatements('EXPLAIN CREATE TRIGGER t AFTER INSERT ON a BEGIN SELECT 1; END;'), + ).toHaveLength(1); + // A transaction's BEGIN and END are statements of their own. + expect(splitSqliteStatements('BEGIN; INSERT INTO a VALUES (1); END;')).toHaveLength(3); + // A trigger missing its END stays open for SQLite to report. + expect( + splitSqliteStatements('CREATE TRIGGER t AFTER INSERT ON a BEGIN SELECT 1;'), + ).toHaveLength(1); + }); + // The shapes mysql2 resolves `query()` to, as `[rows, fields]`. const field = { name: 'a', columnType: 3 }; const header = { fieldCount: 0, affectedRows: 2, insertId: 5, info: '', serverStatus: 2 }; it('reads a single MySQL statement', () => { - expect(mySqlStatementResults([{ a: 1 }], [field])).toEqual([ + expect(mySqlStatementResults([{ a: 1 }], [field], 'SELECT 1')).toEqual([ { results: [{ a: 1 }], success: true, meta: {} }, ]); - expect(mySqlStatementResults([], [field])).toEqual([{ results: [], success: true, meta: {} }]); - expect(mySqlStatementResults(header, undefined)).toEqual([ + expect(mySqlStatementResults([], [field], 'SELECT 1')).toEqual([ + { results: [], success: true, meta: {} }, + ]); + expect(mySqlStatementResults(header, undefined, 'DELETE FROM a')).toEqual([ { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, ]); }); it('reads each MySQL statement of a multi-statement query', () => { - expect(mySqlStatementResults([header, [{ a: 1 }], []], [undefined, [field], [field]])).toEqual([ + expect( + mySqlStatementResults( + [header, [{ a: 1 }], []], + [undefined, [field], [field]], + 'DELETE FROM a; SELECT 1; SELECT 2', + ), + ).toEqual([ { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, { results: [{ a: 1 }], success: true, meta: {} }, { results: [], success: true, meta: {} }, ]); - expect(mySqlStatementResults([[{ a: 1 }], [{ a: 2 }]], [[field], [field]])).toEqual([ + expect( + mySqlStatementResults([[{ a: 1 }], [{ a: 2 }]], [[field], [field]], 'SELECT 1; SELECT 2'), + ).toEqual([ { results: [{ a: 1 }], success: true, meta: {} }, { results: [{ a: 2 }], success: true, meta: {} }, ]); }); + + it("groups a CALL's result sets and header under the CALL", () => { + expect(mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], 'CALL p()')).toEqual([ + { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + expect( + mySqlStatementResults( + [[{ a: 1 }], [{ b: 2 }], [{ c: 3 }], header, header], + [[field], [field], [field], undefined, undefined], + 'SELECT 1; CALL p(); DELETE FROM a', + ), + ).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + { results: [{ b: 2 }, { c: 3 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it('prints one entry per MySQL result when the statements do not line up', () => { + expect( + mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], 'CALL p(); CALL q()'), + ).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it('finds MySQL statements around stored program bodies', () => { + expect( + mySqlCallStatements( + [ + 'BEGIN', + `CREATE PROCEDURE p() lbl: BEGIN + DECLARE x INT DEFAULT 0; + IF x > 0 THEN SELECT 1; END IF; + CASE x WHEN 0 THEN SELECT 2; END CASE; + SELECT CASE WHEN x THEN 'a;' ELSE 'b' END; + WHILE x < 2 DO SET x = x + 1; END WHILE; + END lbl`, + 'call p()', + 'COMMIT', + '-- trailing comment', + ].join(';\n'), + ), + ).toEqual([false, false, true, false]); + }); }); From 6d69c08f198f073efc0584bc419936dfe9fc2caa Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 14:31:10 +0530 Subject: [PATCH 03/11] fix(cli): keep `void db execute --json` output exact for more inputs - Run `cloudflared access login` with `--quiet` and send its output to stderr, so renewing Access never puts the JWT or login text on stdout. - Find MySQL `CALL` statements with MySQL's own lexical rules: `#` comments, `--` only before whitespace, backslash escapes in quotes, and `/*!` / `/*+` comments as SQL. - Give the pg client lossless parsers in JSON mode: `numeric[]` elements stay strings, and numbers in json, jsonb and their arrays keep the digits the database sent. - Skip only the whitespace and comments SQLite skips, so a trailing bare `/*` or nonbreaking space fails as SQLite reports it. Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 2 +- packages/void/src/cli/cf-access.ts | 14 +- packages/void/src/cli/db-execute-results.ts | 185 ++++++++++++++---- packages/void/src/cli/db.ts | 9 +- .../src/runtime/db/migrations/mysql-sql.ts | 4 +- packages/void/test/unit/cf-access.test.ts | 4 +- packages/void/test/unit/db-commands.test.ts | 16 +- .../void/test/unit/db-execute-remote.test.ts | 24 ++- .../void/test/unit/db-execute-results.test.ts | 53 +++++ 9 files changed, 263 insertions(+), 48 deletions(-) diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index fde1cb496..864d2d9f8 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -94,7 +94,7 @@ void db execute --json "select count(*) as total from users; select id from user Each entry has the same shape as a D1 result and as an entry of `wrangler d1 execute --json`: -- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. +- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings, in arrays too, and numbers in `json` and `jsonb` values keep the digits the database returned. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. - `success`: `true` for a statement that ran. - `meta`: what the database reports about the statement. D1 databases report D1's metadata, such as `changes` and `last_row_id` (locally `changes`, `last_row_id` and `duration`). PostgreSQL reports `command` and `rowCount`, and MySQL reports `affectedRows` and `insertId` for a statement that changes data. diff --git a/packages/void/src/cli/cf-access.ts b/packages/void/src/cli/cf-access.ts index da44aea8d..95fb1b145 100644 --- a/packages/void/src/cli/cf-access.ts +++ b/packages/void/src/cli/cf-access.ts @@ -113,7 +113,7 @@ export function ensurePlatformAccessToken( ); } console.error(`Renew Cloudflare Access authentication for ${origin}.`); - runCloudflared(['access', 'login', origin], { inherit: true, timeoutMs: 120_000 }); + runCloudflaredLogin(origin); } let token = runCloudflared(['access', 'token', `-app=${origin}`]); if (token && rejectedTokens.has(token)) { @@ -121,7 +121,7 @@ export function ensurePlatformAccessToken( } if ((!token || !usableToken(token)) && process.stdin.isTTY && process.stdout.isTTY) { console.error(`Authenticate to Cloudflare Access for ${origin}.`); - runCloudflared(['access', 'login', origin], { inherit: true, timeoutMs: 120_000 }); + runCloudflaredLogin(origin); token = runCloudflared(['access', 'token', `-app=${origin}`]); } if (!token || !usableToken(token)) { @@ -135,6 +135,14 @@ export function ensurePlatformAccessToken( writeKeyringPassword(ACCESS_KEYRING_SERVICE, account, token); } +/** + * Sign in through the browser. `--quiet` keeps the JWT off the terminal, and cloudflared's + * output goes to stderr, since stdout may carry a command's result (`void db execute --json`). + */ +function runCloudflaredLogin(origin: string): void { + runCloudflared(['access', 'login', '--quiet', origin], { inherit: true, timeoutMs: 120_000 }); +} + function runCloudflared( args: Array, opts?: { inherit?: boolean; timeoutMs?: number }, @@ -142,7 +150,7 @@ function runCloudflared( try { const result = spawnSync('cloudflared', args, { encoding: 'utf8', - stdio: opts?.inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'], + stdio: opts?.inherit ? ['inherit', 2, 'inherit'] : ['ignore', 'pipe', 'pipe'], timeout: opts?.timeoutMs ?? 5000, }); if (result.error || result.status !== 0) { diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index 04a7725cb..ca6c6dbda 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -1,5 +1,7 @@ import { tokenizeSql } from '@void/deploy-core'; +import type { CustomTypesConfig } from 'pg'; import type { SqliteDatabase } from '../migrations/runner.ts'; +import { skipMySqlQuoted } from '../runtime/db/migrations/mysql-sql.ts'; /** * One statement's outcome for `void db execute --json`. The shape follows D1's result @@ -102,7 +104,10 @@ export function sqliteStatementRanges(sql: string): Array { state = next; }; for (const segment of tokenizeSql(sql)) { - if (segment.kind === 'line-comment' || segment.kind === 'block-comment') { + // SQLite reads a `/*` that ends the input as a `/` and rejects it, so it stays in a statement. + // Any other block comment, even one left open, is a comment. + const bareOpen = segment.kind === 'block-comment' && segment.end - segment.start === 2; + if (segment.kind === 'line-comment' || (segment.kind === 'block-comment' && !bareOpen)) { continue; } if (segment.kind !== 'sql') { @@ -110,11 +115,13 @@ export function sqliteStatementRanges(sql: string): Array { continue; } const text = sql.slice(segment.start, segment.end); - for (const match of text.matchAll(/;|\s+|[\w$\u0080-￿]+|./gu)) { + // SQLite's whitespace is these five characters; anything else, such as a nonbreaking + // space, is part of a statement and fails there. + for (const match of text.matchAll(/;|[ \t\n\f\r]+|[\w$\u0080-￿]+|./gu)) { const [token] = match; if (token === ';') { advance(0, segment.start + match.index); - } else if (!/^\s/u.test(token)) { + } else if (!/^[ \t\n\f\r]/u.test(token)) { advance(keywords.get(token.toLowerCase()) ?? 1, segment.start + match.index); } } @@ -176,6 +183,87 @@ type PgResult = { rows?: Array>; }; +/** What `JSON.rawJSON()` returns. `JSON.stringify` writes its text as it is. */ +type RawJson = { readonly rawJSON: string }; + +/** JSON parsed with each number kept as its source text. */ +type ExactJson = + | string + | boolean + | null + | RawJson + | Array + | { [key: string]: ExactJson }; + +// Node 24 has both; TypeScript's libs do not declare them yet. +declare global { + interface JSON { + /** A reviver also receives a primitive's source text. */ + parse( + text: string, + reviver: (key: string, value: ExactJson | number, context: { source?: string }) => ExactJson, + ): ExactJson; + /** A value that `JSON.stringify` writes as `text`, which must be a JSON primitive. */ + rawJSON(text: string): RawJson; + } +} + +/** Parse JSON keeping each number's digits, which `JSON.stringify` then writes back unchanged. */ +function parseExactJson(text: string): ExactJson { + return JSON.parse(text, (_key, value: ExactJson | number, context: { source?: string }) => + typeof value === 'number' ? JSON.rawJSON(context.source ?? String(value)) : value, + ); +} + +/** A PostgreSQL text array as node-postgres parses it: elements, `NULL`s and nested arrays. */ +type PgTextArray = Array; +type PgJsonArray = Array; + +function parseExactJsonElements(values: PgTextArray): PgJsonArray { + return values.map((value) => + Array.isArray(value) + ? parseExactJsonElements(value) + : value === null + ? null + : parseExactJson(value), + ); +} + +// PostgreSQL type OIDs. pg's `TypeId` lists only the base types, not arrays. +const PG_TEXT_ARRAY = 1009; +const PG_NUMERIC_ARRAY = 1231; +const PG_JSON = 114; +const PG_JSONB = 3802; +const PG_JSON_ARRAY = 199; +const PG_JSONB_ARRAY = 3807; + +/** + * Type parsers for `void db execute --json` on PostgreSQL. node-postgres reads `numeric[]` + * elements as numbers and JSON with `JSON.parse`, which round what a double cannot hold. Here a + * `numeric[]` element stays a string, like a `numeric`, and a JSON number keeps its digits. + */ +export function pgJsonTypes(types: CustomTypesConfig): CustomTypesConfig { + const parseTextArray = types.getTypeParser(PG_TEXT_ARRAY as CustomTypeId, 'text') as ( + value: string, + ) => PgTextArray; + const parsers = new Map ExactJson | PgJsonArray | PgTextArray>([ + [PG_NUMERIC_ARRAY, parseTextArray], + [PG_JSON, parseExactJson], + [PG_JSONB, parseExactJson], + [PG_JSON_ARRAY, (value) => parseExactJsonElements(parseTextArray(value))], + [PG_JSONB_ARRAY, (value) => parseExactJsonElements(parseTextArray(value))], + ]); + return { + getTypeParser(oid, format = 'text') { + const parser = format === 'text' ? parsers.get(oid) : undefined; + // oxlint-disable-next-line typescript/no-unsafe-return -- Other types keep node-postgres's own parsers. + return parser ?? types.getTypeParser(oid, format); + }, + }; +} + +type CustomTypeId = Parameters[0]; + /** * node-postgres returns one result for one statement and an array for several. SQL without a * statement returns an empty-query result with no command, which is left out. @@ -211,6 +299,46 @@ function mySqlStatementResult(value: unknown): StatementResult { : { results: [], success: true, meta: mySqlHeaderMeta(value) }; } +/** + * The words, semicolons and other characters of MySQL SQL, lowercased, outside comments. A + * quoted string or name, and a comment that opens with `/*!` or `/*+`, which MySQL reads as SQL, + * each count as one empty word. + */ +function* mySqlWords(sql: string): Generator { + const word = /[\w$\u0080-￿]+/uy; + let index = 0; + while (index < sql.length) { + const character = sql[index]; + const next = sql[index + 1]; + if (character === "'" || character === '"' || character === '`') { + index = skipMySqlQuoted(sql, index, character); + yield ''; + } else if ( + character === '#' || + // MySQL reads `--` as a comment only when whitespace or a control character follows it. + (character === '-' && next === '-' && !/\S/u.test(sql[index + 2] ?? ' ')) + ) { + const newline = sql.indexOf('\n', index); + index = newline === -1 ? sql.length : newline; + } else if (character === '/' && next === '*') { + const close = sql.indexOf('*/', index + 2); + const executable = sql[index + 2] === '!' || sql[index + 2] === '+'; + index = close === -1 ? sql.length : close + 2; + if (executable) { + yield ''; + } + } else if (/\s/u.test(character)) { + index++; + } else { + word.lastIndex = index; + const match = word.exec(sql); + const token = match ? match[0] : character; + index += token.length; + yield token.toLowerCase(); + } + } +} + /** * Tell which MySQL statements are `CALL`s. Statements end at top-level semicolons; a stored * program body (`BEGIN ... END`) and a `CASE ... END` hold semicolons or an `END` of their own, @@ -232,43 +360,28 @@ export function mySqlCallStatements(sql: string): Array { firstWord = undefined; afterEnd = false; }; - for (const segment of tokenizeSql(sql)) { - if (segment.kind === 'line-comment' || segment.kind === 'block-comment') { - continue; - } - if (segment.kind !== 'sql') { - firstWord ??= ''; + for (const word of mySqlWords(sql)) { + if (word === ';') { afterEnd = false; + if (depth === 0) { + finish(); + } continue; } - const text = sql.slice(segment.start, segment.end); - for (const [token] of text.matchAll(/;|\s+|[\w$\u0080-￿]+|./gu)) { - if (/^\s/u.test(token)) { - continue; - } - const word = token.toLowerCase(); - if (word === ';') { - afterEnd = false; - if (depth === 0) { - finish(); - } - continue; - } - const closedBlock = afterEnd; - afterEnd = false; - if (closedBlock && /^(?:if|loop|while|repeat)$/.test(word)) { - // That END closed an IF or loop, which never opened a level, so restore it. - depth++; - } else if (closedBlock && word === 'case') { - // END CASE closes the CASE that opened a level. - } else if (word === 'case' || (word === 'begin' && (depth > 0 || firstWord !== undefined))) { - depth++; - } else if (word === 'end' && depth > 0) { - depth--; - afterEnd = true; - } - firstWord ??= word; + const closedBlock = afterEnd; + afterEnd = false; + if (closedBlock && /^(?:if|loop|while|repeat)$/.test(word)) { + // That END closed an IF or loop, which never opened a level, so restore it. + depth++; + } else if (closedBlock && word === 'case') { + // END CASE closes the CASE that opened a level. + } else if (word === 'case' || (word === 'begin' && (depth > 0 || firstWord !== undefined))) { + depth++; + } else if (word === 'end' && depth > 0) { + depth--; + afterEnd = true; } + firstWord ??= word; } finish(); return calls; diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index d1e298712..0978315a0 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -50,6 +50,7 @@ import type { DbArgs } from './db-args.ts'; import { formatStatementResults, mySqlStatementResults, + pgJsonTypes, pgStatementResults, runSqliteStatements, splitSqliteStatements, @@ -918,8 +919,12 @@ async function executeExternalSql( json: boolean, ): Promise { if (dialect === 'postgresql') { - const { Client } = await import('pg'); - const pgClient = new Client({ connectionString: dbUrl }); + const { Client, types } = await import('pg'); + const pgClient = new Client({ + connectionString: dbUrl, + // numeric[] and JSON values keep their digits. + ...(json ? { types: pgJsonTypes(types) } : {}), + }); await pgClient.connect(); try { // node-postgres resolves to an array of results when the SQL holds several statements. diff --git a/packages/void/src/runtime/db/migrations/mysql-sql.ts b/packages/void/src/runtime/db/migrations/mysql-sql.ts index d9d7c684f..997eaab04 100644 --- a/packages/void/src/runtime/db/migrations/mysql-sql.ts +++ b/packages/void/src/runtime/db/migrations/mysql-sql.ts @@ -71,7 +71,7 @@ function splitMySqlStatements(sql: string): Array { const next = sql[index + 1]; if (character === "'" || character === '"' || character === '`') { - const close = skipQuoted(sql, index, character); + const close = skipMySqlQuoted(sql, index, character); take(index, close); bare += ' '; index = close; @@ -127,7 +127,7 @@ function splitMySqlStatements(sql: string): Array { } /** The index after the quoted string or name that opens at `open`. */ -function skipQuoted(sql: string, open: number, quote: string): number { +export function skipMySqlQuoted(sql: string, open: number, quote: string): number { let index = open + 1; while (index < sql.length) { const character = sql[index]; diff --git a/packages/void/test/unit/cf-access.test.ts b/packages/void/test/unit/cf-access.test.ts index a0a94860b..eb2985499 100644 --- a/packages/void/test/unit/cf-access.test.ts +++ b/packages/void/test/unit/cf-access.test.ts @@ -271,9 +271,11 @@ describe('origin-scoped self-hosted Access login', () => { Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: stdoutTty }); } expect(spawnSyncMock.mock.calls.map((call) => call[1])).toEqual([ - ['access', 'login', 'https://api.example.com'], + ['access', 'login', '--quiet', 'https://api.example.com'], ['access', 'token', '-app=https://api.example.com'], ]); + // The browser login keeps the JWT and its messages off stdout. + expect(spawnSyncMock.mock.calls[0]?.[2]).toMatchObject({ stdio: ['inherit', 2, 'inherit'] }); expect(cfAccessHeaders(process.env, 'https://api.example.com')).toEqual({ 'cf-access-token': fresh, }); diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index b69fbe6b9..62aae755f 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -34,13 +34,14 @@ vi.mock('node:child_process', () => ({ vi.mock('pg', async (importOriginal) => { // Keep pg's own connection-string parsing; stub only the network calls. - class Client extends (await importOriginal()).Client {} + const pg = await importOriginal(); + class Client extends pg.Client {} Object.assign(Client.prototype, { async connect() {}, async end() {}, query: (sql: string) => mockPgQuery(sql), }); - return { Client }; + return { Client, types: pg.types }; }); const mysqlQueries = vi.hoisted((): Array => []); @@ -986,6 +987,17 @@ describe('void db execute', () => { expect(vi.mocked(console.log)).not.toHaveBeenCalled(); }); + it('reports trailing input SQLite rejects instead of ignoring it', async () => { + const root = await createLocalSqliteProject(); + + for (const command of ['SELECT 1;/*', 'SELECT 1; ']) { + await expect( + runDbCommand(root, { action: 'execute', command, json: true }), + ).rejects.toThrow('syntax error'); + } + expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + }); + it('prints an empty array for SQL without a statement', async () => { const root = await createLocalSqliteProject(); diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index 45ec27301..646151c8d 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -1,6 +1,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import type { CustomTypesConfig } from 'pg'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { Buffer } from '../../src/cli/node-buffer.ts'; @@ -75,8 +76,14 @@ const mockPgQuery = vi.fn<() => Promise<{ rows: Array> } Promise.resolve({ rows: [] }), ); -vi.mock('pg', () => ({ +const mockPgClient = vi.fn((_options: Record) => undefined); + +vi.mock('pg', async (importOriginal) => ({ + types: (await importOriginal()).types, Client: class { + constructor(options: Record) { + mockPgClient(options); + } connect = mockPgConnect; end = mockPgEnd; query = mockPgQuery; @@ -871,6 +878,21 @@ describe('void db execute --remote (PostgreSQL)', () => { ); }); + it('keeps PostgreSQL numeric arrays and JSON numbers exact with --json only', async () => { + const root = createProjectRoot({ database: 'pg' }); + mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); + const parserFor = (oid: number) => { + const options = mockPgClient.mock.lastCall?.[0] as { types?: CustomTypesConfig } | undefined; + return options?.types?.getTypeParser(oid, 'text') as ((value: string) => unknown) | undefined; + }; + + await runDbCommand(root, { action: 'execute', command: 'SELECT 1', remote: true, json: true }); + expect(parserFor(1231)?.('{1234567890123456789.987}')).toEqual(['1234567890123456789.987']); + + await runDbCommand(root, { action: 'execute', command: 'SELECT 1', remote: true }); + expect(parserFor(1231)).toBeUndefined(); + }); + it('prints every statement of a multi-statement query with --json', async () => { const root = createProjectRoot({ database: 'pg' }); mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index add09af02..33c16c4cd 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -1,8 +1,10 @@ +import { types } from 'pg'; import { describe, expect, it } from 'vite-plus/test'; import { formatStatementResults, mySqlCallStatements, mySqlStatementResults, + pgJsonTypes, pgStatementResults, splitSqliteStatements, } from '../../src/cli/db-execute-results.ts'; @@ -80,6 +82,33 @@ describe('db execute --json results', () => { ]); }); + it('keeps the digits of PostgreSQL numeric arrays and JSON numbers', () => { + const parsers = pgJsonTypes(types); + const parse = (oid: number, text: string) => + (parsers.getTypeParser(oid, 'text') as (value: string) => object | string | number | null)( + text, + ); + // The value as `--json` prints it, without whitespace. + const value = (oid: number, text: string) => + formatStatementResults([{ results: [{ v: parse(oid, text) }], success: true, meta: {} }]) + .replaceAll(/\s/g, '') + .slice('[{"results":[{"v":'.length, -'}],"success":true,"meta":{}}]'.length); + // numeric[] elements stay strings, like a numeric. + expect(value(1231, '{1234567890123456789.987,NULL}')).toBe('["1234567890123456789.987",null]'); + // json and jsonb numbers print with the digits the database sent. + expect(value(3802, '{"a": 9007199254740993, "b": [1.50, "x", null, true]}')).toBe( + '{"a":9007199254740993,"b":[1.50,"x",null,true]}', + ); + expect(value(114, '0.1000000000000000000001')).toBe('0.1000000000000000000001'); + expect(value(3807, String.raw`{"{\"a\": 9007199254740993}",NULL}`)).toBe( + '[{"a":9007199254740993},null]', + ); + expect(value(199, '{{"1e400"}}')).toBe('[[1e400]]'); + // Other types keep node-postgres's parsers. + expect(parse(23, '5')).toBe(5); + expect(parse(20, '9007199254740993')).toBe('9007199254740993'); + }); + it('leaves out the empty-query result of SQL without a statement', () => { expect(pgStatementResults({ command: null, rowCount: null, rows: [] })).toEqual([]); }); @@ -99,6 +128,13 @@ describe('db execute --json results', () => { ).toHaveLength(1); // A transaction's BEGIN and END are statements of their own. expect(splitSqliteStatements('BEGIN; INSERT INTO a VALUES (1); END;')).toHaveLength(3); + // SQLite rejects a bare `/*` at the end and characters it does not count as whitespace, so + // they stay as statements that fail. A block comment left open is still a comment. + expect(splitSqliteStatements('SELECT 1;/*')).toEqual(['SELECT 1;', '/*']); + expect(splitSqliteStatements('SELECT 1;\u00a0')).toEqual(['SELECT 1;', '\u00a0']); + expect(splitSqliteStatements('SELECT 1;\v')).toEqual(['SELECT 1;', '\v']); + expect(splitSqliteStatements('SELECT 1; /* open')).toEqual(['SELECT 1;']); + expect(splitSqliteStatements('SELECT 1;\t\n\f\r ')).toEqual(['SELECT 1;']); // A trigger missing its END stays open for SQLite to report. expect( splitSqliteStatements('CREATE TRIGGER t AFTER INSERT ON a BEGIN SELECT 1;'), @@ -167,6 +203,23 @@ describe('db execute --json results', () => { ]); }); + it('reads MySQL comments and quoted text the way MySQL does', () => { + expect(mySqlCallStatements('# note\nCALL report()')).toEqual([true]); + expect(mySqlCallStatements(String.raw`SELECT 'it\'s; ok'; CALL p()`)).toEqual([false, true]); + expect(mySqlCallStatements(String.raw`SELECT "a\";b"; CALL p()`)).toEqual([false, true]); + // `--` starts a comment only before whitespace, so `1--1` is arithmetic. + expect(mySqlCallStatements('SELECT 1--1; -- x;\nCALL p()')).toEqual([false, true]); + // MySQL runs the SQL in a `/*!` comment, and `[` quotes nothing. + expect(mySqlCallStatements('/*!40101 SET @a = 1 */; SELECT [1; CALL p()')).toEqual([ + false, + false, + true, + ]); + expect( + mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], '# note\nCALL report()'), + ).toEqual([{ results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }]); + }); + it('finds MySQL statements around stored program bodies', () => { expect( mySqlCallStatements( From 7387f6930a87c2adc1d1563c83bc8a70997b56da Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 14:45:32 +0530 Subject: [PATCH 04/11] fix(cli): read `void db execute --json` SQL the way each database does - SQLite: a byte-order mark where a token starts is whitespace, so a file that begins with one keeps its `CREATE TRIGGER` whole. - MySQL: grouping a `CALL`'s results follows the server's sql_mode and version, read only when the SQL holds a backslash or a `/*!` comment. With NO_BACKSLASH_ESCAPES a backslash is an ordinary character, and a version comment counts only on a server that runs it. - MySQL: a control character after `--` starts a comment, and `/*+` hints outside a statement are ordinary comments. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-execute-results.ts | 99 +++++++++++++++---- packages/void/src/cli/db.ts | 12 ++- .../src/runtime/db/migrations/mysql-sql.ts | 14 ++- .../void/test/unit/db-execute-remote.test.ts | 35 +++++++ .../void/test/unit/db-execute-results.test.ts | 48 +++++++++ 5 files changed, 184 insertions(+), 24 deletions(-) diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index ca6c6dbda..36c3a2677 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -115,13 +115,14 @@ export function sqliteStatementRanges(sql: string): Array { continue; } const text = sql.slice(segment.start, segment.end); - // SQLite's whitespace is these five characters; anything else, such as a nonbreaking - // space, is part of a statement and fails there. - for (const match of text.matchAll(/;|[ \t\n\f\r]+|[\w$\u0080-￿]+|./gu)) { + // SQLite's whitespace is these five characters, and a byte-order mark where a token would + // start; anything else, such as a nonbreaking space, is part of a statement and fails there. + // A byte-order mark inside a word is part of the word, as it is for SQLite. + for (const match of text.matchAll(/;|[ \t\n\f\r\uFEFF]+|[\w$\u0080-￿]+|./gu)) { const [token] = match; if (token === ';') { advance(0, segment.start + match.index); - } else if (!/^[ \t\n\f\r]/u.test(token)) { + } else if (!/^[ \t\n\f\r\uFEFF]/u.test(token)) { advance(keywords.get(token.toLowerCase()) ?? 1, segment.start + match.index); } } @@ -300,34 +301,88 @@ function mySqlStatementResult(value: unknown): StatementResult { } /** - * The words, semicolons and other characters of MySQL SQL, lowercased, outside comments. A - * quoted string or name, and a comment that opens with `/*!` or `/*+`, which MySQL reads as SQL, - * each count as one empty word. + * How the server reads SQL. `version` is its version as MySQL writes it in a `/*!` comment + * (80403 for 8.4.3), and `backslashEscapes` is false in `NO_BACKSLASH_ESCAPES` mode. */ -function* mySqlWords(sql: string): Generator { +export type MySqlServerMode = { version: number; backslashEscapes: boolean }; + +/** Reads what `mySqlServerMode()` needs. It only matters for SQL that `needsMySqlServerMode` finds. */ +export const MYSQL_SERVER_MODE_QUERY = + 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version'; + +/** Whether the SQL holds a backslash or a version comment, which read differently per server. */ +export function needsMySqlServerMode(sql: string): boolean { + return sql.includes('\\') || sql.includes('/*!'); +} + +/** Read the row `MYSQL_SERVER_MODE_QUERY` returns. */ +export function mySqlServerMode(rows: unknown): MySqlServerMode { + const row: unknown = Array.isArray(rows) ? rows[0] : undefined; + const fields = (typeof row === 'object' && row !== null ? row : {}) as Record; + const modes = typeof fields.sql_mode === 'string' ? fields.sql_mode.split(',') : []; + const version = /^(\d+)\.(\d+)\.(\d+)/.exec(String(fields.version ?? '')); + return { + // A server whose version does not read as one runs every version comment. + version: version + ? Number(version[1]) * 10_000 + Number(version[2]) * 100 + Number(version[3]) + : Number.POSITIVE_INFINITY, + backslashEscapes: !modes.includes('NO_BACKSLASH_ESCAPES'), + }; +} + +/** Whether the character after `--` (`NaN` at the end of the input) makes it a comment. */ +function startsMySqlDashComment(code: number): boolean { + // Whitespace or a control character, as MySQL's lexer checks. + return Number.isNaN(code) || code <= 0x20 || code === 0x7f; +} + +const MYSQL_DEFAULT_MODE: MySqlServerMode = { + version: Number.POSITIVE_INFINITY, + backslashEscapes: true, +}; + +/** + * The words, semicolons and other characters of MySQL SQL, lowercased, outside comments, with + * a quoted string or name as one empty word. The SQL in a `/*!` comment counts when the server + * runs it: always without a version, else when the server is at least that version (six digits + * when whitespace follows them, otherwise five). + */ +function* mySqlWords(sql: string, mode: MySqlServerMode): Generator { const word = /[\w$\u0080-￿]+/uy; + const versionDigits = /!(?:(\d{6})(?=\s)|(\d{5}))?/y; let index = 0; + // Inside a `/*!` comment whose SQL the server runs, so its `*/` is skipped. + let inVersionComment = false; while (index < sql.length) { const character = sql[index]; const next = sql[index + 1]; if (character === "'" || character === '"' || character === '`') { - index = skipMySqlQuoted(sql, index, character); + index = skipMySqlQuoted(sql, index, character, mode.backslashEscapes); yield ''; } else if ( character === '#' || - // MySQL reads `--` as a comment only when whitespace or a control character follows it. - (character === '-' && next === '-' && !/\S/u.test(sql[index + 2] ?? ' ')) + // MySQL reads `--` as a comment only when whitespace or a control character, or the end of + // the input, follows it. + (character === '-' && next === '-' && startsMySqlDashComment(sql.charCodeAt(index + 2))) ) { const newline = sql.indexOf('\n', index); index = newline === -1 ? sql.length : newline; + } else if (inVersionComment && character === '*' && next === '/') { + inVersionComment = false; + index += 2; } else if (character === '/' && next === '*') { - const close = sql.indexOf('*/', index + 2); - const executable = sql[index + 2] === '!' || sql[index + 2] === '+'; - index = close === -1 ? sql.length : close + 2; - if (executable) { - yield ''; + versionDigits.lastIndex = index + 2; + const version = sql[index + 2] === '!' ? versionDigits.exec(sql) : null; + const required = version?.[1] ?? version?.[2]; + if (version && (required === undefined || Number(required) <= mode.version)) { + inVersionComment = true; + index = versionDigits.lastIndex; + } else { + // Any other comment, an optimizer hint (`/*+`) too, holds no statement. + const close = sql.indexOf('*/', index + 2); + index = close === -1 ? sql.length : close + 2; } - } else if (/\s/u.test(character)) { + } else if (/[ \t\n\v\f\r]/u.test(character)) { index++; } else { word.lastIndex = index; @@ -346,7 +401,10 @@ function* mySqlWords(sql: string): Generator { * a `BEGIN`, so they do not change the depth. A `BEGIN` that opens a top-level statement starts * a transaction, not a block. */ -export function mySqlCallStatements(sql: string): Array { +export function mySqlCallStatements( + sql: string, + mode: MySqlServerMode = MYSQL_DEFAULT_MODE, +): Array { const calls: Array = []; let depth = 0; let firstWord: string | undefined; @@ -360,7 +418,7 @@ export function mySqlCallStatements(sql: string): Array { firstWord = undefined; afterEnd = false; }; - for (const word of mySqlWords(sql)) { + for (const word of mySqlWords(sql, mode)) { if (word === ';') { afterEnd = false; if (depth === 0) { @@ -397,6 +455,7 @@ export function mySqlStatementResults( rows: unknown, fields: unknown, sql: string, + mode: MySqlServerMode = MYSQL_DEFAULT_MODE, ): Array { const severalResults = Array.isArray(rows) && @@ -409,7 +468,7 @@ export function mySqlStatementResults( const grouped: Array = []; let index = 0; let matched = true; - for (const isCall of mySqlCallStatements(sql)) { + for (const isCall of mySqlCallStatements(sql, mode)) { if (!isCall) { matched &&= index < entries.length; grouped.push(mySqlStatementResult(entries[index++])); diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 0978315a0..e4c4a86a2 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -49,7 +49,10 @@ import { PlatformApiError, PlatformClient } from './client.ts'; import type { DbArgs } from './db-args.ts'; import { formatStatementResults, + MYSQL_SERVER_MODE_QUERY, + mySqlServerMode, mySqlStatementResults, + needsMySqlServerMode, pgJsonTypes, pgStatementResults, runSqliteStatements, @@ -949,9 +952,16 @@ async function executeExternalSql( ...(json ? { supportBigNumbers: true, bigNumberStrings: false } : {}), }); try { + // Grouping a CALL's results reads the SQL the way this server does: its sql_mode decides + // what a backslash means, and its version which `/*!` comments run. A SET of sql_mode in + // the SQL itself is not followed. + const mode = + json && needsMySqlServerMode(sql) + ? mySqlServerMode((await mySqlClient.query(MYSQL_SERVER_MODE_QUERY))[0]) + : undefined; const [rows, fields] = await mySqlClient.query(sql); if (json) { - printStatementResults(mySqlStatementResults(rows, fields, sql)); + printStatementResults(mySqlStatementResults(rows, fields, sql, mode)); } else if (Array.isArray(rows) && rows.length > 0) { printTable(rows as Array>); } diff --git a/packages/void/src/runtime/db/migrations/mysql-sql.ts b/packages/void/src/runtime/db/migrations/mysql-sql.ts index 997eaab04..a8a7b4de8 100644 --- a/packages/void/src/runtime/db/migrations/mysql-sql.ts +++ b/packages/void/src/runtime/db/migrations/mysql-sql.ts @@ -126,13 +126,21 @@ function splitMySqlStatements(sql: string): Array { return statements; } -/** The index after the quoted string or name that opens at `open`. */ -export function skipMySqlQuoted(sql: string, open: number, quote: string): number { +/** + * The index after the quoted string or name that opens at `open`. Pass `backslashEscapes: false` + * for a server in `NO_BACKSLASH_ESCAPES` mode, where a backslash is an ordinary character. + */ +export function skipMySqlQuoted( + sql: string, + open: number, + quote: string, + backslashEscapes = true, +): number { let index = open + 1; while (index < sql.length) { const character = sql[index]; // Backslash escapes apply in strings, not in backtick-quoted names. - if (character === '\\' && quote !== '`') { + if (character === '\\' && quote !== '`' && backslashEscapes) { index += 2; continue; } diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index 646151c8d..a7f076383 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -878,6 +878,41 @@ describe('void db execute --remote (PostgreSQL)', () => { ); }); + it("groups a MySQL CALL's results by the server's sql_mode", async () => { + const root = createProjectRoot({ database: 'mysql' }); + mockGetDatabaseUrl.mockResolvedValue({ url: 'mysql://host/db' }); + const header = { fieldCount: 0, affectedRows: 0, insertId: 0 }; + mockMySqlQuery.mockImplementation((sql) => + Promise.resolve( + sql.startsWith('SELECT @@SESSION.sql_mode') + ? [[{ sql_mode: 'NO_BACKSLASH_ESCAPES', version: '8.4.3' }], [{ name: 'sql_mode' }]] + : [ + [[{ a: '\\' }], [{ b: 2 }], header], + [[{ name: 'a' }], [{ name: 'b' }], undefined], + ], + ), + ); + const command = String.raw`SELECT '\'; CALL p()`; + + await runDbCommand(root, { action: 'execute', command, remote: true, json: true }); + + expect(mockMySqlQuery.mock.calls.map(([sql]) => sql)).toEqual([ + 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version', + command, + ]); + expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + { results: [{ a: '\\' }], success: true, meta: {} }, + { results: [{ b: 2 }], success: true, meta: { affectedRows: 0, insertId: 0 } }, + ]); + + // SQL without a backslash or a version comment, and the table, need no extra query. + mockMySqlQuery.mockClear(); + await runDbCommand(root, { action: 'execute', command: 'CALL p()', remote: true, json: true }); + await runDbCommand(root, { action: 'execute', command, remote: true }); + expect(mockMySqlQuery.mock.calls.map(([sql]) => sql)).toEqual(['CALL p()', command]); + mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); + }); + it('keeps PostgreSQL numeric arrays and JSON numbers exact with --json only', async () => { const root = createProjectRoot({ database: 'pg' }); mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index 33c16c4cd..17dcd18ad 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -3,8 +3,10 @@ import { describe, expect, it } from 'vite-plus/test'; import { formatStatementResults, mySqlCallStatements, + mySqlServerMode, mySqlStatementResults, pgJsonTypes, + needsMySqlServerMode, pgStatementResults, splitSqliteStatements, } from '../../src/cli/db-execute-results.ts'; @@ -135,6 +137,10 @@ describe('db execute --json results', () => { expect(splitSqliteStatements('SELECT 1;\v')).toEqual(['SELECT 1;', '\v']); expect(splitSqliteStatements('SELECT 1; /* open')).toEqual(['SELECT 1;']); expect(splitSqliteStatements('SELECT 1;\t\n\f\r ')).toEqual(['SELECT 1;']); + // A byte-order mark where a token starts is whitespace to SQLite, so it hides no keyword. + const bomTrigger = '\uFEFFCREATE TRIGGER t AFTER INSERT ON a BEGIN SELECT 1; END;'; + expect(splitSqliteStatements(`${bomTrigger} SELECT 2;`)).toEqual([bomTrigger, ' SELECT 2;']); + expect(splitSqliteStatements('SELECT 1;\uFEFF')).toEqual(['SELECT 1;']); // A trigger missing its END stays open for SQLite to report. expect( splitSqliteStatements('CREATE TRIGGER t AFTER INSERT ON a BEGIN SELECT 1;'), @@ -215,11 +221,53 @@ describe('db execute --json results', () => { false, true, ]); + // A control character after `--` starts a comment too. + expect(mySqlCallStatements('SELECT 1; --\u0001 x;\nCALL p()')).toEqual([false, true]); + expect(mySqlCallStatements('SELECT 1; --')).toEqual([false]); + // An optimizer hint outside a statement is an ordinary comment. + expect(mySqlCallStatements('/*+ BKA(t) */ CALL p()')).toEqual([true]); expect( mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], '# note\nCALL report()'), ).toEqual([{ results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }]); }); + it('reads MySQL SQL the way the server it runs on does', () => { + const mysql84 = mySqlServerMode([{ sql_mode: 'STRICT_TRANS_TABLES', version: '8.4.3' }]); + expect(mysql84).toEqual({ version: 80_403, backslashEscapes: true }); + const noEscapes = mySqlServerMode([ + { sql_mode: 'STRICT_TRANS_TABLES,NO_BACKSLASH_ESCAPES', version: '10.11.6-MariaDB' }, + ]); + expect(noEscapes).toEqual({ version: 101_106, backslashEscapes: false }); + // With NO_BACKSLASH_ESCAPES, a backslash before a quote is an ordinary character. + const backslash = String.raw`SELECT '\'; CALL p()`; + expect(mySqlCallStatements(backslash, noEscapes)).toEqual([false, true]); + expect(mySqlCallStatements(backslash, mysql84)).toEqual([false]); + expect( + mySqlStatementResults( + [[{ a: 1 }], [{ b: 2 }], header], + [[field], [field], undefined], + backslash, + noEscapes, + ), + ).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + { results: [{ b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + // The server skips a version comment for a later version and runs one for its own. + expect(mySqlCallStatements('/*!99999 SET @n = 1 */ CALL p()', mysql84)).toEqual([true]); + expect(mySqlCallStatements('/*!80403 SET @n = 1 */ CALL p()', mysql84)).toEqual([false]); + expect(mySqlCallStatements('/*! CALL p() */', mysql84)).toEqual([true]); + expect(mySqlCallStatements('/*!40101 CALL p() */; SELECT 1', mysql84)).toEqual([true, false]); + // Six digits are a version when whitespace follows them; otherwise five are. + expect(mySqlCallStatements('/*!100000 SET @n = 1 */ CALL p()', mysql84)).toEqual([true]); + expect(mySqlCallStatements('/*!800001 CALL p() */ SELECT 1', mysql84)).toEqual([false]); + expect(mySqlCallStatements('/*!800001; CALL p() */', mysql84)).toEqual([false, true]); + expect(mySqlCallStatements('/*!80000CALL p() */', mysql84)).toEqual([true]); + expect(needsMySqlServerMode('SELECT 1; CALL p()')).toBe(false); + expect(needsMySqlServerMode(backslash)).toBe(true); + expect(needsMySqlServerMode('/*!80000 SET @n = 1 */')).toBe(true); + }); + it('finds MySQL statements around stored program bodies', () => { expect( mySqlCallStatements( From 66df40cdf09b89a469c919e74005915aafc48888 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 15:00:03 +0530 Subject: [PATCH 05/11] fix(cli): match MySQL and MariaDB lexing when grouping `void db execute --json` CALL results - Read the server mode on a separate connection so the user's session state (FOUND_ROWS(), ROW_COUNT(), warnings) is untouched. - Treat BEGIN as a block opener only in stored programs and MariaDB's BEGIN NOT ATOMIC, not as a column name or XA BEGIN. - Follow MariaDB's executable comments: /*M!, six-digit versions, and skipping /*! comments for versions 50700 to 99999. - Read double quotes as identifiers in ANSI_QUOTES mode. - Allow one nested comment inside a skipped version comment. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-execute-results.ts | 153 ++++++++++++++---- packages/void/src/cli/db.ts | 21 ++- .../void/test/unit/db-execute-remote.test.ts | 6 + .../void/test/unit/db-execute-results.test.ts | 111 ++++++++++++- 4 files changed, 251 insertions(+), 40 deletions(-) diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index 36c3a2677..ddee1e547 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -301,18 +301,28 @@ function mySqlStatementResult(value: unknown): StatementResult { } /** - * How the server reads SQL. `version` is its version as MySQL writes it in a `/*!` comment - * (80403 for 8.4.3), and `backslashEscapes` is false in `NO_BACKSLASH_ESCAPES` mode. + * How the server reads SQL. `version` is its version as a `/*!` comment writes it (80403 for + * 8.4.3), `backslashEscapes` is false in `NO_BACKSLASH_ESCAPES` mode, `ansiQuotes` is true in + * `ANSI_QUOTES` mode, and `mariaDb` tells MariaDB, which reads executable comments its own way. */ -export type MySqlServerMode = { version: number; backslashEscapes: boolean }; +export type MySqlServerMode = { + version: number; + backslashEscapes: boolean; + ansiQuotes: boolean; + mariaDb: boolean; +}; /** Reads what `mySqlServerMode()` needs. It only matters for SQL that `needsMySqlServerMode` finds. */ export const MYSQL_SERVER_MODE_QUERY = 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version'; -/** Whether the SQL holds a backslash or a version comment, which read differently per server. */ +/** + * Whether the SQL holds a backslash or an executable comment, which read differently per + * server. Without a backslash, `ANSI_QUOTES` changes what a double-quoted text is but not + * where it ends. + */ export function needsMySqlServerMode(sql: string): boolean { - return sql.includes('\\') || sql.includes('/*!'); + return sql.includes('\\') || /\/\*M?!/u.test(sql); } /** Read the row `MYSQL_SERVER_MODE_QUERY` returns. */ @@ -320,13 +330,16 @@ export function mySqlServerMode(rows: unknown): MySqlServerMode { const row: unknown = Array.isArray(rows) ? rows[0] : undefined; const fields = (typeof row === 'object' && row !== null ? row : {}) as Record; const modes = typeof fields.sql_mode === 'string' ? fields.sql_mode.split(',') : []; - const version = /^(\d+)\.(\d+)\.(\d+)/.exec(String(fields.version ?? '')); + const versionText = String(fields.version ?? ''); + const version = /^(\d+)\.(\d+)\.(\d+)/.exec(versionText); return { // A server whose version does not read as one runs every version comment. version: version ? Number(version[1]) * 10_000 + Number(version[2]) * 100 + Number(version[3]) : Number.POSITIVE_INFINITY, backslashEscapes: !modes.includes('NO_BACKSLASH_ESCAPES'), + ansiQuotes: modes.includes('ANSI_QUOTES'), + mariaDb: /mariadb/iu.test(versionText), }; } @@ -336,29 +349,71 @@ function startsMySqlDashComment(code: number): boolean { return Number.isNaN(code) || code <= 0x20 || code === 0x7f; } +/** + * The index after the comment whose text starts at `index`. A skipped version comment may hold + * one nested comment (`nesting` 1); any other comment ends at its first closing marker. + */ +function skipMySqlComment(sql: string, index: number, nesting: number): number { + while (index < sql.length) { + const character = sql[index++]; + if (nesting > 0 && character === '/' && sql[index] === '*') { + index = skipMySqlComment(sql, index + 1, nesting - 1); + } else if (character === '*' && sql[index] === '/') { + return index + 1; + } + } + return sql.length; +} + +// After `/*`: MySQL reads six digits as a version when whitespace follows them, otherwise five. +// MariaDB reads six when a sixth digit follows, and its own `/*M!` comments too. +const MYSQL_VERSION_COMMENT = /!(?:(\d{6})(?=\s)|(\d{5}))?/y; +const MARIADB_VERSION_COMMENT = /(M?)!(?:(\d{6})|(\d{5}))?/y; + +/** The index after the marker of an executable comment the server runs at `index`, if any. */ +function runsMySqlComment(sql: string, index: number, mode: MySqlServerMode): number | undefined { + const marker = mode.mariaDb ? MARIADB_VERSION_COMMENT : MYSQL_VERSION_COMMENT; + marker.lastIndex = index; + const match = marker.exec(sql); + if (!match) { + return undefined; + } + const digits = mode.mariaDb ? (match[2] ?? match[3]) : (match[1] ?? match[2]); + if (digits === undefined) { + return marker.lastIndex; + } + const required = Number(digits); + // MariaDB skips `/*!` comments for MySQL 5.7 and later (50700 to 99999), not its own `/*M!`. + const mySqlOnly = mode.mariaDb && match[1] !== 'M' && required >= 50_700 && required <= 99_999; + return required <= mode.version && !mySqlOnly ? marker.lastIndex : undefined; +} + const MYSQL_DEFAULT_MODE: MySqlServerMode = { version: Number.POSITIVE_INFINITY, backslashEscapes: true, + ansiQuotes: false, + mariaDb: false, }; /** * The words, semicolons and other characters of MySQL SQL, lowercased, outside comments, with - * a quoted string or name as one empty word. The SQL in a `/*!` comment counts when the server - * runs it: always without a version, else when the server is at least that version (six digits - * when whitespace follows them, otherwise five). + * a quoted string or name as one empty word. The SQL in an executable comment (`/*!`, and + * `/*M!` on MariaDB) counts when the server runs it. */ -function* mySqlWords(sql: string, mode: MySqlServerMode): Generator { +function mySqlWords(sql: string, mode: MySqlServerMode): Array { const word = /[\w$\u0080-￿]+/uy; - const versionDigits = /!(?:(\d{6})(?=\s)|(\d{5}))?/y; + const words: Array = []; let index = 0; - // Inside a `/*!` comment whose SQL the server runs, so its `*/` is skipped. + // Inside an executable comment whose SQL the server runs, so its `*/` is skipped. let inVersionComment = false; while (index < sql.length) { const character = sql[index]; const next = sql[index + 1]; if (character === "'" || character === '"' || character === '`') { - index = skipMySqlQuoted(sql, index, character, mode.backslashEscapes); - yield ''; + // A backslash escapes nothing in a quoted name, `ANSI_QUOTES` double quotes included. + const name = character === '`' || (character === '"' && mode.ansiQuotes); + index = skipMySqlQuoted(sql, index, character, mode.backslashEscapes && !name); + words.push(''); } else if ( character === '#' || // MySQL reads `--` as a comment only when whitespace or a control character, or the end of @@ -371,16 +426,15 @@ function* mySqlWords(sql: string, mode: MySqlServerMode): Generator { inVersionComment = false; index += 2; } else if (character === '/' && next === '*') { - versionDigits.lastIndex = index + 2; - const version = sql[index + 2] === '!' ? versionDigits.exec(sql) : null; - const required = version?.[1] ?? version?.[2]; - if (version && (required === undefined || Number(required) <= mode.version)) { + const executable = /^M?!/u.test(sql.slice(index + 2, index + 4)); + const runsFrom = executable ? runsMySqlComment(sql, index + 2, mode) : undefined; + if (runsFrom !== undefined) { inVersionComment = true; - index = versionDigits.lastIndex; + index = runsFrom; } else { - // Any other comment, an optimizer hint (`/*+`) too, holds no statement. - const close = sql.indexOf('*/', index + 2); - index = close === -1 ? sql.length : close + 2; + // Any other comment, an optimizer hint (`/*+`) too, holds no statement. One the server + // skips for its version may nest a comment. + index = skipMySqlComment(sql, index + 2, executable ? 1 : 0); } } else if (/[ \t\n\v\f\r]/u.test(character)) { index++; @@ -389,25 +443,52 @@ function* mySqlWords(sql: string, mode: MySqlServerMode): Generator { const match = word.exec(sql); const token = match ? match[0] : character; index += token.length; - yield token.toLowerCase(); + words.push(token.toLowerCase()); } } + return words; } +// The object a CREATE statement makes, which tells a stored program from other DDL. +const MYSQL_STORED_PROGRAMS = new Set(['procedure', 'function', 'trigger', 'event']); +const MYSQL_OTHER_OBJECTS = new Set([ + 'database', + 'fulltext', + 'index', + 'logfile', + 'resource', + 'role', + 'schema', + 'sequence', + 'server', + 'spatial', + 'table', + 'tablespace', + 'temporary', + 'undo', + 'unique', + 'user', + 'view', +]); + /** - * Tell which MySQL statements are `CALL`s. Statements end at top-level semicolons; a stored - * program body (`BEGIN ... END`) and a `CASE ... END` hold semicolons or an `END` of their own, - * so they nest. `END IF`, `END LOOP`, `END WHILE` and `END REPEAT` close blocks that sit inside - * a `BEGIN`, so they do not change the depth. A `BEGIN` that opens a top-level statement starts - * a transaction, not a block. + * Tell which MySQL statements are `CALL`s. Statements end at top-level semicolons. In a stored + * program (`CREATE PROCEDURE`, `FUNCTION`, `TRIGGER` or `EVENT`), a `BEGIN ... END` body holds + * semicolons of its own, so it nests, as does MariaDB's `BEGIN NOT ATOMIC` block. Elsewhere + * `BEGIN` starts a transaction or is a name. A `CASE ... END` nests anywhere. `END IF`, + * `END LOOP`, `END WHILE` and `END REPEAT` close blocks that sit inside a `BEGIN`, so they do + * not change the depth. */ export function mySqlCallStatements( sql: string, mode: MySqlServerMode = MYSQL_DEFAULT_MODE, ): Array { + const words = mySqlWords(sql, mode); const calls: Array = []; let depth = 0; let firstWord: string | undefined; + // Whether this statement creates a stored program, once its CREATE names the object. + let storedProgram: boolean | undefined; // Set right after an END that closed a block, so a following IF, LOOP, WHILE, REPEAT or CASE // reads as part of that END. let afterEnd = false; @@ -416,9 +497,10 @@ export function mySqlCallStatements( calls.push(firstWord === 'call'); } firstWord = undefined; + storedProgram = undefined; afterEnd = false; }; - for (const word of mySqlWords(sql, mode)) { + for (const [index, word] of words.entries()) { if (word === ';') { afterEnd = false; if (depth === 0) { @@ -426,14 +508,25 @@ export function mySqlCallStatements( } continue; } + if (firstWord === 'create' && storedProgram === undefined) { + if (MYSQL_STORED_PROGRAMS.has(word)) { + storedProgram = true; + } else if (MYSQL_OTHER_OBJECTS.has(word)) { + storedProgram = false; + } + } const closedBlock = afterEnd; afterEnd = false; + const opensBlock = + word === 'begin' && + words[index - 1] !== '.' && + (storedProgram === true || (words[index + 1] === 'not' && words[index + 2] === 'atomic')); if (closedBlock && /^(?:if|loop|while|repeat)$/.test(word)) { // That END closed an IF or loop, which never opened a level, so restore it. depth++; } else if (closedBlock && word === 'case') { // END CASE closes the CASE that opened a level. - } else if (word === 'case' || (word === 'begin' && (depth > 0 || firstWord !== undefined))) { + } else if (word === 'case' || opensBlock) { depth++; } else if (word === 'end' && depth > 0) { depth--; diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index e4c4a86a2..8f19af72f 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -58,6 +58,7 @@ import { runSqliteStatements, splitSqliteStatements, } from './db-execute-results.ts'; +import type { MySqlServerMode } from './db-execute-results.ts'; import type { StatementResult } from './db-execute-results.ts'; import { assertPgExportableSchema, @@ -945,6 +946,19 @@ async function executeExternalSql( return; } const { createConnection } = await import('mysql2/promise'); + // Grouping a CALL's results reads the SQL the way this server does: its sql_mode decides + // what a backslash means, and its version and family which executable comments run. The + // query runs on a connection of its own, so the session the SQL runs in stays untouched + // (FOUND_ROWS(), ROW_COUNT(), warnings). A SET of sql_mode in the SQL itself is not followed. + let mode: MySqlServerMode | undefined; + if (json && needsMySqlServerMode(sql)) { + const modeClient = await createConnection({ uri: dbUrl }); + try { + mode = mySqlServerMode((await modeClient.query(MYSQL_SERVER_MODE_QUERY))[0]); + } finally { + await modeClient.end(); + } + } const mySqlClient = await createConnection({ uri: dbUrl, multipleStatements: true, @@ -952,13 +966,6 @@ async function executeExternalSql( ...(json ? { supportBigNumbers: true, bigNumberStrings: false } : {}), }); try { - // Grouping a CALL's results reads the SQL the way this server does: its sql_mode decides - // what a backslash means, and its version which `/*!` comments run. A SET of sql_mode in - // the SQL itself is not followed. - const mode = - json && needsMySqlServerMode(sql) - ? mySqlServerMode((await mySqlClient.query(MYSQL_SERVER_MODE_QUERY))[0]) - : undefined; const [rows, fields] = await mySqlClient.query(sql); if (json) { printStatementResults(mySqlStatementResults(rows, fields, sql, mode)); diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index a7f076383..a3148bad0 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -893,6 +893,7 @@ describe('void db execute --remote (PostgreSQL)', () => { ), ); const command = String.raw`SELECT '\'; CALL p()`; + mockMySqlCreateConnection.mockClear(); await runDbCommand(root, { action: 'execute', command, remote: true, json: true }); @@ -900,6 +901,11 @@ describe('void db execute --remote (PostgreSQL)', () => { 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version', command, ]); + // The mode is read on a connection of its own, which leaves the SQL's session untouched. + expect(mockMySqlCreateConnection.mock.calls.map(([options]) => options)).toEqual([ + { uri: 'mysql://host/db' }, + expect.objectContaining({ uri: 'mysql://host/db', multipleStatements: true }), + ]); expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ { results: [{ a: '\\' }], success: true, meta: {} }, { results: [{ b: 2 }], success: true, meta: { affectedRows: 0, insertId: 0 } }, diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index 17dcd18ad..1e9b6deb7 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -233,11 +233,21 @@ describe('db execute --json results', () => { it('reads MySQL SQL the way the server it runs on does', () => { const mysql84 = mySqlServerMode([{ sql_mode: 'STRICT_TRANS_TABLES', version: '8.4.3' }]); - expect(mysql84).toEqual({ version: 80_403, backslashEscapes: true }); + expect(mysql84).toEqual({ + version: 80_403, + backslashEscapes: true, + ansiQuotes: false, + mariaDb: false, + }); const noEscapes = mySqlServerMode([ - { sql_mode: 'STRICT_TRANS_TABLES,NO_BACKSLASH_ESCAPES', version: '10.11.6-MariaDB' }, + { sql_mode: 'STRICT_TRANS_TABLES,NO_BACKSLASH_ESCAPES', version: '8.4.3' }, ]); - expect(noEscapes).toEqual({ version: 101_106, backslashEscapes: false }); + expect(noEscapes).toEqual({ + version: 80_403, + backslashEscapes: false, + ansiQuotes: false, + mariaDb: false, + }); // With NO_BACKSLASH_ESCAPES, a backslash before a quote is an ordinary character. const backslash = String.raw`SELECT '\'; CALL p()`; expect(mySqlCallStatements(backslash, noEscapes)).toEqual([false, true]); @@ -263,9 +273,66 @@ describe('db execute --json results', () => { expect(mySqlCallStatements('/*!800001 CALL p() */ SELECT 1', mysql84)).toEqual([false]); expect(mySqlCallStatements('/*!800001; CALL p() */', mysql84)).toEqual([false, true]); expect(mySqlCallStatements('/*!80000CALL p() */', mysql84)).toEqual([true]); + // A skipped version comment may hold one nested comment. + expect(mySqlCallStatements('/*!99999 /* note */ SELECT 1 */ CALL p()', mysql84)).toEqual([ + true, + ]); + expect(mySqlCallStatements('/* /* note */ CALL p()', mysql84)).toEqual([true]); + // MySQL reads MariaDB's `/*M!` as an ordinary comment. + expect(mySqlCallStatements('/*M! SELECT 0; */ CALL p()', mysql84)).toEqual([true]); expect(needsMySqlServerMode('SELECT 1; CALL p()')).toBe(false); expect(needsMySqlServerMode(backslash)).toBe(true); expect(needsMySqlServerMode('/*!80000 SET @n = 1 */')).toBe(true); + expect(needsMySqlServerMode('/*M!100100 SELECT 0 */')).toBe(true); + }); + + it('reads MariaDB executable comments the way MariaDB does', () => { + const mariaDb = mySqlServerMode([ + { sql_mode: 'STRICT_TRANS_TABLES', version: '10.11.6-MariaDB-1:10.11.6+maria~ubu2204' }, + ]); + expect(mariaDb).toEqual({ + version: 101_106, + backslashEscapes: true, + ansiQuotes: false, + mariaDb: true, + }); + expect(mySqlCallStatements('/*M!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(mySqlCallStatements('/*M! SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(mySqlCallStatements('/*M!110000 SELECT 0; */ CALL p()', mariaDb)).toEqual([true]); + // MariaDB skips `/*!` comments for MySQL 5.7 and later, but not its own versions. + expect(mySqlCallStatements('/*!80000 SELECT 0; */ CALL p()', mariaDb)).toEqual([true]); + expect(mySqlCallStatements('/*!50699 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(mySqlCallStatements('/*!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + // A sixth digit belongs to the version without whitespace after it. + expect(mySqlCallStatements('/*!100100SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect( + mySqlStatementResults( + [[{ 0: 0 }], [{ a: 1 }], header], + [[field], [field], undefined], + '/*M!100100 SELECT 0 */; CALL p()', + mariaDb, + ), + ).toEqual([ + { results: [{ 0: 0 }], success: true, meta: {} }, + { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it('reads double quotes as a name in ANSI_QUOTES mode', () => { + const ansi = mySqlServerMode([ + { + sql_mode: 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ONLY_FULL_GROUP_BY,ANSI', + version: '8.4.3', + }, + ]); + expect(ansi.ansiQuotes).toBe(true); + // A backslash escapes nothing in a quoted name. + expect(mySqlCallStatements(String.raw`SELECT 1 AS "a\"; CALL p()`, ansi)).toEqual([ + false, + true, + ]); + // A single-quoted string still reads its backslash escapes. + expect(mySqlCallStatements(String.raw`SELECT 'a\'; CALL p()'`, ansi)).toEqual([false]); }); it('finds MySQL statements around stored program bodies', () => { @@ -287,4 +354,42 @@ describe('db execute --json results', () => { ), ).toEqual([false, false, true, false]); }); + + it('opens a BEGIN block only in a stored program', () => { + // BEGIN may name a column, and XA BEGIN starts a transaction. + expect(mySqlCallStatements('SELECT begin FROM appointments; CALL report()')).toEqual([ + false, + true, + ]); + expect(mySqlCallStatements("XA BEGIN 'x'; CALL p()")).toEqual([false, true]); + expect( + mySqlCallStatements('CREATE TABLE event (begin INT, `end` INT); CREATE VIEW v AS SELECT 1'), + ).toEqual([false, false]); + expect( + mySqlCallStatements( + [ + `CREATE DEFINER = CURRENT_USER TRIGGER t BEFORE INSERT ON a FOR EACH ROW BEGIN + SET NEW.begin = 1; SELECT x.begin INTO @b FROM x; + END`, + `CREATE EVENT e ON SCHEDULE EVERY 1 DAY DO BEGIN DELETE FROM a; END`, + 'CALL p()', + ].join(';\n'), + ), + ).toEqual([false, false, true]); + // MariaDB runs BEGIN NOT ATOMIC blocks outside a stored program. + expect(mySqlCallStatements('BEGIN NOT ATOMIC SELECT 1; SELECT 2; END; CALL p()')).toEqual([ + false, + true, + ]); + expect( + mySqlStatementResults( + [[{ begin: 1 }], [{ a: 1 }], header], + [[field], [field], undefined], + 'SELECT begin FROM appointments; CALL report()', + ), + ).toEqual([ + { results: [{ begin: 1 }], success: true, meta: {} }, + { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); }); From 0e1c0165ec10e036f799e5a0a59c187cb048f773 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 15:45:25 +0530 Subject: [PATCH 06/11] fix(cli): follow MySQL sql_mode changes and keep `void db execute --json` output exact - Read later statements with the mode a `SET sql_mode` to a quoted list leaves, and refuse before running SQL whose CALL results could not be grouped after an unreadable change - Read reserved words after a dot (`t.case`, `t.end`) as names - Keep `ALTER EVENT ... DO BEGIN ... END` bodies in one statement - Print MySQL dates and times as the text MySQL returns - Leave --json out of the interactive `void db` menu, which draws on stdout - Drop URL options that would change JSON output, such as `debug`, from both connections Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 4 +- packages/void/src/cli/db-args.ts | 3 +- packages/void/src/cli/db-execute-results.ts | 309 ++++++++++++++---- packages/void/src/cli/db.ts | 75 ++++- packages/void/test/unit/db-args.test.ts | 8 +- .../void/test/unit/db-execute-remote.test.ts | 61 ++++ .../void/test/unit/db-execute-results.test.ts | 298 +++++++++++++---- 7 files changed, 616 insertions(+), 142 deletions(-) diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 864d2d9f8..7dcd5a4b3 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -94,13 +94,13 @@ void db execute --json "select count(*) as total from users; select id from user Each entry has the same shape as a D1 result and as an entry of `wrangler d1 execute --json`: -- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings, in arrays too, and numbers in `json` and `jsonb` values keep the digits the database returned. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. +- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings, in arrays too, and numbers in `json` and `jsonb` values keep the digits the database returned. MySQL dates and times print as the text MySQL returns, such as `"2024-01-02 03:04:05.123456"`. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. - `success`: `true` for a statement that ran. - `meta`: what the database reports about the statement. D1 databases report D1's metadata, such as `changes` and `last_row_id` (locally `changes`, `last_row_id` and `duration`). PostgreSQL reports `command` and `rowCount`, and MySQL reports `affectedRows` and `insertId` for a statement that changes data. If a statement fails, stdout stays empty. -`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command; a `CREATE TRIGGER` counts as one statement. +`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command; a `CREATE TRIGGER` counts as one statement. On MySQL, a backslash in a quoted string reads differently once `sql_mode` changes. So `--json` stops, without running anything, when a `CALL` comes after a statement that may change `sql_mode` in a way Void cannot read and after a quoted string with a backslash. Such statements are a `SET sql_mode` to anything other than a quoted list of modes, such as `SET sql_mode = @saved`, and an `EXECUTE`. Set `sql_mode` to a quoted list such as `'ANSI_QUOTES'`, or run the `CALL` in a separate command. ## `void db migrate` {#void-db-migrate} diff --git a/packages/void/src/cli/db-args.ts b/packages/void/src/cli/db-args.ts index 775ab77c1..742c5a969 100644 --- a/packages/void/src/cli/db-args.ts +++ b/packages/void/src/cli/db-args.ts @@ -16,10 +16,11 @@ export const dbSubcommands: Array = [ name: 'execute', arg: '', description: 'Run SQL against the database (use --remote for the deployed database)', + // No --json: this menu draws on stdout, which --json keeps for its result. Scripts pass it + // on the command line, which skips the menu. flags: [ { name: '--remote', description: 'Run against the deployed database' }, { name: '--yes', description: 'Skip the confirmation prompt' }, - { name: '--json', description: "Print each statement's results as JSON" }, ], }, { diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index ddee1e547..114a83d1c 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -395,66 +395,69 @@ const MYSQL_DEFAULT_MODE: MySqlServerMode = { mariaDb: false, }; +/** Where `readMySqlWord` reads next, and whether that is in an executable comment that runs. */ +type MySqlLexer = { index: number; inVersionComment: boolean }; + +const MYSQL_WORD = /[\w$\u0080-￿]+/uy; + /** - * The words, semicolons and other characters of MySQL SQL, lowercased, outside comments, with - * a quoted string or name as one empty word. The SQL in an executable comment (`/*!`, and - * `/*M!` on MariaDB) counts when the server runs it. + * The next word, semicolon or other character of MySQL SQL after any whitespace and comments, + * lowercased, or `undefined` at the end. A quoted string or name is one word, as written with + * its quotes. The SQL in an executable comment (`/*!`, and `/*M!` on MariaDB) counts when the + * server runs it. */ -function mySqlWords(sql: string, mode: MySqlServerMode): Array { - const word = /[\w$\u0080-￿]+/uy; - const words: Array = []; - let index = 0; - // Inside an executable comment whose SQL the server runs, so its `*/` is skipped. - let inVersionComment = false; - while (index < sql.length) { +function readMySqlWord(sql: string, lexer: MySqlLexer, mode: MySqlServerMode): string | undefined { + while (lexer.index < sql.length) { + const index = lexer.index; const character = sql[index]; const next = sql[index + 1]; if (character === "'" || character === '"' || character === '`') { // A backslash escapes nothing in a quoted name, `ANSI_QUOTES` double quotes included. const name = character === '`' || (character === '"' && mode.ansiQuotes); - index = skipMySqlQuoted(sql, index, character, mode.backslashEscapes && !name); - words.push(''); - } else if ( + lexer.index = skipMySqlQuoted(sql, index, character, mode.backslashEscapes && !name); + return sql.slice(index, lexer.index); + } + if ( character === '#' || // MySQL reads `--` as a comment only when whitespace or a control character, or the end of // the input, follows it. (character === '-' && next === '-' && startsMySqlDashComment(sql.charCodeAt(index + 2))) ) { const newline = sql.indexOf('\n', index); - index = newline === -1 ? sql.length : newline; - } else if (inVersionComment && character === '*' && next === '/') { - inVersionComment = false; - index += 2; + lexer.index = newline === -1 ? sql.length : newline; + } else if (lexer.inVersionComment && character === '*' && next === '/') { + lexer.inVersionComment = false; + lexer.index += 2; } else if (character === '/' && next === '*') { const executable = /^M?!/u.test(sql.slice(index + 2, index + 4)); const runsFrom = executable ? runsMySqlComment(sql, index + 2, mode) : undefined; if (runsFrom !== undefined) { - inVersionComment = true; - index = runsFrom; + lexer.inVersionComment = true; + lexer.index = runsFrom; } else { // Any other comment, an optimizer hint (`/*+`) too, holds no statement. One the server // skips for its version may nest a comment. - index = skipMySqlComment(sql, index + 2, executable ? 1 : 0); + lexer.index = skipMySqlComment(sql, index + 2, executable ? 1 : 0); } } else if (/[ \t\n\v\f\r]/u.test(character)) { - index++; + lexer.index++; } else { - word.lastIndex = index; - const match = word.exec(sql); - const token = match ? match[0] : character; - index += token.length; - words.push(token.toLowerCase()); + MYSQL_WORD.lastIndex = index; + const token = MYSQL_WORD.exec(sql)?.[0] ?? character; + lexer.index += token.length; + return token.toLowerCase(); } } - return words; + return undefined; } -// The object a CREATE statement makes, which tells a stored program from other DDL. +// The object a CREATE or ALTER statement names, which tells a stored program from other DDL. const MYSQL_STORED_PROGRAMS = new Set(['procedure', 'function', 'trigger', 'event']); const MYSQL_OTHER_OBJECTS = new Set([ 'database', 'fulltext', 'index', + 'instance', 'logfile', 'resource', 'role', @@ -471,44 +474,233 @@ const MYSQL_OTHER_OBJECTS = new Set([ 'view', ]); +/** How a server's quoting rules stand after a statement changes its `sql_mode`. */ +type MySqlQuoting = Pick; + +// The modes that turn on ANSI_QUOTES: itself, and the combination modes that include it. +const MYSQL_ANSI_QUOTES_MODES = new Set([ + 'ANSI', + 'ANSI_QUOTES', + 'DB2', + 'MAXDB', + 'MSSQL', + 'ORACLE', + 'POSTGRESQL', +]); +const MYSQL_GLOBAL_SCOPES = new Set(['global', 'persist', 'persist_only']); +const MYSQL_SESSION_SCOPES = new Set(['session', 'local']); + +/** The name a word in a SET statement gives, unquoted and lowercased. */ +function mySqlName(word: string | undefined, mode: MySqlServerMode): string | undefined { + const quote = word?.[0]; + if (word !== undefined && (quote === '`' || (quote === '"' && mode.ansiQuotes))) { + return word.slice(1, -1).replaceAll(`${quote}${quote}`, quote).toLowerCase(); + } + return word; +} + +/** The quoting rules a quoted list of modes, such as `'ANSI,NO_BACKSLASH_ESCAPES'`, sets. */ +function mySqlModeList(value: Array, mode: MySqlServerMode): MySqlQuoting | 'unclear' { + const [word] = value; + const quote = word?.[0]; + const string = quote === "'" || (quote === '"' && !mode.ansiQuotes); + if (value.length !== 1 || !string || word.length < 2 || !word.endsWith(quote)) { + return 'unclear'; + } + const text = word.slice(1, -1); + // Mode names hold only letters and underscores. Anything else (an escape, a quote, a space) + // is read here as unclear rather than guessed. + if (!/^[A-Za-z_,]*$/u.test(text)) { + return 'unclear'; + } + const modes = text.toUpperCase().split(','); + return { + backslashEscapes: !modes.includes('NO_BACKSLASH_ESCAPES'), + ansiQuotes: modes.some((name) => MYSQL_ANSI_QUOTES_MODES.has(name)), + }; +} + +/** Split words at top-level commas, or at the first top-level word `at` when one is given. */ +function splitMySqlWords(words: Array, at = ','): Array> { + let current: Array = []; + const parts = [current]; + let parentheses = 0; + for (const word of words) { + if (word === at && parentheses === 0 && (at === ',' || parts.length === 1)) { + current = []; + parts.push(current); + continue; + } + if (word === '(') { + parentheses++; + } else if (word === ')') { + parentheses--; + } + current.push(word); + } + return parts; +} + +/** + * How a top-level statement changes the session's quoting rules: not at all (`undefined`), to + * the rules a quoted list of modes sets, or in a way this scan cannot read (`'unclear'`), such + * as `SET sql_mode = @saved` or a prepared statement's `EXECUTE`. A stored program, and a + * MariaDB `BEGIN NOT ATOMIC` block, run with a `sql_mode` of their own and restore the + * session's, and `SET GLOBAL` leaves it alone. + */ +function mySqlModeChange( + words: Array, + mode: MySqlServerMode, +): MySqlQuoting | 'unclear' | undefined { + const [first] = words; + // A prepared statement, or MariaDB's EXECUTE IMMEDIATE, may set sql_mode. + if (first === 'execute') { + return 'unclear'; + } + if (first !== 'set') { + return undefined; + } + if (words[1] === 'statement') { + // MariaDB's SET STATEMENT ... FOR keeps what the statement after FOR changes, unless it + // sets sql_mode itself, which it then restores. + const [settings, statement] = splitMySqlWords(words.slice(2), 'for'); + const restores = settings.some((word) => mySqlName(word, mode) === 'sql_mode'); + return statement === undefined || restores ? undefined : mySqlModeChange(statement, mode); + } + const assignments = splitMySqlWords(words.slice(1)); + let change: MySqlQuoting | 'unclear' | undefined; + // A GLOBAL or SESSION before an assignment holds for the ones after it. + let global = false; + for (const assignment of assignments) { + let index = 0; + if (MYSQL_GLOBAL_SCOPES.has(assignment[index])) { + global = true; + index++; + } else if (MYSQL_SESSION_SCOPES.has(assignment[index])) { + global = false; + index++; + } + let targetsGlobal = global; + if (assignment[index] === '@') { + // `@name` is a user variable. + if (assignment[index + 1] !== '@') { + continue; + } + index += 2; + // `@@name` is the session's variable, and `@@scope.name` the scope's. + targetsGlobal = false; + if (assignment[index + 1] === '.') { + targetsGlobal = MYSQL_GLOBAL_SCOPES.has(assignment[index]); + index += 2; + } + } + if (targetsGlobal || mySqlName(assignment[index], mode) !== 'sql_mode') { + continue; + } + index++; + if (assignment[index] === ':') { + index++; + } + change = + assignment[index] === '=' + ? mySqlModeList(assignment.slice(index + 1), mode) + : // Not an assignment MySQL accepts, so the statement fails. + 'unclear'; + } + return change; +} + /** - * Tell which MySQL statements are `CALL`s. Statements end at top-level semicolons. In a stored - * program (`CREATE PROCEDURE`, `FUNCTION`, `TRIGGER` or `EVENT`), a `BEGIN ... END` body holds - * semicolons of its own, so it nests, as does MariaDB's `BEGIN NOT ATOMIC` block. Elsewhere - * `BEGIN` starts a transaction or is a name. A `CASE ... END` nests anywhere. `END IF`, - * `END LOOP`, `END WHILE` and `END REPEAT` close blocks that sit inside a `BEGIN`, so they do - * not change the depth. + * The statements of MySQL SQL, in order: `calls` tells which ones are `CALL`s. When `uncounted` + * is true, more statements follow them, none of them a `CALL`, which this scan cannot count. */ -export function mySqlCallStatements( +export type MySqlStatements = { calls: Array; uncounted: boolean }; + +/** + * Find MySQL's statements and tell which are `CALL`s, reading the SQL the way a server in + * `mode` does. Statements end at top-level semicolons. In a stored program (`CREATE PROCEDURE`, + * `FUNCTION`, `TRIGGER` or `EVENT`, and `ALTER EVENT`), a `BEGIN ... END` body holds semicolons + * of its own, so it nests, as does MariaDB's `BEGIN NOT ATOMIC` block. Elsewhere `BEGIN` starts a + * transaction or is a name. A `CASE ... END` nests anywhere. `END IF`, `END LOOP`, `END WHILE` + * and `END REPEAT` close blocks that sit inside a `BEGIN`, so they do not change the depth. After + * a dot, each of these words is a name, such as the column in `t.case`. + * + * The server reads each statement with the `sql_mode` the statements before it left, so a + * `SET sql_mode` to a quoted list of modes changes how the SQL after it reads. After a statement + * that changes it in a way this scan cannot read, the SQL reads the same until a quoted string + * or name holds a backslash. From there on, the statements are `uncounted` when none of them can be a `CALL`, + * and otherwise this throws before the SQL runs, since their results could not be grouped. + */ +export function mySqlStatements( sql: string, - mode: MySqlServerMode = MYSQL_DEFAULT_MODE, -): Array { - const words = mySqlWords(sql, mode); + initialMode: MySqlServerMode = MYSQL_DEFAULT_MODE, +): MySqlStatements { + let mode = initialMode; + const lexer: MySqlLexer = { index: 0, inVersionComment: false }; const calls: Array = []; let depth = 0; - let firstWord: string | undefined; - // Whether this statement creates a stored program, once its CREATE names the object. + // The current statement's words, and where it starts. + let words: Array = []; + let start = 0; + // Whether this statement creates a stored program, once its CREATE or ALTER names the object. let storedProgram: boolean | undefined; // Set right after an END that closed a block, so a following IF, LOOP, WHILE, REPEAT or CASE // reads as part of that END. let afterEnd = false; + // Whether a statement changed sql_mode in a way this scan cannot read. Until a quoted string + // or name holds a backslash, every mode reads the SQL after it the same way. + let unclear = false; const finish = () => { - if (firstWord !== undefined) { - calls.push(firstWord === 'call'); + if (words.length > 0) { + calls.push(words[0] === 'call'); + const change = mySqlModeChange(words, mode); + if (change === 'unclear') { + unclear = true; + } else if (change !== undefined) { + mode = { ...mode, ...change }; + unclear = false; + } } - firstWord = undefined; + words = []; + start = lexer.index; storedProgram = undefined; afterEnd = false; }; - for (const [index, word] of words.entries()) { + // Whether the BEGIN just read opens MariaDB's BEGIN NOT ATOMIC block, read without moving on. + const opensBlock = () => { + const ahead = { ...lexer }; + return ( + readMySqlWord(sql, ahead, mode) === 'not' && readMySqlWord(sql, ahead, mode) === 'atomic' + ); + }; + for ( + let word = readMySqlWord(sql, lexer, mode); + word !== undefined; + word = readMySqlWord(sql, lexer, mode) + ) { + if (unclear && word.includes('\\')) { + // `CALL` is a word of its own, so SQL without it holds none. A digit may come before it, + // as in `/*!80000CALL`. + if (/(? 0) { depth--; afterEnd = true; } - firstWord ??= word; } finish(); - return calls; + return { calls, uncounted: false }; } /** * mysql2 returns `[rows, fields]`. With several result sets, `rows` holds one entry per result * (rows, or a result header for a write) and `fields` holds each one's column list, or * `undefined` for a header. A `CALL` returns each result set of the procedure and then its own - * header, so those entries are grouped under the `CALL`, its rows in order. + * header, so those entries are grouped under the `CALL`, its rows in order. `statements` is what + * `mySqlStatements` found in the SQL. */ export function mySqlStatementResults( rows: unknown, fields: unknown, - sql: string, - mode: MySqlServerMode = MYSQL_DEFAULT_MODE, + statements: MySqlStatements, ): Array { const severalResults = Array.isArray(rows) && @@ -561,7 +752,7 @@ export function mySqlStatementResults( const grouped: Array = []; let index = 0; let matched = true; - for (const isCall of mySqlCallStatements(sql, mode)) { + for (const isCall of statements.calls) { if (!isCall) { matched &&= index < entries.length; grouped.push(mySqlStatementResult(entries[index++])); @@ -574,6 +765,12 @@ export function mySqlStatementResults( matched &&= index < entries.length; grouped.push({ results: sets.flat(), success: true, meta: mySqlHeaderMeta(entries[index++]) }); } + if (statements.uncounted) { + // At least one statement follows, and statements that are not CALLs each return one result. + matched &&= index < entries.length; + grouped.push(...entries.slice(index).map(mySqlStatementResult)); + index = entries.length; + } // When the statements and results do not line up (SQL this scan reads differently from // MySQL), print one entry per result rather than guess. return matched && index === entries.length ? grouped : entries.map(mySqlStatementResult); diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 8f19af72f..152315321 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -52,14 +52,14 @@ import { MYSQL_SERVER_MODE_QUERY, mySqlServerMode, mySqlStatementResults, + mySqlStatements, needsMySqlServerMode, pgJsonTypes, pgStatementResults, runSqliteStatements, splitSqliteStatements, } from './db-execute-results.ts'; -import type { MySqlServerMode } from './db-execute-results.ts'; -import type { StatementResult } from './db-execute-results.ts'; +import type { MySqlServerMode, MySqlStatements, StatementResult } from './db-execute-results.ts'; import { assertPgExportableSchema, exportPgConstraints, @@ -946,29 +946,36 @@ async function executeExternalSql( return; } const { createConnection } = await import('mysql2/promise'); + const uri = json ? mySqlJsonUri(dbUrl) : dbUrl; // Grouping a CALL's results reads the SQL the way this server does: its sql_mode decides // what a backslash means, and its version and family which executable comments run. The - // query runs on a connection of its own, so the session the SQL runs in stays untouched - // (FOUND_ROWS(), ROW_COUNT(), warnings). A SET of sql_mode in the SQL itself is not followed. - let mode: MySqlServerMode | undefined; - if (json && needsMySqlServerMode(sql)) { - const modeClient = await createConnection({ uri: dbUrl }); - try { - mode = mySqlServerMode((await modeClient.query(MYSQL_SERVER_MODE_QUERY))[0]); - } finally { - await modeClient.end(); + // mode is read on a connection of its own, so the session the SQL runs in stays untouched + // (FOUND_ROWS(), ROW_COUNT(), warnings). The statements are found before the SQL runs, so SQL + // whose results cannot be grouped fails without running. + let statements: MySqlStatements | undefined; + if (json) { + let mode: MySqlServerMode | undefined; + if (needsMySqlServerMode(sql)) { + const modeClient = await createConnection({ uri }); + try { + mode = mySqlServerMode((await modeClient.query(MYSQL_SERVER_MODE_QUERY))[0]); + } finally { + await modeClient.end(); + } } + statements = mySqlStatements(sql, mode); } const mySqlClient = await createConnection({ - uri: dbUrl, + uri, multipleStatements: true, - // BIGINT values past 2^53 arrive as strings instead of rounded numbers. - ...(json ? { supportBigNumbers: true, bigNumberStrings: false } : {}), + // BIGINT values past 2^53 arrive as strings instead of rounded numbers, and dates and times + // as the text MySQL returns, without a time zone conversion or rounding to milliseconds. + ...(json ? { supportBigNumbers: true, bigNumberStrings: false, dateStrings: true } : {}), }); try { const [rows, fields] = await mySqlClient.query(sql); - if (json) { - printStatementResults(mySqlStatementResults(rows, fields, sql, mode)); + if (statements) { + printStatementResults(mySqlStatementResults(rows, fields, statements)); } else if (Array.isArray(rows) && rows.length > 0) { printTable(rows as Array>); } @@ -977,6 +984,42 @@ async function executeExternalSql( } } +// URL options that would change --json output. mysql2 writes protocol traces to stdout for +// `debug`, and the others change how rows and values arrive. +const MYSQL_JSON_URL_OPTIONS = [ + 'debug', + 'bigNumberStrings', + 'dateStrings', + 'decimalNumbers', + 'jsonStrings', + 'nestTables', + 'rowsAsArray', + 'supportBigNumbers', + 'typeCast', +]; + +/** + * The URL without options that would change --json output. mysql2 reads options from the URL, + * and an option passed as false does not override one the URL sets. + */ +function mySqlJsonUri(dbUrl: string): string { + let url: URL; + try { + url = new URL(dbUrl); + } catch { + // mysql2 reads the URL the same way and reports it. + return dbUrl; + } + const options = MYSQL_JSON_URL_OPTIONS.filter((option) => url.searchParams.has(option)); + if (options.length === 0) { + return dbUrl; + } + for (const option of options) { + url.searchParams.delete(option); + } + return url.toString(); +} + function printStatementResults(results: Array): void { console.log(formatStatementResults(results)); } diff --git a/packages/void/test/unit/db-args.test.ts b/packages/void/test/unit/db-args.test.ts index efbaa1b7e..62658b177 100644 --- a/packages/void/test/unit/db-args.test.ts +++ b/packages/void/test/unit/db-args.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { parseDbArgs } from '../../src/cli/db-args.ts'; +import { dbSubcommands, parseDbArgs } from '../../src/cli/db-args.ts'; describe('parseDbArgs', () => { it('parses status', () => { @@ -73,6 +73,12 @@ describe('parseDbArgs', () => { }); }); + it('leaves --json out of the interactive menu', () => { + // The menu draws on stdout, which --json keeps for its result. + const execute = dbSubcommands.find(({ name }) => name === 'execute'); + expect(execute?.flags?.map(({ name }) => name)).toEqual(['--remote', '--yes']); + }); + it('rejects --json outside execute', () => { expect(() => parseDbArgs(['migrate', '--json'])).toThrow( 'db: `void db migrate` does not support --json.', diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index a3148bad0..682656fea 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -919,6 +919,67 @@ describe('void db execute --remote (PostgreSQL)', () => { mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); }); + it('reads MySQL dates as text and drops URL options that change the output with --json only', async () => { + const root = createProjectRoot({ database: 'mysql' }); + const url = + 'mysql://user:p%40ss@host:3306/db?debug=true&ssl=%7B%22rejectUnauthorized%22%3Atrue%7D&rowsAsArray=true&bigNumberStrings=true'; + mockGetDatabaseUrl.mockResolvedValue({ url }); + mockMySqlQuery.mockImplementation((sql) => + Promise.resolve( + sql.startsWith('SELECT @@SESSION.sql_mode') + ? [[{ sql_mode: '', version: '8.4.3' }], [{ name: 'sql_mode' }]] + : [[{ at: '2024-01-02 03:04:05.123456' }], [{ name: 'at' }]], + ), + ); + // A backslash makes the command read the server's mode on a connection of its own first. + const command = String.raw`SELECT at FROM t WHERE note <> '\\'`; + mockMySqlCreateConnection.mockClear(); + + await runDbCommand(root, { action: 'execute', command, remote: true, json: true }); + + // mysql2 prints protocol traces to stdout for `debug`, and the URL's options would win over + // the ones --json passes as false, so neither connection gets them. + const withoutDebug = + 'mysql://user:p%40ss@host:3306/db?ssl=%7B%22rejectUnauthorized%22%3Atrue%7D'; + expect(mockMySqlCreateConnection.mock.calls.map(([options]) => options)).toEqual([ + { uri: withoutDebug }, + expect.objectContaining({ uri: withoutDebug, dateStrings: true }), + ]); + expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + { results: [{ at: '2024-01-02 03:04:05.123456' }], success: true, meta: {} }, + ]); + + // The table keeps the URL and mysql2's own dates. + await runDbCommand(root, { action: 'execute', command, remote: true }); + expect(mockMySqlCreateConnection).toHaveBeenLastCalledWith({ + uri: url, + multipleStatements: true, + }); + mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); + }); + + it('refuses MySQL SQL whose CALL results it cannot group, before running it', async () => { + const root = createProjectRoot({ database: 'mysql' }); + mockGetDatabaseUrl.mockResolvedValue({ url: 'mysql://host/db' }); + mockMySqlQuery.mockImplementation((sql) => + Promise.resolve( + sql.startsWith('SELECT @@SESSION.sql_mode') + ? [[{ sql_mode: '', version: '8.4.3' }], [{ name: 'sql_mode' }]] + : [[], []], + ), + ); + const command = String.raw`SET sql_mode = @saved; SELECT 'a\'; CALL p()`; + + await expect( + runDbCommand(root, { action: 'execute', command, remote: true, json: true }), + ).rejects.toThrow('cannot group a CALL'); + expect(mockMySqlQuery.mock.calls.map(([sql]) => sql)).toEqual([ + 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version', + ]); + expect(console.log).not.toHaveBeenCalled(); + mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); + }); + it('keeps PostgreSQL numeric arrays and JSON numbers exact with --json only', async () => { const root = createProjectRoot({ database: 'pg' }); mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index 1e9b6deb7..6db8faba5 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -2,16 +2,24 @@ import { types } from 'pg'; import { describe, expect, it } from 'vite-plus/test'; import { formatStatementResults, - mySqlCallStatements, mySqlServerMode, mySqlStatementResults, + mySqlStatements, pgJsonTypes, needsMySqlServerMode, pgStatementResults, splitSqliteStatements, } from '../../src/cli/db-execute-results.ts'; +import type { MySqlServerMode } from '../../src/cli/db-execute-results.ts'; import { Buffer } from '../../src/cli/node-buffer.ts'; +/** Which statements of MySQL SQL are CALLs. */ +const calls = (sql: string, mode?: MySqlServerMode) => mySqlStatements(sql, mode).calls; + +/** Group mysql2's results by the statements of `sql`. */ +const groupResults = (rows: unknown, fields: unknown, sql: string, mode?: MySqlServerMode) => + mySqlStatementResults(rows, fields, mySqlStatements(sql, mode)); + describe('db execute --json results', () => { it('prints binary values as byte arrays', () => { const output = formatStatementResults([ @@ -152,20 +160,20 @@ describe('db execute --json results', () => { const header = { fieldCount: 0, affectedRows: 2, insertId: 5, info: '', serverStatus: 2 }; it('reads a single MySQL statement', () => { - expect(mySqlStatementResults([{ a: 1 }], [field], 'SELECT 1')).toEqual([ + expect(groupResults([{ a: 1 }], [field], 'SELECT 1')).toEqual([ { results: [{ a: 1 }], success: true, meta: {} }, ]); - expect(mySqlStatementResults([], [field], 'SELECT 1')).toEqual([ + expect(groupResults([], [field], 'SELECT 1')).toEqual([ { results: [], success: true, meta: {} }, ]); - expect(mySqlStatementResults(header, undefined, 'DELETE FROM a')).toEqual([ + expect(groupResults(header, undefined, 'DELETE FROM a')).toEqual([ { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, ]); }); it('reads each MySQL statement of a multi-statement query', () => { expect( - mySqlStatementResults( + groupResults( [header, [{ a: 1 }], []], [undefined, [field], [field]], 'DELETE FROM a; SELECT 1; SELECT 2', @@ -176,7 +184,7 @@ describe('db execute --json results', () => { { results: [], success: true, meta: {} }, ]); expect( - mySqlStatementResults([[{ a: 1 }], [{ a: 2 }]], [[field], [field]], 'SELECT 1; SELECT 2'), + groupResults([[{ a: 1 }], [{ a: 2 }]], [[field], [field]], 'SELECT 1; SELECT 2'), ).toEqual([ { results: [{ a: 1 }], success: true, meta: {} }, { results: [{ a: 2 }], success: true, meta: {} }, @@ -184,11 +192,11 @@ describe('db execute --json results', () => { }); it("groups a CALL's result sets and header under the CALL", () => { - expect(mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], 'CALL p()')).toEqual([ + expect(groupResults([[{ a: 1 }], header], [[field], undefined], 'CALL p()')).toEqual([ { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, ]); expect( - mySqlStatementResults( + groupResults( [[{ a: 1 }], [{ b: 2 }], [{ c: 3 }], header, header], [[field], [field], [field], undefined, undefined], 'SELECT 1; CALL p(); DELETE FROM a', @@ -201,33 +209,27 @@ describe('db execute --json results', () => { }); it('prints one entry per MySQL result when the statements do not line up', () => { - expect( - mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], 'CALL p(); CALL q()'), - ).toEqual([ + expect(groupResults([[{ a: 1 }], header], [[field], undefined], 'CALL p(); CALL q()')).toEqual([ { results: [{ a: 1 }], success: true, meta: {} }, { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, ]); }); it('reads MySQL comments and quoted text the way MySQL does', () => { - expect(mySqlCallStatements('# note\nCALL report()')).toEqual([true]); - expect(mySqlCallStatements(String.raw`SELECT 'it\'s; ok'; CALL p()`)).toEqual([false, true]); - expect(mySqlCallStatements(String.raw`SELECT "a\";b"; CALL p()`)).toEqual([false, true]); + expect(calls('# note\nCALL report()')).toEqual([true]); + expect(calls(String.raw`SELECT 'it\'s; ok'; CALL p()`)).toEqual([false, true]); + expect(calls(String.raw`SELECT "a\";b"; CALL p()`)).toEqual([false, true]); // `--` starts a comment only before whitespace, so `1--1` is arithmetic. - expect(mySqlCallStatements('SELECT 1--1; -- x;\nCALL p()')).toEqual([false, true]); + expect(calls('SELECT 1--1; -- x;\nCALL p()')).toEqual([false, true]); // MySQL runs the SQL in a `/*!` comment, and `[` quotes nothing. - expect(mySqlCallStatements('/*!40101 SET @a = 1 */; SELECT [1; CALL p()')).toEqual([ - false, - false, - true, - ]); + expect(calls('/*!40101 SET @a = 1 */; SELECT [1; CALL p()')).toEqual([false, false, true]); // A control character after `--` starts a comment too. - expect(mySqlCallStatements('SELECT 1; --\u0001 x;\nCALL p()')).toEqual([false, true]); - expect(mySqlCallStatements('SELECT 1; --')).toEqual([false]); + expect(calls('SELECT 1; --\u0001 x;\nCALL p()')).toEqual([false, true]); + expect(calls('SELECT 1; --')).toEqual([false]); // An optimizer hint outside a statement is an ordinary comment. - expect(mySqlCallStatements('/*+ BKA(t) */ CALL p()')).toEqual([true]); + expect(calls('/*+ BKA(t) */ CALL p()')).toEqual([true]); expect( - mySqlStatementResults([[{ a: 1 }], header], [[field], undefined], '# note\nCALL report()'), + groupResults([[{ a: 1 }], header], [[field], undefined], '# note\nCALL report()'), ).toEqual([{ results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }]); }); @@ -250,10 +252,10 @@ describe('db execute --json results', () => { }); // With NO_BACKSLASH_ESCAPES, a backslash before a quote is an ordinary character. const backslash = String.raw`SELECT '\'; CALL p()`; - expect(mySqlCallStatements(backslash, noEscapes)).toEqual([false, true]); - expect(mySqlCallStatements(backslash, mysql84)).toEqual([false]); + expect(calls(backslash, noEscapes)).toEqual([false, true]); + expect(calls(backslash, mysql84)).toEqual([false]); expect( - mySqlStatementResults( + groupResults( [[{ a: 1 }], [{ b: 2 }], header], [[field], [field], undefined], backslash, @@ -264,22 +266,20 @@ describe('db execute --json results', () => { { results: [{ b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, ]); // The server skips a version comment for a later version and runs one for its own. - expect(mySqlCallStatements('/*!99999 SET @n = 1 */ CALL p()', mysql84)).toEqual([true]); - expect(mySqlCallStatements('/*!80403 SET @n = 1 */ CALL p()', mysql84)).toEqual([false]); - expect(mySqlCallStatements('/*! CALL p() */', mysql84)).toEqual([true]); - expect(mySqlCallStatements('/*!40101 CALL p() */; SELECT 1', mysql84)).toEqual([true, false]); + expect(calls('/*!99999 SET @n = 1 */ CALL p()', mysql84)).toEqual([true]); + expect(calls('/*!80403 SET @n = 1 */ CALL p()', mysql84)).toEqual([false]); + expect(calls('/*! CALL p() */', mysql84)).toEqual([true]); + expect(calls('/*!40101 CALL p() */; SELECT 1', mysql84)).toEqual([true, false]); // Six digits are a version when whitespace follows them; otherwise five are. - expect(mySqlCallStatements('/*!100000 SET @n = 1 */ CALL p()', mysql84)).toEqual([true]); - expect(mySqlCallStatements('/*!800001 CALL p() */ SELECT 1', mysql84)).toEqual([false]); - expect(mySqlCallStatements('/*!800001; CALL p() */', mysql84)).toEqual([false, true]); - expect(mySqlCallStatements('/*!80000CALL p() */', mysql84)).toEqual([true]); + expect(calls('/*!100000 SET @n = 1 */ CALL p()', mysql84)).toEqual([true]); + expect(calls('/*!800001 CALL p() */ SELECT 1', mysql84)).toEqual([false]); + expect(calls('/*!800001; CALL p() */', mysql84)).toEqual([false, true]); + expect(calls('/*!80000CALL p() */', mysql84)).toEqual([true]); // A skipped version comment may hold one nested comment. - expect(mySqlCallStatements('/*!99999 /* note */ SELECT 1 */ CALL p()', mysql84)).toEqual([ - true, - ]); - expect(mySqlCallStatements('/* /* note */ CALL p()', mysql84)).toEqual([true]); + expect(calls('/*!99999 /* note */ SELECT 1 */ CALL p()', mysql84)).toEqual([true]); + expect(calls('/* /* note */ CALL p()', mysql84)).toEqual([true]); // MySQL reads MariaDB's `/*M!` as an ordinary comment. - expect(mySqlCallStatements('/*M! SELECT 0; */ CALL p()', mysql84)).toEqual([true]); + expect(calls('/*M! SELECT 0; */ CALL p()', mysql84)).toEqual([true]); expect(needsMySqlServerMode('SELECT 1; CALL p()')).toBe(false); expect(needsMySqlServerMode(backslash)).toBe(true); expect(needsMySqlServerMode('/*!80000 SET @n = 1 */')).toBe(true); @@ -296,17 +296,17 @@ describe('db execute --json results', () => { ansiQuotes: false, mariaDb: true, }); - expect(mySqlCallStatements('/*M!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); - expect(mySqlCallStatements('/*M! SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); - expect(mySqlCallStatements('/*M!110000 SELECT 0; */ CALL p()', mariaDb)).toEqual([true]); + expect(calls('/*M!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(calls('/*M! SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(calls('/*M!110000 SELECT 0; */ CALL p()', mariaDb)).toEqual([true]); // MariaDB skips `/*!` comments for MySQL 5.7 and later, but not its own versions. - expect(mySqlCallStatements('/*!80000 SELECT 0; */ CALL p()', mariaDb)).toEqual([true]); - expect(mySqlCallStatements('/*!50699 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); - expect(mySqlCallStatements('/*!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(calls('/*!80000 SELECT 0; */ CALL p()', mariaDb)).toEqual([true]); + expect(calls('/*!50699 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(calls('/*!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); // A sixth digit belongs to the version without whitespace after it. - expect(mySqlCallStatements('/*!100100SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect(calls('/*!100100SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); expect( - mySqlStatementResults( + groupResults( [[{ 0: 0 }], [{ a: 1 }], header], [[field], [field], undefined], '/*M!100100 SELECT 0 */; CALL p()', @@ -327,17 +327,14 @@ describe('db execute --json results', () => { ]); expect(ansi.ansiQuotes).toBe(true); // A backslash escapes nothing in a quoted name. - expect(mySqlCallStatements(String.raw`SELECT 1 AS "a\"; CALL p()`, ansi)).toEqual([ - false, - true, - ]); + expect(calls(String.raw`SELECT 1 AS "a\"; CALL p()`, ansi)).toEqual([false, true]); // A single-quoted string still reads its backslash escapes. - expect(mySqlCallStatements(String.raw`SELECT 'a\'; CALL p()'`, ansi)).toEqual([false]); + expect(calls(String.raw`SELECT 'a\'; CALL p()'`, ansi)).toEqual([false]); }); it('finds MySQL statements around stored program bodies', () => { expect( - mySqlCallStatements( + calls( [ 'BEGIN', `CREATE PROCEDURE p() lbl: BEGIN @@ -357,16 +354,14 @@ describe('db execute --json results', () => { it('opens a BEGIN block only in a stored program', () => { // BEGIN may name a column, and XA BEGIN starts a transaction. - expect(mySqlCallStatements('SELECT begin FROM appointments; CALL report()')).toEqual([ + expect(calls('SELECT begin FROM appointments; CALL report()')).toEqual([false, true]); + expect(calls("XA BEGIN 'x'; CALL p()")).toEqual([false, true]); + expect(calls('CREATE TABLE event (begin INT, `end` INT); CREATE VIEW v AS SELECT 1')).toEqual([ + false, false, - true, ]); - expect(mySqlCallStatements("XA BEGIN 'x'; CALL p()")).toEqual([false, true]); expect( - mySqlCallStatements('CREATE TABLE event (begin INT, `end` INT); CREATE VIEW v AS SELECT 1'), - ).toEqual([false, false]); - expect( - mySqlCallStatements( + calls( [ `CREATE DEFINER = CURRENT_USER TRIGGER t BEFORE INSERT ON a FOR EACH ROW BEGIN SET NEW.begin = 1; SELECT x.begin INTO @b FROM x; @@ -377,12 +372,9 @@ describe('db execute --json results', () => { ), ).toEqual([false, false, true]); // MariaDB runs BEGIN NOT ATOMIC blocks outside a stored program. - expect(mySqlCallStatements('BEGIN NOT ATOMIC SELECT 1; SELECT 2; END; CALL p()')).toEqual([ - false, - true, - ]); + expect(calls('BEGIN NOT ATOMIC SELECT 1; SELECT 2; END; CALL p()')).toEqual([false, true]); expect( - mySqlStatementResults( + groupResults( [[{ begin: 1 }], [{ a: 1 }], header], [[field], [field], undefined], 'SELECT begin FROM appointments; CALL report()', @@ -392,4 +384,178 @@ describe('db execute --json results', () => { { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, ]); }); + + it('reads a reserved word after a dot as a name', () => { + expect(calls('SELECT t.case, t.end FROM t; CALL report()')).toEqual([false, true]); + expect(calls('SELECT CASE WHEN t.end > 0 THEN t.case END FROM t; CALL p()')).toEqual([ + false, + true, + ]); + expect( + calls(`CREATE PROCEDURE p() BEGIN SELECT t.case, t.end, t.begin FROM t; END; CALL p()`), + ).toEqual([false, true]); + }); + + it('keeps an ALTER EVENT body in one MySQL statement', () => { + expect( + calls( + [ + 'ALTER EVENT e DO BEGIN DELETE FROM a; SELECT 1; END', + `ALTER DEFINER = 'admin'@'%' EVENT e ON SCHEDULE EVERY 1 DAY DO BEGIN DELETE FROM a; END`, + 'CALL p()', + ].join(';\n'), + ), + ).toEqual([false, false, true]); + // ALTER of other objects opens no block. + expect(calls('ALTER TABLE event ADD begin INT; BEGIN; CALL p()')).toEqual([false, false, true]); + }); + + it('reads MySQL SQL after a SET of sql_mode the way the new mode does', () => { + const noEscapes = mySqlServerMode([{ sql_mode: 'NO_BACKSLASH_ESCAPES', version: '8.4.3' }]); + const backslash = String.raw`SELECT '\'; CALL p()`; + expect(calls(`SET sql_mode = 'NO_BACKSLASH_ESCAPES'; ${backslash}`)).toEqual([ + false, + false, + true, + ]); + expect(calls(`SET sql_mode = ''; ${backslash}'`, noEscapes)).toEqual([false, false]); + for (const set of [ + `SET SESSION sql_mode = 'no_backslash_escapes'`, + `SET LOCAL sql_mode := 'STRICT_TRANS_TABLES,NO_BACKSLASH_ESCAPES'`, + `SET @@sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET @@SESSION.sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET @@local.sql_mode = "NO_BACKSLASH_ESCAPES"`, + "SET `sql_mode` = 'NO_BACKSLASH_ESCAPES'", + `SET GLOBAL max_connections = 10, SESSION sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET GLOBAL max_connections = 10, @@sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET @old_sql_mode = @@sql_mode, sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `/*!40101 SET SQL_MODE = 'NO_BACKSLASH_ESCAPES' */`, + `SET STATEMENT max_statement_time = 10 FOR SET sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET NAMES utf8mb4, sql_mode = 'ANSI_QUOTES,,NO_BACKSLASH_ESCAPES'`, + ]) { + expect(calls(`${set}; ${backslash}`), set).toEqual([false, false, true]); + } + // The SET reads its own text the way the mode before it does. + expect(calls(String.raw`SET sql_mode = 'NO_BACKSLASH_ESCAPES', @a = '\'; CALL p()'`)).toEqual([ + false, + ]); + // ANSI_QUOTES, and the combination modes that include it, make a double quote a name. + expect(calls(String.raw`SET sql_mode = 'ANSI'; SELECT 1 AS "a\"; CALL p()`)).toEqual([ + false, + false, + true, + ]); + const ansi = mySqlServerMode([{ sql_mode: 'ANSI_QUOTES', version: '8.4.3' }]); + expect(calls(String.raw`SET sql_mode = ''; SELECT "a\"; CALL p()"`, ansi)).toEqual([ + false, + false, + ]); + expect( + groupResults( + [header, [{ a: '\\' }], [{ b: 2 }], header], + [undefined, [field], [field], undefined], + `SET sql_mode = 'NO_BACKSLASH_ESCAPES'; ${backslash}`, + ), + ).toEqual([ + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ a: '\\' }], success: true, meta: {} }, + { results: [{ b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it("leaves the session's sql_mode alone for SQL that does not change it", () => { + const mysql84 = mySqlServerMode([{ sql_mode: '', version: '8.4.3' }]); + // The backslash escapes the quote, so the string holds the rest. + const backslash = String.raw`SELECT 'a\'; CALL p()'`; + for (const statement of [ + `SET GLOBAL sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET PERSIST sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET @@GLOBAL.sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET @@persist.sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET GLOBAL max_connections = 10, sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET @sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `SET STATEMENT sql_mode = 'NO_BACKSLASH_ESCAPES' FOR SELECT 1`, + `SET STATEMENT sql_mode = 'ANSI' FOR SET sql_mode = 'NO_BACKSLASH_ESCAPES'`, + `BEGIN NOT ATOMIC SET sql_mode = 'NO_BACKSLASH_ESCAPES'; END`, + `BEGIN NOT ATOMIC EXECUTE IMMEDIATE 'SET sql_mode = ''NO_BACKSLASH_ESCAPES'''; END`, + `SELECT 'SET sql_mode = ''NO_BACKSLASH_ESCAPES'''`, + `CREATE PROCEDURE q() BEGIN SET sql_mode = 'NO_BACKSLASH_ESCAPES'; END`, + `/*!99999 SET sql_mode = 'NO_BACKSLASH_ESCAPES' */ SELECT 1`, + ]) { + expect(calls(`${statement}; ${backslash}`, mysql84), statement).toEqual([false, false]); + } + }); + + it('stops reading MySQL SQL where an unclear change of sql_mode matters', () => { + const unclear = [ + 'SET sql_mode = @saved', + "SET sql_mode = CONCAT(@@sql_mode, ',NO_BACKSLASH_ESCAPES')", + 'SET sql_mode = DEFAULT', + "SET sql_mode = 'ANSI QUOTES'", + 'EXECUTE set_mode', + "EXECUTE IMMEDIATE 'SET sql_mode = ''NO_BACKSLASH_ESCAPES'''", + 'SET STATEMENT max_statement_time = 10 FOR EXECUTE set_mode', + ]; + for (const statement of unclear) { + // Without a backslash after it, every mode reads the SQL the same. + expect(mySqlStatements(`${statement}; CALL p()`), statement).toEqual({ + calls: [false, true], + uncounted: false, + }); + // After a backslash, the statements cannot be counted, but none of them is a CALL. + expect(mySqlStatements(String.raw`${statement}; SELECT 1; SELECT 'a\'; SELECT 2`)).toEqual({ + calls: [false, false], + uncounted: true, + }); + // A CALL that may follow it cannot be grouped, so the SQL is refused before it runs. + expect(() => mySqlStatements(String.raw`${statement}; SELECT 'a\'; CALL p()`)).toThrow( + 'cannot tell where this MySQL SQL', + ); + } + // A backslash in a comment, or a word that only holds the letters of CALL, changes nothing. + expect(mySqlStatements('SET sql_mode = @saved; -- C:\\path\nCALL p()')).toEqual({ + calls: [false, true], + uncounted: false, + }); + expect( + mySqlStatements( + String.raw`SET sql_mode = @saved; SELECT 'a\b' AS recall; SELECT called_at FROM t`, + ), + ).toEqual({ calls: [false], uncounted: true }); + // A version comment may run a CALL right after its digits. + expect(() => + mySqlStatements(String.raw`SET sql_mode = @saved; SELECT 'a\b'; /*!80000CALL p() */`), + ).toThrow('cannot tell where this MySQL SQL'); + // A SET of a quoted list of modes makes the mode clear again. + expect( + mySqlStatements( + String.raw`SET sql_mode = @saved; CALL p(); SET sql_mode = ''; SELECT 'a\'; CALL q()'`, + ), + ).toEqual({ calls: [false, true, false, false], uncounted: false }); + // At least one statement follows, so results that end before it do not line up. + expect( + groupResults( + [[{ a: 1 }], header, header], + [[field], undefined, undefined], + String.raw`CALL p(); SET sql_mode = @saved; SELECT 'a\b'`, + ), + ).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + // Statements that are not CALLs each return one result. + expect( + groupResults( + [[{ a: 1 }], header, header, [{ b: 1 }], [{ c: 2 }]], + [[field], undefined, undefined, [field], [field]], + String.raw`CALL p(); SET sql_mode = @saved; SELECT 'a\'b'; SELECT 2`, + ), + ).toEqual([ + { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ b: 1 }], success: true, meta: {} }, + { results: [{ c: 2 }], success: true, meta: {} }, + ]); + }); }); From 052a6afffb71871a268917af60975d4ade0ba528 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 20:37:15 +0530 Subject: [PATCH 07/11] fix(cli): group more MySQL results and count D1 trigger writes in `void db execute --json` MySQL and MariaDB: - Leave out comments after the last statement, which the server answers with a result of their own, so a CALL's results stay grouped. - Group the results of an EXECUTE of a prepared CALL, MariaDB's EXECUTE IMMEDIATE and SET STATEMENT ... FOR, and compound statements MariaDB runs outside a stored program. Refuse an EXECUTE of a statement the SQL does not prepare from a quoted string. - Keep stored program bodies without BEGIN together (IF, CASE, LOOP, WHILE, REPEAT, FOR), in procedures, functions, triggers and events. - After an unclear SET sql_mode, read the SQL in each quoting mode the server may be in, rather than refusing whenever a CALL follows. - Read `@case` as a variable, `begin`, `end` and `do` as names where a stored program uses them so, a handler's statement as a statement, and the account in DEFINER = account as no object. - Read `[name]` as a quoted name in MariaDB's MSSQL mode. Local D1: report the rows a statement's triggers write in `meta.changes`, as D1 does. Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 7 +- packages/void/src/cli/db-execute-results.ts | 1138 ++++++++++++++--- packages/void/src/cli/db.ts | 2 +- .../src/runtime/db/migrations/mysql-sql.ts | 12 +- packages/void/test/unit/db-commands.test.ts | 24 +- .../void/test/unit/db-execute-remote.test.ts | 39 +- .../void/test/unit/db-execute-results.test.ts | 459 ++++++- 7 files changed, 1495 insertions(+), 186 deletions(-) diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 7dcd5a4b3..6a8c8bffd 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -94,13 +94,16 @@ void db execute --json "select count(*) as total from users; select id from user Each entry has the same shape as a D1 result and as an entry of `wrangler d1 execute --json`: -- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings, in arrays too, and numbers in `json` and `jsonb` values keep the digits the database returned. MySQL dates and times print as the text MySQL returns, such as `"2024-01-02 03:04:05.123456"`. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. +- `results`: the rows the statement returned, or `[]`. `NULL` prints as `null`, numbers and text keep their types, and binary values print as arrays of bytes. An integer outside ±9007199254740991, which a JSON number cannot hold exactly, prints as a string of its digits, and infinite or not-a-number values print as `"Infinity"`, `"-Infinity"` and `"NaN"`. PostgreSQL `bigint` and `numeric` values print as strings, in arrays too, and numbers in `json` and `jsonb` values keep the digits the database returned. MySQL dates and times print as the text MySQL returns, such as `"2024-01-02 03:04:05.123456"`. A remote D1 database returns values as D1's API reports them. A MySQL `CALL` is one entry, with the rows of every result set the procedure returns. So are an `EXECUTE` of a prepared `CALL`, and a compound statement that MariaDB runs outside a stored program, such as `BEGIN NOT ATOMIC ... END` or `IF ... END IF`. - `success`: `true` for a statement that ran. - `meta`: what the database reports about the statement. D1 databases report D1's metadata, such as `changes` and `last_row_id` (locally `changes`, `last_row_id` and `duration`). PostgreSQL reports `command` and `rowCount`, and MySQL reports `affectedRows` and `insertId` for a statement that changes data. If a statement fails, stdout stays empty. -`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command; a `CREATE TRIGGER` counts as one statement. On MySQL, a backslash in a quoted string reads differently once `sql_mode` changes. So `--json` stops, without running anything, when a `CALL` comes after a statement that may change `sql_mode` in a way Void cannot read and after a quoted string with a backslash. Such statements are a `SET sql_mode` to anything other than a quoted list of modes, such as `SET sql_mode = @saved`, and an `EXECUTE`. Set `sql_mode` to a quoted list such as `'ANSI_QUOTES'`, or run the `CALL` in a separate command. +`--json` is not available for a direct Cloudflare D1 import of a file larger than 100 KB, which returns no rows. On a Void platform D1 database, `--remote --json` runs one statement per command; a `CREATE TRIGGER` counts as one statement. On MySQL, `--json` stops without running anything when it cannot tell which results belong to which statement: + +- An `EXECUTE` runs a statement that the same SQL does not prepare from a quoted string, such as `PREPARE s FROM @sql`, and so may be a `CALL`. A procedure may prepare statements too, so after a `CALL`, prepare a statement again before you run it. Run SQL that prepares a statement from a variable without `--json`. +- A `SET sql_mode` sets anything other than a quoted list of modes, such as `SET sql_mode = @saved`, and a quoted string with a backslash after it reads as different statements in different modes, with a `CALL` or another statement that returns several results among them. Set `sql_mode` to a quoted list such as `'ANSI_QUOTES'`, or run that statement in a separate command. ## `void db migrate` {#void-db-migrate} diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index 114a83d1c..e327f3bec 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -1,7 +1,7 @@ import { tokenizeSql } from '@void/deploy-core'; import type { CustomTypesConfig } from 'pg'; import type { SqliteDatabase } from '../migrations/runner.ts'; -import { skipMySqlQuoted } from '../runtime/db/migrations/mysql-sql.ts'; +import { closeMySqlQuoted } from '../runtime/db/migrations/mysql-sql.ts'; /** * One statement's outcome for `void db execute --json`. The shape follows D1's result @@ -145,12 +145,12 @@ export function splitSqliteStatements(sql: string): Array { */ export function runSqliteStatements(db: SqliteDatabase, sql: string): Array { const counters = db - .prepare<{ changes: bigint; last_row_id: bigint; total: bigint }>( - 'SELECT changes() AS changes, last_insert_rowid() AS last_row_id, total_changes() AS total', + .prepare<{ last_row_id: bigint; total: bigint }>( + 'SELECT last_insert_rowid() AS last_row_id, total_changes() AS total', ) .safeIntegers(true); // A scalar SELECT always returns one row. - const readCounters = () => counters.get() ?? { changes: 0n, last_row_id: 0n, total: 0n }; + const readCounters = () => counters.get() ?? { last_row_id: 0n, total: 0n }; const results: Array = []; for (const statementSql of splitSqliteStatements(sql)) { const statement = db.prepare>(statementSql).safeIntegers(true); @@ -168,8 +168,8 @@ export function runSqliteStatements(db: SqliteDatabase, sql: string): Array 0 && character === '/' && sql[index] === '*') { - index = skipMySqlComment(sql, index + 1, nesting - 1); + const end = skipMySqlComment(sql, index + 1, nesting - 1); + if (end === undefined) { + return undefined; + } + index = end; } else if (character === '*' && sql[index] === '/') { return index + 1; } } - return sql.length; + return undefined; } // After `/*`: MySQL reads six digits as a version when whitespace follows them, otherwise five. @@ -392,11 +401,52 @@ const MYSQL_DEFAULT_MODE: MySqlServerMode = { version: Number.POSITIVE_INFINITY, backslashEscapes: true, ansiQuotes: false, + brackets: false, mariaDb: false, }; -/** Where `readMySqlWord` reads next, and whether that is in an executable comment that runs. */ -type MySqlLexer = { index: number; inVersionComment: boolean }; +/** + * Where `readMySqlWord` reads next, where the word it read last starts, whether that is in an + * executable comment that runs, and what it has read since `readMySqlStatement` began: text that + * another sql_mode may read differently (`modal`: a quoted string or name that holds a + * backslash, or on MariaDB a `[`), text the server rejects (`rejected`: a quoted string or + * name, or a comment, still open at the end of the SQL, or a `[` that quotes no name), and a + * comment. + */ +type MySqlLexer = { + index: number; + start: number; + inVersionComment: boolean; + modal: boolean; + rejected: boolean; + comment: boolean; +}; + +function newMySqlLexer(): MySqlLexer { + return { + index: 0, + start: 0, + inVersionComment: false, + modal: false, + rejected: false, + comment: false, + }; +} + +/** The index after the `[name]` that opens at `open`, where `]]` stands for `]`. */ +function closeMySqlBracket(sql: string, open: number): number | undefined { + let index = open + 1; + for (;;) { + const close = sql.indexOf(']', index); + if (close === -1) { + return undefined; + } + if (sql[close + 1] !== ']') { + return close + 1; + } + index = close + 2; + } +} const MYSQL_WORD = /[\w$\u0080-￿]+/uy; @@ -411,11 +461,30 @@ function readMySqlWord(sql: string, lexer: MySqlLexer, mode: MySqlServerMode): s const index = lexer.index; const character = sql[index]; const next = sql[index + 1]; + lexer.start = index; if (character === "'" || character === '"' || character === '`') { // A backslash escapes nothing in a quoted name, `ANSI_QUOTES` double quotes included. const name = character === '`' || (character === '"' && mode.ansiQuotes); - lexer.index = skipMySqlQuoted(sql, index, character, mode.backslashEscapes && !name); - return sql.slice(index, lexer.index); + const end = closeMySqlQuoted(sql, index, character, mode.backslashEscapes && !name); + lexer.rejected ||= end === undefined; + lexer.index = end ?? sql.length; + const word = sql.slice(index, lexer.index); + // Whether a double quote opens a string or a name depends on the mode too. + lexer.modal ||= character !== '`' && word.includes('\\'); + return word; + } + // MariaDB's MSSQL mode quotes a name in square brackets. Elsewhere the server rejects a `[` + // outside a quoted text. + if (character === '[') { + lexer.modal ||= mode.mariaDb; + if (!mode.brackets) { + lexer.rejected = true; + } else { + const end = closeMySqlBracket(sql, index); + lexer.rejected ||= end === undefined; + lexer.index = end ?? sql.length; + return sql.slice(index, lexer.index); + } } if ( character === '#' || @@ -425,19 +494,23 @@ function readMySqlWord(sql: string, lexer: MySqlLexer, mode: MySqlServerMode): s ) { const newline = sql.indexOf('\n', index); lexer.index = newline === -1 ? sql.length : newline; + lexer.comment = true; } else if (lexer.inVersionComment && character === '*' && next === '/') { lexer.inVersionComment = false; lexer.index += 2; } else if (character === '/' && next === '*') { const executable = /^M?!/u.test(sql.slice(index + 2, index + 4)); const runsFrom = executable ? runsMySqlComment(sql, index + 2, mode) : undefined; + lexer.comment = true; if (runsFrom !== undefined) { lexer.inVersionComment = true; lexer.index = runsFrom; } else { // Any other comment, an optimizer hint (`/*+`) too, holds no statement. One the server // skips for its version may nest a comment. - lexer.index = skipMySqlComment(sql, index + 2, executable ? 1 : 0); + const end = skipMySqlComment(sql, index + 2, executable ? 1 : 0); + lexer.rejected ||= end === undefined; + lexer.index = end ?? sql.length; } } else if (/[ \t\n\v\f\r]/u.test(character)) { lexer.index++; @@ -474,8 +547,409 @@ const MYSQL_OTHER_OBJECTS = new Set([ 'view', ]); +/** + * A block that holds statements of its own, so a `;` in it does not end the statement, or a + * CASE expression, which ends at END like a CASE statement does. MariaDB's FOR loop is one too. + */ +type MySqlBlock = 'begin' | 'case' | 'caseExpression' | 'if' | 'loop' | 'while' | 'repeat' | 'for'; + +/** + * A block open in the statement being read. `depth` counts the parentheses around it, and `past` + * is set once a WHILE or FOR has come to its DO, or a REPEAT to its UNTIL. + */ +type MySqlOpenBlock = { kind: MySqlBlock; depth: number; past: boolean }; + +// Compound statements that close with END and their own name, such as END IF. +const MYSQL_CONTROL_BLOCKS = new Set(['if', 'loop', 'while', 'repeat', 'for']); +// The words a stored procedure's characteristics are made of, between its parameters and body. +const MYSQL_PROCEDURE_CHARACTERISTICS = new Set([ + 'comment', + 'contains', + 'data', + 'definer', + 'deterministic', + 'invoker', + 'language', + 'modifies', + 'no', + 'not', + 'reads', + 'security', + 'sql', +]); +// The words a stored function's body starts with when it is a compound statement. Its other +// body is a RETURN. +const MYSQL_BODY_BLOCKS = new Set(['begin', 'case', ...MYSQL_CONTROL_BLOCKS]); + +// The words after which an expression goes on with an operand, so that a name there, such as an +// `end` column, is not the END of a CASE expression or of a REPEAT's UNTIL condition, nor a `do` +// column the DO of a WHILE. Operators written with other characters than letters do the same. +const MYSQL_OPERAND_BEFORE = new Set([ + 'and', + 'between', + 'binary', + 'case', + 'div', + 'else', + 'elseif', + 'if', + 'in', + 'interval', + 'is', + 'like', + 'mod', + 'not', + 'of', + 'or', + 'regexp', + 'return', + 'rlike', + 'then', + 'until', + 'when', + 'while', + 'xor', +]); + +/** Whether an operand follows `previous`, the word before it in an expression. */ +function expectsMySqlOperand(previous: string | undefined): boolean { + return ( + previous === undefined || + MYSQL_OPERAND_BEFORE.has(previous) || + // An operator or an opening parenthesis. A closing one, a `?` placeholder and the `}` of an + // ODBC literal end an operand. + (previous.length === 1 && !/[\w$)?}\u0080-￿]/u.test(previous)) + ); +} + +// What a handler does when its condition comes, in DECLARE ... HANDLER. +const MYSQL_HANDLER_ACTIONS = new Set(['continue', 'exit', 'undo']); + +/** + * Where DECLARE ... HANDLER FOR is in its conditions: before FOR, before a condition, after + * SQLSTATE, before the last word of a condition (SQLSTATE VALUE's text, NOT's FOUND), or after a + * condition, where a comma or the handler's statement follows. + */ +type MySqlHandlerPart = 'for' | 'condition' | 'sqlstate' | 'last' | 'after'; + +/** Where a handler's conditions are after `word`, or `'statement'` when its statement starts. */ +function nextMySqlHandlerPart( + part: MySqlHandlerPart, + word: string, +): MySqlHandlerPart | 'statement' | undefined { + switch (part) { + case 'for': + return word === 'for' ? 'condition' : undefined; + case 'condition': + return word === 'sqlstate' ? 'sqlstate' : word === 'not' ? 'last' : 'after'; + case 'sqlstate': + return word === 'value' ? 'last' : 'after'; + case 'last': + return 'after'; + default: + return word === ',' ? 'condition' : 'statement'; + } +} + +/** Where a stored program's statement is, up to the start of its body. */ +type MySqlProgramHead = + | 'name' + | 'parameters' + | 'characteristics' + | 'triggerOrder' + | 'triggerOrderName' + | 'body'; + +/** One top-level statement of MySQL SQL. */ +type MySqlStatementRead = { + /** Its words, without the `;` that ends it, empty when it holds only comments or nothing. */ + words: Array; + /** Where the next statement starts: after the `;`, or at the end of the SQL. */ + end: number; + inVersionComment: boolean; + /** Whether a `;` ends it, so another statement may follow. */ + terminated: boolean; + modal: boolean; + rejected: boolean; + comment: boolean; +}; + +/** + * Close the innermost block at an END. `next` is the word after it, which names the block for + * END IF, END LOOP, END WHILE, END REPEAT, END FOR and END CASE. Returns whether `next` belongs + * to the END. + */ +function closeMySqlBlock(blocks: Array, next: string | undefined): boolean { + const top = blocks.at(-1)?.kind; + if (top === 'caseExpression') { + // A CASE expression ends at its END, whatever follows it, as in `END FOR UPDATE`. + blocks.pop(); + return next === 'case'; + } + if (next !== undefined && MYSQL_CONTROL_BLOCKS.has(next)) { + // An END IF whose IF opened no block here closes nothing. + // MariaDB's Oracle mode ends WHILE and FOR loops with END LOOP. + if (top === next || (next === 'loop' && (top === 'while' || top === 'for'))) { + blocks.pop(); + } + return true; + } + if (next === 'case') { + if (top === 'case') { + blocks.pop(); + } + return true; + } + // A plain END closes a BEGIN block, and any block left open in it. + for (let index = blocks.length - 1; index >= 0; index--) { + if (blocks[index].kind === 'begin' || blocks[index].kind === 'case') { + blocks.length = index; + break; + } + } + return false; +} + +/** + * Read one top-level statement of MySQL SQL the way a server in `mode` does, from where `lexer` + * is to its `;` or the end of the SQL. + * + * A statement ends at a semicolon outside any block. A stored program's body (`CREATE + * PROCEDURE`, `FUNCTION`, `TRIGGER` or `EVENT`, and `ALTER EVENT`) holds statements of its own: + * a BEGIN block, or an IF, CASE, LOOP, WHILE, REPEAT or MariaDB FOR statement, which may also + * stand alone as the body. MariaDB also runs these, and BEGIN NOT ATOMIC blocks, outside stored + * programs. Each opens a block only where a statement starts, a handler's statement among them, + * so the IF() function and DROP TABLE IF EXISTS do not, and BEGIN elsewhere starts a transaction + * or is a name. END closes a block where a statement starts too, and ends a CASE expression or + * a REPEAT's UNTIL condition after an operand; elsewhere it is a name, as `begin` and `end` + * columns are. A CASE expression nests anywhere. A word after a dot or right after an `@` is a + * name, such as the column in `t.case` or the variable `@case`, as is the account in + * `DEFINER = account`. + */ +function readMySqlStatement( + sql: string, + lexer: MySqlLexer, + mode: MySqlServerMode, +): MySqlStatementRead { + lexer.modal = false; + lexer.rejected = false; + lexer.comment = false; + const words: Array = []; + const blocks: Array = []; + // The stored program a CREATE or ALTER makes, once it names one, and how far its head goes. + let program: string | undefined; + let otherObject = false; + let head: MySqlProgramHead = 'name'; + let parentheses = 0; + // Whether a function's body is a RETURN. In MariaDB's Oracle mode, RETURN gives the function's + // type, and its body starts after AS or IS. + let returns = false; + // The parentheses open at the word being read. + let depth = 0; + // Where a DECLARE ... HANDLER FOR is in its conditions. + let handler: MySqlHandlerPart | undefined; + // Whether the next word starts a statement, and whether the last one did. + let startsNext = true; + let startedLast = false; + // Set right after an END, when the word after it names the block it closed. + let namesBlock = false; + // Where the word before ends, and whether it is a name, which ends an operand. + let wordEnd = -1; + let named = false; + const result = (terminated: boolean): MySqlStatementRead => ({ + words, + end: lexer.index, + inVersionComment: lexer.inVersionComment, + terminated, + modal: lexer.modal, + rejected: lexer.rejected, + comment: lexer.comment, + }); + // The words after the one just read, without moving on. + const ahead = (count: number) => { + const copy = { ...lexer }; + return Array.from({ length: count }, () => readMySqlWord(sql, copy, mode)); + }; + for ( + let word = readMySqlWord(sql, lexer, mode); + word !== undefined; + word = readMySqlWord(sql, lexer, mode) + ) { + const touches = lexer.start === wordEnd; + wordEnd = lexer.index; + if (word === ';') { + if (blocks.length === 0) { + return result(true); + } + words.push(word); + startsNext = true; + startedLast = false; + namesBlock = false; + named = false; + handler = undefined; + continue; + } + const previous = words.at(-1); + const operandBefore = !named && expectsMySqlOperand(previous); + named = false; + words.push(word); + let starts = startsNext; + startsNext = false; + const afterLabel = word === ':' && startedLast; + startedLast = false; + const closing = namesBlock; + namesBlock = false; + if (word === '(') { + depth++; + } else if (word === ')') { + depth--; + } + // A word after a dot names a column or other object, and one right after an `@` a variable, + // or the host of an account. + if (previous === '.' || (previous === '@' && touches)) { + named = true; + continue; + } + if ((words[0] === 'create' || words[0] === 'alter') && program === undefined && !otherObject) { + // The account in DEFINER = account, such as user@localhost, names no object. + if (previous === '=' && words.at(-3) === 'definer') { + continue; + } + if (MYSQL_STORED_PROGRAMS.has(word)) { + program = word; + continue; + } + otherObject = MYSQL_OTHER_OBJECTS.has(word); + } else if (program !== undefined && head !== 'body') { + // Find where the body starts: after a procedure's or function's parameters and + // characteristics (a function's RETURNS type among them), a trigger's FOR EACH ROW and + // FOLLOWS or PRECEDES, or an event's DO. In MariaDB's Oracle mode, a procedure's or + // function's body starts after AS or IS, with or without parameters before it. + const routine = program === 'procedure' || program === 'function'; + if (head === 'name') { + if (word === '(' && routine) { + head = 'parameters'; + parentheses = 1; + } else if (program === 'trigger' && word === 'row' && previous === 'each') { + head = 'triggerOrder'; + } else if ( + (program === 'event' && + word === 'do' && + !['event', 'exists', 'to'].includes(previous ?? '')) || + (routine && (word === 'as' || word === 'is')) + ) { + // The word before a DO may name the event, as in CREATE EVENT do. + head = 'body'; + startsNext = true; + } + } else if (head === 'parameters') { + if (word === '(') { + parentheses++; + } else if (word === ')' && --parentheses === 0) { + head = 'characteristics'; + } + } else if (head === 'characteristics') { + if (word === ':' || word === 'as' || word === 'is') { + // The word before a `:` labels the body, and may be a characteristic's word. + head = 'body'; + startsNext = true; + } else if (program === 'procedure') { + if (!MYSQL_PROCEDURE_CHARACTERISTICS.has(word) && !/^['"]/u.test(word)) { + head = 'body'; + starts = true; + } + } else if (word === 'return' || MYSQL_BODY_BLOCKS.has(word)) { + head = 'body'; + starts = true; + returns = word === 'return'; + } + } else if (head === 'triggerOrder') { + if (word === 'follows' || word === 'precedes') { + head = 'triggerOrderName'; + } else { + head = 'body'; + starts = true; + } + } else { + head = 'body'; + startsNext = true; + } + } + if (handler !== undefined) { + const part = nextMySqlHandlerPart(handler, word); + handler = part === 'statement' ? undefined : part; + starts ||= part === 'statement'; + } else if ( + word === 'handler' && + blocks.length > 0 && + MYSQL_HANDLER_ACTIONS.has(previous ?? '') && + words.at(-3) === 'declare' + ) { + handler = 'for'; + } + const top = blocks.at(-1); + if (closing && (MYSQL_CONTROL_BLOCKS.has(word) || word === 'case')) { + // The name of the block the END before it closed. + } else if (starts && MYSQL_CONTROL_BLOCKS.has(word)) { + blocks.push({ kind: word as MySqlBlock, depth, past: false }); + // A LOOP or REPEAT holds its statements right after its name. + startsNext = word === 'loop' || word === 'repeat'; + } else if (word === 'case') { + blocks.push({ kind: starts ? 'case' : 'caseExpression', depth, past: false }); + } else if ( + word === 'begin' && + starts && + // At the top level, BEGIN starts a transaction, unless MariaDB's BEGIN NOT ATOMIC opens a + // block. + (program !== undefined || blocks.length > 0 || ahead(2).join(' ') === 'not atomic') + ) { + blocks.push({ kind: 'begin', depth, past: false }); + startsNext = true; + } else if ( + word === 'end' && + top !== undefined && + (starts || + ((top.kind === 'caseExpression' || (top.kind === 'repeat' && top.past)) && + top.depth === depth && + !operandBefore)) + ) { + namesBlock = closeMySqlBlock(blocks, ahead(1)[0]); + } else if (word === 'until' && starts && top?.kind === 'repeat') { + top.past = true; + } else if ( + // The DO of a WHILE or a MariaDB FOR, after its condition, not a `do` column in it. + word === 'do' && + (top?.kind === 'while' || top?.kind === 'for') && + !top.past && + top.depth === depth && + !operandBefore + ) { + top.past = true; + startsNext = true; + } else if ( + ((word === 'then' || word === 'else') && top?.kind !== 'caseExpression') || + // In MariaDB's Oracle mode, WHILE and FOR loops hold their statements after LOOP. + word === 'loop' || + afterLabel || + (word === 'atomic' && previous === 'not' && words.at(-3) === 'begin') || + (returns && blocks.length === 0 && depth === 0 && (word === 'as' || word === 'is')) + ) { + startsNext = true; + } + startedLast = starts; + } + return result(false); +} + /** How a server's quoting rules stand after a statement changes its `sql_mode`. */ -type MySqlQuoting = Pick; +type MySqlQuoting = Pick; + +/** + * How a statement changes the session's quoting rules: not at all (`undefined`), to the rules + * a quoted list of modes sets, or in a way this scan cannot read (`'unclear'`), such as + * `SET sql_mode = @saved`. + */ +type MySqlModeChange = MySqlQuoting | 'unclear' | undefined; // The modes that turn on ANSI_QUOTES: itself, and the combination modes that include it. const MYSQL_ANSI_QUOTES_MODES = new Set([ @@ -490,21 +964,69 @@ const MYSQL_ANSI_QUOTES_MODES = new Set([ const MYSQL_GLOBAL_SCOPES = new Set(['global', 'persist', 'persist_only']); const MYSQL_SESSION_SCOPES = new Set(['session', 'local']); -/** The name a word in a SET statement gives, unquoted and lowercased. */ -function mySqlName(word: string | undefined, mode: MySqlServerMode): string | undefined { +/** Whether a word is a quoted name. */ +function isMySqlQuotedName(word: string | undefined, mode: MySqlServerMode): word is string { const quote = word?.[0]; - if (word !== undefined && (quote === '`' || (quote === '"' && mode.ansiQuotes))) { - return word.slice(1, -1).replaceAll(`${quote}${quote}`, quote).toLowerCase(); + return quote === '`' || (quote === '"' && mode.ansiQuotes) || (quote === '[' && mode.brackets); +} + +/** The name a word gives, unquoted and lowercased. */ +function mySqlName(word: string | undefined, mode: MySqlServerMode): string | undefined { + if (isMySqlQuotedName(word, mode)) { + const close = word[0] === '[' ? ']' : word[0]; + return word.slice(1, -1).replaceAll(`${close}${close}`, close).toLowerCase(); } return word; } +/** Whether a word is a quoted string, not a name. */ +function isMySqlString(word: string | undefined, mode: MySqlServerMode): word is string { + const quote = word?.[0]; + return ( + word !== undefined && + (quote === "'" || (quote === '"' && !mode.ansiQuotes)) && + word.length >= 2 && + word.endsWith(quote) + ); +} + +// What a backslash escape in a string stands for. Any other character stands for itself, and +// `\%` and `\_` keep their backslash. +const MYSQL_ESCAPES = new Map([ + ['0', '\0'], + ['b', '\b'], + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['Z', '\u001A'], + ['%', String.raw`\%`], + ['_', String.raw`\_`], +]); + +/** The text of a quoted string. */ +function mySqlStringText(word: string, mode: MySqlServerMode): string { + const quote = word[0]; + let text = ''; + for (let index = 1; index < word.length - 1; index++) { + const character = word[index]; + if (character === '\\' && mode.backslashEscapes) { + const escaped = word[++index]; + text += MYSQL_ESCAPES.get(escaped) ?? escaped; + } else { + text += character; + // A doubled quote stands for one. + if (character === quote) { + index++; + } + } + } + return text; +} + /** The quoting rules a quoted list of modes, such as `'ANSI,NO_BACKSLASH_ESCAPES'`, sets. */ function mySqlModeList(value: Array, mode: MySqlServerMode): MySqlQuoting | 'unclear' { const [word] = value; - const quote = word?.[0]; - const string = quote === "'" || (quote === '"' && !mode.ansiQuotes); - if (value.length !== 1 || !string || word.length < 2 || !word.endsWith(quote)) { + if (value.length !== 1 || !isMySqlString(word, mode)) { return 'unclear'; } const text = word.slice(1, -1); @@ -517,6 +1039,7 @@ function mySqlModeList(value: Array, mode: MySqlServerMode): MySqlQuotin return { backslashEscapes: !modes.includes('NO_BACKSLASH_ESCAPES'), ansiQuotes: modes.some((name) => MYSQL_ANSI_QUOTES_MODES.has(name)), + brackets: mode.mariaDb && modes.includes('MSSQL'), }; } @@ -542,33 +1065,12 @@ function splitMySqlWords(words: Array, at = ','): Array> { } /** - * How a top-level statement changes the session's quoting rules: not at all (`undefined`), to - * the rules a quoted list of modes sets, or in a way this scan cannot read (`'unclear'`), such - * as `SET sql_mode = @saved` or a prepared statement's `EXECUTE`. A stored program, and a - * MariaDB `BEGIN NOT ATOMIC` block, run with a `sql_mode` of their own and restore the - * session's, and `SET GLOBAL` leaves it alone. + * How a SET statement changes the session's quoting rules. `SET GLOBAL` leaves them alone, as + * does a SET of a user variable. */ -function mySqlModeChange( - words: Array, - mode: MySqlServerMode, -): MySqlQuoting | 'unclear' | undefined { - const [first] = words; - // A prepared statement, or MariaDB's EXECUTE IMMEDIATE, may set sql_mode. - if (first === 'execute') { - return 'unclear'; - } - if (first !== 'set') { - return undefined; - } - if (words[1] === 'statement') { - // MariaDB's SET STATEMENT ... FOR keeps what the statement after FOR changes, unless it - // sets sql_mode itself, which it then restores. - const [settings, statement] = splitMySqlWords(words.slice(2), 'for'); - const restores = settings.some((word) => mySqlName(word, mode) === 'sql_mode'); - return statement === undefined || restores ? undefined : mySqlModeChange(statement, mode); - } +function mySqlSetChange(words: Array, mode: MySqlServerMode): MySqlModeChange { const assignments = splitMySqlWords(words.slice(1)); - let change: MySqlQuoting | 'unclear' | undefined; + let change: MySqlModeChange; // A GLOBAL or SESSION before an assignment holds for the ones after it. let global = false; for (const assignment of assignments) { @@ -611,122 +1113,456 @@ function mySqlModeChange( } /** - * The statements of MySQL SQL, in order: `calls` tells which ones are `CALL`s. When `uncounted` - * is true, more statements follow them, none of them a `CALL`, which this scan cannot count. + * How a statement's results arrive: one result (`'single'`), or like a CALL's (`'call'`), each + * result set the statements in it return and then one result header. `'unknown'` is an EXECUTE + * of a statement this scan cannot see. + */ +type MySqlResultKind = 'single' | 'call' | 'unknown'; + +/** What a statement prepared by PREPARE returns when EXECUTE runs it, and how it sets sql_mode. */ +type MySqlPreparedStatement = { kind: MySqlResultKind; change: MySqlModeChange }; + +/** The statements prepared so far, by name. */ +type MySqlPrepared = Map; + +/** What one statement does that matters for reading the statements after it and its results. */ +type MySqlEffect = MySqlPreparedStatement & { + /** + * A PREPARE of a statement (`statement` undefined when this scan cannot see it), or a + * DEALLOCATE, by name. + */ + prepares?: { + name: string | undefined; + statement: MySqlPreparedStatement | undefined; + deallocates?: boolean; + }; + /** The prepared statement an EXECUTE runs. */ + executes?: string; + /** Whether the server rejects the statement read this way. */ + rejected?: boolean; +}; + +const MYSQL_SINGLE: MySqlEffect = { kind: 'single', change: undefined }; + +/** + * Whether the server rejects the text a PREPARE or EXECUTE IMMEDIATE is given: a quoted name + * there, such as a double-quoted text in `ANSI_QUOTES` mode, names no statement. + */ +function rejectsMySqlSource(source: Array, mode: MySqlServerMode): boolean { + return source.length === 1 && isMySqlQuotedName(source[0], mode); +} + +/** The statement in a PREPARE's or EXECUTE IMMEDIATE's text, when it is a quoted string. */ +function mySqlPreparedStatement( + source: Array, + mode: MySqlServerMode, +): MySqlPreparedStatement | undefined { + const [word] = source; + if (source.length !== 1 || !isMySqlString(word, mode)) { + return undefined; + } + // The server prepares one statement and rejects more, so the first one is the statement. + const { words } = readMySqlStatement(mySqlStringText(word, mode), newMySqlLexer(), mode); + const { kind, change } = mySqlStatementEffect(words, mode, new Map()); + return { kind, change }; +} + +/** + * What a top-level statement does. A CALL, and a compound statement that MariaDB runs outside + * a stored program (a BEGIN NOT ATOMIC block, IF, CASE, LOOP, WHILE, REPEAT or FOR), return + * their results like a CALL. So does an EXECUTE, or MariaDB's EXECUTE IMMEDIATE, of a CALL. + * MariaDB's SET STATEMENT ... FOR returns what the statement after FOR does, and keeps what it + * changes unless it sets sql_mode itself, which it then restores. A stored program, and a + * compound statement, run with a sql_mode of their own and restore the session's. */ -export type MySqlStatements = { calls: Array; uncounted: boolean }; +function mySqlStatementEffect( + words: Array, + mode: MySqlServerMode, + prepared: MySqlPrepared, +): MySqlEffect { + const [first, second] = words; + if ( + first === 'call' || + first === 'case' || + MYSQL_CONTROL_BLOCKS.has(first) || + (first === 'begin' && second === 'not' && words[2] === 'atomic') + ) { + return { kind: 'call', change: undefined }; + } + if (first === 'execute') { + // MariaDB's EXECUTE IMMEDIATE runs the text it is given. In MySQL, IMMEDIATE may name a + // prepared statement, which only a USING may follow. + if (second === 'immediate' && words.length > 2 && words[2] !== 'using') { + const [source] = splitMySqlWords(words.slice(2), 'using'); + const statement = mySqlPreparedStatement(source, mode); + return { + ...(statement ?? { kind: 'unknown', change: 'unclear' }), + rejected: rejectsMySqlSource(source, mode), + }; + } + const name = mySqlName(second, mode) ?? ''; + return { ...(prepared.get(name) ?? { kind: 'unknown', change: 'unclear' }), executes: name }; + } + if (first === 'prepare' && words[2] === 'from') { + const source = words.slice(3); + return { + ...MYSQL_SINGLE, + prepares: { name: mySqlName(second, mode), statement: mySqlPreparedStatement(source, mode) }, + rejected: rejectsMySqlSource(source, mode), + }; + } + if ((first === 'deallocate' || first === 'drop') && second === 'prepare') { + return { + ...MYSQL_SINGLE, + prepares: { name: mySqlName(words[2], mode), statement: undefined, deallocates: true }, + }; + } + if (first === 'set' && second === 'statement') { + const [settings, statement] = splitMySqlWords(words.slice(2), 'for'); + if (statement === undefined) { + return MYSQL_SINGLE; + } + const effect = mySqlStatementEffect(statement, mode, prepared); + const restores = settings.some((word) => mySqlName(word, mode) === 'sql_mode'); + return restores ? { ...effect, change: undefined } : effect; + } + if (first === 'set') { + return { kind: 'single', change: mySqlSetChange(words, mode) }; + } + return MYSQL_SINGLE; +} /** - * Find MySQL's statements and tell which are `CALL`s, reading the SQL the way a server in - * `mode` does. Statements end at top-level semicolons. In a stored program (`CREATE PROCEDURE`, - * `FUNCTION`, `TRIGGER` or `EVENT`, and `ALTER EVENT`), a `BEGIN ... END` body holds semicolons - * of its own, so it nests, as does MariaDB's `BEGIN NOT ATOMIC` block. Elsewhere `BEGIN` starts a - * transaction or is a name. A `CASE ... END` nests anywhere. `END IF`, `END LOOP`, `END WHILE` - * and `END REPEAT` close blocks that sit inside a `BEGIN`, so they do not change the depth. After - * a dot, each of these words is a name, such as the column in `t.case`. + * Each quoting mode a server of `mode`'s version and family may be in. Only MariaDB reads + * square brackets as quotes, in its MSSQL mode. + */ +function mySqlQuotingModes(mode: MySqlServerMode): Array { + return [true, false].flatMap((backslashEscapes) => + [false, true].flatMap((ansiQuotes) => + (mode.mariaDb ? [false, true] : [false]).map((brackets) => ({ + ...mode, + backslashEscapes, + ansiQuotes, + brackets, + })), + ), + ); +} + +/** Whether two modes read quoted text the same. */ +function sameMySqlQuoting(a: MySqlQuoting, b: MySqlQuoting): boolean { + return ( + a.backslashEscapes === b.backslashEscapes && + a.ansiQuotes === b.ansiQuotes && + a.brackets === b.brackets + ); +} + +/** The modes a server in `mode` may be in after a statement that makes `change`. */ +function nextMySqlModes(mode: MySqlServerMode, change: MySqlModeChange): Array { + if (change === 'unclear') { + return mySqlQuotingModes(mode); + } + return [change === undefined ? mode : { ...mode, ...change }]; +} + +/** Record what a PREPARE or DEALLOCATE does, the same in every mode the server may be in. */ +function applyMySqlPrepares(prepared: MySqlPrepared, effects: Array): void { + if (effects[0].kind === 'call') { + // A procedure may prepare or deallocate statements of the session, though not the one that + // runs it, which the server refuses. + const { executes } = effects[0]; + for (const name of prepared.keys()) { + if (name !== executes) { + prepared.delete(name); + } + } + return; + } + const [{ prepares }] = effects; + if (prepares === undefined) { + return; + } + const agree = effects.every( + (effect) => JSON.stringify(effect.prepares) === JSON.stringify(prepares), + ); + for (const effect of effects) { + const name = effect.prepares?.name; + if (name !== undefined) { + prepared.delete(name); + } + } + if (agree && prepares.name !== undefined && prepares.statement !== undefined) { + prepared.set(prepares.name, prepares.statement); + } +} + +const MYSQL_UNKNOWN_EXECUTE = + "db: `void db execute --json` cannot tell whether an EXECUTE in this MySQL SQL runs a CALL, which returns several results, so it cannot group them. It reads the statement that a PREPARE or EXECUTE IMMEDIATE in the same SQL takes as a quoted string, such as PREPARE s FROM 'CALL p()', but a procedure may prepare a statement again, so it forgets the others after a CALL. Prepare the statement again after the CALL, or run SQL that prepares a statement from a variable or an expression without --json."; + +/** The error for SQL whose statements this scan cannot tell apart, which says what it cannot do. */ +function unclearMySqlStatements(consequence: string, remedy: string): Error { + return new Error( + `db: \`void db execute --json\` cannot tell where the statements of this MySQL SQL end, so it ${consequence}. A statement in it changes sql_mode in a way the command cannot read, such as SET sql_mode = @saved, and the mode decides how quoted text reads, such as what a backslash in a string means. Set sql_mode to a quoted list of modes, such as SET sql_mode = 'ANSI_QUOTES', or ${remedy}.`, + ); +} + +const MYSQL_UNCLEAR_CALL = () => + unclearMySqlStatements( + 'cannot group the results of a statement after it that returns several, such as a CALL', + 'run that statement in a separate command', + ); + +/** + * The statements of MySQL SQL, in order: `calls` tells which ones return their results like a + * CALL. When `uncounted` is true, more statements follow them, none of them like a CALL, which + * this scan cannot count. `sql` is the SQL to run: comments after the last statement are left + * out, since the server would answer them with a result of their own. + */ +export type MySqlStatements = { calls: Array; uncounted: boolean; sql: string }; + +/** + * Find MySQL's statements (see `readMySqlStatement`) and tell which return their results like a + * CALL (see `mySqlStatementEffect`), reading the SQL the way a server in `mode` does. * * The server reads each statement with the `sql_mode` the statements before it left, so a * `SET sql_mode` to a quoted list of modes changes how the SQL after it reads. After a statement - * that changes it in a way this scan cannot read, the SQL reads the same until a quoted string - * or name holds a backslash. From there on, the statements are `uncounted` when none of them can be a `CALL`, - * and otherwise this throws before the SQL runs, since their results could not be grouped. + * that changes it in a way this scan cannot read, the SQL is read in each quoting mode the + * server may be in, leaving out a reading that leaves a quoted string open, or finds a `[` that + * quotes no name, which the server rejects. Where they read different statements, the statements are `uncounted` when none of + * them can return results like a CALL, and otherwise this throws before the SQL runs, since + * their results could not be grouped. It also throws for an EXECUTE of a statement it cannot + * see, which may be a CALL. */ export function mySqlStatements( sql: string, initialMode: MySqlServerMode = MYSQL_DEFAULT_MODE, ): MySqlStatements { - let mode = initialMode; - const lexer: MySqlLexer = { index: 0, inVersionComment: false }; + const lexer = newMySqlLexer(); + let modes = [initialMode]; + const prepared: MySqlPrepared = new Map(); const calls: Array = []; - let depth = 0; - // The current statement's words, and where it starts. - let words: Array = []; - let start = 0; - // Whether this statement creates a stored program, once its CREATE or ALTER names the object. - let storedProgram: boolean | undefined; - // Set right after an END that closed a block, so a following IF, LOOP, WHILE, REPEAT or CASE - // reads as part of that END. - let afterEnd = false; - // Whether a statement changed sql_mode in a way this scan cannot read. Until a quoted string - // or name holds a backslash, every mode reads the SQL after it the same way. - let unclear = false; - const finish = () => { - if (words.length > 0) { - calls.push(words[0] === 'call'); - const change = mySqlModeChange(words, mode); - if (change === 'unclear') { - unclear = true; - } else if (change !== undefined) { - mode = { ...mode, ...change }; - unclear = false; - } + // Where the SQL may be cut after its last statement, and whether only comments follow it. + let cut: number | undefined; + let trailingComment = false; + let read: MySqlStatementRead; + do { + const from = { ...lexer }; + read = readMySqlStatement(sql, lexer, modes[0]); + // Without a backslash in a quoted string or name, or a `[` on MariaDB, every quoting mode + // reads it the same. + let readings = modes.map((mode, index) => ({ + mode, + read: index === 0 || !read.modal ? read : readMySqlStatement(sql, { ...from }, mode), + })); + const accepted = readings.filter((reading) => !reading.read.rejected); + if (accepted.length > 0) { + readings = accepted; } - words = []; - start = lexer.index; - storedProgram = undefined; - afterEnd = false; - }; - // Whether the BEGIN just read opens MariaDB's BEGIN NOT ATOMIC block, read without moving on. - const opensBlock = () => { - const ahead = { ...lexer }; - return ( - readMySqlWord(sql, ahead, mode) === 'not' && readMySqlWord(sql, ahead, mode) === 'atomic' - ); - }; - for ( - let word = readMySqlWord(sql, lexer, mode); - word !== undefined; - word = readMySqlWord(sql, lexer, mode) - ) { - if (unclear && word.includes('\\')) { - // `CALL` is a word of its own, so SQL without it holds none. A digit may come before it, - // as in `/*!80000CALL`. - if (/(? !sameMySqlStatement(reading.read, chosen))) { + return divergedMySqlStatements( + sql, + from, + readings.map((reading) => reading.mode), + { + calls, + prepared, + }, + ); } - const previous = words.at(-1); - if (word === ';') { - afterEnd = false; - if (depth === 0) { - finish(); - } else { - words.push(word); - } + lexer.index = read.end; + lexer.inVersionComment = read.inVersionComment; + if (read.words.length === 0) { + trailingComment ||= read.comment; + cut = mySqlCut(cut, read); continue; } - words.push(word); - const first = words[0]; - if ((first === 'create' || first === 'alter') && storedProgram === undefined) { - if (MYSQL_STORED_PROGRAMS.has(word)) { - storedProgram = true; - } else if (MYSQL_OTHER_OBJECTS.has(word)) { - storedProgram = false; - } + let effects = readings.map((reading) => + mySqlStatementEffect(read.words, reading.mode, prepared), + ); + // As with a quoted string left open, the server is not in a mode that rejects the statement. + if (effects.some((effect) => !effect.rejected)) { + readings = readings.filter((_, index) => !effects[index].rejected); + effects = effects.filter((effect) => !effect.rejected); } - const closedBlock = afterEnd; - afterEnd = false; - // A word after a dot names a column or other object. - if (previous === '.') { + if (effects.some((effect) => effect.kind === 'unknown')) { + throw new Error(MYSQL_UNKNOWN_EXECUTE); + } + if (effects.some((effect) => effect.kind !== effects[0].kind)) { + throw MYSQL_UNCLEAR_CALL(); + } + calls.push(effects[0].kind === 'call'); + applyMySqlPrepares(prepared, effects); + const next = readings.flatMap((reading, index) => + nextMySqlModes(reading.mode, effects[index].change), + ); + modes = next.filter( + (mode, index) => next.findIndex((other) => sameMySqlQuoting(other, mode)) === index, + ); + cut = mySqlCut(undefined, read); + trailingComment = false; + } while (read.terminated); + return { + calls, + uncounted: false, + sql: trailingComment && cut !== undefined ? sql.slice(0, cut) : sql, + }; +} + +/** + * Where the SQL may be cut to leave out what follows a statement, after reading `read`: at the + * end of a statement, unless an executable comment is still open there, and not where comments + * that follow leave one open, which the server rejects. + */ +function mySqlCut(cut: number | undefined, read: MySqlStatementRead): number | undefined { + if (read.words.length > 0) { + return read.inVersionComment ? undefined : read.end; + } + return read.rejected ? undefined : cut; +} + +/** Whether two readings of a statement find the same words and end in the same place. */ +function sameMySqlStatement(a: MySqlStatementRead, b: MySqlStatementRead): boolean { + return ( + a === b || + (a.end === b.end && + a.inVersionComment === b.inVersionComment && + a.words.length === b.words.length && + a.words.every((word, index) => word === b.words[index])) + ); +} + +/** + * Record a PREPARE that one way of reading diverged SQL finds, in the statements all the ways + * share. Returns 1 when that forgets a statement some way may have read an EXECUTE with. + * + * A name keeps a statement while every way that prepares it prepares the same one as before, + * or the first time. A way that does not prepare it then reads the statement prepared before, + * which is the same, or none, and the server rejects its EXECUTE. Otherwise the name is + * forgotten for every way. A DEALLOCATE changes nothing here: its own way then fails on the + * server at any EXECUTE of the name, and the others still read the statement. + */ +function prepareDivergedMySql( + effect: MySqlEffect, + before: MySqlPrepared, + prepared: MySqlPrepared, + conflicts: Set, +): number { + const { name, statement, deallocates } = effect.prepares ?? {}; + if (name === undefined || deallocates || conflicts.has(name)) { + return 0; + } + const same = (other: MySqlPreparedStatement | undefined) => + other === undefined || JSON.stringify(other) === JSON.stringify(statement); + if (statement !== undefined && same(prepared.get(name)) && same(before.get(name))) { + prepared.set(name, statement); + return 0; + } + conflicts.add(name); + return prepared.delete(name) ? 1 : 0; +} + +/** One way the server may read the SQL from a statement on. */ +type MySqlReading = { + lexer: MySqlLexer; + mode: MySqlServerMode; + cut: number | undefined; +}; + +/** + * The statements of SQL whose quoting modes read the statement at `from` differently. Every way + * the server may read the rest is followed to the end. They are counted only where they hold + * no statement that returns results like a CALL, and comments after the last statement are left + * out only where every way agrees on where they start. + * + * The ways share their prepared statements (see `prepareDivergedMySql`), which tells less than + * each way knows, never more, and keeps the walk short. + */ +function divergedMySqlStatements( + sql: string, + from: MySqlLexer, + modes: Array, + before: { calls: Array; prepared: MySqlPrepared }, +): MySqlStatements { + const prepared = new Map(before.prepared); + // Names that ways of reading prepare differently. + const conflicts = new Set(); + let forgotten = 0; + const ends = new Set(); + // Each place is read once in each mode, and again once a prepared statement is forgotten. + // A statement prepared the first time changes no EXECUTE read before, since that one failed. + const seen = new Set(); + const readings: Array = modes.map((mode) => ({ + lexer: { ...from }, + mode, + cut: undefined, + })); + for (let reading = readings.pop(); reading !== undefined; reading = readings.pop()) { + const { lexer } = reading; + const key = JSON.stringify([ + lexer.index, + lexer.inVersionComment, + reading.mode.backslashEscapes, + reading.mode.ansiQuotes, + reading.mode.brackets, + reading.cut, + forgotten, + ]); + if (seen.has(key)) { continue; } - if (closedBlock && /^(?:if|loop|while|repeat)$/.test(word)) { - // That END closed an IF or loop, which never opened a level, so restore it. - depth++; - } else if (closedBlock && word === 'case') { - // END CASE closes the CASE that opened a level. - } else if (word === 'case' || (word === 'begin' && (storedProgram === true || opensBlock()))) { - depth++; - } else if (word === 'end' && depth > 0) { - depth--; - afterEnd = true; + seen.add(key); + let trailingComment = false; + let finished = true; + let read: MySqlStatementRead; + do { + read = readMySqlStatement(sql, lexer, reading.mode); + if (read.rejected) { + // The server rejects the SQL if it reads it this way. + finished = false; + break; + } + if (read.words.length === 0) { + trailingComment ||= read.comment; + continue; + } + const effect = mySqlStatementEffect(read.words, reading.mode, prepared); + if (effect.rejected) { + finished = false; + break; + } + if (effect.kind === 'unknown') { + throw new Error(MYSQL_UNKNOWN_EXECUTE); + } + if (effect.kind === 'call') { + throw MYSQL_UNCLEAR_CALL(); + } + forgotten += prepareDivergedMySql(effect, before.prepared, prepared, conflicts); + reading.cut = mySqlCut(undefined, read); + trailingComment = false; + if (effect.change === 'unclear') { + for (const next of mySqlQuotingModes(reading.mode)) { + readings.push({ lexer: { ...lexer }, mode: next, cut: reading.cut }); + } + finished = false; + break; + } + [reading.mode] = nextMySqlModes(reading.mode, effect.change); + } while (read.terminated); + if (finished) { + ends.add(trailingComment && reading.cut !== undefined ? reading.cut : sql.length); } } - finish(); - return { calls, uncounted: false }; + if (ends.size > 1) { + throw unclearMySqlStatements( + 'cannot tell whether the comments after its last statement return a result of their own', + 'remove those comments', + ); + } + const [end = sql.length] = ends; + return { calls: before.calls, uncounted: true, sql: sql.slice(0, end) }; } /** @@ -734,13 +1570,17 @@ export function mySqlStatements( * (rows, or a result header for a write) and `fields` holds each one's column list, or * `undefined` for a header. A `CALL` returns each result set of the procedure and then its own * header, so those entries are grouped under the `CALL`, its rows in order. `statements` is what - * `mySqlStatements` found in the SQL. + * `mySqlStatements` found in the SQL. SQL without a statement returns no entry, though the + * server answers comments alone with a result header. */ export function mySqlStatementResults( rows: unknown, fields: unknown, statements: MySqlStatements, ): Array { + if (statements.calls.length === 0 && !statements.uncounted) { + return []; + } const severalResults = Array.isArray(rows) && Array.isArray(fields) && diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 152315321..aa53f621d 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -973,7 +973,7 @@ async function executeExternalSql( ...(json ? { supportBigNumbers: true, bigNumberStrings: false, dateStrings: true } : {}), }); try { - const [rows, fields] = await mySqlClient.query(sql); + const [rows, fields] = await mySqlClient.query(statements?.sql ?? sql); if (statements) { printStatementResults(mySqlStatementResults(rows, fields, statements)); } else if (Array.isArray(rows) && rows.length > 0) { diff --git a/packages/void/src/runtime/db/migrations/mysql-sql.ts b/packages/void/src/runtime/db/migrations/mysql-sql.ts index a8a7b4de8..dbbc166a9 100644 --- a/packages/void/src/runtime/db/migrations/mysql-sql.ts +++ b/packages/void/src/runtime/db/migrations/mysql-sql.ts @@ -136,6 +136,16 @@ export function skipMySqlQuoted( quote: string, backslashEscapes = true, ): number { + return closeMySqlQuoted(sql, open, quote, backslashEscapes) ?? sql.length; +} + +/** Like `skipMySqlQuoted`, but `undefined` when the quote is still open at the end of the SQL. */ +export function closeMySqlQuoted( + sql: string, + open: number, + quote: string, + backslashEscapes = true, +): number | undefined { let index = open + 1; while (index < sql.length) { const character = sql[index]; @@ -153,5 +163,5 @@ export function skipMySqlQuoted( } index++; } - return sql.length; + return undefined; } diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index 62aae755f..ab47ed69d 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -939,6 +939,26 @@ describe('void db execute', () => { expect(result.meta).toMatchObject({ changes: 1, last_row_id: 1 }); }); + it("counts the rows a view's INSTEAD OF trigger writes", async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: [ + 'CREATE VIEW item_names AS SELECT name FROM items;', + 'CREATE TRIGGER item_names_insert INSTEAD OF INSERT ON item_names BEGIN', + ' INSERT INTO items (name) VALUES (new.name);', + 'END;', + "INSERT INTO item_names VALUES ('v');", + 'SELECT 1;', + ].join('\n'), + json: true, + }); + + expect(jsonOutput().map((result) => result.meta.changes)).toEqual([0, 0, 1, 0]); + expect(await readItems(root)).toEqual([{ name: 'v' }]); + }); + it('splits only between statements, not inside literals, comments or a trigger body', async () => { const root = await createLocalSqliteProject(); @@ -959,8 +979,8 @@ describe('void db execute', () => { const results = jsonOutput(); expect(results).toHaveLength(4); expect(results[3].results).toEqual([{ 'x;y': 'a;b' }, { 'x;y': 'c;d' }]); - // A trigger's writes do not count toward the statement's own changes. - expect(results[2].meta.changes).toBe(1); + // A trigger's writes count toward the statement's changes, as D1 counts them. + expect(results[2].meta.changes).toBe(3); }); it('stops at a failing statement after the ones before it took effect', async () => { diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index 682656fea..7a9a80a59 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -968,18 +968,53 @@ describe('void db execute --remote (PostgreSQL)', () => { : [[], []], ), ); - const command = String.raw`SET sql_mode = @saved; SELECT 'a\'; CALL p()`; + // With backslash escapes the string holds `';'`, without them it ends before the first `;`. + const command = String.raw`SET sql_mode = @saved; SELECT 'a\';\''; CALL p()`; await expect( runDbCommand(root, { action: 'execute', command, remote: true, json: true }), - ).rejects.toThrow('cannot group a CALL'); + ).rejects.toThrow('cannot tell where the statements of this MySQL SQL end'); expect(mockMySqlQuery.mock.calls.map(([sql]) => sql)).toEqual([ 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version', ]); + // Nor does it run an EXECUTE of a statement it cannot see, which may be a CALL. + mockMySqlQuery.mockClear(); + await expect( + runDbCommand(root, { + action: 'execute', + command: 'PREPARE s FROM @sql; EXECUTE s', + remote: true, + json: true, + }), + ).rejects.toThrow('cannot tell whether an EXECUTE in this MySQL SQL runs a CALL'); + expect(mockMySqlQuery).not.toHaveBeenCalled(); expect(console.log).not.toHaveBeenCalled(); mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); }); + it('runs MySQL SQL without the comments after its last statement with --json only', async () => { + const root = createProjectRoot({ database: 'mysql' }); + mockGetDatabaseUrl.mockResolvedValue({ url: 'mysql://host/db' }); + const header = { fieldCount: 0, affectedRows: 0, insertId: 0 }; + mockMySqlQuery.mockImplementation(() => + Promise.resolve([ + [[{ a: 1 }], header], + [[{ name: 'a' }], undefined], + ]), + ); + const command = 'CALL p(); -- end of script'; + + await runDbCommand(root, { action: 'execute', command, remote: true, json: true }); + await runDbCommand(root, { action: 'execute', command, remote: true }); + + // MySQL answers a comment after the last statement with a result of its own. + expect(mockMySqlQuery.mock.calls.map(([sql]) => sql)).toEqual(['CALL p();', command]); + expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + { results: [{ a: 1 }], success: true, meta: { affectedRows: 0, insertId: 0 } }, + ]); + mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); + }); + it('keeps PostgreSQL numeric arrays and JSON numbers exact with --json only', async () => { const root = createProjectRoot({ database: 'pg' }); mockGetDatabaseUrl.mockResolvedValue({ url: 'postgres://host/db' }); diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index 6db8faba5..cec77c16e 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -239,6 +239,7 @@ describe('db execute --json results', () => { version: 80_403, backslashEscapes: true, ansiQuotes: false, + brackets: false, mariaDb: false, }); const noEscapes = mySqlServerMode([ @@ -248,6 +249,7 @@ describe('db execute --json results', () => { version: 80_403, backslashEscapes: false, ansiQuotes: false, + brackets: false, mariaDb: false, }); // With NO_BACKSLASH_ESCAPES, a backslash before a quote is an ordinary character. @@ -294,6 +296,7 @@ describe('db execute --json results', () => { version: 101_106, backslashEscapes: true, ansiQuotes: false, + brackets: false, mariaDb: true, }); expect(calls('/*M!100100 SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); @@ -371,8 +374,9 @@ describe('db execute --json results', () => { ].join(';\n'), ), ).toEqual([false, false, true]); - // MariaDB runs BEGIN NOT ATOMIC blocks outside a stored program. - expect(calls('BEGIN NOT ATOMIC SELECT 1; SELECT 2; END; CALL p()')).toEqual([false, true]); + // MariaDB runs BEGIN NOT ATOMIC blocks outside a stored program, and returns their results + // like a CALL's. + expect(calls('BEGIN NOT ATOMIC SELECT 1; SELECT 2; END; CALL p()')).toEqual([true, true]); expect( groupResults( [[{ begin: 1 }], [{ a: 1 }], header], @@ -432,6 +436,7 @@ describe('db execute --json results', () => { `/*!40101 SET SQL_MODE = 'NO_BACKSLASH_ESCAPES' */`, `SET STATEMENT max_statement_time = 10 FOR SET sql_mode = 'NO_BACKSLASH_ESCAPES'`, `SET NAMES utf8mb4, sql_mode = 'ANSI_QUOTES,,NO_BACKSLASH_ESCAPES'`, + "EXECUTE IMMEDIATE 'SET sql_mode = ''NO_BACKSLASH_ESCAPES'''", ]) { expect(calls(`${set}; ${backslash}`), set).toEqual([false, false, true]); } @@ -482,62 +487,120 @@ describe('db execute --json results', () => { `CREATE PROCEDURE q() BEGIN SET sql_mode = 'NO_BACKSLASH_ESCAPES'; END`, `/*!99999 SET sql_mode = 'NO_BACKSLASH_ESCAPES' */ SELECT 1`, ]) { - expect(calls(`${statement}; ${backslash}`, mysql84), statement).toEqual([false, false]); + expect(calls(`${statement}; ${backslash}`, mysql84).slice(1), statement).toEqual([false]); } }); - it('stops reading MySQL SQL where an unclear change of sql_mode matters', () => { + it('reads MySQL SQL after an unclear change of sql_mode in each quoting mode', () => { const unclear = [ 'SET sql_mode = @saved', "SET sql_mode = CONCAT(@@sql_mode, ',NO_BACKSLASH_ESCAPES')", 'SET sql_mode = DEFAULT', "SET sql_mode = 'ANSI QUOTES'", - 'EXECUTE set_mode', - "EXECUTE IMMEDIATE 'SET sql_mode = ''NO_BACKSLASH_ESCAPES'''", - 'SET STATEMENT max_statement_time = 10 FOR EXECUTE set_mode', + 'SET STATEMENT max_statement_time = 10 FOR SET sql_mode = @saved', + "EXECUTE IMMEDIATE 'SET sql_mode = @saved'", + "PREPARE m FROM 'SET sql_mode = @saved'; EXECUTE m", ]; for (const statement of unclear) { + const before = calls(statement); // Without a backslash after it, every mode reads the SQL the same. expect(mySqlStatements(`${statement}; CALL p()`), statement).toEqual({ - calls: [false, true], + calls: [...before, true], uncounted: false, + sql: `${statement}; CALL p()`, }); - // After a backslash, the statements cannot be counted, but none of them is a CALL. - expect(mySqlStatements(String.raw`${statement}; SELECT 1; SELECT 'a\'; SELECT 2`)).toEqual({ - calls: [false, false], + // Every mode ends this string, and the comment after it, in the same place. + expect( + calls(String.raw`${statement}; SELECT 'C:\\tmp' AS path /* CALL syntax note */; CALL p()`), + statement, + ).toEqual([...before, false, true]); + // A mode that would leave the string open is not the server's, since it would reject it. + expect(calls(String.raw`${statement}; SELECT 'a\'; CALL p()`), statement).toEqual([ + ...before, + false, + true, + ]); + // The modes read different statements, none of them a CALL, so they are not counted. + expect(mySqlStatements(String.raw`${statement}; SELECT 'a\';\''; SELECT 2`)).toEqual({ + calls: before, uncounted: true, + sql: String.raw`${statement}; SELECT 'a\';\''; SELECT 2`, }); - // A CALL that may follow it cannot be grouped, so the SQL is refused before it runs. - expect(() => mySqlStatements(String.raw`${statement}; SELECT 'a\'; CALL p()`)).toThrow( - 'cannot tell where this MySQL SQL', + // A CALL among them cannot be grouped, so the SQL is refused before it runs. + expect(() => mySqlStatements(String.raw`${statement}; SELECT 'a\';\''; CALL p()`)).toThrow( + 'cannot tell where the statements of this MySQL SQL end', ); } - // A backslash in a comment, or a word that only holds the letters of CALL, changes nothing. - expect(mySqlStatements('SET sql_mode = @saved; -- C:\\path\nCALL p()')).toEqual({ - calls: [false, true], - uncounted: false, - }); - expect( - mySqlStatements( - String.raw`SET sql_mode = @saved; SELECT 'a\b' AS recall; SELECT called_at FROM t`, - ), - ).toEqual({ calls: [false], uncounted: true }); + // A backslash in a comment changes nothing. + expect(calls('SET sql_mode = @saved; -- C:\\path\nCALL p()')).toEqual([false, true]); // A version comment may run a CALL right after its digits. expect(() => - mySqlStatements(String.raw`SET sql_mode = @saved; SELECT 'a\b'; /*!80000CALL p() */`), - ).toThrow('cannot tell where this MySQL SQL'); + mySqlStatements(String.raw`SET sql_mode = @saved; SELECT 'a\';\''; /*!80000CALL p() */`), + ).toThrow('cannot tell where the statements of this MySQL SQL end'); + // So may a compound statement, which MariaDB runs outside a stored program. + expect(() => + mySqlStatements( + String.raw`SET sql_mode = @saved; SELECT 'a\';\''; IF 1 THEN SELECT 1; END IF`, + ), + ).toThrow('cannot tell where the statements of this MySQL SQL end'); // A SET of a quoted list of modes makes the mode clear again. expect( mySqlStatements( String.raw`SET sql_mode = @saved; CALL p(); SET sql_mode = ''; SELECT 'a\'; CALL q()'`, ), - ).toEqual({ calls: [false, true, false, false], uncounted: false }); + ).toEqual({ + calls: [false, true, false, false], + uncounted: false, + sql: String.raw`SET sql_mode = @saved; CALL p(); SET sql_mode = ''; SELECT 'a\'; CALL q()'`, + }); + // Comments after the last statement are left out where every mode ends it in the same place. + expect( + mySqlStatements(String.raw`SET sql_mode = @saved; SELECT 'a\';\''; SELECT 2; -- end`).sql, + ).toBe(String.raw`SET sql_mode = @saved; SELECT 'a\';\''; SELECT 2;`); + // Ways of reading the SQL that prepare different statements are followed without reading the + // rest again for each combination of them. + const forks = Array.from( + { length: 40 }, + (_, index) => `SET sql_mode = @m; PREPARE s${index} FROM "SELECT 1";`, + ).join(' '); + const started = performance.now(); + expect( + mySqlStatements(String.raw`SET sql_mode = @m; SELECT 'a\';' ; ${forks} SELECT 1`).uncounted, + ).toBe(true); + expect(performance.now() - started).toBeLessThan(2000); + // Where the modes read different statements, a statement prepared before them, or among + // them the same way in every mode, is still known. + for (const sql of [ + String.raw`PREPARE s FROM 'SELECT 1'; SET sql_mode = @m; SELECT 'a\';\''; EXECUTE s`, + String.raw`SET sql_mode = @m; SELECT 'a\';\''; SELECT 2; PREPARE g FROM 'SELECT 1'; EXECUTE g`, + String.raw`PREPARE g FROM 'SELECT 1'; SET sql_mode = @m; SELECT 'a\';\''; PREPARE g FROM 'SELECT 2'; EXECUTE g`, + // A double-quoted text names no statement in ANSI_QUOTES mode, which the server rejects. + String.raw`SET sql_mode = @m; SELECT 'a\';\''; PREPARE g FROM "SELECT 1"; EXECUTE g`, + ]) { + expect(mySqlStatements(sql).uncounted, sql).toBe(true); + } + // One prepared differently from before is forgotten. + expect(() => + mySqlStatements( + String.raw`PREPARE g FROM 'SELECT 1'; SET sql_mode = @m; SELECT 'a\';\''; PREPARE g FROM 'SET sql_mode = ''ANSI'''; EXECUTE g`, + ), + ).toThrow('cannot tell whether an EXECUTE in this MySQL SQL runs a CALL'); + // A mode in which the server rejects a statement is not the server's. + expect(calls('SET sql_mode = DEFAULT; PREPARE s FROM "CALL p()"; EXECUTE s; SELECT 3')).toEqual( + [false, false, true, false], + ); + // Here one mode reads a comment after the last statement and the other reads a string. + expect(() => + mySqlStatements(String.raw`SET sql_mode = @saved; SELECT '\'; -- '; SELECT 1`), + ).toThrow( + 'cannot tell whether the comments after its last statement return a result of their own', + ); // At least one statement follows, so results that end before it do not line up. expect( groupResults( [[{ a: 1 }], header, header], [[field], undefined, undefined], - String.raw`CALL p(); SET sql_mode = @saved; SELECT 'a\b'`, + String.raw`CALL p(); SET sql_mode = @saved; SELECT 'a\';\''`, ), ).toEqual([ { results: [{ a: 1 }], success: true, meta: {} }, @@ -549,7 +612,7 @@ describe('db execute --json results', () => { groupResults( [[{ a: 1 }], header, header, [{ b: 1 }], [{ c: 2 }]], [[field], undefined, undefined, [field], [field]], - String.raw`CALL p(); SET sql_mode = @saved; SELECT 'a\'b'; SELECT 2`, + String.raw`CALL p(); SET sql_mode = @saved; SELECT 'a\';\''; SELECT 2`, ), ).toEqual([ { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, @@ -558,4 +621,342 @@ describe('db execute --json results', () => { { results: [{ c: 2 }], success: true, meta: {} }, ]); }); + + it('leaves out MySQL comments after the last statement, which return a result of their own', () => { + const mysql84 = mySqlServerMode([{ sql_mode: '', version: '8.4.3' }]); + expect(mySqlStatements('CALL p(); -- end of script')).toEqual({ + calls: [true], + uncounted: false, + sql: 'CALL p();', + }); + for (const [sql, sent] of [ + ['SELECT 1; /* a */ # b\n', 'SELECT 1;'], + ['SELECT 1; -- note\n;', 'SELECT 1;'], + ['SELECT 1;/*+ hint */', 'SELECT 1;'], + ['SELECT 1; /*!99999 SELECT 2 */', 'SELECT 1;'], + ['SELECT 1; /*! */', 'SELECT 1;'], + ['SELECT 1; --', 'SELECT 1;'], + // Whitespace and semicolons alone return nothing, and a comment before the end of a + // statement is part of it. + ['SELECT 1;\n\n', 'SELECT 1;\n\n'], + ['SELECT 1;;', 'SELECT 1;;'], + ['SELECT 1 -- note', 'SELECT 1 -- note'], + ['SELECT 1; /*!80000 SELECT 2 */', 'SELECT 1; /*!80000 SELECT 2 */'], + // The server rejects a comment left open, and a cut in a running executable comment would + // leave that open. + ['SELECT 1; /* open', 'SELECT 1; /* open'], + ['SELECT 1 /*!40101 ; */ -- note', 'SELECT 1 /*!40101 ; */ -- note'], + ]) { + expect(mySqlStatements(sql, mysql84).sql, sql).toBe(sent); + } + expect(calls('SELECT 1; /*!80000 SELECT 2 */', mysql84)).toEqual([false, false]); + expect( + groupResults( + [[{ a: 1 }], [{ b: 2 }], header], + [[field], [field], undefined], + 'CALL p(); -- end of script', + ), + ).toEqual([ + { results: [{ a: 1 }, { b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + // SQL that holds only comments has no statement, though the server answers it. + expect(mySqlStatements('-- nothing here')).toEqual({ + calls: [], + uncounted: false, + sql: '-- nothing here', + }); + expect(groupResults(header, undefined, '-- nothing here')).toEqual([]); + }); + + it('groups the results of a prepared MySQL CALL under its EXECUTE', () => { + const mysql84 = mySqlServerMode([{ sql_mode: '', version: '8.4.3' }]); + const mariaDb = mySqlServerMode([{ sql_mode: '', version: '11.4.4-MariaDB' }]); + expect( + calls("PREPARE s FROM 'CALL p()'; EXECUTE s; EXECUTE s USING @a; SELECT 1; EXECUTE s"), + ).toEqual([false, true, true, false, true]); + expect(calls("PREPARE s FROM 'SELECT 1'; EXECUTE s")).toEqual([false, false]); + // Names are not case-sensitive, and a double-quoted string is a string. + expect(calls('PREPARE `S` FROM "CALL p()"; EXECUTE s')).toEqual([false, true]); + expect(calls(String.raw`PREPARE s FROM 'CALL p(''a'', \'b\')'; EXECUTE s`)).toEqual([ + false, + true, + ]); + expect(calls("PREPARE s FROM '-- note\nCALL p()'; EXECUTE s")).toEqual([false, true]); + // The statement reads the way the server does, executable comments too. + expect(calls("PREPARE s FROM '/*!80000 CALL p() */'; EXECUTE s", mysql84)).toEqual([ + false, + true, + ]); + expect(calls("PREPARE s FROM '/*!80000 CALL p() */'; EXECUTE s", mariaDb)).toEqual([ + false, + false, + ]); + // A later PREPARE of the name replaces the statement. + expect(calls("PREPARE s FROM 'CALL p()'; PREPARE s FROM 'SELECT 1'; EXECUTE s")).toEqual([ + false, + false, + false, + ]); + // MariaDB's EXECUTE IMMEDIATE runs the text it is given, and SET STATEMENT the statement + // after FOR. + expect( + calls( + "EXECUTE IMMEDIATE 'CALL p()'; EXECUTE IMMEDIATE 'CALL p(?)' USING 1; EXECUTE IMMEDIATE 'SELECT 1'", + ), + ).toEqual([true, true, false]); + expect( + calls( + "SET STATEMENT max_statement_time = 10 FOR CALL p(); PREPARE s FROM 'CALL p()'; SET STATEMENT max_statement_time = 10 FOR EXECUTE s", + ), + ).toEqual([true, false, true]); + // A prepared SET of sql_mode changes it when EXECUTE runs it. + expect( + calls( + String.raw`PREPARE m FROM 'SET sql_mode = ''NO_BACKSLASH_ESCAPES'''; EXECUTE m; SELECT '\'; CALL p()`, + ), + ).toEqual([false, false, false, true]); + expect( + groupResults( + [header, [{ a: 1 }], [{ b: 2 }], header, [{ c: 3 }]], + [undefined, [field], [field], undefined, [field]], + "PREPARE s FROM 'CALL p()'; EXECUTE s; SELECT 3", + ), + ).toEqual([ + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ a: 1 }, { b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ c: 3 }], success: true, meta: {} }, + ]); + }); + + it('refuses MySQL SQL that executes a statement it cannot see', () => { + for (const sql of [ + 'EXECUTE s', + "SET @q = 'CALL p()'; PREPARE s FROM @q; EXECUTE s", + "PREPARE s FROM CONCAT('CALL ', 'p()'); EXECUTE s", + "PREPARE s FROM 'CALL p()' 'x'; EXECUTE s", + "PREPARE s FROM 'SELECT 1'; DEALLOCATE PREPARE s; EXECUTE s", + "PREPARE s FROM 'SELECT 1'; DROP PREPARE s; EXECUTE s", + // A procedure may prepare a statement under the same name, though not the one that runs it. + "PREPARE s FROM 'SELECT 1'; CALL p(); EXECUTE s", + "PREPARE s FROM 'SELECT 1'; PREPARE c FROM 'CALL p()'; EXECUTE c; EXECUTE s", + "PREPARE s FROM 'SELECT 1'; EXECUTE IMMEDIATE 'CALL p()'; EXECUTE s", + "PREPARE s FROM 'SELECT 1'; IF 1 THEN CALL p(); END IF; EXECUTE s", + 'SET STATEMENT max_statement_time = 10 FOR EXECUTE s', + "EXECUTE IMMEDIATE CONCAT('CALL ', 'p()')", + 'EXECUTE IMMEDIATE @q', + // In MySQL, IMMEDIATE can name a prepared statement. + 'EXECUTE immediate USING @a', + ]) { + expect(() => mySqlStatements(sql), sql).toThrow( + 'cannot tell whether an EXECUTE in this MySQL SQL runs a CALL', + ); + } + // Statements that prepare or deallocate return one result each. + expect(calls('PREPARE s FROM @q; DEALLOCATE PREPARE s; SELECT 1')).toEqual([ + false, + false, + false, + ]); + }); + + it('keeps a stored program body that is a single compound statement together', () => { + for (const program of [ + 'CREATE PROCEDURE p() IF 1 THEN SELECT 1; SELECT 2; END IF', + "CREATE PROCEDURE p() COMMENT 'x;' DETERMINISTIC IF (1) THEN SELECT 1; ELSE SELECT 2; END IF", + 'CREATE PROCEDURE IF NOT EXISTS p() IF NOT EXISTS (SELECT 1) THEN SELECT 1; SELECT 2; END IF', + 'CREATE DEFINER = CURRENT_USER PROCEDURE db.p(IN a INT) READS SQL DATA SQL SECURITY INVOKER CASE a WHEN 1 THEN SELECT 1; SELECT 2; ELSE BEGIN END; END CASE', + 'CREATE PROCEDURE p() lbl: LOOP SELECT 1; LEAVE lbl; END LOOP lbl', + 'CREATE PROCEDURE p() comment: LOOP SELECT 1; LEAVE comment; END LOOP', + 'CREATE PROCEDURE p() REPEAT SELECT 1; UNTIL 1 END REPEAT', + 'CREATE PROCEDURE p() WHILE (0) DO SELECT 1; END WHILE', + 'CREATE PROCEDURE p() FOR i IN 1..3 DO SELECT i; END FOR', + 'CREATE PROCEDURE p() IF a THEN IF (b) THEN SELECT 1; END IF; SELECT 2; ELSE BEGIN SELECT 3; END; END IF', + 'CREATE PROCEDURE p() IF a THEN SELECT CASE WHEN b THEN 1 END; ELSEIF c THEN CASE WHEN d THEN SELECT 2; END CASE; END IF', + 'CREATE FUNCTION f(a INT) RETURNS INT DETERMINISTIC IF a > 0 THEN RETURN 1; ELSE RETURN 0; END IF', + "CREATE FUNCTION f(a INT) RETURNS VARCHAR(10) CHARACTER SET utf8mb4 DETERMINISTIC IF a > 0 THEN RETURN 'y'; END IF", + 'CREATE FUNCTION f() RETURNS INT lbl: BEGIN RETURN 1; END lbl', + 'CREATE TRIGGER t BEFORE INSERT ON a FOR EACH ROW IF NEW.a < 0 THEN SET NEW.a = 0; END IF', + 'CREATE TRIGGER t BEFORE INSERT ON a FOR EACH ROW FOLLOWS t0 IF NEW.a < 0 THEN SET NEW.a = 0; END IF', + 'CREATE EVENT e ON SCHEDULE EVERY 1 DAY DO IF 1 THEN DELETE FROM a; DELETE FROM b; END IF', + 'ALTER EVENT e DO WHILE 0 DO DELETE FROM a; END WHILE', + // IF() and REPEAT() are functions, and IF EXISTS is part of a statement. + 'CREATE PROCEDURE p() SELECT IF(a, 1, 2), REPEAT(b, 2) FROM t FOR UPDATE', + 'CREATE FUNCTION f(a INT) RETURNS INT DETERMINISTIC RETURN IF(a > 0, 1, 0)', + 'CREATE PROCEDURE p() BEGIN DROP TABLE IF EXISTS t; CREATE TABLE IF NOT EXISTS t (a INT); SELECT IF(1, 2, 3); END', + // A CASE expression ends at its END, whatever follows it. + 'CREATE PROCEDURE p() BEGIN SELECT CASE WHEN a THEN 1 END FOR UPDATE; SELECT 2; END', + // A handler's statement may be a compound statement of its own. + 'CREATE PROCEDURE p() BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND IF 1 THEN SET @a = 1; END IF; SELECT 1; END', + // MariaDB's Oracle mode ends a WHILE loop with END LOOP. + 'CREATE PROCEDURE p AS BEGIN WHILE a LOOP SELECT 1; END LOOP; END', + ]) { + expect(calls(`${program}; CALL p()`), program).toEqual([false, true]); + } + }); + + it('groups the results of a compound statement MariaDB runs outside a stored program', () => { + for (const statement of [ + 'BEGIN NOT ATOMIC SELECT 1; SELECT 2; END', + 'BEGIN NOT ATOMIC BEGIN SELECT 1; END; IF 1 THEN SELECT 2; END IF; END', + 'BEGIN NOT ATOMIC DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; START TRANSACTION; SELECT 1; COMMIT; END', + 'IF 1 THEN SELECT 1; SELECT 2; END IF', + 'CASE WHEN 1 THEN SELECT 1; END CASE', + 'FOR i IN 1..2 DO SELECT i; END FOR', + 'WHILE 0 DO SELECT 1; END WHILE', + 'REPEAT SELECT 1; UNTIL 1 END REPEAT', + ]) { + expect(calls(`${statement}; SELECT 3`), statement).toEqual([true, false]); + } + expect( + groupResults( + [[{ a: 1 }], [{ b: 2 }], header, [{ c: 3 }]], + [[field], [field], undefined, [field]], + 'IF 1 THEN SELECT 1; SELECT 2; END IF; SELECT 3', + ), + ).toEqual([ + { results: [{ a: 1 }, { b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ c: 3 }], success: true, meta: {} }, + ]); + }); + + it('reads a word right after an @ as a name', () => { + // `@case` is a user variable, and the words after `@@` and in `@x.case` are names too. + expect(calls('SELECT @case AS n; CALL p()')).toEqual([false, true]); + expect( + calls('SELECT @begin, @end, @if, @loop, @while, @repeat, @for, @do, @x.case; CALL p()'), + ).toEqual([false, true]); + expect(calls('SET @@session.sql_mode = @@sql_mode; SELECT @@begin; CALL p()')).toEqual([ + false, + false, + true, + ]); + expect(calls('CREATE PROCEDURE q() BEGIN SET @end = 1; SELECT @begin; END; CALL p()')).toEqual([ + false, + true, + ]); + expect( + groupResults( + [[{ n: null }], [{ a: 1 }], [{ b: 2 }], header], + [[field], [field], [field], undefined], + 'SELECT @case AS n; CALL p()', + ), + ).toEqual([ + { results: [{ n: null }], success: true, meta: {} }, + { results: [{ a: 1 }, { b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it('reads begin, end and do as names where a stored program body uses them so', () => { + for (const program of [ + 'CREATE PROCEDURE q() BEGIN SELECT begin, end, do FROM t; END', + 'CREATE PROCEDURE q() BEGIN SELECT 1 AS begin; SELECT 2 AS end; SELECT 3 do; END', + 'CREATE PROCEDURE q() SELECT 1 AS begin', + 'CREATE PROCEDURE q() BEGIN SELECT end AS end FROM t; UPDATE t SET end = 2 WHERE begin = 1; END', + 'CREATE PROCEDURE q() BEGIN SELECT 1 FROM t WHERE end IS NOT NULL; END', + // A CASE expression ends at an END after an operand, and holds `end` columns elsewhere. + 'CREATE PROCEDURE q() BEGIN SELECT CASE WHEN 1 THEN end END FROM t; END', + 'CREATE PROCEDURE q() BEGIN SELECT CASE end WHEN 2 THEN begin ELSE - end END FROM t; END', + 'CREATE PROCEDURE q() BEGIN SELECT CASE WHEN end = 2 THEN (SELECT end FROM t) END end FROM t; END', + 'CREATE PROCEDURE q() BEGIN SELECT CASE WHEN EXISTS (SELECT end FROM t) THEN 1 END; END', + 'CREATE PROCEDURE q() BEGIN SELECT CASE WHEN t.end > 0 THEN t.case END FROM t; END', + // So does a REPEAT's UNTIL condition. + 'CREATE PROCEDURE q() BEGIN DECLARE end INT DEFAULT 0; REPEAT SET end = end + 1; UNTIL end END REPEAT; END', + 'CREATE PROCEDURE q() BEGIN REPEAT SELECT end FROM t; UNTIL end > 1 END REPEAT; END', + // A WHILE's DO comes after its condition. + 'CREATE PROCEDURE q() BEGIN DECLARE do INT DEFAULT 0; WHILE do DO SET do = 0; END WHILE; END', + 'CREATE PROCEDURE q() BEGIN WHILE (SELECT do FROM t) = 0 DO SELECT 1; END WHILE; SELECT do FROM t; END', + // Names of routines, parameters and variables. + 'CREATE PROCEDURE begin() BEGIN SELECT 1; END', + 'CREATE PROCEDURE do() BEGIN SELECT 1; END', + 'CREATE PROCEDURE q(begin INT, end INT) BEGIN SELECT begin + end; END', + 'CREATE PROCEDURE q() BEGIN DECLARE begin INT DEFAULT 1; DECLARE end INT DEFAULT 2; SET begin = end; END', + 'CREATE EVENT do ON SCHEDULE EVERY 1 DAY DO BEGIN SELECT 1; SELECT 2; END', + 'CREATE TRIGGER begin BEFORE INSERT ON begin FOR EACH ROW BEGIN SET NEW.end = 1; END', + // A handler's statement starts after its conditions. + "CREATE PROCEDURE q() BEGIN DECLARE c CONDITION FOR SQLSTATE '45000'; DECLARE CONTINUE HANDLER FOR c BEGIN END; DECLARE EXIT HANDLER FOR SQLSTATE VALUE '23000', 1062, NOT FOUND, SQLWARNING BEGIN SELECT 9; END; SELECT 1; END", + 'CREATE PROCEDURE q() BEGIN DECLARE CONTINUE HANDLER FOR SQLEXCEPTION IF 1 THEN SELECT 1; END IF; SELECT 2; END', + ]) { + expect(calls(`${program}; CALL p()`), program).toEqual([false, true]); + } + expect( + groupResults( + [header, [{ a: 1 }], [{ b: 2 }], header], + [undefined, [field], [field], undefined], + 'CREATE PROCEDURE q() BEGIN SELECT begin, end FROM t; END; CALL p()', + ), + ).toEqual([ + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + { results: [{ a: 1 }, { b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + it('reads the account in DEFINER = account as a name', () => { + for (const program of [ + 'CREATE DEFINER = user@localhost PROCEDURE q() BEGIN SELECT 1; SELECT 2; END', + 'CREATE DEFINER=event@localhost PROCEDURE q() BEGIN SELECT 1; END', + 'CREATE DEFINER = user PROCEDURE q() BEGIN SELECT 1; END', + 'CREATE DEFINER = user@local.host FUNCTION f() RETURNS INT BEGIN RETURN 1; END', + 'CREATE DEFINER = `table`@`localhost` TRIGGER t BEFORE INSERT ON a FOR EACH ROW BEGIN SET NEW.a = 1; END', + 'CREATE OR REPLACE DEFINER = role EVENT e ON SCHEDULE EVERY 1 DAY DO BEGIN DELETE FROM a; END', + 'ALTER DEFINER = user@localhost EVENT e DO BEGIN DELETE FROM a; END', + ]) { + expect(calls(`${program}; CALL p()`), program).toEqual([false, true]); + } + // A view is not a stored program, so a BEGIN after it starts a transaction. + expect( + calls( + 'CREATE ALGORITHM = MERGE DEFINER = user@localhost SQL SECURITY INVOKER VIEW v AS SELECT 1; BEGIN; CALL p()', + ), + ).toEqual([false, false, true]); + }); + + it("reads square-bracket names in MariaDB's MSSQL mode", () => { + const mssql = mySqlServerMode([ + { sql_mode: 'PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,MSSQL', version: '11.4.4-MariaDB' }, + ]); + expect(mssql).toMatchObject({ ansiQuotes: true, brackets: true, mariaDb: true }); + const mariaDb = mySqlServerMode([{ sql_mode: '', version: '11.4.4-MariaDB' }]); + // MySQL 5.7's MSSQL mode quotes nothing in brackets. + expect(mySqlServerMode([{ sql_mode: 'MSSQL', version: '5.7.44' }]).brackets).toBe(false); + expect(needsMySqlServerMode('SELECT [a] FROM t')).toBe(true); + for (const sql of [ + 'SELECT [case] FROM t; CALL p()', + 'SELECT [a;b] FROM t; CALL p()', + // `]]` stands for `]`, and a backslash escapes nothing. + 'SELECT [a]]b;] FROM t; CALL p()', + String.raw`SELECT [x\], 'it''s' FROM t; CALL p()`, + 'SELECT [x\'y], [x"y], [x`y], [x/*y], [x-- y] FROM t; CALL p()', + ]) { + expect(calls(sql, mssql), sql).toEqual([false, true]); + } + expect(calls("PREPARE [S] FROM 'CALL p()'; EXECUTE s", mssql)).toEqual([false, true]); + // A name in brackets is no statement to prepare, so the server rejects the PREPARE. + expect(calls('SET sql_mode = @m; PREPARE s FROM [CALL p()]; SELECT 1', mariaDb)).toEqual([ + false, + false, + false, + ]); + // A SET of sql_mode turns the brackets on and off. + expect( + calls("SET sql_mode = 'MSSQL'; SELECT [a;b]; SET sql_mode = ''; CALL p()", mariaDb), + ).toEqual([false, false, false, true]); + // After an unclear change, only the mode that reads the brackets as a name is the server's, + // since the server rejects a `[` that quotes nothing. + expect(calls('SET sql_mode = @m; SELECT [case] FROM t; CALL p()', mariaDb)).toEqual([ + false, + false, + true, + ]); + expect( + groupResults( + [[{ case: 4 }], [{ a: 1 }], [{ b: 2 }], header], + [[field], [field], [field], undefined], + 'SELECT [case] FROM t; CALL p()', + mssql, + ), + ).toEqual([ + { results: [{ case: 4 }], success: true, meta: {} }, + { results: [{ a: 1 }, { b: 2 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); }); From 427381be24ce552fc28f77ffb03d4284d53ba4de Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 25 Nov 2026 21:36:09 +0530 Subject: [PATCH 08/11] fix(cli): keep `void db execute --json` stdout to the results and read more MySQL SQL exactly - Send anything else written to stdout, such as output from void.config.ts on each load, to stderr from the start of the command until the process exits. - Read the dot after digits as a decimal point, so `1.` before END closes a CASE expression. - Read the server's mode for SQL with double quotes, so ANSI_QUOTES names of prepared statements resolve, and set aside readings where a string names a prepared statement, which the server rejects. - Report MySQL insert IDs of 2^63 and more as unsigned; mysql2 reads them as signed. - Keep a SQLite column named __proto__ in the rows. - Let Cloudflare Access sign in with a terminal on stdin and stderr, so piping stdout no longer prevents renewing a rejected credential. Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 2 +- packages/void/src/cli/cf-access.ts | 12 ++- packages/void/src/cli/db-execute-results.ts | 67 +++++++++++++---- packages/void/src/cli/db.ts | 73 +++++++++++++----- packages/void/src/migrations/runner.ts | 4 + packages/void/test/unit/cf-access.test.ts | 75 ++++++++++++++----- packages/void/test/unit/db-commands.test.ts | 68 +++++++++++++++-- .../void/test/unit/db-execute-remote.test.ts | 40 ++++++---- .../void/test/unit/db-execute-results.test.ts | 39 ++++++++++ .../void/test/unit/direct-r2-client.test.ts | 5 ++ 10 files changed, 309 insertions(+), 76 deletions(-) diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 6a8c8bffd..7bccec50c 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -71,7 +71,7 @@ For destructive statements (`DELETE`, `UPDATE`, `DROP`, etc.) when running in a ### JSON output {#void-db-execute-json} -Pass `--json` to read results from a script. stdout receives only a JSON array with one entry per statement, including statements in SQL with several statements. Prompts, warnings and errors go to stderr, and a failure exits with a non-zero status. +Pass `--json` to read results from a script. stdout receives only a JSON array with one entry per statement, including statements in SQL with several statements. Prompts, warnings, errors and any other output, such as messages that `void.config.ts` prints, go to stderr, and a failure exits with a non-zero status. ```sh void db execute --json "select count(*) as total from users; select id from users limit 1" diff --git a/packages/void/src/cli/cf-access.ts b/packages/void/src/cli/cf-access.ts index 95fb1b145..d5d70eea4 100644 --- a/packages/void/src/cli/cf-access.ts +++ b/packages/void/src/cli/cf-access.ts @@ -107,7 +107,7 @@ export function ensurePlatformAccessToken( if (challenged && rejectedTokens.size > 0) { forgetOriginToken(origin); keyringTokens.set(origin, null); - if (!process.stdin.isTTY || !process.stdout.isTTY) { + if (!canSignIn()) { throw new Error( `platform: Cloudflare Access rejected the cached credential for ${origin}. Re-run this command in an interactive terminal to renew it.`, ); @@ -119,7 +119,7 @@ export function ensurePlatformAccessToken( if (token && rejectedTokens.has(token)) { token = null; } - if ((!token || !usableToken(token)) && process.stdin.isTTY && process.stdout.isTTY) { + if ((!token || !usableToken(token)) && canSignIn()) { console.error(`Authenticate to Cloudflare Access for ${origin}.`); runCloudflaredLogin(origin); token = runCloudflared(['access', 'token', `-app=${origin}`]); @@ -135,6 +135,14 @@ export function ensurePlatformAccessToken( writeKeyringPassword(ACCESS_KEYRING_SERVICE, account, token); } +/** + * Whether a browser sign-in can run: it needs a terminal on stdin and stderr, where it writes. + * stdout may be redirected, as it is for a command's result (`void db execute --json | jq`). + */ +function canSignIn(): boolean { + return Boolean(process.stdin.isTTY && process.stderr.isTTY); +} + /** * Sign in through the browser. `--quiet` keeps the JWT off the terminal, and cloudflared's * output goes to stderr, since stdout may carry a command's result (`void db execute --json`). diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index e327f3bec..50c99a2e9 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -153,12 +153,18 @@ export function runSqliteStatements(db: SqliteDatabase, sql: string): Array counters.get() ?? { last_row_id: 0n, total: 0n }; const results: Array = []; for (const statementSql of splitSqliteStatements(sql)) { - const statement = db.prepare>(statementSql).safeIntegers(true); + const statement = db.prepare>(statementSql).safeIntegers(true); const before = readCounters().total; const started = performance.now(); let rows: Array> = []; if (statement.reader) { - rows = statement.all(); + // better-sqlite3 builds a row object by assigning each column, which drops a column named + // __proto__, so the rows are read as arrays and each column defined as its own property. + const columns = statement.columns().map((column) => column.name); + rows = statement + .raw(true) + .all() + .map((values) => Object.fromEntries(columns.map((name, index) => [name, values[index]]))); } else { statement.run(); } @@ -279,19 +285,35 @@ export function pgStatementResults(result: PgResult | Array): Array; - return { affectedRows: mySqlCount(header.affectedRows), insertId: mySqlCount(header.insertId) }; + return { + affectedRows: mySqlCount(header.affectedRows), + insertId: mySqlInsertId(header.insertId), + }; } function mySqlStatementResult(value: unknown): StatementResult { @@ -319,12 +341,12 @@ export const MYSQL_SERVER_MODE_QUERY = 'SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS version'; /** - * Whether the SQL holds a backslash, a `[` or an executable comment, which read differently per - * server. Without a backslash, `ANSI_QUOTES` changes what a double-quoted text is but not - * where it ends. + * Whether the SQL holds a backslash, a double quote, a `[` or an executable comment, which read + * differently per server. A double quote opens a string, or in `ANSI_QUOTES` mode a name, such + * as the name of a prepared statement. */ export function needsMySqlServerMode(sql: string): boolean { - return sql.includes('\\') || sql.includes('[') || /\/\*M?!/u.test(sql); + return /[\\"[]|\/\*M?!/u.test(sql); } /** Read the row `MYSQL_SERVER_MODE_QUERY` returns. */ @@ -724,7 +746,7 @@ function closeMySqlBlock(blocks: Array, next: string | undefined * a REPEAT's UNTIL condition after an operand; elsewhere it is a name, as `begin` and `end` * columns are. A CASE expression nests anywhere. A word after a dot or right after an `@` is a * name, such as the column in `t.case` or the variable `@case`, as is the account in - * `DEFINER = account`. + * `DEFINER = account`, but the dot in a number such as `1.` is its decimal point. */ function readMySqlStatement( sql: string, @@ -756,6 +778,8 @@ function readMySqlStatement( // Where the word before ends, and whether it is a name, which ends an operand. let wordEnd = -1; let named = false; + // Whether the word before is a number's decimal point, as in `1.`, which ends an operand too. + let decimalPoint = false; const result = (terminated: boolean): MySqlStatementRead => ({ words, end: lexer.index, @@ -786,11 +810,16 @@ function readMySqlStatement( startedLast = false; namesBlock = false; named = false; + decimalPoint = false; handler = undefined; continue; } const previous = words.at(-1); - const operandBefore = !named && expectsMySqlOperand(previous); + const afterDecimalPoint = decimalPoint; + const operandBefore = !named && !afterDecimalPoint && expectsMySqlOperand(previous); + // A `.` right after digits is their decimal point, as in `1.` or `1.5`, unless the digits + // name a column, as in `t.1`. + decimalPoint = word === '.' && touches && /^\d+$/u.test(previous ?? '') && !named; named = false; words.push(word); let starts = startsNext; @@ -804,9 +833,9 @@ function readMySqlStatement( } else if (word === ')') { depth--; } - // A word after a dot names a column or other object, and one right after an `@` a variable, - // or the host of an account. - if (previous === '.' || (previous === '@' && touches)) { + // A word after a dot names a column or other object, unless the dot is a decimal point, and + // one right after an `@` a variable, or the host of an account. + if ((previous === '.' && !afterDecimalPoint) || (previous === '@' && touches)) { named = true; continue; } @@ -1143,6 +1172,9 @@ type MySqlEffect = MySqlPreparedStatement & { }; const MYSQL_SINGLE: MySqlEffect = { kind: 'single', change: undefined }; +// A statement the server rejects in this mode, such as one that names a prepared statement with +// a string: a double-quoted name is a string outside ANSI_QUOTES mode. +const MYSQL_REJECTED: MySqlEffect = { ...MYSQL_SINGLE, rejected: true }; /** * Whether the server rejects the text a PREPARE or EXECUTE IMMEDIATE is given: a quoted name @@ -1200,10 +1232,16 @@ function mySqlStatementEffect( rejected: rejectsMySqlSource(source, mode), }; } + if (isMySqlString(second, mode)) { + return MYSQL_REJECTED; + } const name = mySqlName(second, mode) ?? ''; return { ...(prepared.get(name) ?? { kind: 'unknown', change: 'unclear' }), executes: name }; } if (first === 'prepare' && words[2] === 'from') { + if (isMySqlString(second, mode)) { + return MYSQL_REJECTED; + } const source = words.slice(3); return { ...MYSQL_SINGLE, @@ -1212,6 +1250,9 @@ function mySqlStatementEffect( }; } if ((first === 'deallocate' || first === 'drop') && second === 'prepare') { + if (isMySqlString(words[2], mode)) { + return MYSQL_REJECTED; + } return { ...MYSQL_SINGLE, prepares: { name: mySqlName(words[2], mode), statement: undefined, deallocates: true }, diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index aa53f621d..e4190fa96 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -202,8 +202,15 @@ function validatePendingMigrations( } export async function runDbCommand(root: string, args: DbArgs): Promise { - // Keep raw SQL exports and JSON results clean for piping into other tools. - if (!(args.action === 'export' && !args.output) && !(args.action === 'execute' && args.json)) { + if (args.action === 'execute' && args.json) { + // Before the config loads, which may write to stdout. + const printResults = reserveStdoutForResults(); + await runExecute(root, args, getDatabaseDialect(readConfig(root)), printResults); + return; + } + + // Keep raw SQL exports clean for piping into other tools. + if (!(args.action === 'export' && !args.output)) { console.log(); } @@ -220,7 +227,7 @@ export async function runDbCommand(root: string, args: DbArgs): Promise { } else if (args.action === 'seed') { await runSeed(root, args.file, dialect, args.yes); } else if (args.action === 'execute') { - await runExecute(root, args, dialect); + await runExecute(root, args, dialect, undefined); } else if (args.action === 'migrate') { await runMigrate(root, dialect, args.remote); } else if (args.action === 'studio') { @@ -914,14 +921,16 @@ async function fetchRemoteDatabaseUrl( /** * Run SQL on a PostgreSQL or MySQL database. Both drivers return one result per statement, so - * `--json` prints every statement; the table prints only a single statement's rows. + * `--json` prints every statement with `printResults`; the table prints only a single + * statement's rows. */ async function executeExternalSql( dialect: Exclude, dbUrl: string, sql: string, - json: boolean, + printResults: PrintResults | undefined, ): Promise { + const json = printResults !== undefined; if (dialect === 'postgresql') { const { Client, types } = await import('pg'); const pgClient = new Client({ @@ -936,7 +945,7 @@ async function executeExternalSql( | QueryResult> | Array>> = await pgClient.query(sql); if (json) { - printStatementResults(pgStatementResults(result)); + printResults(pgStatementResults(result)); } else if (!Array.isArray(result) && result.rows.length > 0) { printTable(result.rows); } @@ -974,8 +983,8 @@ async function executeExternalSql( }); try { const [rows, fields] = await mySqlClient.query(statements?.sql ?? sql); - if (statements) { - printStatementResults(mySqlStatementResults(rows, fields, statements)); + if (json && statements) { + printResults(mySqlStatementResults(rows, fields, statements)); } else if (Array.isArray(rows) && rows.length > 0) { printTable(rows as Array>); } @@ -1020,8 +1029,33 @@ function mySqlJsonUri(dbUrl: string): string { return url.toString(); } -function printStatementResults(results: Array): void { - console.log(formatStatementResults(results)); +/** How `void db execute --json` prints its results. */ +type PrintResults = (results: Array) => void; + +/** stdout's own write, and what takes its place while stdout is kept for results. */ +let reservedStdout: + | { write: (text: string) => void; redirect: typeof process.stdout.write } + | undefined; + +/** + * Keep stdout for `void db execute --json` results, and return the function that prints them. + * Anything else written to stdout from then on goes to stderr until the process exits: a + * console.log in void.config.ts runs each time the command loads the config, and a timer the + * config starts may still write after the results. A second command in the same process keeps + * the first one's place, unless stdout's write has changed since. + */ +function reserveStdoutForResults(): PrintResults { + const { stdout, stderr } = process; + if (reservedStdout?.redirect !== stdout.write) { + const redirect = ((...args: Parameters) => + stderr.write(...args)) as typeof stdout.write; + reservedStdout = { write: stdout.write.bind(stdout), redirect }; + stdout.write = redirect; + } + const { write } = reservedStdout; + return (results) => { + write(`${formatStatementResults(results)}\n`); + }; } /** @@ -1059,11 +1093,14 @@ const D1_MAX_SQL_STATEMENT_BYTES = 100_000; type ExecuteArgs = Omit, 'action'>; +/** Run `void db execute`. `printResults` prints the results with --json, and is undefined without. */ async function runExecute( root: string, - { command, file, remote, yes, json = false }: ExecuteArgs, + { command, file, remote, yes }: ExecuteArgs, dialect: DatabaseDialect, + printResults: PrintResults | undefined, ): Promise { + const json = printResults !== undefined; // With --json, stdout carries only the results: prompts and messages go to stderr. const messages = json ? { output: process.stderr } : {}; const finish = () => { @@ -1119,7 +1156,7 @@ async function runExecute( if (bulkImport) { await importCloudflareD1Sql(context, sql); } else if (json) { - printStatementResults(await executeCloudflareD1Statements(context, sql)); + printResults(await executeCloudflareD1Statements(context, sql)); } else { const rows = await executeCloudflareD1Sql(context, sql); if (rows.length > 0) { @@ -1135,7 +1172,7 @@ async function runExecute( ); process.exit(1); } - await executeExternalSql(dialect, dbUrl, sql, json); + await executeExternalSql(dialect, dbUrl, sql, printResults); } finish(); return; @@ -1171,7 +1208,7 @@ async function runExecute( const client = new PlatformClient(token, { root }); const dbUrl = await fetchRemoteDatabaseUrl(client, projectConfig.projectId, messages); - await executeExternalSql(dialect, dbUrl, sql, json); + await executeExternalSql(dialect, dbUrl, sql, printResults); finish(); return; } @@ -1243,9 +1280,7 @@ async function runExecute( }>(); const rows = data.results ?? []; if (json) { - printStatementResults([ - { results: rows, success: data.success !== false, meta: data.meta ?? {} }, - ]); + printResults([{ results: rows, success: data.success !== false, meta: data.meta ?? {} }]); } else if (rows.length > 0) { printTable(rows); } @@ -1255,7 +1290,7 @@ async function runExecute( if (dialect !== 'sqlite') { const sql = readSql(); - await executeExternalSql(dialect, getLocalDatabaseUrl(root, dialect), sql, json); + await executeExternalSql(dialect, getLocalDatabaseUrl(root, dialect), sql, printResults); finish(); return; } @@ -1273,7 +1308,7 @@ async function runExecute( const db = await openSqliteDatabase(dbPath); try { if (json) { - printStatementResults(runSqliteStatements(db, sql)); + printResults(runSqliteStatements(db, sql)); } else { const statement = prepareSingleStatement(db, sql); if (statement?.reader) { diff --git a/packages/void/src/migrations/runner.ts b/packages/void/src/migrations/runner.ts index b14738040..0a416daa2 100644 --- a/packages/void/src/migrations/runner.ts +++ b/packages/void/src/migrations/runner.ts @@ -14,6 +14,10 @@ export type SqliteStatement = { run(...params: Array): void; /** Read INTEGER columns as BigInt, so values past 2^53 keep every digit. */ safeIntegers(toggle?: boolean): SqliteStatement; + /** Read each row as an array of its values, in column order. */ + raw(toggle?: boolean): SqliteStatement; + /** The columns of the rows the statement returns. */ + columns(): Array<{ name: string }>; }; type SqliteTransaction = { diff --git a/packages/void/test/unit/cf-access.test.ts b/packages/void/test/unit/cf-access.test.ts index eb2985499..b5c4a4143 100644 --- a/packages/void/test/unit/cf-access.test.ts +++ b/packages/void/test/unit/cf-access.test.ts @@ -175,6 +175,25 @@ describe('origin-scoped self-hosted Access login', () => { }); afterEach(() => vi.unstubAllEnvs()); + /** Run `run` with each standard stream a terminal or not, as `terminals` says. */ + async function withTerminals( + terminals: Record<'stdin' | 'stdout' | 'stderr', boolean>, + run: () => Promise, + ): Promise { + const names = ['stdin', 'stdout', 'stderr'] as const; + const before = names.map((name) => process[name].isTTY); + for (const name of names) { + Object.defineProperty(process[name], 'isTTY', { configurable: true, value: terminals[name] }); + } + try { + await run(); + } finally { + names.forEach((name, index) => { + Object.defineProperty(process[name], 'isTTY', { configurable: true, value: before[index] }); + }); + } + } + it('loads a keychain token only for its selected origin', async () => { const token = jwt(Math.floor(Date.now() / 1000) + 600); keyring.read.mockReturnValue(token); @@ -191,17 +210,10 @@ describe('origin-scoped self-hosted Access login', () => { it('reuses a valid cached human token when Access is known to be required', async () => { const token = jwt(Math.floor(Date.now() / 1000) + 600); keyring.read.mockReturnValue(token); - const stdinTty = process.stdin.isTTY; - const stdoutTty = process.stdout.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false }); - Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: false }); - try { + await withTerminals({ stdin: false, stdout: false, stderr: false }, async () => { const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); ensurePlatformAccessToken('https://api.example.com', false, true); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: stdinTty }); - Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: stdoutTty }); - } + }); expect(cfAccessHeaders(process.env, 'https://api.example.com')).toEqual({ 'cf-access-token': token, }); @@ -259,17 +271,12 @@ describe('origin-scoped self-hosted Access login', () => { spawnSyncMock.mockImplementation((_command, args: Array) => args[1] === 'login' ? { status: 0, stdout: '' } : { status: 0, stdout: fresh }, ); - const stdinTty = process.stdin.isTTY; - const stdoutTty = process.stdout.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true }); - Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true }); - try { + // stdout may be piped, as in `void db execute --remote --json | jq`: the sign-in uses stdin + // and stderr. + await withTerminals({ stdin: true, stdout: false, stderr: true }, async () => { const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); ensurePlatformAccessToken('https://api.example.com', true); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: stdinTty }); - Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: stdoutTty }); - } + }); expect(spawnSyncMock.mock.calls.map((call) => call[1])).toEqual([ ['access', 'login', '--quiet', 'https://api.example.com'], ['access', 'token', '-app=https://api.example.com'], @@ -282,6 +289,38 @@ describe('origin-scoped self-hosted Access login', () => { expect(keyring.write).toHaveBeenCalledWith('dev.void.cli.access', expect.any(String), fresh); }); + it('signs in only with a terminal on stdin and stderr', async () => { + keyring.read.mockReturnValue(jwt(Math.floor(Date.now() / 1000) + 600)); + for (const terminals of [ + { stdin: true, stdout: true, stderr: false }, + { stdin: false, stdout: true, stderr: true }, + ]) { + spawnSyncMock.mockReset(); + await withTerminals(terminals, async () => { + vi.resetModules(); + const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); + expect(() => ensurePlatformAccessToken('https://api.example.com', true)).toThrow( + 'Re-run this command in an interactive terminal to renew it.', + ); + }); + expect(spawnSyncMock).not.toHaveBeenCalled(); + } + + // Nor does an expired credential start one. + keyring.read.mockReturnValue(jwt(1)); + spawnSyncMock.mockReset().mockReturnValue({ status: 0, stdout: '' }); + await withTerminals({ stdin: true, stdout: true, stderr: false }, async () => { + vi.resetModules(); + const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); + expect(() => ensurePlatformAccessToken('https://api.example.com')).toThrow( + 'Cloudflare Access authentication is required.', + ); + }); + expect(spawnSyncMock.mock.calls.map((call) => call[1])).toEqual([ + ['access', 'token', '-app=https://api.example.com'], + ]); + }); + it('does not treat arbitrary redirects as company authentication challenges', async () => { const { isCloudflareAccessChallenge } = await import('../../src/cli/cf-access.ts'); expect( diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index ab47ed69d..20d276417 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -11,6 +11,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { toSlash } from 'pathslash'; import { afterEach, beforeEach, describe, it, expect, vi } from 'vite-plus/test'; +import type { MockInstance } from 'vite-plus/test'; const mockExecFileSync = vi.hoisted(() => vi.fn<(...args: Array) => string | Buffer | undefined>(), @@ -830,15 +831,24 @@ describe('void db execute', () => { }); describe('SQLite --json', () => { - // With --json, console.log writes the results and nothing else, not even a blank line. + // The command puts a write of its own in stdout's place, so the spy is kept here. + let stdoutWrite: MockInstance; + beforeEach(() => { + stdoutWrite = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + }); + + // With --json, stdout receives the results in one write and nothing else, not even a blank + // line. function jsonOutput(): Array<{ results: Array>; success: boolean; meta: Record; }> { - const calls = vi.mocked(console.log).mock.calls; - expect(calls).toHaveLength(1); - return JSON.parse(String(calls[0][0])) as ReturnType; + const writes = stdoutWrite.mock.calls; + expect(writes).toHaveLength(1); + const [[text]] = writes; + expect(String(text).endsWith(']\n')).toBe(true); + return JSON.parse(String(text)) as ReturnType; } async function readItems(root: string): Promise> { @@ -878,6 +888,50 @@ describe('void db execute', () => { expect(outro).not.toHaveBeenCalled(); }); + it('sends what void.config.ts writes to stdout to stderr, every time it loads and after', async () => { + const root = await createLocalSqliteProject(); + rmSync(join(root, 'void.json')); + writeFileSync( + join(root, 'void.config.ts'), + "process.stdout.write('config loaded\\n');\nexport default {};\n", + ); + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true); + + await runDbCommand(root, { action: 'execute', command: 'SELECT 1 AS one', json: true }); + + expect(jsonOutput()).toEqual([ + { results: [{ one: 1 }], success: true, meta: expect.any(Object) }, + ]); + const loads = stderr.mock.calls.filter(([text]) => text === 'config loaded\n'); + expect(loads.length).toBeGreaterThan(1); + + // A failing statement leaves stdout empty, config output included. + stdoutWrite.mockClear(); + await expect( + runDbCommand(root, { action: 'execute', command: 'SELECT * FROM missing', json: true }), + ).rejects.toThrow('no such table: missing'); + expect(stdoutWrite).not.toHaveBeenCalled(); + // What the config started may write once the results are out, and that goes to stderr too. + process.stdout.write('later\n'); + expect(stderr).toHaveBeenLastCalledWith('later\n'); + expect(stdoutWrite).not.toHaveBeenCalled(); + }); + + it('keeps a column named __proto__', async () => { + const root = await createLocalSqliteProject(); + + await runDbCommand(root, { + action: 'execute', + command: 'SELECT 1 AS [__proto__], 2 AS a, 3 AS a', + json: true, + }); + + const [{ results }] = jsonOutput(); + expect(Object.hasOwn(results[0], '__proto__')).toBe(true); + expect(Object.getPrototypeOf(results[0])).toBe(Object.prototype); + expect(JSON.stringify(results)).toBe('[{"__proto__":1,"a":3}]'); + }); + it('keeps NULL, text, numbers, newlines and blobs apart', async () => { const root = await createLocalSqliteProject(); @@ -994,7 +1048,7 @@ describe('void db execute', () => { }), ).rejects.toThrow('no such table: missing'); - expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + expect(stdoutWrite).not.toHaveBeenCalled(); expect(await readItems(root)).toEqual([{ name: 'kept' }]); }); @@ -1004,7 +1058,7 @@ describe('void db execute', () => { await expect( runDbCommand(root, { action: 'execute', command: 'SELECT 1; SELECT (2', json: true }), ).rejects.toThrow('incomplete input'); - expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + expect(stdoutWrite).not.toHaveBeenCalled(); }); it('reports trailing input SQLite rejects instead of ignoring it', async () => { @@ -1015,7 +1069,7 @@ describe('void db execute', () => { runDbCommand(root, { action: 'execute', command, json: true }), ).rejects.toThrow('syntax error'); } - expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + expect(stdoutWrite).not.toHaveBeenCalled(); }); it('prints an empty array for SQL without a statement', async () => { diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index 7a9a80a59..fb2082caa 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { CustomTypesConfig } from 'pg'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import type { MockInstance } from 'vite-plus/test'; import { Buffer } from '../../src/cli/node-buffer.ts'; const mockReadDeploymentPlatform = vi.fn(() => 'void'); @@ -149,6 +150,16 @@ function jsonResponse(body: unknown, status = 200): Response { }); } +// The command puts a write of its own in stdout's place, so the spy is kept here. +let stdoutWrite: MockInstance; + +/** The results `void db execute --json` wrote to stdout, in one write and nothing else. */ +function stdoutJson(): unknown { + const writes = stdoutWrite.mock.calls; + expect(writes).toHaveLength(1); + return JSON.parse(String(writes[0][0])); +} + describe('void db execute --remote (D1)', () => { let runDbCommand: typeof import('../../src/cli/db.ts').runDbCommand; @@ -609,12 +620,10 @@ describe('void db execute --remote (D1)', () => { }); describe('--json', () => { - // With --json, console.log writes the results and nothing else. - const jsonOutput = () => { - const calls = vi.mocked(console.log).mock.calls; - expect(calls).toHaveLength(1); - return JSON.parse(String(calls[0][0])) as unknown; - }; + beforeEach(() => { + stdoutWrite = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + }); + const jsonOutput = stdoutJson; it('prints each direct D1 statement result as JSON without the success line', async () => { mockReadDeploymentPlatform.mockReturnValue('cloudflare'); @@ -665,7 +674,7 @@ describe('void db execute --remote (D1)', () => { expect(mockConfirm).not.toHaveBeenCalled(); expect(mockImportD1).not.toHaveBeenCalled(); expect(mockExecuteD1Statements).not.toHaveBeenCalled(); - expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + expect(stdoutWrite).not.toHaveBeenCalled(); }); it("prints the platform proxy's D1 result as a one-statement array", async () => { @@ -731,7 +740,7 @@ describe('void db execute --remote (D1)', () => { expect(clackLog.error).toHaveBeenCalledWith(expect.stringContaining('Not logged in'), { output: process.stderr, }); - expect(vi.mocked(console.log)).not.toHaveBeenCalled(); + expect(stdoutWrite).not.toHaveBeenCalled(); }); }); @@ -762,6 +771,7 @@ describe('void db execute --remote (PostgreSQL)', () => { mockIsCancel.mockImplementation((v) => typeof v === 'symbol'); vi.spyOn(console, 'log').mockImplementation(() => {}); + stdoutWrite = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`process.exit:${code ?? 0}`); }) as never); @@ -868,7 +878,7 @@ describe('void db execute --remote (PostgreSQL)', () => { expect(mockMySqlCreateConnection).toHaveBeenLastCalledWith( expect.objectContaining({ supportBigNumbers: true, bigNumberStrings: false }), ); - expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + expect(stdoutJson()).toEqual([ { results: [{ id: '9007199254740993' }], success: true, meta: {} }, ]); @@ -906,7 +916,7 @@ describe('void db execute --remote (PostgreSQL)', () => { { uri: 'mysql://host/db' }, expect.objectContaining({ uri: 'mysql://host/db', multipleStatements: true }), ]); - expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + expect(stdoutJson()).toEqual([ { results: [{ a: '\\' }], success: true, meta: {} }, { results: [{ b: 2 }], success: true, meta: { affectedRows: 0, insertId: 0 } }, ]); @@ -945,7 +955,7 @@ describe('void db execute --remote (PostgreSQL)', () => { { uri: withoutDebug }, expect.objectContaining({ uri: withoutDebug, dateStrings: true }), ]); - expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + expect(stdoutJson()).toEqual([ { results: [{ at: '2024-01-02 03:04:05.123456' }], success: true, meta: {} }, ]); @@ -988,7 +998,7 @@ describe('void db execute --remote (PostgreSQL)', () => { }), ).rejects.toThrow('cannot tell whether an EXECUTE in this MySQL SQL runs a CALL'); expect(mockMySqlQuery).not.toHaveBeenCalled(); - expect(console.log).not.toHaveBeenCalled(); + expect(stdoutWrite).not.toHaveBeenCalled(); mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); }); @@ -1009,7 +1019,7 @@ describe('void db execute --remote (PostgreSQL)', () => { // MySQL answers a comment after the last statement with a result of its own. expect(mockMySqlQuery.mock.calls.map(([sql]) => sql)).toEqual(['CALL p();', command]); - expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0]))).toEqual([ + expect(stdoutJson()).toEqual([ { results: [{ a: 1 }], success: true, meta: { affectedRows: 0, insertId: 0 } }, ]); mockMySqlQuery.mockImplementation(() => Promise.resolve([[], []])); @@ -1046,9 +1056,7 @@ describe('void db execute --remote (PostgreSQL)', () => { json: true, }); - const calls = vi.mocked(console.log).mock.calls; - expect(calls).toHaveLength(1); - expect(JSON.parse(String(calls[0][0]))).toEqual([ + expect(stdoutJson()).toEqual([ { results: [], success: true, meta: { command: 'UPDATE', rowCount: 2 } }, { results: [{ id: 1, name: null }], diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index cec77c16e..7a247aac1 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -171,6 +171,22 @@ describe('db execute --json results', () => { ]); }); + it('reads MySQL insert IDs as unsigned', () => { + // mysql2 reads the unsigned 64-bit ID as signed, so 2^63 and up arrive negative. + const insertIds = (ids: Array) => + ids.map( + (insertId) => + groupResults({ ...header, insertId }, undefined, 'INSERT INTO a VALUES ()')[0].meta + .insertId, + ); + expect(insertIds([5, '9007199254740993', '-9223372036854775808', -1])).toEqual([ + 5, + '9007199254740993', + '9223372036854775808', + '18446744073709551615', + ]); + }); + it('reads each MySQL statement of a multi-statement query', () => { expect( groupResults( @@ -286,6 +302,8 @@ describe('db execute --json results', () => { expect(needsMySqlServerMode(backslash)).toBe(true); expect(needsMySqlServerMode('/*!80000 SET @n = 1 */')).toBe(true); expect(needsMySqlServerMode('/*M!100100 SELECT 0 */')).toBe(true); + // A double quote opens a name in ANSI_QUOTES mode. + expect(needsMySqlServerMode('PREPARE "s" FROM \'SELECT 1\'')).toBe(true); }); it('reads MariaDB executable comments the way MariaDB does', () => { @@ -333,6 +351,15 @@ describe('db execute --json results', () => { expect(calls(String.raw`SELECT 1 AS "a\"; CALL p()`, ansi)).toEqual([false, true]); // A single-quoted string still reads its backslash escapes. expect(calls(String.raw`SELECT 'a\'; CALL p()'`, ansi)).toEqual([false]); + // A prepared statement's name may be double-quoted. + const prepared = 'PREPARE "s" FROM \'CALL p()\'; EXECUTE s; EXECUTE "S"'; + expect(calls(prepared, ansi)).toEqual([false, true, true]); + expect(() => + calls('PREPARE s FROM \'CALL p()\'; DEALLOCATE PREPARE "s"; EXECUTE s', ansi), + ).toThrow('cannot tell whether an EXECUTE in this MySQL SQL runs a CALL'); + // Elsewhere a double-quoted name is a string, which the server rejects there, so after an + // unclear change of sql_mode only ANSI_QUOTES mode reads such SQL. + expect(calls(`SET sql_mode = @m; ${prepared}`)).toEqual([false, false, true, true]); }); it('finds MySQL statements around stored program bodies', () => { @@ -400,6 +427,18 @@ describe('db execute --json results', () => { ).toEqual([false, true]); }); + it('reads the dot after digits as a decimal point, not a name qualifier', () => { + for (const number of ['1.', '1.5', '1.e5', '1.5e-3', '.5']) { + expect(calls(`SELECT CASE WHEN 1 THEN ${number} END; CALL p()`)).toEqual([false, true]); + } + expect( + calls('CREATE PROCEDURE p() BEGIN SELECT CASE WHEN 1 THEN 1. END; END; CALL p()'), + ).toEqual([false, true]); + // Digits after a qualifier name a column, and a dot after them qualifies the next name. + expect(calls('SELECT CASE WHEN 1 THEN t.1 END FROM t; CALL p()')).toEqual([false, true]); + expect(calls('SELECT CASE WHEN 1 THEN d.1.case END FROM d.1; CALL p()')).toEqual([false, true]); + }); + it('keeps an ALTER EVENT body in one MySQL statement', () => { expect( calls( diff --git a/packages/void/test/unit/direct-r2-client.test.ts b/packages/void/test/unit/direct-r2-client.test.ts index 3dccbac89..06e7b4851 100644 --- a/packages/void/test/unit/direct-r2-client.test.ts +++ b/packages/void/test/unit/direct-r2-client.test.ts @@ -1136,6 +1136,7 @@ describe('PlatformClient Cloudflare Access challenge renewal', () => { `e30.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + seconds })).toString('base64url')}.signature`; let stdinTty: boolean | undefined; let stdoutTty: boolean | undefined; + let stderrTty: boolean | undefined; beforeEach(() => { spawnSyncMock.mockReset(); @@ -1143,12 +1144,14 @@ describe('PlatformClient Cloudflare Access challenge renewal', () => { accessKeyring.write.mockReset().mockReturnValue(true); stdinTty = process.stdin.isTTY; stdoutTty = process.stdout.isTTY; + stderrTty = process.stderr.isTTY; vi.stubEnv('VOID_ACCESS_ORIGIN', undefined); }); afterEach(() => { Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: stdinTty }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: stdoutTty }); + Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: stderrTty }); }); it('renews a rejected human token and retries once at the original API endpoint', async () => { @@ -1157,6 +1160,7 @@ describe('PlatformClient Cloudflare Access challenge renewal', () => { vi.stubEnv('VOID_ACCESS_CREDENTIALS', JSON.stringify({ [origin]: { CF_ACCESS_TOKEN: stale } })); Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true }); + Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: true }); spawnSyncMock.mockImplementation((_command, args: Array) => args[1] === 'login' ? { status: 0, stdout: '' } : { status: 0, stdout: fresh }, ); @@ -1210,6 +1214,7 @@ describe('PlatformClient Cloudflare Access challenge renewal', () => { ); Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false }); Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: false }); + Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: false }); const client = new PlatformClient(token, { apiUrl: origin }); vi.stubEnv('VOID_ACCESS_CREDENTIALS', undefined); fetchMock.mockResolvedValueOnce( From 176d2db5d3ac698200db2d12502a6c8b5852adbc Mon Sep 17 00:00:00 2001 From: karthic Date: Thu, 26 Nov 2026 08:19:15 +0530 Subject: [PATCH 09/11] fix(cli): renew Access sessions with stderr redirected and keep child process output off `void db execute --json` stdout The Cloudflare Access sign-in writes to stdout again when it is a terminal, so an interactive command run with `2>log` can renew an expired session. It uses stderr only while stdout is redirected or kept for `--json` results. While `--json` keeps stdout for its results, child processes that would inherit stdout (for example one void.config.ts starts with `execFileSync(..., { stdio: 'inherit' })`) get stderr instead. Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/database.md | 2 +- packages/void/src/cli/cf-access.ts | 32 +++-- packages/void/src/cli/db.ts | 34 +---- packages/void/src/cli/stdout-results.ts | 127 ++++++++++++++++++ packages/void/test/unit/cf-access.test.ts | 83 +++++++++--- .../test/unit/db-execute-json-stdout.test.ts | 70 ++++++++++ 6 files changed, 290 insertions(+), 58 deletions(-) create mode 100644 packages/void/src/cli/stdout-results.ts create mode 100644 packages/void/test/unit/db-execute-json-stdout.test.ts diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 7bccec50c..6210d5677 100644 --- a/docs/reference/cli/database.md +++ b/docs/reference/cli/database.md @@ -71,7 +71,7 @@ For destructive statements (`DELETE`, `UPDATE`, `DROP`, etc.) when running in a ### JSON output {#void-db-execute-json} -Pass `--json` to read results from a script. stdout receives only a JSON array with one entry per statement, including statements in SQL with several statements. Prompts, warnings, errors and any other output, such as messages that `void.config.ts` prints, go to stderr, and a failure exits with a non-zero status. +Pass `--json` to read results from a script. stdout receives only a JSON array with one entry per statement, including statements in SQL with several statements. Prompts, warnings, errors and any other output, such as messages that `void.config.ts` or a process it starts prints, go to stderr, and a failure exits with a non-zero status. ```sh void db execute --json "select count(*) as total from users; select id from users limit 1" diff --git a/packages/void/src/cli/cf-access.ts b/packages/void/src/cli/cf-access.ts index d5d70eea4..c9b7be6bd 100644 --- a/packages/void/src/cli/cf-access.ts +++ b/packages/void/src/cli/cf-access.ts @@ -3,6 +3,7 @@ import { cfAccessHeaders } from '../shared/cf-access.ts'; import { readKeyringPassword, writeKeyringPassword } from './keyring.ts'; import { Buffer } from './node-buffer.ts'; import { normalizePlatformApiUrl, platformCredentialAccount } from './platform-registry.ts'; +import { isStdoutReservedForResults } from './stdout-results.ts'; const ACCESS_KEYRING_SERVICE = 'dev.void.cli.access'; const keyringTokens = new Map(); @@ -136,29 +137,40 @@ export function ensurePlatformAccessToken( } /** - * Whether a browser sign-in can run: it needs a terminal on stdin and stderr, where it writes. - * stdout may be redirected, as it is for a command's result (`void db execute --json | jq`). + * The terminal a browser sign-in writes to: stdout, or stderr while stdout is redirected or kept + * for a command's result (`void db execute --json | jq`). Undefined when neither is a terminal + * it may use, or stdin is not one, so no sign-in can run. */ +function signInOutput(): 1 | 2 | undefined { + if (!process.stdin.isTTY) { + return undefined; + } + if (process.stdout.isTTY && !isStdoutReservedForResults()) { + return 1; + } + return process.stderr.isTTY ? 2 : undefined; +} + function canSignIn(): boolean { - return Boolean(process.stdin.isTTY && process.stderr.isTTY); + return signInOutput() !== undefined; } -/** - * Sign in through the browser. `--quiet` keeps the JWT off the terminal, and cloudflared's - * output goes to stderr, since stdout may carry a command's result (`void db execute --json`). - */ +/** Sign in through the browser. `--quiet` keeps the JWT off the terminal. */ function runCloudflaredLogin(origin: string): void { - runCloudflared(['access', 'login', '--quiet', origin], { inherit: true, timeoutMs: 120_000 }); + runCloudflared(['access', 'login', '--quiet', origin], { + output: signInOutput(), + timeoutMs: 120_000, + }); } function runCloudflared( args: Array, - opts?: { inherit?: boolean; timeoutMs?: number }, + opts?: { output?: 1 | 2; timeoutMs?: number }, ): string | null { try { const result = spawnSync('cloudflared', args, { encoding: 'utf8', - stdio: opts?.inherit ? ['inherit', 2, 'inherit'] : ['ignore', 'pipe', 'pipe'], + stdio: opts?.output ? ['inherit', opts.output, 'inherit'] : ['ignore', 'pipe', 'pipe'], timeout: opts?.timeoutMs ?? 5000, }); if (result.error || result.status !== 0) { diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index e4190fa96..187998f20 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -71,6 +71,7 @@ import { formatTimestamp } from './gen.ts'; import { Buffer } from './node-buffer.ts'; import { printSuccess, dim, formatCount, formatUrl, getErrorMessage, pc } from './output.ts'; import { readDeploymentPlatform, readProjectConfig } from './project.ts'; +import { reserveStdoutForResults } from './stdout-results.ts'; import { drizzleKitBin } from './yarn-pnp.ts'; const DEFAULT_SEED_FILES = [ @@ -203,8 +204,11 @@ function validatePendingMigrations( export async function runDbCommand(root: string, args: DbArgs): Promise { if (args.action === 'execute' && args.json) { - // Before the config loads, which may write to stdout. - const printResults = reserveStdoutForResults(); + // Before the config loads, which may write to stdout or start a process that does. + const writeResults = reserveStdoutForResults(); + const printResults: PrintResults = (results) => { + writeResults(`${formatStatementResults(results)}\n`); + }; await runExecute(root, args, getDatabaseDialect(readConfig(root)), printResults); return; } @@ -1032,32 +1036,6 @@ function mySqlJsonUri(dbUrl: string): string { /** How `void db execute --json` prints its results. */ type PrintResults = (results: Array) => void; -/** stdout's own write, and what takes its place while stdout is kept for results. */ -let reservedStdout: - | { write: (text: string) => void; redirect: typeof process.stdout.write } - | undefined; - -/** - * Keep stdout for `void db execute --json` results, and return the function that prints them. - * Anything else written to stdout from then on goes to stderr until the process exits: a - * console.log in void.config.ts runs each time the command loads the config, and a timer the - * config starts may still write after the results. A second command in the same process keeps - * the first one's place, unless stdout's write has changed since. - */ -function reserveStdoutForResults(): PrintResults { - const { stdout, stderr } = process; - if (reservedStdout?.redirect !== stdout.write) { - const redirect = ((...args: Parameters) => - stderr.write(...args)) as typeof stdout.write; - reservedStdout = { write: stdout.write.bind(stdout), redirect }; - stdout.write = redirect; - } - const { write } = reservedStdout; - return (results) => { - write(`${formatStatementResults(results)}\n`); - }; -} - /** * Prompt the user to confirm a destructive remote query when running in a TTY. * `always` asks even for read-only SQL, and `yes` (`--yes`) never asks. Returns true if diff --git a/packages/void/src/cli/stdout-results.ts b/packages/void/src/cli/stdout-results.ts new file mode 100644 index 000000000..10bf1c3e1 --- /dev/null +++ b/packages/void/src/cli/stdout-results.ts @@ -0,0 +1,127 @@ +import type { execSync, spawnSync } from 'node:child_process'; +import { createRequire, syncBuiltinESMExports } from 'node:module'; + +/** stdout's own write, and what takes its place while stdout is kept for results. */ +let reservation: + | { write: (text: string) => void; redirect: typeof process.stdout.write } + | undefined; +let childProcessesRedirected = false; + +/** + * Keep stdout for a command's results (`void db execute --json`), and return the function that + * writes them. Anything else written to stdout from then on goes to stderr until the process + * exits: a console.log in void.config.ts runs each time the command loads the config, and a timer + * the config starts may still write after the results. The same holds for a child process that + * would inherit stdout, such as one void.config.ts starts with `execFileSync(..., { stdio: + * 'inherit' })`: its stdout is stderr. A second command in the same process keeps the first + * one's place, unless stdout's write has changed since. + */ +export function reserveStdoutForResults(): (text: string) => void { + const { stdout, stderr } = process; + if (reservation?.redirect !== stdout.write) { + const redirect = ((...args: Parameters) => + stderr.write(...args)) as typeof stdout.write; + reservation = { write: stdout.write.bind(stdout), redirect }; + stdout.write = redirect; + } + redirectChildProcessStdout(); + const { write } = reservation; + return (text) => write(text); +} + +/** Whether stdout is kept for a command's results, so nothing else may write to it. */ +export function isStdoutReservedForResults(): boolean { + return reservation !== undefined && reservation.redirect === process.stdout.write; +} + +/** + * Give child processes stderr where they would inherit stdout, while stdout is reserved. The + * builtin's exports are wrapped, and synced to its ESM bindings, so every way of starting a child + * goes through here: `spawn`, `exec`, `execFile` and `fork` start through + * `ChildProcess.prototype.spawn`, and the synchronous functions are wrapped one by one. + */ +function redirectChildProcessStdout(): void { + if (childProcessesRedirected) { + return; + } + childProcessesRedirected = true; + // The builtin itself, whose exports the ESM bindings follow, rather than a module mock. + const childProcess = createRequire(import.meta.url)('node:child_process') as ChildProcessModule; + + const { prototype } = childProcess.ChildProcess; + const spawn = prototype.spawn; + prototype.spawn = function (options) { + return spawn.call(this, withStdoutOnStderr(options)); + }; + childProcess.spawnSync = withOptionsAt(childProcess.spawnSync, optionsAfterArgs); + childProcess.execFileSync = withOptionsAt(childProcess.execFileSync, optionsAfterArgs); + childProcess.execSync = withOptionsAt(childProcess.execSync, () => 1); + syncBuiltinESMExports(); +} + +/** The parts of `node:child_process` that start a child process. */ +type ChildProcessModule = { + ChildProcess: { prototype: ChildProcessStart }; + spawnSync: StartSync; + execFileSync: StartSync; + execSync: StartSync; +}; + +/** + * The internal method that starts every asynchronous child process. It returns the spawn error + * code, or undefined once the process starts. + */ +type ChildProcessStart = { + spawn: (this: ChildProcessStart, options?: SpawnOptions) => number | undefined; +}; + +type StartSync = ( + ...args: Array +) => ReturnType | ReturnType; + +type SpawnOptions = { stdio?: unknown }; + +/** + * spawnSync(command, args?, options?) and execFileSync(file, args?, options?) take options + * second when args are left out. + */ +function optionsAfterArgs(args: Array): number { + return args[1] === undefined || args[1] === null || Array.isArray(args[1]) ? 2 : 1; +} + +/** `run`, with stderr in place of an inherited stdout in the options at `optionsIndex`. */ +function withOptionsAt(run: StartSync, optionsIndex: (args: Array) => number): StartSync { + return (...args) => { + const index = optionsIndex(args); + const options = args[index]; + if (typeof options === 'object' && options !== null && !Array.isArray(options)) { + args[index] = withStdoutOnStderr(options); + } + return run(...args); + }; +} + +/** The options with stderr in place of an inherited stdout, while stdout is reserved. */ +function withStdoutOnStderr(options: SpawnOptions | undefined): SpawnOptions | undefined { + if (!options || !isStdoutReservedForResults()) { + return options; + } + const stdio: unknown = options.stdio; + if (stdio === 'inherit') { + return { ...options, stdio: ['inherit', 2, 'inherit'] }; + } + if (Array.isArray(stdio) && inheritsStdout(stdio[1])) { + const redirected: Array = Array.from(stdio as Array); + redirected[1] = 2; + return { ...options, stdio: redirected }; + } + return options; +} + +function inheritsStdout(value: unknown): boolean { + return ( + value === 'inherit' || + value === 1 || + (typeof value === 'object' && value !== null && 'fd' in value && value.fd === 1) + ); +} diff --git a/packages/void/test/unit/cf-access.test.ts b/packages/void/test/unit/cf-access.test.ts index b5c4a4143..9d7d107f5 100644 --- a/packages/void/test/unit/cf-access.test.ts +++ b/packages/void/test/unit/cf-access.test.ts @@ -271,8 +271,7 @@ describe('origin-scoped self-hosted Access login', () => { spawnSyncMock.mockImplementation((_command, args: Array) => args[1] === 'login' ? { status: 0, stdout: '' } : { status: 0, stdout: fresh }, ); - // stdout may be piped, as in `void db execute --remote --json | jq`: the sign-in uses stdin - // and stderr. + // With stdout piped, the sign-in writes to stderr. await withTerminals({ stdin: true, stdout: false, stderr: true }, async () => { const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); ensurePlatformAccessToken('https://api.example.com', true); @@ -281,7 +280,6 @@ describe('origin-scoped self-hosted Access login', () => { ['access', 'login', '--quiet', 'https://api.example.com'], ['access', 'token', '-app=https://api.example.com'], ]); - // The browser login keeps the JWT and its messages off stdout. expect(spawnSyncMock.mock.calls[0]?.[2]).toMatchObject({ stdio: ['inherit', 2, 'inherit'] }); expect(cfAccessHeaders(process.env, 'https://api.example.com')).toEqual({ 'cf-access-token': fresh, @@ -289,27 +287,74 @@ describe('origin-scoped self-hosted Access login', () => { expect(keyring.write).toHaveBeenCalledWith('dev.void.cli.access', expect.any(String), fresh); }); - it('signs in only with a terminal on stdin and stderr', async () => { - keyring.read.mockReturnValue(jwt(Math.floor(Date.now() / 1000) + 600)); - for (const terminals of [ - { stdin: true, stdout: true, stderr: false }, - { stdin: false, stdout: true, stderr: true }, - ]) { - spawnSyncMock.mockReset(); - await withTerminals(terminals, async () => { - vi.resetModules(); - const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); - expect(() => ensurePlatformAccessToken('https://api.example.com', true)).toThrow( - 'Re-run this command in an interactive terminal to renew it.', + it('signs in on stdout, or on stderr while stdout is redirected or kept for results', async () => { + const fresh = jwt(Math.floor(Date.now() / 1000) + 900); + const cases: Array<{ + terminals: Record<'stdin' | 'stdout' | 'stderr', boolean>; + reserved: boolean; + output: 1 | 2 | undefined; + }> = [ + // An interactive command with its messages in a file (`void db execute ... 2>log`). + { terminals: { stdin: true, stdout: true, stderr: false }, reserved: false, output: 1 }, + { terminals: { stdin: true, stdout: true, stderr: true }, reserved: false, output: 1 }, + { terminals: { stdin: true, stdout: false, stderr: true }, reserved: false, output: 2 }, + // `void db execute --remote --json` in a terminal keeps stdout for its results. + { terminals: { stdin: true, stdout: true, stderr: true }, reserved: true, output: 2 }, + { + terminals: { stdin: true, stdout: true, stderr: false }, + reserved: true, + output: undefined, + }, + { + terminals: { stdin: false, stdout: true, stderr: true }, + reserved: false, + output: undefined, + }, + { + terminals: { stdin: true, stdout: false, stderr: false }, + reserved: false, + output: undefined, + }, + ]; + const write = process.stdout.write; + for (const { terminals, reserved, output } of cases) { + keyring.read.mockReturnValue(jwt(Math.floor(Date.now() / 1000) + 600)); + spawnSyncMock + .mockReset() + .mockImplementation((_command, args: Array) => + args[1] === 'login' ? { status: 0, stdout: '' } : { status: 0, stdout: fresh }, ); - }); - expect(spawnSyncMock).not.toHaveBeenCalled(); + vi.resetModules(); + if (reserved) { + const { reserveStdoutForResults } = await import('../../src/cli/stdout-results.ts'); + reserveStdoutForResults(); + } + try { + await withTerminals(terminals, async () => { + const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); + const renew = () => ensurePlatformAccessToken('https://api.example.com', true); + if (output === undefined) { + expect(renew).toThrow('Re-run this command in an interactive terminal to renew it.'); + } else { + renew(); + } + }); + } finally { + process.stdout.write = write; + } + if (output === undefined) { + expect(spawnSyncMock).not.toHaveBeenCalled(); + } else { + expect(spawnSyncMock.mock.calls[0]?.[2]).toMatchObject({ + stdio: ['inherit', output, 'inherit'], + }); + } } - // Nor does an expired credential start one. + // Nor does an expired credential start a sign-in without a terminal to write to. keyring.read.mockReturnValue(jwt(1)); spawnSyncMock.mockReset().mockReturnValue({ status: 0, stdout: '' }); - await withTerminals({ stdin: true, stdout: true, stderr: false }, async () => { + await withTerminals({ stdin: true, stdout: false, stderr: false }, async () => { vi.resetModules(); const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); expect(() => ensurePlatformAccessToken('https://api.example.com')).toThrow( diff --git a/packages/void/test/unit/db-execute-json-stdout.test.ts b/packages/void/test/unit/db-execute-json-stdout.test.ts new file mode 100644 index 000000000..8472c853e --- /dev/null +++ b/packages/void/test/unit/db-execute-json-stdout.test.ts @@ -0,0 +1,70 @@ +import { execFile } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { afterEach, expect, it } from 'vite-plus/test'; + +const roots: Array = []; +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +const source = (path: string) => + pathToFileURL(join(import.meta.dirname, '..', '..', 'src', path)).href; + +// Child processes write to the process's own stdout, which only a real process can observe. +it('keeps the stdout of processes that void.config.ts starts off `void db execute --json` stdout', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-execute-json-stdout-')); + roots.push(root); + writeFileSync(join(root, 'fork.mjs'), "console.log('fork');\n"); + const harness = join(root, 'harness.mjs'); + writeFileSync( + harness, + `import { mkdirSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; +const { getLocalD1Target, runDbCommand } = await import(${JSON.stringify(source('cli/db.ts'))}); +const { openSqliteDatabase } = await import(${JSON.stringify(source('migrations/runner.ts'))}); +// The database is created before the config exists, so the setup prints nothing. +const { databasePath } = getLocalD1Target(process.cwd()); +mkdirSync(dirname(databasePath), { recursive: true }); +(await openSqliteDatabase(databasePath)).close(); +writeFileSync('void.config.ts', ${JSON.stringify(`import { execFileSync, fork, spawn, spawnSync } from 'node:child_process'; +const print = (text: string) => ['-e', \`console.log(\${JSON.stringify(text)})\`]; +console.log('config'); +execFileSync(process.execPath, print('execFileSync'), { stdio: 'inherit' }); +spawnSync(process.execPath, print('spawnSync'), { stdio: [0, process.stdout, 2] }); +spawn(process.execPath, print('spawn'), { stdio: ['ignore', 'inherit', 'inherit'] }); +fork('fork.mjs'); +// Output the config reads is still its own. +if (execFileSync(process.execPath, print('captured'), { encoding: 'utf8' }) !== 'captured\\n') { + throw new Error('captured output changed'); +} +export default {}; +`)}); +await runDbCommand(process.cwd(), { action: 'execute', command: 'SELECT 1 AS one', json: true }); +`, + ); + + const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>( + (resolve, reject) => { + execFile( + process.execPath, + [harness], + { cwd: root, encoding: 'utf8', timeout: 30_000 }, + (error, stdout, stderr) => + error ? reject(new Error(`${error.message}\n${stderr}`)) : resolve({ stdout, stderr }), + ); + }, + ); + + expect(JSON.parse(stdout)).toEqual([ + { results: [{ one: 1 }], success: true, meta: expect.any(Object) }, + ]); + expect(stdout.endsWith(']\n')).toBe(true); + expect(new Set(stderr.split('\n'))).toEqual( + new Set(['config', 'execFileSync', 'spawnSync', 'spawn', 'fork', '']), + ); +}); From fff7e0d2653dcb0bf3533d95bdce96f4ae94b6f6 Mon Sep 17 00:00:00 2001 From: karthic Date: Thu, 26 Nov 2026 09:30:54 +0530 Subject: [PATCH 10/11] fix(cli): keep child stderr off `void db execute --json` stdout and print PostgreSQL dates and MySQL JSON exactly Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-execute-results.ts | 40 +++++++++++++++++++ packages/void/src/cli/db.ts | 15 +++++-- packages/void/src/cli/stdout-results.ts | 27 ++++++++----- .../test/unit/db-execute-json-stdout.test.ts | 24 ++++++++++- .../void/test/unit/db-execute-remote.test.ts | 7 +++- .../void/test/unit/db-execute-results.test.ts | 40 +++++++++++++++++++ 6 files changed, 138 insertions(+), 15 deletions(-) diff --git a/packages/void/src/cli/db-execute-results.ts b/packages/void/src/cli/db-execute-results.ts index 50c99a2e9..7f7467a9a 100644 --- a/packages/void/src/cli/db-execute-results.ts +++ b/packages/void/src/cli/db-execute-results.ts @@ -243,11 +243,20 @@ const PG_JSON = 114; const PG_JSONB = 3802; const PG_JSON_ARRAY = 199; const PG_JSONB_ARRAY = 3807; +const PG_DATE = 1082; +const PG_TIMESTAMP = 1114; +const PG_TIMESTAMPTZ = 1184; +const PG_DATE_ARRAY = 1182; +const PG_TIMESTAMP_ARRAY = 1115; +const PG_TIMESTAMPTZ_ARRAY = 1185; /** * Type parsers for `void db execute --json` on PostgreSQL. node-postgres reads `numeric[]` * elements as numbers and JSON with `JSON.parse`, which round what a double cannot hold. Here a * `numeric[]` element stays a string, like a `numeric`, and a JSON number keeps its digits. + * Dates and timestamps stay the text PostgreSQL sends: node-postgres reads a `date` or a + * `timestamp` in the machine's time zone and rounds to milliseconds, so the same row would + * print differently on each machine. */ export function pgJsonTypes(types: CustomTypesConfig): CustomTypesConfig { const parseTextArray = types.getTypeParser(PG_TEXT_ARRAY as CustomTypeId, 'text') as ( @@ -259,6 +268,12 @@ export function pgJsonTypes(types: CustomTypesConfig): CustomTypesConfig { [PG_JSONB, parseExactJson], [PG_JSON_ARRAY, (value) => parseExactJsonElements(parseTextArray(value))], [PG_JSONB_ARRAY, (value) => parseExactJsonElements(parseTextArray(value))], + [PG_DATE, (value) => value], + [PG_TIMESTAMP, (value) => value], + [PG_TIMESTAMPTZ, (value) => value], + [PG_DATE_ARRAY, parseTextArray], + [PG_TIMESTAMP_ARRAY, parseTextArray], + [PG_TIMESTAMPTZ_ARRAY, parseTextArray], ]); return { getTypeParser(oid, format = 'text') { @@ -271,6 +286,31 @@ export function pgJsonTypes(types: CustomTypesConfig): CustomTypesConfig { type CustomTypeId = Parameters[0]; +/** The parts of mysql2's `typeCast` field that `mySqlJsonTypeCast` reads. */ +type MySqlTypeCastField = { + type: string; + extendedFormat?: string; + string: (encoding?: string) => string | null; +}; + +/** + * mysql2's `typeCast` for `void db execute --json`. mysql2 reads JSON with `JSON.parse`, which + * rounds what a double cannot hold, so a JSON number keeps its digits here, as on PostgreSQL. + * MySQL sends JSON as binary, which is UTF-8 text; MariaDB sends it as text and marks it as JSON + * only in its extended metadata. + */ +export function mySqlJsonTypeCast( + field: MySqlTypeCastField, + next: () => Value, +): Value | ExactJson { + const isJson = field.type === 'JSON'; + if (!isJson && field.extendedFormat !== 'json') { + return next(); + } + const text = isJson ? field.string('utf8') : field.string(); + return text === null ? null : parseExactJson(text); +} + /** * node-postgres returns one result for one statement and an array for several. SQL without a * statement returns an empty-query result with no command, which is left out. diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 187998f20..873281881 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -50,6 +50,7 @@ import type { DbArgs } from './db-args.ts'; import { formatStatementResults, MYSQL_SERVER_MODE_QUERY, + mySqlJsonTypeCast, mySqlServerMode, mySqlStatementResults, mySqlStatements, @@ -981,9 +982,17 @@ async function executeExternalSql( const mySqlClient = await createConnection({ uri, multipleStatements: true, - // BIGINT values past 2^53 arrive as strings instead of rounded numbers, and dates and times - // as the text MySQL returns, without a time zone conversion or rounding to milliseconds. - ...(json ? { supportBigNumbers: true, bigNumberStrings: false, dateStrings: true } : {}), + // BIGINT values past 2^53 arrive as strings instead of rounded numbers, dates and times + // as the text MySQL returns, without a time zone conversion or rounding to milliseconds, + // and JSON numbers with the digits MySQL sends. + ...(json + ? { + supportBigNumbers: true, + bigNumberStrings: false, + dateStrings: true, + typeCast: mySqlJsonTypeCast, + } + : {}), }); try { const [rows, fields] = await mySqlClient.query(statements?.sql ?? sql); diff --git a/packages/void/src/cli/stdout-results.ts b/packages/void/src/cli/stdout-results.ts index 10bf1c3e1..661a75196 100644 --- a/packages/void/src/cli/stdout-results.ts +++ b/packages/void/src/cli/stdout-results.ts @@ -101,7 +101,11 @@ function withOptionsAt(run: StartSync, optionsIndex: (args: Array) => n }; } -/** The options with stderr in place of an inherited stdout, while stdout is reserved. */ +/** + * The options with stderr in place of stdout for each of the child's streams that would write to + * it, while stdout is reserved: an inherited stdout, and any stream given stdout's fd or + * `process.stdout`, such as a stderr sent to `process.stdout` while stdout is captured. + */ function withStdoutOnStderr(options: SpawnOptions | undefined): SpawnOptions | undefined { if (!options || !isStdoutReservedForResults()) { return options; @@ -110,18 +114,21 @@ function withStdoutOnStderr(options: SpawnOptions | undefined): SpawnOptions | u if (stdio === 'inherit') { return { ...options, stdio: ['inherit', 2, 'inherit'] }; } - if (Array.isArray(stdio) && inheritsStdout(stdio[1])) { - const redirected: Array = Array.from(stdio as Array); - redirected[1] = 2; - return { ...options, stdio: redirected }; + if (!Array.isArray(stdio)) { + return options; } - return options; + const entries: Array = Array.from(stdio as Array); + const redirected = entries.map((value, index) => + (index === 1 && value === 'inherit') || isStdout(value) ? 2 : value, + ); + return redirected.some((value, index) => value !== entries[index]) + ? { ...options, stdio: redirected } + : options; } -function inheritsStdout(value: unknown): boolean { +/** Whether a stdio entry is stdout's fd, or a stream on it such as `process.stdout`. */ +function isStdout(value: unknown): boolean { return ( - value === 'inherit' || - value === 1 || - (typeof value === 'object' && value !== null && 'fd' in value && value.fd === 1) + value === 1 || (typeof value === 'object' && value !== null && 'fd' in value && value.fd === 1) ); } diff --git a/packages/void/test/unit/db-execute-json-stdout.test.ts b/packages/void/test/unit/db-execute-json-stdout.test.ts index 8472c853e..fd0c9030d 100644 --- a/packages/void/test/unit/db-execute-json-stdout.test.ts +++ b/packages/void/test/unit/db-execute-json-stdout.test.ts @@ -38,6 +38,18 @@ execFileSync(process.execPath, print('execFileSync'), { stdio: 'inherit' }); spawnSync(process.execPath, print('spawnSync'), { stdio: [0, process.stdout, 2] }); spawn(process.execPath, print('spawn'), { stdio: ['ignore', 'inherit', 'inherit'] }); fork('fork.mjs'); +const warn = (text: string) => ['-e', \`console.log('out'); console.error(\${JSON.stringify(text)})\`]; +// A child whose stdout the config reads and whose stderr it sends to stdout. +if ( + execFileSync(process.execPath, warn('stderr to process.stdout'), { + encoding: 'utf8', + stdio: ['ignore', 'pipe', process.stdout], + }) !== 'out\\n' +) { + throw new Error('captured output changed'); +} +spawnSync(process.execPath, warn('stderr to fd 1'), { stdio: ['ignore', 'ignore', 1] }); +spawn(process.execPath, warn('spawn stderr to stdout'), { stdio: ['ignore', 'ignore', process.stdout] }); // Output the config reads is still its own. if (execFileSync(process.execPath, print('captured'), { encoding: 'utf8' }) !== 'captured\\n') { throw new Error('captured output changed'); @@ -65,6 +77,16 @@ await runDbCommand(process.cwd(), { action: 'execute', command: 'SELECT 1 AS one ]); expect(stdout.endsWith(']\n')).toBe(true); expect(new Set(stderr.split('\n'))).toEqual( - new Set(['config', 'execFileSync', 'spawnSync', 'spawn', 'fork', '']), + new Set([ + 'config', + 'execFileSync', + 'spawnSync', + 'spawn', + 'fork', + 'stderr to process.stdout', + 'stderr to fd 1', + 'spawn stderr to stdout', + '', + ]), ); }); diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index fb2082caa..aa03776f8 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import type { CustomTypesConfig } from 'pg'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import type { MockInstance } from 'vite-plus/test'; +import { mySqlJsonTypeCast } from '../../src/cli/db-execute-results.ts'; import { Buffer } from '../../src/cli/node-buffer.ts'; const mockReadDeploymentPlatform = vi.fn(() => 'void'); @@ -953,7 +954,11 @@ describe('void db execute --remote (PostgreSQL)', () => { 'mysql://user:p%40ss@host:3306/db?ssl=%7B%22rejectUnauthorized%22%3Atrue%7D'; expect(mockMySqlCreateConnection.mock.calls.map(([options]) => options)).toEqual([ { uri: withoutDebug }, - expect.objectContaining({ uri: withoutDebug, dateStrings: true }), + expect.objectContaining({ + uri: withoutDebug, + dateStrings: true, + typeCast: mySqlJsonTypeCast, + }), ]); expect(stdoutJson()).toEqual([ { results: [{ at: '2024-01-02 03:04:05.123456' }], success: true, meta: {} }, diff --git a/packages/void/test/unit/db-execute-results.test.ts b/packages/void/test/unit/db-execute-results.test.ts index 7a247aac1..a518f67e1 100644 --- a/packages/void/test/unit/db-execute-results.test.ts +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -2,6 +2,7 @@ import { types } from 'pg'; import { describe, expect, it } from 'vite-plus/test'; import { formatStatementResults, + mySqlJsonTypeCast, mySqlServerMode, mySqlStatementResults, mySqlStatements, @@ -114,11 +115,50 @@ describe('db execute --json results', () => { '[{"a":9007199254740993},null]', ); expect(value(199, '{{"1e400"}}')).toBe('[[1e400]]'); + // Dates and timestamps print as PostgreSQL sends them, in any time zone. + expect(value(1082, '2024-01-15')).toBe('"2024-01-15"'); + expect(value(1114, '2024-01-15 10:30:00.123456')).toBe('"2024-01-1510:30:00.123456"'); + expect(value(1184, '2024-01-15 10:30:00.123456+01')).toBe('"2024-01-1510:30:00.123456+01"'); + expect(value(1182, '{2024-01-15,NULL}')).toBe('["2024-01-15",null]'); + expect(value(1115, '{"2024-01-15 10:30:00.5"}')).toBe('["2024-01-1510:30:00.5"]'); + expect(value(1185, '{"2024-01-15 10:30:00+00"}')).toBe('["2024-01-1510:30:00+00"]'); // Other types keep node-postgres's parsers. expect(parse(23, '5')).toBe(5); expect(parse(20, '9007199254740993')).toBe('9007199254740993'); }); + it('keeps the digits of MySQL and MariaDB JSON numbers', () => { + const cast = (field: { type: string; extendedFormat?: string }, text: string | null) => { + const encodings: Array = []; + const result = mySqlJsonTypeCast( + { + ...field, + string: (encoding) => { + encodings.push(encoding); + return text; + }, + }, + () => 'next', + ); + return { result, encodings }; + }; + const printed = (result: unknown) => + formatStatementResults([{ results: [{ v: result }], success: true, meta: {} }]) + .replaceAll(/\s/g, '') + .slice('[{"results":[{"v":'.length, -'}],"success":true,"meta":{}}]'.length); + // MySQL's JSON type arrives as binary, read as UTF-8. + const mySql = cast({ type: 'JSON' }, '{"id": 12345678901234567890, "p": 1.10}'); + expect(printed(mySql.result)).toBe('{"id":12345678901234567890,"p":1.10}'); + expect(mySql.encodings).toEqual(['utf8']); + // MariaDB marks JSON in its extended metadata, on a text column. + const mariaDb = cast({ type: 'BLOB', extendedFormat: 'json' }, '[0.1000000000000000000001]'); + expect(printed(mariaDb.result)).toBe('[0.1000000000000000000001]'); + expect(mariaDb.encodings).toEqual([undefined]); + expect(cast({ type: 'JSON' }, null).result).toBeNull(); + // Other columns keep mysql2's own reading. + expect(cast({ type: 'VAR_STRING' }, '{"a": 1}')).toEqual({ result: 'next', encodings: [] }); + }); + it('leaves out the empty-query result of SQL without a statement', () => { expect(pgStatementResults({ command: null, rowCount: null, rows: [] })).toEqual([]); }); From a306bbf3bac0f711bc12510927796a9d3238b4bc Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Thu, 26 Nov 2026 13:18:42 +0900 Subject: [PATCH 11/11] Isolate JSON database results from config output. --- packages/void/src/cli/cf-access.ts | 8 +- packages/void/src/cli/cli-main.ts | 12 +- packages/void/src/cli/db-execute-process.ts | 64 +++++++++ packages/void/src/cli/db.ts | 9 +- packages/void/src/cli/stdout-results.ts | 134 ------------------ packages/void/test/unit/cf-access.test.ts | 47 ++---- packages/void/test/unit/db-commands.test.ts | 30 ---- .../test/unit/db-execute-json-stdout.test.ts | 36 ++++- .../void/test/unit/db-execute-remote.test.ts | 1 - packages/void/vite.config.ts | 1 + 10 files changed, 125 insertions(+), 217 deletions(-) create mode 100644 packages/void/src/cli/db-execute-process.ts delete mode 100644 packages/void/src/cli/stdout-results.ts diff --git a/packages/void/src/cli/cf-access.ts b/packages/void/src/cli/cf-access.ts index c9b7be6bd..4e61b2ecf 100644 --- a/packages/void/src/cli/cf-access.ts +++ b/packages/void/src/cli/cf-access.ts @@ -3,7 +3,6 @@ import { cfAccessHeaders } from '../shared/cf-access.ts'; import { readKeyringPassword, writeKeyringPassword } from './keyring.ts'; import { Buffer } from './node-buffer.ts'; import { normalizePlatformApiUrl, platformCredentialAccount } from './platform-registry.ts'; -import { isStdoutReservedForResults } from './stdout-results.ts'; const ACCESS_KEYRING_SERVICE = 'dev.void.cli.access'; const keyringTokens = new Map(); @@ -137,15 +136,14 @@ export function ensurePlatformAccessToken( } /** - * The terminal a browser sign-in writes to: stdout, or stderr while stdout is redirected or kept - * for a command's result (`void db execute --json | jq`). Undefined when neither is a terminal - * it may use, or stdin is not one, so no sign-in can run. + * Browser sign-in needs stdin and an output terminal. For JSON database execution, the child + * process's stdout already goes to the caller's stderr. */ function signInOutput(): 1 | 2 | undefined { if (!process.stdin.isTTY) { return undefined; } - if (process.stdout.isTTY && !isStdoutReservedForResults()) { + if (process.stdout.isTTY) { return 1; } return process.stderr.isTTY ? 2 : undefined; diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 43e1fdcb4..7595199b5 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -170,9 +170,15 @@ const subcommandGroups = { import('./email.ts').then(({ runEmailCommand }) => runEmailCommand(root, parsed)), ), db: () => - runSubcommandGroup('db', dbSubcommands, parseDbArgs, (root, parsed) => - import('./db.ts').then(({ runDbCommand }) => runDbCommand(root, parsed)), - ), + runSubcommandGroup('db', dbSubcommands, parseDbArgs, async (root, parsed) => { + if (parsed.action === 'execute' && parsed.json) { + const { runDbExecuteProcess } = await import('./db-execute-process.ts'); + await runDbExecuteProcess(root, args); + } else { + const { runDbCommand } = await import('./db.ts'); + await runDbCommand(root, parsed); + } + }), env: () => runSubcommandGroup('env', envSubcommands, parseEnvArgs, (root, parsed) => import('./env.ts').then(({ runEnvCommand }) => runEnvCommand(root, parsed)), diff --git a/packages/void/src/cli/db-execute-process.ts b/packages/void/src/cli/db-execute-process.ts new file mode 100644 index 000000000..d08b26c97 --- /dev/null +++ b/packages/void/src/cli/db-execute-process.ts @@ -0,0 +1,64 @@ +import { spawn } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; +import { constants } from 'node:os'; +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { formatCloudflareUserMessage } from './cloudflare-user-output.ts'; +import { Buffer } from './node-buffer.ts'; + +const CHILD_COMMAND = '__void-db-execute-json__'; +const RESULT_FD = 3; + +/** Keep config output on stderr, including writes to fd 1 and output from its children. */ +export async function runDbExecuteProcess( + root: string, + args: ReadonlyArray, +): Promise { + const child = spawn( + process.execPath, + [...process.execArgv, import.meta.filename, CHILD_COMMAND, process.argv[1], ...args], + { + cwd: root, + stdio: ['inherit', 2, 'inherit', 'pipe'], + }, + ); + const chunks: Array = []; + child.stdio[RESULT_FD]?.on('data', (chunk: Buffer) => chunks.push(chunk)); + + // Also forward signals sent to the parent PID alone, as process supervisors do. + const interrupt = () => child.kill('SIGINT'); + const terminate = () => child.kill('SIGTERM'); + process.on('SIGINT', interrupt); + process.on('SIGTERM', terminate); + try { + const code = await new Promise((resolve, reject) => { + child.once('error', reject); + child.once('close', (status, signal) => { + resolve(signal ? 128 + constants.signals[signal] : (status ?? 1)); + }); + }); + if (code !== 0) { + process.exitCode = code; + } else if (chunks.length > 0) { + process.stdout.write(Buffer.concat(chunks)); + } + } finally { + process.off('SIGINT', interrupt); + process.off('SIGTERM', terminate); + } +} + +if (process.argv[2] === CHILD_COMMAND) { + try { + // Keep the CLI arguments visible to project config evaluated by this process. + process.argv.splice(1, 2); + const { parseDbArgs } = await import('./db-args.ts'); + const args = parseDbArgs(process.argv.slice(3)); + const { runDbCommand } = await import('./db.ts'); + await runDbCommand(process.cwd(), args, (text) => writeFileSync(RESULT_FD, text)); + } catch (error) { + log.error(formatCloudflareUserMessage(error instanceof Error ? error.message : String(error)), { + output: process.stderr, + }); + process.exitCode = 1; + } +} diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 873281881..1ae386671 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -72,7 +72,6 @@ import { formatTimestamp } from './gen.ts'; import { Buffer } from './node-buffer.ts'; import { printSuccess, dim, formatCount, formatUrl, getErrorMessage, pc } from './output.ts'; import { readDeploymentPlatform, readProjectConfig } from './project.ts'; -import { reserveStdoutForResults } from './stdout-results.ts'; import { drizzleKitBin } from './yarn-pnp.ts'; const DEFAULT_SEED_FILES = [ @@ -203,10 +202,12 @@ function validatePendingMigrations( validateMigrations(pending); } -export async function runDbCommand(root: string, args: DbArgs): Promise { +export async function runDbCommand( + root: string, + args: DbArgs, + writeResults: (text: string) => void = (text) => process.stdout.write(text), +): Promise { if (args.action === 'execute' && args.json) { - // Before the config loads, which may write to stdout or start a process that does. - const writeResults = reserveStdoutForResults(); const printResults: PrintResults = (results) => { writeResults(`${formatStatementResults(results)}\n`); }; diff --git a/packages/void/src/cli/stdout-results.ts b/packages/void/src/cli/stdout-results.ts deleted file mode 100644 index 661a75196..000000000 --- a/packages/void/src/cli/stdout-results.ts +++ /dev/null @@ -1,134 +0,0 @@ -import type { execSync, spawnSync } from 'node:child_process'; -import { createRequire, syncBuiltinESMExports } from 'node:module'; - -/** stdout's own write, and what takes its place while stdout is kept for results. */ -let reservation: - | { write: (text: string) => void; redirect: typeof process.stdout.write } - | undefined; -let childProcessesRedirected = false; - -/** - * Keep stdout for a command's results (`void db execute --json`), and return the function that - * writes them. Anything else written to stdout from then on goes to stderr until the process - * exits: a console.log in void.config.ts runs each time the command loads the config, and a timer - * the config starts may still write after the results. The same holds for a child process that - * would inherit stdout, such as one void.config.ts starts with `execFileSync(..., { stdio: - * 'inherit' })`: its stdout is stderr. A second command in the same process keeps the first - * one's place, unless stdout's write has changed since. - */ -export function reserveStdoutForResults(): (text: string) => void { - const { stdout, stderr } = process; - if (reservation?.redirect !== stdout.write) { - const redirect = ((...args: Parameters) => - stderr.write(...args)) as typeof stdout.write; - reservation = { write: stdout.write.bind(stdout), redirect }; - stdout.write = redirect; - } - redirectChildProcessStdout(); - const { write } = reservation; - return (text) => write(text); -} - -/** Whether stdout is kept for a command's results, so nothing else may write to it. */ -export function isStdoutReservedForResults(): boolean { - return reservation !== undefined && reservation.redirect === process.stdout.write; -} - -/** - * Give child processes stderr where they would inherit stdout, while stdout is reserved. The - * builtin's exports are wrapped, and synced to its ESM bindings, so every way of starting a child - * goes through here: `spawn`, `exec`, `execFile` and `fork` start through - * `ChildProcess.prototype.spawn`, and the synchronous functions are wrapped one by one. - */ -function redirectChildProcessStdout(): void { - if (childProcessesRedirected) { - return; - } - childProcessesRedirected = true; - // The builtin itself, whose exports the ESM bindings follow, rather than a module mock. - const childProcess = createRequire(import.meta.url)('node:child_process') as ChildProcessModule; - - const { prototype } = childProcess.ChildProcess; - const spawn = prototype.spawn; - prototype.spawn = function (options) { - return spawn.call(this, withStdoutOnStderr(options)); - }; - childProcess.spawnSync = withOptionsAt(childProcess.spawnSync, optionsAfterArgs); - childProcess.execFileSync = withOptionsAt(childProcess.execFileSync, optionsAfterArgs); - childProcess.execSync = withOptionsAt(childProcess.execSync, () => 1); - syncBuiltinESMExports(); -} - -/** The parts of `node:child_process` that start a child process. */ -type ChildProcessModule = { - ChildProcess: { prototype: ChildProcessStart }; - spawnSync: StartSync; - execFileSync: StartSync; - execSync: StartSync; -}; - -/** - * The internal method that starts every asynchronous child process. It returns the spawn error - * code, or undefined once the process starts. - */ -type ChildProcessStart = { - spawn: (this: ChildProcessStart, options?: SpawnOptions) => number | undefined; -}; - -type StartSync = ( - ...args: Array -) => ReturnType | ReturnType; - -type SpawnOptions = { stdio?: unknown }; - -/** - * spawnSync(command, args?, options?) and execFileSync(file, args?, options?) take options - * second when args are left out. - */ -function optionsAfterArgs(args: Array): number { - return args[1] === undefined || args[1] === null || Array.isArray(args[1]) ? 2 : 1; -} - -/** `run`, with stderr in place of an inherited stdout in the options at `optionsIndex`. */ -function withOptionsAt(run: StartSync, optionsIndex: (args: Array) => number): StartSync { - return (...args) => { - const index = optionsIndex(args); - const options = args[index]; - if (typeof options === 'object' && options !== null && !Array.isArray(options)) { - args[index] = withStdoutOnStderr(options); - } - return run(...args); - }; -} - -/** - * The options with stderr in place of stdout for each of the child's streams that would write to - * it, while stdout is reserved: an inherited stdout, and any stream given stdout's fd or - * `process.stdout`, such as a stderr sent to `process.stdout` while stdout is captured. - */ -function withStdoutOnStderr(options: SpawnOptions | undefined): SpawnOptions | undefined { - if (!options || !isStdoutReservedForResults()) { - return options; - } - const stdio: unknown = options.stdio; - if (stdio === 'inherit') { - return { ...options, stdio: ['inherit', 2, 'inherit'] }; - } - if (!Array.isArray(stdio)) { - return options; - } - const entries: Array = Array.from(stdio as Array); - const redirected = entries.map((value, index) => - (index === 1 && value === 'inherit') || isStdout(value) ? 2 : value, - ); - return redirected.some((value, index) => value !== entries[index]) - ? { ...options, stdio: redirected } - : options; -} - -/** Whether a stdio entry is stdout's fd, or a stream on it such as `process.stdout`. */ -function isStdout(value: unknown): boolean { - return ( - value === 1 || (typeof value === 'object' && value !== null && 'fd' in value && value.fd === 1) - ); -} diff --git a/packages/void/test/unit/cf-access.test.ts b/packages/void/test/unit/cf-access.test.ts index 9d7d107f5..ee66c4069 100644 --- a/packages/void/test/unit/cf-access.test.ts +++ b/packages/void/test/unit/cf-access.test.ts @@ -287,37 +287,26 @@ describe('origin-scoped self-hosted Access login', () => { expect(keyring.write).toHaveBeenCalledWith('dev.void.cli.access', expect.any(String), fresh); }); - it('signs in on stdout, or on stderr while stdout is redirected or kept for results', async () => { + it('signs in on stdout, or on stderr while stdout is redirected', async () => { const fresh = jwt(Math.floor(Date.now() / 1000) + 900); const cases: Array<{ terminals: Record<'stdin' | 'stdout' | 'stderr', boolean>; - reserved: boolean; output: 1 | 2 | undefined; }> = [ // An interactive command with its messages in a file (`void db execute ... 2>log`). - { terminals: { stdin: true, stdout: true, stderr: false }, reserved: false, output: 1 }, - { terminals: { stdin: true, stdout: true, stderr: true }, reserved: false, output: 1 }, - { terminals: { stdin: true, stdout: false, stderr: true }, reserved: false, output: 2 }, - // `void db execute --remote --json` in a terminal keeps stdout for its results. - { terminals: { stdin: true, stdout: true, stderr: true }, reserved: true, output: 2 }, - { - terminals: { stdin: true, stdout: true, stderr: false }, - reserved: true, - output: undefined, - }, + { terminals: { stdin: true, stdout: true, stderr: false }, output: 1 }, + { terminals: { stdin: true, stdout: true, stderr: true }, output: 1 }, + { terminals: { stdin: true, stdout: false, stderr: true }, output: 2 }, { terminals: { stdin: false, stdout: true, stderr: true }, - reserved: false, output: undefined, }, { terminals: { stdin: true, stdout: false, stderr: false }, - reserved: false, output: undefined, }, ]; - const write = process.stdout.write; - for (const { terminals, reserved, output } of cases) { + for (const { terminals, output } of cases) { keyring.read.mockReturnValue(jwt(Math.floor(Date.now() / 1000) + 600)); spawnSyncMock .mockReset() @@ -325,23 +314,15 @@ describe('origin-scoped self-hosted Access login', () => { args[1] === 'login' ? { status: 0, stdout: '' } : { status: 0, stdout: fresh }, ); vi.resetModules(); - if (reserved) { - const { reserveStdoutForResults } = await import('../../src/cli/stdout-results.ts'); - reserveStdoutForResults(); - } - try { - await withTerminals(terminals, async () => { - const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); - const renew = () => ensurePlatformAccessToken('https://api.example.com', true); - if (output === undefined) { - expect(renew).toThrow('Re-run this command in an interactive terminal to renew it.'); - } else { - renew(); - } - }); - } finally { - process.stdout.write = write; - } + await withTerminals(terminals, async () => { + const { ensurePlatformAccessToken } = await import('../../src/cli/cf-access.ts'); + const renew = () => ensurePlatformAccessToken('https://api.example.com', true); + if (output === undefined) { + expect(renew).toThrow('Re-run this command in an interactive terminal to renew it.'); + } else { + renew(); + } + }); if (output === undefined) { expect(spawnSyncMock).not.toHaveBeenCalled(); } else { diff --git a/packages/void/test/unit/db-commands.test.ts b/packages/void/test/unit/db-commands.test.ts index 20d276417..ec7bb5195 100644 --- a/packages/void/test/unit/db-commands.test.ts +++ b/packages/void/test/unit/db-commands.test.ts @@ -831,7 +831,6 @@ describe('void db execute', () => { }); describe('SQLite --json', () => { - // The command puts a write of its own in stdout's place, so the spy is kept here. let stdoutWrite: MockInstance; beforeEach(() => { stdoutWrite = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); @@ -888,35 +887,6 @@ describe('void db execute', () => { expect(outro).not.toHaveBeenCalled(); }); - it('sends what void.config.ts writes to stdout to stderr, every time it loads and after', async () => { - const root = await createLocalSqliteProject(); - rmSync(join(root, 'void.json')); - writeFileSync( - join(root, 'void.config.ts'), - "process.stdout.write('config loaded\\n');\nexport default {};\n", - ); - const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true); - - await runDbCommand(root, { action: 'execute', command: 'SELECT 1 AS one', json: true }); - - expect(jsonOutput()).toEqual([ - { results: [{ one: 1 }], success: true, meta: expect.any(Object) }, - ]); - const loads = stderr.mock.calls.filter(([text]) => text === 'config loaded\n'); - expect(loads.length).toBeGreaterThan(1); - - // A failing statement leaves stdout empty, config output included. - stdoutWrite.mockClear(); - await expect( - runDbCommand(root, { action: 'execute', command: 'SELECT * FROM missing', json: true }), - ).rejects.toThrow('no such table: missing'); - expect(stdoutWrite).not.toHaveBeenCalled(); - // What the config started may write once the results are out, and that goes to stderr too. - process.stdout.write('later\n'); - expect(stderr).toHaveBeenLastCalledWith('later\n'); - expect(stdoutWrite).not.toHaveBeenCalled(); - }); - it('keeps a column named __proto__', async () => { const root = await createLocalSqliteProject(); diff --git a/packages/void/test/unit/db-execute-json-stdout.test.ts b/packages/void/test/unit/db-execute-json-stdout.test.ts index fd0c9030d..b80340397 100644 --- a/packages/void/test/unit/db-execute-json-stdout.test.ts +++ b/packages/void/test/unit/db-execute-json-stdout.test.ts @@ -1,8 +1,8 @@ -import { execFile } from 'node:child_process'; +import { execFile, execFileSync, spawnSync } from 'node:child_process'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { pathToFileURL } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { afterEach, expect, it } from 'vite-plus/test'; const roots: Array = []; @@ -15,25 +15,35 @@ afterEach(() => { const source = (path: string) => pathToFileURL(join(import.meta.dirname, '..', '..', 'src', path)).href; -// Child processes write to the process's own stdout, which only a real process can observe. -it('keeps the stdout of processes that void.config.ts starts off `void db execute --json` stdout', async () => { +const cli = fileURLToPath(new URL('../../dist/cli/cli.mjs', import.meta.url)); + +it('keeps config and subprocess output off `void db execute --json` stdout', async () => { const root = mkdtempSync(join(tmpdir(), 'void-execute-json-stdout-')); roots.push(root); + const preload = join(root, 'preload.cjs'); + writeFileSync(preload, 'globalThis.voidDbPreloaded = true;\n'); + const args = ['--require', preload, cli, 'db', 'execute', '--json']; writeFileSync(join(root, 'fork.mjs'), "console.log('fork');\n"); const harness = join(root, 'harness.mjs'); writeFileSync( harness, `import { mkdirSync, writeFileSync } from 'node:fs'; import { dirname } from 'node:path'; -const { getLocalD1Target, runDbCommand } = await import(${JSON.stringify(source('cli/db.ts'))}); +const { getLocalD1Target } = await import(${JSON.stringify(source('cli/db.ts'))}); const { openSqliteDatabase } = await import(${JSON.stringify(source('migrations/runner.ts'))}); // The database is created before the config exists, so the setup prints nothing. const { databasePath } = getLocalD1Target(process.cwd()); mkdirSync(dirname(databasePath), { recursive: true }); (await openSqliteDatabase(databasePath)).close(); writeFileSync('void.config.ts', ${JSON.stringify(`import { execFileSync, fork, spawn, spawnSync } from 'node:child_process'; +import { writeSync } from 'node:fs'; +if (!(globalThis as { voidDbPreloaded?: boolean }).voidDbPreloaded) { + throw new Error('Node preload missing'); +} const print = (text: string) => ['-e', \`console.log(\${JSON.stringify(text)})\`]; console.log('config'); +writeSync(1, 'config fd\\n'); +setTimeout(() => writeSync(1, 'later fd\\n'), 10); execFileSync(process.execPath, print('execFileSync'), { stdio: 'inherit' }); spawnSync(process.execPath, print('spawnSync'), { stdio: [0, process.stdout, 2] }); spawn(process.execPath, print('spawn'), { stdio: ['ignore', 'inherit', 'inherit'] }); @@ -56,15 +66,16 @@ if (execFileSync(process.execPath, print('captured'), { encoding: 'utf8' }) !== } export default {}; `)}); -await runDbCommand(process.cwd(), { action: 'execute', command: 'SELECT 1 AS one', json: true }); `, ); + execFileSync(process.execPath, [harness], { cwd: root }); + const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>( (resolve, reject) => { execFile( process.execPath, - [harness], + [...args, 'SELECT 1 AS one'], { cwd: root, encoding: 'utf8', timeout: 30_000 }, (error, stdout, stderr) => error ? reject(new Error(`${error.message}\n${stderr}`)) : resolve({ stdout, stderr }), @@ -79,6 +90,8 @@ await runDbCommand(process.cwd(), { action: 'execute', command: 'SELECT 1 AS one expect(new Set(stderr.split('\n'))).toEqual( new Set([ 'config', + 'config fd', + 'later fd', 'execFileSync', 'spawnSync', 'spawn', @@ -89,4 +102,13 @@ await runDbCommand(process.cwd(), { action: 'execute', command: 'SELECT 1 AS one '', ]), ); + const failure = spawnSync(process.execPath, [...args, 'SELECT * FROM missing'], { + cwd: root, + encoding: 'utf8', + timeout: 30_000, + }); + expect(failure.status).toBe(1); + expect(failure.stdout).toBe(''); + expect(failure.stderr).toContain('no such table: missing'); + expect(failure.stderr).toContain('config fd'); }); diff --git a/packages/void/test/unit/db-execute-remote.test.ts b/packages/void/test/unit/db-execute-remote.test.ts index aa03776f8..c8efeffa1 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -151,7 +151,6 @@ function jsonResponse(body: unknown, status = 200): Response { }); } -// The command puts a write of its own in stdout's place, so the spy is kept here. let stdoutWrite: MockInstance; /** The results `void db execute --json` wrote to stdout, in one write and nothing else. */ diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index a1773edb5..cf90d1b51 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -140,6 +140,7 @@ export default defineConfig({ 'src/pages/serialize.ts', 'src/pages/islands-plugin.ts', 'src/cli/cli.ts', + 'src/cli/db-execute-process.ts', // Stable entry that deploy spawns as an isolated child. 'src/cli/env-schema-probe.ts', // Private typed Cloudflare transport, spawned by deployment orchestrators.