编写Database.Esqueleto查询,条件连接和计数

时间:2013-05-16 19:30:46

标签: sql haskell yesod

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

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

the 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 ()

2 个答案:

答案 0 :(得分:8)

查看文档和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

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

答案 1 :(得分:7)

对于LIMITCOUNT,哈马尔的回答是完全正确的,所以我不会深入研究它们。我将重申,一旦您使用select,您将无法再以任何方式更改查询。

对于JOIN,目前您无法使用在其他INNER JOIN(也不是from s)中定义的查询执行(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 JOIN完成了工作。如果您需要执行OUTER JOIN,那么您必须重构代码,以便所有OUTER JOIN都在同一个from中(请注意,您可以执行隐式连接在OUTER JOIN之间就好了。