Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix locking #586

Merged
merged 2 commits into from
Apr 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}
}