metabase / toucan

A classy high-level Clojure library for defining application models and retrieving them from a DB
Eclipse Public License 1.0
569 stars 49 forks source link

Add an `upsert!` function #17

Open camsaul opened 7 years ago

camsaul commented 7 years ago

Right now to do an "upsert" operation you have to do

(or (db/update! ...) ; update! returns truthy value iff something was updated
    (db/insert!))

However, that is subject to race conditions 🙀

It would be nice to simplify this common pattern and avoid the race conditions with an upsert! function or something like that. (suggestion credit: @thearthur)

RokLenarcic commented 6 years ago

When using H2 I've just used MERGE statements, which does what you want.

trinityXmontoya commented 5 years ago

i'd be happy to try working on this, can you suggest an implementation that would avoid the race condition? ex. a query for existence first by id & then an insert/update based on that? i know upsert is available in a few databases ~Postgres's INSERT ON CONFLICT but imagine raw SQL isn't an option bc that command isn't supported by all the dbs that u can connect to w JDBC.