Search code examples
javascriptnode.jsknex.js

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


Solution

  • 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 *