creation of rows in knex_migration_lock table is not safe concurrently
Environment
Knex version: 0.19.5 Database + version: XtraDB 5.7 OS: CentOS
Bug
We have encountered a concurrency-related issue around the knex_migration_lock table. The issue we have observed is as follows:
3 nodes concurrently try to execute db.migrate.latest() against a database which has not yet been initialized for use with Knex.
The knex_migration_lock table is created with three entries, rather than only one, because of a data race here: https://github.com/knex/knex/blob/master/lib/migrate/table-creator.js#L30 . The race is between the return of return getTable(trxOrKnex, lockTable, schemaName).select('*'); and the check of data.length in !data.length && trxOrKnex.into(lockTableWithSchema).insert({ is_locked: 0 }) .
Multiple nodes execute the (non-locking) select query simultaneously and all return 0 rows. Next, multiple nodes execute the (non-locking) insert query simultaneously, leading to the creation of multiple sequential locking rows.
After this has happened, no migrations can function until the table is reset, because the check in https://github.com/knex/knex/blob/master/lib/migrate/Migrator.js#L318 verifies that only one row is updated by the query which takes the lock.
Perhaps an upsert primitive could be used to insert the locking record into the table initially, or the first indexed lock row can be utilized as the semaphore for the lock?
- Error message
Migration table is already locked
- Reduced test code, for example in https://npm.runkit.com/knex or if it needs real database connection to MySQL or PostgreSQL, then single file example which initializes needed data and demonstrates the problem.
Executing db.migrate.latest in multiple truly concurrent processes in a loop will eventually trigger various migration concurrency/race issues, this being the most common one.
Source: knex/knex