简体   繁体   English

在Esqueleto和Yesod中执行COUNT(id)的正确方法是什么

[英]What is a correct way of doing COUNT(id) in Esqueleto and Yesod

I'm trying to figure out how to write the following query using Esqueleto 我试图弄清楚如何使用Esqueleto编写以下查询

SELECT COUNT("person"."id")
FROM "person"
WHERE (("person"."admin" = 't' OR "person"."vip" = 't') // 't' as in True
      OR "person"."karma" >= 5000 AND "person"."hellbanned" = 'f')

Here's how my model is defined 这是我的模型的定义方式

Person
    admin Bool
    vip Bool
    karma Int
    hellbanned Bool

I've managed to get almost everything, except for the COUNT part 除了COUNT部分,我已经成功获得了所有东西

select $
  from $ \p -> do
    where_
      ((p ^. PersonAdmin ==. val True) ||. (p ^. PersonVip ==. val True)
      &&. (p ^. PersonKarma >=. val 5000) &&. (p ^. PersonHellbanned ==. val False))
    return $ p ^. PersonId

I managed to find a countRows function, however I haven't managed to find a way to combine these two in a way that typechecks. 我设法找到了一个countRows函数,但是我没有设法找到一种方法来组合这两个以countRows的方式。

I'm also not sure if I need all those p ^. 我也不确定我是否需要所有那些p ^. in each branch of the where clause, or if those can be collapsed together somehow? 在where子句的每个分支中,或者如果那些可以以某种方式折叠在一起?

Here's some old code I have that does a count, I don't remember much about this, but hopefully it helps! 这里有一些我有的旧代码,我不记得很多,但希望它有所帮助!

selectCount
  :: (From SqlQuery SqlExpr SqlBackend a)
  => (a -> SqlQuery ()) -> Persist Int
selectCount q = do
  res <- select $ from $ (\x -> q x >> return countRows)
  return $ fromMaybe 0 $ (\(Value a) -> a) <$> headMay res

getCount :: RepositoryUri -> Persist Int
getCount ruri =
  selectCount $ \(r `InnerJoin` rs) -> do
    on     $ r ^. R.RepositoryId  ==. rs ^. Repo
    where_ $ r ^. R.Uri ==. val ruri

I've found Adam Bergmark's answer quite useful, but I think it should be more informative: 我发现Adam Bergmark的答案非常有用,但我认为它应该提供更多信息:

import Import hiding ( Value )
import Data.Maybe ( maybeToList
                  , listToMaybe )
import Database.Esqueleto
import Database.Esqueleto.Internal.Language (From)

selectCount
  :: (From SqlQuery SqlExpr SqlBackend a)
  => (a -> SqlQuery ()) -> YesodDB App Int
selectCount q = do
  res <- select $ from $ (\x -> q x >> return countRows)
  return $ fromMaybe 0 . listToMaybe . fmap (\(Value v) -> v) $ res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM