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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16315-the-data-tab-of-an-sqlite-file-filters-a → main 0 commits fork 2 threads · 2 unresolved
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 | ||
| 16 | 16 | |
| 17 | 17 | 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. |
| 18 | 18 | |
| 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. | |
| 20 | 20 | |
| 21 | 21 | 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. |
| 22 | 22 | |
| @@ -24,7 +24,7 @@ API and MCP by repository (`data/repo_scope.ts`, `http/api/data.ts`): `GET /api/ | ||
| 24 | 24 | |
| 25 | 25 | ## On the web (#7580) |
| 26 | 26 | |
| 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. | |
| 28 | 28 | |
| 29 | 29 | 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. |
| 30 | 30 |
src/data/browse.ts +24
| @@ -25,7 +25,20 @@ export interface RowFilter { | ||
| 25 | 25 | readonly exact?: boolean; |
| 26 | 26 | } |
| 27 | 27 | |
| 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 | ||
| 28 | 39 | 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[]; | |
| 29 | 42 | readonly filter?: RowFilter; |
| 30 | 43 | readonly order?: { readonly column: string; readonly dir?: "asc" | "desc" }; |
| 31 | 44 | /** Zero-based. */ |
| @@ -160,6 +173,17 @@ export function rows( | ||
| 160 | 173 | for (let i = 0; i < searchable.length; i++) args.push(`%${like}%`); |
| 161 | 174 | } |
| 162 | 175 | } |
| 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 | } | |
| 163 | 187 | let order = ""; |
| 164 | 188 | if (opts.order) { |
| 165 | 189 | 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"; | ||
| 10 | 10 | import { canWrite, type Repo } from "../core/repos.ts"; |
| 11 | 11 | import type { User } from "../core/users.ts"; |
| 12 | 12 | import { isEnvName } from "../apps/data.ts"; |
| 13 | import { rows, tables } from "./browse.ts"; | |
| 13 | import { rows, tables, type ColumnFilter } from "./browse.ts"; | |
| 14 | 14 | import { query } from "./query.ts"; |
| 15 | 15 | import { sqlWindow } from "./sql_window.ts"; |
| 16 | 16 | import { listSources, type Source } from "./sources.ts"; |
| @@ -64,8 +64,8 @@ export const sourceList = (sources: readonly Source[]) => | ||
| 64 | 64 | |
| 65 | 65 | export const tableList = (source: Source) => tables(source); |
| 66 | 66 | |
| 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 } : {}) }); | |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | 71 | 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 @@ | ||
| 3 | 3 | * tables → rows. Pure: which nodes are open and what to filter by come in, |
| 4 | 4 | * the visible lines go out. Reads happen only for an open file or table. |
| 5 | 5 | */ |
| 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"; | |
| 7 | 7 | import { rowObject, cellLine, type Cell } from "./shape.ts"; |
| 8 | 8 | import type { SpecRow } from "./spec_scope.ts"; |
| 9 | 9 | import type { Source } from "./sources.ts"; |
| @@ -66,6 +66,7 @@ export function visible( | ||
| 66 | 66 | reads: Reads = newReads(), |
| 67 | 67 | page: ReadonlyMap<string, number> = new Map(), |
| 68 | 68 | specs?: Specs, |
| 69 | by: ReadonlyMap<string, readonly ColumnFilter[]> = new Map(), | |
| 69 | 70 | ): Node[] { |
| 70 | 71 | const out: Node[] = []; |
| 71 | 72 | const specNode = (key: string, depth: number, repo: string | undefined) => { |
| @@ -92,19 +93,22 @@ export function visible( | ||
| 92 | 93 | for (const t of list) { |
| 93 | 94 | const key = join(file.key, t.name); |
| 94 | 95 | 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)) { | |
| 101 | 99 | 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 } : {}) })); | |
| 103 | 101 | } catch { |
| 104 | 102 | reads.pages.set(pk, undefined); |
| 105 | 103 | } |
| 106 | 104 | } |
| 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; | |
| 108 | 112 | for (const [i, r] of (got?.rows ?? []).entries()) |
| 109 | 113 | out.push({ |
| 110 | 114 | 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"; | |
| 2 | 2 | import { findSource, listSources, type Source } from "../../../data/sources.ts"; |
| 3 | 3 | import { isFailure, parsePage, pickSource, repoSources, rowPage, runSql, sourceList, tableList } from "../../../data/repo_scope.ts"; |
| 4 | 4 | import { appSpec, forgeSpec } from "../../../data/spec_scope.ts"; |
| 5 | import { filtersFrom } from "../../../data/column_filters.ts"; | |
| 5 | 6 | import { exportCsv } from "../../../data/export_csv.ts"; |
| 6 | 7 | import { bad, good, isAnswer, repoArg, type Tool } from "../shared.ts"; |
| 7 | 8 | |
| @@ -10,7 +11,7 @@ const CSV_ROWS = 1000; | ||
| 10 | 11 | |
| 11 | 12 | export const tool: Tool = { |
| 12 | 13 | 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", | |
| 14 | 15 | description: "Read SQLite files you may see: tables, rows, read-only SQL; secrets masked.", |
| 15 | 16 | inputSchema: { |
| 16 | 17 | type: "object", |
| @@ -25,6 +26,7 @@ export const tool: Tool = { | ||
| 25 | 26 | format: { type: "string" }, |
| 26 | 27 | spec: { type: "boolean" }, |
| 27 | 28 | q: { type: "string" }, |
| 29 | filter: { type: "object", additionalProperties: { type: "string" } }, | |
| 28 | 30 | }, |
| 29 | 31 | }, |
| 30 | 32 | writes: false, |
| @@ -39,11 +41,19 @@ export const tool: Tool = { | ||
| 39 | 41 | const [id, table, sql, env, file] = ["source", "table", "sql", "env", "file"].map(str); |
| 40 | 42 | const format = args["format"]; |
| 41 | 43 | 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 | }; | |
| 42 | 51 | const asCsv = (source: Source, name: string) => { |
| 43 | 52 | const out = exportCsv(ctx.app, user, source, name, { rows: CSV_ROWS }); |
| 44 | 53 | if (out.ok) return good({ format: "csv", rows: out.rows, truncated: out.truncated, csv: out.csv }); |
| 45 | 54 | return out.error === "rate" ? bad("rate_limited", `too many queries: try again in ${out.retryAfter} s`) : bad("not_found", "no such table"); |
| 46 | 55 | }; |
| 56 | if (format === "csv" && args["filter"] !== undefined) return bad("invalid", "`filter` does not apply to `format` csv: read rows without `format`"); | |
| 47 | 57 | if (args["spec"] !== undefined && typeof args["spec"] !== "boolean") return bad("invalid", "`spec` is true or false"); |
| 48 | 58 | if (args["q"] !== undefined && typeof args["q"] !== "string") return bad("invalid", "`q` is text"); |
| 49 | 59 | if (args["spec"] === true) { |
| @@ -54,6 +64,8 @@ export const tool: Tool = { | ||
| 54 | 64 | if (spec === undefined) return bad("not_found", "no such app or repository (owner/name)"); |
| 55 | 65 | return spec === "none" ? bad("not_found", "this app serves no /openapi.json right now") : good(spec); |
| 56 | 66 | } |
| 67 | const by = filtersFrom(args["filter"]); | |
| 68 | if (typeof by === "string") return bad("invalid", by); | |
| 57 | 69 | const page = args["page"]; |
| 58 | 70 | const pageNo = page === undefined || typeof page !== "number" ? undefined : parsePage(page); |
| 59 | 71 | 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 = { | ||
| 71 | 83 | } |
| 72 | 84 | if (table === undefined) return good({ items: tableList(picked) }); |
| 73 | 85 | 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); | |
| 76 | 87 | } |
| 77 | 88 | if (id === undefined) { |
| 78 | 89 | return good(listSources(db, config.dataDir, user).map((s) => ({ source: s.id, label: s.label }))); |
| @@ -85,7 +96,6 @@ export const tool: Tool = { | ||
| 85 | 96 | } |
| 86 | 97 | if (table === undefined) return good(tables(source)); |
| 87 | 98 | 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); | |
| 90 | 100 | }, |
| 91 | 101 | }; |
src/tui/screens/data.ts +34 −5
| @@ -16,7 +16,7 @@ import { query, type QueryResult } from "../../data/query.ts"; | ||
| 16 | 16 | import { cellLine, rowObject, type Cell } from "../../data/shape.ts"; |
| 17 | 17 | import { listSources, maySeeData } from "../../data/sources.ts"; |
| 18 | 18 | 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"; | |
| 20 | 20 | import { exportCsv } from "../../data/export_csv.ts"; |
| 21 | 21 | import { appSpec, forgeSpec, type SpecRow } from "../../data/spec_scope.ts"; |
| 22 | 22 | 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 { | ||
| 127 | 127 | const open = new Set<string>(); |
| 128 | 128 | let at = 0; |
| 129 | 129 | let filter = ""; |
| 130 | let mode: "filter" | "sql" | "values" | undefined; | |
| 130 | let mode: "filter" | "sql" | "values" | "column" | undefined; | |
| 131 | 131 | let line = typing(FILTER_MAX); |
| 132 | 132 | |
| 133 | 133 | // Built once and rebuilt only when `open`, a page, the filter or a reload changes it. |
| 134 | 134 | 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[]>(); | |
| 135 | 137 | let reads = newReads(); |
| 136 | 138 | // The spec nodes' readings, by `forge` or `owner/name`; the forge's is sync, an app's is asked |
| 137 | 139 | // once. |
| @@ -167,7 +169,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 167 | 169 | const lines = (): Node[] => { |
| 168 | 170 | if (shown) return shown; |
| 169 | 171 | 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); | |
| 171 | 173 | return (shown = filtered(built, filter)); |
| 172 | 174 | }; |
| 173 | 175 | const reload = () => { |
| @@ -207,6 +209,28 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 207 | 209 | ); |
| 208 | 210 | } |
| 209 | 211 | |
| 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 | ||
| 210 | 234 | /** The commonest values of `column` in the table under the cursor: the page's pick-list. */ |
| 211 | 235 | function showValues(n: Node | undefined, column: string) { |
| 212 | 236 | const name = column.trim(); |
| @@ -235,7 +259,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 235 | 259 | title: "Data", |
| 236 | 260 | get keys() { |
| 237 | 261 | 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")] | |
| 239 | 263 | : [ |
| 240 | 264 | binding(["j", "k"], "move"), |
| 241 | 265 | binding(["h", "l"], "close / open"), |
| @@ -244,6 +268,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 244 | 268 | binding("y", "yank row as JSON or operation"), |
| 245 | 269 | binding("e", "export table as CSV"), |
| 246 | 270 | binding("v", "common values of a column"), |
| 271 | binding("f", "filter a table by column=text"), | |
| 247 | 272 | binding(["n", "p"], `page of ${PAGE_SIZE}`), |
| 248 | 273 | binding("r", "reload"), |
| 249 | 274 | binding("esc", "back"), |
| @@ -263,7 +288,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 263 | 288 | 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); |
| 264 | 289 | }); |
| 265 | 290 | 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); | |
| 267 | 292 | } |
| 268 | 293 | }, |
| 269 | 294 | key(e) { |
| @@ -279,6 +304,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 279 | 304 | dirty(); |
| 280 | 305 | at = 0; |
| 281 | 306 | } else if (done === "values") showValues(current(), line.text); |
| 307 | else if (done === "column") setColumnFilter(current(), line.text); | |
| 282 | 308 | else ask(line.text); |
| 283 | 309 | } else if (!line.key(e)) return true; |
| 284 | 310 | else if (mode === "filter") { |
| @@ -312,6 +338,9 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 312 | 338 | } else if (e.key === "v") { |
| 313 | 339 | mode = "values"; |
| 314 | 340 | line = typing(FILTER_MAX); |
| 341 | } else if (e.key === "f") { | |
| 342 | mode = "column"; | |
| 343 | line = typing(FILTER_MAX); | |
| 315 | 344 | } else if (e.key === ":") { |
| 316 | 345 | mode = "sql"; |
| 317 | 346 | 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 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import { PAGE_SIZE, rows, tables, topValues, type RowsResult } from "../../data/browse.ts"; |
| 11 | import { columnFilters, FILTER_PREFIX, filterParams } from "../../data/column_filters.ts"; | |
| 11 | 12 | import { query } from "../../data/query.ts"; |
| 12 | 13 | import type { Source } from "../../data/sources.ts"; |
| 13 | 14 | import type { SpecAnswer } from "../../data/spec_scope.ts"; |
| @@ -68,11 +69,12 @@ function grid( | ||
| 68 | 69 | caption: string, |
| 69 | 70 | head: (c: string) => Html, |
| 70 | 71 | copyIds: boolean, |
| 72 | boxes?: (c: string) => Html, | |
| 71 | 73 | ): Html { |
| 72 | 74 | return html`<div class="table-scroll"> |
| 73 | 75 | <table class="table" data-dense data-sortable> |
| 74 | 76 | <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> | |
| 76 | 78 | <tbody> |
| 77 | 79 | ${data.map( |
| 78 | 80 | (r, i) => html`<tr> |
| @@ -148,17 +150,22 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html | ||
| 148 | 150 | const col = q.get("col") || undefined; |
| 149 | 151 | const exact = col !== undefined && q.get("exact") === "1"; |
| 150 | 152 | 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) }; | |
| 152 | 155 | let shown: RowsResult | undefined = rows(source, tableName, { |
| 153 | 156 | page: pageNo, |
| 157 | ...(by.length > 0 ? { by } : {}), | |
| 154 | 158 | ...(sort ? { order: { column: sort, dir } } : {}), |
| 155 | 159 | ...(text !== "" ? { filter: { text, ...(col ? { column: col } : {}), ...(exact ? { exact } : {}) } } : {}), |
| 156 | 160 | }); |
| 157 | 161 | let note: string | null = null; |
| 158 | if (!shown && (sort || text !== "")) { | |
| 162 | if (!shown && (sort || text !== "" || by.length > 0)) { | |
| 159 | 163 | // An unknown or sealed column cannot be sorted or searched: show the table, say so. |
| 160 | 164 | shown = rows(source, tableName, { page: pageNo }); |
| 161 | 165 | 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])) }; | |
| 162 | 169 | } |
| 163 | 170 | if (!shown) return undefined; |
| 164 | 171 | const cols = shown.columns; |
| @@ -175,13 +182,17 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html | ||
| 175 | 182 | ? html`<p class="muted small">Too many queries to list common values; try again in ${String(wait)} s.</p>` |
| 176 | 183 | : null; |
| 177 | 184 | const more = (shown.page + 1) * PAGE_SIZE < shown.total; |
| 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>`; | |
| 178 | 189 | const header = (c: string): Html => { |
| 179 | 190 | const next = sort === c && dir === "asc" ? "desc" : "asc"; |
| 180 | 191 | 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>`; |
| 181 | 192 | }; |
| 182 | 193 | out = html`${out} |
| 183 | 194 | <h2>${tableName}</h2> |
| 184 | <form method="get" action="${path}" role="search"> | |
| 195 | <form method="get" action="${path}" role="search" id="rowfilter"> | |
| 185 | 196 | <input type="hidden" name="source" value="${source.id}" /> |
| 186 | 197 | <input type="hidden" name="table" value="${tableName}" /> |
| 187 | 198 | ${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 | ||
| 202 | 213 | })} |
| 203 | 214 | <div class="form-actions"> |
| 204 | 215 | ${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} | |
| 206 | 217 | ${view.byEnv ? btn("Download CSV", { href: url(`${path}/${encodeURIComponent(tableName)}.csv`, { source: source.id }), size: "sm", variant: "outline" }) : null} |
| 207 | 218 | </div> |
| 208 | 219 | </form> |
| 209 | 220 | ${note ? html`<p class="muted small">${note}</p>` : null} |
| 210 | 221 | ${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)} | |
| 212 | 224 | ${pager({ |
| 213 | 225 | note: `${shown.total} rows`, |
| 214 | 226 | 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(""><b>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", () => { | ||
| 122 | 122 | expect((await mcpTool(servers.url, token["bob"]!, "data", { repo: "alice/notes", env: "production", file: "app.db", table: "t", format: "csv" })).error).toBeDefined(); |
| 123 | 123 | }); |
| 124 | 124 | |
| 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 | ||
| 125 | 136 | test("a table past 10,000 rows downloads its first 10,000 and says so", async () => { |
| 126 | 137 | const res = await get(url("big"), "alice"); |
| 127 | 138 | 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" | ||
| 385 | 385 | tui.stop?.(); |
| 386 | 386 | } |
| 387 | 387 | }); |
| 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 | }); |
new above
offline
basespreadsfilterParams(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 hostilef.key. Keep only filters on real columns.