如果第二次插入失败,如何安全地对具有外键关系的 SQL 表进行多次插入,并删除第一次插入

Dan*_*tan 1 sql knex.js

我有这些拖车桌:

CREATE TABLE cities (
        city     varchar(80) primary key,
        location point
);

CREATE TABLE weather (
        city      varchar(80) references cities(city),
        temp_lo   int,
        temp_hi   int,
        prcp      real,
        date      date
);
Run Code Online (Sandbox Code Playgroud)

我正在使用 PostgreSQL 和 Knex JavaScript 驱动程序

在执行插入事务时,如何确保如果在插入表城市后插入表天气时出现错误,我可以返回并删除表城市中的插入以确保数据库完整性。拜托,我只需要看看我能做什么。

Mik*_*stö 5

也许我对这个问题的理解是错误的,但这听起来像是使用交易的基本案例。只需启动事务,执行插入,如果任何插入失败则回滚。你knex可以这样做(http://knexjs.org/#Transactions):

knex.transaction(trx => {
  return trx('cities')
    .insert({
      city: 'inari',
      ... rest of the fields ...
    })
    .then(() => {
     return trx('weather').insert({
       city: 'inari',
       ... rest of the fields ...
     });
    });
})
.then(() => {
  console.log('inserted 2 rows');
})
.catch(err => {
  console.log('one of the queries failed, no rows were inserted and transaction was rolled back')
});
Run Code Online (Sandbox Code Playgroud)

您不应该为此使用触发器。