Last active
December 15, 2016 13:34
-
-
Save derMart/87e75fbd1fdca73d6d3cebf561ca3fc6 to your computer and use it in GitHub Desktop.
knex.js migration with automatic foreign key constraints being deferrable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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