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

The Data tab of an SQLite file filters a table by one column's value, from the address #16823

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16315-the-data-tab-of-an-sqlite-file-filters-a → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/16315-the-data-tab-of-an-sqlite-file-filters-a was merged into main as 8b76613.

Review

Sign in to review this change.
11 files changed +276 −31
docs/features/data-browser.md +2 −2
@@ -16,7 +16,7 @@ Views are masked whole when their text mentions a masked column (an alias cannot
1616
1717 Limits on work: `query` runs at most 2 workers at once (a third is told it is busy), each with a 128 MB heap cap (`hard_heap_limit`), a 5 s timer, 1,000 rows and about 250 KB of result; every cell is cut to 1,000 characters inside SQLite and a blob shows as its size. `rows()` cuts cells the same way.
1818
19 Terminal: `src/tui/screens/data.ts` is a tree (repos → apps → environments → files → tables → first 50 rows; `src/data/tree.ts` builds it), offered by `maySeeData`. Keys: `j`/`k` move, `l`/Enter open, `h` close or go up, `/` filter the open lines, `:` a read-only SQL prompt against the file under the cursor (same caps; a write is refused), `y` yank a row as JSON (OSC 52), `n`/`p` next/previous page of 50 rows on a table or row, `r` read the files afresh. The tree is built once and rebuilt only when a node opens, a page turns or `r` is pressed; the files are read once per open node. Shell: `forge data <app> [env] [sql] [--json]` (docs/CLI.md) calls the MCP tool.
19 Terminal: `src/tui/screens/data.ts` is a tree (repos → apps → environments → files → tables → first 50 rows; `src/data/tree.ts` builds it), offered by `maySeeData`. Keys: `j`/`k` move, `l`/Enter open, `h` close or go up, `/` filter the open lines, `:` a read-only SQL prompt against the file under the cursor (same caps; a write is refused), `y` yank a row as JSON (OSC 52), `n`/`p` next/previous page of 50 rows on a table or row, `f` filters the table under the cursor by one column (`column=text`; empty text lifts it; every column named must match, a sealed one matches nothing, an unknown one shows `no such column`), `r` read the files afresh. The tree is built once and rebuilt only when a node opens, a page turns or `r` is pressed; the files are read once per open node. Shell: `forge data <app> [env] [sql] [--json]` (docs/CLI.md) calls the MCP tool.
2020
2121 Not done: a filter that reaches into closed lines. SQL on any door (web, terminal, `forge data` and the MCP `data` tool) is 20 runs a minute per person (`src/data/sql_window.ts`); beyond that it says when to retry.
2222
@@ -24,7 +24,7 @@ API and MCP by repository (`data/repo_scope.ts`, `http/api/data.ts`): `GET /api/
2424
2525 ## On the web (#7580)
2626
27 Three doors, one body (`src/web/pages/data_view.ts`): `/data` (every file you may see), `/admin/data` (the forge's own database, admins; the Forge data button on `/data`) and `/:owner/:name/data` (an app's Data tab for its writers: environments → files → tables → rows; a reader gets the 404). Rows sort by header (`sort`, `dir`), filter by text on one column or all (`q`, `col`), JSON cells are pretty-printed, and a copy button per row puts it on the clipboard as JSON. Sealed columns show `••••••` and cannot be sorted or searched. The SQL box is a GET form (`sql`, capped at 4,000 characters), so a query is an address to share; it shows the rows and the elapsed ms. The sorted column carries `aria-sort` and a muted arrow from CSS; a wide grid scrolls sideways only. Not done: saved queries, export, editing rows.
27 Three doors, one body (`src/web/pages/data_view.ts`): `/data` (every file you may see), `/admin/data` (the forge's own database, admins; the Forge data button on `/data`) and `/:owner/:name/data` (an app's Data tab for its writers: environments → files → tables → rows; a reader gets the 404). Rows sort by header (`sort`, `dir`), filter by text on one column or all (`q`, `col`), and by one box per column under the header (`f.<column>=<text>` in the address, every box must match; the MCP `data` tool takes `filter: {column: text}`; the column must be one the table reports (the tool says `invalid` for one it lacks, and refuses `filter` with `format` csv), the text is a bound parameter, a sealed column matches nothing), JSON cells are pretty-printed, and a copy button per row puts it on the clipboard as JSON. Sealed columns show `••••••` and cannot be sorted or searched. The SQL box is a GET form (`sql`, capped at 4,000 characters), so a query is an address to share; it shows the rows and the elapsed ms. The sorted column carries `aria-sort` and a muted arrow from CSS; a wide grid scrolls sideways only. Not done: saved queries, export, editing rows.
2828
2929 Cost of a query: `query` also returns `rowsRead` (rows the query produced, the one that tripped a cap included) and `elapsedMs` (at least 1). The page prints them as one muted line under the table (`N rows read · X ms`), the terminal's `:` result shows the same in its header line, and the MCP `data` answer with `sql` carries both fields. They count rows the query produced, not rows SQLite scanned.
3030
src/data/browse.ts +24
@@ -25,7 +25,20 @@ export interface RowFilter {
2525 readonly exact?: boolean;
2626 }
2727
28 /** Most per-column filters one read honours. */
29 export const MAX_COLUMN_FILTERS = 20;
30 /** Longest value one column filter carries. */
31 export const COLUMN_FILTER_CHARS = 200;
32
33 export interface ColumnFilter {
34 readonly column: string;
35 /** Rows whose cell contains this text; always a bound parameter. */
36 readonly text: string;
37 }
38
2839 export interface RowsOptions {
40 /** One box per column: every one must match (AND). A column the table lacks refuses the read. */
41 readonly by?: readonly ColumnFilter[];
2942 readonly filter?: RowFilter;
3043 readonly order?: { readonly column: string; readonly dir?: "asc" | "desc" };
3144 /** Zero-based. */
@@ -160,6 +173,17 @@ export function rows(
160173 for (let i = 0; i < searchable.length; i++) args.push(`%${like}%`);
161174 }
162175 }
176 for (const f of (opts.by ?? []).slice(0, MAX_COLUMN_FILTERS)) {
177 if (f.text === "") continue;
178 // The name is only ever one the table reports; anything else is no table read at all.
179 if (!columns.includes(f.column)) return undefined;
180 if (masked.has(f.column)) {
181 where.push("0"); // searching a masked column would leak it a character at a time
182 continue;
183 }
184 where.push(`CAST(${quote(f.column)} AS TEXT) LIKE ? ESCAPE '\\'`);
185 args.push(`%${f.text.slice(0, COLUMN_FILTER_CHARS).replace(/[\\%_]/g, (m) => `\\${m}`)}%`);
186 }
163187 let order = "";
164188 if (opts.order) {
165189 if (!columns.includes(opts.order.column)) return undefined;
src/data/column_filters.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * The per-column filters of an address: `?f.<column>=<text>`, one per column. This only reads
3 * the shape; whether a column exists is decided by `rows` against the table's real columns, and
4 * the text only ever reaches SQL as a bound parameter.
5 */
6
7 import { COLUMN_FILTER_CHARS, MAX_COLUMN_FILTERS, type ColumnFilter } from "./browse.ts";
8
9 export const FILTER_PREFIX = "f.";
10
11 /** The filters a query string carries, empty boxes left out, capped. */
12 export function columnFilters(q: URLSearchParams): ColumnFilter[] {
13 const out = new Map<string, string>();
14 for (const [k, v] of q) {
15 if (!k.startsWith(FILTER_PREFIX) || k.length === FILTER_PREFIX.length || v === "") continue;
16 if (out.size >= MAX_COLUMN_FILTERS && !out.has(k)) break;
17 if (!out.has(k.slice(FILTER_PREFIX.length))) out.set(k.slice(FILTER_PREFIX.length), v.slice(0, COLUMN_FILTER_CHARS));
18 }
19 return [...out].map(([column, text]) => ({ column, text }));
20 }
21
22 /** The same filters as address parameters, for a link that keeps them. */
23 export const filterParams = (by: readonly ColumnFilter[]): Record<string, string> =>
24 Object.fromEntries(by.map((f) => [FILTER_PREFIX + f.column, f.text]));
25
26 /** A tool's `filter` object (`{ column: text }`) as filters; a string says what is wrong. */
27 export function filtersFrom(v: unknown): ColumnFilter[] | string {
28 if (v === undefined) return [];
29 if (typeof v !== "object" || v === null || Array.isArray(v)) return "`filter` is an object of column: text";
30 const pairs = Object.entries(v);
31 if (pairs.length > MAX_COLUMN_FILTERS) return `\`filter\` names at most ${MAX_COLUMN_FILTERS} columns`;
32 const out: ColumnFilter[] = [];
33 for (const [column, text] of pairs) {
34 if (typeof text !== "string") return "`filter` values are text";
35 if (text.length > COLUMN_FILTER_CHARS) return `\`filter\` values are at most ${COLUMN_FILTER_CHARS} characters`;
36 if (text !== "") out.push({ column, text });
37 }
38 return out;
39 }
src/data/repo_scope.ts +3 −3
@@ -10,7 +10,7 @@ import { getAppByRepo } from "../core/apps.ts";
1010 import { canWrite, type Repo } from "../core/repos.ts";
1111 import type { User } from "../core/users.ts";
1212 import { isEnvName } from "../apps/data.ts";
13 import { rows, tables } from "./browse.ts";
13 import { rows, tables, type ColumnFilter } from "./browse.ts";
1414 import { query } from "./query.ts";
1515 import { sqlWindow } from "./sql_window.ts";
1616 import { listSources, type Source } from "./sources.ts";
@@ -64,8 +64,8 @@ export const sourceList = (sources: readonly Source[]) =>
6464
6565 export const tableList = (source: Source) => tables(source);
6666
67 export function rowPage(source: Source, table: string, page: number | undefined) {
68 return rows(source, table, page === undefined ? {} : { page });
67 export function rowPage(source: Source, table: string, page: number | undefined, by: readonly ColumnFilter[] = []) {
68 return rows(source, table, { ...(page === undefined ? {} : { page }), ...(by.length > 0 ? { by } : {}) });
6969 }
7070
7171 export type SqlOutcome = Awaited<ReturnType<typeof query>> | { readonly ok: false; readonly error: "rate"; readonly message: string; readonly retryAfter: number };
src/data/tree.ts +13 −9
@@ -3,7 +3,7 @@
33 * tables → rows. Pure: which nodes are open and what to filter by come in,
44 * the visible lines go out. Reads happen only for an open file or table.
55 */
6 import { PAGE_SIZE, rows as readRows, tables as readTables, type RowsResult, type TableInfo } from "./browse.ts";
6 import { PAGE_SIZE, rows as readRows, type ColumnFilter, tables as readTables, type RowsResult, type TableInfo } from "./browse.ts";
77 import { rowObject, cellLine, type Cell } from "./shape.ts";
88 import type { SpecRow } from "./spec_scope.ts";
99 import type { Source } from "./sources.ts";
@@ -66,6 +66,7 @@ export function visible(
6666 reads: Reads = newReads(),
6767 page: ReadonlyMap<string, number> = new Map(),
6868 specs?: Specs,
69 by: ReadonlyMap<string, readonly ColumnFilter[]> = new Map(),
6970 ): Node[] {
7071 const out: Node[] = [];
7172 const specNode = (key: string, depth: number, repo: string | undefined) => {
@@ -92,19 +93,22 @@ export function visible(
9293 for (const t of list) {
9394 const key = join(file.key, t.name);
9495 const at = page.get(key) ?? 0;
95 const paged = t.rows > PAGE_SIZE ? ` page ${at + 1}/${pageCount(t.rows)}` : "";
96 const node: Node = { key, kind: "table", depth, label: `${t.name} ${t.rows} rows${open.has(key) ? paged : ""}`, source, table: t.name, total: t.rows };
97 out.push(node);
98 if (!open.has(node.key)) continue;
99 const pk = `${key}${SEP}${at}`;
100 if (!reads.pages.has(pk)) {
96 const mine = by.get(key) ?? [];
97 const pk = `${key}${SEP}${at}${SEP}${JSON.stringify(mine)}`;
98 if (open.has(key) && !reads.pages.has(pk)) {
10199 try {
102 reads.pages.set(pk, readRows(source, t.name, { page: at }));
100 reads.pages.set(pk, readRows(source, t.name, { page: at, ...(mine.length > 0 ? { by: mine } : {}) }));
103101 } catch {
104102 reads.pages.set(pk, undefined);
105103 }
106104 }
107 const got = reads.pages.get(pk);
105 const got = open.has(key) ? reads.pages.get(pk) : undefined;
106 const total = mine.length > 0 && got ? got.total : t.rows;
107 const paged = total > PAGE_SIZE ? ` page ${at + 1}/${pageCount(total)}` : "";
108 const note = mine.length === 0 ? "" : got ? ` of ${t.rows}, where ${mine.map((f) => `${f.column}~${f.text}`).join(" and ")}` : " no such column";
109 const node: Node = { key, kind: "table", depth, label: `${t.name} ${got && mine.length > 0 ? got.total : t.rows} rows${open.has(key) ? note + paged : ""}`, source, table: t.name, total };
110 out.push(node);
111 if (!open.has(node.key)) continue;
108112 for (const [i, r] of (got?.rows ?? []).entries())
109113 out.push({
110114 key: join(node.key, String(i)),
src/http/mcp/tools/data.ts +16 −6
@@ -1,7 +1,8 @@
1 import { rows, tables } from "../../../data/browse.ts";
1 import { tables, type ColumnFilter } from "../../../data/browse.ts";
22 import { findSource, listSources, type Source } from "../../../data/sources.ts";
33 import { isFailure, parsePage, pickSource, repoSources, rowPage, runSql, sourceList, tableList } from "../../../data/repo_scope.ts";
44 import { appSpec, forgeSpec } from "../../../data/spec_scope.ts";
5 import { filtersFrom } from "../../../data/column_filters.ts";
56 import { exportCsv } from "../../../data/export_csv.ts";
67 import { bad, good, isAnswer, repoArg, type Tool } from "../shared.ts";
78
@@ -10,7 +11,7 @@ const CSV_ROWS = 1000;
1011
1112 export const tool: Tool = {
1213 name: "data",
13 doc: "`{ repo, env?, file?, table?, sql? }` as `GET …/data`: an app's databases, then `env`+`file`: its tables, `table`: rows, `sql`: one read-only SELECT; its writers only. Without `repo`: the SQLite files you may read (the forge's own for an admin; each app's per environment for its writers), with `source`: its tables and row counts, with `table` (and `page`): a page of rows (`format` csv: 1,000 as CSV), with `sql`: a read-only SELECT (5 s, 1,000 rows); secret columns are masked; `spec: true` (+`q`, `repo`): the API operations, the forge's or the app's",
14 doc: "`{ repo, env?, file?, table?, sql? }` as `GET …/data`: an app's databases, then `env`+`file`: its tables, `table`: rows (`filter` `{ column: text }`: only rows whose cell contains the text, every column named must match), `sql`: one read-only SELECT; its writers only. Without `repo`: the SQLite files you may read (the forge's own for an admin; each app's per environment for its writers), with `source`: its tables and row counts, with `table` (and `page`, `filter`): a page of rows (`format` csv: 1,000 as CSV), with `sql`: a read-only SELECT (5 s, 1,000 rows); secret columns are masked; `spec: true` (+`q`, `repo`): the API operations, the forge's or the app's",
1415 description: "Read SQLite files you may see: tables, rows, read-only SQL; secrets masked.",
1516 inputSchema: {
1617 type: "object",
@@ -25,6 +26,7 @@ export const tool: Tool = {
2526 format: { type: "string" },
2627 spec: { type: "boolean" },
2728 q: { type: "string" },
29 filter: { type: "object", additionalProperties: { type: "string" } },
2830 },
2931 },
3032 writes: false,
@@ -39,11 +41,19 @@ export const tool: Tool = {
3941 const [id, table, sql, env, file] = ["source", "table", "sql", "env", "file"].map(str);
4042 const format = args["format"];
4143 if (format !== undefined && format !== "csv") return bad("invalid", "`format` is csv");
44 const rowsAnswer = (source: Source, name: string, pageNo: number | undefined, by: ColumnFilter[]) => {
45 const found = rowPage(source, name, pageNo, by);
46 if (found) return good(found);
47 // Rows are undefined for a missing table and for a column the table lacks: say which.
48 const real = by.length > 0 && tables(source).some((t) => t.name === name);
49 return real ? bad("invalid", "`filter` names a column the table does not have") : bad("not_found", "no such table");
50 };
4251 const asCsv = (source: Source, name: string) => {
4352 const out = exportCsv(ctx.app, user, source, name, { rows: CSV_ROWS });
4453 if (out.ok) return good({ format: "csv", rows: out.rows, truncated: out.truncated, csv: out.csv });
4554 return out.error === "rate" ? bad("rate_limited", `too many queries: try again in ${out.retryAfter} s`) : bad("not_found", "no such table");
4655 };
56 if (format === "csv" && args["filter"] !== undefined) return bad("invalid", "`filter` does not apply to `format` csv: read rows without `format`");
4757 if (args["spec"] !== undefined && typeof args["spec"] !== "boolean") return bad("invalid", "`spec` is true or false");
4858 if (args["q"] !== undefined && typeof args["q"] !== "string") return bad("invalid", "`q` is text");
4959 if (args["spec"] === true) {
@@ -54,6 +64,8 @@ export const tool: Tool = {
5464 if (spec === undefined) return bad("not_found", "no such app or repository (owner/name)");
5565 return spec === "none" ? bad("not_found", "this app serves no /openapi.json right now") : good(spec);
5666 }
67 const by = filtersFrom(args["filter"]);
68 if (typeof by === "string") return bad("invalid", by);
5769 const page = args["page"];
5870 const pageNo = page === undefined || typeof page !== "number" ? undefined : parsePage(page);
5971 if (page !== undefined && pageNo === undefined) return bad("invalid", "`page` is a whole number from 0 to 1000");
@@ -71,8 +83,7 @@ export const tool: Tool = {
7183 }
7284 if (table === undefined) return good({ items: tableList(picked) });
7385 if (format === "csv") return asCsv(picked, table);
74 const found = rowPage(picked, table, pageNo);
75 return found ? good(found) : bad("not_found", "no such table");
86 return rowsAnswer(picked, table, pageNo, by);
7687 }
7788 if (id === undefined) {
7889 return good(listSources(db, config.dataDir, user).map((s) => ({ source: s.id, label: s.label })));
@@ -85,7 +96,6 @@ export const tool: Tool = {
8596 }
8697 if (table === undefined) return good(tables(source));
8798 if (format === "csv") return asCsv(source, table);
88 const found = rows(source, table, pageNo === undefined ? {} : { page: pageNo });
89 return found ? good(found) : bad("not_found", "no such table");
99 return rowsAnswer(source, table, pageNo, by);
90100 },
91101 };
src/tui/screens/data.ts +34 −5
@@ -16,7 +16,7 @@ import { query, type QueryResult } from "../../data/query.ts";
1616 import { cellLine, rowObject, type Cell } from "../../data/shape.ts";
1717 import { listSources, maySeeData } from "../../data/sources.ts";
1818 import { sqlWindow } from "../../data/sql_window.ts";
19 import { PAGE_SIZE, topValues, type TopValue } from "../../data/browse.ts";
19 import { MAX_COLUMN_FILTERS, PAGE_SIZE, topValues, type ColumnFilter, type TopValue } from "../../data/browse.ts";
2020 import { exportCsv } from "../../data/export_csv.ts";
2121 import { appSpec, forgeSpec, type SpecRow } from "../../data/spec_scope.ts";
2222 import { filtered, newReads, opens, pageCount, parentKey, visible, type Node } from "../../data/tree.ts";
@@ -127,11 +127,13 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
127127 const open = new Set<string>();
128128 let at = 0;
129129 let filter = "";
130 let mode: "filter" | "sql" | "values" | undefined;
130 let mode: "filter" | "sql" | "values" | "column" | undefined;
131131 let line = typing(FILTER_MAX);
132132
133133 // Built once and rebuilt only when `open`, a page, the filter or a reload changes it.
134134 const pages = new Map<string, number>();
135 /** Per-column filters by table key: `f` on a table or row sets one as `column=text`. */
136 const by = new Map<string, ColumnFilter[]>();
135137 let reads = newReads();
136138 // The spec nodes' readings, by `forge` or `owner/name`; the forge's is sync, an app's is asked
137139 // once.
@@ -167,7 +169,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
167169 const lines = (): Node[] => {
168170 if (shown) return shown;
169171 files ??= listSources(session.app.db, session.app.config.dataDir, session.user);
170 built ??= visible(files, open, reads, pages, specs);
172 built ??= visible(files, open, reads, pages, specs, by);
171173 return (shown = filtered(built, filter));
172174 };
173175 const reload = () => {
@@ -207,6 +209,28 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
207209 );
208210 }
209211
212 /** `column=text` on the table under the cursor; empty text lifts that column's filter. */
213 function setColumnFilter(n: Node | undefined, entry: string) {
214 const tk = n && tableKey(n);
215 const eq = entry.indexOf("=");
216 if (tk === undefined || !n?.source) return ctx.toast("Move onto a table or one of its rows first.", "danger");
217 if (entry.trim() === "") {
218 by.delete(tk);
219 } else {
220 const column = (eq < 0 ? entry : entry.slice(0, eq)).trim();
221 const text = eq < 0 ? "" : entry.slice(eq + 1);
222 if (column === "") return ctx.toast("Type column=text.", "danger");
223 const rest = (by.get(tk) ?? []).filter((f) => f.column !== column);
224 if (text !== "") rest.push({ column, text });
225 if (rest.length > MAX_COLUMN_FILTERS) return ctx.toast(`At most ${MAX_COLUMN_FILTERS} columns at once.`, "danger");
226 if (rest.length === 0) by.delete(tk);
227 else by.set(tk, rest);
228 }
229 pages.set(tk, 0);
230 dirty(true);
231 at = Math.max(0, lines().findIndex((x) => x.key === tk));
232 }
233
210234 /** The commonest values of `column` in the table under the cursor: the page's pick-list. */
211235 function showValues(n: Node | undefined, column: string) {
212236 const name = column.trim();
@@ -235,7 +259,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
235259 title: "Data",
236260 get keys() {
237261 return mode
238 ? [binding("enter", mode === "filter" ? "keep" : mode === "sql" ? "run" : "list"), binding("esc", "cancel")]
262 ? [binding("enter", mode === "filter" ? "keep" : mode === "sql" ? "run" : mode === "column" ? "apply" : "list"), binding("esc", "cancel")]
239263 : [
240264 binding(["j", "k"], "move"),
241265 binding(["h", "l"], "close / open"),
@@ -244,6 +268,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
244268 binding("y", "yank row as JSON or operation"),
245269 binding("e", "export table as CSV"),
246270 binding("v", "common values of a column"),
271 binding("f", "filter a table by column=text"),
247272 binding(["n", "p"], `page of ${PAGE_SIZE}`),
248273 binding("r", "reload"),
249274 binding("esc", "back"),
@@ -263,7 +288,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
263288 s.text(area.x + 1, area.y + 2 + i, truncate(`${" ".repeat(n.depth)}${mark}${n.label}`, area.w - 2), style(on ? c.accent : c.fg, c.bg), area.x + area.w);
264289 });
265290 if (mode) {
266 s.text(area.x + 1, area.y + area.h - 1, truncate(`${mode === "sql" ? ":" : mode === "values" ? "column " : "/"}${line.text}`, area.w - 2), style(c.fg, c.card), area.x + area.w);
291 s.text(area.x + 1, area.y + area.h - 1, truncate(`${mode === "sql" ? ":" : mode === "values" ? "column " : mode === "column" ? "column=text " : "/"}${line.text}`, area.w - 2), style(c.fg, c.card), area.x + area.w);
267292 }
268293 },
269294 key(e) {
@@ -279,6 +304,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
279304 dirty();
280305 at = 0;
281306 } else if (done === "values") showValues(current(), line.text);
307 else if (done === "column") setColumnFilter(current(), line.text);
282308 else ask(line.text);
283309 } else if (!line.key(e)) return true;
284310 else if (mode === "filter") {
@@ -312,6 +338,9 @@ export function dataScreen(session: Session, ctx: Ctx): Screen {
312338 } else if (e.key === "v") {
313339 mode = "values";
314340 line = typing(FILTER_MAX);
341 } else if (e.key === "f") {
342 mode = "column";
343 line = typing(FILTER_MAX);
315344 } else if (e.key === ":") {
316345 mode = "sql";
317346 line = typing(SQL_MAX, n?.table ? `SELECT * FROM "${n.table.replaceAll('"', '""')}" LIMIT 20` : "");
src/web/pages/data_view.ts +18 −6
@@ -8,6 +8,7 @@
88 */
99
1010 import { PAGE_SIZE, rows, tables, topValues, type RowsResult } from "../../data/browse.ts";
11 import { columnFilters, FILTER_PREFIX, filterParams } from "../../data/column_filters.ts";
1112 import { query } from "../../data/query.ts";
1213 import type { Source } from "../../data/sources.ts";
1314 import type { SpecAnswer } from "../../data/spec_scope.ts";
@@ -68,11 +69,12 @@ function grid(
6869 caption: string,
6970 head: (c: string) => Html,
7071 copyIds: boolean,
72 boxes?: (c: string) => Html,
7173 ): Html {
7274 return html`<div class="table-scroll">
7375 <table class="table" data-dense data-sortable>
7476 <caption class="sr-only">${caption}</caption>
75 <thead><tr>${copyIds ? html`<th scope="col"><span class="sr-only">Copy</span></th>` : null}${columns.map(head)}</tr></thead>
77 <thead><tr>${copyIds ? html`<th scope="col"><span class="sr-only">Copy</span></th>` : null}${columns.map(head)}</tr>${boxes ? html`<tr>${copyIds ? html`<th></th>` : null}${columns.map(boxes)}</tr>` : null}</thead>
7678 <tbody>
7779 ${data.map(
7880 (r, i) => html`<tr>
@@ -148,17 +150,22 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html
148150 const col = q.get("col") || undefined;
149151 const exact = col !== undefined && q.get("exact") === "1";
150152 const pageNo = intOr0(q.get("page"));
151 const base = { source: source.id, table: tableName, sort, dir: sort ? dir : undefined, q: text, col, exact: exact ? "1" : undefined };
153 const by = columnFilters(q);
154 let base: Record<string, string | undefined> = { source: source.id, table: tableName, sort, dir: sort ? dir : undefined, q: text, col, exact: exact ? "1" : undefined, ...filterParams(by) };
152155 let shown: RowsResult | undefined = rows(source, tableName, {
153156 page: pageNo,
157 ...(by.length > 0 ? { by } : {}),
154158 ...(sort ? { order: { column: sort, dir } } : {}),
155159 ...(text !== "" ? { filter: { text, ...(col ? { column: col } : {}), ...(exact ? { exact } : {}) } } : {}),
156160 });
157161 let note: string | null = null;
158 if (!shown && (sort || text !== "")) {
162 if (!shown && (sort || text !== "" || by.length > 0)) {
159163 // An unknown or sealed column cannot be sorted or searched: show the table, say so.
160164 shown = rows(source, tableName, { page: pageNo });
161165 note = "That column cannot be sorted or searched here.";
166 // Links from here on keep only filters on columns the table really has.
167 const real = new Set(shown?.columns ?? []);
168 base = { ...base, ...Object.fromEntries(by.filter((f) => !real.has(f.column)).map((f) => [FILTER_PREFIX + f.column, undefined])) };
162169 }
163170 if (!shown) return undefined;
164171 const cols = shown.columns;
@@ -175,13 +182,17 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html
175182 ? html`<p class="muted small">Too many queries to list common values; try again in ${String(wait)} s.</p>`
176183 : null;
177184 const more = (shown.page + 1) * PAGE_SIZE < shown.total;
outdated

base spreads filterParams(by) including columns the table does not have, so after the "cannot be sorted or searched" note every sort and page link still carries the hostile f. key. Keep only filters on real columns.

185 const mine = new Map(by.map((f) => [f.column, f.text]));
186 // One box per column, in the table's own form: Enter in any of them filters by all.
187 const box = (c: string): Html =>
188 html`<th scope="col"><input type="search" form="rowfilter" name="f.${c}" value="${mine.get(c) ?? ""}" maxlength="200" aria-label="Filter ${c}" placeholder="Filter" autocomplete="off" /></th>`;
178189 const header = (c: string): Html => {
179190 const next = sort === c && dir === "asc" ? "desc" : "asc";
180191 return html`<th scope="col" ${sort === c ? html`aria-sort="${dir === "asc" ? "ascending" : "descending"}"` : null}><a href="${url(path, { ...base, sort: c, dir: next })}">${c}</a></th>`;
181192 };
182193 out = html`${out}
183194 <h2>${tableName}</h2>
184 <form method="get" action="${path}" role="search">
195 <form method="get" action="${path}" role="search" id="rowfilter">
185196 <input type="hidden" name="source" value="${source.id}" />
186197 <input type="hidden" name="table" value="${tableName}" />
187198 ${sort ? html`<input type="hidden" name="sort" value="${sort}" /><input type="hidden" name="dir" value="${dir}" />` : null}
@@ -202,13 +213,14 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html
202213 })}
203214 <div class="form-actions">
204215 ${btn("Filter", { size: "sm", type: "submit" })}
205 ${text !== "" ? btn("Clear", { href: url(path, { source: source.id, table: tableName, sort, dir: sort ? dir : undefined }), size: "sm", variant: "outline" }) : null}
216 ${text !== "" || by.length > 0 ? btn("Clear", { href: url(path, { source: source.id, table: tableName, sort, dir: sort ? dir : undefined }), size: "sm", variant: "outline" }) : null}
206217 ${view.byEnv ? btn("Download CSV", { href: url(`${path}/${encodeURIComponent(tableName)}.csv`, { source: source.id }), size: "sm", variant: "outline" }) : null}
207218 </div>
208219 </form>
209220 ${note ? html`<p class="muted small">${note}</p>` : null}
210221 ${exact && text !== "" ? html`<p class="muted small">Rows where ${col ?? ""} equals “${text}”. Filtering again finds rows that contain the text.</p>` : null}
211 ${shown.rows.length === 0 ? emptyList("rows", { noAction: true, reason: text !== "" ? "Nothing matches that filter." : "This table is empty." }) : grid(cols, shown.rows, `${tableName} in ${source.label}`, header, true)}
222 ${shown.rows.length === 0 ? emptyList("rows", { noAction: true, reason: text !== "" || by.length > 0 ? "Nothing matches that filter." : "This table is empty." }) : null}
223 ${shown.rows.length === 0 && by.length === 0 ? null : grid(cols, shown.rows, `${tableName} in ${source.label}`, header, true, box)}
212224 ${pager({
213225 note: `${shown.total} rows`,
214226 words: { prev: "Previous page", next: "Next page" },
test/data-column-filters.test.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * One filter box per column: the address, the bound-parameter query, a hostile name and value, the
3 * page's boxes.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { Database } from "bun:sqlite";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { rows } from "../src/data/browse.ts";
11 import { columnFilters, filtersFrom } from "../src/data/column_filters.ts";
12 import { rowPage } from "../src/data/repo_scope.ts";
13 import type { Source } from "../src/data/sources.ts";
14 import { dataBody } from "../src/web/pages/data_view.ts";
15
16 let dir = "";
17 let source: Source;
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-col-filters-"));
20 const path = join(dir, "app.db");
21 const d = new Database(path);
22 d.exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, city TEXT, kind TEXT, api_token TEXT, "we""ird" TEXT)`);
23 d.exec(`INSERT INTO t (city, kind, api_token, "we""ird") VALUES
24 ('Paris','cafe','sekrit-1','a'),('Paris','museum','sekrit-2','b'),('Rome','cafe','sekrit-3','100%'),('Oslo','x'' OR 1=1 --','sekrit-4','c')`);
25 d.close();
26 source = { id: "app:x:production:app.db", label: "Test", kind: "app", path } as unknown as Source;
27 });
28 afterAll(() => rm(dir, { recursive: true, force: true }));
29
30 const cities = (by: { column: string; text: string }[]) => rows(source, "t", { by })?.rows.map((r) => r[1]);
31
32 describe("column filters", () => {
33 test("the address names column and value; empty boxes are dropped", () => {
34 const by = columnFilters(new URLSearchParams("table=t&f.city=Par&f.kind=&f.=x&sort=id"));
35 expect(by).toEqual([{ column: "city", text: "Par" }]);
36 });
37 test("every box must match", () => {
38 expect(cities([{ column: "city", text: "paris" }])).toEqual(["Paris", "Paris"]);
39 expect(cities([{ column: "city", text: "paris" }, { column: "kind", text: "mus" }])).toEqual(["Paris"]);
40 });
41 test("a hostile value is only a bound parameter", () => {
42 expect(cities([{ column: "kind", text: "x' OR 1=1 --" }])).toEqual(["Oslo"]);
43 expect(cities([{ column: "city", text: "'; DROP TABLE t; --" }])).toEqual([]);
44 expect(rows(source, "t")?.total).toBe(4);
45 });
46 test("LIKE wildcards in a value are literal", () => {
47 expect(cities([{ column: "we\"ird", text: "%" }])).toEqual(["Rome"]);
48 expect(cities([{ column: "city", text: "_" }])).toEqual([]);
49 });
50 test("a hostile column name is refused, never run", () => {
51 for (const column of ['city" OR 1=1 --', "city) UNION SELECT 1 --", "nope", "sqlite_master"])
52 expect(rows(source, "t", { by: [{ column, text: "x" }] })).toBeUndefined();
53 expect(rows(source, "t", { by: [{ column: "we\"ird", text: "b" }] })?.total).toBe(1);
54 });
55 test("a secret column matches nothing, so it cannot be read by guessing", () => {
56 expect(rows(source, "t", { by: [{ column: "api_token", text: "sekrit-1" }] })?.total).toBe(0);
57 });
58 test("the tool's filter object is checked", () => {
59 expect(filtersFrom({ city: "Rome" })).toEqual([{ column: "city", text: "Rome" }]);
60 expect(filtersFrom("city")).toBeString();
61 expect(filtersFrom({ city: 1 })).toBeString();
62 expect(filtersFrom(["a"])).toBeString();
63 expect(rowPage(source, "t", undefined, [{ column: "city", text: "Rome" }])?.total).toBe(1);
64 });
65 });
66
67 describe("the page", () => {
68 const mk = () => ({ path: "/data", sources: [source] as readonly Source[] });
69 test("a box per column keeps its value, escaped, and the pager keeps the filter", async () => {
70 const q = new URLSearchParams({ source: "app:x:production:app.db", table: "t", "f.city": '"><b>x' });
71 expect(String(await dataBody(mk(), q))).toContain('name="f.kind"'); // no match: the boxes stay, to be edited
72 const h = String(await dataBody(mk(), new URLSearchParams({ ...Object.fromEntries(q), "f.city": "Par" })));
73 expect(h).toContain('name="f.city"');
74 expect(h).toContain('name="f.kind"');
75 expect(h).toContain('form="rowfilter"');
76 expect(h).toContain('value="Par"');
77 const none = String(await dataBody(mk(), q));
78 expect(none).not.toContain('"><b>x');
79 expect(none).toContain("&quot;&gt;&lt;b&gt;x");
80 });
81 test("a hostile column in the address shows the table with a note", async () => {
82 const q = new URLSearchParams({ source: "app:x:production:app.db", table: "t", 'f.city" OR 1=1 --': "x" });
83 const h = String(await dataBody(mk(), q));
84 expect(h).toContain("cannot be sorted or searched");
85 expect(h).toContain("Paris");
86 expect(h).not.toContain("f.city%22");
87 });
88 });
test/data-csv-export.test.ts +11
@@ -122,6 +122,17 @@ describe("CSV export", () => {
122122 expect((await mcpTool(servers.url, token["bob"]!, "data", { repo: "alice/notes", env: "production", file: "app.db", table: "t", format: "csv" })).error).toBeDefined();
123123 });
124124
125 test("the data tool: a filter on a column the table lacks is invalid, and csv refuses a filter", async () => {
126 const a = { repo: "alice/notes", env: "production", file: "app.db", table: "t" };
127 const bad = await mcpTool(servers.url, token["alice"]!, "data", { ...a, filter: { nope: "x" } });
128 expect(bad.error).toContain("column");
129 expect(bad.error).not.toContain("no such table");
130 const csv = await mcpTool(servers.url, token["alice"]!, "data", { ...a, format: "csv", filter: { s: "a" } });
131 expect(csv.error).toContain("filter");
132 const missing = await mcpTool(servers.url, token["alice"]!, "data", { ...a, table: "nope", filter: { s: "a" } });
133 expect(missing.error).toContain("no such table");
134 });
135
125136 test("a table past 10,000 rows downloads its first 10,000 and says so", async () => {
126137 const res = await get(url("big"), "alice");
127138 expect(res.status).toBe(200);
test/tui-data.test.ts +28
@@ -385,3 +385,31 @@ test("a reader and a guest who reach the screen see no app and none of its spec"
385385 tui.stop?.();
386386 }
387387 });
388
389 test("f filters the table under the cursor by column=text, and says when the column is unknown", async () => {
390 const { tui } = await fresh("alice");
391 await open_(tui, 5);
392 press(tui, "k");
393 press(tui, "f");
394 typeText(tui, "name=zzz");
395 press(tui, "enter");
396 await settleApp(tui);
397 expect(tui.screen.toText()).toContain("users 0 rows");
398 expect(tui.screen.toText()).not.toContain("ann-visible");
399 press(tui, "f");
400 typeText(tui, "name=ann");
401 press(tui, "enter");
402 await settleApp(tui);
403 expect(tui.screen.toText()).toContain("ann-visible");
404 press(tui, "f");
405 typeText(tui, "api_token=tok");
406 press(tui, "enter");
407 await settleApp(tui);
408 expect(tui.screen.toText()).toContain("users 0 rows");
409 press(tui, "f");
410 typeText(tui, 'nope" OR 1=1=x');
411 press(tui, "enter");
412 await settleApp(tui);
413 expect(tui.screen.toText()).toContain("no such column");
414 tui.stop?.();
415 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs