|
| 1 | +// SPDX-License-Identifier: MPL-2.0 |
| 2 | +// db-theory #1c — Node ESM harness for the Sqlite schema-introspection + |
| 3 | +// bulk-I/O + error-inspection codegen smoke. |
| 4 | +// |
| 5 | +// Extends the #1a/#1b mock adapter with `schemaTables`, `schemaColumns`, |
| 6 | +// `tableExists`, `importCsv`, `exportCsv`, `lastError`. The csv methods |
| 7 | +// here use a virtual filesystem map keyed by path so the smoke runs |
| 8 | +// hermetically (no real disk I/O); production adapters back the same |
| 9 | +// methods with `Deno.readTextFileSync` / `fs.writeFileSync`. |
| 10 | + |
| 11 | +import assert from "node:assert/strict"; |
| 12 | + |
| 13 | +let nextDbHandle = 1; |
| 14 | +const dbs = new Map(); |
| 15 | +const vfs = new Map(); // path -> string contents |
| 16 | +const errors = new Map(); // db handle -> last error message |
| 17 | + |
| 18 | +const parseRowLiteral = (s) => { |
| 19 | + const out = []; |
| 20 | + let buf = ""; |
| 21 | + let inStr = false; |
| 22 | + for (const ch of s) { |
| 23 | + if (ch === "'") { inStr = !inStr; buf += ch; } |
| 24 | + else if (ch === "," && !inStr) { out.push(buf.trim()); buf = ""; } |
| 25 | + else buf += ch; |
| 26 | + } |
| 27 | + if (buf.trim()) out.push(buf.trim()); |
| 28 | + return out.map((t) => ( |
| 29 | + t.startsWith("'") && t.endsWith("'") ? t.slice(1, -1) : |
| 30 | + /^-?\d+$/.test(t) ? Number(t) : |
| 31 | + t |
| 32 | + )); |
| 33 | +}; |
| 34 | + |
| 35 | +globalThis.__as_sqlite = { |
| 36 | + open(path) { |
| 37 | + const h = nextDbHandle++; |
| 38 | + dbs.set(h, { path, tables: new Map(), schema: new Map() }); |
| 39 | + errors.set(h, ""); |
| 40 | + return h; |
| 41 | + }, |
| 42 | + close(h) { dbs.delete(h); errors.delete(h); }, |
| 43 | + |
| 44 | + execute(h, sql) { |
| 45 | + const db = dbs.get(h); |
| 46 | + if (!db) throw new Error("invalid db handle " + h); |
| 47 | + |
| 48 | + // Fault-injection convention for the smoke: a literal SQL string |
| 49 | + // starting with `RAISE` records a last-error and returns without |
| 50 | + // throwing, so the smoke can validate the read-back path. |
| 51 | + if (/^\s*RAISE\s+'(.+)'\s*$/i.test(sql)) { |
| 52 | + const m = sql.match(/^\s*RAISE\s+'(.+)'\s*$/i); |
| 53 | + errors.set(h, m[1]); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + const create = sql.match(/CREATE TABLE (\w+)\s*\(([^)]+)\)/i); |
| 58 | + if (create) { |
| 59 | + const cols = create[2].split(",").map((c) => { |
| 60 | + const parts = c.trim().split(/\s+/); |
| 61 | + return { name: parts[0], type: parts[1] || "" }; |
| 62 | + }); |
| 63 | + db.tables.set(create[1], []); |
| 64 | + db.schema.set(create[1], cols); |
| 65 | + errors.set(h, ""); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + const insert = sql.match(/INSERT INTO (\w+)\s+VALUES\s+(.+)/i); |
| 70 | + if (insert) { |
| 71 | + const tableName = insert[1]; |
| 72 | + const valuesPart = insert[2].replace(/;$/, "").trim(); |
| 73 | + const tupleRe = /\(([^)]+)\)/g; |
| 74 | + let m; |
| 75 | + while ((m = tupleRe.exec(valuesPart))) { |
| 76 | + const cols = parseRowLiteral(m[1]); |
| 77 | + const tbl = db.tables.get(tableName); |
| 78 | + if (!tbl) { errors.set(h, "no such table " + tableName); throw new Error(errors.get(h)); } |
| 79 | + tbl.push(cols); |
| 80 | + } |
| 81 | + errors.set(h, ""); |
| 82 | + } |
| 83 | + }, |
| 84 | + |
| 85 | + // ── Schema introspection ────────────────────────────────────────── |
| 86 | + |
| 87 | + schemaTables(h) { |
| 88 | + const db = dbs.get(h); |
| 89 | + if (!db) return "[]"; |
| 90 | + const names = [...db.tables.keys()].filter((n) => !n.startsWith("sqlite_")); |
| 91 | + return JSON.stringify(names); |
| 92 | + }, |
| 93 | + |
| 94 | + schemaColumns(h, table) { |
| 95 | + const db = dbs.get(h); |
| 96 | + if (!db) return "[]"; |
| 97 | + const cols = db.schema.get(table); |
| 98 | + if (!cols) return "[]"; |
| 99 | + return JSON.stringify(cols.map((c, i) => ({ |
| 100 | + name: c.name, |
| 101 | + type: c.type, |
| 102 | + notnull: false, |
| 103 | + pk: i === 0 && /id/i.test(c.name), |
| 104 | + }))); |
| 105 | + }, |
| 106 | + |
| 107 | + tableExists(h, table) { |
| 108 | + const db = dbs.get(h); |
| 109 | + if (!db) return false; |
| 110 | + return db.tables.has(table) && !table.startsWith("sqlite_"); |
| 111 | + }, |
| 112 | + |
| 113 | + // ── Bulk I/O ────────────────────────────────────────────────────── |
| 114 | + |
| 115 | + importCsv(h, table, csvPath, hasHeader) { |
| 116 | + const db = dbs.get(h); |
| 117 | + if (!db) { errors.set(h, "invalid handle"); return 0; } |
| 118 | + const text = vfs.get(csvPath); |
| 119 | + if (text == null) { errors.set(h, "no such csv " + csvPath); return 0; } |
| 120 | + const tbl = db.tables.get(table); |
| 121 | + if (!tbl) { errors.set(h, "no such table " + table); return 0; } |
| 122 | + const cols = db.schema.get(table) || []; |
| 123 | + const lines = text.split(/\r?\n/).filter((l) => l.length > 0); |
| 124 | + const data = hasHeader ? lines.slice(1) : lines; |
| 125 | + let inserted = 0; |
| 126 | + for (const line of data) { |
| 127 | + const fields = line.split(",").map((f) => { |
| 128 | + const t = f.trim(); |
| 129 | + return /^-?\d+$/.test(t) ? Number(t) : t; |
| 130 | + }); |
| 131 | + // Pad/truncate to schema width. |
| 132 | + while (fields.length < cols.length) fields.push(null); |
| 133 | + tbl.push(fields.slice(0, cols.length)); |
| 134 | + inserted++; |
| 135 | + } |
| 136 | + errors.set(h, ""); |
| 137 | + return inserted; |
| 138 | + }, |
| 139 | + |
| 140 | + exportCsv(h, sql, params, csvPath) { |
| 141 | + const db = dbs.get(h); |
| 142 | + if (!db) { errors.set(h, "invalid handle"); return 0; } |
| 143 | + const tblMatch = sql.match(/FROM\s+(\w+)/i); |
| 144 | + if (!tblMatch) { errors.set(h, "no FROM in sql"); return 0; } |
| 145 | + const table = tblMatch[1]; |
| 146 | + const rows = db.tables.get(table) || []; |
| 147 | + const schema = db.schema.get(table) || []; |
| 148 | + const header = schema.map((c) => c.name).join(","); |
| 149 | + const body = rows.map((r) => r.map((v) => v == null ? "" : String(v)).join(",")).join("\n"); |
| 150 | + vfs.set(csvPath, header + "\n" + body + "\n"); |
| 151 | + errors.set(h, ""); |
| 152 | + return rows.length; |
| 153 | + }, |
| 154 | + |
| 155 | + lastError(h) { return errors.get(h) ?? ""; }, |
| 156 | + |
| 157 | + // Convenience surface methods present from the #1a/#1b mock — not |
| 158 | + // exercised in this smoke but kept for future stack-on harnesses. |
| 159 | + query() { return []; }, |
| 160 | + queryOne() { return null; }, |
| 161 | + queryInt() { return 0; }, |
| 162 | + prepare() { throw new Error("prepare not used in this smoke"); }, |
| 163 | + bindInt() {}, bindText() {}, bindNull() {}, |
| 164 | + step() { return false; }, |
| 165 | + columnCount() { return 0; }, |
| 166 | + columnInt() { return 0; }, |
| 167 | + columnText() { return ""; }, |
| 168 | + reset() {}, finalize() {}, |
| 169 | +}; |
| 170 | + |
| 171 | +const mod = await import("./sqlite_introspect_bulk.deno.js"); |
| 172 | + |
| 173 | +// ── schema_tables ──────────────────────────────────────────────────── |
| 174 | +const tablesJson = mod.smoke_schema_tables(":memory:"); |
| 175 | +const tables = JSON.parse(tablesJson); |
| 176 | +assert.deepEqual( |
| 177 | + tables.sort(), |
| 178 | + ["posts", "users"], |
| 179 | + "smoke_schema_tables: returns the two created tables (sqlite_* excluded)", |
| 180 | +); |
| 181 | + |
| 182 | +// ── schema_columns ────────────────────────────────────────────────── |
| 183 | +const colsJson = mod.smoke_schema_columns(":memory:"); |
| 184 | +const cols = JSON.parse(colsJson); |
| 185 | +assert.equal(cols.length, 3, "smoke_schema_columns: 3 columns parsed"); |
| 186 | +assert.equal(cols[0].name, "id", "first column is id"); |
| 187 | +assert.equal(cols[0].pk, true, "id column flagged as PK"); |
| 188 | +assert.equal(cols[1].name, "name", "second column is name"); |
| 189 | +assert.equal(cols[2].name, "age", "third column is age"); |
| 190 | + |
| 191 | +// ── table_exists ──────────────────────────────────────────────────── |
| 192 | +assert.equal(mod.smoke_table_exists_true(":memory:"), true, "present table: exists=true"); |
| 193 | +assert.equal(mod.smoke_table_exists_false(":memory:"), false, "absent table: exists=false"); |
| 194 | + |
| 195 | +// ── import_csv ────────────────────────────────────────────────────── |
| 196 | +vfs.set("/tmp/in.csv", "a,b\n1,alpha\n2,beta\n3,gamma\n"); |
| 197 | +const inserted = mod.smoke_import_csv(":memory:", "rows", "/tmp/in.csv"); |
| 198 | +assert.equal(inserted, 3, "smoke_import_csv: 3 data rows imported (header skipped)"); |
| 199 | + |
| 200 | +// ── export_csv ────────────────────────────────────────────────────── |
| 201 | +const exported = mod.smoke_export_csv(":memory:", "SELECT a, b FROM rows", "[]", "/tmp/out.csv"); |
| 202 | +assert.equal(exported, 3, "smoke_export_csv: 3 rows exported"); |
| 203 | +const out = vfs.get("/tmp/out.csv"); |
| 204 | +assert.ok(out.startsWith("a,b\n"), "exported CSV starts with column header"); |
| 205 | +assert.ok(out.includes("1,one"), "exported CSV contains first row"); |
| 206 | +assert.ok(out.includes("3,three"), "exported CSV contains third row"); |
| 207 | + |
| 208 | +// ── last_error ────────────────────────────────────────────────────── |
| 209 | +assert.equal(mod.smoke_last_error_empty(":memory:"), "", "smoke_last_error_empty: returns ''"); |
| 210 | +assert.equal( |
| 211 | + mod.smoke_last_error_set(":memory:"), |
| 212 | + "simulated failure", |
| 213 | + "smoke_last_error_set: fault-injected message round-trips", |
| 214 | +); |
| 215 | + |
| 216 | +console.log("sqlite_introspect_bulk OK"); |
0 commit comments