Using the Migrations API in knex.js inside a gulp task causes the task process to hang and not exit. What causes this and how can I fix it?
gulp.task('migrate:latest', function () {
return knex.migrate.latest({
migrations: {
tableName: 'migrations'
}
})
.then(function () {
return knex.migrate.currentVersion();
})
.then(function (version) {
console.log("Kicked database to version: " + version);
})
.catch(function (err) {
console.error(err);
});
});
It looks as though Knex keeps a reference to the open database connection, which it doesn't automatically destroy after the migration completes - which causes the process to hang. To fix this, call knex.destroy after the migration resolves. This will allow the gulp process to exit normally.
Documentation on knex's connection pooling and the explicit destroy command are here.
The gulp task becomes this:
gulp.task('migrate:latest', function () {
return knex.migrate.latest({
migrations: {
tableName: 'migrations'
}
})
.then(function () {
return knex.migrate.currentVersion();
})
.then(function (version) {
console.log("Kicked database to version: " + version);
knex.destroy();
})
.catch(function (err) {
console.error(err);
knex.destroy();
});
});
As a note, if you configure knex as a variable in your gulpfile, this will happen for all of your tasks even if that task doesn't use your knex instance. The solution to this is to define the knex configuration as a function, and then call it when you need it, like so:
var knex = function () {
return require('knex')({
client: 'postgresql',
connection: {
host: process.env.DB_HOSTNAME,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
charset: 'utf8'
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'migrations'
}
});
};
gulp.task('migrate:latest', function () {
return knex().migrate.latest({ // Call the function to set up your config.
migrations: {
tableName: 'migrations'
}
})
...
This save you from having to call knex.destroy in tasks where you don't need it. Hope this can help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With