Repository navigation
fix(server-core): pin migration-authored constraint names on the entities - #3408
Conversation
…ties
The hand-authored beta.52 and beta.53 migrations created 9 foreign keys and
20 indexes under readable names, where typeorm derives a table+column hash.
The entity classes never declared them, so `migration generate` read the
difference as drift and emitted a migration renaming all 29 back to hashes,
burying whatever real change was being generated.
Declare the existing names on the model instead, via `@Index('IDX_...')` and
`@JoinColumn({ foreignKeyConstraintName: 'FK_...' })`. The 3 `UQ_*` names were
already pinned this way, so this follows the existing convention. Primary keys
need nothing: the schema builder does not compare their constraint names.
Postgres drift is now 0 and `migration generate` emits no postgres file. The
mysql residue is documented rather than closed: 15 uuid columns the migrations
declared `varchar(36)`, where a plain `@Column({ type: 'uuid' })` derives
`varchar(255)`. That half cannot be fixed from the entity, since postgres
rejects `length` on a uuid column at `DataSource.initialize()`.
There was a problem hiding this comment.
Pull request overview
Pins previously hand-authored foreign key and index names on the corresponding TypeORM entity metadata in apps/server-core, eliminating schema “drift noise” during migration generate by aligning entity-declared names with the already-migrated database schema.
Changes:
- Added explicit
@Index('IDX_...')names for previously unnamed indexes across several entities. - Pinned foreign key constraint names via
@JoinColumn({ foreignKeyConstraintName: 'FK_...' })for existing relations so TypeORM no longer proposes renames. - Documented the constraint-name pinning rule (and the known MySQL uuid-length residual drift) in
.agents/conventions.md.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| apps/server-core/src/adapters/database/domains/user-authenticator/entity.ts | Names indexes and pins user_id / realm_id FK constraint names to match migrated schema. |
| apps/server-core/src/adapters/database/domains/trust-anchor/entity.ts | Names the realm_id index and pins the realm_id FK constraint name. |
| apps/server-core/src/adapters/database/domains/session-token/entity.ts | Names indexes (session_id, kind, expires_at) and pins FK constraint names for session_id and client_id. |
| apps/server-core/src/adapters/database/domains/event/entity.ts | Assigns explicit names to composite and per-column indexes to match the hand-authored migration names. |
| apps/server-core/src/adapters/database/domains/consent/entity.ts | Names indexes and pins FK constraint names for client_id, realm_id, and nullable user_id. |
| apps/server-core/src/adapters/database/domains/client/entity.ts | Pins the access_policy_id FK constraint name to match the migrated schema. |
| .agents/conventions.md | Documents the “pin hand-authored constraint names on entities” rule and records the known MySQL uuid-length residual drift. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
authup
@authup/client-account-console
@authup/client-admin-console
@authup/client-auth-console
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughThe PR adds explicit names for TypeORM indexes and foreign-key constraints across several database entities. It also documents migration guidance for preserving constraint names and unresolved MySQL UUID column-length drift. ChangesDatabase metadata naming
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Rewrites the alignment migration as plain SQL and takes the naming question to one regime instead of two. The hand-authored migrations named 32 constraints readably where typeorm derives a table+column hash, so `migration generate` reconciled every new migration against the model and emitted the renames before the real change. #3408 closed that from the entity side by pinning the names, as interim scaffolding while this sat parked. Pins and renames are mutually exclusive, so the pins come back out here: of 221 constraints 184 are already typeorm-derived, and hand-crafting the rest would mean inventing and pinning a name for every future foreign key and index forever, with nothing enforcing it. Scope is 32, not 29: the three `UQ_auth_*` only avoided showing as drift because their entities pinned them. The five `PK_auth_*` are left alone, since the schema builder never compares primary key constraint names. MySQL additionally widens the 15 uuid columns those migrations declared as varchar(36) where a plain `type: 'uuid'` derives varchar(255). 70 of the 85 plain-uuid columns are already 255, so this makes them consistent rather than leaving 15 outliers. MODIFY COLUMN widens in place; a generated migration would have emitted DROP COLUMN plus re-ADD, since `MysqlQueryRunner.changeColumn` drops and re-adds a column whose length differs. The first cut of this migration imported guarded rename/widen helpers and a 400-line data module, which made a migration a program rather than a list of statements. Both are gone: every other migration in the chain is a sequence of query strings, and the idempotence those helpers bought is a property none of them has, because the migrations table is what prevents a re-run. Verified on mysql 9 and postgres 18: `migration generate` emits no file on either dialect, the CLI round-trip (run, revert x17, run) is clean on both, and the populated round-trip passes 11/11 on both, including that row counts and column values survive revert and re-apply and that the foreign keys still reject orphans and still cascade. Also fixes verify-latest-migration.mjs, which seeded against the `web` client that plan 082 removed and so had been failing since then.
* fix: align the migrated schema with the entity metadata The migration chain and the entity classes are two independent descriptions of the same schema, and only the chain is exercised against mysql/postgres (the suites synchronize on sqlite). They had drifted in two respects, both introduced by the hand-authored 1783325495597 and 1783769340000: - 20 indexes and 8 foreign keys carry readable names (IDX_auth_events_actor_name) where typeorm derives a table+column hash, on both dialects - 15 mysql uuid columns are varchar(36) where the driver derives varchar(255) for `type: 'uuid'`, since it only shortens to 36 for values it generates itself (MysqlDriver.getColumnLength) Neither has a runtime effect, but `migration:generate` consequently emitted a 56 (postgres) / 92 (mysql) statement reconciliation including DROP COLUMN on primary keys, so the next generated migration would have been data-destroying, and that noise hid real defects: the auth_permissions.client_id and auth_roles.client_id foreign keys both referenced the wrong table. Every statement in the repair is guarded by a catalog lookup, so it is a no-op on a schema that already matches and resumes after an interrupted run, which matters because mysql commits DDL regardless of the surrounding transaction. The foreign key work runs with FOREIGN_KEY_CHECKS disabled: each constraint is recreated exactly as it already existed, so re-validating it would only add a table scan and a failure mode for rows a past import inserted with checks off. Adds the drift assertion as a fourth step of the tests-migrations job so the split cannot reopen, a populated round-trip script for the migrations the empty CI round-trip cannot certify, and records the generate-never-hand-write rule in the conventions. * refactor: consume typeorm-extension's schema repair helpers typeorm-extension 4.0.0-beta.2 ships the drift assertion and the guarded rename helpers proposed in tada5hi/typeorm-extension#1420, so the local dialect machinery goes away: renameIndex, renameForeignKey, withForeignKeyChecksDisabled and getSchemaDrift now come from the library, and the module keeps only the rename/type data, which describes this schema's history rather than anything reusable. changeColumnType is deliberately not adopted. It delegates to typeorm's changeColumn, and MysqlQueryRunner.changeColumn DROPs and re-ADDs a column whose length differs, which empties the column on a populated table and fails outright on a foreign key column (ER_FK_COLUMN_CANNOT_DROP, even with the checks disabled). The local MODIFY COLUMN implementation stays until the upstream helper can express an in-place change (tada5hi/typeorm-extension#1424). Re-verified on mysql 9 and postgres 18: chain applies with zero drift, revert x15 and re-run clean, and the populated round-trip passes 9/9 on both dialects with row counts unchanged and foreign keys still enforcing. * fix(deps): bump typeorm-extension to 4.0.0-beta.3 beta.3 alters the column in place (tada5hi/typeorm-extension#1425), so the local MODIFY COLUMN helper this branch carried can go: the mysql column widening runs through the library's changeColumnType again, and the schema-alignment module is pure data. The populated round-trip additionally asserts per-column value counts now. Row counts alone would not have noticed the defect that forced the local helper - a type change implemented as DROP COLUMN plus ADD COLUMN keeps every row and empties one column - so the harness could have reported a clean run while a column was silently cleared. Verified on mysql 9 and postgres 18: chain applies with zero drift, revert x15 and re-run clean, populated round-trip 11/11 on both. * refactor: align the schema on typeorm's derived constraint names Rewrites the alignment migration as plain SQL and takes the naming question to one regime instead of two. The hand-authored migrations named 32 constraints readably where typeorm derives a table+column hash, so `migration generate` reconciled every new migration against the model and emitted the renames before the real change. #3408 closed that from the entity side by pinning the names, as interim scaffolding while this sat parked. Pins and renames are mutually exclusive, so the pins come back out here: of 221 constraints 184 are already typeorm-derived, and hand-crafting the rest would mean inventing and pinning a name for every future foreign key and index forever, with nothing enforcing it. Scope is 32, not 29: the three `UQ_auth_*` only avoided showing as drift because their entities pinned them. The five `PK_auth_*` are left alone, since the schema builder never compares primary key constraint names. MySQL additionally widens the 15 uuid columns those migrations declared as varchar(36) where a plain `type: 'uuid'` derives varchar(255). 70 of the 85 plain-uuid columns are already 255, so this makes them consistent rather than leaving 15 outliers. MODIFY COLUMN widens in place; a generated migration would have emitted DROP COLUMN plus re-ADD, since `MysqlQueryRunner.changeColumn` drops and re-adds a column whose length differs. The first cut of this migration imported guarded rename/widen helpers and a 400-line data module, which made a migration a program rather than a list of statements. Both are gone: every other migration in the chain is a sequence of query strings, and the idempotence those helpers bought is a property none of them has, because the migrations table is what prevents a re-run. Verified on mysql 9 and postgres 18: `migration generate` emits no file on either dialect, the CLI round-trip (run, revert x17, run) is clean on both, and the populated round-trip passes 11/11 on both, including that row counts and column values survive revert and re-apply and that the foreign keys still reject orphans and still cascade. Also fixes verify-latest-migration.mjs, which seeded against the `web` client that plan 082 removed and so had been failing since then. * perf: widen each mysql table in a single ALTER Every one of these column changes crosses the utf8mb4 varchar length-prefix boundary (varchar(36) is 144 bytes and carries a 1-byte prefix, varchar(255) is 1020 and needs 2), so InnoDB rejects ALGORITHM=INPLACE and rebuilds the table: a full row-by-row copy, with writes blocked while it runs. One statement per column therefore copied auth_events and auth_session_tokens four times each and auth_consents three, 15 rebuilds in total. MySQL accepts several MODIFY COLUMN clauses in one ALTER and does a single copy, so the two highest-volume tables are now rebuilt once. Since migrations are applied at boot, this is startup time on a populated deployment. Round-trip and the populated round-trip re-verified on mysql 9, 11/11. * fix: widen before renaming so an interrupted mysql run can retry MySQL commits each DDL statement regardless of the surrounding transaction, so a boot killed partway through leaves this migration applied but unrecorded, and the whole `up` re-runs on the next start. Migrations are applied at boot and the widening rebuilds six tables, so being killed is not hypothetical here: it is what a startup probe timeout on a large auth_events looks like. The two phases have opposite properties. Widening is re-runnable, since a MODIFY COLUMN onto the width a column already has just succeeds. A rename is not: RENAME INDEX on an already-renamed index fails with ER_KEY_DOES_NOT_EXITS. Running the minutes-long phase first and the instant one last means the phase that can realistically be interrupted is the one that survives a retry. Verified on mysql 9 by applying a prefix of `up` and then re-running it whole: with the widening first the retry succeeds, and with the previous order it fails on `IDX_auth_consents_sub`. Round-trip and the populated round-trip re-run, 11/11. * fix: restore FOREIGN_KEY_CHECKS on failure and run the populated round-trip in CI FOREIGN_KEY_CHECKS is a session setting and the connection returns to the pool when a migration aborts, so a failed ALTER left the next caller with a connection that accepts orphaned rows. The two windows now restore it in a `finally`. Verified by making a statement throw mid-widening: the setting comes back as 1. The setting cannot simply be dropped, since MySQL refuses to widen a column an existing foreign key references (ER_FK_COLUMN_CANNOT_CHANGE). `test:migration-latest` also moves into the `tests-migrations` job. It is the only gate that can catch a column rewrite losing values or a foreign key regression, because the round-trip beside it runs on an empty schema, and this migration rewrites 15 columns. Leaving it manual meant CI could not see the failure mode this change introduces. Also corrects three stale references the rename left behind: the migration id in testing.md, the typeorm-extension pin in the reference file, and the drift-gate row there, which credited RdbmsSchemaBuilder.log() where the gate actually calls typeorm-extension's getSchemaDrift. * fix: drop the foreign keys before widening so the migration runs on mariadb MySQL lets a column an existing foreign key references be changed while FOREIGN_KEY_CHECKS is off. MariaDB refuses either way, including under ALGORITHM=COPY, so the first widening statement aborted the migration with ER_FK_COLUMN_CANNOT_CHANGE. Every earlier migration in the chain applies cleanly on MariaDB, so this would have broken the upgrade for deployments pointing `type: 'mysql'` at a MariaDB server. All nine constraints are dropped and re-added for the rename anyway, so widening between the two halves costs no extra statement and works on both engines. Verified on MariaDB 11.8: the chain applies, round-trips, and keeps row counts, column values and foreign key behaviour intact. The cost is that an interrupted run can no longer be retried, since it would drop a foreign key that is already gone, and there is no portable `DROP FOREIGN KEY IF EXISTS`. Documented in the migration, together with the recommendation to apply migrations with `migration run` before rolling the application on any deployment large enough for the rebuild to matter. MariaDB also carries pre-existing schema drift against the entity metadata (292 statements before this migration, 213 after) because typeorm's mysql driver models MySQL. Noted in testing.md so the two drift checks failing there are not read as a regression. * Revert "fix: drop the foreign keys before widening so the migration runs on mariadb" This reverts commit 0de6647. * docs: record that mariadb is not a supported server There is no `migrations/mariadb/` directory and the config validator accepts only mysql / postgres / better-sqlite3, so typeorm's MariaDB-specific behaviour never activates either: it is gated on `options.type === 'mariadb'`. Pointing `type: 'mysql'` at a MariaDB server mostly works, so it is worth writing down where it does not. MariaDB refuses to change a column an existing foreign key references even with FOREIGN_KEY_CHECKS off, which aborts the alignment migration, and MariaDB 11.4+ defaults to the utf8mb4_uca1400_ai_ci collation where MySQL 9 uses utf8mb4_0900_ai_ci, so every string column reads as drift. Both were measured while briefly reshaping the migration to accommodate it; that reshaping is reverted, since accommodating it costs the ability to retry an interrupted run and buys nothing supported. * refactor: assert schema drift through the library helper typeorm-extension ships `assertSchemaMatchesMetadata`, which wraps `getSchemaDrift` and throws a `SchemaDriftError` listing the reconciling statements, so the gate no longer formats that output itself. The `typeorm-extension db drift` CLI covers the same ground and would remove the script entirely, but it discovers a DataSource from a file while this application builds its options programmatically: DataSourceOptionsBuilder injects the entities, migrations and subscribers around the env-derived connection. Writing a data-source file to satisfy the CLI would be more code than the script it replaced, so the script stays, thinner, with the reason recorded in it. Verified both ways against mysql: exit 0 on the aligned schema, exit 1 with the 96 statements listed after reverting the alignment migration. * fix: stop the spawned server when the verification script fails The script boots the application twice and only stops it on the happy path, so a throw while the child is running orphaned it: the process survives the parent and keeps holding its port, and the next run then fails to bind and reports something unrelated to the actual failure. That is the likely case rather than a rare one, since the failure this script exists to catch shows up as a failing `login()` between the boot and the stop. Both resources are now released from a cleanup handler on uncaughtException and unhandledRejection as well as at the end. Verified by injecting a throw between the boot and the stop: one orphaned server on the port before, none after. * fix: remove a debug throw left in the verification script It was injected to test the cleanup handler and committed by mistake, which failed both tests-migrations jobs and the lint job. * fix: report only real drift as drift in the schema gate The catch introduced when the gate moved onto assertSchemaMatchesMetadata swallowed every error, so an unreachable server, a bad credential or a missing database was reported as "the migrated schema and the entity metadata disagree" and sent whoever read the CI log looking for a schema problem that does not exist. Only SchemaDriftError is drift; anything else is re-thrown and surfaces as itself. * refactor: fold the unreleased migrations into one file per dialect The release window since v1.0.0-beta.59 held three migrations: SessionTokenClientId (1785871780234), AlignSchemaWithEntityMetadata (1785940000000) and EventSessionId (1786320000000). Per the release convention they are squashed into one file per dialect under the earliest timestamp, 1785871780234-AlignSchemaWithEntityMetadata. The fold also closes the alignment gap the ordering had left open: EventSessionId sorted after the alignment migration, so its readable IDX_auth_events_session_id survived the chain and stayed pinned on the entity. The folded migration creates both new columns directly under typeorm's derived constraint names (FK_883cfabf7d5f7466a27625843db, IDX_cac31ef1ae7871c905a3842df4), so no create-then-rename churn and the entity pin is gone. The populated round-trip now exempts columns the reverted migration itself added from the value comparison: the revert drops them together with their values by contract, while every pre-existing column stays guarded against a type change implemented as DROP plus ADD. A new check asserts the re-run restores the added columns. Anyone who executed the pre-fold files must drop their dev database or fix its migrations table by hand. Verified on mysql and postgres: full chain run, schema-drift gate, revert/re-run round-trip, and the populated round-trip (12/12 both).
Why
migration generatereconciles the live schema against the entity metadata, so anything a migration spelled out that the model does not declare reads as drift. The hand-authored1783325495597(beta.52) and1783769340000(beta.53) created 9 foreign keys and 20 indexes under readable names (IDX_auth_events_actor_name,FK_auth_consents_client_id) where typeorm derives a table+column hash, and the entity classes never declared them.The effect is that generating a migration for any unrelated change first produced 29 rename statements, so the real change arrived buried in noise. That is how the two wrong-target foreign keys (
auth_permissions.client_id,auth_roles.client_id) survived long enough to need fixing by hand.What
Declare the existing names on the model:
29 names across
auth_clients,auth_consents,auth_events,auth_session_tokens,auth_trust_anchorsandauth_user_authenticators. The 3UQ_*names were already pinned this way, so this follows the existing convention rather than introducing one. Primary keys need nothing: the schema builder does not compare their constraint names.No migration, no schema change, no runtime effect. Nothing resolves an index or constraint by name.
The alternative was renaming the database to match the hashes, which is what #3352 currently does. That is a migration touching all 6 tables at boot to reach a name nobody reads, so it is the more expensive way to the same place.
Verification
The oracle is
migration generateitself: it drops and recreates a scratch database, applies the full chain, then diffs against the model.synchronize(), fresh create then reopencheck:types, eslintTwo of those are worth spelling out.
The mysql residue is not a naming problem. Every index and foreign key in it is dropped and re-added under its own name, as collateral of a column rebuild; no hash name appears anywhere. All 140 statements are attributable to 15 uuid columns the migrations declared
varchar(36), where a plain@Column({ type: 'uuid' })derivesvarchar(255)(MysqlDriver.getColumnLengthonly shortens to 36 for values typeorm generates itself). Applying exactly those statements converges to 0 in one pass, which is what rules out anything hiding behind them.sqlite was the one real risk. Those deployments boot through
synchronize(), andPRAGMA foreign_key_listreturns no constraint names, so a failure to round-trip the pinned names would have rebuilt 5 tables on every boot. It round-trips: 0 drift on create and 0 on reopen.The mysql half, and why it is not here
It cannot be closed from the entity.
@Column({ type: 'uuid', length: 36 })throws atDataSource.initialize()on postgres, fromEntityMetadataValidator.js:94, which rejectslengthon any type outsidewithLengthColumnTypes. A dialect-conditional type is not an escape either, sincemigration generatebuilds both dialects in one process off the same entity classes.It is also not worth closing by widening to
varchar(255): 36 is the correct width for a uuid, so widening removes the diff by making the schema worse.The closing move is to pin
length: 36on those 15 columns, which needs no migration at all. MySQL already accepts that and emits exactlyvarchar(36); postgres is the only side that refuses. Getting there needs postgres to ignore alengthon types that do not take one, which is three changes in typeorm, each verified necessary by simulating it against postgres 18:PostgresDriver.createFullTypeEntityMetadataValidatorPostgresDriver.getColumnLengthPart 3 is the one that decides feasibility.
getColumnLengthreturns the metadata length while postgres reads back none, so with only parts 1 and 2 the column is seen as changed on every boot and generates a destructiveDROP COLUMNplus re-ADD: measured at 2 statements per pass, repeating indefinitely. With all three, drift converges to 0 and the column stays nativeuuid. So parts 1+2 alone would leave postgres permanently worse than it is today.Until then the residue is documented in
.agents/conventions.md, including the part that matters in review: a generated mysql migration renders it asDROP COLUMNplus re-ADDonauth_events.idand 14 siblings, which is data loss that reads as routine.Relation to #3352
#3352 stays the vehicle for the residue and for the CI drift gate, and its description has been updated. It is necessary but not near-term, so this change is what makes the interim workable: postgres generation is usable today instead of waiting on it.
Landing this first also removes the need for its rename half, since the names are now pinned on the model rather than rewritten in the database.