Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: recognize quoted table references when describing data
Afloatb3d847d88412
diff --git a/server/data/engine.test.ts b/server/data/engine.test.tsindex 36297b6feb..e4acfe26fb 100644--- a/server/data/engine.test.ts+++ b/server/data/engine.test.ts@@ -8,7 +8,7 @@ import type { DuckDBConnection } from "@duckdb/node-api";import { afterAll, describe, expect, it, vi } from "vitest";import { DATA_LIMITS, DATA_RESULTS_SCHEMA } from "../../shared/data-surface.ts";-import { CLOSE_DRAIN_MS, EXTENSION_INSTALL_TIMEOUT_MS, Lane, closeNames, createDataEngine, dataEngine, drainLanes, duckdbDirectory, instanceSettings, levenshtein, likePattern, loadExtensions, type DataEngineOptions } from "./engine.ts";+import { CLOSE_DRAIN_MS, EXTENSION_INSTALL_TIMEOUT_MS, Lane, closeNames, createDataEngine, dataEngine, drainLanes, duckdbDirectory, instanceSettings, levenshtein, likePattern, loadExtensions, quoteIdentifier, type DataEngineOptions } from "./engine.ts";import { DataFailure, type BotDatabase, type DataEngine } from "./types.ts";const root = mkdtempSync(join(tmpdir(), "omb-data-engine-"));@@ -367,6 +367,19 @@ describe("a bot's database", () => {expect(query.columns[0]).toMatchObject({ name: "id", max: "9" });});+ it.each(["分析", "report/2026", 'Revenue "USD"', "select from report", " padded "])("describes a quoted table named %j without treating its name as SQL", async (name) => {+ await ready;+ await db.run(`CREATE TABLE ${quoteIdentifier(name)} AS SELECT 17 AS amount`, bot);+ const described = await db.describe(`main . ${quoteIdentifier(name)}`, bot);+ expect(described).toMatchObject({ rowCount: 1, columns: [{ name: "amount", min: "17", max: "17" }] });+ });++ it("still describes an existing unquoted display name with spaces", async () => {+ await ready;+ await db.run('CREATE TABLE "Old display name" AS SELECT 19 AS amount', bot);+ expect(await db.describe("Old display name", bot)).toMatchObject({ rowCount: 1, columns: [{ name: "amount", min: "19" }] });+ });+it("profiles at most describeColumnsMax columns and lists the rest by type only", async () => {await ready;const wide = Array.from({ length: DATA_LIMITS.describeColumnsMax + 5 }, (_, i) => `${i} AS c${i}`).join(", ");diff --git a/server/data/engine.ts b/server/data/engine.tsindex d7d873c10c..95c1936f0f 100644--- a/server/data/engine.ts+++ b/server/data/engine.ts@@ -10,6 +10,7 @@ import type * as DuckDB from "@duckdb/node-api";import { DATA_LIMITS, DATA_RESULTS_SCHEMA } from "../../shared/data-surface.ts";import { botFolder as defaultBotFolder } from "../bot-folder.ts";import { DATA_DIR } from "../config.ts";+import { tableIdentifierParts } from "./identifiers.ts";import {DataFailure,type BotDatabase,@@ -450,7 +451,7 @@ class BotDb implements BotDatabase {}private async lookup(name: string): Promise<CatalogEntry> {- const parts = this.splitIdentifier(name.trim()).slice(-2);+ const parts = (tableIdentifierParts(name) ?? this.splitIdentifier(name.trim())).slice(-2);const table = parts[parts.length - 1];const schema = parts.length === 2 ? parts[0] : null;if (!table) throw new DataFailure({ code: "invalid_input", message: "A table name is required." });@@ -519,8 +520,10 @@ class BotDb implements BotDatabase {private async source(target: string): Promise<string> {const text = target.trim().replace(/;+\s*$/, "");- const looksLikeName = /^[\w."$ -]+$/.test(text) && !/\s(?:from|select|with|values)\s/i.test(text) && !/^(?:select|with|from|values|pivot|unpivot|show|describe)\b/i.test(text);- if (looksLikeName) return this.resolveTable(text);+ // Keep accepting the display names callers could pass before quoted SQL+ // identifiers were recognized here (for example, Order Items).+ const displayName = /^[\w."$ -]+$/.test(text) && !/\s(?:from|select|with|values)\s/i.test(text) && !/^(?:select|with|from|values|pivot|unpivot|show|describe)\b/i.test(text);+ if (tableIdentifierParts(text) || displayName) return this.resolveTable(text);return `(${text}) AS omb_described`;}diff --git a/server/data/identifiers.test.ts b/server/data/identifiers.test.tsnew file mode 100644index 0000000000..1d84f0aa09--- /dev/null+++ b/server/data/identifiers.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";+import { tableIdentifierParts } from "./identifiers.ts";++describe("table identifier parts", () => {+ it.each([+ ["sales", ["sales"]],+ [" café ", ["café"]],+ [' main . " 分析 " ', ["main", " 分析 "]],+ ['"catalog.name"."schema"."x""y"', ["catalog.name", "schema", 'x"y']],+ ['" select from x "', [" select from x "]],+ ['"line\nbreak"', ["line\nbreak"]],+ ] as const)("preserves the meaning of %j", (input, expected) => {+ expect(tableIdentifierParts(input)).toEqual(expected);+ });++ it.each(["", '""', '"unfinished', "main.", "main. ", "a..b", "a.b.c.d", '"name"suffix', "SELECT * FROM t", "(SELECT 1)", "x; SELECT 1", "read_csv('x')"])("does not classify %j as a table identifier", (input) => {+ expect(tableIdentifierParts(input)).toBeNull();+ });+});diff --git a/server/data/identifiers.ts b/server/data/identifiers.tsnew file mode 100644index 0000000000..3322b9c1f2--- /dev/null+++ b/server/data/identifiers.ts@@ -0,0 +1,31 @@+/** A table reference, not a SQL expression. Quoted parts keep their exact spaces and doubled quotes. */+export function tableIdentifierParts(input: string): string[] | null {+ const text = input.trim();+ const parts: string[] = [];+ let at = 0;+ while (at < text.length && parts.length < 3) {+ while (/\s/.test(text[at] ?? "")) at++;+ let part = "";+ if (text[at] === '"') {+ at++;+ let closed = false;+ while (at < text.length) {+ const char = text[at++]!;+ if (char !== '"') part += char;+ else if (text[at] === '"') { part += '"'; at++; }+ else { closed = true; break; }+ }+ if (!closed || !part) return null;+ } else {+ const match = /^[\p{L}_][\p{L}\p{M}\p{N}_$]*/u.exec(text.slice(at));+ if (!match) return null;+ part = match[0];+ at += part.length;+ }+ parts.push(part);+ while (/\s/.test(text[at] ?? "")) at++;+ if (at === text.length) return parts;+ if (text[at++] !== "." || at === text.length) return null;+ }+ return null;+}diff --git a/server/data/tools.test.ts b/server/data/tools.test.tsindex fc7a3b2d73..c1d4f9fabc 100644--- a/server/data/tools.test.ts+++ b/server/data/tools.test.ts@@ -330,6 +330,19 @@ describe("data_load", () => {});describe("data_describe saved results", () => {+ it.each(['"Revenue ""USD"""', ' main . "分析" ', "café"])("routes identifier %j to catalog resolution", async (target) => {+ const { ctx, database } = context();+ database.resolveTable = async (name) => {+ database.calls.push({ method: "resolveTable", target: name });+ return "main.resolved";+ };+ const result = await runDataTool(ctx, "data_describe", { target });+ expect(result.isError).toBeUndefined();+ expect(database.calls.map((call) => call.method)).toEqual(["resolveTable", "describe"]);+ expect(result.structuredContent).toHaveProperty("name");+ expect(result.structuredContent).not.toHaveProperty("sql");+ });+it("reads the latest saved SQL after a person edits it, without rerunning queries", async () => {const { ctx, database, sheet } = context();await showCard(ctx, { kind: "table", sql: "SELECT 1", title: "First" });diff --git a/server/data/tools.ts b/server/data/tools.tsindex d61f3aef19..405a3da4a3 100644--- a/server/data/tools.ts+++ b/server/data/tools.ts@@ -18,6 +18,7 @@ import {type OmbChartSpec,} from "../../shared/data-surface.ts";import { compileToolSchema, schemaProblems } from "../mcp-schema-validator.ts";+import { tableIdentifierParts } from "./identifiers.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";@@ -609,8 +610,6 @@ export async function loadData(ctx: DataContext, input: LoadInput): Promise<Loadreturn { tables, warnings, elapsedMs: Date.now() - started };}-const IDENTIFIER_LIKE = /^\s*("[^"]+"|[A-Za-z_][\w$]*)(\.("[^"]+"|[A-Za-z_][\w$]*)){0,2}\s*$/;-export interface DescribeOutput { name?: string; sql?: string; rowCount: number; columns: DataColumn[]; truncated?: boolean; elapsedMs: number }export async function describeTarget(ctx: DataContext, target: string): Promise<DescribeOutput> {@@ -618,7 +617,7 @@ export async function describeTarget(ctx: DataContext, target: string): Promise<let relation: string;let name: string | undefined;let sql: string | undefined;- if (IDENTIFIER_LIKE.test(target)) {+ if (tableIdentifierParts(target)) {name = await ctx.database.resolveTable(target.trim());relation = name;} else {