Skip to content

Instantly share code, notes, and snippets.

@avimar
Created August 28, 2016 07:15
Show Gist options
  • Save avimar/80b8ad0518b244d56bc358cf9a89ab3b to your computer and use it in GitHub Desktop.
Save avimar/80b8ad0518b244d56bc358cf9a89ab3b to your computer and use it in GitHub Desktop.
knex mysql update on duplicate and replace
function upsert(table, data, update){
if(!update) update=data;
var insert = knex(table).insert(data).toString();
var update = knex(table).update(update).toString().replace(/^update .* set /i, '');
return knex.raw(insert + ' on duplicate key update ' + update);
}
function replace(table, data){
var insert = knex(table).insert(data).toString().replace(/^INSERT/i, 'REPLACE');
return knex.raw(insert);
}
@insidewhy
Copy link

insidewhy commented Jul 9, 2018

Slightly better:

const update = knex.queryBuilder().update(update)

@JefferyHus
Copy link

@ohjames I believe this is related to the sql statement REPLACE not UPDATE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment