Sql Coder Cli
Latest: v0.1.0
- Added guidance for installing, configuring, and validating the SQL Coder CLI and database semantic file.
- Defined a read-only workflow for generating, reviewing, debugging, and retrieving versioned SQL, including plan-review and clarification steps.
- Added requirements for reporting results, definitions, assumptions, SQL version, and session ID.
- Documented when the skill should and should not be used.
SQL Coder CLI
Turn a user's natural-language data question into executable, auditable SQL, then report both the result and the definitions behind it.
Three hard rules; violating any of them counts as failure:
- CLI only: do not import the SDK, query the database directly, or hand-write SQL as the deliverable. SQL must be produced by this tool and carry a version.
- Read-only: only SELECT and WITH are permitted; never attempt DDL or DML.
- Never invent definitions: when metric definitions, time windows or column ownership are ambiguous, ask the user or raise a clarification instead of assuming.
Run all commands from the repository root. Confirm installation per section 0, then load variables per 1.1. Placeholders used below:
| Placeholder | Meaning | Source |
|---|---|---|
$CODER_PY | Python interpreter | coder.env |
$CODER_CONFIG | Runtime configuration file | coder.env, default coder.yaml |
$CODER_SEMANTIC | Semantic file of the current database | coder.env, default semantic.yaml |
$CODER_SOURCE | Database identifier (source_id) | coder.env |
<session_id> / <run_id> / <window> | Session, run and window identifiers | Output of the preceding command |
When to use, when not to
- Use when the database is configured and its semantic file is available, and the user wants executable, auditable SQL; an explanation, repair or review of existing SQL; query or intermediate results; version history; or business definitions.
- Do not use when no local CLI or runtime configuration exists, when the task requires writing to the database, or when the question is conceptual and needs no real data.
0. Installation and checks
Confirm the CLI is usable before any query; if it is not, install it first.
Detection (any one of these succeeding means it is installed):
coder --version # when the console script is on PATH
python -m sql_coder --version # with an activated virtualenv or system Python
- A working install prints something like
sql-coder-cli 0.2.0. - If
coder: command not foundbut the current directory is the repository, the virtualenv is probably not active. On Windows use.venv/Scripts/python -m sql_coder --version; on macOS/Linux use.venv/bin/python -m sql_coder --version. Section 1.1 records that interpreter as$CODER_PY. - If both fail, or the current directory has no
pyproject.toml, install as follows.
Installation (repository: https://github.com/AskSqlAI/asksql_coding_assistant):
git clone https://github.com/AskSqlAI/asksql_coding_assistant.git
cd asksql_coding_assistant
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e ".[mysql]"
- Python 3.11 or newer is required. The
[mysql]extra is mandatory; without it, database access fails withModuleNotFoundError: No module named 'pymysql'. - With uv installed,
uv venvfollowed byuv pip install -e ".[mysql]"is equivalent. - Do not install into a global environment. Keep the package in the project virtualenv and use
$CODER_PYfor every command. - After installation, return to this skill: create
coder.envat the repository root (1.1), then generate the semantic file (1.2).
Common installation failures:
| Symptom | Cause | Remedy |
|---|---|---|
git: command not found | Git is not installed | Install Git, or download and unpack the repository archive |
| Clone times out / HTTP 403 | GitHub is unreachable | Configure a proxy or use a mirror |
No module named 'pymysql' | The [mysql] extra was omitted | Reinstall inside the venv: pip install -e ".[mysql]" |
coder still not found | The venv is inactive, or its script directory is not on PATH | Use python -m sql_coder from the venv instead of the console script |
Fast path
Follow these steps by default; consult the referenced section when a branch appears.
- Confirm installation per section 0 (install first if missing). Then run
set -a; . ./coder.env; set +aand"$CODER_PY" -m sql_coder --version. - Confirm
$CODER_SEMANTICexists andsemantic_model.name == $CODER_SOURCE; otherwise rescan per 1.2. - Start a new window for a new question:
run --window <new-window> --semantic "$CODER_SEMANTIC" "<question>"(2.3). - On
pending, dispatch oncheckpoint.hook_typeto plan review (2.4) or clarification (2.5). Do not skip either. - On
completed, fetch the SQL withhistory(2.3) and rundebug --mainat least once (section 3). - Reply with the SQL, a result excerpt, the definitions and assumptions,
sql_versionandsession_id(2.7).
1. Preparation
1.1 Load environment variables
Place a coder.env in each working directory (plain shell variables; the CLI does not read it):
cat > coder.env <<'EOF'
export CODER_PY="$PWD/.venv/Scripts/python.exe"
export CODER_CONFIG="$PWD/coder.yaml"
export CODER_SEMANTIC="$PWD/semantic.yaml"
export CODER_SOURCE="sales"
EOF
set -a; . ./coder.env; set +a
"$CODER_PY" -m sql_coder --version
- On Windows the virtualenv interpreter is
.venv/Scripts/python.exe; on macOS/Linux it is.venv/bin/python. - Without a
.venv, use the systempython(the package must already be installed withpip install -e .). When the console script is available,"$CODER_PY" -m sql_codermay be shortened tocoder. - Point
CODER_CONFIGat an existing file; do not create a second configuration. It is equivalent to passing--configon every command. - Path resolution: relative paths inside the configuration (for example
runtime.workspace) resolve against the configuration file's directory;--output,--semanticand--inputresolve against the current directory. - If
--versionprints nothing, the interpreter or virtualenv is wrong. Fix the environment before continuing.
1.2 Generate the semantic file (scan)
The semantic file is the only schema evidence the model receives; one file per database:
"$CODER_PY" -m sql_coder scan \
--config "$CODER_CONFIG" --database "$CODER_SOURCE" \
--output "$CODER_SEMANTIC" \
--sample-rows 50 --overwrite
Expected output: {"status":"completed","output":"...","tables":N}.
tables: 0or an error means the host, credentials or database name is wrong. Fix the configuration first.- With multiple databases, scan once per
source_id, keep the file name equal to thesource_id, and pointCODER_SEMANTICat the matching file. - A full scan of a large database can take minutes. To check connectivity only, restrict it with
--table <name>(repeatable). - Reuse an existing file only when it exists,
semantic_model.name == source_id, and the schema has not changed since the scan. Rescan with--overwriteif the schema changed or is uncertain. --sample-rows 50samples real values (enums, date formats);--sample-rows 0disables sampling.- Check:
semantic_model.namemust equalsource_id(not the database name).scanwrites this correctly; do not edit it by hand.
1.3 Model service (the llm section)
- Set
providerto an id:deepseek,openai,qwen,kimi,glm,doubao,minimax,hunyuan,xiaomi, orgenericfor a self-hosted gateway. The preset determinesbase_url; onlygenericrequires an explicit one. modelandapi_keyare required. Settimeout_secondsto 300 for reasoning models; otherwise long SQL requests time out.- Changes to
llmaffect subsequent requests only; committed SQL versions are unchanged.
1.4 Workspaces and windows
- Sessions, SQL versions and debugging evidence live under
runtime.workspace(defaultcontent/), never in the business database. - A
--windowis one continuous conversation. It binds the database (via the semantic file), mode and language at creation and cannot switch afterwards. - Use a new window name for each new question (for example
q-064-ordinary); continue in the same window for follow-ups. Omitting--windowproduces a default name (Untitled); multiple unnamed windows are indistinguishable, so scripts must always name them. - Local-state commands (
status,history,restore,export,memory show) accept--workspace <dir>alone and need no model. - Never run two processes against the same workspace concurrently: they contend for the
state/runtime.sqlitewrite lock and reportdatabase is locked. For parallelism use separate workspaces such as./content/ws-aand./content/ws-b. If a lock occurs, check whether the previous process is still running; do not deletestate/.
2. Querying
2.1 Probe before writing SQL
Confirm the time window, enum encodings and grain with a read-only query first:
mkdir -p .scratch
cat > .scratch/probe.sql <<'SQL'
SELECT MIN(order_date) AS min_date, MAX(order_date) AS max_date, COUNT(*) AS rows_total
FROM sales.orders
SQL
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --sql-file .scratch/probe.sql \
--semantic "$CODER_SEMANTIC" --main --row-limit 5
- Probes are single-table SELECTs (MIN/MAX, COUNT,
GROUP BYfor distribution); they are not deliverables. - Write temporary files under the current directory (for example
.scratch/), not/tmp: on Windows, Git Bash and native Python resolve that path differently, which ends inFileNotFoundError. - Confirm the actual data range (a request for "all of 2020" may only cover through April), status encodings, primary key and grain, and null ratios.
- Do not infer encodings from ordering: numeric status codes usually map to a lookup table (for example
order_statustoorder_status_map). Join the lookup table before writing the main query; a wrong encoding yields plausible but incorrect results. - When a date format contains
%(for exampleDATE_FORMAT(x,'%Y-%m')), write the file with a non-interpolating heredoc. If the shell or Python consumes the%, MySQL silently returns the literal format string. Run--previewto inspect the actual SQL. - Carry only ranges and encodings into the plan, never statistics that change between snapshots (row counts, amounts, customer counts). If rerunning at another time changes the value, it is a snapshot and does not belong in the plan.
2.2 chat: interactive terminal session
"$CODER_PY" -m sql_coder chat --config "$CODER_CONFIG" --window sales-a \
--semantic "$CODER_SEMANTIC" \
--mode plan --language chinese
- The first turn must pass
--semanticto create the window; passing it again in the same window is ignored with a notice. - Type the question at
coder>and press Enter;:quitexits and printssession_idandwindow_id. - With
--mode plan, the plan is printed for review:1approves,2accepts revision instructions (Enter alone approves). - Clarifications list each question and its options: enter an option number, press Enter for the recommended option, or type free text.
--language chinese|englishcontrols the language of replies, clarification cards and plan explanations. Follow the language the user writes in, not the language of the question text or the data.chatrequires a TTY. In a pipeline or CI job it fails withchat requires a TTY; use run/resume; use 2.3 instead.
2.3 run: single-turn query (the agent path)
"$CODER_PY" -m sql_coder run \
--config "$CODER_CONFIG" --window q-064-ordinary \
--semantic "$CODER_SEMANTIC" \
--mode ordinary --language chinese \
"the user's question verbatim"
-
For stored procedures add
--coding-profile sp(defaultgeneral). -
For automation,
--request -reads a JSON body from stdin (instruction,window_name,mode,language,coding_profile,semantic_file) and avoids shell quoting problems. Inside that body,semantic_fileandsql_fileresolve againstruntime.workspace, not the current directory. -
For process events add
--format jsonl: it emitswindow.created,message.delta,tool.*andrun.finishedline by line, ending with{"type":"result","result":...}. -
Continue in the same window without
--semantic:bash "$CODER_PY" -m sql_coder run --config "$CODER_CONFIG" --window q-064-ordinary "narrow the range to 2021" -
A missing window reports
Window 'x' does not exist; add --semantic to create it: either the name is wrong or--semanticwas omitted when creating a new window.
Response fields (JSON on stdout):
| Field | Meaning |
|---|---|
status | completed, pending, partial or failed |
session_id / window_id / run_id / operation_id | Identifiers for history, debug, status and resume |
sql_version | Delivered version for this run; 0 means no SQL |
plan_version | Plan version (plan mode) |
checkpoint | Credential for human decisions: hook_type, hook_id, plan_version, questions, and so on |
error_code | Reason for partial or failed, for example NO_SQL_COMMITTED |
work_records | Work-record ids committed by this run |
When status == "pending", dispatch on checkpoint.hook_type:
hook_type | Action |
|---|---|
coder_plan_review | Review the plan per 2.4 |
coder_clarification | Collect answers from the user per 2.5 |
| Anything else or missing | Read the latest pending with status --session <session_id>; do not guess |
The SQL body is not in the response. Fetch it with history:
"$CODER_PY" -m sql_coder history --config "$CODER_CONFIG" \
--session <session_id> --kind sql --version <sql_version>
The returned content is the SQL; id is the work-record id used by export --record.
Exit code → action
| Code | Meaning | Action |
|---|---|---|
0 | Success | Fetch SQL, debug it, then report |
1 | Run failed | Read error_type and error from the final JSON line |
2 | Invalid request | Fix the arguments; do not retry the same request |
3 | Waiting for a human decision | Follow checkpoint to 2.4 or 2.5 |
4 | Model or database error | Read error_code and troubleshoot per 3.5 |
5 | Partial completion or I/O error | Inspect partial and the artifact paths |
130 | Cancelled | Rerun if the result is still required |
On failure, stderr carries a traceback while stdout still ends with one JSON line. Decide from that JSON and the exit code; do not infer the cause from the traceback.
2.4 Plan review (--mode plan)
The first turn returns:
{"status":"pending",
"checkpoint":{"hook_type":"coder_plan_review","hook_id":"...","plan_version":1},
"sql_version":0}
-
Read the plan first; never approve unread.
bash "$CODER_PY" -m sql_coder history --config "$CODER_CONFIG" \ --session <session_id> --kind plan --version <plan_version>contentis the plan text;graph.nodesholds nodes (id,title,question,inputs,outputs,depends_on). -
Approve or request changes with
resume, passing the body on stdin:bash "$CODER_PY" -m sql_coder resume --config "$CODER_CONFIG" --request - <<'JSON' {"submission_id":"sub-20261127-01","session_id":"session_xxx", "checkpoint_id":"hook_xxx","action":"approve_plan","plan_version":1} JSONTo request changes (produces a new plan and another review):
json {"submission_id":"sub-20261127-02","session_id":"session_xxx", "checkpoint_id":"hook_xxx","action":"revise_plan","instruction":"Split by customer instead of aggregating to month first."} -
Read the response:
completedwithsql_version: Nmeans SQL has been produced. If it is stillpendingwithhook_typecoder_plan_review, the plan was revised; the response already carries a newcheckpoint(hook_id,plan_version), so approve again. Two or three consecutive reviews are normal.
Do not approve when:
- the plan contains placeholders such as "to be confirmed", "TBD" or "depends on";
- the time window, filters or aggregation grain contradict the probe results (for example, "full year" when data ends in April);
- several definitions are merged into one sentence ("average balance" without a denominator);
- nodes lack
inputsoroutputs, or the grain does not match the question (a multi-step task reduced to a single node).
Three pitfalls: plan_version must match the current checkpoint (otherwise Plan version changed); submission_id must be new each time (reuse returns a cached result); checkpoint_id is single-use (use status --session <id> to recover pending).
2.5 Clarification (either mode)
checkpoint.hook_type == "coder_clarification"; each entry in checkpoint.questions[] looks like:
{"id":"balance_definition","title":"How should the monthly balance be computed?","description":"...",
"options":[{"id":"net","label":"Net deposits minus withdrawals","recommended":true}],
"recommended_option_id":"net","allow_manual":true,"required":true}
Present the questions and options to the user first, then submit the answers:
"$CODER_PY" -m sql_coder resume --config "$CODER_CONFIG" --request - <<'JSON'
{"submission_id":"sub-20261127-03","session_id":"session_xxx","checkpoint_id":"hook_xxx",
"action":"answer",
"answers":[{"question_id":"balance_definition","answer_type":"choice","option_id":"net"}]}
JSON
- Use
recommended_option_idonly when the user explicitly accepts the recommendation; never decide a definition on the user's behalf. - Free-form answers use
{"question_id":"...","answer_type":"manual","text":"the user's own words"}. - When a round has several questions, submit all
answersat once. - If the user declines to answer, send
{"action":"cancel_pending"}; the model continues with known information and records the gap.
2.6 Failures, cancellation and reset
| Situation | Action |
|---|---|
partial with NO_SQL_COMMITTED | The model replied without committing SQL: narrow the question or add definitions, then ask again in the same window |
failed | Read error_code and details; do not blindly resend the same prompt |
| A long run appears stuck | status --run <run_id> --events, or --after-sequence N for incremental events |
| The run must stop | cancel --run <run_id> |
| The window's definitions are fundamentally wrong | regenerate --window <w> (irreversible; ask the user first). --blank clears without rerunning; --keep-memory keeps definitions written by this window |
2.7 Reporting to the user
Fetch the SQL, run it at least once with --main, then report: the SQL, the first rows, the definitions and assumptions, sql_version and session_id.
To hand over a file:
"$CODER_PY" -m sql_coder export --config "$CODER_CONFIG" \
--record <id from history> --output ./out.sql --overwrite
The absence of a clarification card is normal; it does not mean the request is unambiguous. Check before delivery:
- Does every key definition have exactly one reading? Typical conflicts: balance as monthly net versus cumulative; whether
purchase,withdrawalanddepositare positive or negative; whether "average" covers all customers or only those with transactions. - Ask about inactive months separately: filling gaps with zero (
monthly_change=0) and carrying the previous balance forward are different definitions, and the model often merges them into "fill zeros". Decide separately whether customers appear before their first transaction. - If the model chose a definition without stating it, ask a follow-up in the same window to make it explicit and consistent; if it still conflicts, list it as unresolved rather than presenting it as a conclusion.
- Definitions must stay consistent across turns in one window. If a later turn changes sign handling, say so and ask which turn governs.
- Empty results, unexpected row counts and truncation must be stated explicitly; never hide them behind "generated".
- When a key column is all zeros, all equal, or contradicts the filter, treat it as wrong first. Present the conflict and the plausible definitions to the user instead of silently switching definitions.
- State when the grain inflates or narrows totals (attribution by session, one row per line item, deduplicated cart events) and describe the grain in one sentence.
- Local aggregation and reconciliation over
debugresults are allowed, but distinguish values returned by the query from values recomputed locally; every conclusion must be reproducible fromresults.
3. Debugging
Debugging is read-only; evidence is archived under records/debug/<evidence_id>.json.
3.1 Inspect structure, then choose a target
# Latest SQL in a session
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --session <session_id> --list-segments
# Standalone SQL file (--semantic is required to identify the database)
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" \
--sql-file ./draft.sql --semantic "$CODER_SEMANTIC" --list-segments
The response contains structure_type (with, union or plain), cte_segments[] (name, deps, span, sql), union_segments[] (index, span, sql) and main-query information. Use these to select a CTE, branch or line range.
3.2 Generate without executing
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --session <id> --main --preview
Returns targets[].sql without connecting to the database; use it to confirm the exact statement after parameter binding and CTE expansion.
3.3 Execute a target (exactly one of --main, --cte, --branch, --range)
# Entire main query (mandatory before delivery)
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --session <id> --main --row-limit 20
# One CTE (repeatable; --results all returns every target, otherwise the last)
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --session <id> \
--cte per_month --cte ranked --results all --row-limit 5
# The Nth UNION branch (1-based)
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --session <id> --branch 2
# A line and column range
"$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --session <id> --range "3:1-12:40"
-
Resource limits:
--row-limit N,--timeout-seconds N(default from configuration). -
Parameterized SQL uses
--params(pyformat, for example%(year)s):bash "$CODER_PY" -m sql_coder debug --config "$CODER_CONFIG" --sql-file ./draft.sql \ --semantic "$CODER_SEMANTIC" --main --params ./params.json -
--sql-version <N>selects a historical version of the session (requires--session).
3.4 Read the results
Each entry in results[] carries target, columns, rows, returned, truncated and elapsed_ms; the envelope also has id (evidence id) and status.
- Verify layer by layer: run each CTE or branch separately, check base row counts and key columns first, then cumulative or windowed values.
- Multiple targets:
--results allreturns one entry per target;--mainreturns a singlemainentry. - Truncation:
truncated: trueonly means--row-limitcut the output; it does not mean the query failed. Raise the limit when the full set is required. - Empty results: inspect the WHERE clause with
--preview, then use--cteto distinguish an empty source from an over-restrictive filter. - Version discipline: one window accumulates v1 with a wrong definition, v2 for diagnosis, v3 timing out, v4 usable. Deliver the latest version that passed
--mainand state its version number. - History:
history --session <id> --kind sqllists versions;restore --session <id> --kind sql --version Nrestores an old version as a new one without rewriting history. - Business definitions:
memory show --database "$CODER_SOURCE", with--queryfor keywords,--type definitionfor definitions only and--historyfor changes.
3.5 Reading failures
On execution failure stdout still carries JSON:
{"status":"failed","error_type":"DatabaseError",
"error":"(1054, \"Unknown column 'nope' in 'field list'\")",
"details":{"sql":"SELECT nope ...","evidence_id":"debug_xxx","partial":[]}}
- Exit code
4means a model or database error;details.sqlis the statement actually issued, so inspect that first. - A failed response has no
results; onlyerror,error_typeanddetails. A non-emptydetails.partialmeans earlier targets succeeded and the failure is confined to one CTE or branch. Unknown column/Unknown table: confirm real column names with--list-segmentsand the semantic file; do not guess.- Syntax errors: fix
draft.sqland rerun with--sql-file; do not let the model rewrite blindly for several rounds inside the session. - Timeouts /
Lost connection: the definition may be correct but the query shape cannot hold (row-by-row correlated subqueries, missing pre-aggregation). Ask for pre-aggregated CTEs before the join, and probe with--timeout-seconds 30before a full run. - Anti-joins are prone to hanging:
NOT IN (subquery)andINsubqueries withLIMIToften time out or raise1235 (LIMIT & IN/ALL/ANY/SOME). Run the subquery alone first, then rewrite asLEFT JOIN ... IS NULLor materialize it as a CTE; do not retry the timing-out statement unchanged.
3.6 Pre-delivery checklist
- SQL contains only SELECT/WITH; no DDL or DML
- Time window, filters and aggregation grain match the user's question
-
--mainsucceeded at least once, with row count and column names understood - Empty or truncated results were reported explicitly rather than presented as conclusions
- The reply includes
sql_versionandsession_idfor traceability
4. Command reference
| Command | Purpose | Key options |
|---|---|---|
scan | Generate the semantic file | --database, --output, --table, --sample-rows, --overwrite |
run | Single-turn query | --window, --semantic, --mode, --coding-profile, --language, --request |
chat | Interactive session (TTY required) | Same as run |
resume | Submit plan review or clarification answers | --request - (JSON on stdin) |
status | Inspect run or session state and events | --run, --session, --events, --after-sequence |
cancel | Cancel a run | --run |
regenerate | Reset a window and rerun | --window, --blank, --keep-memory |
history | Fetch SQL or plan versions | --session, --kind, --version |
restore | Restore a historical version | --session, --kind, --version |
debug | Read-only segmented execution | --session/--sql-file, --main/--cte/--branch/--range, --row-limit |
export | Export SQL or artifacts | --record, --artifact, --output, --overwrite |
memory show | Query business definitions | --database, --query, --type, --history |
5. Prohibitions
- Do not ask unrelated new questions in one window; database, mode, language and context are bound at creation.
- Do not pass a
--semanticfile from another database to an existing window; it fails withSemantic file belongs to another database. - Do not reuse
submission_idorcheckpoint_id. - Do not invent definitions to keep the workflow moving; clarification exists for the user to decide.
- Do not bypass CLI validation with the SDK or a direct database connection; that is not the path the user will exercise.
- Do not treat a traceback as a conclusion, and do not ignore
partial.
