diff --git a/docs/reference/cli/database.md b/docs/reference/cli/database.md index 53535aced..6210d5677 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,42 @@ 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, 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" +``` + +```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. 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, `--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/cf-access.ts b/packages/void/src/cli/cf-access.ts index da44aea8d..4e61b2ecf 100644 --- a/packages/void/src/cli/cf-access.ts +++ b/packages/void/src/cli/cf-access.ts @@ -107,21 +107,21 @@ 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.`, ); } 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)) { 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}.`); - runCloudflared(['access', 'login', origin], { inherit: true, timeoutMs: 120_000 }); + runCloudflaredLogin(origin); token = runCloudflared(['access', 'token', `-app=${origin}`]); } if (!token || !usableToken(token)) { @@ -135,14 +135,40 @@ export function ensurePlatformAccessToken( writeKeyringPassword(ACCESS_KEYRING_SERVICE, account, token); } +/** + * 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) { + return 1; + } + return process.stderr.isTTY ? 2 : undefined; +} + +function canSignIn(): boolean { + return signInOutput() !== undefined; +} + +/** Sign in through the browser. `--quiet` keeps the JWT off the terminal. */ +function runCloudflaredLogin(origin: string): void { + 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' : ['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/cli-main.ts b/packages/void/src/cli/cli-main.ts index bd08dbc28..7595199b5 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( @@ -105,7 +110,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); } @@ -164,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/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..742c5a969 100644 --- a/packages/void/src/cli/db-args.ts +++ b/packages/void/src/cli/db-args.ts @@ -16,6 +16,8 @@ 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' }, @@ -85,7 +87,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 +146,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 +206,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 +248,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-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-execute-results.ts b/packages/void/src/cli/db-execute-results.ts new file mode 100644 index 000000000..7f7467a9a --- /dev/null +++ b/packages/void/src/cli/db-execute-results.ts @@ -0,0 +1,1698 @@ +import { tokenizeSql } from '@void/deploy-core'; +import type { CustomTypesConfig } from 'pg'; +import type { SqliteDatabase } from '../migrations/runner.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 + * objects, which `wrangler d1 execute --json` also prints, so a script can read either tool. + */ +export type StatementResult = { + results: Array>; + success: boolean; + meta: Record; +}; + +/** 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, jsonValue, 2); +} + +type StatementRange = { start: number; end: number }; + +/** + * 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. + */ +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)) { + // 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') { + advance(1, segment.start); + continue; + } + const text = sql.slice(segment.start, segment.end); + // 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\uFEFF]/u.test(token)) { + advance(keywords.get(token.toLowerCase()) ?? 1, segment.start + match.index); + } + } + } + if (hasStatement) { + ranges.push({ start, end: sql.length }); + } + return ranges; +} + +/** 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. Integers are read exactly, as BigInt. + */ +export function runSqliteStatements(db: SqliteDatabase, sql: string): Array { + const counters = db + .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() ?? { last_row_id: 0n, total: 0n }; + const results: Array = []; + for (const statementSql of splitSqliteStatements(sql)) { + const statement = db.prepare>(statementSql).safeIntegers(true); + const before = readCounters().total; + const started = performance.now(); + let rows: Array> = []; + if (statement.reader) { + // 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(); + } + const duration = performance.now() - started; + const after = readCounters(); + results.push({ + results: rows, + success: true, + meta: { + // The rows the statement wrote, its triggers' writes among them, as D1 counts them. + changes: after.total - before, + last_row_id: after.last_row_id, + duration, + }, + }); + } + return results; +} + +type PgResult = { + command?: string | null; + rowCount?: number | null; + 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; +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 ( + 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))], + [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') { + 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]; + +/** 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. + */ +export function pgStatementResults(result: PgResult | Array): Array { + 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 }, + })); +} + +/** A write's result header. A count or ID past 2^53 is a string 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; +} + +const UINT64_RANGE = 2n ** 64n; + +/** + * The insert ID of a result header. MySQL sends it as an unsigned 64-bit integer, which mysql2 + * reads as a signed one, so an ID of 2^63 or more, from a BIGINT UNSIGNED column, arrives + * negative. + */ +function mySqlInsertId(field: unknown): number | string { + const id = mySqlCount(field); + const negative = typeof id === 'number' ? id < 0 : id.startsWith('-'); + return negative ? (BigInt(id) + UINT64_RANGE).toString() : id; +} + +function mySqlHeaderMeta(value: unknown): MySqlHeaderMeta { + const header = (typeof value === 'object' && value !== null ? value : {}) as Record< + string, + unknown + >; + return { + affectedRows: mySqlCount(header.affectedRows), + insertId: mySqlInsertId(header.insertId), + }; +} + +function mySqlStatementResult(value: unknown): StatementResult { + return Array.isArray(value) + ? { results: value as Array>, success: true, meta: {} } + : { results: [], success: true, meta: mySqlHeaderMeta(value) }; +} + +/** + * 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, `brackets` is true in MariaDB's `MSSQL` mode, which reads `[name]` as a + * quoted name, and `mariaDb` tells MariaDB, which reads executable comments its own way. + */ +export type MySqlServerMode = { + version: number; + backslashEscapes: boolean; + ansiQuotes: boolean; + brackets: 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, 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 /[\\"[]|\/\*M?!/u.test(sql); +} + +/** 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 versionText = String(fields.version ?? ''); + const version = /^(\d+)\.(\d+)\.(\d+)/.exec(versionText); + const mariaDb = /mariadb/iu.test(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'), + brackets: mariaDb && modes.includes('MSSQL'), + mariaDb, + }; +} + +/** 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; +} + +/** + * The index after the comment whose text starts at `index`, or `undefined` when it does not + * close. 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 | undefined { + while (index < sql.length) { + const character = sql[index++]; + if (nesting > 0 && character === '/' && sql[index] === '*') { + const end = skipMySqlComment(sql, index + 1, nesting - 1); + if (end === undefined) { + return undefined; + } + index = end; + } else if (character === '*' && sql[index] === '/') { + return index + 1; + } + } + return undefined; +} + +// 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, + brackets: false, + mariaDb: false, +}; + +/** + * 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; + +/** + * 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 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]; + 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); + 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 === '#' || + // 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); + 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. + 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++; + } else { + MYSQL_WORD.lastIndex = index; + const token = MYSQL_WORD.exec(sql)?.[0] ?? character; + lexer.index += token.length; + return token.toLowerCase(); + } + } + return undefined; +} + +// 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', + 'schema', + 'sequence', + 'server', + 'spatial', + 'table', + 'tablespace', + 'temporary', + 'undo', + 'unique', + 'user', + '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`, but the dot in a number such as `1.` is its decimal point. + */ +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; + // 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, + 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; + decimalPoint = false; + handler = undefined; + continue; + } + const previous = words.at(-1); + 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; + 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, 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; + } + 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; + +/** + * 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([ + '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']); + +/** Whether a word is a quoted name. */ +function isMySqlQuotedName(word: string | undefined, mode: MySqlServerMode): word is string { + const quote = word?.[0]; + 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; + if (value.length !== 1 || !isMySqlString(word, mode)) { + 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)), + brackets: mode.mariaDb && modes.includes('MSSQL'), + }; +} + +/** 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 SET statement changes the session's quoting rules. `SET GLOBAL` leaves them alone, as + * does a SET of a user variable. + */ +function mySqlSetChange(words: Array, mode: MySqlServerMode): MySqlModeChange { + const assignments = splitMySqlWords(words.slice(1)); + let change: MySqlModeChange; + // 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; +} + +/** + * 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 }; +// 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 + * 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. + */ +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), + }; + } + 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, + prepares: { name: mySqlName(second, mode), statement: mySqlPreparedStatement(source, mode) }, + rejected: rejectsMySqlSource(source, mode), + }; + } + 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 }, + }; + } + 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; +} + +/** + * 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 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 { + const lexer = newMySqlLexer(); + let modes = [initialMode]; + const prepared: MySqlPrepared = new Map(); + const calls: Array = []; + // 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; + } + const [{ read: chosen }] = readings; + read = chosen; + if (readings.some((reading) => !sameMySqlStatement(reading.read, chosen))) { + return divergedMySqlStatements( + sql, + from, + readings.map((reading) => reading.mode), + { + calls, + prepared, + }, + ); + } + lexer.index = read.end; + lexer.inVersionComment = read.inVersionComment; + if (read.words.length === 0) { + trailingComment ||= read.comment; + cut = mySqlCut(cut, read); + continue; + } + 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); + } + 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; + } + 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); + } + } + 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) }; +} + +/** + * 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. `statements` is what + * `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) && + fields.some((entry) => entry === undefined || Array.isArray(entry)); + if (!severalResults) { + return [mySqlStatementResult(rows)]; + } + const entries = rows as Array; + const grouped: Array = []; + let index = 0; + let matched = true; + for (const isCall of statements.calls) { + 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++]) }); + } + 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 89f43d566..1ae386671 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -9,10 +9,12 @@ import { writeFileSync, } from 'node:fs'; import { createRequire } from 'node:module'; +import type { Writable } from 'node:stream'; import { pathToFileURL } from 'node:url'; 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 +47,20 @@ import { } from './cf-access.ts'; import { PlatformApiError, PlatformClient } from './client.ts'; import type { DbArgs } from './db-args.ts'; +import { + formatStatementResults, + MYSQL_SERVER_MODE_QUERY, + mySqlJsonTypeCast, + mySqlServerMode, + mySqlStatementResults, + mySqlStatements, + needsMySqlServerMode, + pgJsonTypes, + pgStatementResults, + runSqliteStatements, + splitSqliteStatements, +} from './db-execute-results.ts'; +import type { MySqlServerMode, MySqlStatements, StatementResult } from './db-execute-results.ts'; import { assertPgExportableSchema, exportPgConstraints, @@ -186,7 +202,19 @@ 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) { + const printResults: PrintResults = (results) => { + writeResults(`${formatStatementResults(results)}\n`); + }; + 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(); @@ -205,7 +233,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, undefined); } else if (args.action === 'migrate') { await runMigrate(root, dialect, args.remote); } else if (args.action === 'studio') { @@ -877,7 +905,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 +917,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 +925,34 @@ 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 with `printResults`; the table prints only a single + * statement's rows. + */ +async function executeExternalSql( dialect: Exclude, dbUrl: string, sql: string, + printResults: PrintResults | undefined, ): Promise { + const json = printResults !== undefined; 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 { - 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) { + printResults(pgStatementResults(result)); + } else if (!Array.isArray(result) && result.rows.length > 0) { printTable(result.rows); } } finally { @@ -912,10 +961,45 @@ async function executeExternalRemoteSql( return; } const { createConnection } = await import('mysql2/promise'); - const mySqlClient = await createConnection({ uri: dbUrl, multipleStatements: true }); + 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 + // 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, + multipleStatements: 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] = await mySqlClient.query(sql); - if (Array.isArray(rows) && rows.length > 0) { + const [rows, fields] = await mySqlClient.query(statements?.sql ?? sql); + if (json && statements) { + printResults(mySqlStatementResults(rows, fields, statements)); + } else if (Array.isArray(rows) && rows.length > 0) { printTable(rows as Array>); } } finally { @@ -923,6 +1007,45 @@ async function executeExternalRemoteSql( } } +// 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(); +} + +/** How `void db execute --json` prints its results. */ +type PrintResults = (results: Array) => void; + /** * 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 +1053,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 +1067,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 +1079,23 @@ 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'>; + +/** Run `void db execute`. `printResults` prints the results with --json, and is undefined without. */ async function runExecute( root: string, - command: string | undefined, - file: string | undefined, + { command, file, remote, yes }: ExecuteArgs, dialect: DatabaseDialect, - remote?: boolean, - yes?: boolean, + 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 = () => { + if (!json) { + printSuccess('SQL executed successfully.'); + } + }; const readSql = () => { if (file) { return readFileSync(resolve(root, file), 'utf8'); @@ -977,22 +1114,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) { + printResults(await executeCloudflareD1Statements(context, sql)); } else { const rows = await executeCloudflareD1Sql(context, sql); if (rows.length > 0) { @@ -1004,40 +1156,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, printResults); } - 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' && 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.', + ); + } + + 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, printResults); + finish(); return; } @@ -1097,43 +1257,29 @@ 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) { + printResults([{ 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, printResults); + finish(); return; } @@ -1141,7 +1287,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 +1295,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) { + printResults(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/src/migrations/runner.ts b/packages/void/src/migrations/runner.ts index 10dd2cf5b..0a416daa2 100644 --- a/packages/void/src/migrations/runner.ts +++ b/packages/void/src/migrations/runner.ts @@ -12,6 +12,12 @@ 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; + /** 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/src/runtime/db/migrations/mysql-sql.ts b/packages/void/src/runtime/db/migrations/mysql-sql.ts index d9d7c684f..dbbc166a9 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; @@ -126,13 +126,31 @@ function splitMySqlStatements(sql: string): Array { return statements; } -/** The index after the quoted string or name that opens at `open`. */ -function skipQuoted(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 { + 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]; // Backslash escapes apply in strings, not in backtick-quoted names. - if (character === '\\' && quote !== '`') { + if (character === '\\' && quote !== '`' && backslashEscapes) { index += 2; continue; } @@ -145,5 +163,5 @@ function skipQuoted(sql: string, open: number, quote: string): number { } index++; } - return sql.length; + return undefined; } diff --git a/packages/void/test/unit/cf-access.test.ts b/packages/void/test/unit/cf-access.test.ts index a0a94860b..ee66c4069 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,27 +271,82 @@ 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 { + // 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); - } 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', 'https://api.example.com'], + ['access', 'login', '--quiet', 'https://api.example.com'], ['access', 'token', '-app=https://api.example.com'], ]); + expect(spawnSyncMock.mock.calls[0]?.[2]).toMatchObject({ stdio: ['inherit', 2, 'inherit'] }); expect(cfAccessHeaders(process.env, 'https://api.example.com')).toEqual({ 'cf-access-token': fresh, }); expect(keyring.write).toHaveBeenCalledWith('dev.void.cli.access', expect.any(String), fresh); }); + 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>; + 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 }, 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 }, + output: undefined, + }, + { + terminals: { stdin: true, stdout: false, stderr: false }, + output: undefined, + }, + ]; + for (const { terminals, 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 }, + ); + vi.resetModules(); + 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 { + expect(spawnSyncMock.mock.calls[0]?.[2]).toMatchObject({ + stdio: ['inherit', output, 'inherit'], + }); + } + } + + // 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: false, 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/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..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', () => { @@ -63,6 +63,28 @@ 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('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.', + ); + }); + 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..ec7bb5195 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>(), @@ -34,13 +35,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 => []); @@ -827,6 +829,240 @@ describe('void db execute', () => { db.close(); } }); + + describe('SQLite --json', () => { + 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 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> { + 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 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(); + + 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('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(); + + 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("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(); + + 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 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 () => { + 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(stdoutWrite).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(stdoutWrite).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(stdoutWrite).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-json-stdout.test.ts b/packages/void/test/unit/db-execute-json-stdout.test.ts new file mode 100644 index 000000000..b80340397 --- /dev/null +++ b/packages/void/test/unit/db-execute-json-stdout.test.ts @@ -0,0 +1,114 @@ +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 { fileURLToPath, 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; + +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 } = 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'] }); +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'); +} +export default {}; +`)}); +`, + ); + + execFileSync(process.execPath, [harness], { cwd: root }); + + const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>( + (resolve, reject) => { + execFile( + process.execPath, + [...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 }), + ); + }, + ); + + 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', + 'config fd', + 'later fd', + 'execFileSync', + 'spawnSync', + 'spawn', + 'fork', + 'stderr to process.stdout', + 'stderr to fd 1', + 'spawn stderr to stdout', + '', + ]), + ); + 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 220147383..c8efeffa1 100644 --- a/packages/void/test/unit/db-execute-remote.test.ts +++ b/packages/void/test/unit/db-execute-remote.test.ts @@ -1,7 +1,10 @@ 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 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'); @@ -9,9 +12,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, })); @@ -71,14 +78,33 @@ 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; }, })); +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; @@ -101,11 +127,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 } }; } @@ -121,6 +151,15 @@ function jsonResponse(body: unknown, status = 200): Response { }); } +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; @@ -580,6 +619,131 @@ describe('void db execute --remote (D1)', () => { expect(mockImportD1).toHaveBeenCalledWith(mockD1Context, sql); }); + describe('--json', () => { + 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'); + 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(stdoutWrite).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('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); + + 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(stdoutWrite).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. @@ -607,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); @@ -697,4 +862,211 @@ 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(stdoutJson()).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("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()`; + mockMySqlCreateConnection.mockClear(); + + 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, + ]); + // 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(stdoutJson()).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('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, + typeCast: mySqlJsonTypeCast, + }), + ]); + expect(stdoutJson()).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' }]] + : [[], []], + ), + ); + // 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 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(stdoutWrite).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(stdoutJson()).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' }); + 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' }); + // 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, + }); + + expect(stdoutJson()).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..a518f67e1 --- /dev/null +++ b/packages/void/test/unit/db-execute-results.test.ts @@ -0,0 +1,1041 @@ +import { types } from 'pg'; +import { describe, expect, it } from 'vite-plus/test'; +import { + formatStatementResults, + mySqlJsonTypeCast, + 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([ + { + 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('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 } }, + ]); + 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 } }, + ]); + }); + + 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]]'); + // 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([]); + }); + + 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); + // 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 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;'), + ).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(groupResults([{ a: 1 }], [field], 'SELECT 1')).toEqual([ + { results: [{ a: 1 }], success: true, meta: {} }, + ]); + expect(groupResults([], [field], 'SELECT 1')).toEqual([ + { results: [], success: true, meta: {} }, + ]); + expect(groupResults(header, undefined, 'DELETE FROM a')).toEqual([ + { results: [], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + }); + + 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( + [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( + groupResults([[{ 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(groupResults([[{ a: 1 }], header], [[field], undefined], 'CALL p()')).toEqual([ + { results: [{ a: 1 }], success: true, meta: { affectedRows: 2, insertId: 5 } }, + ]); + expect( + groupResults( + [[{ 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(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(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(calls('SELECT 1--1; -- x;\nCALL p()')).toEqual([false, true]); + // MySQL runs the SQL in a `/*!` comment, and `[` quotes nothing. + expect(calls('/*!40101 SET @a = 1 */; SELECT [1; CALL p()')).toEqual([false, false, true]); + // A control character after `--` starts a comment too. + 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(calls('/*+ BKA(t) */ CALL p()')).toEqual([true]); + expect( + groupResults([[{ 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, + ansiQuotes: false, + brackets: false, + mariaDb: false, + }); + const noEscapes = mySqlServerMode([ + { sql_mode: 'STRICT_TRANS_TABLES,NO_BACKSLASH_ESCAPES', version: '8.4.3' }, + ]); + expect(noEscapes).toEqual({ + version: 80_403, + backslashEscapes: false, + ansiQuotes: false, + brackets: false, + mariaDb: false, + }); + // With NO_BACKSLASH_ESCAPES, a backslash before a quote is an ordinary character. + const backslash = String.raw`SELECT '\'; CALL p()`; + expect(calls(backslash, noEscapes)).toEqual([false, true]); + expect(calls(backslash, mysql84)).toEqual([false]); + expect( + groupResults( + [[{ 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(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(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(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(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); + 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', () => { + 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, + brackets: false, + mariaDb: 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(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(calls('/*!100100SELECT 0 */; CALL p()', mariaDb)).toEqual([false, true]); + expect( + groupResults( + [[{ 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(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', () => { + expect( + calls( + [ + '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]); + }); + + it('opens a BEGIN block only in a stored program', () => { + // BEGIN may name a column, and XA BEGIN starts a transaction. + 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, + ]); + expect( + 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; + 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, 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], + [[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 } }, + ]); + }); + + 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('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( + [ + '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'`, + "EXECUTE IMMEDIATE 'SET sql_mode = ''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).slice(1), statement).toEqual([false]); + } + }); + + 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'", + '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: [...before, true], + uncounted: false, + sql: `${statement}; CALL p()`, + }); + // 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 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 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\';\''; /*!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, + 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\';\''`, + ), + ).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\';\''; 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: {} }, + ]); + }); + + 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 } }, + ]); + }); +}); 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( 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.