Skip to content

refactor: align the schema on typeorm's derived constraint names - #3352

Merged
tada5hi merged 18 commits into
masterfrom
fix/schema-alignment
Aug 11, 2026
Merged

tada5hi merged 18 commits into
masterfrom
fix/schema-alignment

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Reworked. Now one PR: the renames, the mysql uuid widening, and the revert of #3408's entity pins, which are mutually exclusive with the renames. The migration is plain SQL again; the guarded-helper approach and its 400-line data module are gone.

Folded (2026-08-10). The release window's other two unreleased migrations are merged in per the release convention (one file per dialect, earliest timestamp): SessionTokenClientId (#3421) and EventSessionId (#3422) now live inside 1785871780234-AlignSchemaWithEntityMetadata. Both new columns are created directly under typeorm's derived constraint names, which also closes a 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 populated round-trip now exempts columns the reverted migration itself adds (their values cannot survive their own column's drop, by contract) and asserts the re-run restores them. Anyone who executed the pre-fold files must drop their dev database or fix its migrations table by hand.

Why

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 test suites build their schema with synchronize() on sqlite. They had drifted, and nothing was watching.

Two causes, both from migrations that were hand-authored rather than generated (1783325495597 beta.52, 1783769340000 beta.53, 1785871780234 unreleased):

  1. Constraint names. 20 indexes, 9 foreign keys and 3 unique constraints created under readable names (IDX_auth_events_actor_name) where typeorm derives a table+column hash. Every generated migration before them used the hash, so the schema carried two naming regimes.
  2. uuid column widths, mysql only. 15 columns declared varchar(36). MySQL has no uuid type and MysqlDriver.getColumnLength only shortens to 36 for values typeorm generates itself, so a plain @Column({ type: 'uuid' }) derives the generic varchar(255) every earlier table got. Postgres has a native uuid type and is unaffected.

Neither has a runtime effect: nothing resolves a constraint by name, and varchar(36) holds a uuid perfectly well. The damage is that migration generate reconciles against the model, so any new migration arrived with 32 renames and 15 DROP COLUMN plus re-ADD pairs attached. That is data loss which reads as routine in review, and it buries the real change. It is also how two wrong-target foreign keys (auth_permissions.client_id, auth_roles.client_id) survived long enough to need finding by hand.

One naming regime, and it is typeorm's

221 constraints exist. 37 are hand-crafted, 184 are typeorm-derived:

total hand-crafted derived
FK 107 9 98
IDX 56 20 36
UQ 21 3 18
PK 37 5 32

All-hand-crafted would mean renaming 184 and then inventing and pinning a name for every future foreign key and index, forever, with nothing enforcing it: a forgotten name silently falls back to a hash and the drift reopens. So the 37 move to the derived names and the entities declare none.

Scope is 32, not 29 or 37. The 29 that drift, plus the 3 UQ_auth_* which only avoided showing as drift because their entities pinned them (@Unique('UQ_auth_keys_name_realm_id', ...)), and which would otherwise survive as exactly the hand-maintained exception this removes. The 5 PK_auth_* are left alone: the schema builder never compares primary key constraint names, so they cannot drift, and renaming them would touch tables for a name nothing reads.

#3408 is reverted here. It pinned those names on the entities as interim scaffolding, which bought a clean postgres migration generate while this sat parked. Pins and renames cannot both ship: the result is the same drift, mirrored. So the six entity files go back to bare @Index() / @JoinColumn({ name }), and the three @Unique('UQ_...') names come off.

Why widen mysql rather than keep 36

70 of the 85 plain-uuid columns are already varchar(255), so widening the 15 makes them consistent rather than leaving outliers. The alternative is length: 36 on the entity, which postgres rejects at DataSource.initialize() (EntityMetadataValidator: "does not support length property") and which depends on an unfinished upstream change. A dialect-conditional column type is not expressible either, since migration generate builds both dialects in one process off the same entity classes.

The cost of 255 is narrower than it looks: mysql VARCHAR stores the actual bytes, so per-row storage and index entries are effectively unchanged. The real cost is MEMORY temp tables and sort buffers allocating the declared maximum.

MODIFY COLUMN widens in place. A generated migration would have emitted DROP COLUMN plus re-ADD instead, because MysqlQueryRunner.changeColumn drops and re-adds a column whose length differs, which empties it on a populated table and fails outright on a foreign key column.

Plain SQL, not helpers

The first cut imported guarded rename/widen helpers plus a 400-line data module, which made this migration a program rather than a list of statements. Both are gone. Every other migration in the chain is a sequence of queryRunner.query(...) strings, and the idempotence the helpers bought is a property none of them has: the migrations table is what prevents a re-run.

  • postgres: ALTER INDEX ... RENAME TO x20, ALTER TABLE ... RENAME CONSTRAINT x12.
  • mysql: RENAME INDEX x23 (mysql stores a unique constraint as a unique index), foreign key drop + add x9 (no RENAME CONSTRAINT on mysql), MODIFY COLUMN x15, wrapped in SET FOREIGN_KEY_CHECKS.

The widening runs first and the order is load-bearing. MySQL commits each DDL statement regardless of the surrounding transaction, so a boot killed partway leaves this applied but unrecorded and the whole up re-runs. Widening is re-runnable (a MODIFY COLUMN onto the width a column already has succeeds); a rename is not (RENAME INDEX on an already-renamed index fails). 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 by applying a prefix of up and re-running it whole: it succeeds in this order and fails on IDX_auth_consents_sub in the other.

The checks are restored in a finally. FOREIGN_KEY_CHECKS is per session and the connection returns to the pool when a migration aborts, so a failed statement would otherwise hand the next caller a connection that accepts orphaned rows.

Each table is widened in one ALTER. Every one of these columns 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. One statement per column copied auth_events and auth_session_tokens four times each; grouped, the two highest-volume tables are rebuilt once, 6 rebuilds instead of 15.

The checks are disabled for the duration because every constraint is re-added with the definition it already enforced, so re-validating would only buy a table scan plus a failure mode for rows some past import inserted with the checks off. It is also what lets a foreign key column be widened while its constraint is in place.

The upstream helpers this used to consume (renameIndex, renameForeignKey, changeColumnType, withForeignKeyChecksDisabled) were still filed and shipped from this work as tada5hi/typeorm-extension#1420 and #1424; getSchemaDrift from the same line still backs the drift gate.

Verification

mysql 9 and postgres 18.

Check Result
migration generate emits no file on either dialect
CLI round-trip: run, revert x17, run clean on both
Drift gate against the migrated schema 0 on both
Populated round-trip (test:migration-latest) 11/11 on both
sqlite synchronize(): create, then reopen 0 drift and 0 drift
Full server-core suite 2020/2020
eslint, check:types clean

The populated run is the one that matters, since CI's round-trip runs on an empty schema and cannot surface a column rewrite losing values. With 234 auth_events plus sessions, session tokens, consents, trust anchors and authenticators seeded, it asserts row counts and column values unchanged after revert and after re-apply, that the foreign keys still reject an orphan insert and still cascade, and that the application boots and issues a token against the migrated schema.

Also in here

  • npm run test:schema-drift (scripts/assert-schema-drift.mjs), wired as a fourth step of tests-migrations. Asserts zero drift on both dialects, with no mysql carve-out. This is what stops the split reopening.
  • npm run test:migration-latest (scripts/verify-latest-migration.mjs), the populated round-trip above. Not in CI, since it boots the app and drops the target database. Fixed on the way: it seeded against the web client that plan 082 removed, so it had been failing since then.
  • Conventions. "Never hand-write a constraint name" replaces "pin the names a migration spelled out". A rule with no list cannot rot. The mysql uuid width trap is written down alongside it, including why length: 36 is not the escape.
  • .agents/references/typeorm.md updated for what is and is not consumed now.

Notes for review

  • MariaDB is out of scope, and this PR writes that down (.agents/conventions.md). There is no migrations/mariadb/ directory and the config validator accepts only mysql / postgres / better-sqlite3. Pointing type: 'mysql' at a MariaDB server mostly works, so the two concrete divergences are recorded: it refuses to change a column an existing foreign key references even with the checks off, which aborts this migration, and MariaDB 11.4+ defaults to utf8mb4_uca1400_ai_ci where MySQL 9 uses utf8mb4_0900_ai_ci, so every string column reads as drift. Accommodating it was tried and reverted: it costs the retry property above and buys nothing supported.
  • Merge after the pending release. Nothing in the current window depends on this.
  • Operational cost: the mysql widening rebuilds 6 tables, so the boot applying it stalls on a large auth_events or auth_session_tokens. That cost is the same whenever it ships.
  • Two suite failures appeared on the first full run (session.spec.ts, provisioning.spec.ts). Both pass in isolation and a re-run of the identical tree is 2020/2020: the documented parallel-suite flake, not this change.

Summary by CodeRabbit

  • Bug Fixes

    • Improved database migration compatibility across MySQL and PostgreSQL.
    • Updated schema handling to prevent migration-related drift and preserve relationships, constraints, and data integrity.
    • Adjusted UUID storage compatibility for MySQL databases.
  • Tests

    • Added automated checks for schema consistency, migration rollback and reapplication, populated data preservation, foreign-key behavior, application startup, and login verification.
  • Documentation

    • Expanded migration guidance, testing instructions, database compatibility notes, and troubleshooting references.

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.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

TypeORM entities now use generated database names. PostgreSQL and MySQL migrations align existing schemas with that metadata. New scripts and CI checks validate schema drift, migration round-trips, data preservation, referential integrity, startup, and login.

Changes

Schema alignment and verification

Layer / File(s) Summary
TypeORM-generated entity metadata
apps/server-core/src/adapters/database/domains/*/entity.ts, .agents/conventions.md, .agents/references/typeorm.md
Entity indexes, unique constraints, and foreign keys now use TypeORM-generated names. Documentation defines the related naming, UUID, and migration rules.
Dialect-specific schema migrations
apps/server-core/src/adapters/database/migrations/mysql/..., apps/server-core/src/adapters/database/migrations/postgres/...
New reversible migrations rename database objects to metadata-derived names. The MySQL migration widens UUID columns to varchar(255).
Migration verification and CI wiring
apps/server-core/scripts/*, apps/server-core/package.json, .github/workflows/main.yml, .agents/testing.md
Schema-drift and populated latest-migration checks validate schemas, data, foreign keys, startup, and login.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CI
  participant MigrationVerifier
  participant Database
  participant ServerCore
  CI->>MigrationVerifier: run migration verification
  MigrationVerifier->>Database: recreate and migrate database
  MigrationVerifier->>ServerCore: boot application and perform login
  MigrationVerifier->>Database: revert and reapply latest migration
  MigrationVerifier->>ServerCore: reboot application and verify login
Loading

Possibly related PRs

  • authup/authup#3068: Both changes extend migration testing in documentation and CI.
  • authup/authup#3186: Both changes modify the TypeORM session-token schema and migrations.
  • authup/authup#3408: Both changes modify server-core entity index and foreign-key constraint naming.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary schema change to use TypeORM-derived constraint names.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/schema-alignment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3352

@authup/client-account-console

npm i https://pkg.pr.new/@authup/client-account-console@3352

@authup/client-admin-console

npm i https://pkg.pr.new/@authup/client-admin-console@3352

@authup/client-auth-console

npm i https://pkg.pr.new/@authup/client-auth-console@3352

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3352

@authup/access

npm i https://pkg.pr.new/@authup/access@3352

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3352

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3352

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3352

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3352

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3352

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3352

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3352

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3352

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3352

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3352

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3352

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3352

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3352

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3352

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3352

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3352

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3352

commit: 9af68b5

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.
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.
tada5hi added 2 commits August 5, 2026 16:02
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.
@tada5hi tada5hi changed the title fix: align the migrated schema with the entity metadata refactor: align the schema on typeorm's derived constraint names Aug 5, 2026
@tada5hi
tada5hi marked this pull request as ready for review August 5, 2026 14:32
Copilot AI lite review requested due to automatic review settings August 5, 2026 14:32

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (1)
.agents/conventions.md (1)

74-84: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the required exception for data-preserving schema repair DDL.

The MySQL migration uses hand-authored DDL to rename MySQL indexes and change MySQL UUID column lengths in place. The generated DDL exception only permits UPDATE / INSERT data migrations, guards, and comments. Add a narrow, reviewed exception for this class of data-preserving schema repair DDL; otherwise change the migration to match the generated-only DDL rule.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/conventions.md around lines 74 - 84, Update the conventions entry
around the migration rules to add a narrow exception for data-preserving schema
repair DDL, since the current “hand-authored statements” allowance only covers
data migrations, guards, and comments. Make the exception explicit and scoped to
the MySQL migration pattern described here, and keep the existing generated-only
rule intact for all other schema changes; if you choose not to broaden the rule,
then adjust the migration to rely on generated DDL instead of hand-written index
renames or UUID length changes.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/references/typeorm.md:
- Line 6: Update the typeorm-extension workspace pin in the “Workspace pins” row
to the installed version that provides getSchemaDrift, and mark the duplicate
RdbmsSchemaBuilder.log() row as upstream reference-only while retaining the
schema-drift row’s typeorm-extension API reference.

In @.agents/testing.md:
- Line 299: Update the migration reference in the schema-drift documentation
from 1785264000000 to 1785940000000-AlignSchemaWithEntityMetadata, preserving
the surrounding explanation of the migration chain and schema alignment.

In @.github/workflows/main.yml:
- Around line 231-234: Update the workflow job after the existing
test:schema-drift step to run the populated migration round-trip via
test:migration-latest for every database matrix entry, and revise the testing
documentation to state that this check runs in CI rather than being manual-only.

In `@apps/server-core/package.json`:
- Around line 27-28: Update the test:schema-drift and test:migration-latest
scripts in the package scripts configuration to run the existing build script
before invoking their respective Node verification scripts, ensuring both checks
operate on current dist artifacts.

In
`@apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts`:
- Around line 43-100: Ensure both migration blocks in
apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts#L43-L100
and `#L104-L161` wrap their ALTER TABLE and MODIFY COLUMN operations in
try/finally, moving SET FOREIGN_KEY_CHECKS = 1 into each finally block so checks
are restored even when a migration statement fails; update the migration method
containing these query sequences and make no direct changes outside these two
sites.

---

Nitpick comments:
In @.agents/conventions.md:
- Around line 74-84: Update the conventions entry around the migration rules to
add a narrow exception for data-preserving schema repair DDL, since the current
“hand-authored statements” allowance only covers data migrations, guards, and
comments. Make the exception explicit and scoped to the MySQL migration pattern
described here, and keep the existing generated-only rule intact for all other
schema changes; if you choose not to broaden the rule, then adjust the migration
to rely on generated DDL instead of hand-written index renames or UUID length
changes.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 335fe337-5964-4283-b171-74aaa3566349

📥 Commits

Reviewing files that changed from the base of the PR and between 77c334e and d7c680f.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (16)
  • .agents/conventions.md
  • .agents/references/typeorm.md
  • .agents/testing.md
  • .github/workflows/main.yml
  • apps/server-core/package.json
  • apps/server-core/scripts/assert-schema-drift.mjs
  • apps/server-core/scripts/verify-latest-migration.mjs
  • apps/server-core/src/adapters/database/domains/client/entity.ts
  • apps/server-core/src/adapters/database/domains/consent/entity.ts
  • apps/server-core/src/adapters/database/domains/event/entity.ts
  • apps/server-core/src/adapters/database/domains/key/entity.ts
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts
  • apps/server-core/src/adapters/database/domains/trust-anchor/entity.ts
  • apps/server-core/src/adapters/database/domains/user-authenticator/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1785940000000-AlignSchemaWithEntityMetadata.ts

Comment thread .agents/references/typeorm.md Resolved
Comment thread .agents/testing.md Resolved
Comment thread .github/workflows/main.yml Resolved
Comment on lines +27 to +28
"test:schema-drift": "node scripts/assert-schema-drift.mjs",
"test:migration-latest": "node scripts/verify-latest-migration.mjs",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Build before running these verification scripts.

Both scripts execute dist files. A direct invocation after source changes can validate stale artifacts. Run the existing build script before the Node command.

As per coding guidelines, “Run npm run build before testing.”

Proposed fix
-        "test:schema-drift": "node scripts/assert-schema-drift.mjs",
-        "test:migration-latest": "node scripts/verify-latest-migration.mjs",
+        "test:schema-drift": "npm run build && node scripts/assert-schema-drift.mjs",
+        "test:migration-latest": "npm run build && node scripts/verify-latest-migration.mjs",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"test:schema-drift": "node scripts/assert-schema-drift.mjs",
"test:migration-latest": "node scripts/verify-latest-migration.mjs",
"test:schema-drift": "npm run build && node scripts/assert-schema-drift.mjs",
"test:migration-latest": "npm run build && node scripts/verify-latest-migration.mjs",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/package.json` around lines 27 - 28, Update the
test:schema-drift and test:migration-latest scripts in the package scripts
configuration to run the existing build script before invoking their respective
Node verification scripts, ensuring both checks operate on current dist
artifacts.

Source: Coding guidelines

tada5hi added 6 commits August 5, 2026 17:36
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.
…d-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.
…ariadb

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.
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.
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.
@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/server-core/scripts/verify-latest-migration.mjs`:
- Around line 145-152: Wrap the verification flow beginning with bootApplication
in a try/finally block so cleanup runs when login, database, or migration
operations throw. In finally, stop the existing child process and destroy the
datasource only after it has been initialized, preserving the normal login and
migration behavior.

In
`@apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts`:
- Around line 65-105: The migration class’s up and down methods are not
restart-safe because MySQL commits each rename and foreign-key change
independently. Update the operations in
apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts
at lines 65-105 and 120-160 so each index rename and foreign-key replacement
detects and tolerates either the original or already-updated name, including
partial child-key states, allowing retries in both directions without failing on
missing objects.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 55299ff5-4a8a-40d4-845e-a6fff99eecf5

📥 Commits

Reviewing files that changed from the base of the PR and between 77c334e and b0d754c.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (16)
  • .agents/conventions.md
  • .agents/references/typeorm.md
  • .agents/testing.md
  • .github/workflows/main.yml
  • apps/server-core/package.json
  • apps/server-core/scripts/assert-schema-drift.mjs
  • apps/server-core/scripts/verify-latest-migration.mjs
  • apps/server-core/src/adapters/database/domains/client/entity.ts
  • apps/server-core/src/adapters/database/domains/consent/entity.ts
  • apps/server-core/src/adapters/database/domains/event/entity.ts
  • apps/server-core/src/adapters/database/domains/key/entity.ts
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts
  • apps/server-core/src/adapters/database/domains/trust-anchor/entity.ts
  • apps/server-core/src/adapters/database/domains/user-authenticator/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1785940000000-AlignSchemaWithEntityMetadata.ts

Comment on lines +65 to +105
await queryRunner.query('ALTER TABLE `auth_consents` RENAME INDEX `IDX_auth_consents_sub` TO `IDX_482fa13b8f47218a844e333282`');
await queryRunner.query('ALTER TABLE `auth_consents` RENAME INDEX `IDX_auth_consents_client_id` TO `IDX_adc5a3c5fa915f59ddac529f2b`');
await queryRunner.query('ALTER TABLE `auth_consents` RENAME INDEX `IDX_auth_consents_realm_id` TO `IDX_089778fa70ab97a637b84957a8`');
await queryRunner.query('ALTER TABLE `auth_consents` RENAME INDEX `IDX_auth_consents_user_id` TO `IDX_f945cd1ec65cc16e8462384d3a`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_client_id` TO `IDX_e50f1f5e014087edaac7240ba9`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_actor_id` TO `IDX_a5cc98d786bf9fce973ab2594f`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_actor_name` TO `IDX_ce33c3f58b802bb3c7b2668adc`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_request_ip_address` TO `IDX_5fafa06904d87cf1d77bbf4564`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_realm_id` TO `IDX_5a0f436c6949aeb968db4f2473`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_expiring` TO `IDX_0c8183e935c03317f4829cb427`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_expires_at` TO `IDX_1db311adb485ecbefd92c5daf8`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_created_at` TO `IDX_64ac9bded13b2b6b75b128d8e5`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_ref_type_ref_id` TO `IDX_12ed04e1591ed2574d1324070b`');
await queryRunner.query('ALTER TABLE `auth_events` RENAME INDEX `IDX_auth_events_name_scope` TO `IDX_85536e251a24fe5141925ee3f9`');
await queryRunner.query('ALTER TABLE `auth_session_tokens` RENAME INDEX `IDX_auth_session_tokens_session_id` TO `IDX_cdedfe142e7b60c17140fc19d8`');
await queryRunner.query('ALTER TABLE `auth_session_tokens` RENAME INDEX `IDX_auth_session_tokens_kind` TO `IDX_37121db8ac9517c083c473b95c`');
await queryRunner.query('ALTER TABLE `auth_session_tokens` RENAME INDEX `IDX_auth_session_tokens_expires_at` TO `IDX_2a86161c2eae4ef90aee1fa657`');
await queryRunner.query('ALTER TABLE `auth_trust_anchors` RENAME INDEX `IDX_auth_trust_anchors_realm_id` TO `IDX_68b091bb8e853316ad1f953673`');
await queryRunner.query('ALTER TABLE `auth_user_authenticators` RENAME INDEX `IDX_auth_user_authenticators_kind` TO `IDX_e89cdcc8924d5fef9ae47d49d8`');
await queryRunner.query('ALTER TABLE `auth_user_authenticators` RENAME INDEX `IDX_auth_user_authenticators_user_id` TO `IDX_ed232e3a899e0556f1b052bc50`');
await queryRunner.query('ALTER TABLE `auth_keys` RENAME INDEX `UQ_auth_keys_name_realm_id` TO `IDX_0b3208b80576419f0b1319de7a`');
await queryRunner.query('ALTER TABLE `auth_consents` RENAME INDEX `UQ_auth_consents_subject_scope` TO `IDX_8f8ad5088770598763efdb2c46`');
await queryRunner.query('ALTER TABLE `auth_trust_anchors` RENAME INDEX `UQ_auth_trust_anchors_name_realm_id` TO `IDX_f3eacccc977b8597cc66db600f`');
await queryRunner.query('ALTER TABLE `auth_clients` DROP FOREIGN KEY `FK_auth_clients_access_policy_id`');
await queryRunner.query('ALTER TABLE `auth_clients` ADD CONSTRAINT `FK_7e7bca0ba30295b43b02a690511` FOREIGN KEY (`access_policy_id`) REFERENCES `auth_policies`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_consents` DROP FOREIGN KEY `FK_auth_consents_client_id`');
await queryRunner.query('ALTER TABLE `auth_consents` ADD CONSTRAINT `FK_adc5a3c5fa915f59ddac529f2b2` FOREIGN KEY (`client_id`) REFERENCES `auth_clients`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_consents` DROP FOREIGN KEY `FK_auth_consents_realm_id`');
await queryRunner.query('ALTER TABLE `auth_consents` ADD CONSTRAINT `FK_089778fa70ab97a637b84957a84` FOREIGN KEY (`realm_id`) REFERENCES `auth_realms`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_consents` DROP FOREIGN KEY `FK_auth_consents_user_id`');
await queryRunner.query('ALTER TABLE `auth_consents` ADD CONSTRAINT `FK_f945cd1ec65cc16e8462384d3a8` FOREIGN KEY (`user_id`) REFERENCES `auth_users`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_session_tokens` DROP FOREIGN KEY `FK_auth_session_tokens_session_id`');
await queryRunner.query('ALTER TABLE `auth_session_tokens` ADD CONSTRAINT `FK_cdedfe142e7b60c17140fc19d8a` FOREIGN KEY (`session_id`) REFERENCES `auth_sessions`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_session_tokens` DROP FOREIGN KEY `FK_auth_session_tokens_client_id`');
await queryRunner.query('ALTER TABLE `auth_session_tokens` ADD CONSTRAINT `FK_883cfabf7d5f7466a27625843db` FOREIGN KEY (`client_id`) REFERENCES `auth_clients`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_trust_anchors` DROP FOREIGN KEY `FK_auth_trust_anchors_realm_id`');
await queryRunner.query('ALTER TABLE `auth_trust_anchors` ADD CONSTRAINT `FK_68b091bb8e853316ad1f9536731` FOREIGN KEY (`realm_id`) REFERENCES `auth_realms`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_user_authenticators` DROP FOREIGN KEY `FK_auth_user_authenticators_user_id`');
await queryRunner.query('ALTER TABLE `auth_user_authenticators` ADD CONSTRAINT `FK_ed232e3a899e0556f1b052bc50e` FOREIGN KEY (`user_id`) REFERENCES `auth_users`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');
await queryRunner.query('ALTER TABLE `auth_user_authenticators` DROP FOREIGN KEY `FK_auth_user_authenticators_realm_id`');
await queryRunner.query('ALTER TABLE `auth_user_authenticators` ADD CONSTRAINT `FK_db13de293f01ac8ab7bc0342c4f` FOREIGN KEY (`realm_id`) REFERENCES `auth_realms`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package scripts =="
if [ -f package.json ]; then
  node -e "const p=require('./package.json'); console.log(JSON.stringify(p.scripts || {}, null, 2))"
fi

echo "== local package tools =="
for f in package.json apps/server-core/package.json; do
  [ -f "$f" ] && echo "-- $f --" && sed -n '1,220p' "$f"
done

echo "== target migration excerpt =="
sed -n '1,220p' apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts

echo "== relevant TypeORM migration APIs in repo =="
rg -n "class .*Migration|super\\.\\(.*Transaction|update|up\\(|down\\(|query\\(||QueryBuilder|Migration" apps/server-core/src -g '*.ts' | head -n 200

Repository: authup/authup

Length of output: 40542


🌐 Web query:

TypeORM 1.1.0 MySQL MigrationInterface queryRunner transaction DDL autocommit migration recorded after up completes

💡 Result:

In TypeORM, the handling of transactions during migrations and the subsequent recording of the migration in the database follow a specific workflow. Transaction Management By default, TypeORM runs all pending migrations within a single wrapping transaction (migrationsTransactionMode: 'all') [1][2]. You can configure this behavior using the migrationsTransactionMode option in your DataSource configuration or command-line flags: - 'all': All migrations are executed within a single transaction [1][2]. - 'each': Each migration is executed within its own individual transaction [1][2]. - 'none': Migrations are executed without any transaction wrapping [1][2]. Additionally, you can override this behavior on a per-migration basis by setting the transaction property (a boolean) on your class implementing MigrationInterface [3][4]. Note that this per-migration override only functions when migrationsTransactionMode is set to 'each' or 'none' [1][4]. MySQL DDL and Autocommit In MySQL, Data Definition Language (DDL) statements (such as CREATE TABLE, ALTER TABLE, DROP TABLE) cause an implicit commit of any active transaction. Because TypeORM wraps migrations in transactions, if your migration executes DDL statements, MySQL will automatically commit the transaction before the migration completes if not handled carefully [1][5]. While the migration code itself may finish successfully, the atomicity of the entire migration batch (or individual migration, depending on the mode) is broken because the DDL execution forces a commit [1][5]. Recording Migrations TypeORM records that a migration has run by inserting a record into a specific table (defaulting to "migrations") in your database [2]. This recording happens after the up method of the migration successfully completes [6]. If a migration fails, the up method throws an error, the transaction is rolled back (if a transaction is active), and the migration is not recorded in the database table [6]. However, because MySQL implicitly commits on DDL, if a DDL statement occurs midway, the changes made up to that point remain in the database even if subsequent statements in the same up method fail, potentially leaving your database in a partially migrated state without the migration being marked as "run" [1][5]. Recommendations If you need to perform DDL operations that cannot be rolled back or conflict with transaction handling, set transaction = false on your migration class (when using 'each' or 'none' mode) to prevent TypeORM from wrapping that specific migration in a transaction [1][4].

Citations:


🌐 Web query:

MySQL ALTER TABLE RENAME INDEX fails ER_KEY_DOES_NOT_EXIST existing index destination name same source

💡 Result:

The MySQL error ER_KEY_DOES_NOT_EXIST occurs when attempting to use the ALTER TABLE... RENAME INDEX old_index_name TO new_index_name statement if the specified old_index_name does not exist in the table [1][2]. If you attempt to use the same name for both the source (old_index_name) and the destination (new_index_name)—for example, ALTER TABLE t RENAME INDEX i1 TO i1—the operation will fail if the index does not exist [3]. Even if the index does exist, attempting to rename it to itself is technically redundant and logically invalid in many implementation contexts, often leading to command failures because the requirement for renaming implies a change [3][4]. To successfully rename an index, ensure that: 1. The old_index_name exists in the table [1][2]. 2. The old_index_name is not being dropped by the same ALTER TABLE statement [1][2]. 3. The new_index_name does not already exist in the table [1][2]. 4. Neither name is PRIMARY [1][2]. If you are encountering this error, verify that the index name is spelled correctly and exists in the table by running SHOW INDEX FROM table_name [5]. If you are performing multiple operations in one ALTER TABLE statement, ensure the index is not being dropped or renamed incorrectly elsewhere in the same command [1][2].

Citations:


🌐 Web query:

MySQL documentation ALGORITHM=COPY DDL implicit commit transaction per statement autocommit

💡 Result:

In MySQL, the ALTER TABLE statement—including those executed with ALGORITHM=COPY—causes an implicit commit of any active transaction in the current session [1][2]. The following key points summarize this behavior: 1. Implicit Commit: DDL statements, such as ALTER TABLE, trigger an implicit commit before they execute [1][2]. This means they cannot be performed within another transaction, such as within a START TRANSACTION... COMMIT block [2]. This behavior holds regardless of whether the operation uses ALGORITHM=COPY or ALGORITHM=INPLACE [2]. 2. ALGORITHM=COPY Behavior: When ALGORITHM=COPY is used, MySQL creates a new temporary copy of the table, copies the data row by row, and then swaps the original table with the new one [3]. While this process is more resource-intensive and restrictive regarding concurrent Data Manipulation Language (DML) than online (INPLACE) operations, it does not change the fundamental transactional rule that the DDL statement itself causes an implicit commit [1][2][3]. 3. Autocommit Interaction: Because ALTER TABLE causes an implicit commit, it essentially acts as if you had issued a COMMIT command immediately before the statement [1]. If you have autocommit enabled (the default in MySQL), the statement is handled as its own atomic unit [2]. Even if autocommit is disabled, the active transaction is committed by the DDL statement [1]. 4. Atomic DDL: Since the introduction of Atomic DDL in modern MySQL versions (for the InnoDB storage engine), the entire DDL operation is processed as a single atomic unit that is either committed or rolled back [2]. However, this atomicity does not mean DDL statements are transactional in the sense of allowing them to be nested within other transactions; the rule that DDL causes an implicit commit remains [2].

Citations:


Make the MySQL rename/FK migration restart-safe.

MySQL atomic DDL commits before each rename or DROP FOREIGN KEY, and TypeORM records the migration after up()/down() completes. A process stop after one completed operation leaves the source name or foreign-key name missing, so the same migration direction cannot retry cleanly.

Wrap the up() renames and foreign-key replacements so later steps handle already-renamed sources/grandchild keys, and make the rollback path handle the reciprocal partial states.

📍 Affects 1 file
  • apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts#L65-L105 (this comment)
  • apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts#L120-L160
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts`
around lines 65 - 105, The migration class’s up and down methods are not
restart-safe because MySQL commits each rename and foreign-key change
independently. Update the operations in
apps/server-core/src/adapters/database/migrations/mysql/1785940000000-AlignSchemaWithEntityMetadata.ts
at lines 65-105 and 120-160 so each index rename and foreign-key replacement
detects and tolerates either the original or already-updated name, including
partial child-key states, allowing retries in both directions without failing on
missing objects.

@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

tada5hi added 2 commits August 5, 2026 19:34
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.
It was injected to test the cleanup handler and committed by mistake,
which failed both tests-migrations jobs and the lint job.
tada5hi added 3 commits August 5, 2026 20:05
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.
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants