Cotton code
200 lines · 10.1 KB · TypeScriptRaw
/** * WHERE A DATABASE FILE'S BYTES GO (owner, 22 Nov 2026: his file stood at * 6.5 GB while its records' values came to about 1.45 GB). A Durable Object's * SQLite answers no `dbstat` and no `page_count`, so the file cannot be asked * page by page; this works each part out from what it holds, sizes only, never * a value: every store table and every index, its entries and the bytes its * entries carry (each value's own width: text and blobs by their bytes, a * number by 8), one scan of each table with every index on it measured in the * same pass. What the parts do not cover (each entry's cell and record * headers, the b-trees' inner pages and the room left on each page) is the * remainder against the file's own size, said as `overhead`. * * Read by `storage_summary` (src/mcp/tools/records/summary.ts), unless it is * asked `parts: false`. */export interface StoragePart {  /** The store table or index. */  name: string;  kind: "table" | "index";  /** The table an index orders. */  of?: string;  /** Entries: a table's rows, an index's keys (a partial index's only where its condition holds). */  entries: number;  /** The bytes the entries' own values take. */  bytes: number;}export interface StorageParts {  /** The file's size, as the object reports it. */  file: number;  parts: StoragePart[];  /** The bytes the parts carry, together. */  carried: number;  /** The file less what the parts carry: per-entry headers, inner pages and free room on pages. */  overhead: number;}/** A value's width in its column: what SQLite stores for it, near enough (a number's varint is said as 8). */const width = (expr: string): string => `(CASE typeof(${expr}) WHEN 'null' THEN 0 WHEN 'integer' THEN 8 WHEN 'real' THEN 8 ELSE length(CAST(${expr} AS BLOB)) END)`;/** `a, f(b, c), d` split at its top-level commas. */export function topLevel(list: string): string[] {  const out: string[] = [];  let depth = 0;  let quote: string | null = null;  let at = 0;  for (let i = 0; i < list.length; i++) {    const c = list[i]!;    if (quote) {      if (c === quote) quote = null;      continue;    }    if (c === "'" || c === '"') quote = c;    else if (c === "(") depth++;    else if (c === ")") depth--;    else if (c === "," && depth === 0) {      out.push(list.slice(at, i).trim());      at = i + 1;    }  }  out.push(list.slice(at).trim());  return out.filter(Boolean);}/** An index's key expressions and its condition, read from its own CREATE INDEX text. */export function indexShape(sql: string): { keys: string[]; where: string | null } | null {  const open = sql.indexOf("(", sql.search(/\bON\b/i));  if (open < 0) return null;  let depth = 0;  let close = -1;  let quote: string | null = null;  for (let i = open; i < sql.length; i++) {    const c = sql[i]!;    if (quote) {      if (c === quote) quote = null;      continue;    }    if (c === "'" || c === '"') quote = c;    else if (c === "(") depth++;    else if (c === ")" && --depth === 0) {      close = i;      break;    }  }  if (close < 0) return null;  const keys = topLevel(sql.slice(open + 1, close)).map((k) => k.replace(/\s+(ASC|DESC)$/i, "").replace(/\s+COLLATE\s+\w+$/i, ""));  const rest = sql.slice(close + 1);  const w = rest.search(/\bWHERE\b/i);  return { keys, where: w >= 0 ? rest.slice(w + 5).trim() : null };}const quoted = (name: string): string => `"${name.replace(/"/g, '""')}"`;/** * Every part of the file: each table (its rows and the bytes of every column), * and each index on it (its keys' bytes, the rowid or primary key each entry * carries included), measured together in one pass over the table. Sizes only. *//** One store table's measures: the SQL figures one pass over it works out, and where each index's pair of figures sits. */export interface PartsJob {  name: string;  /** No rowid: a range is read along the primary key (`pk`) instead. */  withoutRowid: boolean;  /** The primary key's columns, quoted, in order. */  pk: string[];  measures: string[];  indexes: { name: string; at: number }[];}/** What to measure, table by table: the figures for each table and every index on it, read from the schema alone. */export function partsPlan(sql: SqlStorage): PartsJob[] {  const objects = sql    .exec<{ type: string; name: string; tbl_name: string; sql: string | null }>("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%' ORDER BY name")    .toArray();  const tables = objects.filter((o) => o.type === "table" && o.sql && !/^CREATE VIRTUAL/i.test(o.sql));  const jobs: PartsJob[] = [];  for (const t of tables) {    const info = sql.exec<{ name: string; type: string; pk: number }>(`PRAGMA table_info(${quoted(t.name)})`).toArray();    const withoutRowid = /WITHOUT\s+ROWID/i.test(t.sql ?? "");    const pk = info.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk).map((c) => quoted(c.name));    // An index entry carries the row's key besides its own: the rowid (8), or a WITHOUT ROWID table's primary key.    const rowKey = withoutRowid ? pk.map(width).join(" + ") || "0" : "8";    // A table of numbers only (the search index's `blind`: tens of millions of entries) is counted, never read value by    // value: each entry is its columns at 8 bytes, and each index on it its keys and row key at 8 a column.    const numeric = info.length > 0 && info.every((c) => /INT|REAL|NUM/i.test(c.type ?? ""));    const all = numeric ? String(8 * info.length) : info.map((c) => width(quoted(c.name))).join(" + ") || "0";    const measures = ["COUNT(*)", numeric ? `COUNT(*) * ${all}` : `SUM(${all})`];    const indexes: { name: string; at: number }[] = [];    const add = (name: string, keys: string[], where: string | null): void => {      if (numeric && !where) {        indexes.push({ name, at: measures.length });        measures.push(`COUNT(*) * ${8 * (keys.length + (withoutRowid ? pk.length : 1))}`, "COUNT(*)");        return;      }      const key = `${keys.map(width).join(" + ")} + ${rowKey}`;      indexes.push({ name, at: measures.length });      measures.push(where ? `SUM(CASE WHEN ${where} THEN ${key} ELSE 0 END)` : `SUM(${key})`, where ? `SUM(CASE WHEN ${where} THEN 1 ELSE 0 END)` : "COUNT(*)");    };    for (const u of sql.exec<{ name: string; origin: string }>(`PRAGMA index_list(${quoted(t.name)})`).toArray()) {      // A WITHOUT ROWID table's primary key is the table itself.      if (withoutRowid && u.origin === "pk") continue;      const made = objects.find((o) => o.type === "index" && o.name === u.name)?.sql;      const shape = made ? indexShape(made) : null;      if (shape) add(u.name, shape.keys, shape.where);      else {        // One SQLite keeps for a PRIMARY KEY or UNIQUE: its columns, from the index itself.        const cols = sql.exec<{ name: string | null }>(`PRAGMA index_info(${quoted(u.name)})`).toArray().map((c) => c.name).filter((c): c is string => !!c);        if (cols.length) add(`${u.name} (${t.name}: ${cols.join(", ")})`, cols.map(quoted), null);      }    }    jobs.push({ name: t.name, withoutRowid, pk, measures, indexes });  }  return jobs;}/** Where a range ends: a rowid, or a WITHOUT ROWID table's primary key, its columns' values in order. */export type RangeEnd = number | SqlStorageValue[];/** * A job's figures over its rows past `after` (a rowid, or a WITHOUT ROWID table's primary key; null: from the start), * at most `most` of them in that order (null: the whole table), and where the range ended (null when it held none). */export function measureRange(sql: SqlStorage, job: PartsJob, after: RangeEnd | null = null, most: number | null = null): { figures: number[]; last: RangeEnd | null } {  const sum = (from: string, extra = "", ...args: SqlStorageValue[]): Record<string, SqlStorageValue> =>    sql.exec(`SELECT ${job.measures.map((m, i) => `${m} AS m${i}`).join(", ")}${extra} FROM ${from}`, ...args).one();  const figures = (got: Record<string, SqlStorageValue>): number[] => job.measures.map((_m, i) => Number(got[`m${i}`] ?? 0));  if (most === null) return { figures: figures(sum(quoted(job.name))), last: null };  const limit = Math.max(1, Math.floor(most));  if (!job.withoutRowid) {    const got = sum(`(SELECT rowid AS rowid_, * FROM ${quoted(job.name)} WHERE rowid > ? ORDER BY rowid LIMIT ${limit})`, ", MAX(rowid_) AS last_", typeof after === "number" ? after : 0);    return { figures: figures(got), last: got.last_ === null || got.last_ === undefined ? null : Number(got.last_) };  }  // Along the primary key: the range's figures, then the key it ended at.  const keys = job.pk.join(", ");  const past = Array.isArray(after) && after.length === job.pk.length ? `WHERE (${keys}) > (${job.pk.map(() => "?").join(", ")})` : "";  const args = Array.isArray(after) && after.length === job.pk.length ? after : [];  const range = `(SELECT * FROM ${quoted(job.name)} ${past} ORDER BY ${keys} LIMIT ${limit})`;  const got = sum(range, "", ...args);  const end = sql.exec(`SELECT ${keys} FROM ${range} ORDER BY ${job.pk.map((k) => `${k} DESC`).join(", ")} LIMIT 1`, ...args).toArray()[0];  return { figures: figures(got), last: end ? job.pk.map((_k, i) => Object.values(end)[i] ?? null) : null };}/** A job's parts from its figures: the table, then each index on it. */export function partsOf(job: PartsJob, figures: number[]): StoragePart[] {  const n = (i: number): number => figures[i] ?? 0;  return [{ name: job.name, kind: "table", entries: n(0), bytes: n(1) }, ...job.indexes.map((i): StoragePart => ({ name: i.name, kind: "index", of: job.name, entries: n(i.at + 1), bytes: n(i.at) }))];}/** The parts, largest first, against the file's size. */export function partsTotal(file: number, parts: StoragePart[]): StorageParts {  parts.sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));  const carried = parts.reduce((s, p) => s + p.bytes, 0);  return { file, parts, carried, overhead: Math.max(0, file - carried) };}/** Every part measured now, in one pass of each table: a small object's, or a test's. */export function storageParts(sql: SqlStorage): StorageParts {  return partsTotal(sql.databaseSize, partsPlan(sql).flatMap((job) => partsOf(job, measureRange(sql, job).figures)));}