Knex 截断 table 与外键约束

Knex truncate table with foreign key constraints

是否可以使用外键约束强制截断 table,以便其他 table 中受影响的所有行也被删除?

我在文档中看不到传递给 knex('tableName').truncate() 方法的选项。

我还没有找到内置的方法,所以我直接进入原始模式:

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

您也可以将其设置为在迁移中自动发生:

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');
  });
};

Knexjs 中现在有一个 truncate() 方法。

knex('accounts').truncate()
Outputs:
truncate `accounts`

可能并非适用于所有情况,但对于基本的截断需求应该没问题。

我无法在 Jest 集成测试后使用 Knex 进行清理,所以我直接使用 Node PostGres(即 pg),如下所示:

  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()
  })