Public: anyone can read this; the crew can change it.

A `.sql` file in a repository opens as its schema: each CREATE TABLE as its columns, other statements one per row #11196

Closed opened this
Closed without merging

mason/forge:mason/11187-a-sql-file-in-a-repository-opens-as-its → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +388 −0
docs/design/areas/render.md +4
@@ -47,3 +47,7 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis
4747 ## OpenAPI operations (openapi.json, *.openapi.yaml)
4848
4949 `src/web/render/openapi.ts` draws one `h3` per tag and under it one existing `.table` (`data-dense`) of method, path, summary and a `deprecated` mark; the cap line is a `muted small` paragraph. `.openapi-view` is only a hook on the wrapper and has no rule. How it works: `docs/features/file-openapi.md`.
50
51 ## SQL schema (*.sql)
52
53 `src/web/render/sql.ts` draws, per statement, either an `h3` with the table name and one existing `.table` (`data-dense`) of its columns, or a one-row `.table` with the statement's first line. `.sql-view` is only a hook on the wrapper and has no rule. How it works: `docs/features/file-sql.md`.
docs/features/file-sql.md added +12
@@ -0,0 +1,12 @@
1 # A `.sql` file opens as its schema
2
3 A file ending `.sql` opens as one block per statement instead of raw text. Source is one tap away (`?view=source`).
4
5 - **`CREATE TABLE`:** the table name, then a row per column: **name**, **type**, **NOT NULL**, **PRIMARY KEY** and **DEFAULT** (`—` when absent). A table-level `PRIMARY KEY (a, b)` marks those columns. Other table-level constraints (`FOREIGN KEY`, `UNIQUE`, `CHECK`) are listed under the table.
6 - **Anything else** (`CREATE INDEX`, `ALTER TABLE`, `INSERT` …): one row with the statement's first line.
7 - **Comments** (`-- …`, `/* … */`) are not statements; a `;` inside a quote or comment does not end one.
8 - **Cannot be read:** a file with no recognisable statement, or an unterminated quote or comment, shows Source with the reason, never an error. A `CREATE TABLE` it cannot parse is one row like any other statement.
9 - **Cap:** at most 500 statements and 500 columns a table, then `N more not shown`. Files over 1 MB keep Source.
10 - Every name is escaped and the page is drawn on the server. No script, no new CSS (`.sql-view` is a hook with no rule).
11
12 Code: `src/web/render/sql.ts`, `src/web/render/kinds.ts`. Tests: `test/render-sql.test.ts`.
src/web/render/kinds.ts +3
@@ -42,6 +42,7 @@ export type FileKind =
4242 | "junit"
4343 | "env"
4444 | "openapi"
45 | "sql"
4546 | "text"
4647 | "binary";
4748
@@ -82,6 +83,7 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
8283 junit: 5 * MB,
8384 env: 1 * MB,
8485 openapi: 1 * MB,
86 sql: 1 * MB,
8587 text: 1 * MB,
8688 binary: 0,
8789 };
@@ -205,6 +207,7 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
205207 gco: "gcode",
206208 sarif: "sarif",
207209 lcov: "lcov",
210 sql: "sql",
208211 };
209212
210213 /** The three example names; a plain `.env` is never one. */
src/web/render/renderers.ts +2
@@ -11,6 +11,7 @@ import { audio } from "./audio.ts";
1111 import { config } from "./config.ts";
1212 import { isFormConfig } from "./config-format.ts";
1313 import { envView } from "./env.ts";
14 import { sqlView } from "./sql.ts";
1415 import { eml } from "./eml.ts";
1516 import { csv } from "./csv.ts";
1617 import { geojson } from "./geojson.ts";
@@ -100,6 +101,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
100101 lcov,
101102 junit,
102103 env: envView,
104 sql: sqlView,
103105 openapi,
104106 mail: eml,
105107 archive,
src/web/render/sql.ts added +276
@@ -0,0 +1,276 @@
1 /**
2 * A `.sql` file as its schema: one block per statement. A `CREATE TABLE` shows
3 * the table name and a row per column (name, type, NOT NULL / PRIMARY KEY /
4 * DEFAULT); every other statement is one row with its first line.
5 * The reader is its own and small: it splits on `;` outside quotes, comments
6 * and parentheses, and reads column definitions at the table's top level.
7 * A file with no statement it can recognise, or an unterminated quote or
8 * comment, is not drawn: the source view shows with the reason.
9 * Every name is escaped by the template; at most `ROW_CAP` statements are drawn.
10 */
11
12 import { html, type Html } from "../html.ts";
13 import { fileSize } from "../ui.ts";
14 import type { Rendered, RenderInput } from "./renderers.ts";
15
16 export const ROW_CAP = 500;
17 const COLUMN_CAP = 500;
18 const LINE_CAP = 200;
19
20 export interface SqlColumn {
21 readonly name: string;
22 readonly type: string;
23 readonly notNull: boolean;
24 readonly primaryKey: boolean;
25 readonly default: string;
26 }
27
28 export type SqlStatement =
29 | { readonly kind: "table"; readonly name: string; readonly columns: readonly SqlColumn[]; readonly extras: readonly string[] }
30 | { readonly kind: "other"; readonly line: string };
31
32 export interface SqlDoc {
33 readonly statements: readonly SqlStatement[];
34 /** Statements in the file, drawn or not. */
35 readonly total: number;
36 }
37
38 const VERB = /^(create|alter|drop|insert|update|delete|pragma|begin|commit|rollback|with|select|replace|vacuum|attach|detach|reindex|analyze|grant|revoke|set|comment|truncate|explain|savepoint|release)\b/i;
39
40 /** Split into statements with comments removed. Null when a quote or comment never closes. */
41 function split(source: string): string[] | null {
42 const out: string[] = [];
43 let cur = "";
44 let depth = 0;
45 for (let i = 0; i < source.length; i++) {
46 const ch = source[i]!;
47 if (ch === "-" && source[i + 1] === "-") {
48 const nl = source.indexOf("\n", i);
49 i = nl === -1 ? source.length : nl - 1;
50 } else if (ch === "/" && source[i + 1] === "*") {
51 const end = source.indexOf("*/", i + 2);
52 if (end === -1) return null;
53 i = end + 1;
54 cur += " ";
55 } else if (ch === "'" || ch === '"' || ch === "`" || ch === "[") {
56 const close = ch === "[" ? "]" : ch;
57 let j = i + 1;
58 for (; j < source.length; j++) {
59 if (source[j] === close) {
60 if (close !== "]" && source[j + 1] === close) j++; // doubled quote
61 else break;
62 }
63 }
64 if (j >= source.length) return null;
65 cur += source.slice(i, j + 1);
66 i = j;
67 } else if (ch === ";" && depth === 0) {
68 if (cur.trim() !== "") out.push(cur.trim());
69 cur = "";
70 } else {
71 if (ch === "(") depth++;
72 else if (ch === ")" && depth > 0) depth--;
73 cur += ch;
74 }
75 }
76 if (cur.trim() !== "") out.push(cur.trim());
77 return out;
78 }
79
80 /** Split on commas outside quotes and parentheses. */
81 function parts(body: string): string[] {
82 const out: string[] = [];
83 let cur = "";
84 let depth = 0;
85 for (let i = 0; i < body.length; i++) {
86 const ch = body[i]!;
87 if (ch === "'" || ch === '"' || ch === "`" || ch === "[") {
88 const close = ch === "[" ? "]" : ch;
89 let j = i + 1;
90 while (j < body.length && !(body[j] === close && (close === "]" || body[j + 1] !== close))) j += body[j] === close ? 2 : 1;
91 cur += body.slice(i, j + 1);
92 i = j;
93 } else if (ch === "," && depth === 0) {
94 out.push(cur.trim());
95 cur = "";
96 } else {
97 if (ch === "(") depth++;
98 else if (ch === ")") depth--;
99 cur += ch;
100 }
101 }
102 if (cur.trim() !== "") out.push(cur.trim());
103 return out;
104 }
105
106 const unquote = (id: string): string => {
107 const q = id[0];
108 if (q === "[" && id.endsWith("]")) return id.slice(1, -1);
109 if ((q === '"' || q === "`" || q === "'") && id.length >= 2 && id.endsWith(q)) return id.slice(1, -1).replaceAll(q + q, q);
110 return id;
111 };
112
113 /** One identifier, possibly quoted, from the start of `s`; then what follows. */
114 const IDENT = /^(\[[^\]]*\]|"(?:[^"]|"")*"|`(?:[^`]|``)*`|[^\s(),]+)\s*/;
115
116 /** A possibly schema-qualified name: `main."my table"`. */
117 function qualified(s: string): { name: string; rest: string } | null {
118 let name = "";
119 let rest = s;
120 for (let n = 0; n < 3; n++) {
121 const m = IDENT.exec(rest);
122 if (m === null) return null;
123 name += (name === "" ? "" : ".") + unquote(m[1]!);
124 rest = rest.slice(m[0].length);
125 if (rest[0] === ".") rest = rest.slice(1);
126 else break;
127 }
128 return { name, rest };
129 }
130
131 const STOP = /^(not|null|primary|default|unique|references|check|constraint|collate|generated|autoincrement|auto_increment|as|on|comment)$/i;
132 const TABLE_LEVEL = /^(constraint|primary|foreign|unique|check|key|index|fulltext|exclude|like)\b/i;
133
134 /** A word-boundary-aware first token and the rest, quotes kept whole. */
135 function tokens(s: string): string[] {
136 const out: string[] = [];
137 let i = 0;
138 while (i < s.length) {
139 if (/\s/.test(s[i]!)) {
140 i++;
141 continue;
142 }
143 const start = i;
144 const q = s[i]!;
145 if (q === "'" || q === '"' || q === "`" || q === "[") {
146 const close = q === "[" ? "]" : q;
147 i++;
148 while (i < s.length && !(s[i] === close && (close === "]" || s[i + 1] !== close))) i += s[i] === close ? 2 : 1;
149 i++;
150 } else if (q === "(") {
151 let d = 0;
152 for (; i < s.length; i++) {
153 if (s[i] === "(") d++;
154 else if (s[i] === ")" && --d === 0) {
155 i++;
156 break;
157 }
158 }
159 } else {
160 while (i < s.length && !/[\s(]/.test(s[i]!)) i++;
161 if (s[i] === "(") {
162 // a type like varchar(20): keep its arguments with it
163 let d = 0;
164 for (; i < s.length; i++) {
165 if (s[i] === "(") d++;
166 else if (s[i] === ")" && --d === 0) {
167 i++;
168 break;
169 }
170 }
171 }
172 }
173 out.push(s.slice(start, i));
174 }
175 return out;
176 }
177
178 function column(def: string): SqlColumn | null {
179 const t = tokens(def);
180 if (t.length === 0) return null;
181 const name = unquote(t[0]!);
182 const type: string[] = [];
183 let i = 1;
184 while (i < t.length && !STOP.test(t[i]!)) type.push(t[i++]!);
185 let notNull = false;
186 let primaryKey = false;
187 let dflt = "";
188 for (; i < t.length; i++) {
189 const w = t[i]!.toLowerCase();
190 if (w === "not" && t[i + 1]?.toLowerCase() === "null") notNull = true;
191 else if (w === "primary" && t[i + 1]?.toLowerCase() === "key") primaryKey = true;
192 else if (w === "default" && t[i + 1] !== undefined) dflt = t[i + 1]!;
193 }
194 return { name, type: type.join(" "), notNull: notNull || primaryKey, primaryKey, default: dflt };
195 }
196
197 /** Column names listed in a table-level `PRIMARY KEY (a, b)`. */
198 function pkColumns(def: string): string[] {
199 const m = /^(?:constraint\s+\S+\s+)?primary\s+key\s*\(([^)]*)\)/i.exec(def);
200 return m === null ? [] : parts(m[1]!).map((c) => unquote(c.trim().split(/\s+/)[0]!));
201 }
202
203 function table(stmt: string): SqlStatement | null {
204 const m = /^create\s+(?:(?:global\s+|local\s+)?(?:temp|temporary)\s+|virtual\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?/i.exec(stmt);
205 if (m === null) return null;
206 const q = qualified(stmt.slice(m[0].length));
207 if (q === null || q.rest[0] !== "(") return null;
208 let depth = 0;
209 let end = -1;
210 for (let i = 0; i < q.rest.length && end === -1; i++) {
211 const ch = q.rest[i]!;
212 if (ch === "'" || ch === '"' || ch === "`" || ch === "[") {
213 const close = ch === "[" ? "]" : ch;
214 let j = i + 1;
215 while (j < q.rest.length && !(q.rest[j] === close && (close === "]" || q.rest[j + 1] !== close))) j += q.rest[j] === close ? 2 : 1;
216 i = j;
217 } else if (ch === "(") depth++;
218 else if (ch === ")" && --depth === 0) end = i;
219 }
220 if (end === -1) return null;
221 const columns: SqlColumn[] = [];
222 const extras: string[] = [];
223 const keys: string[] = [];
224 for (const def of parts(q.rest.slice(1, end))) {
225 if (TABLE_LEVEL.test(def)) {
226 keys.push(...pkColumns(def));
227 extras.push(def.replace(/\s+/g, " "));
228 } else {
229 const c = column(def);
230 if (c !== null) columns.push(c);
231 }
232 }
233 if (columns.length === 0) return null;
234 const done = columns.map((c) => (keys.includes(c.name) ? { ...c, primaryKey: true, notNull: true } : c));
235 return { kind: "table", name: q.name, columns: done, extras };
236 }
237
238 /** Read a SQL file. Pure; never throws; null when it is not SQL it can read. */
239 export function parseSql(source: string): SqlDoc | null {
240 const stmts = split(source.replace(/^/, ""));
241 if (stmts === null || !stmts.some((s) => VERB.test(s))) return null;
242 const statements: SqlStatement[] = [];
243 for (const s of stmts) {
244 if (statements.length >= ROW_CAP) break;
245 const t = table(s);
246 if (t !== null) {
247 statements.push(t.kind === "table" ? { ...t, columns: t.columns.slice(0, COLUMN_CAP) } : t);
248 } else {
249 const line = (s.split(/\r?\n/)[0] ?? "").trim();
250 statements.push({ kind: "other", line: line.length > LINE_CAP ? line.slice(0, LINE_CAP) + "…" : line });
251 }
252 }
253 return { statements, total: stmts.length };
254 }
255
256 const cell = (v: string): string => (v === "" ? "—" : v);
257
258 function block(s: SqlStatement): Html {
259 if (s.kind === "other") return html`<table class="table" data-dense><tbody><tr><td><code>${s.line}</code></td></tr></tbody></table>`;
260 const rows = s.columns.map(
261 (c) =>
262 html`<tr><th scope="row"><code>${c.name}</code></th><td>${cell(c.type)}</td><td>${c.notNull ? "NOT NULL" : "—"}</td><td>${c.primaryKey ? "PRIMARY KEY" : "—"}</td><td>${cell(c.default)}</td></tr>`,
263 );
264 const extras = s.extras.length === 0 ? html`` : html`<p class="muted small">${s.extras.join(" · ")}</p>`;
265 return html`<h3><code>${s.name}</code></h3><table class="table" data-dense aria-label="${s.name} columns"><thead><tr><th scope="col">Column</th><th scope="col">Type</th><th scope="col">Null</th><th scope="col">Key</th><th scope="col">Default</th></tr></thead><tbody>${rows}</tbody></table>${extras}`;
266 }
267
268 export function sqlView(input: RenderInput): Rendered {
269 const doc = parseSql(new TextDecoder().decode(input.body));
270 if (doc === null) return { content: html``, lines: 0, fallback: "This file holds no SQL statements to draw." };
271 const more = doc.total - doc.statements.length;
272 const foot = more > 0 ? html`<p class="muted small">${more.toLocaleString()} more not shown</p>` : html``;
273 const content = html`<div class="sql-view">${doc.statements.map(block)}${foot}</div>`;
274 const n = doc.total;
275 return { content, lines: 0, summary: `${n.toLocaleString()} ${n === 1 ? "statement" : "statements"} · ${fileSize(input.size)}` };
276 }
test/render-kinds.test.ts +1
@@ -81,6 +81,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
8181 ics: [enc("BEGIN:VCALENDAR\nEND:VCALENDAR\n"), "calendar", "application/octet-stream"],
8282 gcode: [enc("G28\nG1 X1 E1\n"), "gcode", "application/octet-stream"],
8383 gco: [enc("G28\n"), "gcode", "application/octet-stream"],
84 sql: [enc("CREATE TABLE a (id int);\n"), "sql", "application/octet-stream"],
8485 sarif: [enc('{"runs":[]}'), "sarif", "application/octet-stream"],
8586 lcov: [enc("SF:a.ts\nend_of_record\n"), "lcov", "application/octet-stream"],
8687 };
test/render-sql.test.ts added +90
@@ -0,0 +1,90 @@
1 import { describe, expect, test } from "bun:test";
2 import { fileKind, NO_BYTES } from "../src/web/render/kinds.ts";
3 import { RENDERERS } from "../src/web/render/renderers.ts";
4 import { parseSql, ROW_CAP, sqlView } from "../src/web/render/sql.ts";
5
6 const draw = (text: string) => {
7 const body = new TextEncoder().encode(text);
8 const r = sqlView({ path: "db/001.sql", size: body.length, body, media: "", download: "" });
9 return { html: String(r.content), summary: r.summary, fallback: r.fallback };
10 };
11
12 describe("sql", () => {
13 test("a .sql file is its own kind with a renderer", () => {
14 expect(fileKind("db/001.sql", NO_BYTES)).toBe("sql");
15 expect(RENDERERS.sql).toBe(sqlView);
16 });
17
18 test("a table with constraints", () => {
19 const doc = parseSql(
20 `CREATE TABLE IF NOT EXISTS users (
21 id INTEGER PRIMARY KEY AUTOINCREMENT,
22 email TEXT NOT NULL UNIQUE,
23 name VARCHAR(20, 2) DEFAULT 'a,b',
24 org_id INT,
25 created TEXT NOT NULL DEFAULT (datetime('now')),
26 FOREIGN KEY (org_id) REFERENCES orgs(id)
27 );
28 CREATE INDEX idx ON users(email);`,
29 )!;
30 expect(doc.total).toBe(2);
31 const t = doc.statements[0]!;
32 if (t.kind !== "table") throw new Error("table");
33 expect(t.name).toBe("users");
34 expect(t.columns.map((c) => [c.name, c.type, c.notNull, c.primaryKey, c.default])).toEqual([
35 ["id", "INTEGER", true, true, ""],
36 ["email", "TEXT", true, false, ""],
37 ["name", "VARCHAR(20, 2)", false, false, "'a,b'"],
38 ["org_id", "INT", false, false, ""],
39 ["created", "TEXT", true, false, "(datetime('now'))"],
40 ]);
41 expect(t.extras).toEqual(["FOREIGN KEY (org_id) REFERENCES orgs(id)"]);
42 expect(doc.statements[1]).toEqual({ kind: "other", line: "CREATE INDEX idx ON users(email)" });
43 });
44
45 test("a table-level primary key marks its columns", () => {
46 const t = parseSql("CREATE TABLE m (a INT, b INT, PRIMARY KEY (a, b));")!.statements[0]!;
47 if (t.kind !== "table") throw new Error("table");
48 expect(t.columns.map((c) => c.primaryKey)).toEqual([true, true]);
49 });
50
51 test("comments are not statements and may hide semicolons", () => {
52 const doc = parseSql("-- first; second\n/* CREATE TABLE no (x int); */\nALTER TABLE a ADD COLUMN b INT; -- done\n")!;
53 expect(doc.statements).toEqual([{ kind: "other", line: "ALTER TABLE a ADD COLUMN b INT" }]);
54 });
55
56 test("a quoted name with < is escaped", () => {
57 const out = draw('CREATE TABLE "<img src=x onerror=alert(1)>" ("<b>" TEXT);\nALTER TABLE "<i>" ADD x INT;').html;
58 expect(out).not.toContain("<img");
59 expect(out).not.toContain("<b>");
60 expect(out).not.toContain("<i>");
61 expect(out).toContain("&lt;img src=x onerror=alert(1)&gt;");
62 });
63
64 test("renders a block per statement with a summary", () => {
65 const r = draw("CREATE TABLE t (id INT NOT NULL);\nDROP TABLE u;");
66 expect(r.html).toContain("<h3>");
67 expect(r.html).toContain("NOT NULL");
68 expect(r.summary).toContain("2 statements");
69 expect(r.fallback).toBeUndefined();
70 });
71
72 test("an unparsable file falls back to the source", () => {
73 for (const text of ["just some prose, nothing here", "", "SELECT 'unterminated;", "/* never closed\nCREATE TABLE a (x int);"]) {
74 const r = draw(text);
75 expect(r.fallback).toBeDefined();
76 }
77 });
78
79 test("a malformed CREATE TABLE is one row, not an error", () => {
80 const doc = parseSql("CREATE TABLE broken (a INT, ;\nCREATE TABLE t2;")!;
81 expect(doc.statements.every((s) => s.kind === "other")).toBe(true);
82 });
83
84 test("the cap", () => {
85 const text = Array.from({ length: ROW_CAP + 25 }, (_, i) => `CREATE INDEX i${i} ON t(a);`).join("\n");
86 const r = draw(text);
87 expect(r.html).toContain("25 more not shown");
88 expect(r.html.match(/<table/g)?.length).toBe(ROW_CAP);
89 });
90 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs