Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex truncate table with foreign key constraints

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.

like image 556
Kousha Avatar asked Apr 07 '16 20:04

Kousha


People also ask

Can we truncate a table with foreign key?

You cannot truncate a table that has foreign key constraints.

Does truncate ignore foreign keys?

But if there is a foreign key constraint on the table, SQL Server will not allow a truncate, only a delete.

What is KNEX NPM?

A SQL query builder that is flexible, portable, and fun to use! A batteries-included, multi-dialect (PostgreSQL, MySQL, CockroachDB, MSSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for Node. js, featuring: transactions. connection pooling.


1 Answers

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');
  });
};
like image 96
Gangstead Avatar answered Oct 06 '22 10:10

Gangstead