IHP 1.1 is out now!

How to check if column exist, update if it does, and insert new if it doesnt?

Aksel Stadler Kjetså

Say I have a Post with many to many relationship to tags. It's nice to add the tags as a comma separated list when creating a post. That means I need to update two records at the same time. That seems fine. However, i struggle with the fact that the tag might already exist, and how to deal with it. That part of the code looks like this

 action CreatePostAction = do         
      tagg <- case  (query @Tag |> findMaybeBy #name (param @Text "name") ) of
           Just tag -> tag
           Nothing -> newRecord @Tag

And I get the compile error

 Couldn't match expected type ‘IO (Maybe Tag)’
             with actual type ‘Maybe a0’
HugoPeters1024

Similarly, I've been missing a create if not exist operation for a database seed script that can safely be run every deployment. (which update or create would solve)

HugoPeters1024

For your specific code however, you are pattern matching on an IO operation, you will first need to bind (<-) the result of query, then make a let definition for tagg over that result

Amitai Burstein

I think you would need to do something like:

action CreatePostAction = do     
    maybeTag <- query @Tag |> findMaybeBy #name (param @Text "name") 
    let tagg = case maybeTag of
           Just tag -> pure tag
           Nothing -> newRecord @Tag