knex: ON DUPLICATE KEY UPDATE ?
Anyway to pull off an on duplicate key update for an insert statement with MySQL ?
Couldn’t find anything documentation or search wise.
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 45 (12 by maintainers)
This version handles multi-record inserts. Remove the type annotations if you’re not using Typescript.
I’ve wrote tiny lib, that adds
onDuplicateUpdatefunction to Knex QueryBuilder. https://github.com/felixmosh/knex-on-duplicate-updateUtility funciton to generate upsert query Usage:
upsert(data, 'tableName', [], ['colName']);Thought this might help someone:
I’m using this to insert-or-update in knex (ES6):
If someone could collect info how each database does this, maybe it could be specified what kind of API would be good for knex. If support is very different on every dialect, it might be better to have different API for each dialect.
This is pretty common request, so in this case separate implementations could be valid solution compared to unusable abstraction which works well only on one platform.
ON DUPLICATE KEY UPDATE It´s not supported by SQLITE.
@kibertoad version
0.21.14working perfectly. Thks.code sample:
Sorry about that.
@dotnil thx for the code. arent u missing ) closing util.format? anyways it works with it
mine is more generic.
From: http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Desired output:
Input:
It is possible to UPSERT multiple values at one time:
@ivoneijr Please try version
^0.21.14, and if that still doesn’t work, please share the code you are using and the error that you are getting.Knew has now a built in support for this, no more query concats 🎉
Here a quick example about how to insert batch data or update few fields.
@leventov do you happen to have an example of how one might use your function? Having difficulties using it here. Thanks in advance! And while I have your attention, any chance this can be used for batch style inserts?
Here’s an improvement of @j0h’s version from https://github.com/knex/knex/issues/701#issuecomment-488075856 for Postgres. It doesn’t require bothering with the constraint name, and re-uses inserted values via the special
excludedtable, that appears to work (unlike the original version) e. g. when an integer is inserted as JSONB.@dcbasso I’ve made one for postgress but perhaps you could adapt it for mysql: https://gist.github.com/adnanoner/b6c53482243b9d5d5da4e29e109af9bd
@NathanJPhillips it´s possible to make similar code with “batchInsert”?
@shikasta-kashti Ah, that’s because in your query the table name is wrapped with
"instead of `. Give this regex a try/^update ([`"])[^\1]+\1 set/i