|
| 1 | +defmodule Ecto.Integration.ValuesTest do |
| 2 | + use Ecto.Integration.Case, async: true |
| 3 | + |
| 4 | + import Ecto.Query, only: [from: 2, with_cte: 3] |
| 5 | + |
| 6 | + alias Ecto.Integration.Comment |
| 7 | + alias Ecto.Integration.Post |
| 8 | + alias Ecto.Integration.TestRepo |
| 9 | + |
| 10 | + test "join to values works" do |
| 11 | + TestRepo.insert!(%Post{id: 1}) |
| 12 | + TestRepo.insert!(%Comment{post_id: 1, text: "short"}) |
| 13 | + TestRepo.insert!(%Comment{post_id: 1, text: "much longer text"}) |
| 14 | + |
| 15 | + params = [%{id: 1, post_id: 1, n: 0}, %{id: 2, post_id: 1, n: 10}] |
| 16 | + types = %{id: :integer, post_id: :integer, n: :integer} |
| 17 | + |
| 18 | + results = |
| 19 | + from(p in Post, |
| 20 | + right_join: params in values(params, types), |
| 21 | + on: params.post_id == p.id, |
| 22 | + left_join: c in Comment, |
| 23 | + on: c.post_id == p.id and fragment("LENGTH(?)", c.text) > params.n, |
| 24 | + group_by: params.id, |
| 25 | + select: {params.id, count(c.id)} |
| 26 | + ) |
| 27 | + |> TestRepo.all() |
| 28 | + |
| 29 | + assert [{1, 2}, {2, 1}] = results |
| 30 | + end |
| 31 | + |
| 32 | + test "values can be used together with CTE" do |
| 33 | + TestRepo.insert!(%Post{id: 1, visits: 42}) |
| 34 | + TestRepo.insert!(%Comment{post_id: 1, text: "short"}) |
| 35 | + TestRepo.insert!(%Comment{post_id: 1, text: "much longer text"}) |
| 36 | + |
| 37 | + params = [%{id: 1, post_id: 1, n: 0}, %{id: 2, post_id: 1, n: 10}] |
| 38 | + types = %{id: :integer, post_id: :integer, n: :integer} |
| 39 | + |
| 40 | + cte_query = from(p in Post, select: %{id: p.id, visits: coalesce(p.visits, 0)}) |
| 41 | + |
| 42 | + q = Post |> with_cte("xxx", as: ^cte_query) |
| 43 | + |
| 44 | + results = |
| 45 | + from(p in q, |
| 46 | + right_join: params in values(params, types), |
| 47 | + on: params.post_id == p.id, |
| 48 | + left_join: c in Comment, |
| 49 | + on: c.post_id == p.id and fragment("LENGTH(?)", c.text) > params.n, |
| 50 | + left_join: cte in "xxx", |
| 51 | + on: cte.id == p.id, |
| 52 | + group_by: params.id, |
| 53 | + select: {params.id, count(c.id), cte.visits} |
| 54 | + ) |
| 55 | + |> TestRepo.all() |
| 56 | + |
| 57 | + assert [{1, 2, 42}, {2, 1, 42}] = results |
| 58 | + end |
| 59 | +end |
0 commit comments