Skip to content

Instantly share code, notes, and snippets.

@beppu
Created October 30, 2013 00:24
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 beppu/7225158 to your computer and use it in GitHub Desktop.
Save beppu/7225158 to your computer and use it in GitHub Desktop.
upsert function (and associated helper functions) written in livescript
insert-statement = (table, obj) ->
columns = keys obj
value-set = [ "$#{i+1}" for k,i in columns ].join ', '
vals = values obj
return ["INSERT INTO #table (#columns) VALUES (#value-set) RETURNING *", vals]
update-statement = (table, obj, wh) ->
wh ?= "WHERE id = $1"
ks = keys obj |> filter (-> it isnt \id)
obj-vals = [ obj[k] for k in ks ]
value-set = [ "#k = $#{i + 2}" for k,i in ks].join ', '
vals = [obj.id, ...obj-vals]
return ["UPDATE #table SET #value-set #wh RETURNING *", vals]
# Generate an upsert function for the given table name
#
# @param String table name of table
# @return Function an upsert function for the table
upsert-fn = (table) ->
(object, cb) ->
do-insert = (cb) ->
[insert-sql, vals] = insert-statement table, object
postgres.query insert-sql, vals, cb
do-update = (cb) ->
[update-sql, vals] = update-statement table, object
postgres.query update-sql, vals, cb
if not object.id
return do-insert cb
err, r <- postgres.query "SELECT * FROM #table WHERE id = $1", [ object.id ]
if r.length
do-update cb
else
do-insert cb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment