Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: support for upserts #81

Open
JeffML opened this issue May 30, 2020 · 1 comment
Open

Enhancement: support for upserts #81

JeffML opened this issue May 30, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@JeffML
Copy link

JeffML commented May 30, 2020

As you probably know, and upsert is a combination of insert/update. The operation will either update and existing row or insert a new one in a table. Most databases support SQL syntax necessary to do this in one operation. Unfortunately, the syntax varies depending on DBMS.

MySQL:

SET @id = 1,
    @title = 'In Search of Lost Time',
    @author = 'Marcel Proust',
    @year_published = 1913;
INSERT INTO books
    (id, title, author, year_published)
VALUES
    (@id, @title, @author, @year_published)
ON DUPLICATE KEY UPDATE
    title = @title,
    author = @author,
    year_published = @year_published;

Where ON DUPLICATE KEY triggers an UPDATE instead of an INSERT.

Postgres (9.5+):

INSERT INTO tablename (a, b, c) values (1, 2, 10)
ON CONFLICT (a) DO UPDATE SET c = tablename.c + 1;

where a is (usually) the primary key.

SQLite:
Appears to be the same (or close to) the syntax Postgres uses.

Here's a link on how to implement ON CONFICT in knex.js:
https://jaketrent.com/post/upsert-knexjs/

@danielrearden danielrearden added the enhancement New feature or request label May 30, 2020
@danielrearden
Copy link
Owner

Great suggestion! Would be great if this finally got merged, which would add an onConflict method to the Knex builder but it looks like progress on that PR has stalled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants