【问题标题】:Haskell database query inside ScottyM() functionScottyM() 函数中的 Haskell 数据库查询
【发布时间】:2016-12-28 12:17:19
【问题描述】:

我正在尝试编写简单的 rest API。我使用 Database.SQLite.Simple、Scotty 和 Aeson。我在 ScottyM() 路由函数中遇到数据库查询问题。当我有这样的事情时

routes :: [User] -> ScottyM ()
routes allUsers = do
    get "/users/:id" $ do
        id <- param "id"
        json ([x | x <- allUsers, userId x == id] !! 0)

main = do
    conn <- open "data.db"
    users <- ( query_ conn "select id, first_name, second_name, team from users" :: IO [User] )
    scotty 3000 (routes users)

一切正常,但在这种情况下,allUsers 只会在服务器启动时更新一次。每次有人询问时,我都想查询。所以我写了这个:

routes :: Connection -> ScottyM ()
routes conn= do
   get "/users/:id" $ do
        id <- param "id"
        users <- ( query_ conn "select id, first_name, second_name, team from users" :: IO [User] )
        json (users !! id)

main = do
    conn <- open "data.db"
    scotty 3000 (routes conn)

我收到错误

Couldn't match expected type ‘Web.Scotty.Internal.Types.ActionT
                                Text IO [a0]’
            with actual type ‘IO [User]’
In a stmt of a 'do' block:
  users <- (query_
              conn "select id, first_name, second_name, team from users" ::
              IO [User])
In the second argument of ‘($)’, namely
  ‘do { id <- param "id";
        users <- (query_
                    conn "select id, first_name, second_name, team from users" ::
                    IO [User]);
        json (users !! id) }’
In a stmt of a 'do' block:
  get "/users/:id"
  $ do { id <- param "id";
         users <- (query_
                     conn "select id, first_name, second_name, team from users" ::
                     IO [User]);
         json (users !! id) }

如何解决这个问题?另外,如果我想例如select * from users where id = id from parameters,如何将参数传递给sql查询?

【问题讨论】:

    标签: sql rest haskell scotty


    【解决方案1】:

    get 函数的第二个参数是ActionM 类型。如果您进一步调查,您会发现这只是外观更复杂的ActionT 的简写,eTextmIO

    因为您的do 块属于这种类型,所以您不能直接调用IO 函数。您需要使用liftIO 来获得正确的类型。因此,只需在 query_ 调用之前添加 liftIO 即可修复它。

    项目 wiki 中有一个名为 using scotty with IO 的示例显示了这一点。

    【讨论】:

      猜你喜欢
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多