danielrearden / sqlmancer

Conjure SQL from GraphQL queries 🧙🔮✨
https://sqlmancer.netlify.com
MIT License
139 stars 7 forks source link

Enhancement: support for upserts #81

Open JeffML opened 4 years ago

JeffML commented 4 years ago

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 commented 4 years ago

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.