如果第二次插入失败,如何安全地对具有外键关系的 SQL table 进行多次插入并删除第一次插入
How to do multiple inserts to SQL table with foreign key relationship safely with delete first insert if second insert fails
我有这些 tables:
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
);
我正在使用 PostgreSQL 和 Knex JavaScript 驱动程序
在进行插入事务时,如何确保如果在 table 天气插入 table 城市后出现错误,我可以返回并删除插入table 城市确保数据库完整性。
请让我看一眼我能做什么。
您可以写 AFTER INSERT trigger
ON weather
table。
由于您的 city
是 cities
table 中的主键,当 weather
table 中的插入失败时,您可以使用 table 从城市中删除条目 WHERE 条件- city = NEW.city
。
NEW.city表示天气table当前插入的城市的值,插入失败
也许我理解错了问题,但这听起来像是使用交易的基本案例。只需开始事务,执行插入,如果任何插入失败则回滚。使用 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')
});
你不应该为此使用触发器。
我有这些 tables:
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
);
我正在使用 PostgreSQL 和 Knex JavaScript 驱动程序
在进行插入事务时,如何确保如果在 table 天气插入 table 城市后出现错误,我可以返回并删除插入table 城市确保数据库完整性。 请让我看一眼我能做什么。
您可以写 AFTER INSERT trigger
ON weather
table。
由于您的 city
是 cities
table 中的主键,当 weather
table 中的插入失败时,您可以使用 table 从城市中删除条目 WHERE 条件- city = NEW.city
。
NEW.city表示天气table当前插入的城市的值,插入失败
也许我理解错了问题,但这听起来像是使用交易的基本案例。只需开始事务,执行插入,如果任何插入失败则回滚。使用 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')
});
你不应该为此使用触发器。