Skip to content

Commit

Permalink
Add subquery selects to cache (#4242)
Browse files Browse the repository at this point in the history
  • Loading branch information
greg-rychlewski authored Jul 24, 2023
1 parent fb73769 commit 1d4a17e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/ecto/query/planner.ex
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,10 @@ defmodule Ecto.Query.Planner do
end

defp expr_to_cache(%QueryExpr{expr: expr}), do: expr
defp expr_to_cache(%SelectExpr{expr: expr}), do: expr
defp expr_to_cache(%SelectExpr{expr: expr, subqueries: []}), do: expr
defp expr_to_cache(%SelectExpr{expr: expr, subqueries: subqueries}) do
{expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)}
end
defp expr_to_cache(%BooleanExpr{op: op, expr: expr, subqueries: []}), do: {op, expr}
defp expr_to_cache(%BooleanExpr{op: op, expr: expr, subqueries: subqueries}) do
# Alternate implementation could be replace {:subquery, i} expression in expr.
Expand Down
29 changes: 29 additions & 0 deletions test/ecto/query/planner_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,35 @@ defmodule Ecto.Query.PlannerTest do
assert deeper_level_union_query.sources == {{"comments", Comment, "global"}}
end

test "plan: cache key for select with subquery" do
subquery = select(Comment, 1)

{_, _, _, key} =
from(Post, as: :post)
|> select([p], %{title: p.title, comment_count: subquery(subquery)})
|> plan()

assert key ==
[
:all,
{:aliases, %{post: 0}},
{:from, {"posts", Ecto.Query.PlannerTest.Post, 111_065_921, "my_prefix"}, []},
{:select,
{{:%{}, [],
[
title: {{:., [], [{:&, [], [0]}, :title]}, [], []},
comment_count: {:subquery, 0}
]},
[
subquery: [
:all,
{:from, {"comments", Ecto.Query.PlannerTest.Comment, 38_292_156, nil}, []},
{:select, 1}
]
]}}
]
end

describe "plan: CTEs" do
test "with uncacheable queries are uncacheable" do
{_, _, _, cache} =
Expand Down

0 comments on commit 1d4a17e

Please sign in to comment.