Skip to content

feat(cli): add --json to void db execute - #920

Merged
cpojer merged 11 commits into
voidzero-dev:mainfrom
karthickeyan-dev:feat/db-execute-json
Nov 26, 2026
Merged

cpojer merged 11 commits into
voidzero-dev:mainfrom
karthickeyan-dev:feat/db-execute-json

Conversation

@karthickeyan-dev

@karthickeyan-dev karthickeyan-dev commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #912.

void db execute only printed a text table. The table can't tell NULL from 'NULL' or 1 from '1', a value with a newline splits its row, and SQL with several statements printed nothing.

--json prints a JSON array to stdout with one entry per statement, in the shape of a D1 result (the same as wrangler d1 execute --json):

$ void db execute --json "select 1 as a; select 2 as b"
[
  { "results": [{ "a": 1 }], "success": true, "meta": { "changes": 0, "last_row_id": 0, "duration": 0.02 } },
  { "results": [{ "b": 2 }], "success": true, "meta": { "changes": 0, "last_row_id": 0, "duration": 0.01 } }
]

stdout holds only that array. Prompts, warnings, errors and any other output (for example a console.log in void.config.ts) go to stderr. A failure exits non-zero with stdout empty. Without --json, nothing changes.

Per database

Target How statements are split meta
Local D1 (SQLite) SQLite's own rules (sqlite3_complete()), so a CREATE TRIGGER … END; stays one statement changes (trigger writes included, as D1 counts them), last_row_id, duration
Direct Cloudflare D1 D1 returns one result per statement D1's metadata
Void platform D1 The proxy returns only the first result, so several statements are refused before sending D1's metadata
PostgreSQL node-postgres returns one result per statement command, rowCount
MySQL / MariaDB See below affectedRows, insertId

A direct D1 import (a --file over 100 KB) returns no rows, so --json is refused before the upload.

MySQL: one entry per CALL

A MySQL CALL returns each of its procedure's result sets and then a header. These are grouped into one entry, so the array still has one entry per statement. The same goes for an EXECUTE of a prepared CALL and for compound statements MariaDB runs outside a procedure (BEGIN NOT ATOMIC, IF, LOOP, ...).

