【发布时间】:2018-11-22 00:21:21
【问题描述】:
我正在尝试对表的每一行运行子查询。这是一个带有“students”表的最小工作示例。
data StudentT f
= StudentT
{ _studentId :: C f Int
, _studentName :: C f String
, _score :: C f Int
} deriving Generic
type Student = StudentT Identity
type StudentId = PrimaryKey StudentT Identity
deriving instance Show Student
instance Beamable StudentT
instance Beamable (PrimaryKey StudentT)
instance Table StudentT where
data PrimaryKey StudentT f = StudentId (Columnar f Int) deriving Generic
data SchoolDb f
= SchoolDb
{ _students :: f (TableEntity StudentT)
} deriving Generic
instance Database be SchoolDb
schoolDb :: DatabaseSettings be SchoolDb
schoolDb = defaultDbSettings
我想要实现的是这样的查询:
SELECT s.id,
s.name,
s.score,
(SELECT COUNT(*) FROM students AS t where s.score >= t.score) AS percentile
FROM students as S
我的尝试如下:
main = do
conn <- open "test.db"
runBeamSqliteDebug putStrLn conn $ do
(students :: [(Student, Int)]) <- runSelectReturningList $ select tablePercentile
liftIO $ mapM_ print students
tablePercentile :: Q _ _ _ _
tablePercentile = do
student <- all_ (_students schoolDb)
let percentile = subquery_ $ aggregate_ (const countAll_) $ filter_ (\s -> _score s <=. (_score student)) (all_ (_students schoolDb))
return (student, percentile)
有人能指出我正确的方向吗?
编辑:这是完整的错误消息。我认为subquery_ 返回一个QGenExpr,所以我没有绑定它(<-),而是把它放到了一个 let 语句中。这稍微简化了错误消息。
src/Main.hs:52:71: error:
• Couldn't match type ‘Database.Beam.Query.Internal.QNested s0’
with ‘Database.Beam.Query.QueryInaccessible’
Expected type: Q SqliteSelectSyntax
SchoolDb
Database.Beam.Query.QueryInaccessible
(StudentT
(QExpr
Database.Beam.Sqlite.Syntax.SqliteExpressionSyntax
(Database.Beam.Query.Internal.QNested s0)),
QGenExpr
QValueContext
(Database.Beam.Backend.SQL.SQL92.Sql92SelectTableExpressionSyntax
(Database.Beam.Backend.SQL.SQL92.Sql92SelectSelectTableSyntax
SqliteSelectSyntax))
s0
Int)
Actual type: Q SqliteSelectSyntax
SchoolDb
(Database.Beam.Query.Internal.QNested s0)
(StudentT
(QExpr
(Database.Beam.Backend.SQL.SQL92.Sql92SelectTableExpressionSyntax
(Database.Beam.Backend.SQL.SQL92.Sql92SelectSelectTableSyntax
SqliteSelectSyntax))
(Database.Beam.Query.Internal.QNested s0)),
QGenExpr
QValueContext
(Database.Beam.Backend.SQL.SQL92.Sql92SelectTableExpressionSyntax
(Database.Beam.Backend.SQL.SQL92.Sql92SelectSelectTableSyntax
SqliteSelectSyntax))
s0
Int)
• In the first argument of ‘select’, namely ‘tablePercentile’
In the second argument of ‘($)’, namely ‘select tablePercentile’
In a stmt of a 'do' block:
(students :: [(Student, Int)]) <- runSelectReturningList
$ select tablePercentile
|
52 | (students :: [(Student, Int)]) <- runSelectReturningList $ select tablePercentile
| ^^^^^^^^^^^^^^^
【问题讨论】:
-
请包括完整的错误——它很长不是问题。特别是,此处发布的错误部分缺少有关导致错误的代码位的信息。
标签: haskell haskell-beam