Skip to content

Instantly share code, notes, and snippets.

Created November 11, 2016 23:09
What would you like to do?
Truncating tables with Sequelize

In tests that use a database, it's necessary to clean out the tables before each run (we don't use after so we can debug a failed test's db).

Sometimes we forget the syntax though so here's what we do:

before(function truncateDatabase (done) {
  // DEV: PostgreSQL doesn't support truncating all tables via a `*`
  // DEV: Our query is vulnerable to SQL injection but we can't use bind and trust our table names more/less
  var tableNames = _.pluck(_.values(sequelize.models), 'tableName');
  sequelize.query('TRUNCATE TABLE ' + tableNames.join(', ')).asCallback(done);
Copy link

danpe91 commented May 30, 2017

Why don't you use a forced sync on your models?

Copy link

I'm guessing that truncating is quicker than force sync? I don't imagine the structure of the tables should be changing in-between tests.

Copy link

mrded commented Jan 5, 2018

You can also do it like that:

Object.values(sequelize.models).map(function(model) {
  return model.destroy({ truncate: true });

Copy link

az-iB commented Oct 7, 2018

where: {},
truncate: true

Copy link

bradley commented Jul 29, 2020

Why don't you use a forced sync on your models?

It's been three years but a good reason not to do this is because sync ignores the schema migrations. This may sound inconsequential but there are things with sequelize like defaulting ids to UUIDs where the best solution remains configuring the database within migrations.

Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment