on dev help sign in
exists
3906bfbEitan Chatav
squeal-postgresql/src/Squeal/PostgreSQL/Query.hs+20
@@ -91,6 +91,7 @@ module Squeal.PostgreSQL.Query
91 , GroupByClause (..)
91 , GroupByClause (..)
92 , HavingClause (..)
92 , HavingClause (..)
93 -- * Subquery Expressions
93 -- * Subquery Expressions
94+ , exists
94 , in_
95 , in_
95 , rowIn
96 , rowIn
96 , eqAll
97 , eqAll
@@ -321,6 +322,20 @@ let
321in printSQL query
322in printSQL query
322:}
323:}
323SELECT "col1" AS "col1", rank() OVER (PARTITION BY "col1" ORDER BY "col2" ASC) AS "rank" FROM "tab" AS "tab"
324SELECT "col1" AS "col1", rank() OVER (PARTITION BY "col1" ORDER BY "col2" ASC) AS "rank" FROM "tab" AS "tab"
325+
326+correlated subqueries
327+
328+>>> :{
329+let
330+ query :: Query '[] '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4]
331+ query =
332+ select #col1 (from (table (#tab `as` #t1))
333+ & where_ (exists (
334+ select Star (from (table (#tab `as` #t2))
335+ & where_ (#t2 ! #col2 .== #t1 ! #col1)))))
336+in printSQL query
337+:}
338+SELECT "col1" AS "col1" FROM "tab" AS "t1" WHERE EXISTS (SELECT * FROM "tab" AS "t2" WHERE ("t2"."col2" = "t1"."col1"))
324-}
339-}
325newtype Query
340newtype Query
326 (outer :: FromType)
341 (outer :: FromType)
@@ -1075,6 +1090,11 @@ unsafeRowSubqueryExpression
1075unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1090unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1076 renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
1091 renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
1077
1092
1093+exists
1094+ :: Query (Join outer from) commons schemas params row
1095+ -> Condition outer grp commons schemas params from
1096+exists query = UnsafeExpression $ "EXISTS" <+> parenthesized (renderSQL query)
1097+
1078-- | The right-hand side is a sub`Query`, which must return exactly one column.
1098-- | The right-hand side is a sub`Query`, which must return exactly one column.
1079-- The left-hand expression is evaluated and compared to each row of the
1099-- The left-hand expression is evaluated and compared to each row of the
1080-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1100-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.