使用 knexjs 检测并发出 onConflict 信号
Detect and signal onConflict with knexjs
本文档 here 解释了使用 onConflict()
和 ignore()
只会悄悄地停止操作。如果我尝试将新行插入到 table 中,如下所示:
const addItem = (item) => {
return database(dbTable).insert(item)
.onConflict('name')
.ignore()
.then(() => {
}).catch((err) => {
console.log(err)
})
}
如果不是 ignoring
,我如何(或在哪里)return 向调用函数 addItem
的外部调用发出某种信号?例如,return 0
如果没有冲突(并且正在添加项目); return 1
是否有冲突(并且 promise 悄悄地解决了,没有做任何事情)?谢谢
可能是依赖于数据库的功能,但是例如,如果您使用 postgres 进行插入并且它没有 return 任何行,则表示存在本期提到的冲突:
而且 .returning('*')
似乎与 .onConflict(...).ignore()
结合使用也能正常工作
https://runkit.com/embed/6p825ex0xt4b
knex('table').insert({a: 1, b:2}).onConflict('id').ignore().returning('*').toSQL().sql;
// knex 0.21.15 returns:
// insert into "table" ("a", "b") values (?, ?)
// on conflict ("id") do nothing returning *
本文档 here 解释了使用 onConflict()
和 ignore()
只会悄悄地停止操作。如果我尝试将新行插入到 table 中,如下所示:
const addItem = (item) => {
return database(dbTable).insert(item)
.onConflict('name')
.ignore()
.then(() => {
}).catch((err) => {
console.log(err)
})
}
如果不是 ignoring
,我如何(或在哪里)return 向调用函数 addItem
的外部调用发出某种信号?例如,return 0
如果没有冲突(并且正在添加项目); return 1
是否有冲突(并且 promise 悄悄地解决了,没有做任何事情)?谢谢
可能是依赖于数据库的功能,但是例如,如果您使用 postgres 进行插入并且它没有 return 任何行,则表示存在本期提到的冲突:
而且 .returning('*')
似乎与 .onConflict(...).ignore()
https://runkit.com/embed/6p825ex0xt4b
knex('table').insert({a: 1, b:2}).onConflict('id').ignore().returning('*').toSQL().sql;
// knex 0.21.15 returns:
// insert into "table" ("a", "b") values (?, ?)
// on conflict ("id") do nothing returning *