Making Custom Instances of PersistBackend
-
13-11-2019 - |
Question
I have a monad transformer stack of the form:
newtype T m a = T { unT :: StateT State (SqlPersist m) a }
deriving (Monad, MonadState State)
And want to use the persistent insert
and lookup
calls, so I need to make a PersistBackend
instance for T
. However, a phantom type encodes the specific backend into the Key
return type - this causes some extra headaches. To solve the phantom type issue, my instance has the form:
instance (Monad m, MonadIO m, MonadBaseControl IO m) => PersistBackend T m where
insert = T . lift . liftM (Key . unKey) . insert
... and about a dozen such methods ...
Am I blindly overlooking an easier way? A way other than calling the function by manually lifting: insertT = T . lift . insert
Solution
I have two different recommendations:
- Flip things around, and put the SqlPersist around your StateT instead of vice-versa.
- Create a module with lifted versions of the functions, similar to what
MonadState
does.
I'd go for (1). If a lot of people are running into this, I suppose we could have a specialized package providing the lifted versions of all the functions.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow