Skip to content
Advertisement

Upsert in KnexJS

I have an upsert query in PostgreSQL like:

INSERT INTO table
  (id, name)
values
  (1, 'Gabbar')
ON CONFLICT (id) DO UPDATE SET
  name = 'Gabbar'
WHERE
  table.id = 1

I need to use knex to this upsert query. How to go about this?

Advertisement

Answer

So I solved this using the following suggestion from Dotnil’s answer on Knex Issues Page:

var data = {id: 1, name: 'Gabbar'};
var insert = knex('table').insert(data);
var dataClone = {id: 1, name: 'Gabbar'};

delete dataClone.id;

var update = knex('table').update(dataClone).whereRaw('table.id = ' + data.id);
var query = `${ insert.toString() } ON CONFLICT (id) DO UPDATE SET ${ update.toString().replace(/^updates.*ssets/i, '') }`;

return knex.raw(query)
.then(function(dbRes){
  // stuff
});

Hope this helps someone.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement