Haskell Persistent Library - 如何将数据从我的数据库获取到我的前端?

问题描述

您好,感谢您抽出宝贵时间。 我正在尝试创建一个网站,该网站具有一个增加计数器的按钮。我希望当前计数器是持久的,如果有人访问我的页面,则应显示当前计数器。 每次单击按钮以增加计数器时,都应发送请求。该请求不包含有关计数器值的任何信息。服务器 - 在我的例子中是一个 warp web 服务器 - 应该更新数据库中的计数器值,在更新后读取该值,然后如果成功则将其发送到前端,否则将发送错误消息。

到目前为止,只有更新有效,因为我没有设法弄清楚如何将数据从数据库获取到前端。 这是我的 Repository 模块中应该进行更新的代码

{-# LANGUAGE EmptyDataDecls,FlexibleContexts,GADTs,GeneralizednewtypeDeriving#-}
{-# LANGUAGE MultiParamTypeClasses,OverloadedStrings,QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell,TypeFamilies,DataKinds,FlexibleInstances#-}
{-# LANGUAGE DerivingStrategies,StandaloneDeriving,UndecidableInstances #-}

module Repository (increaseCounter) where

import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger (runStderrLoggingT)
import Database.Persist
import Database.Persist.sqlite
import Database.Persist.TH
import Control.Monad.Reader
import Data.Text
import Data.Maybe

-- setting up the Counter entity with a unique key so I can use the getBy function
share [mkPersist sqlSettings,mkMigrate "migrateall"] [persistLowerCase|
      Counter
        counterName String
        counterCount Int Maybe
        UniqueCounterName counterName
        deriving Show
    |]
    
increaseCounter :: IO ()
increaseCounter = 
    runStderrLoggingT $ withsqliteConn "//absolute/path/database.db" $ runsqlConn $ do
    runMigration migrateall -- only for developing

    updateWhere [CounterCounterName ==. "unique name"] [CounterCounterCount +=. Just 1]
    counterEntity <- getBy $ UniqueCounterName name
    liftIO $ print counterEntity

这会编译并实际持久化计数器并在每次调用时更新该值。但是从类型中可以看出,更新后它只会将计数器值打印到控制台。 我似乎在理解如何使用从 getBy 函数返回的数据时遇到问题。 文档说:

getBy :: (PersistUniqueRead backend,Monadio m,PersistRecordBackend record backend) => 
Unique record -> ReaderT backend m (Maybe (Entity record))

“后端 m”基本上是一个嵌套的 monad 吗? 假设我只想发送计数器的值,如果它是 Just Int,如果它是 nothing,我想返回 -1。 我假设我无法修改 increaseCounter 函数,使其类型为 Maybe Int。但是如何将函数传递到 monad / 访问里面的值以向前端发送响应?

如果这个问题很肤浅和/或我目前缺乏太多知识,您能推荐好的信息来源吗?像好的教程或 YouTube 频道之类的东西?

谢谢!

解决方法

您可以忽略 getBy 类型签名的所有一元部分。如果您让代码进行类型检查,则 counterEntity 的类型为 Maybe (Entity Counter),这就是这里的全部内容。

如果查询失败(即表中没有该计数器的记录),则 counterEntityNothing。否则,它是包含检索到的记录的 Just 一个 Entity Counter

case counterEntity of
  Just e -> ...

这个 e :: Entity Counter 可以通过 Counter 变成一个 entityVal。可以使用 Counter 提取该 counterCounterCount 的所需字段。结果将是 Maybe Int,因为您已将该字段标记为 Maybe,因此您将有另一层 Maybe 需要解压缩:

case counterEntity of
   Nothing -> -1    -- no record for this counter
   Just e -> case counterCounterCount (entityVal e) of
     Nothing -> -1  -- record,but counter value missing
     Just v -> v

您需要从 increaseCounter 返回此值,因此最终版本将如下所示:

increaseCounter :: IO Int
increaseCounter =
    runStderrLoggingT $ withSqliteConn "//absolute/path/database.db" $ runSqlConn $ do
    runMigration migrateAll -- only for developing
    updateWhere [CounterCounterName ==. "unique name"] [CounterCounterCount +=. Just 1]
    counterEntity <- getBy $ UniqueCounterName "unique name"
    return $ case counterEntity of
      Nothing -> -1
      Just e -> case counterCounterCount . entityVal $ e of
        Nothing -> -1
        Just v -> v

无论您之前成功使用 increaseCounter 增加计数器的位置,您现在都需要编写:

updatedCounterValue <- increaseCounter

并且您可以将普通的旧 updatedCounterValue :: Int 传递到前端。

您可能会发现使用 upsertBy 更明智,它可以在计数器记录丢失时插入它,否则就更新它。它还返回插入/更新的实体,为您节省单独的 getBy 调用。我也不明白你为什么用 counterCount 标记 Maybe。为什么要在表中插入一个没有价值的计数器?如果要表示“无计数”,“0”不是更好的起始值吗?

因此,我将架构重写为:

  Counter
    counterName String
    counterCount Int    -- no Maybe
    UniqueCounterName counterName
    deriving Show

increaseCounter 函数为:

increaseCounter :: IO Int
increaseCounter =
    runStderrLoggingT $ withSqliteConn "//absolute/path/database.db" $ runSqlConn $ do
    runMigration migrateAll -- only for developing
    let name = "unique name"
    counterEntity <- upsertBy (UniqueCounterName name)
                              (Counter name 1)
                              [CounterCounterCount +=. 1]
    return $ counterCounterCount (entityVal counterEntity)

插入 1 个计数或增加现有计数。

最后,作为通用设计方法,最好将数据库迁移和连接设置移到 main 函数中,并且可能使用连接池,例如:

#!/usr/bin/env stack
-- stack --resolver lts-18.0 script
--   --package warp
--   --package persistent
--   --package persisent-sqlite

{-# LANGUAGE EmptyDataDecls,FlexibleContexts,GADTs,GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses,OverloadedStrings,QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell,TypeFamilies,DataKinds,FlexibleInstances#-}
{-# LANGUAGE DerivingStrategies,StandaloneDeriving,UndecidableInstances #-}

import Control.Monad.Logger (runStderrLoggingT)
import Database.Persist
import Database.Persist.TH
import Database.Persist.Sqlite
import Control.Monad.Reader
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Handler.Warp
import qualified Data.ByteString.Lazy.Char8 as C8

share [mkPersist sqlSettings,mkMigrate "migrateAll"] [persistLowerCase|
      Counter
        counterName String
        counterCount Int
        UniqueCounterName counterName
        deriving Show
    |]

increaseCounter :: ReaderT SqlBackend IO Int
increaseCounter = do
    let name = "unique name"
    counterEntity <- upsertBy (UniqueCounterName name)
                              (Counter name 1)
                              [CounterCounterCount +=. 1]
    return $ counterCounterCount (entityVal counterEntity)

main :: IO ()
main = runStderrLoggingT $ withSqlitePool "some_database.db" 5 $ \pool -> do
  runSqlPool (runMigration migrateAll) pool
  let runDB act = runSqlPool act pool
  liftIO $ run 3000 $ \req res -> do
    count <- runDB $ increaseCounter
    res $ responseLBS
      status200
      [("Content-Type","text/plain")]
      (C8.pack $ show count ++ "\n")

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...