Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
2620cc0
fix: explain why `sql_execute` refuses a query as a write; stop misre…
anandgupta42 Nov 21, 2026
7f0ed7f
fix: keep `SELECT 1. INTO t` a write when exempting qualified columns
anandgupta42 Nov 21, 2026
b97438c
fix: tighten shell-residue detection, align `readSql`, keep SQL out o…
anandgupta42 Nov 21, 2026
4c2d954
fix: qualified columns are reads on SQL Server too; refusal reasons f…
anandgupta42 Nov 21, 2026
6a9d1c6
fix: refusal reasons keep file paths and pipe arguments out; a qualif…
anandgupta42 Nov 21, 2026
2101006
fix: shell-residue detection uses anchored patterns only; docs match …
anandgupta42 Nov 21, 2026
effb526
fix: dotted names of any length are columns, never after a number; te…
anandgupta42 Nov 21, 2026
b4e4daf
test: send a rule denial through `Effect.runPromise`, as the tool bri…
anandgupta42 Nov 21, 2026
de0937f
fix: name a plain write by its type on SQL Server; keep SQL text out …
anandgupta42 Nov 21, 2026
57c9b35
fix: word a pattern-scoped write denial as a rule, not read-only; ski…
anandgupta42 Nov 21, 2026
270bf82
fix: judge read-only from the rule in effect; cut parser messages to …
anandgupta42 Nov 21, 2026
9e8b968
fix: name SELECT INTO before batch keywords, hint quoted qualifiers, …
anandgupta42 Nov 21, 2026
01e219c
fix: query_from refusals carry the reason once; parser positions are …
anandgupta42 Nov 21, 2026
548ab80
fix: name the word a stricter sql_check list refuses; tidy parser det…
anandgupta42 Nov 21, 2026
e1af0c9
fix: pattern-only denies are not read-only; name SQL Server batches a…
anandgupta42 Nov 21, 2026
28e880b
fix: one reason helper names a stricter-list word only when it is the…
anandgupta42 Nov 21, 2026
65f502c
fix: keep ClickHouse dotted keywords strict; name only known keywords…
anandgupta42 Nov 21, 2026
bf8dc49
fix: trim the residue tail in linear time; report a missing SQL class…
anandgupta42 Nov 21, 2026
67f519e
fix: keep readSql strict for dotted statement words on ClickHouse, ma…
anandgupta42 Nov 21, 2026
d1b725a
test: the write corpus asserts write classification and a specific re…
anandgupta42 Nov 21, 2026
ef53fc9
fix: own next step for an unavailable classifier; one keyword source;…
anandgupta42 Nov 21, 2026
151e409
fix: refusals from sql_check, query_from and sql_materialize carry th…
anandgupta42 Nov 21, 2026
fa40acd
refactor: one constant for the unavailable-classifier next step
anandgupta42 Nov 21, 2026
b2466f9
fix: name hard-blocked statements in read-only refusals
anandgupta42 Nov 21, 2026
9aae937
docs: spaced qualifiers still ask, like quoted ones
anandgupta42 Nov 21, 2026
16c2cc2
fix: word unreadable quoted text neutrally (open or unsupported)
anandgupta42 Nov 21, 2026
ade0b00
fix: name a closed executable comment instead of asking to close a quote
anandgupta42 Nov 21, 2026
742003c
fix: name which statement is hard-blocked in read-only refusals
anandgupta42 Nov 21, 2026
f48e3d5
fix: detect executable comments from comment tokens, not raw text
anandgupta42 Nov 21, 2026
993e19e
fix: do not place a real hard block inside an unclosed quote
anandgupta42 Nov 21, 2026
162d1d9
fix: name the hard-block rule and explain hard blocks in every tool
anandgupta42 Nov 21, 2026
83b753f
fix: record the hard-block cause in the classifier itself
anandgupta42 Nov 21, 2026
6fb1ee4
fix: CLI denial wording, fixed-word hard-block labels
anandgupta42 Nov 21, 2026
b77eeec
fix: name the clearest write and the warehouse hint only where it helps
anandgupta42 Nov 21, 2026
da71cba
fix: one parse per dialect on denial; test the missing-parser path
anandgupta42 Nov 21, 2026
c52a33c
fix: streamline SQL refusal explanations and stabilize parser test
anandgupta42 Nov 21, 2026
6caa2a4
test: pin qualified keyword-named functions as calls; keep tests vali…
anandgupta42 Nov 21, 2026
bd397d8
fix: preserve SQL refusal telemetry classes and explain unsupported r…
anandgupta42 Nov 21, 2026
5cd4407
fix: name why a read cannot be embedded; a missing classifier is not …
anandgupta42 Nov 21, 2026
0b34a0b
refactor: one ordered check names why a read cannot be embedded
anandgupta42 Nov 21, 2026
cb887bf
fix: keep SQL Server XML .query() a read; hard blocks keep their own …
anandgupta42 Nov 21, 2026
aa3d5ce
fix: hard blocks keep the permission class; one SQL Server dialect ch…
anandgupta42 Nov 21, 2026
c8a3d47
fix: SQLite returns rows for comment-led reads; ClickHouse names shel…
anandgupta42 Nov 21, 2026
4feaf28
fix: keep the SQLite driver unchanged; name ClickHouse redirects only…
anandgupta42 Nov 21, 2026
d06aa2b
fix: name ClickHouse redirects on any read, including SHOW and DESCRIBE
anandgupta42 Nov 21, 2026
29fe53f
fix: quote names in refusal hints the way the dialect does
anandgupta42 Nov 22, 2026
94a878d
fix: refusal hints quote names with brackets on SQL Server and backti…
anandgupta42 Nov 22, 2026
050301b
fix: case-correct quoting hints on ClickHouse, Snowflake and Oracle
anandgupta42 Nov 22, 2026
c730117
fix: pattern-rule refusals name the allowed patterns; hints fit the a…
anandgupta42 Nov 22, 2026
67ceaaa
fix: honest write-clause hints; pattern names stay out of telemetry; …
anandgupta42 Nov 22, 2026
d0585f0
fix: name only sql_execute_write's own allow/ask patterns
anandgupta42 Nov 22, 2026
2645542
fix: name only rule patterns still in effect after the last catch-all…
anandgupta42 Nov 22, 2026
b1a702f
fix: ClickHouse pipe rule needs a flagged command; escape backslashes…
anandgupta42 Nov 22, 2026
01d0a8c
fix: numbers never read as dotted names in hints; residue refusals sk…
anandgupta42 Nov 22, 2026
81d9e4e
fix: residue is a flag from explainWrite; leading-dot decimals are nu…
anandgupta42 Nov 22, 2026
54ad4d6
fix: data_diff names the refused input; a parenthesized SELECT is tol…
anandgupta42 Nov 22, 2026
14e92f7
fix: a read starting with a parenthesis gets advice that holds for se…
anandgupta42 Nov 22, 2026
7746915
fix: the parenthesis reason no longer repeats the closing advice
anandgupta42 Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/docs/configure/permissions.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,12 @@ When prompted, you have three choices:

