Skip to content

CLI Output and Exit Codes

radix29 edited this page Oct 31, 2026 · 1 revision

← goSSMS Home · ← CLI

CLI — Output and exit codes

What every command writes, where it writes it, and how to read it from a script. One contract for all 66 commands: the same envelope, the same six formats, the same limits, the same exit codes.

Streams

  • Results go to stdout in the --output format — errors too, so the caller parses one stream. On an error, stderr also gets exactly one line, gossms: <CODE>: <message>, for a human scanning a terminal.
  • Output is UTF-8 without a BOM, \n line ends on every OS, independent of the locale.
  • gosmo/go-mssqldb library logging is discarded unless --verbose, so nothing else ever appears on stderr.
  • With -o csv/tsv the rows are stdout and everything else (header block, messages, warnings, errors) is the text summary on stderr — even on success. The exit code carries the status.

The envelope

Every command answers the same structure: a header (status, command, server, database, duration, rows affected, out file), then a record (data — for answers like version), result sets, or both, then messages, warnings and errors. status is ok, error, blocked or cancelled; the first error decides the exit code.

$ gossms version
STATUS: OK
COMMAND: version
DURATION_MS: 0

VERSION: v0.2.0
COMMIT: 72a0e3c
CLI_SCHEMA: 1.0

text (the default)

KEY: value header lines, then sections separated by a blank line. Section markers are fixed, so a caller can split the output:

  • SERVER and DATABASE appear only when set; ROWS_AFFECTED only when the server reported a count; OUT_FILE only with --out-file; RESULT_SETS: n only when there are sets.
  • A record prints as KEY: value lines; the key is the JSON key in UPPER_SNAKE (cliSchema → CLI_SCHEMA). A null value prints KEY:, as an empty one does.
  • A multi-line record value (a module's definition, a script's text) is its own section: === DEFINITION (n lines) === followed by exactly n lines, line breaks kept and never cut by --max-col-width. A reader takes the n lines after the marker without scanning them — the text itself may hold a line that looks like a marker.
  • A result set is === RESULT n (r rows, truncated: no) === (or r of t rows, truncated: yes); a command with several fixed sets names each (=== RESULT 2: indexes (…) ===). Then a header row, a -+- rule and the rows, aligned by display width. NULL prints --null-text.
  • Then === MESSAGES === and === WARNINGS === when non-empty, and each error as an ERROR_CODE: / MESSAGE: / HINT: block; a SQL Server error adds SQL_ERROR_NUMBER:, SEVERITY:, STATE:, LINE: and (inside a module) PROCEDURE:.
  • Every value is one line: line breaks and tabs become spaces, so no value can forge a marker.

A real classified script (this output is gossms query classify live):

$ gossms query classify --sql "SELECT 1; UPDATE t SET a=1;"
STATUS: OK
COMMAND: query classify
DURATION_MS: 0
RESULT_SETS: 1

DETECTED_CLASS: write
FLAGS:
STATEMENT_COUNT: 2

=== RESULT 1 (2 rows, truncated: no) ===
batch | repeat | line | class | leader | object | reason | flags
------+--------+------+-------+--------+--------+--------+------
1     | 1      | 1    | read  | SELECT | NULL   | NULL   |
1     | 1      | 1    | write | UPDATE | t      | NULL   |

json

The same envelope, indented, one trailing newline:

