Proposal: Add databricks query command (Statement API) with a profile‑level safety gate; vector‑ready design
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Facilidade para iniciantes
- 35/100
Direção de pesquisa
Comece revisando os pontos de entrada de comandos propostos em cmd/query, cmd/query/sql.go e sua integração em cmd/cmd.go. Em seguida, inspecione o escopo proposto dos testes unitários de libs/safety/sqlsafe e os requisitos da Statement Execution API. Considera-se concluído quando o escopo v1 aceito funcionar com as flags listadas, a segurança e a precedência de configuração forem testadas, os fluxos da API mock forem cobertos e a documentação da CLI for adicionada.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Summary
Introduce a new top‑level databricks query command for running queries from the CLI. The first subcommand, databricks query sql, would execute SQL via the Statement Execution API on a SQL Warehouse. A profile‑level safety gate enforces read‑only behavior by default so both humans and AI tools can use the command safely. The structure intentionally leaves space for databricks query vector (future) to execute vector/search queries.
Problem & Motivation
- Today there is no CLI command that submits a SQL statement and returns results. The
databricks psqlcommand is interactive JDBC; it’s not great for automation, scripting, or AI agents that need a one‑shot query with structured output. - Teams often want CI jobs, notebooks, or AI dev tools to run read‑only queries safely without risking accidental
DROP/ALTER/INSERT/DELETE. - We also want a coherent home for non‑SQL queries (e.g., vector search) that return records but don’t fit into the “workspace admin” groups under
workspace sql-*.
Goals
- Provide a simple, scriptable command to run queries and get results back as table/JSON/CSV (Arrow optional later).
- Make it safe by default for people and AI: a profile flag controls whether destructive SQL is allowed; default is read‑only only.
- Establish a query namespace that can grow:
query sqlnow,query vectorlater.
Non‑Goals (v1)
- Replace the interactive SQL CLI or JDBC clients.
- Implement every Statement API option; start with a minimal, solid core.
- Add a full SQL parser; we’ll use a conservative token/keyword approach to detect non‑read‑only statements.
Proposed UX
Run an inline statement
databricks query sql \
--warehouse-id <WAREHOUSE_ID> \
--sql "select 1 as one"
Run from a file
databricks query sql \
--warehouse-id <WAREHOUSE_ID> \
--file queries/top10_customers.sql
Output control
# Render as a table to TTY (default)
# Write JSON/CSV to a file
databricks query sql --warehouse-id <ID> \
--sql "select * from system.builtin.current_queries" \
--format json --output out/current_queries.json
Wait behavior (hybrid default)
# Wait up to 10s; if still running, fall back to async and poll.
databricks query sql --warehouse-id <ID> --sql "select count(*) from t"
# Force async return immediately
# (caller can poll with statement id; may be out of scope for v1 CLI)
# databricks query sql --wait-timeout 0s ...
Safety gate (profile/env/flag)
- Default: read‑only only. Destructive statements are blocked with a clear error.
- Opt‑in overrides:
- CLI flag:
--allow-destructive - Env var:
DATABRICKS_CLI_ALLOW_DESTRUCTIVE_SQL=true - Profile key:
cli.allow_destructive_sql = true
- CLI flag:
Example profile (in ~/.databrickscfg):
[dev]
host = https://dbc-xxx.cloud.databricks.com
token = dapi***********
cli.allow_destructive_sql = false # default; safe for AI and scripts
Future: databricks query vector ... to issue vector/search queries to Databricks vector services, returning JSON/CSV similarly.
Why a new top‑level query command?
- Keeps execution distinct from workspace admin commands (query history, visualizations, permissions). Those are CRUD‑style operations; this proposal is about running queries.
- Avoids overloading
psql(interactive) and gives a clean automation entrypoint for humans and AI. - Provides a natural home for multiple modalities (SQL today, vector tomorrow) under one user mental model.
Implementation Plan (high level)
1) Command structure
- New package:
cmd/querywith root commandquery. - Subcommand:
cmd/query/sql.goexportingNew()that wires intocmd/cmd.go.
2) Flags (v1)
--warehouse-id <string>(required; no implicit default in v1)- One of:
--sql "..."(inline statement)--file <path.sql>(read file contents; allow multiple statements separated by;)
- Output/format:
--format table|json|csv(default:tablefor TTY,jsonif--outputis provided)--output <path>(writes file; otherwise print)
- Wait & control:
--wait-timeout <duration>(default10shybrid: wait, then poll)- (Optional later)
--on-wait-timeout CONTINUE|CANCEL(default CONTINUE)
- Safety:
--allow-destructive(override)- As noted: env and profile keys also supported
- (Stretch)
--dry-run&--explain-safetyto print parsed statements and classification results.
3) Statement Execution & polling
- Use Go SDK’s Statement Execution API client to
ExecuteStatementwith warehouse id, SQL text, wait timeout. - If result returns inline: render immediately.
- If not ready: poll
GetStatementuntil success/error; if chunked results, stream viaGetStatementResultChunkN. - Renderers: table (TTY), JSON/CSV (file or stdout).
4) Read‑only safety classifier (minimal, conservative)
- Strip
--and/* ... */comments while respecting'"and backtick quotes. - Split on semicolons that are not inside quotes.
- For each statement, check first meaningful token (case‑insensitive):
- Allow:
SELECT,SHOW,DESCRIBE,EXPLAIN(only if target is read‑only),WITHleading toSELECT. - Block: everything else (
INSERT,UPDATE,DELETE,MERGE,CREATE,ALTER,DROP,TRUNCATE,REPLACE,VACUUM,OPTIMIZE,COPY,GRANT,REVOKE,RESTORE,MSCK,SET[treat as stateful; block in v1]).
- Allow:
- If any statement in a multi‑statement input is non‑read‑only, fail fast with a helpful error:
"Blocked by safe‑only mode: found DDL/DML keyword
CREATEat statement 1 (pos 1:1). Pass--allow-destructiveor setcli.allow_destructive_sql=trueto override." - Note the classifier is intentionally conservative; we’ll document that user‑defined or engine‑side side effects cannot be perfectly detected statically.
Placement: implement classifier as
libs/safety/sqlsafewith unit tests.
5) Config resolution order
- CLI flag
--allow-destructive - Env var
DATABRICKS_CLI_ALLOW_DESTRUCTIVE_SQL - Profile key
cli.allow_destructive_sql - Default:
false(safe‑only)
6) Error handling & UX
- Map Statement API terminal states to clear CLI errors with exit codes.
- Spinner/progress while polling;
--log-level debugshould include request ids for supportability.
7) Tests & acceptance
- Unit: classifier edge cases (comments, quotes, multi‑stmt,
EXPLAIN SELECTvsEXPLAIN INSERT, etc.). - Integration (optional): behind a guard/environment, run a tiny safe query against a test warehouse.
- Acceptance: mock server for Statement API covering inline/hybrid/chunked paths.
8) Docs
- New page under CLI docs: usage, safety gate, examples.
- Mention how this differs from
psqland from the Databricks SQL CLI.
Backwards Compatibility & Impact
- Purely additive: no changes to existing command groups.
- Defaults emphasize safety and deterministic output for automation.
- Future
query vectorwill reuse output/UI and safety philosophy (read‑only by nature; separate rate/size limits to discuss later).
Open Questions for Maintainers
- Placement & naming
- Approve a new root
querycommand withsqlsubcommand? - Alternate:
databricks sql rununder a newsqlgroup? (My preference:queryto keep modality‑agnostic.)
- Approve a new root
- Default output
- Table to TTY, JSON to file by default—ok?
- Safety defaults & scope
- Is
SETconsidered destructive (block in v1)? Any other keywords to add to the blocklist/allowlist?
- Is
- Warehouse resolution
- v1 requires
--warehouse-id. Should we look up a default from profile in a later PR?
- v1 requires
- Arrow support
- Should we include
--format arrowin v1 or leave to a follow‑up?
- Should we include
- Async surface
- Expose statement id and a
query sql get --statement-idin v1, or leave until there’s demand?
- Expose statement id and a
- CLA/process
- Is a CLA required and are you open to a community PR for this feature?
Willing to Implement
I’m happy to implement the v1 scope outlined above (command, Statement API integration, conservative safety classifier, table/JSON/CSV output, tests, docs). I’ll incorporate your feedback on naming, defaults, and any repo‑specific conventions. If a CLA or additional steps are needed, please let me know.
Acceptance Criteria (proposed)
databricks query sqlexecutes a SQL statement on a warehouse and returns results.- Read‑only safety gate enforced by default; destructive statements blocked with a clear error message.
- Flags:
--warehouse-id,--sql/--file,--format,--output,--wait-timeout,--allow-destructive. - Profile/env/flag precedence works as documented.
- Unit tests for classifier; basic acceptance tests for inline/hybrid/chunked flows.
- Docs added with examples and safety guidance.
Future Work (non‑blocking)
databricks query vectorfor vector/search queries.--format arrowand streaming Arrow to stdout.- Async surface: return statement id,
getsubcommands. - Sane defaults for warehouse selection.
- Richer result rendering (paging, truncation, width control) if demand arises.
Request for feedback:
- Do you agree with the top‑level
querycommand design and v1 scope? - Are the safety defaults the right trade‑off (helpful for AI and automation)?
- Any concerns with implementation approach or repo structure?
- Linguagem predominante
- Go
- Estrelas
- 427
- Forks
- 267
- Merge médio
- 2d 1h
- PRs com merge (30d)
- 233
Preparar o ambiente
- Inclui um Dockerfile ou arquivo Docker Compose
- Tem um modelo de pull request
- Sem guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de databricks/cli
-
Apps commands only accept relative path to app.ymlTalvez já em andamento @yuri-rod assumiu há 38 dias. AbertaCLI
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 82/100
databricks/cli#6910 ·
Mantenedores costumam responder em até 1 dia
-
DABs
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
databricks/cli#6670 · 1 reação ·
Mantenedores costumam responder em até 1 dia
-
Bump vulnerable dependencies workflow is failingTalvez já em andamento @shreyas-goenka assumiu hoje. Abertabump-vuln-deps-failure
databricks/cli#7531 · 1 comentário · 7 responsáveis ·
Mantenedores costumam responder em até 1 dia
-
bundle run on an app fails with "not in RUNNING state" when the app's compute is UPDATINGTalvez já em andamento @andrewnester assumiu há 1 dia. AbertaBug DABs
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 76/100
databricks/cli#7451 · 1 responsável ·
Mantenedores costumam responder em até 1 dia
-
Bundle deploy of an AI/BI dashboard breaks viewers' private bookmarks (UI save + publish does not)Aberta
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 45/100
databricks/cli#7419 ·
Mantenedores costumam responder em até 1 dia
Todas as issues de databricks/cli
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
prime-radiant-inc/evener#6241 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
coder/openstorage#807 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
NVIDIA/kubectl-nv#100 ·
Mantenedores costumam responder em até 1 dia
-
TestNoEagerPackageRegexps red on main: internal/gui/feedback.go:19 compiles a package-level regexpAberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 86/100
Mantenedores costumam responder em até 1 dia