haskellhaskell-persistent

Couldn't match type ‘PersistEntityBackend (Entity a)’ with ‘SqlBackend’


I've got the following:

asSqlBackendReader :: ReaderT SqlBackend m a -> ReaderT SqlBackend m a
asSqlBackendReader = id

insertEnt :: (Entity a) -> IO (Key (Entity a))
insertEnt x = runWithDb $ do
  insert $ x
  where runWithDb = runSqlite "test.db" . asSqlBackendReader

The purpose of the asSqlBAckendReader is due to Persistent selectList causing error of "Couldn't match type ‘BaseBackend backend0’ with ‘SqlBackend’".

I'm running into an error of:

• Couldn't match type ‘PersistEntityBackend (Entity a)’
                 with ‘SqlBackend’
    arising from a use of ‘insert’
• In a stmt of a 'do' block: insert $ x
  In the second argument of ‘($)’, namely ‘do { insert $ x }’
  In the expression: runWithDb $ do { insert $ x }

Solution

  • Add the constraint to the signature of insertEnt. You'll also need a PersistEntity constraint.

    insertEnt
      :: ( PersistEntity (Entity a)
         , PersistEntityBackend (Entity a) ~ SqlBackend)
      => Entity a -> IO (Key (Entity a))
    

    To deduce that (other than just giving the compiler what it's indirectly asking), you may look at the type of insert

    insert
      :: ( PersistStoreWrite backend
         , MonadIO m
         , PersistRecordBackend record backend)
      => record -> ReaderT backend m (Key record)
    

    We also have

    type PersistRecordBackend record backend =
      ( PersistEntity record
      , PersistEntityBackend record ~ BaseBackend backend)
    

    Furthermore, in your application you have some concrete types:

    backend ~ SqlBackend
    m ~ (some concrete transformer stack on top of IO)
    record ~ Entity a
    

    These concrete types discharge PersistStoreWrite backend and MonadIO m, and since Entity a is still mostly abstract, you are left with the two constraints that define PersistRecordBackend. You could in fact use that synonym as a shorthand:

    insertEnt
      :: PersistRecordBackend (Entity a) SqlBackend
      => Entity a -> IO (Key (Entity a))