/** * `list_records`' `where`, checked against the table and then written as SQL * over the object's rows, as the made-table SQL is (crates/cotton-core/src/ * records/mod.rs `parse_where`; tables/mod.rs `condition_sql`, `within_days`): * a page of a table is read in SQL, never the table into memory. */ import { fail, type Data } from "../../context.ts"; import { col, typeOf, type Cond } from "../../../store.ts"; import { isSensitiveColumn, type Table } from "./table.ts"; import { checkValue, describe, quoted } from "./values.ts"; export type Condition = | { is: unknown } | { oneOf: unknown[] } | { noneOf: unknown[] } | { present: boolean } | { month: number } | { window: "within" | "before" | "ahead"; days: number }; export interface Clause { column: string; condition: Condition; multipleLink?: boolean; } function bad(column: string, reason: string): never { fail(`where ${quoted(column)}: ${reason}`); } function anyOf(t: Table, name: string, values: unknown[]): unknown[] { if (!values.length) bad(name, "values is a list of at least one value"); const column = t.column(name)!; for (const v of values) { if (v === null || Array.isArray(v) || typeof v === "object") bad(name, `each of values is one value; ${describe(v)} is not`); checkValue(t, column.type === "link" && column.multiple ? { ...column, multiple: false } : column, v); } return values; } export function parseWhere(t: Table, value: unknown): Clause[] { if (value === undefined || value === null) return []; if (typeof value !== "object" || Array.isArray(value)) bad("", `where is an object of column keys and the values they hold; ${describe(value)} is not one`); const out: Clause[] = []; for (const [name, wanted] of Object.entries(value as Data)) { const column = t.column(name) ?? fail(`${t.plural} have no column ${quoted(name)}`); // A column no read answers is no column to narrow by either: a match would answer what it holds. if (isSensitiveColumn(name) || column.secret === true) bad(name, "it is never read, so nothing is narrowed by it"); if (t.sealed(name)) bad(name, `${t.plural} keep it sealed: the object cannot read it to narrow by it`); let condition: Condition; if (wanted === null) { bad(name, 'null matches nothing here; ask for {"present": false} to find records where it is empty'); } else if (Array.isArray(wanted)) { condition = { oneOf: anyOf(t, name, wanted) }; } else if (typeof wanted === "object") { const keys = Object.keys(wanted as Data); if (keys.length !== 1) bad(name, 'say exactly one of {"values": [...]}, {"not": [...]}, {"present": true | false} or, on a date, {"month": 1-12} or {"within_days": n}'); const only = keys[0]!; const shape = (wanted as Data)[only]; const date = column.type === "date"; if (only === "values") { if (!Array.isArray(shape) || !shape.length) bad(name, "values is a list of at least one value"); condition = { oneOf: anyOf(t, name, shape) }; } else if (only === "not") { if (!Array.isArray(shape) || !shape.length) bad(name, "not is a list of at least one value"); condition = { noneOf: anyOf(t, name, shape) }; } else if (only === "month") { if (!date) bad(name, "month narrows only a date column"); if (typeof shape !== "number" || !Number.isInteger(shape) || shape < 1 || shape > 12) bad(name, `month is a number from 1 to 12; ${describe(shape)} is not`); condition = { month: shape }; } else if (only === "within_days" || only === "before_days" || only === "ahead_days") { if (!date) bad(name, "within_days narrows only a date column"); if (typeof shape !== "number" || !Number.isInteger(shape) || shape < 1) bad(name, `within_days is a whole number of days, 1 or more; ${describe(shape)} is not`); condition = { window: only === "before_days" ? "before" : only === "ahead_days" ? "ahead" : "within", days: shape }; } else if (only === "present") { if (typeof shape !== "boolean") bad(name, `present is true or false; ${describe(shape)} is not`); condition = { present: shape }; } else { bad(name, `${quoted(only)} is not a condition; say {"values": [...]}, {"not": [...]} or {"present": true | false}`); } } else { checkValue(t, column.type === "link" && column.multiple ? { ...column, multiple: false } : column, wanted); condition = { is: wanted }; } out.push({ column: name, condition, ...(column.type === "link" && column.multiple ? { multipleLink: true } : {}) }); } return out; } /** A value as SQLite binds it: a bool its 1 or 0. */ function bound(v: unknown): SqlStorageValue { if (typeof v === "boolean") return v ? 1 : 0; if (typeof v === "number" || typeof v === "string") return v; return JSON.stringify(v); } /** SQLite's `=` over what a row keeps: numbers by worth, a string exactly, never a list or an object. */ export function equalSql(key: string, value: unknown): Cond { return { sql: `${typeOf(key)} NOT IN ('object', 'array') AND ${col(key)} = ?`, args: [bound(value)] }; } /** Empty: absent, null or "". */ export function blankSql(key: string): string { return `COALESCE(${col(key)}, '') = ''`; } const DAY = 86_400_000; /** A text value read as an instant, in epoch milliseconds (NULL when it reads as none). */ const millis = (key: string): string => `(julianday(${col(key)}) - 2440587.5) * 86400000.0`; export function clauseSql(clause: Clause, nowMs: number): Cond { const k = clause.column; const c = clause.condition; // A related record names one member of a declared multiple link. const equal = (value: unknown): Cond => clause.multipleLink ? { sql: `EXISTS (SELECT 1 FROM json_each(CASE WHEN ${typeOf(k)} = 'array' THEN ${col(k)} ELSE '[]' END) linked WHERE linked.type = 'text' AND linked.value = ?)`, args: [bound(value)] } : equalSql(k, value); const any = (values: unknown[]): Cond => { const parts = values.map(equal); return { sql: parts.map((p) => `(${p.sql})`).join(" OR "), args: parts.flatMap((p) => p.args) }; }; if ("is" in c) return equal(c.is); if ("oneOf" in c) return any(c.oneOf); if ("noneOf" in c) { const one = any(c.noneOf); return { sql: `NOT (${blankSql(k)}) AND NOT (${one.sql})`, args: one.args }; } if ("present" in c) return { sql: c.present ? `NOT (${blankSql(k)})` : blankSql(k), args: [] }; const text = `${typeOf(k)} = 'text'`; if ("month" in c) return { sql: `${text} AND ${col(k)} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]*' AND CAST(substr(${col(k)}, 6, 2) AS INTEGER) = ?`, args: [c.month] }; const at = `${text} AND julianday(${col(k)}) IS NOT NULL AND ${millis(k)}`; switch (c.window) { case "within": return { sql: `${at} >= ?`, args: [nowMs - c.days * DAY] }; case "before": return { sql: `${at} < ?`, args: [nowMs - c.days * DAY] }; case "ahead": return { sql: `${at} >= ? AND ${millis(k)} <= ?`, args: [nowMs - DAY, nowMs + c.days * DAY] }; } }