1

我有以下内容:

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

的目的asSqlBAckendReader是由于Persistent selectList 导致错误 "Couldn't match type 'BaseBackend backend0' with 'SqlBackend'"

我遇到了以下错误:

• 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 }
4

1 回答 1

2

将约束添加到 的签名中insertEnt。您还需要一个PersistEntity约束。

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

要推断出这一点(不仅仅是给编译器它间接询问的内容),您可以查看insert

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

我们还有

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

此外,在您的应用程序中,您有一些具体的类型:

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

这些具体类型释放PersistStoreWrite backendMonadIO m,并且由于Entity a仍然主要是抽象的,因此您只剩下定义 的两个约束PersistRecordBackend。实际上,您可以将该同义词用作速记:

insertEnt
  :: PersistRecordBackend (Entity a) SqlBackend
  => Entity a -> IO (Key (Entity a))
于 2017-05-30T21:45:01.640 回答