11

Is it possible to force truncate a table with foreign key constraints so that all rows in other tables effected are also removed?

I cannot see in documentation for an option to pass to knex('tableName').truncate() method.

Kousha
  • 32,871
  • 51
  • 172
  • 296

2 Answers2

17

I haven't found a built in way to do it, so I just drop into raw mode:

 knex.raw('TRUNCATE TABLE users, products CASCADE')

You can also set this up to happen automatically in your migrations:

exports.up = function(knex) {
  return knex.schema.createTable('users_products', (t) => {
      t.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()'));
      t.uuid('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
      t.uuid('product_id').notNullable().references('id').inTable('products').onDelete('CASCADE');
  });
};
Gangstead
  • 4,152
  • 22
  • 35
  • 2
    in the current version of knex, the command looks like this: `knex.schema.raw('TRUNCATE TABLE users, products CASCADE')` – JP Lew Sep 05 '18 at 02:39
1

I couldn't get this to work with Knex for cleaning up after Jest integration tests, so I used Node PostGres (i.e. pg) directly, like this:

  const { Pool } = require('pg')
  const connectionString = 'postgresql://dbuser:secretpassword@database.server.com:3211/mydb';
  const pool = new Pool({
    connectionString,
  })
  pool.query('TRUNCATE myTable RESTART IDENTITY CASCADE;', (err, res) => {
    console.log(err, res)
    pool.end()
  })
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
  • Awesome answer, tried many before this worked. They key part here is was including "RESTART IDENTITY" in the raw command before "CASCADE" – Display name Jan 19 '23 at 19:38