Created
April 3, 2013 15:51
-
-
Save torhve/5302439 to your computer and use it in GitHub Desktop.
use postgresql "upsert" using writable CTE (psql 9.1 feature)
This file contains 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
-- use postgresql "upsert" using writable CTE (psql 9.1 feature) | |
local sql = [[ | |
WITH new_values (rss_feed, guid, title, url, pubDate, content) AS ( | |
VALUES | |
]]..sprintf('(%s, %s, %s, %s, %s::timestamp, %s)', rss_feed, quote(guid), quote(e.title), quote(e.link), quote(e.updated), quote(content))..[[ | |
), | |
upsert as | |
( | |
UPDATE rss_item m | |
SET rss_feed = nv.rss_feed, | |
guid = nv.guid, | |
title = nv.title, | |
url = nv.url, | |
pubDate = nv.pubDate, | |
content = nv.content | |
FROM new_values nv | |
WHERE m.rss_feed = nv.rss_feed | |
AND m.guid = nv.guid | |
RETURNING m.* | |
) | |
INSERT INTO rss_item (rss_feed, guid, title, url, pubDate, content) | |
SELECT rss_feed, guid, title, url, pubDate, content | |
FROM new_values | |
WHERE NOT EXISTS (SELECT 1 | |
FROM upsert up | |
WHERE up.rss_feed = new_values.rss_feed | |
AND up.guid = new_values.guid) | |
]] | |
local res = db.dbreq(sql) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment