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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions docs/reference/cli/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sql>
void db execute --file <path>
void db execute --remote <sql> [--yes]
void db execute --remote --file <path> [--yes]
void db execute <sql> [--json]
void db execute --file <path> [--json]
void db execute --remote <sql> [--yes] [--json]
void db execute --remote --file <path> [--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`:

Expand All @@ -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}

```
Expand Down
38 changes: 32 additions & 6 deletions packages/void/src/cli/cf-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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<string>,
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) {
Expand Down
22 changes: 17 additions & 5 deletions packages/void/src/cli/cli-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,12 @@ async function runSubcommandGroup<T>(
.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(
Expand Down Expand Up @@ -105,7 +110,8 @@ async function runSubcommandGroup<T>(
: 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);
}
Expand Down Expand Up @@ -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)),
Expand Down
36 changes: 23 additions & 13 deletions packages/void/src/cli/cloudflare-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<Array<Record<string, unknown>>> {
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<Array<StatementResult>> {
const execute = (source: { sql: string } | { file: string }) =>
run(context.operation, {
type: 'd1.execute',
Expand All @@ -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<Record<string, unknown>> = [];
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<string, unknown>).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<string, unknown>);
}
}
}
return rows;
const { results, success, meta } = item as Record<string, unknown>;
return {
results: Array.isArray(results)
? results.filter(
(row): row is Record<string, unknown> =>
typeof row === 'object' && row !== null && !Array.isArray(row),
)
: [],
success: success !== false,
meta: typeof meta === 'object' && meta !== null ? (meta as Record<string, unknown>) : {},
};
});
}

export async function readCloudflareD1Migrations(
Expand Down
23 changes: 20 additions & 3 deletions packages/void/src/cli/db-args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const dbSubcommands: Array<SubcommandDef> = [
name: 'execute',
arg: '<sql>',
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' },
Expand Down Expand Up @@ -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 }
| {
Expand Down Expand Up @@ -137,7 +146,7 @@ const ACTION_FLAGS: Record<DbArgs['action'], Array<string>> = {
status: [],
reset: ['yes'],
seed: ['file', 'yes'],
execute: ['file', 'remote', 'yes'],
execute: ['file', 'remote', 'yes', 'json'],
migrate: ['remote'],
studio: ['remote'],
'set-url': [],
Expand Down Expand Up @@ -197,6 +206,7 @@ export function parseDbArgs(args: Array<string>): DbArgs {
region: { type: 'string' },
'local-only': { type: 'boolean' },
yes: { type: 'boolean' },
json: { type: 'boolean' },
bookmark: { type: 'string' },
timestamp: { type: 'string' },
platform: { type: 'string' },
Expand Down Expand Up @@ -238,7 +248,14 @@ export function parseDbArgs(args: Array<string>): 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':
Expand Down
64 changes: 64 additions & 0 deletions packages/void/src/cli/db-execute-process.ts
Original file line number Diff line number Diff line change
@@ -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<string>,
): Promise<void> {
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<Buffer> = [];
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<number>((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;
}
}
Loading