Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(data): handle query terminators and trailing comments

Afloatc2c5f59b5b3f
diff --git a/server/data/query-subquery-boundaries.test.ts b/server/data/query-subquery-boundaries.test.ts
new file mode 100644
index 0000000000..21b76137a2
--- /dev/null
+++ b/server/data/query-subquery-boundaries.test.ts
@@ -0,0 +1,100 @@
+import { mkdtempSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { chartRenderer, compileChart, validateVegaLite } from "./deps.ts";
+import { createDataEngine } from "./engine.ts";
+import { DataSheetStore } from "./sheet.ts";
+import { describeTarget, exportData, quoteLiteral, showCard, type DataContext } from "./tools.ts";
+
+const root = mkdtempSync(join(tmpdir(), "omb-query-boundaries-"));
+const engine = createDataEngine({ botFolder: (id) => join(root, "bots", id), dataDir: join(root, "data") });
+const connection = "bot" as const;
+let sequence = 0;
+
+afterAll(async () => {
+ await engine.closeAll();
+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+});
+
+async function context(): Promise<DataContext> {
+ const botId = `case-${++sequence}`;
+ return {
+ database: await engine.forBot(botId),
+ sheet: new DataSheetStore({ botId, dir: join(root, "sheets", botId) }),
+ renderer: chartRenderer,
+ compileChart,
+ validateVegaLite,
+ exportRoots: () => [join(root, "exports", botId)],
+ signal: new AbortController().signal,
+ connection,
+ by: "bot",
+ };
+}
+
+type Operation = "describe" | "show" | "export";
+
+async function valueFrom(ctx: DataContext, operation: Operation, sql: string): Promise<string> {
+ if (operation === "describe") {
+ const result = await describeTarget(ctx, sql);
+ expect(result.rowCount).toBe(1);
+ expect(result.columns[0]!.name).toBe("value");
+ return result.columns[0]!.sample![0]!;
+ }
+ let resultSql: string;
+ if (operation === "show") {
+ const result = await showCard(ctx, { kind: "table", sql });
+ expect(result.rowCount).toBe(1);
+ expect(ctx.sheet.card(result.id)!.sql).toBe(sql);
+ resultSql = `SELECT value FROM omb_results.${result.id}`;
+ } else {
+ const result = await exportData(ctx, { format: "csv", sql });
+ expect(result.rowCount).toBe(1);
+ resultSql = `SELECT value FROM read_csv(${quoteLiteral(result.path)}, delim=',', header=true)`;
+ }
+ const rows = (await ctx.database.run(resultSql, { connection })).rows;
+ expect(rows).toHaveLength(1);
+ return String(rows[0]![0]);
+}
+
+const queries = [
+ ["statement terminator", "SELECT 7 AS value;", "7"],
+ ["trailing line comment", "SELECT 7 AS value -- result; stays in the comment", "7"],
+ ["quoted semicolon and nested comments", "SELECT 'semi;--text' AS value; /* outer ; /* inner ; */ done */ -- tail", "semi;--text"],
+ ["dollar-quoted semicolon", "SELECT $tag$semi;--text$tag$ AS value; -- tail", "semi;--text"],
+ ["plain query", "SELECT 7 AS value", "7"],
+];
+
+describe.each(["describe", "show", "export"] as const)("%s query boundaries", (operation) => {
+ it.each(queries)("accepts a %s without changing its value", async (_name, sql, expected) => {
+ expect(await valueFrom(await context(), operation, sql)).toBe(expected);
+ });
+
+ it("still refuses a second statement before executing either one", async () => {
+ const ctx = await context();
+ await ctx.database.run("CREATE TABLE victim AS SELECT 'keep' AS value", { connection });
+ await expect(valueFrom(ctx, operation, "SELECT 7 AS value; DELETE FROM victim")).rejects.toMatchObject({ error: { code: "invalid_input" } });
+ expect((await ctx.database.run("SELECT value FROM victim", { connection })).rows).toEqual([["keep"]]);
+ });
+});
+
+it("charts a CTE query with a final terminator and comment", async () => {
+ const ctx = await context();
+ const sql = "WITH source AS (SELECT * FROM (VALUES (1, 3), (2, 5)) t(category, amount)) SELECT * FROM source; -- plot these rows";
+ const result = await showCard(ctx, { kind: "chart", sql, chart: { type: "bar", x: "category", y: "amount", bins: 2 } });
+ expect(result.rowCount).toBe(2);
+ expect(ctx.sheet.card(result.id)!.sql).toBe(sql);
+ const rows = (await ctx.database.run(`SELECT * FROM omb_results.${result.id} ORDER BY x`, { connection })).rows;
+ expect(rows.map(([x, x2, y]) => [Number(x), Number(x2), Number(y)])).toEqual([[1, 2, 3], [2, 3, 5]]);
+});
+
+it("exports a saved query without a result table when its SQL ends in a comment", async () => {
+ const ctx = await context();
+ const card = await ctx.sheet.addCard({ kind: "table", title: "Saved query", sql: "SELECT 7 AS value -- saved query", by: "bot" });
+ const result = await exportData(ctx, { id: card.id, format: "csv" });
+ expect(result.rowCount).toBe(1);
+ const rows = (await ctx.database.run(`SELECT value FROM read_csv(${quoteLiteral(result.path)}, delim=',', header=true)`, { connection })).rows;
+ expect(rows.map(([value]) => Number(value))).toEqual([7]);
+});
diff --git a/server/data/sql-statements.ts b/server/data/sql-statements.ts
new file mode 100644
index 0000000000..0b7f7ce144
--- /dev/null
+++ b/server/data/sql-statements.ts
@@ -0,0 +1,106 @@
+import { DataFailure } from "./types.ts";
+
+const fail = (code: "invalid_input", message: string, hint?: string) => new DataFailure({ code, message, ...(hint ? { hint } : {}) });
+
+export type Token = { kind: "word" | "ident" | "punct" | "block"; text: string; raw: string };
+
+export function singleStatement(sql: string): { tokens: Token[]; end: number } {
+ const tokens: Token[] = [];
+ let statements = 1;
+ let ended = false;
+ let depth = 0;
+ let i = 0;
+ const n = sql.length;
+ let end = n;
+ const push = (kind: Token["kind"], raw: string, text = raw) => { if (depth === 0) tokens.push({ kind, text, raw }); };
+ while (i < n) {
+ const ch = sql[i]!;
+ const next = sql[i + 1];
+ if (ch === "-" && next === "-") { const end = sql.slice(i).search(/[\n\r]/); i = end === -1 ? n : i + end + 1; continue; }
+ if (ch === "/" && next === "*") { i = blockCommentEnd(sql, i); continue; }
+ if (ch === ";") { end = Math.min(end, i); ended = true; i++; continue; }
+ if (ended && /\S/.test(ch)) { statements++; ended = false; }
+ if (ch === "'") {
+ push("word", "'…'");
+ i = stringEnd(sql, i); continue;
+ }
+ if (ch === "$") {
+ const delimiter = /\$(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?\$/y;
+ delimiter.lastIndex = i;
+ const open = delimiter.exec(sql)?.[0];
+ if (open) {
+ const end = sql.indexOf(open, i + open.length);
+ if (end === -1) throw fail("invalid_input", "Unterminated dollar-quoted string.");
+ push("word", "'…'");
+ i = end + open.length; continue;
+ }
+ }
+ if (ch === '"') {
+ let j = i + 1;
+ for (;;) {
+ const q = sql.indexOf('"', j);
+ if (q === -1) throw fail("invalid_input", "Unterminated quoted identifier.");
+ if (sql[q + 1] === '"') { j = q + 2; continue; }
+ j = q + 1; break;
+ }
+ push("ident", sql.slice(i, j));
+ i = j; continue;
+ }
+ if (ch === "(") { push("block", "(…)"); depth++; i++; continue; }
+ if (ch === ")") { depth = Math.max(0, depth - 1); i++; continue; }
+ if (/[A-Za-z_\u0080-\uffff]/.test(ch)) {
+ let j = i + 1;
+ while (j < n && /[A-Za-z0-9_$.\u0080-\uffff]/.test(sql[j]!)) j++;
+ push("word", sql.slice(i, j), sql.slice(i, j).toUpperCase());
+ i = j; continue;
+ }
+ if (ch === ",") { push("punct", ","); i++; continue; }
+ i++;
+ }
+ if (statements > 1) throw fail("invalid_input", "One statement per call.", "Send each statement in its own data_sql call.");
+ return { tokens, end };
+}
+
+/** DuckDB 1.5 nests block comments: `/* a /* b *\/ c *\/` is one comment. */
+function blockCommentEnd(sql: string, start: number): number {
+ let depth = 0;
+ for (let i = start; i < sql.length - 1;) {
+ if (sql[i] === "/" && sql[i + 1] === "*") { depth++; i += 2; continue; }
+ if (sql[i] === "*" && sql[i + 1] === "/") { depth--; i += 2; if (!depth) return i; continue; }
+ i++;
+ }
+ throw fail("invalid_input", "Unterminated comment.");
+}
+
+/**
+ * DuckDB 1.5 reads backslash escapes in E'…' unless the E ends an identifier. After a digit the E may
+ * end a number (`1E'…'`), so a literal the two readings end in different places is refused.
+ */
+function stringEnd(sql: string, quote: number): number {
+ if (!/[eE]/.test(sql[quote - 1] ?? "")) return literalEnd(sql, quote, false);
+ const before = sql[quote - 2] ?? "";
+ if (!/[0-9]/.test(before)) return literalEnd(sql, quote, !/[A-Za-z_$\u0080-\uffff]/.test(before));
+ const end = literalEnd(sql, quote, false);
+ if (end !== literalEnd(sql, quote, true)) throw fail("invalid_input", "Put a space before E'…' so the string reads one way.");
+ return end;
+}
+
+/** DuckDB 1.5 joins 'a' and 'b' separated by a line break into one literal that keeps the first one's escapes. */
+const STRING_CONTINUES = /[ \t\f]*(?:--[^\n\r]*)?[\n\r](?:[ \t\n\r\f]|--[^\n\r]*[\n\r])*'/y;
+
+function literalEnd(sql: string, quote: number, escapes: boolean): number {
+ for (let j = quote + 1; j < sql.length; j++) {
+ if (escapes && sql[j] === "\\") { j++; continue; }
+ if (sql[j] !== "'") continue;
+ if (sql[j + 1] === "'") { j++; continue; }
+ STRING_CONTINUES.lastIndex = j + 1;
+ if (!STRING_CONTINUES.test(sql)) return j + 1;
+ j = STRING_CONTINUES.lastIndex - 1;
+ }
+ throw fail("invalid_input", "Unterminated string literal.");
+}
+
+export function queryRelation(sql: string): string {
+ const { end } = singleStatement(sql);
+ return `(${sql.slice(0, end)}\n)`;
+}
diff --git a/server/data/tools.test.ts b/server/data/tools.test.ts
index 313a2c3336..d5ed081532 100644
--- a/server/data/tools.test.ts
+++ b/server/data/tools.test.ts
@@ -483,7 +483,7 @@ describe("data_show", () => {
const card = sheet.card("c_1")!;
expect(card).toMatchObject({ status: "ready", result: "c_1", rowCount: 12, truncated: false, by: "bot", sql: "SELECT * FROM orders" });
expect(card.columns).toHaveLength(2);
- expect(database.calls.find((call) => call.method === "materialise")).toMatchObject({ sql: `SELECT * FROM (SELECT * FROM orders) LIMIT ${DATA_LIMITS.showTableRowsMax}`, name: "c_1" });
+ expect(database.calls.find((call) => call.method === "materialise")).toMatchObject({ sql: `SELECT * FROM (SELECT * FROM orders\n) LIMIT ${DATA_LIMITS.showTableRowsMax}`, name: "c_1" });
});
it("points a card at a loaded table through resolveTable", async () => {
@@ -605,8 +605,8 @@ describe("data_show", () => {
const card = sheet.card("c_1")!;
expect(card).toMatchObject({ kind: "chart", title: "bar of count by region", status: "ready", result: "c_1", chart: { type: "bar", x: "region" }, vegaLite: { mark: "bar", columns: ["region", "n"] } });
const materialised = database.calls.find((call) => call.method === "materialise")!;
- expect(materialised.sql).toBe("SELECT region, count(*) AS n FROM (SELECT * FROM orders) GROUP BY ALL");
- expect(database.calls.some((call) => call.sql === "SELECT * FROM (SELECT * FROM orders) LIMIT 0")).toBe(true);
+ expect(materialised.sql).toBe("SELECT region, count(*) AS n FROM (SELECT * FROM orders\n) GROUP BY ALL");
+ expect(database.calls.some((call) => call.sql === "SELECT * FROM (SELECT * FROM orders\n) LIMIT 0")).toBe(true);
database.onRun = (sql) => (sql.startsWith("SELECT count(*)") ? { columns: [{ name: "n", type: "BIGINT" }], rows: [[3]], rowCount: 1, truncated: false, elapsedMs: 1 } : undefined);
const whole = await showCard(ctx, { kind: "chart", sql: "SELECT * FROM small", chart: { type: "scatter", x: "a", y: "b" } });
expect(whole.reduction).toEqual({ method: "none", inputRows: 3, outputRows: 3 });
@@ -655,7 +655,7 @@ describe("data_show", () => {
const out = await showCard(ctx, { kind: "chart", sql: "SELECT a, b FROM t", vegaLite: { mark: "line" }, limit: 100 });
expect(out.reduction).toEqual({ method: "none", inputRows: 1234, outputRows: 3 });
expect(sheet.card("c_1")!.vegaLite).toEqual({ mark: "line", validated: true });
- expect(database.calls.find((call) => call.method === "materialise")!.sql).toBe("SELECT * FROM (SELECT a, b FROM t) LIMIT 101");
+ expect(database.calls.find((call) => call.method === "materialise")!.sql).toBe("SELECT * FROM (SELECT a, b FROM t\n) LIMIT 101");
expect(await failure(showCard(ctx, { kind: "chart", sql: "SELECT 1", vegaLite: { nope: true } }))).toMatchObject({ code: "spec_invalid" });
});
@@ -763,7 +763,7 @@ describe("data_export", () => {
expect(again.path).toBe(join(dir, "work", "paid_orders-2.csv"));
const parquet = await exportData(ctx, { sql: "SELECT 1 AS one", format: "parquet", path: "out/one" });
expect(parquet.path).toBe(join(dir, "work", "out", "one.parquet"));
- expect(database.calls.at(-1)!.sql).toBe(`COPY (SELECT * FROM (SELECT 1 AS one)) TO '${parquet.path}' (FORMAT parquet)`);
+ expect(database.calls.at(-1)!.sql).toBe(`COPY (SELECT * FROM (SELECT 1 AS one\n)) TO '${parquet.path}' (FORMAT parquet)`);
const xlsx = await exportData(ctx, { sql: "SELECT 1", format: "xlsx", path: join(dir, "Downloads") });
expect(xlsx.path).toBe(join(dir, "Downloads", "query.xlsx"));
expect(database.calls.at(-1)!.sql).toContain("(FORMAT xlsx, HEADER true)");
diff --git a/server/data/tools.ts b/server/data/tools.ts
index f5a7fe5779..622cdffd6c 100644
--- a/server/data/tools.ts
+++ b/server/data/tools.ts
@@ -19,6 +19,7 @@ import {
} from "../../shared/data-surface.ts";
import { compileToolSchema, schemaProblems } from "../mcp-schema-validator.ts";
import { tableIdentifierParts } from "./identifiers.ts";
+import { queryRelation, singleStatement, type Token } from "./sql-statements.ts";
import type { DataSheetStore } from "./sheet.ts";
import { DataFailure, type BotDatabase, type ChartCompiler, type ChartRenderer, type DataConnection, type DataExtension, type RunOptions, type RunResult, type VegaLiteValidator } from "./types.ts";
@@ -137,103 +138,6 @@ export const resultRelation = (name: string) => `${DATA_RESULTS_SCHEMA}.${quoteI
const fail = (code: DataErrorCode, message: string, extra: Partial<DataError> = {}): DataFailure =>
new DataFailure({ code, message, ...extra });
-type Token = { kind: "word" | "ident" | "punct" | "block"; text: string; raw: string };
-
-/** Top-level tokens, each parenthesised group one block; strings, comments and quoted identifiers never leak a keyword. */
-function topLevelTokens(sql: string): { tokens: Token[]; statements: number } {
- const tokens: Token[] = [];
- let statements = 1;
- let ended = false;
- let depth = 0;
- let i = 0;
- const n = sql.length;
- const push = (kind: Token["kind"], raw: string, text = raw) => { if (depth === 0) tokens.push({ kind, text, raw }); };
- while (i < n) {
- const ch = sql[i]!;
- const next = sql[i + 1];
- if (ch === "-" && next === "-") { const end = sql.slice(i).search(/[\n\r]/); i = end === -1 ? n : i + end + 1; continue; }
- if (ch === "/" && next === "*") { i = blockCommentEnd(sql, i); continue; }
- if (ch === ";") { ended = true; i++; continue; }
- if (ended && /\S/.test(ch)) { statements++; ended = false; }
- if (ch === "'") {
- push("word", "'…'");
- i = stringEnd(sql, i); continue;
- }
- if (ch === "$") {
- const delimiter = /\$(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?\$/y;
- delimiter.lastIndex = i;
- const open = delimiter.exec(sql)?.[0];
- if (open) {
- const end = sql.indexOf(open, i + open.length);
- if (end === -1) throw fail("invalid_input", "Unterminated dollar-quoted string.");
- push("word", "'…'");
- i = end + open.length; continue;
- }
- }
- if (ch === '"') {
- let j = i + 1;
- for (;;) {
- const q = sql.indexOf('"', j);
- if (q === -1) throw fail("invalid_input", "Unterminated quoted identifier.");
- if (sql[q + 1] === '"') { j = q + 2; continue; }
- j = q + 1; break;
- }
- push("ident", sql.slice(i, j));
- i = j; continue;
- }
- if (ch === "(") { push("block", "(…)"); depth++; i++; continue; }
- if (ch === ")") { depth = Math.max(0, depth - 1); i++; continue; }
- if (/[A-Za-z_\u0080-\uffff]/.test(ch)) {
- let j = i + 1;
- while (j < n && /[A-Za-z0-9_$.\u0080-\uffff]/.test(sql[j]!)) j++;
- push("word", sql.slice(i, j), sql.slice(i, j).toUpperCase());
- i = j; continue;
- }
- if (ch === ",") { push("punct", ","); i++; continue; }
- i++;
- }
- return { tokens, statements };
-}
-
-/** DuckDB 1.5 nests block comments: `/* a /* b *\/ c *\/` is one comment. */
-function blockCommentEnd(sql: string, start: number): number {
- let depth = 0;
- for (let i = start; i < sql.length - 1;) {
- if (sql[i] === "/" && sql[i + 1] === "*") { depth++; i += 2; continue; }
- if (sql[i] === "*" && sql[i + 1] === "/") { depth--; i += 2; if (!depth) return i; continue; }
- i++;
- }
- throw fail("invalid_input", "Unterminated comment.");
-}
-
-/**
- * DuckDB 1.5 reads backslash escapes in E'…' unless the E ends an identifier. After a digit the E may
- * end a number (`1E'…'`), so a literal the two readings end in different places is refused.
- */
-function stringEnd(sql: string, quote: number): number {
- if (!/[eE]/.test(sql[quote - 1] ?? "")) return literalEnd(sql, quote, false);
- const before = sql[quote - 2] ?? "";
- if (!/[0-9]/.test(before)) return literalEnd(sql, quote, !/[A-Za-z_$\u0080-\uffff]/.test(before));
- const end = literalEnd(sql, quote, false);
- if (end !== literalEnd(sql, quote, true)) throw fail("invalid_input", "Put a space before E'…' so the string reads one way.");
- return end;
-}
-
-/** DuckDB 1.5 joins 'a' and 'b' separated by a line break into one literal that keeps the first one's escapes. */
-const STRING_CONTINUES = /[ \t\f]*(?:--[^\n\r]*)?[\n\r](?:[ \t\n\r\f]|--[^\n\r]*[\n\r])*'/y;
-
-function literalEnd(sql: string, quote: number, escapes: boolean): number {
- for (let j = quote + 1; j < sql.length; j++) {
- if (escapes && sql[j] === "\\") { j++; continue; }
- if (sql[j] !== "'") continue;
- if (sql[j + 1] === "'") { j++; continue; }
- STRING_CONTINUES.lastIndex = j + 1;
- if (!STRING_CONTINUES.test(sql)) return j + 1;
- j = STRING_CONTINUES.lastIndex - 1;
- }
- throw fail("invalid_input", "Unterminated string literal.");
-}
-
const READ_VERBS = new Set(["SELECT", "WITH", "FROM", "PIVOT", "UNPIVOT", "VALUES", "SUMMARIZE", "DESCRIBE", "EXPLAIN", "SHOW"]);
const MATERIALISABLE = new Set(["SELECT", "WITH", "FROM", "PIVOT", "UNPIVOT", "VALUES"]);
@@ -248,8 +152,7 @@ const REPARSED_SPACES = /[\u00a0\u2000-\u200b\u202f\u205f\u2060\u3000\ufeff]/;
export function classifySql(sql: string): SqlClass {
if (REPARSED_SPACES.test(sql)) throw fail("invalid_input", "Replace non-ASCII spaces with plain spaces.", { hint: "In a string, write chr(160) and similar instead." });
- const { tokens, statements } = topLevelTokens(sql);
- if (statements > 1) throw fail("invalid_input", "One statement per call.", { hint: "Send each statement in its own data_sql call." });
+ const { tokens } = singleStatement(sql);
if (!tokens.length || tokens[0]!.kind !== "word") throw fail("invalid_input", "The statement is empty.");
return classifyTokens(tokens);
}
@@ -632,7 +535,7 @@ export async function describeTarget(ctx: DataContext, target: string): Promise<
const kind = gateSql(target);
if (kind.kind !== "read" || !kind.materialisable) throw fail("invalid_input", "Describe takes a table name or a SELECT.", { sql: target });
sql = target;
- relation = `(${target})`;
+ relation = queryRelation(target);
}
const described = await ctx.database.describe(relation, runOptions(ctx));
const { columns, truncated } = boundColumns(described.columns, DATA_LIMITS.describeBytesMax);
@@ -777,7 +680,7 @@ export async function showCard(context: DataContext, input: ShowInput, onCardRea
if (input.sql) {
const kind = gateSql(input.sql);
if (kind.kind !== "read" || !kind.materialisable) throw fail("invalid_input", "A card shows a SELECT's result.", { sql: input.sql });
- from = `(${input.sql})`;
+ from = queryRelation(input.sql);
} else {
from = await ctx.database.resolveTable(input.table!);
cardSql = `SELECT * FROM ${from}`;
@@ -941,7 +844,7 @@ export async function exportData(ctx: DataContext, input: ExportInput): Promise<
let stem: string;
if (card) {
if (card.result) relation = resultRelation(card.result);
- else if (card.sql) relation = `(${card.sql})`;
+ else if (card.sql) relation = queryRelation(card.sql);
else throw fail("invalid_input", `${card.id} has no data to export.`);
stem = card.title;
} else if (input.table) {
@@ -950,7 +853,7 @@ export async function exportData(ctx: DataContext, input: ExportInput): Promise<
} else {
const kind = gateSql(input.sql!);
if (kind.kind !== "read" || !kind.materialisable) throw fail("invalid_input", "Export takes a SELECT.", { sql: input.sql });
- relation = `(${input.sql})`;
+ relation = queryRelation(input.sql!);
stem = "query";
}
const format = input.format === "csv" ? "FORMAT csv, HEADER true" : input.format === "xlsx" ? "FORMAT xlsx, HEADER true" : "FORMAT parquet";