因为我对Haskell很新,有人可以帮助我找到解决以下问题的正确方向吗?
我从Yesod的脚手架应用开始。提供从数据库内容生成的HTML工作正常,但有一种优雅的方法来创建迭代数据库表的纯文本响应吗?使用像
这样的处理程序的简单纯文本getTestR = return . RepPlain . toContent ...
也有效,但我想服务:
配置/模型:
File
path Text
Conf
key Text
val Text
file FileId
与SQL查询中的明文相同:
select path, key, val from file, conf order by path, key;
由于hamlet用于生成HTML,我认为我必须完全在Haskell中生成响应(迭代数据库内容)?
如何在数据库实体和文本(或Int,如果Row类型为Int)之间进行转换,如何从数据库列Id转换为?
答案 0 :(得分:2)
使用纯文本模板!! ''#{expr}''允许Text,String,Int32或Int64表达式作为Text.Shakespeare.Text.ToText的实例
{-# LANGUAGE OverloadedStrings, ConstraintKinds #-}
module Handler.Plain where
import Import
import qualified Data.List as List
import Database.Persist.Sqlite
import qualified Data.Text as Text
import Control.Monad.Logger (MonadLogger)
import Control.Monad.Trans.Resource (MonadResourceBase)
import Text.Shakespeare.Text -- for the plain text template
stmt :: Text
stmt = "SELECT ??, ?? FROM File, Conf ON Conf.file = File.id ORDER BY File.path, Conf.key"
getQryResult :: (PersistQuery SqlPersist m, MonadLogger m, MonadResourceBase m) => () -> SqlPersist m [(Text, Text, Text)]
getQryResult () = do
result <- rawSql stmt []
return $ List.map getMyData (result :: [(Entity File, Entity Conf)])
where
getMyData (Entity _ file, Entity _ conf) = (filePath file, confKey conf, confVal conf)
getPlainR :: Handler RepPlain
getPlainR = do
result <- runDB $ getQryResult ()
return $ RepPlain $ toContent $ Text.unlines $ List.map formatMyData result
where
-- formatMyData (a, b, c) = Text.intercalate ", " [a,b,c]
-- with a plain text template:
formatMyData (a, b, c) = [st|
#{a}, #{b}, #{c} |]