Search code examples
postgresqlsequelize.js

How can I drop all tables with Sequelize.js using postgresql?


I am trying:

if (process.NODE_ENV === 'test') {
  foreignKeyChecks = 0;
  forceSync = true;
} else {
  foreignKeyChecks = 1;
  forceSync = false;
}

global.db.sequelize.query("SET FOREIGN_KEY_CHECKS = " + foreignKeyChecks).then(function() {
  return global.db.sequelize.sync({
    force: forceSync
  });
}).then(function() {
  return global.db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
}).then(function() {
  var server;
  console.log('Initialzed database on:');
  console.log(config.db);
  return server = app.listen(port, function() {
    return console.log("Server listening at http://" + (server.address().address) + ":" + (server.address().port));
  });
})["catch"](function(err) {
  return console.log('err', err);
});

module.exports = app;

But I get: SequelizeDatabaseError: unrecognized configuration parameter "foreign_key_checks"

I assume I can't have that keyword in postgres? But is there an equivalent way to drop all tables and recreate?


Solution

  • This is an updated answer, targeted at the googlers who wound up here like me.

    Sequelize offers a drop function:

    drop(options) => promise
    

    Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. Sequelize docs

    Example

    var sequelize = new Sequelize(config.database, config.username, config.password, config);
    
    var someModel = sequelize.define('somemodel', {
      name: DataTypes.STRING
    });
    
    sequelize
      .sync() // create the database table for our model(s)
      .then(function(){
        // do some work
      })
      .then(function(){
        return sequelize.drop() // drop all tables in the db
      });