Skip to content

Instantly share code, notes, and snippets.

@cirosantilli
Forked from twolfson/README.md
Created April 7, 2021 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cirosantilli/6914bec358fcce4b9a2432d47aedbcb9 to your computer and use it in GitHub Desktop.
Save cirosantilli/6914bec358fcce4b9a2432d47aedbcb9 to your computer and use it in GitHub Desktop.
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) {
  // http://docs.sequelizejs.com/en/v3/docs/raw-queries/
  // https://www.postgresql.org/docs/9.3/static/sql-truncate.html
  // 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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment