无法将类型“PersistEntityBackend(实体 a)”与“SqlBackend”匹配

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

我有以下内容:

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 的目的是由于

我 运行 遇到以下错误:

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

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

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

要推断出这一点(除了给编译器它间接询问的内容之外),您可以查看 the type of 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 的两个约束。实际上,您可以将该同义词用作 shorthand:

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