To find the statements, the SQL is read the way the server reads it before it runs:

  • comments and quoted text, following sql_mode;
  • executable comments (/*!, MariaDB's /*M!) for the server's version;
  • stored program bodies;
  • SET sql_mode changes in the SQL itself.

When the SQL depends on the server's mode, --json first reads sql_mode and VERSION() on a separate connection. It only does this when the SQL contains a backslash, a double quote, a [ or an executable comment.

--json refuses, before running anything, when it can't tell which results belong to which statement:

  • an EXECUTE of a statement not prepared from a quoted string, such as PREPARE s FROM @sql;
  • a SET sql_mode = @saved after which the rest of the SQL could split differently, with a CALL among the statements.

If the results still don't line up with the statements, it prints one entry per result rather than guess.

Values

  • Binary values print as byte arrays, as D1 returns them.
  • Integers beyond ±(2^53 − 1) print as strings, so they don't round. This includes SQLite rows, last_row_id and MySQL insertId. mysql2 reads insertId as signed, so IDs of 2^63 or more are converted back to unsigned.
  • Infinity, -Infinity and NaN print as strings, not null.
  • PostgreSQL numeric[] elements print as strings, and numbers inside json/jsonb keep their digits.
  • MySQL dates print as the text MySQL returns.

Design choices

  • Destructive --remote --json in a terminal still asks first. The prompt is on stderr. wrangler's --json skips it.
  • Errors are plain text on stderr, not a JSON object on stdout.
  • Cloudflare Access sign-in writes to stderr and only needs a terminal on stdin and stderr, so --json | jq can still renew a rejected credential.
  • void db --json in a terminal no longer opens the subcommand menu, which drew on stdout. It prints a usage error instead.

Known limits

  • SQL that prepares a statement from a variable and runs it is refused with --json. It still runs without --json.
  • mysql2 refuses a MySQL column named __proto__. SQLite and PostgreSQL keep it.
  • A CALL's entry combines the rows of all its result sets.

Tests

  • Unit tests:
    • db-commands.test.ts: local SQLite end to end.
    • db-execute-remote.test.ts: D1, PostgreSQL and MySQL paths.
    • db-execute-results.test.ts: statement splitting and grouping.
    • cf-access.test.ts: Access sign-in.
    • Tests added for review fixes fail without their fix.
  • End to end: the built CLI against MySQL 8.4, MariaDB 11.4, MySQL 8.0 and PostgreSQL 18. This includes about 70,000 generated scripts whose grouping was compared with what the servers returned, with no mismatches.
  • vp check, vp run test and vpr test:all pass.

Docs

docs/reference/cli/database.md: new "JSON output" section.

🤖 Generated with Claude Code

karthickeyan-dev and others added 8 commits November 25, 2026 13:51
`void db execute --json` writes a JSON array with one D1-shaped
`{ results, success, meta }` entry per statement to stdout, matching
`wrangler d1 execute --json`. Prompts, warnings and errors go to stderr,
and the success line is left out.

- Local SQLite runs the SQL statement by statement. The shared SQL
  tokenizer cuts at top-level semicolons, and a piece SQLite reports as
  incomplete input (a trigger body) continues into the next one.
- Direct Cloudflare D1 keeps each statement's result instead of merging
  their rows.
- PostgreSQL and MySQL read each statement's result from the driver.
- A direct D1 import (a file over 100 KB) and several statements
  through the Void platform proxy are refused before anything runs,
  since neither can return every statement's rows.

Table output without `--json` is unchanged.

Fixes voidzero-dev#912

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Read SQLite integers as BigInt and MySQL BIGINTs with supportBigNumbers;
  integers past 2^53 print as strings of their digits.
- Print Infinity, -Infinity and NaN as strings instead of null.
- Serialize bytes at any depth, so bytea[] elements print as byte arrays.
- Split SQLite SQL the way sqlite3_complete() does, so a CREATE TRIGGER is
  one statement locally and through the platform proxy.
- Group a MySQL CALL's result sets and header into one entry.
- Leave out PostgreSQL's empty-query result.
- Do not open a subcommand menu when --json is passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Run `cloudflared access login` with `--quiet` and send its output to
  stderr, so renewing Access never puts the JWT or login text on stdout.
- Find MySQL `CALL` statements with MySQL's own lexical rules: `#`
  comments, `--` only before whitespace, backslash escapes in quotes,
  and `/*!` / `/*+` comments as SQL.
- Give the pg client lossless parsers in JSON mode: `numeric[]`
  elements stay strings, and numbers in json, jsonb and their arrays
  keep the digits the database sent.
- Skip only the whitespace and comments SQLite skips, so a trailing
  bare `/*` or nonbreaking space fails as SQLite reports it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- SQLite: a byte-order mark where a token starts is whitespace, so a file
  that begins with one keeps its `CREATE TRIGGER` whole.
- MySQL: grouping a `CALL`'s results follows the server's sql_mode and
  version, read only when the SQL holds a backslash or a `/*!` comment.
  With NO_BACKSLASH_ESCAPES a backslash is an ordinary character, and a
  version comment counts only on a server that runs it.
- MySQL: a control character after `--` starts a comment, and `/*+`
  hints outside a statement are ordinary comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…te --json` CALL results

- Read the server mode on a separate connection so the user's session state
  (FOUND_ROWS(), ROW_COUNT(), warnings) is untouched.
- Treat BEGIN as a block opener only in stored programs and MariaDB's
  BEGIN NOT ATOMIC, not as a column name or XA BEGIN.
- Follow MariaDB's executable comments: /*M!, six-digit versions, and
  skipping /*! comments for versions 50700 to 99999.
- Read double quotes as identifiers in ANSI_QUOTES mode.
- Allow one nested comment inside a skipped version comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…son` output exact

- Read later statements with the mode a `SET sql_mode` to a quoted list leaves, and refuse
  before running SQL whose CALL results could not be grouped after an unreadable change
- Read reserved words after a dot (`t.case`, `t.end`) as names
- Keep `ALTER EVENT ... DO BEGIN ... END` bodies in one statement
- Print MySQL dates and times as the text MySQL returns
- Leave --json out of the interactive `void db` menu, which draws on stdout
- Drop URL options that would change JSON output, such as `debug`, from both connections

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…id db execute --json`

MySQL and MariaDB:
- Leave out comments after the last statement, which the server answers
  with a result of their own, so a CALL's results stay grouped.
- Group the results of an EXECUTE of a prepared CALL, MariaDB's EXECUTE
  IMMEDIATE and SET STATEMENT ... FOR, and compound statements MariaDB
  runs outside a stored program. Refuse an EXECUTE of a statement the
  SQL does not prepare from a quoted string.
- Keep stored program bodies without BEGIN together (IF, CASE, LOOP,
  WHILE, REPEAT, FOR), in procedures, functions, triggers and events.
- After an unclear SET sql_mode, read the SQL in each quoting mode the
  server may be in, rather than refusing whenever a CALL follows.
- Read `@case` as a variable, `begin`, `end` and `do` as names where a
  stored program uses them so, a handler's statement as a statement,
  and the account in DEFINER = account as no object.
- Read `[name]` as a quoted name in MariaDB's MSSQL mode.

Local D1: report the rows a statement's triggers write in
`meta.changes`, as D1 does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d more MySQL SQL exactly

- Send anything else written to stdout, such as output from void.config.ts on each load, to
  stderr from the start of the command until the process exits.
- Read the dot after digits as a decimal point, so `1.` before END closes a CASE expression.
- Read the server's mode for SQL with double quotes, so ANSI_QUOTES names of prepared
  statements resolve, and set aside readings where a string names a prepared statement, which
  the server rejects.
- Report MySQL insert IDs of 2^63 and more as unsigned; mysql2 reads them as signed.
- Keep a SQLite column named __proto__ in the rows.
- Let Cloudflare Access sign in with a terminal on stdin and stderr, so piping stdout no longer
  prevents renewing a rejected credential.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@karthickeyan-dev
karthickeyan-dev marked this pull request as ready for review November 25, 2026 16:08
@cpojer

cpojer commented Nov 26, 2026

Copy link
Copy Markdown
Member

Thanks! There are two issues:

  • An existing interactive command with 2>log can no longer renew an expired Cloudflare Access session even without --json.
  • If void.config.ts starts a subprocess with stdio: 'inherit', the subprocess can write to stdout before the JSON array, for example when you use execFileSync it still exits with 0. Can we keep that output off stdout too?

@cpojer cpojer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See above.

… process output off `void db execute --json` stdout

The Cloudflare Access sign-in writes to stdout again when it is a terminal, so an
interactive command run with `2>log` can renew an expired session. It uses stderr
only while stdout is redirected or kept for `--json` results.

While `--json` keeps stdout for its results, child processes that would inherit
stdout (for example one void.config.ts starts with `execFileSync(..., { stdio:
'inherit' })`) get stderr instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@karthickeyan-dev

Copy link
Copy Markdown
Contributor Author

Thanks! Both are fixed in 176d2db.

  • Access renewal with 2>log: The sign-in writes cloudflared to stdout again when stdout is a terminal, as before this PR, so an interactive command with 2>log can renew an expired session. It uses stderr only when stdout is redirected or kept for --json results. If neither one is a terminal it can use, it fails with the existing "Re-run this command in an interactive terminal" error. cf-access.test.ts covers each terminal combination, with and without --json.
  • Subprocesses from void.config.ts: While --json keeps stdout for its results, child processes that would inherit stdout get stderr instead. That covers spawn, exec, execFile, fork, spawnSync, execFileSync and execSync, whether stdout is passed as 'inherit', 1 or process.stdout. Output a config captures through the default pipe is unchanged. This lives in src/cli/stdout-results.ts, which now also holds the stdout redirect that used to be in db.ts. It wraps the node:child_process exports and ChildProcess.prototype.spawn, then calls syncBuiltinESMExports() so ESM imports pick up the wrappers too. Node can't redirect fd 1 within a process. The other option I considered was re-running the CLI as a child process with stdout swapped, which costs startup time and adds signal and Windows fd handling. I'm happy to switch to that if you'd rather not wrap the builtin.

db-execute-json-stdout.test.ts runs void db execute --json in a real Node process. Its void.config.ts starts children each of those ways, and the test checks that stdout holds only the JSON array.

@cpojer

cpojer commented Nov 26, 2026

Copy link
Copy Markdown
Member

One more issue: --json can still exit successfully with invalid JSON. When void.config.ts captures a child’s stdout and sends its stderr to process.stdout, the diagnostic appears before the JSON array.

…rint PostgreSQL dates and MySQL JSON exactly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@karthickeyan-dev

Copy link
Copy Markdown
Contributor Author

Thanks! Fixed in fff7e0d.

Child stderr on stdout: While --json holds stdout for its results, any stream a child process is given that points at stdout now goes to stderr instead. That covers 1, process.stdout or any other stream on fd 1, whether the child uses it for stdout or stderr. Before, only an inherited stdout was redirected, so stdio: ['ignore', 'pipe', process.stdout] let the child's stderr reach stdout ahead of the JSON array. Output the config captures through a pipe is unchanged. db-execute-json-stdout.test.ts now also runs execFileSync with stdout captured and stderr sent to process.stdout. It checks that the captured output is still exact and that stdout holds only the JSON array. It also covers stderr sent to fd 1 from spawnSync, and to process.stdout from spawn.

I also fixed two related ways the output could differ from what the database sends:

  • PostgreSQL dates and timestamps: date, timestamp, timestamptz and their arrays now print as the text PostgreSQL sends. Before, node-postgres read them in the machine's time zone, so select current_date could print the previous day east of UTC, and microseconds were lost.
  • MySQL JSON numbers: JSON columns now keep their exact digits, as on PostgreSQL. mysql2's JSON.parse dropped the trailing zero of 1.10 and rounded long decimals, and turned integers past 2^53 into strings. This works on MySQL and MariaDB.

@cpojer
cpojer merged commit 8f6f1ca into voidzero-dev:main Nov 26, 2026
3 checks passed
@karthickeyan-dev
karthickeyan-dev deleted the feat/db-execute-json branch November 26, 2026 05:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

void db execute prints results only as a table

2 participants