Skip to content

Commit

Permalink
Wrap rebind in dummy offset 0
Browse files Browse the repository at this point in the history
Somewhere between PostgreSQL 11 and PostgreSQL 15, PostgreSQL's optimiser gained the ability to see "through" subqueries, and it seems to choose to do this even when we don't really want it to.

E.g., it started transforming the following:

```haskell
SELECT
  x * y + x * y
FROM (
  SELECT
    a + b + c AS x
    d + e + f AS y
  FROM
    foo
) _
```

into:

```haskell
SELECT
  (a + b + c) * (d + e + f) + (a + b + c) * (d + e + f)
FROM
  foo
```

before evaluating.

You can see how more complicated expressions nested several levels deep could get expanded into crazy big expressions. This seems to be what PostgreSQL actually does on Rel8 code that uses `rebind`. Compared to older versions of PostgreSQL, this increases the planning time and execution time dramatically.

Given that Rel8's `rebind` is intended to function as a "let binding", and the user needs to go out of their way to choose to use it (they could just use `pure` if they wanted the fully expanded expression), we want a way to force PostgreSQL to evaluate the `a + b + c` and the `d + e + f` first before worrying about trying to simplify `x * y + x * y`. Adding `OFFSET 0` to the inner query seems to achieve that.

```haskell
SELECT
  x * y + x * y
FROM (
  SELECT
    a + b + c AS x
    d + e + f AS y
  FROM
    foo
  OFFSET
    0
) _
```
  • Loading branch information
shane-circuithub committed Oct 29, 2023
1 parent a744f05 commit fc771fa
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Rel8/Query/Rebind.hs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import qualified Opaleye.Internal.Rebind as Opaleye
-- rel8
import Rel8.Expr ( Expr )
import Rel8.Query ( Query )
import Rel8.Query.Limit (offset)
import Rel8.Schema.HTable (HTable)
import Rel8.Table ( Table )
import Rel8.Table.Cols (Cols (Cols))
Expand All @@ -27,7 +28,8 @@ import Rel8.Query.Opaleye (fromOpaleye)
-- to a new variable in the SQL. The @a@ returned consists only of these
-- variables. It's essentially a @let@ binding for Postgres expressions.
rebind :: Table Expr a => String -> a -> Query a
rebind prefix a = fromOpaleye (Opaleye.rebindExplicitPrefix prefix unpackspec <<< pure a)
rebind prefix a = offset 0 $
fromOpaleye (Opaleye.rebindExplicitPrefix prefix unpackspec <<< pure a)


hrebind :: HTable t => String -> t Expr -> Query (t Expr)
Expand Down

0 comments on commit fc771fa

Please sign in to comment.