"Allow always" approvals persist for your current session only. They reset when you restart Altimate Code.

### How SQL is classified for `sql_execute_write`

`sql_execute` parses each query and asks for `sql_execute_write` only when a statement is not a read. Comments (except MySQL executable comments such as `/*! ... */`, which are refused), string literals, and column names such as `update_ts`, `t.update` or `s.t.update` do not count (dotted names still count on ClickHouse); a quoted, bracketed or spaced qualifier (`"t".update`, `t . update`) still asks. SQL the parser cannot read is treated as a write, so it is never run without write permission. On a dbt target, any Jinja (`{{ }}`, `{% %}`, `{# #}`) counts as a write too, even inside a comment or literal, because dbt renders and runs it first.

When a query reaches the `sql_execute_write` check and a `"deny"` rule refuses it, the tool error tells the agent why the query counted as a write and what to change (hard-blocked statements such as `DROP DATABASE`, and writes inside a batch, fail earlier with their own messages): the statement that writes, the parser error and its position, or shell syntax such as `2>/dev/null` to remove.

## Tips

- **Start with `"ask"` and relax as you build confidence.** You can always approve patterns with "Allow always" during a session.
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/usage/tool.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Only the data tools are exposed. Coding tools (`bash`, `read`, `edit`, ...), `db

## Permissions

Runs are read-only by default. Reads such as `sql_execute` on a SELECT and `schema_inspect` are allowed; anything else is refused with `Permission denied: <kind>. Re-run with --allow-write to enable writes.` Tools that change local configuration (`warehouse_add`, `warehouse_remove`, `warehouse_install_driver`) also need `--allow-write`.
Runs are read-only by default. Reads such as `sql_execute` on a SELECT and `schema_inspect` are allowed; anything else is refused with `Permission denied: <kind>. Re-run with --allow-write to enable writes.` For `sql_execute`, the refusal first says why the query counts as a write, so a malformed read can be fixed instead. Tools that change local configuration (`warehouse_add`, `warehouse_remove`, `warehouse_install_driver`) also need `--allow-write`.

`DROP` of a database, schema, catalog or namespace (including `DROP EXTERNAL SCHEMA` and `DROP PLUGGABLE DATABASE`), `TRUNCATE`, and MySQL/MariaDB executable comments (`/*! ... */`, `/*M! ... */`) are refused even with `--allow-write` when the SQL check recognises them. The check reads the SQL text, so it is best effort: a statement the warehouse builds or decodes at run time (dynamic SQL assembled by concatenation, a stored routine, an unusual literal encoding) can get past it. For a hard guarantee, connect with a database user that has no `DROP` or `TRUNCATE` privilege.

Expand Down
3 changes: 2 additions & 1 deletion packages/opencode/src/altimate/mcp-server/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as WorkspaceClient from "../workspace/client"
import { which, versionOf } from "../workspace/engine-probes"
import { clearsFloor, engineEntry, ENGINE_BINARY } from "../workspace/engine-types"
import { classifyAndCheck } from "../tools/sql-classify"
import { writeReason } from "../tools/read-only-sql"

// Deliberately closed: adding a new engine capability requires classifying it.
const METADATA_READS = new Set([
Expand Down Expand Up @@ -38,7 +39,7 @@ export function checkEngineRead(name: string, args: Record<string, unknown>) {
for (const query of queries) {
const result = classifyAndCheck(query, dialect)
if (result.parseError || result.blocked || result.queryType !== "read") {
throw new Error("Workspace SQL must be read-only. Use Altimate Code directly for writes.")
throw new Error("Workspace SQL must be read-only. Use Altimate Code directly for writes." + writeReason(query, dialect))
}
}
}
Expand Down
11 changes: 7 additions & 4 deletions packages/opencode/src/altimate/native/connections/data-diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import type { DataDiffParams, DataDiffResult, PartitionDiffResult } from "../types"
import * as Registry from "./registry"
import { requireReadOnlyQuery } from "../../tools/read-only-sql"
import { requireReadOnlyQuery, writeReason } from "../../tools/read-only-sql"
import { classifyAndCheck } from "../../tools/sql-classify"

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -196,7 +196,7 @@ async function executeQuery(sql: string, warehouseName: string | undefined, meta
const dialect = warehouseTypeToDialect(Registry.getConfig(warehouseName)?.type ?? "generic")
if (metadata) {
const check = classifyAndCheck(sql, dialect)
if (check.blocked || check.queryType !== "read") throw new Error("Data diff metadata must be read-only")
if (check.blocked || check.queryType !== "read") throw new Error(`Data diff metadata must be read-only.${writeReason(sql, dialect)}`)
} else {
requireReadOnlyQuery(sql, dialect)
}
Expand Down Expand Up @@ -900,8 +900,11 @@ export async function runDataDiff(params: DataDiffParams): Promise<DataDiffResul
] as const) {
const type = warehouse ? Registry.getConfig(warehouse)?.type : Registry.list().warehouses[0]?.type
const dialect = warehouseTypeToDialect(type ?? "generic")
requireReadOnlyQuery(isQuery(source) ? source : `SELECT * FROM ${source}`, dialect)
if (params.where_clause) requireReadOnlyQuery(`SELECT 1 WHERE (${params.where_clause})`, dialect)
// A query source is checked as sent; a table name and the filter are named, since the SQL wrapped around them
// is not what the user wrote.
if (isQuery(source)) requireReadOnlyQuery(source, dialect)
else requireReadOnlyQuery(`SELECT * FROM ${source}`, dialect, "source or target table name")
if (params.where_clause) requireReadOnlyQuery(`SELECT 1 WHERE (${params.where_clause})`, dialect, "where_clause")
}
} catch (error) {
return { success: false, error: `Data diff requires read-only inputs: ${error instanceof Error ? error.message : String(error)}`, steps: 0 }
Expand Down
6 changes: 5 additions & 1 deletion packages/opencode/src/altimate/tool-cli/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@ function dialectOf(metadata: unknown): string | undefined {
: undefined
}

/** A write refused because writes were not enabled; sql_execute adds why the query counts as a write. */
export class WriteDeniedError extends Error {}

export function denied(permission: string, retry = "Re-run"): Error {
return new Error(`Permission denied: ${permission}. ${retry} with --allow-write to enable writes.`)
const message = `Permission denied: ${permission}. ${retry} with --allow-write to enable writes.`
return permission === "sql_execute_write" ? new WriteDeniedError(message) : new Error(message)
}

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/opencode/src/altimate/tools/data-diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Tool } from "../../tool/tool"
import { Dispatcher } from "../native"
import * as Registry from "../native/connections/registry"
import { classifyAndCheck } from "./sql-classify"
import { hardBlockRefusal } from "./read-only-sql"

export const DataDiffTool = Tool.define("data_diff", {
description: [
Expand Down Expand Up @@ -104,7 +105,7 @@ export const DataDiffTool = Tool.define("data_diff", {
const dialectOf = (warehouse?: string) => Registry.canonicalType(warehouse ? Registry.getConfig(warehouse)?.type : undefined) ?? undefined
for (const [sql, warehouse] of [[args.source, sourceWarehouse], [args.target, targetWarehouse]] as const)
if (classifyAndCheck(sql, dialectOf(warehouse)).blocked)
throw new Error("DROP DATABASE, DROP SCHEMA and TRUNCATE are blocked for safety. This cannot be overridden.")
throw new Error(hardBlockRefusal("DROP DATABASE, DROP SCHEMA and TRUNCATE are blocked for safety.", sql, dialectOf(warehouse)))
for (const side of sides)
await ctx.ask({
permission: "sql_execute_read",
Expand Down
128 changes: 103 additions & 25 deletions packages/opencode/src/altimate/tools/read-only-sql.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { classifyAndCheck, isSingleQuery } from "./sql-classify"
import { maskSql, tokenizeSql } from "./sql-tokenize"
import { UNAVAILABLE_NEXT_STEP, hardBlockCause, hasExecutableComment, classifyAndCheck, explainWrite, isSingleQuery, isSqlServerDialect } from "./sql-classify"
import { maskSql, statementsOf, tokenizeSql } from "./sql-tokenize"
import { sqlFunctionCalls } from "./sql-functions"
import { hasSideEffectFunction } from "./sql-function-policy"

Expand All @@ -8,58 +8,136 @@ import { hasSideEffectFunction } from "./sql-function-policy"
* CTE or subquery it is placed in), it has no statement separator, and it calls no function
* that writes or runs SQL (dynamic query() included). Undefined otherwise. */
function readOnlyBody(sql: string, dialect?: string): { masked: string; body: string } | undefined {
const checked = embeddable(sql, dialect)
return "refused" in checked ? undefined : checked
}

/** readOnlyBody's checks, in order, with the first failed one named in fixed words (no SQL text). A write or
* hard block is refused without a reason: the classifier explains those. */
function embeddable(sql: string, dialect?: string): { masked: string; body: string } | { refused: string } {
const { queryType, blocked } = classifyAndCheck(sql, dialect)
// Settled already; the function scan below is costly on deeply nested input.
if (blocked || queryType !== "read") return undefined
if (blocked || queryType !== "read") return { refused: "" }
const { tokens, complete } = tokenizeSql(sql, dialect)
const masked = maskSql(tokens)
// All calls use real code '(' tokens.
const unsafeFunction = sqlFunctionCalls(sql, dialect).some(
(call) => call.escaped || call.name === "query" || hasSideEffectFunction(call.name),
)
const calls = sqlFunctionCalls(sql, dialect)
// SQL Server's XML .query() takes XQuery, not SQL, as in the classifier; elsewhere query() runs SQL text.
if (!isSqlServerDialect(dialect) && calls.some((call) => call.name === "query")) {
return { refused: "it calls query(), which runs SQL text that cannot be checked; query the tables directly" }
}
if (calls.some((call) => call.escaped)) return { refused: "it has an escaped function call, which cannot be checked" }
if (calls.some((call) => hasSideEffectFunction(call.name))) {
return { refused: "it calls a function that is not known to be read-only" }
}
const body = masked.trim().replace(/;$/, "").trim()
if (body.includes(";")) return { refused: "it holds more than one statement" }
if (!isSingleQuery(sql, dialect)) {
return { refused: "it is not a SELECT or WITH query (a command such as SHOW cannot be embedded)" }
}
let depth = 0
let balanced = true
for (const char of body) {
if (char === "(") depth++
if (char === ")" && --depth < 0) balanced = false
}
const safe =
!blocked &&
queryType === "read" &&
isSingleQuery(sql, dialect) &&
complete &&
!unsafeFunction &&
balanced &&
depth === 0 &&
!body.includes(";")
return safe ? { masked, body } : undefined
if (!complete || !balanced || depth !== 0) return { refused: "its parentheses, quotes or comments do not balance" }
return { masked, body }
}

/** Throws unless sql is one read-only query that is safe to embed in a larger query. */
export function requireReadOnlyQuery(sql: string, dialect?: string): void {
if (readOnlyBody(sql, dialect) === undefined)
throw new Error("Only a single read-only query is accepted here; it never writes data.")
export function requireReadOnlyQuery(sql: string, dialect?: string, input?: string): void {
if (readOnlyBody(sql, dialect) !== undefined) return
// When the caller wrapped user input in SQL it built, name that input: a reason with positions or "it" would
// describe text the user never wrote.
if (input) throw new Error(`The ${input} must be part of a single read-only query; it never writes data.`)
throw new Error(`Only a single read-only query is accepted here; it never writes data.${writeReason(sql, dialect)}`)
}

// Statement words refused anywhere in a read handed to sql_check. A column qualified by a whole
// identifier (t.update) is not one, as in the classifier, except on ClickHouse, whose bundled parser
// accepts trailing text.
const WORDS = "INSERT|UPDATE|DELETE|MERGE|DROP|ALTER|CREATE|TRUNCATE|COPY|ATTACH|DETACH|PRAGMA|VACUUM|CALL|DO|INTO|INSTALL|LOAD|EXPORT|IMPORT|GRANT|REVOKE"
const QUALIFIED = "(?<!(?:^|[^\\w$.])[A-Za-z_][\\w$]*(?:\\.[A-Za-z_][\\w$]*)*\\.[A-Za-z]+)"
const STATEMENT_WORD = new RegExp(`\\b(${WORDS})\\b${QUALIFIED}`, "i")
const REPLACE_WORD = new RegExp(`\\bREPLACE\\b(?!\\s*\\()${QUALIFIED}`, "i")
const STRICT_STATEMENT_WORD = new RegExp(`\\b(${WORDS})\\b`, "i")
const STRICT_REPLACE_WORD = /\bREPLACE\b(?!\s*\()/i

function wordPatterns(dialect?: string): [RegExp, RegExp] {
return dialect?.toLowerCase() === "clickhouse" ? [STRICT_STATEMENT_WORD, STRICT_REPLACE_WORD] : [STATEMENT_WORD, REPLACE_WORD]
}

/** Ignore quoted content while checking structure; preserve the original SELECT and its LIMIT.
* Stricter than requireReadOnlyQuery: sql_check also requires SELECT or WITH and refuses
* write keywords anywhere, even where the parser reports a query. */
export function readSql(sql: string, dialect?: string): string {
export function readSql(sql: string, dialect?: string, options: { explain?: boolean } = {}): string {
const checked = readOnlyBody(sql, dialect)
const body = checked?.body ?? ""
if (
checked === undefined ||
!/^(SELECT|WITH)\b/i.test(body) ||
/\b(INSERT|UPDATE|DELETE|MERGE|DROP|ALTER|CREATE|TRUNCATE|COPY|ATTACH|DETACH|PRAGMA|VACUUM|CALL|DO|INTO|INSTALL|LOAD|EXPORT|IMPORT|GRANT|REVOKE)\b/i.test(
body,
) ||
/\bREPLACE\b(?!\s*\()/i.test(body)
// A column qualified by a whole identifier (t.update) is not a statement word, as in the classifier.
wordPatterns(dialect).some((pattern) => pattern.test(body))
) {
throw new Error(
"This operation only accepts a single read-only SELECT (or WITH ... SELECT); it never writes or fixes data.",
"This operation only accepts a single read-only SELECT (or WITH ... SELECT); it never writes or fixes data." +
(options.explain === false ? "" : writeReason(sql, dialect)),
)
}
const semicolon = checked.masked.indexOf(";")
return semicolon < 0 ? sql : sql.slice(0, semicolon) + sql.slice(semicolon + 1)
}

/** Every hard-block refusal says this; its "permission" keyword sets the telemetry error class. */
export const NOT_OVERRIDABLE = "This cannot be overridden by any permission rule."

/** A hard-block refusal: head, then "cannot be overridden" unless only unreadable text (an open quote or comment)
* made a word count, then the reason. */
export function hardBlockRefusal(head: string, sql: string, dialect?: string): string {
const unreadable = !tokenizeSql(sql, dialect).complete && !hasExecutableComment(sql, dialect)
return `${head}${unreadable ? "" : ` ${NOT_OVERRIDABLE}`}${writeReason(sql, dialect)}`
}

/** Why sql is refused as a read, as a sentence to append to a refusal: a hard block, the classifier's reason for a write,
* a read shape that cannot be embedded, or a statement word refused by the stricter list. Empty for accepted reads. */
export function writeReason(sql: string, dialect?: string): string {
const { queryType, blocked } = classifyAndCheck(sql, dialect)
if (blocked) {
// Name the first statement that is blocked on its own, by position only (no SQL text is quoted back).
const statements = tokenizeSql(sql, dialect).complete ? statementsOf(sql, dialect) : []
const index = statements.length > 1 ? statements.findIndex((statement) => classifyAndCheck(statement, dialect).blocked) : -1
const where = index >= 0 ? `statement ${index + 1} of ${statements.length} is` : "it holds"
const cause = hardBlockCause(index >= 0 ? statements[index] : sql, dialect)
const hard = ` It is refused because ${where} a hard-blocked statement (${cause}); hard-blocked statements never run, whatever the permission rules allow.`
// Text that cannot be read (an open or unsupported quote or comment) is blocked on its words alone, inside the
// unreadable text or outside it: name the unreadable text first, since fixing it may be the whole fix.
const untilClosed =
" Until it can be read, words such as DROP DATABASE or TRUNCATE anywhere in the SQL, inside that quoted text or" +
" outside it, count as a hard-blocked statement; a real one outside it stays refused once the text is fixed."
return tokenizeSql(sql, dialect).complete || hasExecutableComment(sql, dialect)
? hard
: ` It counts as a write because ${explainWrite(sql, dialect).reason}.${untilClosed}`
Comment thread
anandgupta42 marked this conversation as resolved.
Resolved
}
if (queryType === "write") {
const { reason, unreadable, unavailable } = explainWrite(sql, dialect)
// A missing classifier is an installation failure, not a permission decision.
const head = unreadable || unavailable ? "It counts as a write because" : "It counts as a write, which needs a write permission this path does not have, because"
return ` ${head} ${reason}.${unavailable ? ` ${UNAVAILABLE_NEXT_STEP}` : ""}`
}
// Name the word only when it is the sole reason: the body is otherwise one SELECT or WITH query.
const checked = embeddable(sql, dialect)
const body = "refused" in checked ? undefined : checked.body
if (!body || !/^(SELECT|WITH)\b/i.test(body)) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const cause =
"refused" in checked
? checked.refused
: body!.startsWith("(")
? "it starts with a parenthesis (for UNION or a similar set operation, move the parenthesized branches into a WITH query or drop their parentheses)"
: "it is not a SELECT or WITH query (a command such as SHOW cannot be embedded)"
return ` This read is invalid here because ${cause}; send a single SELECT or WITH query that can be embedded.`
}
const [statement, replace] = wordPatterns(dialect)
const word = (statement.exec(body) ?? replace.exec(body))?.[0]
return word ? ` It contains the statement word ${word.toUpperCase()} outside a literal or comment, so the read-only permission does not cover it; quote it if it is a column name${/^(snowflake|oracle)$/i.test(dialect ?? "") ? ", in uppercase as this engine stores unquoted names" : ""}.` : ""
}
Loading
Loading