Skip to content

Wrap each migration into its own transaction #3

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ shift({
before: ({ migration_id, name }) => {
console.log('Migrating', migration_id, name);
},
transactionPerEachMigration: true, // defaults to false
})
.then(() => console.log('All good'))
.catch((err) => {
Expand Down
17 changes: 14 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export default async function({
sql,
path = join(process.cwd(), 'migrations'),
before = null,
after = null
after = null,
transactionPerEachMigration = false
}) {
const migrations = fs.readdirSync(path)
.filter(x => fs.statSync(join(path, x)).isDirectory() && x.match(/^[0-9]{5}_/))
Expand All @@ -28,17 +29,27 @@ export default async function({
const current = await getCurrentMigration()
const needed = migrations.slice(current ? current.id : 0)

return sql.begin(next)
return transactionPerEachMigration ? next(sql) : sql.begin(next)

async function next(sql) {
const current = needed.shift()
if (!current)
return

if (transactionPerEachMigration) {
await sql.begin(async (sql) => {
await step(sql, current);
})
} else {
await step(sql, current);
}
await next(sql)
}

async function step(sql, current) {
before && before(current)
await run(sql, current)
after && after(current)
await next(sql)
}

async function run(sql, {
Expand Down