12

如何以模块化方式编写Database.Esqueleto查询,以便在定义“基本”查询和相应的结果集之后,我可以通过添加额外的内部连接和 where 表达式来限制结果集。

此外,如何将返回实体列表(或字段元组)的基本查询转换为计算结果集的查询,因为基本查询不是这样执行的,而是使用 LIMIT 和 OFFSET 的修改版本。

从Yesod Book 中采用的以下不正确的 Haskell 代码片段希望能阐明我的目标。

{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
{-# LANGUAGE GADTs, FlexibleContexts #-}
import qualified Database.Persist as P
import qualified Database.Persist.Sqlite as PS
import Database.Persist.TH
import Control.Monad.IO.Class (liftIO)
import Data.Conduit
import Control.Monad.Logger
import Database.Esqueleto
import Control.Applicative

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
    name String
    age Int Maybe
    deriving Show
BlogPost
    title String
    authorId PersonId
    deriving Show
Comment
    comment String
    blogPostId BlogPostId
|]

main :: IO ()
main = runStdoutLoggingT $ runResourceT $ PS.withSqliteConn ":memory:" $ PS.runSqlConn $ do
    runMigration migrateAll

    johnId <- P.insert $ Person "John Doe" $ Just 35
    janeId <- P.insert $ Person "Jane Doe" Nothing

    jackId <- P.insert $ Person "Jack Black" $ Just 45
    jillId <- P.insert $ Person "Jill Black" Nothing

    blogPostId <- P.insert $ BlogPost "My fr1st p0st" johnId
    P.insert $ BlogPost "One more for good measure" johnId
    P.insert $ BlogPost "Jane's" janeId

    P.insert $ Comment "great!" blogPostId

    let baseQuery = select $ from $ \(p `InnerJoin` b) -> do 
        on (p ^. PersonId ==. b ^. BlogPostAuthorId)
        where_ (p ^. PersonName `like` (val "J%"))
        return (p,b)

    -- Does not compile
    let baseQueryLimited = (,) <$> baseQuery <*> (limit 2)

    -- Does not compile
    let countingQuery = (,) <$> baseQuery <*> (return countRows)

    -- Results in invalid SQL 
    let commentsQuery = (,) <$> baseQuery
                <*> (select $ from $ \(b `InnerJoin` c) -> do
                        on (b ^. BlogPostId ==. c ^. CommentBlogPostId)
                        return ())

    somePosts <- baseQueryLimited
    count <- countingQuery
    withComments <- commentsQuery
    liftIO $ print somePosts
    liftIO $ print ((head count) :: Value Int)
    liftIO $ print withComments
    return ()
4

2 回答 2

9

查看文档和类型select

select :: (...) => SqlQuery a -> SqlPersistT m [r]

很明显,在调用 时select,我们离开了纯可组合查询的世界 ( SqlQuery a) 并进入了副作用的世界 ( SqlPersistT m [r])。所以我们只需要在我们之前作曲select

let baseQuery = from $ \(p `InnerJoin` b) -> do 
      on (p ^. PersonId ==. b ^. BlogPostAuthorId)
      where_ (p ^. PersonName `like` (val "J%"))
      return (p,b)

let baseQueryLimited = do r <- baseQuery; limit 2; return r
let countingQuery    = do baseQuery; return countRows

somePosts <- select baseQueryLimited
count     <- select countingQuery

这适用于限制和计数。我还没有弄清楚如何为连接做这件事,但它看起来应该是可能的。

于 2013-05-16T22:09:19.247 回答
8

对于LIMITand COUNT,hammar 的答案是完全正确的,所以我不会深入研究它们。我只是重申,一旦您使用select,您将无法再次以任何方式更改查询。

对于JOINs,目前您无法对在不同(nor s)INNER JOIN中定义的查询执行 a。但是,您可以执行隐式连接。例如,如果您定义了:from(FULL|LEFT|RIGHT) OUTER JOIN

baseQuery = 
  from $ \(p `InnerJoin` b) -> do 
  on (p ^. PersonId ==. b ^. BlogPostAuthorId)
  where_ (p ^. PersonName `like` val "J%")
  return (p, b)

然后你可能会说:

commentsQuery = 
  from $ \c -> do
  (p, b) <- baseQuery
  where_ (b ^. BlogPostId ==. c ^. CommentBlogPostId)
  return (p, b, c)

然后,Esqueleto 将生成以下内容:

SELECT ...
FROM Comment, Person INNER JOIN BlogPost
ON    Person.id = BlogPost.authorId
WHERE Person.name LIKE "J%"
AND   BlogPost.id = Comment.blogPostId

不漂亮,但可以为INNER JOINs 完成工作。如果你需要做 aOUTER JOIN那么你必须重构你的代码,以便所有的OUTER JOINs 都在同一个from(注意你可以在OUTER JOINs 之间做一个隐式连接就好了)。

于 2013-05-17T12:45:29.677 回答