How to close database in afterMigrate? #252
-
After each migration, I am doing The problem is, if a migration locked some table (that happens with My question is, how do I close db connection in
but nothing helped. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
For the time being, I'm using this workaround: let migrated = false
export const change = rakeDb(
{ databaseURL },
{
async afterMigrate(db) {
migrated = true
},
async afterRollback() {
migrated = true
},
},
)
if (process.env.NODE_ENV === "development" && migrated) {
change.promise.then(async () => {
await dumpDatabaseSchema(databaseURL)
})
} which is not super elegant and perhaps not very flexible (such as when running migrations programmatically). |
Beta Was this translation helpful? Give feedback.
-
that's a bug, I'll fix it so migration must release the lock |
Beta Was this translation helpful? Give feedback.
-
I realized it's not a bug, but in fact is a good and protective behavior. The idea is that the command as a whole runs as a single transaction, and even if an error happens inside a callback - all is rolled back, you can fix the code and try again. The transaction operates under a lock, so if it's the multi-container environment or something, changes to the same db won't be happening in parallel, but one container will wait for another to finish. How to solve it? Let's return useful info from the promise, so that you could check what was the command this promise was resolved for. |
Beta Was this translation helpful? Give feedback.
-
Published an update:
import { execSync } from 'node:child_process';
export const change = rakeDb(
{ databaseURL: 'postgres://...' },
{
migrationsPath: 'migrations',
},
);
change.promise.then(({ options, args: [command] }) => {
if (process.env.NODE_ENV !== 'development') return;
if (['up', 'down', 'redo', 'recurrent'].includes(command)) {
// `as string` is safe because you can see that databaseURL was set above
dump(options[0].databaseURL as string);
}
});
function dump(databaseURL: string) {
execSync(`pg_dump --schema-only ${databaseURL} > structure.sql`);
console.log('Db structure was dumped to structure.sql');
} |
Beta Was this translation helpful? Give feedback.
Published an update:
beforeChage
andafterChange
for convenience, docs, this won't help you with this use-casechange.promise
will return a result object which you can use to check if it was rollback, migrate, etc.