|
| 1 | +import type { Kysely } from "kysely"; |
| 2 | +import { sql } from "kysely"; |
| 3 | + |
| 4 | +import { columnExists, listTablesLike } from "../dialect-helpers.js"; |
| 5 | +import { validateIdentifier } from "../validate.js"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Denormalize the filter + sort columns from `ec_*` onto `content_taxonomies` |
| 9 | + * and mirror `ec_*`'s composite sort indexes onto the pivot (#1834). |
| 10 | + * |
| 11 | + * A taxonomy-filtered listing used to apply the term filter as a correlated |
| 12 | + * `EXISTS` on `SELECT * FROM ec_<collection> … ORDER BY … LIMIT ?`. The pivot |
| 13 | + * carried only `(collection, entry_id, taxonomy_id)`, so the filter |
| 14 | + * (`deleted_at`, `status`, `locale`) and the sort (`published_at`/`created_at`) |
| 15 | + * could only be evaluated on the `ec_*` row. On stats-blind SQLite/D1 a |
| 16 | + * selective term never fills the `LIMIT`, so the query walked the whole |
| 17 | + * collection (~75k D1 rows read for a one-row page). |
| 18 | + * |
| 19 | + * Copying those columns onto the pivot and indexing them keyed by |
| 20 | + * `(taxonomy_id, collection, …)` lets the loader seek the term and walk a |
| 21 | + * sort-ordered pivot index, short-circuiting on `LIMIT`, then touch `ec_*` only |
| 22 | + * by primary key to hydrate the page. |
| 23 | + * |
| 24 | + * The columns are advisory (D1 has no transactions; the write-path re-stamp is |
| 25 | + * non-atomic), so the read path re-checks the real predicates on the joined |
| 26 | + * `ec_*` row — see loader.ts. `updated_at` is deliberately not denormalized: it |
| 27 | + * moves on every edit and is seldom a public sort, so its write cost outweighs |
| 28 | + * its read value; `updated_at`-sorted taxonomy listings temp-sort instead. |
| 29 | + * |
| 30 | + * Order matters: add the columns, backfill, THEN build the indexes so each |
| 31 | + * index is built once over populated data rather than maintained through the |
| 32 | + * backfill `UPDATE`. |
| 33 | + * |
| 34 | + * Forward-only. |
| 35 | + */ |
| 36 | + |
| 37 | +const DENORM_COLUMNS = [ |
| 38 | + "status", |
| 39 | + "scheduled_at", |
| 40 | + "deleted_at", |
| 41 | + "locale", |
| 42 | + "published_at", |
| 43 | + "created_at", |
| 44 | +] as const; |
| 45 | + |
| 46 | +// `entry_id DESC` (not ASC) matters: the listing orders `<sort> DESC, entry_id |
| 47 | +// DESC` (the common case), and a DESC tiebreaker lets SQLite satisfy the whole |
| 48 | +// ORDER BY from the index — no temp B-tree, clean early-`LIMIT`. An ASC |
| 49 | +// tiebreaker forces `USE TEMP B-TREE FOR LAST TERM OF ORDER BY`, which buffers |
| 50 | +// a whole equal-`sortval` block (e.g. a bulk import sharing one timestamp) |
| 51 | +// before emitting. `DESC` also serves the rarer ASC listing via a backward |
| 52 | +// index scan. Mirrors `ec_*`'s `(deleted_at, [locale,] <sort> DESC, id DESC)`. |
| 53 | +const INDEXES: { name: string; columns: string }[] = [ |
| 54 | + { |
| 55 | + name: "idx_content_taxonomies_pub", |
| 56 | + columns: "taxonomy_id, collection, deleted_at, published_at DESC, entry_id DESC", |
| 57 | + }, |
| 58 | + { |
| 59 | + name: "idx_content_taxonomies_crt", |
| 60 | + columns: "taxonomy_id, collection, deleted_at, created_at DESC, entry_id DESC", |
| 61 | + }, |
| 62 | + { |
| 63 | + name: "idx_content_taxonomies_loc_pub", |
| 64 | + columns: "taxonomy_id, collection, deleted_at, locale, published_at DESC, entry_id DESC", |
| 65 | + }, |
| 66 | + { |
| 67 | + name: "idx_content_taxonomies_loc_crt", |
| 68 | + columns: "taxonomy_id, collection, deleted_at, locale, created_at DESC, entry_id DESC", |
| 69 | + }, |
| 70 | +]; |
| 71 | + |
| 72 | +export async function up(db: Kysely<unknown>): Promise<void> { |
| 73 | + // 1. Add the six denormalized columns (all nullable, no default). Guarded so |
| 74 | + // a partial apply — or a re-run after a mid-migration failure — can retry |
| 75 | + // (`ALTER TABLE ADD COLUMN` is not itself idempotent on either dialect). |
| 76 | + for (const column of DENORM_COLUMNS) { |
| 77 | + if (await columnExists(db, "content_taxonomies", column)) continue; |
| 78 | + await sql` |
| 79 | + ALTER TABLE content_taxonomies ADD COLUMN ${sql.ref(column)} TEXT |
| 80 | + `.execute(db); |
| 81 | + } |
| 82 | + |
| 83 | + // 2. Backfill from each content table by primary key. Drive from the actual |
| 84 | + // `ec_*` tables (not `_emdash_collections`) so collections whose table was |
| 85 | + // dropped are skipped naturally; the pivot's `collection` value is the |
| 86 | + // slug, i.e. the table name without its `ec_` prefix. |
| 87 | + const tableNames = await listTablesLike(db, "ec_%"); |
| 88 | + for (const tableName of tableNames) { |
| 89 | + validateIdentifier(tableName, "content table name"); |
| 90 | + const slug = tableName.slice("ec_".length); |
| 91 | + await sql` |
| 92 | + UPDATE content_taxonomies |
| 93 | + SET (status, scheduled_at, deleted_at, locale, published_at, created_at) = ( |
| 94 | + SELECT status, scheduled_at, deleted_at, locale, published_at, created_at |
| 95 | + FROM ${sql.ref(tableName)} |
| 96 | + WHERE ${sql.ref(tableName)}.id = content_taxonomies.entry_id |
| 97 | + ) |
| 98 | + WHERE collection = ${slug} |
| 99 | + `.execute(db); |
| 100 | + } |
| 101 | + |
| 102 | + // 3. Build the composite sort indexes over the now-populated columns. |
| 103 | + for (const index of INDEXES) { |
| 104 | + await sql` |
| 105 | + CREATE INDEX IF NOT EXISTS ${sql.ref(index.name)} |
| 106 | + ON content_taxonomies (${sql.raw(index.columns)}) |
| 107 | + `.execute(db); |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +export async function down(db: Kysely<unknown>): Promise<void> { |
| 112 | + for (const index of INDEXES) { |
| 113 | + await sql`DROP INDEX IF EXISTS ${sql.ref(index.name)}`.execute(db); |
| 114 | + } |
| 115 | + for (const column of DENORM_COLUMNS) { |
| 116 | + await sql` |
| 117 | + ALTER TABLE content_taxonomies DROP COLUMN ${sql.ref(column)} |
| 118 | + `.execute(db); |
| 119 | + } |
| 120 | +} |
0 commit comments