{
  "schemaVersion": "1.0",
  "status": "ok",
  "command": "version",
  "server": null,
  "database": null,
  "durationMs": 0,
  "rowsAffected": null,
  "outFile": null,
  "data": {
    "version": "v0.2.0",
    "commit": "72a0e3c",
    "cliSchema": "1.0"
  },
  "resultSets": [],
  "messages": [],
  "warnings": [],
  "errors": []
}
  • Keys always appear in this order, and every key is always present (null or []) — except data, which appears only for a record answer.
  • rowsAffected is the sum of the DML row counts the server reported, null when it reported none.
  • An error is {"code", "message", "hint"} — with a SQL Server error behind it also sqlErrorNumber, severity, state, line, procedure. A message is {"type", "text"}; a warning a string.
  • A result set is {"name", "columns": [{"name", "type", "nullable"}], "rows", "rowCount", "totalRowCount", "truncated", "truncatedBy", "rowsAffected"}. rowCount is the rows in this output, totalRowCount what the server returned; truncatedBy is max-rows or max-output-bytes, null when whole.
  • A cell is typed by its column's SQL type: int, bigint, real, float a number; bit true/false; NULL null; everything else — decimal, numeric and money included, which most JSON parsers would round as a float — the grid's text as a string. A column of type json (xevent capture's data under -o jsonl) holds a real JSON document.
  • schemaVersion changes only when the structure breaks compatibility, so a parser written today keeps working across releases.

jsonl

One JSON object per line, written as the rows arrive — the format for large results and streaming:

{"_resultSet":{"index":1,"name":null,"columns":[{"name":"id","key":"id","type":"int","nullable":false}]}}
{"id":1}
{"id":2}
{"_summary":{"schemaVersion":"1.0","status":"ok","…":"…","resultSets":[{"rowCount":2,"totalRowCount":2,"truncated":false,"truncatedBy":null}]}}
  • Each set starts with a _resultSet line mapping every column name to its key; each row is an object keyed by column, typed as in json. A duplicate (or nameless, or _-prefixed) column name gets _<n> appended.
  • The last line is _summary: the json envelope with each set's rows left out. It is always written, also on an error or a cancel.

csv and tsv

Rows only on stdout, written by the TUI's Results To File writer: RFC 4180, NULL an empty field, the empty string "" — the same bytes for the same rows as the TUI produces. TSV is the same with a tab, quoting a field that holds a tab, quote or line break. Cells are never clipped. Everything else goes to stderr as the text summary.

markdown

The text envelope with each set as a GitHub table: | and \ escaped, line breaks as <br>. --no-headers does not apply (a GitHub table needs its header row).

Output limits

Rows past a limit are dropped from the output, never from the run: the whole script runs whatever the output shows, and totalRowCount stays exact.

Limit Behaviour
--max-rows n (default 200) Keeps each set's first n rows on stdout, counts the rest, adds NOTE: Output truncated by --max-rows 200. Use --max-rows 0 or --out-file to get all rows. The kept rows are held in memory, so 0 on a large result holds every row — prefer --out-file or -o jsonl
--max-col-width n (default 256) Cuts a cell to n code points and marks the rest: …[+12,345 chars]. Text, markdown, json and jsonl only; csv, tsv and --out-file are lossless. A typed number or bit is never cut
--max-output-bytes n (default 1048576) Caps stdout by dropping whole trailing rows (the last set's first), so JSON is never cut inside a value. jsonl stops writing rows at the cap; its _summary line is exempt

--quiet leaves the text header block out (a JSON envelope is always whole); --no-headers the column headers (text, csv, tsv); --no-messages the PRINT and informational messages; --null-text picks the NULL spelling.

--out-file

--out-file <path> writes every row — no row, width or byte limit — to a file, in the format its extension names: .csv, .tsv, .jsonl (rows then the summary line), .json, .md, .txt (the whole envelope); anything else is a usage error.

  • stdout gets the summary in the -o format, its sets with no rows and outFile naming the path.
  • Checked before the command runs: unknown extension, a directory, or an existing file without --force is USAGE_ERROR — never a prompt.
  • The rows go to a temporary file beside the target, renamed over it only when the command succeeds. On an error or a cancel the destination is left as it was, and a warning says so.
  • A .json, .md or .txt file is rendered at the end, so its rows are held in memory; prefer .csv, .tsv or .jsonl for large results.
# a nightly extract, uncapped, atomic
gossms query run -p nightly --file extract.sql --out-file extract.csv --force
gossms data export -p nightly Sales.LargeView --out-file view.jsonl

--out-file is not for scripts: --plan-file, --script-file and --deadlock-file are, and --force is what replaces a file any of them writes.

Exit codes

Code Name Meaning Typical next step
0 OK Success — output may still be truncated Check truncated / totalRowCount
1 GENERAL_ERROR Unexpected or internal error (a recovered panic: stack on stderr under --verbose); also "the audit log could not be opened" Read the message; --verbose for the stack
2 USAGE_ERROR Invalid or unknown arguments Read HINT: (it may be a did-you-mean); gossms help <command>
3 CONNECTION_FAILED Server unreachable, TLS or network error Check --server/port/firewall; TLS flags
4 AUTH_FAILED Login failed or credentials missing gossms profile show <name>; --password-env/--password-stdin
5 SQL_ERROR The server returned an error (severity 11+) The error block carries number, line, procedure
6 TIMEOUT Command (--timeout) or connect (--connect-timeout) timeout Raise the timeout, or fix the query
7 BLOCKED Refused by the safety model or a missing --confirm The record names detectedClass/allowedClass/statements; see Safety
8 NOT_FOUND Profile, database or object does not exist The hint lists close matches (up to 5 names, or 3 settings)
9 PERMISSION_DENIED The login lacks the required permission The hint names the permission; gossms agent context
10 PARTIAL Some batches succeeded and some failed (--continue-on-error) Errors are listed first; the run is not atomic
11 UNSUPPORTED The server's version or edition does not support it Check server info's version/edition
130 CANCELLED Ctrl+C or SIGINT Ctrl+C cancels the running command's context and closes the session; the server rolls back an open transaction; a second Ctrl+C kills the process

All codes are defined from the first release so a caller's handling never depends on which commands exist yet. The table is output.ExitCodes, the one place a code's number is spelled, and gossms agent schema prints it as JSON.

Reading the answer in a script

  • Trust the exit code first, then status/errors[0].code. The hint is the designed next step — follow it rather than guessing a spelling.
  • Parse stdout only (except csv/tsv, where stderr holds the summary).
  • Check truncated and totalRowCount before concluding "there were 200 rows".
  • -o json for a stable envelope; -o jsonl to stream; -o csv when the next tool is a spreadsheet or another loader. decimal/money arrive as strings on purpose — parse them with a decimal type.
  • A usage error is answered in the format the command line asked for, so set -o pipefail + jq pipelines never see plain text where JSON was promised.
# CI gate: run a smoke script, fail the build unless the envelope says ok
gossms query run -p ci --file smoke.sql -o json > smoke.json
status=$(jq -r .status smoke.json)
[ "$status" = ok ] || jq '.errors[] | {code, message, hint}' smoke.json
[ "$(gossms query parse -p ci --file migration.sql >/dev/null 2>&1; echo $?)" = 0 ] || echo "migration.sql does not even parse"

Where to go next

Want Page
Formats' safety rules and the --allow ladder Safety and audit
Envelope-adjacent machine docs for agents AI agents
The commands by area Databases · Server · Objects and scripting · Query and plans · Data · Monitoring · Security

Clone this wiki locally