Knex "The migration directory is corrupt" in CI
Knex compared the knex_migrations table to the files on disk and found migrations recorded as run that have no matching file. It refuses to continue because the history and the directory disagree.
What this error means
knex migrate:latest fails immediately listing migration filenames that are "missing", before applying anything. It is deterministic - those files are genuinely absent from the checked-out tree.
migration directory is corrupt, the following files are missing:
20240115_add_orders.jsCommon causes
A recorded migration file is missing
A migration that already ran (and is in knex_migrations) was deleted, renamed, or lives on an unmerged branch, so its file is not on disk.
Database ahead of the code
CI points at a shared database that ran migrations the current branch does not contain, so those filenames have no file here.
Renamed migration changes the recorded name
Knex keys on the filename; renaming an applied migration makes the recorded name unresolvable against the new file.
How to fix it
Restore the missing migration files
Bring the recorded files back - usually by merging the branch that contains them or reverting the deletion.
git log -- migrations/ # find when files were removed
git checkout <commit> -- migrations/ # restore the missing migrationUse a clean database in CI
- Start each CI run from an empty database so
knex_migrationsis rebuilt from the files present. - Run
knex migrate:latestagainst that clean database. - Avoid pointing CI at a shared database migrated by other branches.
How to prevent it
- Treat applied migration files as immutable - never delete or rename them.
- Use an ephemeral database per CI run.
- Merge migration files deliberately so the directory matches
knex_migrations.