-
Notifications
You must be signed in to change notification settings - Fork 1.1k
fix(core): index translation_group with locale so translation lookups seek #2328
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MA2153
wants to merge
6
commits into
emdash-cms:main
Choose a base branch
from
MA2153:fix/translation-group-locale-index
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
994ee0e
fix(core): index translation_group with locale so lookups seek
MA2153 c1bcaf4
docs(core): trim planner narrative from translation-index comments
MA2153 0b3a249
fix(core): keep translation-group reads seeking at full batch size
MA2153 a29e012
test(core): cover the translation index swap for long collection slugs
MA2153 b19004d
fix(core): keep a translation_group-leading index for menu lookups
MA2153 a75abab
Merge branch 'main' into fix/translation-group-locale-index
MA2153 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "emdash": patch | ||
| --- | ||
|
|
||
| Fixes translation lookups reading every non-deleted row of a content table. Content tables now carry `(translation_group, locale)` and `(deleted_at, translation_group, locale)` indexes, replacing the single-column `translation_group` one, so fetching an entry's translations — one entry's, a whole page's, or a menu link's target — seeks straight to the group instead of scanning. The improvement is largest on big collections and on D1, where the query planner has no statistics to fall back on. |
67 changes: 67 additions & 0 deletions
67
packages/core/src/database/migrations/055_content_translation_group_locale_index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import type { Kysely } from "kysely"; | ||
| import { sql } from "kysely"; | ||
|
|
||
| import { listTablesLike } from "../dialect-helpers.js"; | ||
|
|
||
| /** | ||
| * Migration: replace the single-column content `translation_group` index with | ||
| * one index per translation-group read shape. | ||
| * | ||
| * There are two shapes. Translation-group reads filter `deleted_at IS NULL` | ||
| * with `translation_group = ?` / `IN (...)` and order by locale; menu and | ||
| * reference resolution looks a group up by `translation_group` (+ `locale`) | ||
| * alone, with no `deleted_at` term. | ||
| * | ||
| * Neither shape can borrow the other's index. Seeking migration 041's | ||
| * `(deleted_at, locale, ...)` composites on `deleted_at` alone already returns | ||
| * rows in locale order, so a stats-blind planner prefers them over a | ||
| * single-column `translation_group` index and reads every non-deleted row in | ||
| * the table; the batched variant is worse still, because the `IN (...)` list | ||
| * multiplies the planner's row estimate for a `translation_group`-leading index | ||
| * and it falls back to a `deleted_at` composite from a handful of groups | ||
| * onward. Going the other way, an index leading with `deleted_at` cannot seek a | ||
| * lookup that never constrains that column. D1 never has `sqlite_stat1`, so the | ||
| * index shape is the only lever and each shape needs a prefix matching it term | ||
| * for term. | ||
| * | ||
| * Forward-only and idempotent (`IF NOT EXISTS`). | ||
| * | ||
| * Index names use short `tg_locale` / `del_tg_locale` suffixes rather than | ||
| * spelling out `translation_group`: Postgres truncates identifiers to 63 bytes, | ||
| * and the longer forms truncate to the same value for long collection slugs. | ||
| * Keep these identical to the names in `schema/registry.ts`. | ||
| */ | ||
| export async function up(db: Kysely<unknown>): Promise<void> { | ||
| const tableNames = await listTablesLike(db, "ec_%"); | ||
|
|
||
| for (const tableName of tableNames) { | ||
| // D1 DDL is non-transactional: create the replacements before dropping the | ||
| // old index so an interrupted migration always leaves a | ||
| // translation_group-leading index in place. | ||
| await sql` | ||
| CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${tableName}_tg_locale`)} | ||
| ON ${sql.ref(tableName)} (translation_group, locale) | ||
| `.execute(db); | ||
|
|
||
| await sql` | ||
| CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${tableName}_del_tg_locale`)} | ||
| ON ${sql.ref(tableName)} (deleted_at, translation_group, locale) | ||
| `.execute(db); | ||
|
|
||
| await sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${tableName}_translation_group`)}`.execute(db); | ||
| } | ||
| } | ||
|
|
||
| export async function down(db: Kysely<unknown>): Promise<void> { | ||
| const tableNames = await listTablesLike(db, "ec_%"); | ||
|
|
||
| for (const tableName of tableNames) { | ||
| await sql` | ||
| CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${tableName}_translation_group`)} | ||
| ON ${sql.ref(tableName)} (translation_group) | ||
| `.execute(db); | ||
|
|
||
| await sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${tableName}_del_tg_locale`)}`.execute(db); | ||
| await sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${tableName}_tg_locale`)}`.execute(db); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
80 changes: 80 additions & 0 deletions
80
packages/core/tests/integration/database/content-translation-index-name.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { sql } from "kysely"; | ||
| import { afterEach, beforeEach, expect, it } from "vitest"; | ||
|
|
||
| import * as migration055 from "../../../src/database/migrations/055_content_translation_group_locale_index.js"; | ||
| import { SchemaRegistry } from "../../../src/schema/registry.js"; | ||
| import { | ||
| type DialectTestContext, | ||
| describeEachDialect, | ||
| setupForDialect, | ||
| teardownForDialect, | ||
| } from "../../utils/test-db.js"; | ||
|
|
||
| /** | ||
| * The longest collection slug `SchemaRegistry` can create on Postgres: at 47 | ||
| * characters the `deleted_updated_id` and `deleted_status` index names collide | ||
| * once Postgres truncates identifiers to 63 bytes. `idx_{table}_tg_locale` and | ||
| * `idx_{table}_del_tg_locale` are truncated at this length too, so the | ||
| * migration's creates and drop must still name three different indexes. | ||
| */ | ||
| const LONG_SLUG = `t${"o".repeat(45)}`; | ||
| const TABLE_NAME = `ec_${LONG_SLUG}`; | ||
|
|
||
| describeEachDialect("translation_group index replacement for long collection slugs", (dialect) => { | ||
| let ctx: DialectTestContext; | ||
|
|
||
| beforeEach(async () => { | ||
| ctx = await setupForDialect(dialect); | ||
| const registry = new SchemaRegistry(ctx.db); | ||
| await registry.createCollection({ slug: LONG_SLUG, label: "Long", labelSingular: "Long" }); | ||
|
|
||
| await sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${TABLE_NAME}_tg_locale`)}`.execute(ctx.db); | ||
| await sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${TABLE_NAME}_del_tg_locale`)}`.execute(ctx.db); | ||
| await sql` | ||
| CREATE INDEX ${sql.ref(`idx_${TABLE_NAME}_translation_group`)} | ||
| ON ${sql.ref(TABLE_NAME)} (translation_group) | ||
| `.execute(ctx.db); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await teardownForDialect(ctx); | ||
| }); | ||
|
|
||
| it("leaves the table with both composite indexes, not with one or none", async () => { | ||
| await migration055.up(ctx.db); | ||
|
|
||
| const covering = (await translationIndexColumns()) | ||
| .filter((columns) => columns.includes("translation_group")) | ||
| .toSorted(); | ||
| expect(covering).toEqual([ | ||
| "deleted_at, translation_group, locale", | ||
| "translation_group, locale", | ||
| ]); | ||
| }); | ||
|
|
||
| async function translationIndexColumns(): Promise<string[]> { | ||
| if (ctx.dialect === "postgres") { | ||
| const result = await sql<{ indexdef: string }>` | ||
| SELECT indexdef FROM pg_indexes | ||
| WHERE schemaname = current_schema() AND tablename = ${TABLE_NAME} | ||
| `.execute(ctx.db); | ||
| return result.rows.map((row) => columnList(row.indexdef)); | ||
| } | ||
|
|
||
| const result = await sql<{ sql: string | null }>` | ||
| SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${TABLE_NAME} | ||
| `.execute(ctx.db); | ||
| return result.rows.map((row) => columnList(row.sql ?? "")); | ||
| } | ||
| }); | ||
|
|
||
| function columnList(definition: string): string { | ||
| const open = definition.lastIndexOf("("); | ||
| const close = definition.lastIndexOf(")"); | ||
| if (open === -1 || close < open) return ""; | ||
| return definition | ||
| .slice(open + 1, close) | ||
| .replaceAll('"', "") | ||
| .replaceAll(/\s+/g, " ") | ||
| .trim(); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.