Skip to content

Commit

Permalink
Fix locking (#586)
Browse files Browse the repository at this point in the history
* Fix migration locking

* Release lock after running migrations
  • Loading branch information
Nevon authored Apr 3, 2020
1 parent 2dddd7a commit ee60ad2
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,20 @@ const loadMigrations = async (db: DBConnection, options: RunnerOption, logger: L
}

const lock = async (db: DBConnection): Promise<void> => {
const [lockObtained] = await db.select(`select pg_try_advisory_lock(${PG_MIGRATE_LOCK_ID}) as "lockObtained"`)
if (!lockObtained) {
const [result] = await db.select(`select pg_try_advisory_lock(${PG_MIGRATE_LOCK_ID}) as "lockObtained"`)
if (!result.lockObtained) {
throw new Error('Another migration is already running')
}
}

const unlock = async (db: DBConnection): Promise<void> => {
const [result] = await db.select(`select pg_advisory_unlock(${PG_MIGRATE_LOCK_ID}) as "lockReleased"`)

if (!result.lockReleased) {
throw new Error('Failed to release migration lock')
}
}

const ensureMigrationsTable = async (db: DBConnection, options: RunnerOption): Promise<void> => {
try {
const schema = getMigrationTableSchema(options)
Expand Down Expand Up @@ -220,6 +228,9 @@ export default async (options: RunnerOption): Promise<RunMigration[]> => {
timestamp: m.timestamp,
}))
} finally {
if (!options.noLock) {
await unlock(db).catch((error) => logger.warn(error.message))
}
db.close()
}
}

0 comments on commit ee60ad2

Please sign in to comment.