Created
June 27, 2015 09:44
-
-
Save cihangir/202062fd3a7daa711724 to your computer and use it in GitHub Desktop.
Inserts if not exists or select in one-trip to database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --sql, args := DB. | |
| -- Insect("tab"). | |
| -- Columns("b", "c"). | |
| -- Values(1, 2). | |
| -- Where("d = $1", 3). | |
| -- Returning("id", "f", "g"). | |
| -- ToSQL() | |
| WITH | |
| sel AS (SELECT id, f, g FROM tab WHERE (d = $1)), | |
| ins AS ( | |
| INSERT INTO "tab"("b","c") | |
| SELECT $2,$3 | |
| WHERE NOT EXISTS (SELECT 1 FROM sel) | |
| RETURNING "id","f","g" | |
| ) | |
| SELECT * FROM ins UNION ALL SELECT * FROM sel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment