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

落爺英雄遲暮 提交于 2021-01-28 12:32:40

问题


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 }

回答1:


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))


来源:https://stackoverflow.com/questions/44272380/couldnt-match-type-persistentitybackend-entity-a-with-sqlbackend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!