diff --git a/src/runner.ts b/src/runner.ts index fcd9a204..4a2baa0c 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -51,12 +51,20 @@ const loadMigrations = async (db: DBConnection, options: RunnerOption, logger: L } const lock = async (db: DBConnection): Promise => { - 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 => { + 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 => { try { const schema = getMigrationTableSchema(options) @@ -220,6 +228,9 @@ export default async (options: RunnerOption): Promise => { timestamp: m.timestamp, })) } finally { + if (!options.noLock) { + await unlock(db).catch((error) => logger.warn(error.message)) + } db.close() } }