Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created February 26, 2021 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfborjas/d437116bf03a2f5dc61b45ffbabf73b1 to your computer and use it in GitHub Desktop.
Save lfborjas/d437116bf03a2f5dc61b45ffbabf73b1 to your computer and use it in GitHub Desktop.
Upsert that always returns in Postgres
-- :name insert-or-get-image! :<! :1
/* :doc insert an image, or retrieve existing, and return the id, uri, and
public URL as determined by the provided `:bucket` and `:images-host`.
*/
WITH new_img AS (
INSERT INTO image (uri, fmt, size, device_id, os_version_id)
VALUES (:uri, :fmt, :size, :device-id, :os-version-id)
ON CONFLICT (uri) DO NOTHING
RETURNING id, uri,
gcs_uri_to_public_url(uri, COALESCE(:bucket, ''), COALESCE(:images-host, ''))
AS "url"
)
SELECT * from new_img
UNION
SELECT id, uri,
gcs_uri_to_public_url(uri, COALESCE(:bucket, ''), COALESCE(:images-host, ''))
AS "url"
FROM image
WHERE uri = :uri
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment