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