haskellpersistentesqueleto

Update a row with specific ID in Esqueleto


I can change a field of a row with entryId in Esqueleto like this:

  update $ \entry -> do
    set entry [ EntryFoo =. val bar ]
    where_ (entry ^. EntryId ==. val entryId)

However, writing it all the time gets annoying. I'd like to be able to write something like this:

  updateById entryId $ \entry ->
    set entry [ EntryFoo =. val bar ]

I tried to write this helper by myself, but found that I don't know how to write ^. EntryId in a generic way (i.e. a way that would work for any entry types). Is it possible? Or am I missing something and updateById already exists in Esqueleto?


Solution

  • For any Entity, ^. EntityId can be written as ^. persistIdField (the persistIdField field is a method of the PersistEntity class). Thus, your function can be written like this:

    updateById
      :: (E.PersistEntityBackend val ~ E.SqlBackend,
          MonadIO m, E.PersistEntity val)
      => Key val
      -> (E.SqlExpr (E.Entity val) -> E.SqlQuery a)
      -> E.SqlWriteT m ()
    updateById entryId upd = E.update $ \entry -> do
      upd entry
      E.where_ (entry E.^. E.persistIdField ==. E.val entryId)