简体   繁体   中英

Detect and signal onConflict with knexjs

This document here explains that using onConflict() and ignore() will simply drop the action quietly. If I am trying to insert a new row into a table as following:

const addItem = (item) => {
  return database(dbTable).insert(item)
                .onConflict('name')
                .ignore()
                .then(() => {
                }).catch((err) => {
                    console.log(err)
                })
}

If instead of ignoring , how (or where) do I return some sort of signal to the external call that invokes the function addItem ? For example, return 0 if no conflict (and item being added); return 1 if there is conflict (and the promise quietly resolved without doing anything)? Thanks

Might be database dependent functionality, but for example if you do insert with postgres and it doesn't return any rows it means that there was conflict like mentioned in this issue:

How to use RETURNING with ON CONFLICT in PostgreSQL?

Also .returning('*') seems to work correctly combined with .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 *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM