360 Secure SkillHub
360 安全技能中心

Sql Coder Cli

驱动本地 SQL Coder CLI,把自然语言数据问题转换为只读、可审计的 MySQL SQL;支持计划评审、澄清问答、分段调试、结果查看和 SQL 导出,并强调定义确认与版本追踪。

分类:开发
asksqlai
asksqlai
热度 31.60
最近更新 2026-12-03 15:07:05

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add asksqlai/sql-coder-cli-skill
兼容性
通用兼容
联网要求
需要联网
数据出网
必须出网
Metadata
name
sql-coder-cli
description
This skill drives the local SQL Coder CLI (coder or python -m sql_coder) to turn natural-language questions over a configured MySQL database into read-only, auditable, validated SQL, and to handle plan review and clarification across turns. Use it when the user asks an analytical question, asks to write, revise or check SQL, wants query or intermediate results, needs SQL exported, or asks about version history or business definitions. If the CLI is not installed, install it from https://github.com/AskSqlAI/asksql_coding_assistant as described in section 0. Do not use it when the CLI cannot be installed and no configured environment exists, when the task requires database writes, or for conceptual SQL questions that need no real database.

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:

  1. 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.
  2. Read-only: only SELECT and WITH are permitted; never attempt DDL or DML.
  3. 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 found but 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 with ModuleNotFoundError: No module named 'pymysql'.
  • With uv installed, uv venv followed by uv pip install -e ".[mysql]" is equivalent.
  • Do not install into a global environment. Keep the package in the project virtualenv and use $CODER_PY for every command.
  • After installation, return to this skill: create coder.env at 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.

  1. Confirm installation per section 0 (install first if missing). Then run set -a; . ./coder.env; set +a and "$CODER_PY" -m sql_coder --version.
  2. Confirm $CODER_SEMANTIC exists and semantic_model.name == $CODER_SOURCE; otherwise rescan per 1.2.
  3. Start a new window for a new question: run --window <new-window> --semantic "$CODER_SEMANTIC" "<question>" (2.3).
  4. On pending, dispatch on checkpoint.hook_type to plan review (2.4) or clarification (2.5). Do not skip either.
  5. On completed, fetch the SQL with history (2.3) and run debug --main at least once (section 3).
  6. Reply with the SQL, a result excerpt, the definitions and assumptions, sql_version and session_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 system python (the package must already be installed with pip install -e .). When the console script is available, "$CODER_PY" -m sql_coder may be shortened to coder.
  • Point CODER_CONFIG at an existing file; do not create a second configuration. It is equivalent to passing --config on every command.
  • Path resolution: relative paths inside the configuration (for example runtime.workspace) resolve against the configuration file's directory; --output, --semantic and --input resolve against the current directory.
  • If --version prints 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: 0 or 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 the source_id, and point CODER_SEMANTIC at 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 --overwrite if the schema changed or is uncertain.
  • --sample-rows 50 samples real values (enums, date formats); --sample-rows 0 disables sampling.
  • Check: semantic_model.name must equal source_id (not the database name). scan writes this correctly; do not edit it by hand.

1.3 Model service (the llm section)

  • Set provider to an id: deepseek, openai, qwen, kimi, glm, doubao, minimax, hunyuan, xiaomi, or generic for a self-hosted gateway. The preset determines base_url; only generic requires an explicit one.
  • model and api_key are required. Set timeout_seconds to 300 for reasoning models; otherwise long SQL requests time out.
  • Changes to llm affect subsequent requests only; committed SQL versions are unchanged.

1.4 Workspaces and windows

  • Sessions, SQL versions and debugging evidence live under runtime.workspace (default content/), never in the business database.
  • A --window is 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 --window produces 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.sqlite write lock and report database is locked. For parallelism use separate workspaces such as ./content/ws-a and ./content/ws-b. If a lock occurs, check whether the previous process is still running; do not delete state/.

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 BY for 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 in FileNotFoundError.
  • 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_status to order_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 example DATE_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 --preview to 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 --semantic to create the window; passing it again in the same window is ignored with a notice.
  • Type the question at coder> and press Enter; :quit exits and prints session_id and window_id.
  • With --mode plan, the plan is printed for review: 1 approves, 2 accepts 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|english controls 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.
  • chat requires a TTY. In a pipeline or CI job it fails with chat 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 (default general).

  • 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_file and sql_file resolve against runtime.workspace, not the current directory.

  • For process events add --format jsonl: it emits window.created, message.delta, tool.* and run.finished line by line, ending with {"type":"result","result":...}.

  • Continue in the same window without --semantic:

    "$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 --semantic was 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}
  1. Read the plan first; never approve unread.

    "$CODER_PY" -m sql_coder history --config "$CODER_CONFIG" \
      --session <session_id> --kind plan --version <plan_version>
    

    content is the plan text; graph.nodes holds nodes (id, title, question, inputs, outputs, depends_on).

  2. Approve or request changes with resume, passing the body on stdin:

    "$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}
    JSON
    

    To request changes (produces a new plan and another review):

    {"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."}
    
  3. Read the response: completed with sql_version: N means SQL has been produced. If it is still pending with hook_type coder_plan_review, the plan was revised; the response already carries a new checkpoint (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 inputs or outputs, 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_id only 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 answers at 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, withdrawal and deposit are 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 debug results are allowed, but distinguish values returned by the query from values recomputed locally; every conclusion must be reproducible from results.

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):

    "$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 all returns one entry per target; --main returns a single main entry.
  • Truncation: truncated: true only means --row-limit cut 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 --cte to 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 --main and state its version number.
  • History: history --session <id> --kind sql lists versions; restore --session <id> --kind sql --version N restores an old version as a new one without rewriting history.
  • Business definitions: memory show --database "$CODER_SOURCE", with --query for keywords, --type definition for definitions only and --history for 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 4 means a model or database error; details.sql is the statement actually issued, so inspect that first.
  • A failed response has no results; only error, error_type and details. A non-empty details.partial means earlier targets succeeded and the failure is confined to one CTE or branch.
  • Unknown column / Unknown table: confirm real column names with --list-segments and the semantic file; do not guess.
  • Syntax errors: fix draft.sql and 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 30 before a full run.
  • Anti-joins are prone to hanging: NOT IN (subquery) and IN subqueries with LIMIT often time out or raise 1235 (LIMIT & IN/ALL/ANY/SOME). Run the subquery alone first, then rewrite as LEFT JOIN ... IS NULL or 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
  • --main succeeded 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_version and session_id for 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 --semantic file from another database to an existing window; it fails with Semantic file belongs to another database.
  • Do not reuse submission_id or checkpoint_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.