Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(data): preserve tables with colliding import names
Afloatd27758e5120c
diff --git a/server/data/load-table-name-collisions.test.ts b/server/data/load-table-name-collisions.test.tsnew file mode 100644index 0000000000..7a2ef10ee5--- /dev/null+++ b/server/data/load-table-name-collisions.test.ts@@ -0,0 +1,96 @@+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { chartRenderer, compileChart, validateVegaLite } from "./deps.ts";+import { createDataEngine, quoteIdentifier } from "./engine.ts";+import { DataSheetStore } from "./sheet.ts";+import { loadData, type DataContext } from "./tools.ts";++const root = mkdtempSync(join(tmpdir(), "omb-load-name-collisions-"));+const folder = join(root, "mixed");+const engine = createDataEngine({ botFolder: (id) => join(root, "bots", id), dataDir: join(root, "data") });+const connection = "bot" as const;++beforeAll(async () => {+ mkdirSync(folder);+ writeFileSync(join(folder, "first.csv"), "origin,value\ncsv,1\n");+ writeFileSync(join(folder, "second.json"), JSON.stringify([{ origin: "json", value: 2 }]));+ const writer = await engine.forBot("writer");+ await writer.run(`COPY (SELECT 'parquet' AS origin, 3 AS value) TO '${join(folder, "third.parquet").replaceAll("'", "''")}' (FORMAT PARQUET)`, { connection });+});++afterAll(async () => {+ await engine.closeAll();+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+});++async function context(botId: string): Promise<DataContext> {+ return {+ database: await engine.forBot(botId),+ sheet: new DataSheetStore({ botId, dir: join(root, "sheets", botId) }),+ renderer: chartRenderer,+ compileChart,+ validateVegaLite,+ exportRoots: () => [root],+ signal: new AbortController().signal,+ connection,+ by: "bot",+ };+}++async function expectAllSources(ctx: DataContext, tables: Array<{ name: string }>) {+ expect(new Set(tables.map((table) => table.name)).size).toBe(3);+ const rows = [];+ for (const table of tables) {+ expect(table.name.length).toBeLessThanOrEqual(63);+ const result = await ctx.database.run(`SELECT origin, value FROM ${quoteIdentifier(table.name)}`, { connection });+ rows.push(...result.rows.map(([origin, value]) => [origin, Number(value)]));+ }+ expect(rows).toEqual(expect.arrayContaining([["csv", 1], ["json", 2], ["parquet", 3]]));+ expect(rows).toHaveLength(3);+}++describe("distinct table names within one import", () => {+ it.each([62, 63])("keeps every file family when a %i-character prefix truncates their names", async (length) => {+ const ctx = await context(`long-${length}`);+ const result = await loadData(ctx, { source: folder, name: "t".repeat(length) });+ await expectAllSources(ctx, result.tables);+ expect(await ctx.database.listTables()).toHaveLength(3);+ expect(ctx.sheet.sheet().sources).toHaveLength(3);++ const reloaded = await loadData(ctx, { source: folder, name: "t".repeat(length), replace: true });+ expect(reloaded.tables.map((table) => table.name)).toEqual(result.tables.map((table) => table.name));+ await expectAllSources(ctx, reloaded.tables);+ expect(await ctx.database.listTables()).toHaveLength(3);+ });++ it("keeps a pre-existing long name when replacement is disabled", async () => {+ const ctx = await context("no-replacement");+ const name = "t".repeat(63);+ await ctx.database.run(`CREATE TABLE ${quoteIdentifier(name)} AS SELECT 'existing' AS origin, 99 AS value`, { connection });+ const result = await loadData(ctx, { source: folder, name, replace: false });+ await expectAllSources(ctx, result.tables);+ expect(await ctx.database.listTables()).toHaveLength(4);+ expect((await ctx.database.run(`SELECT origin, value FROM ${quoteIdentifier(name)}`, { connection })).rows).toEqual([["existing", 99]]);+ });++ it("still replaces a requested existing table on a single-file import", async () => {+ const ctx = await context("single-file");+ await ctx.database.run("CREATE TABLE imported AS SELECT 'existing' AS origin, 99 AS value", { connection });+ const result = await loadData(ctx, { source: join(folder, "first.csv"), name: "imported" });+ expect(result.tables.map((table) => table.name)).toEqual(["imported"]);+ expect(await ctx.database.listTables()).toHaveLength(1);+ const rows = await ctx.database.run("SELECT origin, value FROM imported", { connection });+ expect(rows.rows.map(([origin, value]) => [origin, Number(value)])).toEqual([["csv", 1]]);+ });++ it("keeps the usual names when the file-family suffixes fit", async () => {+ const ctx = await context("short-prefix");+ const result = await loadData(ctx, { source: folder, name: "mixed" });+ expect(new Set(result.tables.map((table) => table.name))).toEqual(new Set(["mixed_csv", "mixed_json", "mixed_parquet"]));+ await expectAllSources(ctx, result.tables);+ });+});diff --git a/server/data/tools.ts b/server/data/tools.tsindex f5a7fe5779..ebf9184aa9 100644--- a/server/data/tools.ts+++ b/server/data/tools.ts@@ -558,14 +558,14 @@ export async function loadData(ctx: DataContext, input: LoadInput): Promise<Loadconst plans = planLoad(input);const replace = input.replace !== false;const existing = new Set((await ctx.database.listTables()).map((table) => table.name.toLowerCase()));+ const tables: LoadedTable[] = [];const unique = (base: string): string => {const stem = tableNameFrom(base);let name = stem;- for (let n = 2; !replace && existing.has(name.toLowerCase()); n++) name = `${stem.slice(0, 62 - String(n).length)}_${n}`;- existing.add(name.toLowerCase());+ for (let n = 2; tables.some((table) => table.name === name) || (!replace && existing.has(name)); n++) name = `${stem.slice(0, 62 - String(n).length)}_${n}`;+ existing.add(name);return name;};- const tables: LoadedTable[] = [];const warnings: string[] = [];const create = async (name: string, relation: string, plan: LoadPlan, options: Record<string, string | number | boolean>) => {const sql = `CREATE ${replace ? "OR REPLACE " : ""}TABLE ${quoteIdent(name)} AS SELECT * FROM ${relation}`;