Skip to content

Instantly share code, notes, and snippets.

@derMart
Last active December 15, 2016 13:34
Show Gist options
  • Save derMart/87e75fbd1fdca73d6d3cebf561ca3fc6 to your computer and use it in GitHub Desktop.
Save derMart/87e75fbd1fdca73d6d3cebf561ca3fc6 to your computer and use it in GitHub Desktop.
knex.js migration with automatic foreign key constraints being deferrable
var forOwn = require('lodash/forOwn');
exports.up = function (knex) {
var builder = knex.schema;
// do some schema changes using builder
return builder.then(() => {
return knex('pg_constraint').select('*').where('contype', '=', 'f');
})
.then(data => {
var promises = [];
// go through all foreign key constraints and make them deferrable initally deferred
forOwn(data, item => {
promises.push(knex('pg_class').select('relname').where('oid', '=', item.conrelid)
.then(data => {
var tableName = data[0].relname;
return knex.schema.raw('ALTER TABLE ' + tableName + ' ALTER CONSTRAINT ' + item.conname + ' DEFERRABLE INITIALLY DEFERRED');
}));
});
return Promise.all(promises);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment