Migrations lock index sequence already exists
Environment
Knex version: 0.19.3 Database + version: PostgreSQL 10.6 OS: alpine (docker image)
Bug
We have an application that on every request it connects to a certain database. After the connection is established the migrations are executed before performing the request related queries.
Recently we came across the following error when the migrations were performed for the first time on a certain database:
{
error: duplicate key value violates unique constraint "pg_type_typname_nsp_index"
at Connection.parseE (/home/node/app/node_modules/pg/lib/connection.js:555:11)
at Connection.parseMessage (/home/node/app/node_modules/pg/lib/connection.js:380:19)
at Socket.<anonymous> (/home/node/app/node_modules/pg/lib/connection.js:120:22)
at Socket.emit (events.js:198:13)\n at Socket.EventEmitter.emit (domain.js:448:20)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'error',
length: 266,
severity: 'ERROR',
code: '23505',
detail: 'Key (typname, typnamespace)=(migrations_lock_index_seq, 38364) already exists.',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'pg_catalog',
table: 'pg_type',
column: undefined,
dataType: undefined,
constraint: 'pg_type_typname_nsp_index',
file: 'nbtinsert.c',
line: '434',
routine: '_bt_check_unique'
} Sadly the migrations were not performed. After this, on every new request he following error was thrown:
{
MigrationLocked: Migration table is already locked
name: 'MigrationLocked',
message: 'Migration table is already locked'
}Our solution was to manual delete all the rows that were stored in the migrations_lock table and rerun the migrations.
We suspect that two requests were executed concurrently and during the creation of the migrations table one of the requests failed throwing the first error, showed above, locking the table and therefore making it impossible to run the migrations.
Source: knex/knex