@@ -1,5 +1,3 @@
1−{-# language DerivingVia #-}
2−{-# language GeneralizedNewtypeDeriving #-}
3{-# language StandaloneKindSignatures #-}
1{-# language StandaloneKindSignatures #-}
5module Rel8.Query
3module Rel8.Query
@@ -8,14 +6,22 @@ module Rel8.Query
9+import Control.Applicative ( liftA2 )
10+import Control.Monad ( liftM2 )
11import Data.Kind ( Type )
11import Data.Kind ( Type )
12+import Data.Monoid ( Any( Any ) )
12import Prelude
13import Prelude
15−import qualified Opaleye.Select as Opaleye
16+import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
17+import qualified Opaleye.Internal.PackMap as Opaleye
18+import qualified Opaleye.Internal.PrimQuery as Opaleye
19+import qualified Opaleye.Internal.QueryArr as Opaleye
20+import qualified Opaleye.Internal.Tag as Opaleye
18import Rel8.Query.Set ( unionAll )
23import Rel8.Query.Set ( unionAll )
24+import Rel8.Query.Opaleye ( fromOpaleye )
19import Rel8.Query.Values ( values )
25import Rel8.Query.Values ( values )
20import Rel8.Table.Alternative
26import Rel8.Table.Alternative
21 ( AltTable, (<|>:)
27 ( AltTable, (<|>:)
@@ -23,22 +29,172 @@ import Rel8.Table.Alternative
25-- semigroupoids
31-- semigroupoids
26−import Data.Functor.Apply ( Apply, WrappedApplicative(..) )
32+import Data.Functor.Apply ( Apply, (<.>) )
27import Data.Functor.Bind ( Bind, (>>-) )
33import Data.Functor.Bind ( Bind, (>>-) )
30-- | The @Query@ monad allows you to compose a @SELECT@ query. This monad has
36-- | The @Query@ monad allows you to compose a @SELECT@ query. This monad has
31-- semantics similar to the list (@[]@) monad.
37-- semantics similar to the list (@[]@) monad.
32type Query :: Type -> Type
38type Query :: Type -> Type
33−newtype Query a = Query (Opaleye.Select a)
39+newtype Query a =
34− deriving newtype (Functor, Applicative, Monad)
40+ Query (
35− deriving Apply via (WrappedApplicative Opaleye.Select)
41+ -- This is based on Opaleye's Select monad, but with two addtions. We
42+ -- maintain a stack of PrimExprs from parent previous subselects. In
43+ -- practice, these are always the results of dummy calls to random().
45+ -- We also return a Bool that indicates to the parent subselect whether
46+ -- or not that stack of PrimExprs were used at any point. If they weren't,
47+ -- then the call to random() is never added to the query.
49+ -- This is all needed to implement evaluate. Consider the following code:
52+ -- x <- values [lit 'a', lit 'b', lit 'c']
53+ -- y <- evaluate $ nextval "user_id_seq"
56+ -- If we just used Opaleye's Select monad directly, the SQL would come out
62+ -- (VALUES ('a'), ('b'), ('c')) Q1(a),
63+ -- LATERAL (SELECT nextval('user_id_seq')) Q2(b);
65+ -- From the Haskell code, you would intuitively expect to get back the
66+ -- results of three different calls to nextval(), but from Postgres' point
67+ -- of view, because the Q2 subquery doesn't reference anything from the Q1
68+ -- query, it thinks it only needs to call nextval() once. This is actually
69+ -- exactly the same problem you get with the deprecated ListT IO monad from
70+ -- the transformers package — *> behaves differently to >>=, so
71+ -- using ApplicativeDo can change the results of a program. ApplicativeDo
72+ -- is exactly the optimisation Postgres does on a "LATERAL" query that
73+ -- doesn't make any references to previous subselects.
75+ -- Rel8's solution is generate the following SQL instead:
81+ -- random() AS dummy,
84+ -- (VALUES ('a'), ('b'), ('c')) Q1(a)) Q1,
87+ -- WHEN dummy IS NOT NULL
88+ -- THEN nextval('user_id_seq')
91+ -- We use random() here as the dummy value (and not some constant) because
92+ -- Postgres will again optimize if it sees that a value is constant
93+ -- (and thus only call nextval() once), but because random() is marked as
94+ -- VOLATILE, this inhibits Postgres from doing that optimisation.
96+ -- Why not just reference the a column from the previous query directly
97+ -- instead of adding a dummy value? Basically, even if we extract out all
98+ -- the bindings introduced in a PrimQuery, we can't always be sure which
99+ -- ones refer to constant values, so if we end up laterally referencing a
100+ -- constant value, then all of this would be for nothing.
102+ -- Why not just add the call to the previous subselect directly, like so:
108+ -- nextval('user_id_seq') AS eval,
111+ -- (VALUES ('a'), ('b'), ('c')) Q1(a)) Q1,
112+ -- LATERAL (SELECT eval) Q2(b);
114+ -- That would work in this case. But consider the following Rel8 code:
117+ -- x <- values [lit 'a', lit 'b', lit 'c']
118+ -- y <- values [lit 'd', lit 'e', lit 'f']
119+ -- z <- evaluate $ nextval "user_id_seq"
122+ -- How many calls to nextval should there be? Our Haskell intuition says
123+ -- nine. But that's not what you would get if you used the above
124+ -- technique. The problem is, which VALUES query should the nextval be
125+ -- added to? You can choose one or the other to get three calls to
126+ -- nextval, but you still need to make a superfluous LATERAL references to
127+ -- the other if you want nine calls. So for the above Rel8 code we generate
128+ -- the following SQL:
134+ -- random() AS dummy,
137+ -- (VALUES ('a'), ('b'), ('c')) Q1(a)) Q1,
139+ -- random() AS dummy,
142+ -- (VALUES ('d'), ('e'), ('f')) Q2(b)) Q2,
145+ -- WHEN Q1.dummy IS NOT NULL AND Q2.dummy IS NOT NULL
146+ -- THEN nextval('user_id_seq')
149+ -- This gives nine calls to nextval() as we would expect.
150+ [Opaleye.PrimExpr] -> Opaleye.Select (Any, a)
154+instance Functor Query where
155+ fmap f (Query a) = Query (fmap (fmap (fmap f)) a)
158+instance Apply Query where
162+instance Applicative Query where
163+ pure = fromOpaleye . pure
38instance Bind Query where
167instance Bind Query where
39 (>>-) = (>>=)
168 (>>-) = (>>=)
171+instance Monad Query where
172+ Query q >>= f = Query $ \dummies -> Opaleye.QueryArr $ \(_, query, tag) ->
174+ Opaleye.QueryArr qa = q dummies
175+ ((m, a), query', tag') = qa ((), query, tag)
177+ (dummies', lquery, tag'') =
179+ , Opaleye.Rebind True bindings query'
183+ (dummy, bindings) = Opaleye.run $ name random
185+ random = Opaleye.FunExpr "random" []
186+ name = Opaleye.extractAttr "dummy" tag'
187+ Opaleye.QueryArr qa' = Opaleye.lateral $ \_ -> q' dummies'
188+ ((m'@(Any needsDummies), b), rquery, tag''') = qa' ((), Opaleye.Unit, tag'')
190+ | needsDummies = lquery
191+ | otherwise = query'
192+ query'''' = Opaleye.times lquery' rquery
195+ ((m'', b), query'''', tag''')
42-- | '<|>:' = 'unionAll'.
198-- | '<|>:' = 'unionAll'.
43instance AltTable Query where
199instance AltTable Query where
44 (<|>:) = unionAll
200 (<|>:) = unionAll