Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
94 changes: 89 additions & 5 deletions packages/opencode/src/altimate/tools/sql-classify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// Parser failures are never reads; lexical checks retain hard-deny protection.

import { hasMongoWriteStage, normalizeMqlCommand } from "@altimateai/drivers"
import { isModeledDialect, maskSql, statementsOf, tokenizeSql } from "./sql-tokenize"
import { DOLLAR_TAG_ANYWHERE, isModeledDialect, lexesDollarQuotes, maskSql, statementsOf, tokenizeSql } from "./sql-tokenize"
import { sqlFunctionCalls, sqlLiteral } from "./sql-functions"
import { hasSideEffectFunction, isReadOnlyNestedFunction } from "./sql-function-policy"

Expand All @@ -32,6 +32,7 @@ const READ_CATEGORIES = new Set(["query"])
* Only code tokens change; quoted content and the original statement boundaries
* remain authoritative when checking the parser's result. */
function parserSql(sql: string, dialect?: string): string {
if (/\bEXPLAIN\b/i.test(sql)) sql = blankExplainOptions(sql, dialect)
const duckdb = dialect?.toLowerCase() === "duckdb"
if (!duckdb && dialect?.toLowerCase() !== "sqlite") return sql
const compatible = tokenizeSql(sql, dialect).tokens
Expand Down Expand Up @@ -85,7 +86,11 @@ function maskUnpivotLabels(sql: string): string {
// The parser labels SELECT INTO and queries with modifying CTEs as "query".
// Quoted identifiers/literals and comments cannot introduce these write clauses.
function hasQueryWriteClause(sql: string, dialect?: string): boolean {
let masked = maskSql(tokenizeSql(sql, dialect).tokens)
return maskedHasWriteClause(maskSql(tokenizeSql(sql, dialect).tokens), dialect)
}

/** hasQueryWriteClause over text already masked by maskSql. */
function maskedHasWriteClause(masked: string, dialect?: string): boolean {
// UNPIVOT's INTO NAME labels output columns; it does not create a table.
if (dialect?.toLowerCase() === "duckdb") masked = maskUnpivotLabels(masked)
return /\b(INTO|INSERT|UPDATE|DELETE|MERGE)\b/i.test(masked)
Expand Down Expand Up @@ -141,14 +146,92 @@ function isReadOnlyMetadata(statement: string): boolean {
}
// EXPLAIN is a read only when the explained statement is one: `EXPLAIN ANALYZE`
// executes the statement, so `EXPLAIN ANALYZE DELETE …` must stay a write.
const EXPLAIN_PREFIX = /^\s*EXPLAIN\b(\s+(ANALYZE|VERBOSE|QUERY\s+PLAN|FORMAT\s+\w+|\([^)]*\)))*\s+/i
// Options are accepted only where the dialect defines them: Snowflake USING JSON|TEXT|TABULAR,
// Databricks/Spark/Hive EXTENDED|CODEGEN|COST|FORMATTED, and the parenthesized list of each of
// PostgreSQL and DuckDB. Any other option, or a list in another dialect, leaves a write.
const OPTION_BOOLEAN = "(?:\\s+(?:TRUE|FALSE|ON|OFF|YES|NO|T|F|Y|N|0|1))?"
const POSTGRES_OPTION =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (fail-closed, safe in a follow-up): some valid optioned reads are still refused. Each of these is a write at base and at head:

  • EXPLAIN (FORMAT 'json') SELECT 1: PostgreSQL accepts a quoted option value, but the grammar takes bare words only. It was a read on the round-1 head.
  • Nested optioned EXPLAIN, such as EXPLAIN (FORMAT JSON) EXPLAIN SELECT 1. PostgreSQL rejects this anyway.
  • EXPLAIN (FORMAT JSON) (SELECT 1) and EXPLAIN (FORMAT JSON) VALUES (1). Your decline is reasonable: plain EXPLAIN (SELECT 1) and EXPLAIN VALUES (1) are writes at base, and the optioned forms match them.

A list separated by non-ASCII whitespace, such as (ANALYZE,<NBSP>FORMAT<NBSP>JSON), is a read. JavaScript's \s matches NBSP but PostgreSQL does not, so the engine rejects it and no write gets through.

"(?:FORMAT\\s+(?:TEXT|XML|JSON|YAML)|SERIALIZE(?:\\s+(?:NONE|TEXT|BINARY))?|" +
`(?:ANALYZE|ANALYSE|VERBOSE|COSTS|IO|SETTINGS|GENERIC_PLAN|BUFFERS|WAL|TIMING|SUMMARY|MEMORY)${OPTION_BOOLEAN})`
// DuckDB implements only ANALYZE and FORMAT, with its own formats.
const DUCKDB_OPTION = `(?:FORMAT\\s+(?:TEXT|JSON|HTML|GRAPHVIZ|YAML)|ANALYZE${OPTION_BOOLEAN})`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: FORMAT YAML is not a DuckDB format

DuckDB documents TEXT, JSON, HTML and GRAPHVIZ for EXPLAIN (FORMAT …); YAML is PostgreSQL-only. Accepting it here makes EXPLAIN (FORMAT YAML) SELECT 1 a read on duckdb, which the new test pins at sql-classify-explain.test.ts:120 under "accept their own option lists". It only fails open for SQL the engine rejects, but it contradicts the per-dialect contract this commit establishes: the same test asserts (FORMAT XML), (VERBOSE) and (BUFFERS) are writes on duckdb for that reason.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining. DuckDB accepts this format: on DuckDB v2.0.0, EXPLAIN (FORMAT YAML) SELECT 1 returns a YAML plan (- name: "PROJECTION" …). Its error message for an unknown format also lists the valid values: default, text, query_tree, query_tree_optimizer, no_output, json, html, graphviz, yaml, mermaid, compact. So YAML belongs in DUCKDB_OPTION (sql-classify.ts:157), and the read at sql-classify-explain.test.ts:120 is correct.

// Linear: the items are separated by a comma, so no whitespace run can be split two ways.
const optionList = (option: string) => `\\(\\s*${option}(?:\\s*,\\s*${option})*\\s*\\)`
const POSTGRES_OPTION_LIST = optionList(POSTGRES_OPTION)
const DUCKDB_OPTION_LIST = optionList(DUCKDB_OPTION)
// DuckDB runs a COPY written as a CTE body; a column or table named copy is not one.
const COPY_CTE_BODY = /\bAS\s*(?:(?:NOT\s+)?MATERIALIZED\s*)?\(\s*COPY\b/i

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, fail-closed): COPY_CTE_BODY matches more than a CTE body. AS materialized(copy) is a table alias with a column list, not a CTE. With the fix suggested on line 234, plain EXPLAIN no longer runs this check. An optioned read still trips it: EXPLAIN (FORMAT JSON) SELECT * FROM (VALUES (1)) AS materialized(copy) is a write on postgres. Anchoring the pattern to a CTE (after WITH or ,, a name and an optional column list, then AS) would leave only real COPY bodies. This is safe in a follow-up.


/** The EXPLAIN keyword and its options. `legacy` adds the generic words the parser reads itself;
* only the dialect's own options are ever blanked, so the parser still rejects foreign words. */
function explainPrefix(dialect?: string, legacy = true): RegExp {
const d = dialect?.toLowerCase() ?? ""
const words = legacy ? ["ANALYZE", "VERBOSE", "QUERY\\s+PLAN", "FORMAT\\s+\\w+"] : []
if (d === "snowflake") words.push("USING\\s+(?:JSON|TEXT|TABULAR)")
if (/^(databricks|spark|hive)$/.test(d)) words.push("EXTENDED", "CODEGEN", "COST", "FORMATTED")
// Only PostgreSQL and DuckDB have such a list. It is taken either alone or as the legacy words, never both.
const options = /^(postgres|postgresql)$/.test(d) ? POSTGRES_OPTION_LIST : d === "duckdb" ? DUCKDB_OPTION_LIST : ""
const list = options ? `\\s*${options}\\s*|` : ""
const each = words.length ? `(?:\\s+(?:${words.join("|")}))*` : ""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, no write through): keyword options can repeat or combine. (?:\s+(?:…))* accepts any number of keyword options. These are read at head and were write at base:

  • EXPLAIN USING JSON USING TEXT SELECT 1 on snowflake
  • EXPLAIN COST COST SELECT 1, EXPLAIN COST FORMATTED SELECT 1 and EXPLAIN EXTENDED CODEGEN SELECT 1 on databricks

The explained statement is still checked, so a write such as … DELETE FROM t stays a write, and the engines reject this syntax. The description's "at most one list" holds for the parenthesized list only. Allowing at most one keyword option (? instead of *) would match the documented grammars. Codex rated this minor too.

return new RegExp(`^\\s*EXPLAIN\\b(?:${list}${each}\\s+)`, "i")
}

/** Length of the EXPLAIN keyword and its options, beyond a bare `EXPLAIN `. */
function optionsLength(statement: string, prefix: RegExpExecArray): number {
return prefix[0].length - (/^\s*EXPLAIN\s+/i.exec(statement)?.[0].length ?? 0)
}

/** The parser lacks the dialect's EXPLAIN options. Blank them in place, so the parser reads plain
* EXPLAIN <statement> over the original text, comments and statement boundaries unchanged. Never used for execution. */
function blankExplainOptions(sql: string, dialect?: string): string {
const lexical = tokenizeSql(sql, dialect)
if (!lexical.complete) return sql
// Same length as the text: comments are blanks, quoted text a filler no option can match.
const scan = lexical.tokens
.map(({ kind, text }) =>
kind === "code" ? text : kind === "comment" ? " ".repeat(text.length) : "\u0001".repeat(text.length),
)
.join("")
// A lexer without dollar quotes can read `$$--$$` as a comment that hides statements the parser
// skips too, so the two statement counts would agree on a wrong answer. Leave such text unadapted:
// the parser rejects the options and the statement is a write. Only code can open a dollar quote,
// since the lexer and the parser read the same text up to the first one.
if (!lexesDollarQuotes(dialect) && DOLLAR_TAG_ANYWHERE.test(scan)) return sql
const prefix = explainPrefix(dialect, false)
const parts: string[] = []
let copied = 0
let start = 0
for (const statement of scan.split(";")) {
const match = prefix.exec(statement)
if (match && optionsLength(statement, match) > 0 && statement.slice(match[0].length).trim()) {
const from = start + /^\s*/.exec(match[0])![0].length + "EXPLAIN".length
const to = start + match[0].length
parts.push(sql.slice(copied, from), " ".repeat(to - from))
copied = to
}
start += statement.length + 1
}
return parts.length ? parts.join("") + sql.slice(copied) : sql
}

/** EXPLAIN with options is read-only only as the sole statement of its text. */
function hasExplainOptions(statement: string, dialect?: string): boolean {
const prefix = explainPrefix(dialect).exec(statement)
return !!prefix && optionsLength(statement, prefix) > 0
}

/** An adapted EXPLAIN reaches the parser without its options, so the explained query is checked here. */
function isReadOnlyExplainedQuery(explained: string, dialect?: string): boolean {
const masked = maskSql(tokenizeSql(explained, dialect).tokens)
return !maskedHasWriteClause(masked, dialect) && !COPY_CTE_BODY.test(masked)
}

function isReadOnlyOther(statement: string, dialect?: string): boolean {
if (isReadOnlyMetadata(statement)) return true
const explained = statement.replace(EXPLAIN_PREFIX, "")
const explained = statement.replace(explainPrefix(dialect), "")
if (explained === statement) return false
return (
(/^\s*(SELECT|WITH)\b/i.test(explained) && !hasQueryWriteClause(explained, dialect)) ||
(/^\s*(SELECT|WITH)\b/i.test(explained) && isReadOnlyExplainedQuery(explained, dialect)) ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: plain EXPLAIN classifications changed from base. isReadOnlyOther now calls isReadOnlyExplainedQuery for every EXPLAIN, including plain EXPLAIN with no options. So the COPY_CTE_BODY check (line 163) also applies to plain EXPLAIN. Both of these were read at base and are write at head:

  • EXPLAIN SELECT * FROM (VALUES (1)) AS materialized(copy) on duckdb, postgres and snowflake (found by Codex). The regex takes the alias materialized for the CTE modifier. DuckDB runs this query and explains it without error.
  • EXPLAIN WITH c AS (COPY t TO '/x') SELECT 1 and the test's EXPLAIN WITH copied AS (COPY …) SELECT * FROM copied, in all 10 dialects tested (snowflake, databricks, postgres, postgresql, duckdb, bigquery, redshift, mysql, sqlserver, no dialect).

A plain EXPLAIN does not run the COPY. On DuckDB 2.0.1, EXPLAIN WITH c AS (COPY (SELECT 1 AS x) TO 'o3.csv') SELECT * FROM c writes no file. EXPLAIN ANALYZE and the bare query do write it, so the check is right for ANALYZE. The base read was correct for plain EXPLAIN.

This fails closed and the inputs are unusual. The review bar still lists any plain-EXPLAIN classification change from base as a block, so this is major (Codex rated it major and kept that rating on a second pass).

Suggested fix (verified): run the COPY check only when the EXPLAIN has options:

(/^\s*(SELECT|WITH)\b/i.test(explained) &&
  !hasQueryWriteClause(explained, dialect) &&
  (!hasExplainOptions(statement, dialect) || isReadOnlyExplainedQuery(explained, dialect))) ||

With this change, the corpus (63,588 cases) shows 0 plain-EXPLAIN changes from base outside the postgresql dollar-quote fixes. The optioned results are identical to the current head: EXPLAIN ANALYZE and EXPLAIN (ANALYZE) of a COPY CTE stay writes. One assertion has to go: plain EXPLAIN ${copy} in "EXPLAIN of a query with a COPY in a CTE is a write".

isReadOnlyMetadata(explained)
)
}
Expand All @@ -161,6 +244,7 @@ function otherIsReadOnly(sql: string, parsed: Array<{ category: string }>, diale
if (!tokenizeSql(sql, dialect).complete) return false
const statements = statementsOf(sql, dialect)
if (statements.length !== parsed.length) return false
if (statements.length > 1 && statements.some((statement) => hasExplainOptions(statement, dialect))) return false

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: This guard rejects multi-statement reads for every EXPLAIN option, not only the ones added here

hasExplainOptions is built from explainPrefix, which also contains the pre-existing ANALYZE, VERBOSE, QUERY PLAN, FORMAT <x> and generic ( … ) alternatives. On main, a batch such as EXPLAIN ANALYZE SELECT 1; SELECT 2 or EXPLAIN (ANALYZE, BUFFERS) SELECT 1; SELECT 2 was a read (per-statement isReadOnlyOther strips the option prefix); with this line it becomes a write and starts requiring write permission even though the explained statement is still a read.

The per-statement check plus statements.length !== parsed.length already reject an optioned EXPLAIN whose inner statement is a write, so this line can only turn read-only batches into writes. Consider narrowing it to the options this PR adds (USING …, Databricks EXTENDED|CODEGEN|COST|FORMATTED) — or, if the stricter behaviour is intended, add a test that pins the plain-option multi-statement case (EXPLAIN ANALYZE SELECT 1; SELECT 2) as a write so the behaviour change is deliberate and covered.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional: any optioned EXPLAIN, legacy or new, is read-only only as the sole statement of its text (fail closed); plain EXPLAIN is unchanged. Now pinned by a test in ff8f3fe.

Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
return parsed.every(
(statement, i) =>
(READ_CATEGORIES.has(statement.category) && !hasQueryWriteClause(statements[i], dialect)) ||
Expand Down
12 changes: 10 additions & 2 deletions packages/opencode/src/altimate/tools/sql-tokenize.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
type SqlToken = { kind: "code" | "comment" | "literal" | "identifier"; text: string }

// PostgreSQL, DuckDB and Redshift also allow any non-ASCII character in identifiers and dollar tags.
const DOLLAR_TAG = /\$(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?\$/y
const DOLLAR_TAG_SOURCE = "\\$(?:[A-Za-z_\\u0080-\\uffff][\\w\\u0080-\\uffff]*)?\\$"
const DOLLAR_TAG = new RegExp(DOLLAR_TAG_SOURCE, "y")
/** Text that opens a dollar quote, anywhere. */
export const DOLLAR_TAG_ANYWHERE = new RegExp(DOLLAR_TAG_SOURCE)

/** Dialects whose lexer reads dollar quotes (ClickHouse heredocs read alike). */
export function lexesDollarQuotes(dialect?: string): boolean {
return /^(postgres|postgresql|redshift|duckdb|snowflake|clickhouse)$/i.test(dialect ?? "")
}
const IDENTIFIER_CHAR = /[\w$\u0080-\uffff]/

/** A supported warehouse dialect these lexing rules model; anything else (none, "generic",
Expand Down Expand Up @@ -37,7 +45,7 @@ export function tokenizeSql(sql: string, dialect?: string): { tokens: SqlToken[]
// Where nesting is not known either way, a /* inside a comment makes its end uncertain.
const nestingKnown = nestedComments || /^(mysql|mariadb|sqlite|oracle|trino)$/i.test(dialect ?? "")
// ClickHouse heredocs ($tag$...$tag$) read like PostgreSQL dollar quotes.
const dollarQuotes = /^(postgres|redshift|duckdb|snowflake|clickhouse)$/i.test(dialect ?? "")
const dollarQuotes = lexesDollarQuotes(dialect)
// Quoting is dialect-specific: brackets can contain executable array expressions,
// and PostgreSQL backticks can be operators. Unknown dialects keep both visible.
const backtickIdentifiers = /^(mysql|mariadb|sqlite|bigquery|clickhouse|spark|databricks|hive)$/i.test(dialect ?? "")
Expand Down
Loading
Loading