持久化中使用`get`和`toSqlKey` [英] Use of `get` and `toSqlKey` in persistent

查看:146
本文介绍了持久化中使用`get`和`toSqlKey`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个 User 模型。

我试图在服务器上使用persistent-postgresql。 / p>

我想要一个端点接受一个id并返回带有该id的用户。



根据其他答案我可以使用 toSqlKey Int64 变成 feed to get



我的功能如下所示:

  oneUser :: Int64  - > App(实体用户)
oneUser userId = do
maybeUser< - runDb $ get $ toSqlKey userId
case mayUser of
Nothing - >
throwError err404
只是用户 - >
返回用户

当我尝试编译时,出现错误无法匹配预期类型'PersistEntityBackend(实体用户)'与实际类型'SqlBackend'



使用 selectList



  allUsers :: App [实体用户] 
allUsers = runDb $ selectList [] []

请告诉我我做错了什么,我应该在哪里看未来的东西是这样的。我找不到取得在hackage上/正确版本的图书馆在堆叠等。



runDb 看起来像:

  runDb ::(MonadReader Config m,MonadIO m)= > SqlPersistT IO b  - > mb 
runDb query = do
pool< - 请求getPool
liftIO $ runSqlPool查询池

取自这个github项目

解决方案

区别在于 get ... 简单的用户不是实体用户,所以这将工作:

  altSingleUser :: Int64  - >应用用户
altSingleUser userid = do
let foo = get(toSqlKey userid):: SqlPersistT IO(也许用户)
maybeUser< - runDb $ foo
case可能用户
Nothing - >
throwError err404
只是人 - >
return person

如果您要返回实体用户,只需将最后一条return语句改为:

  return $实体{entityKey = toSqlKey userid,entityVal = person} 


I'm trying to use persistent-postgresql with servant.

I have a User model.

I want to have an endpoint that takes an id and returns the user with that id.

According to other answers I can use toSqlKey to turn an Int64 into a Key to feed to get.

My function looks like:

oneUser :: Int64 -> App (Entity User)
oneUser userId = do
  maybeUser <- runDb $ get $ toSqlKey userId
  case maybeUser of
    Nothing ->
      throwError err404
    Just user ->
      return user

When I try to compile I get the error Couldn't match expected type ‘PersistEntityBackend (Entity User)’ with actual type ‘SqlBackend’

Use of selectList works fine.

allUsers :: App [Entity User]
allUsers = runDb $ selectList [] []

Please tell me what I'm doing wrong and where I should look in the future for stuff like this. I couldn't find get on hackage/the right version of the library on stackage etc.

runDb looks like:

runDb :: (MonadReader Config m, MonadIO m) => SqlPersistT IO b -> m b
runDb query = do
  pool <- asks getPool
  liftIO $ runSqlPool query pool

taken from this github project.

解决方案

The difference is that get ... returns a plain User not an Entity User, so this will work:

altSingleUser :: Int64 -> App User
altSingleUser userid = do
    let foo = get (toSqlKey userid) :: SqlPersistT IO (Maybe User)
    maybeUser <- runDb $ foo
    case maybeUser of
         Nothing ->
            throwError err404
         Just person ->
            return person

If you want to return an Entity User, just change the last return statement to:

return $ Entity { entityKey = toSqlKey userid, entityVal = person }

这篇关于持久化中使用`get`和`toSqlKey`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