gokashi commited on
Commit
0d8754d
·
verified ·
1 Parent(s): a554e78

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. deps/ecto/hex_metadata.config +71 -0
  2. deps/ecto/integration_test/cases/assoc.exs +865 -0
  3. deps/ecto/integration_test/cases/interval.exs +419 -0
  4. deps/ecto/integration_test/cases/joins.exs +672 -0
  5. deps/ecto/integration_test/cases/preload.exs +821 -0
  6. deps/ecto/integration_test/cases/repo.exs +2267 -0
  7. deps/ecto/integration_test/cases/type.exs +601 -0
  8. deps/ecto/integration_test/cases/windows.exs +53 -0
  9. deps/ecto/integration_test/support/schemas.exs +423 -0
  10. deps/ecto/integration_test/support/types.exs +53 -0
  11. deps/ecto/lib/ecto.ex +747 -0
  12. deps/ecto/lib/ecto/adapter.ex +142 -0
  13. deps/ecto/lib/ecto/adapter/queryable.ex +127 -0
  14. deps/ecto/lib/ecto/adapter/schema.ex +92 -0
  15. deps/ecto/lib/ecto/adapter/storage.ex +53 -0
  16. deps/ecto/lib/ecto/adapter/transaction.ex +31 -0
  17. deps/ecto/lib/ecto/application.ex +13 -0
  18. deps/ecto/lib/ecto/association.ex +1711 -0
  19. deps/ecto/lib/ecto/changeset.ex +0 -0
  20. deps/ecto/lib/ecto/changeset/relation.ex +584 -0
  21. deps/ecto/lib/ecto/embedded.ex +301 -0
  22. deps/ecto/lib/ecto/enum.ex +341 -0
  23. deps/ecto/lib/ecto/exceptions.ex +321 -0
  24. deps/ecto/lib/ecto/json.ex +48 -0
  25. deps/ecto/lib/ecto/multi.ex +990 -0
  26. deps/ecto/lib/ecto/parameterized_type.ex +213 -0
  27. deps/ecto/lib/ecto/query.ex +0 -0
  28. deps/ecto/lib/ecto/query/api.ex +885 -0
  29. deps/ecto/lib/ecto/query/builder.ex +1542 -0
  30. deps/ecto/lib/ecto/query/builder/combination.ex +36 -0
  31. deps/ecto/lib/ecto/query/builder/cte.ex +121 -0
  32. deps/ecto/lib/ecto/query/builder/distinct.ex +91 -0
  33. deps/ecto/lib/ecto/query/builder/dynamic.ex +112 -0
  34. deps/ecto/lib/ecto/query/builder/filter.ex +196 -0
  35. deps/ecto/lib/ecto/query/builder/from.ex +237 -0
  36. deps/ecto/lib/ecto/query/builder/group_by.ex +118 -0
  37. deps/ecto/lib/ecto/query/builder/join.ex +360 -0
  38. deps/ecto/lib/ecto/query/builder/limit_offset.ex +111 -0
  39. deps/ecto/lib/ecto/query/builder/lock.ex +59 -0
  40. deps/ecto/lib/ecto/query/builder/order_by.ex +255 -0
  41. deps/ecto/lib/ecto/query/builder/preload.ex +322 -0
  42. deps/ecto/lib/ecto/query/builder/select.ex +579 -0
  43. deps/ecto/lib/ecto/query/builder/update.ex +200 -0
  44. deps/ecto/lib/ecto/query/builder/windows.ex +204 -0
  45. deps/ecto/lib/ecto/query/inspect.ex +436 -0
  46. deps/ecto/lib/ecto/query/planner.ex +2699 -0
  47. deps/ecto/lib/ecto/query/window_api.ex +232 -0
  48. deps/ecto/lib/ecto/queryable.ex +150 -0
  49. deps/ecto/lib/ecto/repo.ex +2227 -0
  50. deps/ecto/lib/ecto/repo/assoc.ex +131 -0
deps/ecto/hex_metadata.config ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-ecto/ecto">>}]}.
2
+ {<<"name">>,<<"ecto">>}.
3
+ {<<"version">>,<<"3.12.5">>}.
4
+ {<<"description">>,
5
+ <<"A toolkit for data mapping and language integrated query for Elixir">>}.
6
+ {<<"elixir">>,<<"~> 1.11">>}.
7
+ {<<"app">>,<<"ecto">>}.
8
+ {<<"licenses">>,[<<"Apache-2.0">>]}.
9
+ {<<"files">>,
10
+ [<<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"CHANGELOG.md">>,
11
+ <<"lib">>,<<"lib/ecto">>,<<"lib/ecto/adapter.ex">>,<<"lib/ecto/multi.ex">>,
12
+ <<"lib/ecto/queryable.ex">>,<<"lib/ecto/type.ex">>,
13
+ <<"lib/ecto/changeset.ex">>,<<"lib/ecto/parameterized_type.ex">>,
14
+ <<"lib/ecto/changeset">>,<<"lib/ecto/changeset/relation.ex">>,
15
+ <<"lib/ecto/adapter">>,<<"lib/ecto/adapter/transaction.ex">>,
16
+ <<"lib/ecto/adapter/queryable.ex">>,<<"lib/ecto/adapter/schema.ex">>,
17
+ <<"lib/ecto/adapter/storage.ex">>,<<"lib/ecto/query.ex">>,
18
+ <<"lib/ecto/enum.ex">>,<<"lib/ecto/schema">>,
19
+ <<"lib/ecto/schema/metadata.ex">>,<<"lib/ecto/schema/loader.ex">>,
20
+ <<"lib/ecto/uuid.ex">>,<<"lib/ecto/json.ex">>,<<"lib/ecto/embedded.ex">>,
21
+ <<"lib/ecto/schema.ex">>,<<"lib/ecto/association.ex">>,
22
+ <<"lib/ecto/application.ex">>,<<"lib/ecto/query">>,
23
+ <<"lib/ecto/query/planner.ex">>,<<"lib/ecto/query/window_api.ex">>,
24
+ <<"lib/ecto/query/api.ex">>,<<"lib/ecto/query/inspect.ex">>,
25
+ <<"lib/ecto/query/builder.ex">>,<<"lib/ecto/query/builder">>,
26
+ <<"lib/ecto/query/builder/preload.ex">>,
27
+ <<"lib/ecto/query/builder/group_by.ex">>,
28
+ <<"lib/ecto/query/builder/join.ex">>,<<"lib/ecto/query/builder/update.ex">>,
29
+ <<"lib/ecto/query/builder/distinct.ex">>,
30
+ <<"lib/ecto/query/builder/limit_offset.ex">>,
31
+ <<"lib/ecto/query/builder/select.ex">>,
32
+ <<"lib/ecto/query/builder/windows.ex">>,
33
+ <<"lib/ecto/query/builder/from.ex">>,<<"lib/ecto/query/builder/cte.ex">>,
34
+ <<"lib/ecto/query/builder/combination.ex">>,
35
+ <<"lib/ecto/query/builder/dynamic.ex">>,
36
+ <<"lib/ecto/query/builder/order_by.ex">>,
37
+ <<"lib/ecto/query/builder/lock.ex">>,<<"lib/ecto/query/builder/filter.ex">>,
38
+ <<"lib/ecto/repo.ex">>,<<"lib/ecto/repo">>,
39
+ <<"lib/ecto/repo/transaction.ex">>,<<"lib/ecto/repo/supervisor.ex">>,
40
+ <<"lib/ecto/repo/registry.ex">>,<<"lib/ecto/repo/queryable.ex">>,
41
+ <<"lib/ecto/repo/preloader.ex">>,<<"lib/ecto/repo/schema.ex">>,
42
+ <<"lib/ecto/repo/assoc.ex">>,<<"lib/ecto/exceptions.ex">>,<<"lib/mix">>,
43
+ <<"lib/mix/tasks">>,<<"lib/mix/tasks/ecto.create.ex">>,
44
+ <<"lib/mix/tasks/ecto.ex">>,<<"lib/mix/tasks/ecto.gen.repo.ex">>,
45
+ <<"lib/mix/tasks/ecto.drop.ex">>,<<"lib/mix/ecto.ex">>,<<"lib/ecto.ex">>,
46
+ <<"integration_test/cases">>,<<"integration_test/cases/type.exs">>,
47
+ <<"integration_test/cases/interval.exs">>,
48
+ <<"integration_test/cases/preload.exs">>,
49
+ <<"integration_test/cases/assoc.exs">>,
50
+ <<"integration_test/cases/joins.exs">>,
51
+ <<"integration_test/cases/windows.exs">>,
52
+ <<"integration_test/cases/repo.exs">>,<<"integration_test/support">>,
53
+ <<"integration_test/support/schemas.exs">>,
54
+ <<"integration_test/support/types.exs">>]}.
55
+ {<<"requirements">>,
56
+ [[{<<"name">>,<<"telemetry">>},
57
+ {<<"app">>,<<"telemetry">>},
58
+ {<<"optional">>,false},
59
+ {<<"requirement">>,<<"~> 0.4 or ~> 1.0">>},
60
+ {<<"repository">>,<<"hexpm">>}],
61
+ [{<<"name">>,<<"decimal">>},
62
+ {<<"app">>,<<"decimal">>},
63
+ {<<"optional">>,false},
64
+ {<<"requirement">>,<<"~> 2.0">>},
65
+ {<<"repository">>,<<"hexpm">>}],
66
+ [{<<"name">>,<<"jason">>},
67
+ {<<"app">>,<<"jason">>},
68
+ {<<"optional">>,true},
69
+ {<<"requirement">>,<<"~> 1.0">>},
70
+ {<<"repository">>,<<"hexpm">>}]]}.
71
+ {<<"build_tools">>,[<<"mix">>]}.
deps/ecto/integration_test/cases/assoc.exs ADDED
@@ -0,0 +1,865 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.AssocTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.TestRepo
5
+ import Ecto.Query
6
+
7
+ alias Ecto.Integration.Custom
8
+ alias Ecto.Integration.Post
9
+ alias Ecto.Integration.User
10
+ alias Ecto.Integration.PostUser
11
+ alias Ecto.Integration.Comment
12
+ alias Ecto.Integration.Permalink
13
+
14
+ test "has_many assoc" do
15
+ p1 = TestRepo.insert!(%Post{title: "1"})
16
+ p2 = TestRepo.insert!(%Post{title: "2"})
17
+
18
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
19
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
20
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
21
+
22
+ [c1, c2] = TestRepo.all Ecto.assoc(p1, :comments)
23
+ assert c1.id == cid1
24
+ assert c2.id == cid2
25
+
26
+ [c1, c2, c3] = TestRepo.all Ecto.assoc([p1, p2], :comments)
27
+ assert c1.id == cid1
28
+ assert c2.id == cid2
29
+ assert c3.id == cid3
30
+ end
31
+
32
+ test "has_one assoc" do
33
+ p1 = TestRepo.insert!(%Post{title: "1"})
34
+ p2 = TestRepo.insert!(%Post{title: "2"})
35
+
36
+ %Permalink{id: lid1} = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id})
37
+ %Permalink{} = TestRepo.insert!(%Permalink{url: "2"})
38
+ %Permalink{id: lid3} = TestRepo.insert!(%Permalink{url: "3", post_id: p2.id})
39
+
40
+ [l1, l3] = TestRepo.all Ecto.assoc([p1, p2], :permalink)
41
+ assert l1.id == lid1
42
+ assert l3.id == lid3
43
+ end
44
+
45
+ test "belongs_to assoc" do
46
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
47
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
48
+
49
+ l1 = TestRepo.insert!(%Permalink{url: "1", post_id: pid1})
50
+ l2 = TestRepo.insert!(%Permalink{url: "2"})
51
+ l3 = TestRepo.insert!(%Permalink{url: "3", post_id: pid2})
52
+
53
+ assert [p1, p2] = TestRepo.all Ecto.assoc([l1, l2, l3], :post)
54
+ assert p1.id == pid1
55
+ assert p2.id == pid2
56
+ end
57
+
58
+ test "has_many through assoc" do
59
+ p1 = TestRepo.insert!(%Post{})
60
+ p2 = TestRepo.insert!(%Post{})
61
+
62
+ u1 = TestRepo.insert!(%User{name: "zzz"})
63
+ u2 = TestRepo.insert!(%User{name: "aaa"})
64
+
65
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
66
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
67
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id})
68
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id})
69
+
70
+ query = Ecto.assoc([p1, p2], :comments_authors) |> order_by([a], a.name)
71
+ assert [^u2, ^u1] = TestRepo.all(query)
72
+
73
+ # Dynamic through
74
+ query = Ecto.assoc([p1, p2], [:comments, :author]) |> order_by([a], a.name)
75
+ assert [^u2, ^u1] = TestRepo.all(query)
76
+ end
77
+
78
+ @tag :on_replace_nilify
79
+ test "has_many through-through assoc leading" do
80
+ p1 = TestRepo.insert!(%Post{})
81
+ p2 = TestRepo.insert!(%Post{})
82
+
83
+ u1 = TestRepo.insert!(%User{})
84
+ u2 = TestRepo.insert!(%User{})
85
+
86
+ pl1 = TestRepo.insert!(%Permalink{user_id: u1.id, url: "zzz"})
87
+ pl2 = TestRepo.insert!(%Permalink{user_id: u2.id, url: "aaa"})
88
+
89
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
90
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
91
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id})
92
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id})
93
+
94
+ query = Ecto.assoc([p1, p2], :comments_authors_permalinks) |> order_by([p], p.url)
95
+ assert [^pl2, ^pl1] = TestRepo.all(query)
96
+
97
+ # Dynamic through
98
+ query = Ecto.assoc([p1, p2], [:comments, :author, :permalink]) |> order_by([p], p.url)
99
+ assert [^pl2, ^pl1] = TestRepo.all(query)
100
+ end
101
+
102
+ test "has_many through-through assoc trailing" do
103
+ p1 = TestRepo.insert!(%Post{})
104
+ u1 = TestRepo.insert!(%User{})
105
+ pl1 = TestRepo.insert!(%Permalink{user_id: u1.id, post_id: p1.id})
106
+
107
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
108
+
109
+ query = Ecto.assoc([pl1], :post_comments_authors)
110
+ assert [^u1] = TestRepo.all(query)
111
+
112
+ # Dynamic through
113
+ query = Ecto.assoc([pl1], [:post, :comments, :author])
114
+ assert [^u1] = TestRepo.all(query)
115
+ end
116
+
117
+ test "has_many through has_many, many_to_many and has_many" do
118
+ user1 = %User{id: uid1} = TestRepo.insert!(%User{name: "Gabriel"})
119
+ %User{id: uid2} = TestRepo.insert!(%User{name: "Isadora"})
120
+ %User{id: uid3} = TestRepo.insert!(%User{name: "Joey Mush"})
121
+
122
+ p1 = TestRepo.insert!(%Post{title: "p1", author_id: uid1})
123
+ p2 = TestRepo.insert!(%Post{title: "p2", author_id: uid2})
124
+ p3 = TestRepo.insert!(%Post{title: "p3", author_id: uid2})
125
+ TestRepo.insert!(%Post{title: "p4", author_id: uid3})
126
+
127
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
128
+ [post_id: p1.id, user_id: uid2],
129
+ [post_id: p2.id, user_id: uid3]]
130
+
131
+ [pid1, pid2, pid3] =
132
+ Ecto.assoc(user1, :related_2nd_order_posts)
133
+ |> TestRepo.all()
134
+ |> Enum.map(fn %Post{id: id} -> id end)
135
+ |> Enum.sort()
136
+
137
+ assert p1.id == pid1
138
+ assert p2.id == pid2
139
+ assert p3.id == pid3
140
+ end
141
+
142
+ test "has_many through has_many, belongs_to and a nested has through" do
143
+ user1 = TestRepo.insert!(%User{name: "Gabriel"})
144
+ user2 = TestRepo.insert!(%User{name: "Isadora"})
145
+ user3 = TestRepo.insert!(%User{name: "Joey"})
146
+
147
+ post1 = TestRepo.insert!(%Post{title: "p1"})
148
+ post2 = TestRepo.insert!(%Post{title: "p2"})
149
+
150
+ TestRepo.insert!(%Comment{author_id: user1.id, text: "c1", post_id: post1.id})
151
+ TestRepo.insert!(%Comment{author_id: user2.id, text: "c2", post_id: post1.id})
152
+ TestRepo.insert!(%Comment{author_id: user3.id, text: "c3", post_id: post2.id})
153
+
154
+ [u1_id, u2_id] =
155
+ Ecto.assoc(user1, :co_commenters)
156
+ |> TestRepo.all()
157
+ |> Enum.map(fn %User{id: id} -> id end)
158
+ |> Enum.sort()
159
+
160
+ assert u1_id == user1.id
161
+ assert u2_id == user2.id
162
+ end
163
+
164
+ test "has_many through two many_to_many associations" do
165
+ user1 = %User{id: uid1} = TestRepo.insert!(%User{name: "Gabriel"})
166
+ %User{id: uid2} = TestRepo.insert!(%User{name: "Isadora"})
167
+ %User{id: uid3} = TestRepo.insert!(%User{name: "Joey Mush"})
168
+
169
+ p1 = TestRepo.insert!(%Post{title: "p1", author_id: uid1})
170
+ TestRepo.insert!(%Post{title: "p2", author_id: uid2})
171
+ p3 = TestRepo.insert!(%Post{title: "p3", author_id: uid2})
172
+ p4 = TestRepo.insert!(%Post{title: "p4", author_id: uid3})
173
+
174
+ TestRepo.insert_all "posts_users", [[post_id: p3.id, user_id: uid1],
175
+ [post_id: p3.id, user_id: uid2],
176
+ [post_id: p1.id, user_id: uid3]]
177
+
178
+ TestRepo.insert!(%PostUser{post_id: p1.id, user_id: uid2})
179
+ TestRepo.insert!(%PostUser{post_id: p3.id, user_id: uid1})
180
+ TestRepo.insert!(%PostUser{post_id: p3.id, user_id: uid2})
181
+ TestRepo.insert!(%PostUser{post_id: p4.id, user_id: uid3})
182
+
183
+ [u1, u2] =
184
+ Ecto.assoc(user1, :users_through_schema_posts)
185
+ |> TestRepo.all()
186
+ |> Enum.map(fn %User{id: id} -> id end)
187
+ |> Enum.sort()
188
+
189
+ assert uid1 == u1
190
+ assert uid2 == u2
191
+ end
192
+
193
+ test "has_many through with where" do
194
+ post1 = TestRepo.insert!(%Post{title: "p1"})
195
+ post2 = TestRepo.insert!(%Post{title: "p2"})
196
+ post3 = TestRepo.insert!(%Post{title: "p3"})
197
+
198
+ author = TestRepo.insert!(%User{name: "john"})
199
+
200
+ TestRepo.insert!(%Comment{text: "1", lock_version: 1, post_id: post1.id, author_id: author.id})
201
+ TestRepo.insert!(%Comment{text: "2", lock_version: 2, post_id: post2.id, author_id: author.id})
202
+ TestRepo.insert!(%Comment{text: "3", lock_version: 2, post_id: post3.id, author_id: author.id})
203
+
204
+ [p2, p3] = Ecto.assoc(author, :v2_comments_posts) |> TestRepo.all() |> Enum.sort_by(&(&1.id))
205
+ assert p2.id == post2.id
206
+ assert p3.id == post3.id
207
+ end
208
+
209
+ test "many_to_many assoc" do
210
+ p1 = TestRepo.insert!(%Post{title: "1"})
211
+ p2 = TestRepo.insert!(%Post{title: "2"})
212
+ p3 = TestRepo.insert!(%Post{title: "3"})
213
+
214
+ %User{id: uid1} = TestRepo.insert!(%User{name: "john"})
215
+ %User{id: uid2} = TestRepo.insert!(%User{name: "mary"})
216
+
217
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
218
+ [post_id: p1.id, user_id: uid2],
219
+ [post_id: p2.id, user_id: uid2]]
220
+
221
+ [u1, u2] = TestRepo.all Ecto.assoc([p1], :users)
222
+ assert u1.id == uid1
223
+ assert u2.id == uid2
224
+
225
+ [u2] = TestRepo.all Ecto.assoc([p2], :users)
226
+ assert u2.id == uid2
227
+ [] = TestRepo.all Ecto.assoc([p3], :users)
228
+
229
+ [u1, u2, u2] = TestRepo.all Ecto.assoc([p1, p2, p3], :users)
230
+ assert u1.id == uid1
231
+ assert u2.id == uid2
232
+ end
233
+
234
+ ## Changesets
235
+
236
+ test "has_one changeset assoc (on_replace: :delete)" do
237
+ # Insert new
238
+ changeset =
239
+ %Post{title: "1"}
240
+ |> Ecto.Changeset.change
241
+ |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "1"})
242
+ post = TestRepo.insert!(changeset)
243
+ assert post.permalink.id
244
+ assert post.permalink.post_id == post.id
245
+ assert post.permalink.url == "1"
246
+ post = TestRepo.get!(from(Post, preload: [:permalink]), post.id)
247
+ assert post.permalink.url == "1"
248
+
249
+ # Replace with new
250
+ changeset =
251
+ post
252
+ |> Ecto.Changeset.change
253
+ |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "2"})
254
+ post = TestRepo.update!(changeset)
255
+ assert post.permalink.id
256
+ assert post.permalink.post_id == post.id
257
+ assert post.permalink.url == "2"
258
+ post = TestRepo.get!(from(Post, preload: [:permalink]), post.id)
259
+ assert post.permalink.url == "2"
260
+
261
+ # Replacing with existing
262
+ existing = TestRepo.insert!(%Permalink{url: "3"})
263
+ changeset =
264
+ post
265
+ |> Ecto.Changeset.change
266
+ |> Ecto.Changeset.put_assoc(:permalink, existing)
267
+ post = TestRepo.update!(changeset)
268
+ assert post.permalink.id
269
+ assert post.permalink.post_id == post.id
270
+ assert post.permalink.url == "3"
271
+ post = TestRepo.get!(from(Post, preload: [:permalink]), post.id)
272
+ assert post.permalink.url == "3"
273
+
274
+ # Replacing with nil (on_replace: :delete)
275
+ changeset =
276
+ post
277
+ |> Ecto.Changeset.change
278
+ |> Ecto.Changeset.put_assoc(:permalink, nil)
279
+ post = TestRepo.update!(changeset)
280
+ refute post.permalink
281
+ post = TestRepo.get!(from(Post, preload: [:permalink]), post.id)
282
+ refute post.permalink
283
+
284
+ assert [0] == TestRepo.all(from(p in Permalink, select: count(p.id)))
285
+ end
286
+
287
+ test "has_one changeset assoc (on_replace: :delete_if_exists)" do
288
+ permalink = TestRepo.insert!(%Permalink{url: "1"})
289
+ post = TestRepo.insert!(%Post{title: "1", permalink: permalink, force_permalink: permalink})
290
+ TestRepo.delete!(permalink)
291
+
292
+ assert_raise Ecto.StaleEntryError, fn ->
293
+ post
294
+ |> Ecto.Changeset.change()
295
+ |> Ecto.Changeset.put_assoc(:permalink, nil)
296
+ |> TestRepo.update!()
297
+ end
298
+
299
+ post =
300
+ post
301
+ |> Ecto.Changeset.change()
302
+ |> Ecto.Changeset.put_assoc(:force_permalink, nil)
303
+ |> TestRepo.update!()
304
+
305
+ assert post.force_permalink == nil
306
+ end
307
+
308
+ @tag :on_replace_nilify
309
+ test "has_one changeset assoc (on_replace: :nilify)" do
310
+ # Insert new
311
+ changeset =
312
+ %User{name: "1"}
313
+ |> Ecto.Changeset.change
314
+ |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "1"})
315
+ user = TestRepo.insert!(changeset)
316
+ assert user.permalink.id
317
+ assert user.permalink.user_id == user.id
318
+ assert user.permalink.url == "1"
319
+ user = TestRepo.get!(from(User, preload: [:permalink]), user.id)
320
+ assert user.permalink.url == "1"
321
+
322
+ # Replace with new
323
+ changeset =
324
+ user
325
+ |> Ecto.Changeset.change
326
+ |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "2"})
327
+ user = TestRepo.update!(changeset)
328
+ assert user.permalink.id
329
+ assert user.permalink.user_id == user.id
330
+ assert user.permalink.url == "2"
331
+ user = TestRepo.get!(from(User, preload: [:permalink]), user.id)
332
+ assert user.permalink.url == "2"
333
+
334
+ # Replacing with nil (on_replace: :nilify)
335
+ changeset =
336
+ user
337
+ |> Ecto.Changeset.change
338
+ |> Ecto.Changeset.put_assoc(:permalink, nil)
339
+ user = TestRepo.update!(changeset)
340
+ refute user.permalink
341
+ user = TestRepo.get!(from(User, preload: [:permalink]), user.id)
342
+ refute user.permalink
343
+
344
+ assert [2] == TestRepo.all(from(p in Permalink, select: count(p.id)))
345
+ end
346
+
347
+ @tag :on_replace_update
348
+ test "has_one changeset assoc (on_replace: :update)" do
349
+ # Insert new
350
+ changeset =
351
+ %Post{title: "1"}
352
+ |> Ecto.Changeset.change
353
+ |> Ecto.Changeset.put_assoc(:update_permalink, %Permalink{url: "1"})
354
+ post = TestRepo.insert!(changeset)
355
+ assert post.update_permalink.id
356
+ assert post.update_permalink.post_id == post.id
357
+ assert post.update_permalink.url == "1"
358
+ post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id)
359
+ assert post.update_permalink.url == "1"
360
+
361
+ perma = post.update_permalink
362
+
363
+ # Put on update
364
+ changeset =
365
+ post
366
+ |> Ecto.Changeset.change()
367
+ |> Ecto.Changeset.put_assoc(:update_permalink, %{url: "2"})
368
+ post = TestRepo.update!(changeset)
369
+ assert post.update_permalink.id == perma.id
370
+ assert post.update_permalink.post_id == post.id
371
+ assert post.update_permalink.url == "2"
372
+ post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id)
373
+ assert post.update_permalink.url == "2"
374
+
375
+ # Cast on update
376
+ changeset =
377
+ post
378
+ |> Ecto.Changeset.cast(%{update_permalink: %{url: "3"}}, [])
379
+ |> Ecto.Changeset.cast_assoc(:update_permalink)
380
+ post = TestRepo.update!(changeset)
381
+ assert post.update_permalink.id == perma.id
382
+ assert post.update_permalink.post_id == post.id
383
+ assert post.update_permalink.url == "3"
384
+ post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id)
385
+ assert post.update_permalink.url == "3"
386
+
387
+ # Replace with new struct
388
+ assert_raise RuntimeError, ~r"you are only allowed\sto update the existing entry", fn ->
389
+ post
390
+ |> Ecto.Changeset.change()
391
+ |> Ecto.Changeset.put_assoc(:update_permalink, %Permalink{url: "4"})
392
+ end
393
+
394
+ # Replace with existing struct
395
+ assert_raise RuntimeError, ~r"you are only allowed\sto update the existing entry", fn ->
396
+ post
397
+ |> Ecto.Changeset.change()
398
+ |> Ecto.Changeset.put_assoc(:update_permalink, TestRepo.insert!(%Permalink{url: "5"}))
399
+ end
400
+
401
+ # Replacing with nil (on_replace: :update)
402
+ changeset =
403
+ post
404
+ |> Ecto.Changeset.change
405
+ |> Ecto.Changeset.put_assoc(:update_permalink, nil)
406
+ post = TestRepo.update!(changeset)
407
+ refute post.update_permalink
408
+ post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id)
409
+ refute post.update_permalink
410
+
411
+ assert [2] == TestRepo.all(from(p in Permalink, select: count(p.id)))
412
+ end
413
+
414
+ test "has_many changeset assoc (on_replace: :delete)" do
415
+ c1 = TestRepo.insert! %Comment{text: "1"}
416
+ c2 = %Comment{text: "2"}
417
+
418
+ # Inserting
419
+ changeset =
420
+ %Post{title: "1"}
421
+ |> Ecto.Changeset.change
422
+ |> Ecto.Changeset.put_assoc(:comments, [c2])
423
+ post = TestRepo.insert!(changeset)
424
+ [c2] = post.comments
425
+ assert c2.id
426
+ assert c2.post_id == post.id
427
+ post = TestRepo.get!(from(Post, preload: [:comments]), post.id)
428
+ [c2] = post.comments
429
+ assert c2.text == "2"
430
+
431
+ # Updating
432
+ changeset =
433
+ post
434
+ |> Ecto.Changeset.change
435
+ |> Ecto.Changeset.put_assoc(:comments, [Ecto.Changeset.change(c1, text: "11"),
436
+ Ecto.Changeset.change(c2, text: "22")])
437
+ post = TestRepo.update!(changeset)
438
+ [c1, _c2] = post.comments |> Enum.sort_by(&(&1.id))
439
+ assert c1.id
440
+ assert c1.post_id == post.id
441
+ post = TestRepo.get!(from(Post, preload: [:comments]), post.id)
442
+ [c1, c2] = post.comments |> Enum.sort_by(&(&1.id))
443
+ assert c1.text == "11"
444
+ assert c2.text == "22"
445
+
446
+ # Replacing (on_replace: :delete)
447
+ changeset =
448
+ post
449
+ |> Ecto.Changeset.change
450
+ |> Ecto.Changeset.put_assoc(:comments, [])
451
+ post = TestRepo.update!(changeset)
452
+ assert post.comments == []
453
+ post = TestRepo.get!(from(Post, preload: [:comments]), post.id)
454
+ assert post.comments == []
455
+
456
+ assert [0] == TestRepo.all(from(c in Comment, select: count(c.id)))
457
+ end
458
+
459
+ test "has_many changeset assoc (on_replace: :delete_if_exists)" do
460
+ comment = TestRepo.insert!(%Comment{text: "1"})
461
+ post = TestRepo.insert!(%Post{title: "1", comments: [comment], force_comments: [comment]})
462
+
463
+ TestRepo.delete!(comment)
464
+
465
+ assert_raise Ecto.StaleEntryError, fn ->
466
+ post
467
+ |> Ecto.Changeset.change()
468
+ |> Ecto.Changeset.put_assoc(:comments, [])
469
+ |> TestRepo.update!()
470
+ end
471
+
472
+ post =
473
+ post
474
+ |> Ecto.Changeset.change()
475
+ |> Ecto.Changeset.put_assoc(:force_comments, [])
476
+ |> TestRepo.update!()
477
+
478
+ assert post.force_comments == []
479
+ end
480
+
481
+ test "has_many changeset assoc (on_replace: :nilify)" do
482
+ c1 = TestRepo.insert! %Comment{text: "1"}
483
+ c2 = %Comment{text: "2"}
484
+
485
+ # Inserting
486
+ changeset =
487
+ %User{name: "1"}
488
+ |> Ecto.Changeset.change
489
+ |> Ecto.Changeset.put_assoc(:comments, [c1, c2])
490
+ user = TestRepo.insert!(changeset)
491
+ [c1, c2] = user.comments
492
+ assert c1.id
493
+ assert c1.author_id == user.id
494
+ assert c2.id
495
+ assert c2.author_id == user.id
496
+ user = TestRepo.get!(from(User, preload: [:comments]), user.id)
497
+ [c1, c2] = user.comments
498
+ assert c1.text == "1"
499
+ assert c2.text == "2"
500
+
501
+ # Replacing (on_replace: :nilify)
502
+ changeset =
503
+ user
504
+ |> Ecto.Changeset.change
505
+ |> Ecto.Changeset.put_assoc(:comments, [])
506
+ user = TestRepo.update!(changeset)
507
+ assert user.comments == []
508
+ user = TestRepo.get!(from(User, preload: [:comments]), user.id)
509
+ assert user.comments == []
510
+
511
+ assert [2] == TestRepo.all(from(c in Comment, select: count(c.id)))
512
+ end
513
+
514
+ test "many_to_many changeset assoc" do
515
+ u1 = TestRepo.insert! %User{name: "1"}
516
+ u2 = %User{name: "2"}
517
+
518
+ # Inserting
519
+ changeset =
520
+ %Post{title: "1"}
521
+ |> Ecto.Changeset.change
522
+ |> Ecto.Changeset.put_assoc(:users, [u2])
523
+ post = TestRepo.insert!(changeset)
524
+ [u2] = post.users
525
+ assert u2.id
526
+ post = TestRepo.get!(from(Post, preload: [:users]), post.id)
527
+ [u2] = post.users
528
+ assert u2.name == "2"
529
+
530
+ assert [1] == TestRepo.all(from(j in "posts_users", select: count(j.post_id)))
531
+
532
+ # Updating
533
+ changeset =
534
+ post
535
+ |> Ecto.Changeset.change
536
+ |> Ecto.Changeset.put_assoc(:users, [Ecto.Changeset.change(u1, name: "11"),
537
+ Ecto.Changeset.change(u2, name: "22")])
538
+ post = TestRepo.update!(changeset)
539
+ [u1, _u2] = post.users |> Enum.sort_by(&(&1.id))
540
+ assert u1.id
541
+ post = TestRepo.get!(from(Post, preload: [:users]), post.id)
542
+ [u1, u2] = post.users |> Enum.sort_by(&(&1.id))
543
+ assert u1.name == "11"
544
+ assert u2.name == "22"
545
+
546
+ assert [2] == TestRepo.all(from(j in "posts_users", select: count(j.post_id)))
547
+
548
+ # Replacing (on_replace: :delete)
549
+ changeset =
550
+ post
551
+ |> Ecto.Changeset.change
552
+ |> Ecto.Changeset.put_assoc(:users, [])
553
+ post = TestRepo.update!(changeset)
554
+ assert post.users == []
555
+ post = TestRepo.get!(from(Post, preload: [:users]), post.id)
556
+ assert post.users == []
557
+
558
+ assert [0] == TestRepo.all(from(j in "posts_users", select: count(j.post_id)))
559
+ assert [2] == TestRepo.all(from(c in User, select: count(c.id)))
560
+ end
561
+
562
+ test "many_to_many changeset assoc with schema" do
563
+ p1 = TestRepo.insert! %Post{title: "1"}
564
+ p2 = %Post{title: "2"}
565
+
566
+ # Inserting
567
+ changeset =
568
+ %User{name: "1"}
569
+ |> Ecto.Changeset.change
570
+ |> Ecto.Changeset.put_assoc(:schema_posts, [p2])
571
+ user = TestRepo.insert!(changeset)
572
+ [p2] = user.schema_posts
573
+ assert p2.id
574
+ user = TestRepo.get!(from(User, preload: [:schema_posts]), user.id)
575
+ [p2] = user.schema_posts
576
+ assert p2.title == "2"
577
+
578
+ [up2] = TestRepo.all(PostUser) |> Enum.sort_by(&(&1.id))
579
+ assert up2.post_id == p2.id
580
+ assert up2.user_id == user.id
581
+ assert up2.inserted_at
582
+ assert up2.updated_at
583
+
584
+ # Updating
585
+ changeset =
586
+ user
587
+ |> Ecto.Changeset.change
588
+ |> Ecto.Changeset.put_assoc(:schema_posts, [Ecto.Changeset.change(p1, title: "11"),
589
+ Ecto.Changeset.change(p2, title: "22")])
590
+ user = TestRepo.update!(changeset)
591
+ [p1, _p2] = user.schema_posts |> Enum.sort_by(&(&1.id))
592
+ assert p1.id
593
+ user = TestRepo.get!(from(User, preload: [:schema_posts]), user.id)
594
+ [p1, p2] = user.schema_posts |> Enum.sort_by(&(&1.id))
595
+ assert p1.title == "11"
596
+ assert p2.title == "22"
597
+
598
+ [_up2, up1] = TestRepo.all(PostUser) |> Enum.sort_by(&(&1.id))
599
+ assert up1.post_id == p1.id
600
+ assert up1.user_id == user.id
601
+ assert up1.inserted_at
602
+ assert up1.updated_at
603
+ end
604
+
605
+ test "many_to_many changeset assoc with self-referential binary_id" do
606
+ assoc_custom = TestRepo.insert!(%Custom{uuid: Ecto.UUID.generate()})
607
+ custom = TestRepo.insert!(%Custom{customs: [assoc_custom]})
608
+
609
+ custom = Custom |> TestRepo.get!(custom.bid) |> TestRepo.preload(:customs)
610
+ assert [_] = custom.customs
611
+
612
+ custom =
613
+ custom
614
+ |> Ecto.Changeset.change(%{})
615
+ |> Ecto.Changeset.put_assoc(:customs, [])
616
+ |> TestRepo.update!
617
+ assert [] = custom.customs
618
+
619
+ custom = Custom |> TestRepo.get!(custom.bid) |> TestRepo.preload(:customs)
620
+ assert [] = custom.customs
621
+ end
622
+
623
+ @tag :unique_constraint
624
+ test "has_many changeset assoc with constraints" do
625
+ author = TestRepo.insert!(%User{name: "john doe"})
626
+ p1 = TestRepo.insert!(%Post{title: "hello", author_id: author.id})
627
+ TestRepo.insert!(%Post{title: "world", author_id: author.id})
628
+
629
+ # Asserts that `unique_constraint` for `uuid` exists
630
+ assert_raise Ecto.ConstraintError, fn ->
631
+ TestRepo.insert!(%Post{title: "another", author_id: author.id, uuid: p1.uuid})
632
+ end
633
+
634
+ author = TestRepo.preload author, [:posts]
635
+ posts_params = Enum.map author.posts, fn %Post{uuid: u} ->
636
+ %{uuid: u, title: "fresh"}
637
+ end
638
+
639
+ # This will only work if we delete before performing inserts
640
+ changeset =
641
+ author
642
+ |> Ecto.Changeset.cast(%{"posts" => posts_params}, ~w())
643
+ |> Ecto.Changeset.cast_assoc(:posts)
644
+ author = TestRepo.update! changeset
645
+ assert Enum.map(author.posts, &(&1.title)) == ["fresh", "fresh"]
646
+ end
647
+
648
+ test "belongs_to changeset assoc" do
649
+ # Insert new
650
+ changeset =
651
+ %Permalink{url: "1"}
652
+ |> Ecto.Changeset.change
653
+ |> Ecto.Changeset.put_assoc(:post, %Post{title: "1"})
654
+ perma = TestRepo.insert!(changeset)
655
+ post = perma.post
656
+ assert perma.post_id
657
+ assert perma.post_id == post.id
658
+ assert perma.post.title == "1"
659
+
660
+ # Replace with new
661
+ changeset =
662
+ perma
663
+ |> Ecto.Changeset.change
664
+ |> Ecto.Changeset.put_assoc(:post, %Post{title: "2"})
665
+ perma = TestRepo.update!(changeset)
666
+ assert perma.post.id != post.id
667
+ post = perma.post
668
+ assert perma.post_id
669
+ assert perma.post_id == post.id
670
+ assert perma.post.title == "2"
671
+
672
+ # Replace with existing
673
+ existing = TestRepo.insert!(%Post{title: "3"})
674
+ changeset =
675
+ perma
676
+ |> Ecto.Changeset.change
677
+ |> Ecto.Changeset.put_assoc(:post, existing)
678
+ perma = TestRepo.update!(changeset)
679
+ post = perma.post
680
+ assert perma.post_id == post.id
681
+ assert perma.post_id == existing.id
682
+ assert perma.post.title == "3"
683
+
684
+ # Replace with nil
685
+ changeset =
686
+ perma
687
+ |> Ecto.Changeset.change
688
+ |> Ecto.Changeset.put_assoc(:post, nil)
689
+ perma = TestRepo.update!(changeset)
690
+ assert perma.post == nil
691
+ assert perma.post_id == nil
692
+ end
693
+
694
+ test "belongs_to changeset assoc (on_replace: :update)" do
695
+ # Insert new
696
+ changeset =
697
+ %Permalink{url: "1"}
698
+ |> Ecto.Changeset.change
699
+ |> Ecto.Changeset.put_assoc(:update_post, %Post{title: "1"})
700
+ perma = TestRepo.insert!(changeset)
701
+ post = perma.update_post
702
+ assert perma.post_id
703
+ assert perma.post_id == post.id
704
+ assert perma.update_post.title == "1"
705
+
706
+ # Casting on update
707
+ changeset =
708
+ perma
709
+ |> Ecto.Changeset.cast(%{update_post: %{title: "2"}}, [])
710
+ |> Ecto.Changeset.cast_assoc(:update_post)
711
+ perma = TestRepo.update!(changeset)
712
+ assert perma.update_post.id == post.id
713
+ post = perma.update_post
714
+ assert perma.post_id
715
+ assert perma.post_id == post.id
716
+ assert perma.update_post.title == "2"
717
+
718
+ # Replace with nil
719
+ changeset =
720
+ perma
721
+ |> Ecto.Changeset.change
722
+ |> Ecto.Changeset.put_assoc(:update_post, nil)
723
+ perma = TestRepo.update!(changeset)
724
+ assert perma.update_post == nil
725
+ assert perma.post_id == nil
726
+ end
727
+
728
+ test "inserting struct with associations" do
729
+ tree = %Permalink{
730
+ url: "root",
731
+ post: %Post{
732
+ title: "belongs_to",
733
+ comments: [
734
+ %Comment{text: "child 1"},
735
+ %Comment{text: "child 2"},
736
+ ]
737
+ }
738
+ }
739
+
740
+ tree = TestRepo.insert!(tree)
741
+ assert tree.id
742
+ assert tree.post.id
743
+ assert length(tree.post.comments) == 2
744
+ assert Enum.all?(tree.post.comments, & &1.id)
745
+
746
+ tree = TestRepo.get!(from(Permalink, preload: [post: :comments]), tree.id)
747
+ assert tree.id
748
+ assert tree.post.id
749
+ assert length(tree.post.comments) == 2
750
+ assert Enum.all?(tree.post.comments, & &1.id)
751
+ end
752
+
753
+ test "inserting struct with empty associations" do
754
+ permalink = TestRepo.insert!(%Permalink{url: "root", post: nil})
755
+ assert permalink.post == nil
756
+
757
+ post = TestRepo.insert!(%Post{title: "empty", comments: []})
758
+ assert post.comments == []
759
+ end
760
+
761
+ test "inserting changeset with empty cast associations" do
762
+ changeset =
763
+ %Permalink{}
764
+ |> Ecto.Changeset.cast(%{url: "root", post: nil}, [:url])
765
+ |> Ecto.Changeset.cast_assoc(:post)
766
+ permalink = TestRepo.insert!(changeset)
767
+ assert permalink.post == nil
768
+
769
+ changeset =
770
+ %Post{}
771
+ |> Ecto.Changeset.cast(%{title: "root", comments: []}, [:title])
772
+ |> Ecto.Changeset.cast_assoc(:comments)
773
+ post = TestRepo.insert!(changeset)
774
+ assert post.comments == []
775
+ end
776
+
777
+ test "inserting changeset with empty put associations" do
778
+ changeset =
779
+ %Permalink{}
780
+ |> Ecto.Changeset.change()
781
+ |> Ecto.Changeset.put_assoc(:post, nil)
782
+ permalink = TestRepo.insert!(changeset)
783
+ assert permalink.post == nil
784
+
785
+ changeset =
786
+ %Post{}
787
+ |> Ecto.Changeset.change()
788
+ |> Ecto.Changeset.put_assoc(:comments, [])
789
+ post = TestRepo.insert!(changeset)
790
+ assert post.comments == []
791
+ end
792
+
793
+ test "updating changeset with empty cast associations" do
794
+ post = TestRepo.insert!(%Post{})
795
+ c1 = TestRepo.insert!(%Comment{post_id: post.id})
796
+ c2 = TestRepo.insert!(%Comment{post_id: post.id})
797
+
798
+ assert TestRepo.all(Comment) == [c1, c2]
799
+
800
+ post = TestRepo.get!(from(Post, preload: [:comments]), post.id)
801
+
802
+ post
803
+ |> Ecto.Changeset.change
804
+ |> Ecto.Changeset.put_assoc(:comments, [])
805
+ |> TestRepo.update!()
806
+
807
+ assert TestRepo.all(Comment) == []
808
+ end
809
+
810
+ ## Dependent
811
+
812
+ test "has_many assoc on delete deletes all" do
813
+ post = TestRepo.insert!(%Post{})
814
+ TestRepo.insert!(%Comment{post_id: post.id})
815
+ TestRepo.insert!(%Comment{post_id: post.id})
816
+ TestRepo.delete!(post)
817
+
818
+ assert TestRepo.all(Comment) == []
819
+ refute Process.get(Comment)
820
+ end
821
+
822
+ test "has_many assoc on delete nilifies all" do
823
+ user = TestRepo.insert!(%User{})
824
+ TestRepo.insert!(%Comment{author_id: user.id})
825
+ TestRepo.insert!(%Comment{author_id: user.id})
826
+ TestRepo.delete!(user)
827
+
828
+ author_ids = Comment |> TestRepo.all() |> Enum.map(fn(comment) -> comment.author_id end)
829
+
830
+ assert author_ids == [nil, nil]
831
+ refute Process.get(Comment)
832
+ end
833
+
834
+ test "has_many assoc on delete does nothing" do
835
+ user = TestRepo.insert!(%User{})
836
+ TestRepo.insert!(%Post{author_id: user.id})
837
+
838
+ TestRepo.delete!(user)
839
+ assert Enum.count(TestRepo.all(Post)) == 1
840
+ end
841
+
842
+ test "many_to_many assoc on delete deletes all" do
843
+ p1 = TestRepo.insert!(%Post{title: "1", visits: 1})
844
+ p2 = TestRepo.insert!(%Post{title: "2", visits: 2})
845
+
846
+ u1 = TestRepo.insert!(%User{name: "john"})
847
+ u2 = TestRepo.insert!(%User{name: "mary"})
848
+
849
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: u1.id],
850
+ [post_id: p1.id, user_id: u1.id],
851
+ [post_id: p2.id, user_id: u2.id]]
852
+ TestRepo.delete!(p1)
853
+
854
+ [pid2] = TestRepo.all from(p in Post, select: p.id)
855
+ assert pid2 == p2.id
856
+
857
+ [[pid2, uid2]] = TestRepo.all from(j in "posts_users", select: [j.post_id, j.user_id])
858
+ assert pid2 == p2.id
859
+ assert uid2 == u2.id
860
+
861
+ [uid1, uid2] = TestRepo.all from(u in User, select: u.id)
862
+ assert uid1 == u1.id
863
+ assert uid2 == u2.id
864
+ end
865
+ end
deps/ecto/integration_test/cases/interval.exs ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.IntervalTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.{Post, User, Usec}
5
+ alias Ecto.Integration.TestRepo
6
+ import Ecto.Query
7
+
8
+ @posted ~D[2014-01-01]
9
+ @inserted_at ~N[2014-01-01 02:00:00]
10
+
11
+ setup do
12
+ TestRepo.insert!(%Post{posted: @posted, inserted_at: @inserted_at})
13
+ :ok
14
+ end
15
+
16
+ test "date_add with year" do
17
+ dec = Decimal.new(1)
18
+ assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 1, "year"))
19
+ assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 1.0, "year"))
20
+ assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^1, "year"))
21
+ assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^1.0, "year"))
22
+ assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "year"))
23
+ end
24
+
25
+ test "date_add with month" do
26
+ dec = Decimal.new(3)
27
+ assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3, "month"))
28
+ assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3.0, "month"))
29
+ assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3, "month"))
30
+ assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3.0, "month"))
31
+ assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "month"))
32
+ end
33
+
34
+ test "date_add with week" do
35
+ dec = Decimal.new(3)
36
+ assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3, "week"))
37
+ assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3.0, "week"))
38
+ assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3, "week"))
39
+ assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3.0, "week"))
40
+ assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "week"))
41
+ end
42
+
43
+ test "date_add with day" do
44
+ dec = Decimal.new(5)
45
+ assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, 5, "day"))
46
+ assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, 5.0, "day"))
47
+ assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^5, "day"))
48
+ assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^5.0, "day"))
49
+ assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "day"))
50
+ end
51
+
52
+ test "date_add with hour" do
53
+ dec = Decimal.new(48)
54
+ assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, 48, "hour"))
55
+ assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, 48.0, "hour"))
56
+ assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^48, "hour"))
57
+ assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^48.0, "hour"))
58
+ assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "hour"))
59
+ end
60
+
61
+ test "date_add with dynamic" do
62
+ posted = @posted
63
+ assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(^posted, ^1, ^"year"))
64
+ assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(^posted, ^3, ^"month"))
65
+ assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(^posted, ^3, ^"week"))
66
+ assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(^posted, ^5, ^"day"))
67
+ assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(^posted, ^48, ^"hour"))
68
+ end
69
+
70
+ test "date_add with negative interval" do
71
+ dec = Decimal.new(-1)
72
+ assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, -1, "year"))
73
+ assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, -1.0, "year"))
74
+ assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^-1, "year"))
75
+ assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^-1.0, "year"))
76
+ assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "year"))
77
+ end
78
+
79
+ test "datetime_add with year" do
80
+ dec = Decimal.new(1)
81
+ assert [~N[2015-01-01 02:00:00]] =
82
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1, "year"))
83
+ assert [~N[2015-01-01 02:00:00]] =
84
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1.0, "year"))
85
+ assert [~N[2015-01-01 02:00:00]] =
86
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1, "year"))
87
+ assert [~N[2015-01-01 02:00:00]] =
88
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1.0, "year"))
89
+ assert [~N[2015-01-01 02:00:00]] =
90
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "year"))
91
+ end
92
+
93
+ test "datetime_add with month" do
94
+ dec = Decimal.new(3)
95
+ assert [~N[2014-04-01 02:00:00]] =
96
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3, "month"))
97
+ assert [~N[2014-04-01 02:00:00]] =
98
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3.0, "month"))
99
+ assert [~N[2014-04-01 02:00:00]] =
100
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3, "month"))
101
+ assert [~N[2014-04-01 02:00:00]] =
102
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3.0, "month"))
103
+ assert [~N[2014-04-01 02:00:00]] =
104
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "month"))
105
+ end
106
+
107
+ test "datetime_add with week" do
108
+ dec = Decimal.new(3)
109
+ assert [~N[2014-01-22 02:00:00]] =
110
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3, "week"))
111
+ assert [~N[2014-01-22 02:00:00]] =
112
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3.0, "week"))
113
+ assert [~N[2014-01-22 02:00:00]] =
114
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3, "week"))
115
+ assert [~N[2014-01-22 02:00:00]] =
116
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3.0, "week"))
117
+ assert [~N[2014-01-22 02:00:00]] =
118
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "week"))
119
+ end
120
+
121
+ test "datetime_add with day" do
122
+ dec = Decimal.new(5)
123
+ assert [~N[2014-01-06 02:00:00]] =
124
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 5, "day"))
125
+ assert [~N[2014-01-06 02:00:00]] =
126
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 5.0, "day"))
127
+ assert [~N[2014-01-06 02:00:00]] =
128
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^5, "day"))
129
+ assert [~N[2014-01-06 02:00:00]] =
130
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^5.0, "day"))
131
+ assert [~N[2014-01-06 02:00:00]] =
132
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "day"))
133
+ end
134
+
135
+ test "datetime_add with hour" do
136
+ dec = Decimal.new(60)
137
+ assert [~N[2014-01-03 14:00:00]] =
138
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 60, "hour"))
139
+ assert [~N[2014-01-03 14:00:00]] =
140
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 60.0, "hour"))
141
+ assert [~N[2014-01-03 14:00:00]] =
142
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^60, "hour"))
143
+ assert [~N[2014-01-03 14:00:00]] =
144
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^60.0, "hour"))
145
+ assert [~N[2014-01-03 14:00:00]] =
146
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "hour"))
147
+ end
148
+
149
+ test "datetime_add with minute" do
150
+ dec = Decimal.new(90)
151
+ assert [~N[2014-01-01 03:30:00]] =
152
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90, "minute"))
153
+ assert [~N[2014-01-01 03:30:00]] =
154
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90.0, "minute"))
155
+ assert [~N[2014-01-01 03:30:00]] =
156
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90, "minute"))
157
+ assert [~N[2014-01-01 03:30:00]] =
158
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90.0, "minute"))
159
+ assert [~N[2014-01-01 03:30:00]] =
160
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "minute"))
161
+ end
162
+
163
+ test "datetime_add with second" do
164
+ dec = Decimal.new(90)
165
+ assert [~N[2014-01-01 02:01:30]] =
166
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90, "second"))
167
+ assert [~N[2014-01-01 02:01:30]] =
168
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90.0, "second"))
169
+ assert [~N[2014-01-01 02:01:30]] =
170
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90, "second"))
171
+ assert [~N[2014-01-01 02:01:30]] =
172
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90.0, "second"))
173
+ assert [~N[2014-01-01 02:01:30]] =
174
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "second"))
175
+ end
176
+
177
+ @tag :uses_msec
178
+ test "datetime_add with millisecond" do
179
+ dec = Decimal.new(1500)
180
+ assert [~N[2014-01-01 02:00:01]] =
181
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500, "millisecond"))
182
+ assert [~N[2014-01-01 02:00:01]] =
183
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500.0, "millisecond"))
184
+ assert [~N[2014-01-01 02:00:01]] =
185
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500, "millisecond"))
186
+ assert [~N[2014-01-01 02:00:01]] =
187
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500.0, "millisecond"))
188
+ assert [~N[2014-01-01 02:00:01]] =
189
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "millisecond"))
190
+ end
191
+
192
+ @tag :microsecond_precision
193
+ @tag :uses_usec
194
+ test "datetime_add with microsecond" do
195
+ dec = Decimal.new(1500)
196
+ assert [~N[2014-01-01 02:00:00]] =
197
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500, "microsecond"))
198
+ assert [~N[2014-01-01 02:00:00]] =
199
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500.0, "microsecond"))
200
+ assert [~N[2014-01-01 02:00:00]] =
201
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500, "microsecond"))
202
+ assert [~N[2014-01-01 02:00:00]] =
203
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500.0, "microsecond"))
204
+ assert [~N[2014-01-01 02:00:00]] =
205
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "microsecond"))
206
+ end
207
+
208
+ test "datetime_add with dynamic" do
209
+ inserted_at = @inserted_at
210
+ assert [~N[2015-01-01 02:00:00]] =
211
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^1, ^"year"))
212
+ assert [~N[2014-04-01 02:00:00]] =
213
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^3, ^"month"))
214
+ assert [~N[2014-01-22 02:00:00]] =
215
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^3, ^"week"))
216
+ assert [~N[2014-01-06 02:00:00]] =
217
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^5, ^"day"))
218
+ assert [~N[2014-01-03 14:00:00]] =
219
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^60, ^"hour"))
220
+ assert [~N[2014-01-01 03:30:00]] =
221
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^90, ^"minute"))
222
+ assert [~N[2014-01-01 02:01:30]] =
223
+ TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^90, ^"second"))
224
+ end
225
+
226
+ test "datetime_add with dynamic in filters" do
227
+ inserted_at = @inserted_at
228
+ field = :inserted_at
229
+ assert [_] =
230
+ TestRepo.all(from p in Post, where: p.inserted_at > datetime_add(^inserted_at, ^-1, "year"))
231
+ assert [_] =
232
+ TestRepo.all(from p in Post, where: p.inserted_at > datetime_add(^inserted_at, -3, "month"))
233
+ assert [_] =
234
+ TestRepo.all(from p in Post, where: field(p, ^field) > datetime_add(^inserted_at, ^-3, ^"week"))
235
+ assert [_] =
236
+ TestRepo.all(from p in Post, where: field(p, ^field) > datetime_add(^inserted_at, -5, ^"day"))
237
+ end
238
+
239
+ test "datetime_add with negative interval" do
240
+ dec = Decimal.new(-1)
241
+ assert [~N[2013-01-01 02:00:00]] =
242
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, -1, "year"))
243
+ assert [~N[2013-01-01 02:00:00]] =
244
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, -1.0, "year"))
245
+ assert [~N[2013-01-01 02:00:00]] =
246
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^-1, "year"))
247
+ assert [~N[2013-01-01 02:00:00]] =
248
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^-1.0, "year"))
249
+ assert [~N[2013-01-01 02:00:00]] =
250
+ TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "year"))
251
+ end
252
+
253
+ test "from_now" do
254
+ current = DateTime.utc_now().year
255
+ dec = Decimal.new(5)
256
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(5, "year"))
257
+ assert year > current
258
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(5.0, "year"))
259
+ assert year > current
260
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(^5, "year"))
261
+ assert year > current
262
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(^5.0, "year"))
263
+ assert year > current
264
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(^dec, "year"))
265
+ assert year > current
266
+ end
267
+
268
+ test "ago" do
269
+ current = DateTime.utc_now().year
270
+ dec = Decimal.new(5)
271
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(5, "year"))
272
+ assert year < current
273
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(5.0, "year"))
274
+ assert year < current
275
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(^5, "year"))
276
+ assert year < current
277
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(^5.0, "year"))
278
+ assert year < current
279
+ assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(^dec, "year"))
280
+ assert year < current
281
+ end
282
+
283
+ test "datetime_add with utc_datetime" do
284
+ {:ok, datetime} = DateTime.from_naive(@inserted_at, "Etc/UTC")
285
+ TestRepo.insert!(%User{inserted_at: datetime})
286
+
287
+ {:ok, datetime} = DateTime.from_naive(~N[2015-01-01 02:00:00], "Etc/UTC")
288
+ dec = Decimal.new(1)
289
+
290
+ assert [^datetime] =
291
+ TestRepo.all(from p in User, select: datetime_add(type(^datetime, :utc_datetime), 0, "year"))
292
+ assert [^datetime] =
293
+ TestRepo.all(from p in User, select: datetime_add(p.inserted_at, 1, "year"))
294
+ assert [^datetime] =
295
+ TestRepo.all(from p in User, select: datetime_add(p.inserted_at, 1.0, "year"))
296
+ assert [^datetime] =
297
+ TestRepo.all(from p in User, select: datetime_add(p.inserted_at, ^1, "year"))
298
+ assert [^datetime] =
299
+ TestRepo.all(from p in User, select: datetime_add(p.inserted_at, ^1.0, "year"))
300
+ assert [^datetime] =
301
+ TestRepo.all(from p in User, select: datetime_add(p.inserted_at, ^dec, "year"))
302
+ end
303
+
304
+ @tag :microsecond_precision
305
+ test "datetime_add with naive_datetime_usec" do
306
+ TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.000001]})
307
+ datetime = ~N[2014-01-01 02:00:00.001501]
308
+
309
+ assert [^datetime] =
310
+ TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :naive_datetime_usec), 0, "microsecond"))
311
+ assert [^datetime] =
312
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 1500, "microsecond"))
313
+ assert [^datetime] =
314
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 1500.0, "microsecond"))
315
+ assert [^datetime] =
316
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^1500, "microsecond"))
317
+ end
318
+
319
+ @tag :microsecond_precision
320
+ @tag :decimal_precision
321
+ test "datetime_add with naive_datetime_usec and decimal increment" do
322
+ TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.000001]})
323
+ dec = Decimal.new(1500)
324
+ datetime = ~N[2014-01-01 02:00:00.001501]
325
+
326
+ assert [^datetime] =
327
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^1500.0, "microsecond"))
328
+ assert [^datetime] =
329
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^dec, "microsecond"))
330
+ end
331
+
332
+ @tag :microsecond_precision
333
+ test "datetime_add with utc_datetime_usec" do
334
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.000001], "Etc/UTC")
335
+ TestRepo.insert!(%Usec{utc_datetime_usec: datetime})
336
+
337
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001501], "Etc/UTC")
338
+
339
+ assert [^datetime] =
340
+ TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :utc_datetime_usec), 0, "microsecond"))
341
+ assert [^datetime] =
342
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 1500, "microsecond"))
343
+ assert [^datetime] =
344
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 1500.0, "microsecond"))
345
+ assert [^datetime] =
346
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^1500, "microsecond"))
347
+ end
348
+
349
+ @tag :microsecond_precision
350
+ @tag :decimal_precision
351
+ test "datetime_add uses utc_datetime_usec with decimal increment" do
352
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.000001], "Etc/UTC")
353
+ TestRepo.insert!(%Usec{utc_datetime_usec: datetime})
354
+
355
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001501], "Etc/UTC")
356
+ dec = Decimal.new(1500)
357
+
358
+ assert [^datetime] =
359
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^1500.0, "microsecond"))
360
+ assert [^datetime] =
361
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^dec, "microsecond"))
362
+ end
363
+
364
+ test "datetime_add with utc_datetime_usec in milliseconds" do
365
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001000], "Etc/UTC")
366
+ TestRepo.insert!(%Usec{utc_datetime_usec: datetime})
367
+
368
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.151000], "Etc/UTC")
369
+
370
+ assert [^datetime] =
371
+ TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :utc_datetime_usec), 0, "millisecond"))
372
+ assert [^datetime] =
373
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 150, "millisecond"))
374
+ assert [^datetime] =
375
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 150, "millisecond"))
376
+ assert [^datetime] =
377
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^150, "millisecond"))
378
+ end
379
+
380
+ @tag :decimal_precision
381
+ test "datetime_add uses utc_datetime_usec with decimal increment in milliseconds" do
382
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001000], "Etc/UTC")
383
+ TestRepo.insert!(%Usec{utc_datetime_usec: datetime})
384
+
385
+ {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.151000], "Etc/UTC")
386
+ dec = Decimal.new(150)
387
+
388
+ assert [^datetime] =
389
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^150.0, "millisecond"))
390
+ assert [^datetime] =
391
+ TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^dec, "millisecond"))
392
+ end
393
+
394
+ test "datetime_add with naive_datetime_usec in milliseconds" do
395
+ TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.001000]})
396
+ datetime = ~N[2014-01-01 02:00:00.151000]
397
+
398
+ assert [^datetime] =
399
+ TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :naive_datetime_usec), 0, "millisecond"))
400
+ assert [^datetime] =
401
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 150, "millisecond"))
402
+ assert [^datetime] =
403
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 150.0, "millisecond"))
404
+ assert [^datetime] =
405
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^150, "millisecond"))
406
+ end
407
+
408
+ @tag :decimal_precision
409
+ test "datetime_add with naive_datetime_usec and decimal increment in milliseconds" do
410
+ TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.001000]})
411
+ dec = Decimal.new(150)
412
+ datetime = ~N[2014-01-01 02:00:00.151000]
413
+
414
+ assert [^datetime] =
415
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^150.0, "millisecond"))
416
+ assert [^datetime] =
417
+ TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^dec, "millisecond"))
418
+ end
419
+ end
deps/ecto/integration_test/cases/joins.exs ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.JoinsTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.TestRepo
5
+ import Ecto.Query
6
+
7
+ alias Ecto.Integration.Post
8
+ alias Ecto.Integration.Comment
9
+ alias Ecto.Integration.Permalink
10
+ alias Ecto.Integration.User
11
+ alias Ecto.Integration.PostUserCompositePk
12
+
13
+ @tag :update_with_join
14
+ test "update all with joins" do
15
+ user = TestRepo.insert!(%User{name: "Tester"})
16
+ post = TestRepo.insert!(%Post{title: "foo"})
17
+ comment = TestRepo.insert!(%Comment{text: "hey", author_id: user.id, post_id: post.id})
18
+
19
+ another_post = TestRepo.insert!(%Post{title: "bar"})
20
+ another_comment = TestRepo.insert!(%Comment{text: "another", author_id: user.id, post_id: another_post.id})
21
+
22
+ query = from(c in Comment, join: u in User, on: u.id == c.author_id,
23
+ where: c.post_id in ^[post.id])
24
+
25
+ assert {1, nil} = TestRepo.update_all(query, set: [text: "hoo"])
26
+ assert %Comment{text: "hoo"} = TestRepo.get(Comment, comment.id)
27
+ assert %Comment{text: "another"} = TestRepo.get(Comment, another_comment.id)
28
+ end
29
+
30
+ @tag :delete_with_join
31
+ test "delete all with joins" do
32
+ user = TestRepo.insert!(%User{name: "Tester"})
33
+ post = TestRepo.insert!(%Post{title: "foo"})
34
+ TestRepo.insert!(%Comment{text: "hey", author_id: user.id, post_id: post.id})
35
+ TestRepo.insert!(%Comment{text: "foo", author_id: user.id, post_id: post.id})
36
+ TestRepo.insert!(%Comment{text: "bar", author_id: user.id})
37
+
38
+ query = from(c in Comment, join: u in User, on: u.id == c.author_id,
39
+ where: is_nil(c.post_id))
40
+ assert {1, nil} = TestRepo.delete_all(query)
41
+ assert [%Comment{}, %Comment{}] = TestRepo.all(Comment)
42
+
43
+ query = from(c in Comment, join: u in assoc(c, :author),
44
+ join: p in assoc(c, :post),
45
+ where: p.id in ^[post.id])
46
+ assert {2, nil} = TestRepo.delete_all(query)
47
+ assert [] = TestRepo.all(Comment)
48
+ end
49
+
50
+ test "joins" do
51
+ _p = TestRepo.insert!(%Post{title: "1"})
52
+ p2 = TestRepo.insert!(%Post{title: "2"})
53
+ c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id})
54
+
55
+ query = from(p in Post, join: c in assoc(p, :permalink), order_by: p.id, select: {p, c})
56
+ assert [{^p2, ^c1}] = TestRepo.all(query)
57
+
58
+ query = from(p in Post, join: c in assoc(p, :permalink), on: c.id == ^c1.id, select: {p, c})
59
+ assert [{^p2, ^c1}] = TestRepo.all(query)
60
+ end
61
+
62
+ test "joins with queries" do
63
+ p1 = TestRepo.insert!(%Post{title: "1"})
64
+ p2 = TestRepo.insert!(%Post{title: "2"})
65
+ c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id})
66
+
67
+ # Joined query without parameter
68
+ permalink = from c in Permalink, where: c.url == "1"
69
+
70
+ query = from(p in Post, join: c in ^permalink, on: c.post_id == p.id, select: {p, c})
71
+ assert [{^p2, ^c1}] = TestRepo.all(query)
72
+
73
+ # Joined query with parameter
74
+ permalink = from c in Permalink, where: c.url == "1"
75
+
76
+ query = from(p in Post, join: c in ^permalink, on: c.id == ^c1.id, order_by: p.title, select: {p, c})
77
+ assert [{^p1, ^c1}, {^p2, ^c1}] = TestRepo.all(query)
78
+ end
79
+
80
+ test "named joins" do
81
+ _p = TestRepo.insert!(%Post{title: "1"})
82
+ p2 = TestRepo.insert!(%Post{title: "2"})
83
+ c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id})
84
+
85
+ query =
86
+ from(p in Post, join: c in assoc(p, :permalink), as: :permalink, order_by: p.id)
87
+ |> select([p, permalink: c], {p, c})
88
+
89
+ assert [{^p2, ^c1}] = TestRepo.all(query)
90
+ end
91
+
92
+ test "joins with dynamic in :on" do
93
+ p = TestRepo.insert!(%Post{title: "1"})
94
+ c = TestRepo.insert!(%Permalink{url: "1", post_id: p.id})
95
+
96
+ join_on = dynamic([p, ..., c], c.id == ^c.id)
97
+
98
+ query =
99
+ from(p in Post, join: c in Permalink, on: ^join_on)
100
+ |> select([p, c], {p, c})
101
+
102
+ assert [{^p, ^c}] = TestRepo.all(query)
103
+
104
+ join_on = dynamic([p, permalink: c], c.id == ^c.id)
105
+
106
+ query =
107
+ from(p in Post, join: c in Permalink, as: :permalink, on: ^join_on)
108
+ |> select([p, c], {p, c})
109
+
110
+ assert [{^p, ^c}] = TestRepo.all(query)
111
+ end
112
+
113
+ @tag :cross_join
114
+ test "cross joins with missing entries" do
115
+ p1 = TestRepo.insert!(%Post{title: "1"})
116
+ p2 = TestRepo.insert!(%Post{title: "2"})
117
+ c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id})
118
+
119
+ query = from(p in Post, cross_join: c in Permalink, order_by: p.id, select: {p, c})
120
+ assert [{^p1, ^c1}, {^p2, ^c1}] = TestRepo.all(query)
121
+ end
122
+
123
+ @tag :left_join
124
+ test "left joins with missing entries" do
125
+ p1 = TestRepo.insert!(%Post{title: "1"})
126
+ p2 = TestRepo.insert!(%Post{title: "2"})
127
+ c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id})
128
+
129
+ query = from(p in Post, left_join: c in assoc(p, :permalink), order_by: p.id, select: {p, c})
130
+ assert [{^p1, nil}, {^p2, ^c1}] = TestRepo.all(query)
131
+ end
132
+
133
+ @tag :left_join
134
+ test "left join with missing entries from subquery" do
135
+ p1 = TestRepo.insert!(%Post{title: "1"})
136
+ p2 = TestRepo.insert!(%Post{title: "2"})
137
+ c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id})
138
+
139
+ query = from(p in Post, left_join: c in subquery(Permalink), on: p.id == c.post_id, order_by: p.id, select: {p, c})
140
+ assert [{^p1, nil}, {^p2, ^c1}] = TestRepo.all(query)
141
+ end
142
+
143
+ @tag :right_join
144
+ test "right joins with missing entries" do
145
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
146
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
147
+
148
+ %Permalink{id: plid1} = TestRepo.insert!(%Permalink{url: "1", post_id: pid2})
149
+
150
+ TestRepo.insert!(%Comment{text: "1", post_id: pid1})
151
+ TestRepo.insert!(%Comment{text: "2", post_id: pid2})
152
+ TestRepo.insert!(%Comment{text: "3", post_id: nil})
153
+
154
+ query = from(p in Post, right_join: c in assoc(p, :comments),
155
+ preload: :permalink, order_by: c.id)
156
+ assert [p1, p2, p3] = TestRepo.all(query)
157
+ assert p1.id == pid1
158
+ assert p2.id == pid2
159
+ assert is_nil(p3.id)
160
+
161
+ assert p1.permalink == nil
162
+ assert p2.permalink.id == plid1
163
+ end
164
+
165
+ ## Associations joins
166
+
167
+ test "has_many association join" do
168
+ post = TestRepo.insert!(%Post{title: "1"})
169
+ c1 = TestRepo.insert!(%Comment{text: "hey", post_id: post.id})
170
+ c2 = TestRepo.insert!(%Comment{text: "heya", post_id: post.id})
171
+
172
+ query = from(p in Post, join: c in assoc(p, :comments), select: {p, c}, order_by: p.id)
173
+ [{^post, ^c1}, {^post, ^c2}] = TestRepo.all(query)
174
+ end
175
+
176
+ test "has_one association join" do
177
+ post1 = TestRepo.insert!(%Post{title: "1"})
178
+ post2 = TestRepo.insert!(%Post{title: "1"})
179
+ user = TestRepo.insert!(%User{})
180
+ p1 = TestRepo.insert!(%Permalink{url: "hey", user_id: user.id, post_id: post1.id})
181
+ p2 = TestRepo.insert!(%Permalink{url: "heya", user_id: user.id, post_id: post2.id})
182
+
183
+ query = from(p in User, join: c in assoc(p, :permalink), select: {p, c}, order_by: c.id)
184
+ [{^user, ^p1}, {^user, ^p2}] = TestRepo.all(query)
185
+ end
186
+
187
+ test "belongs_to association join" do
188
+ post1 = TestRepo.insert!(%Post{title: "1"})
189
+ post2 = TestRepo.insert!(%Post{title: "1"})
190
+ user = TestRepo.insert!(%User{})
191
+ p1 = TestRepo.insert!(%Permalink{url: "hey", user_id: user.id, post_id: post1.id})
192
+ p2 = TestRepo.insert!(%Permalink{url: "heya", user_id: user.id, post_id: post2.id})
193
+
194
+ query = from(p in Permalink, join: c in assoc(p, :user), select: {p, c}, order_by: p.id)
195
+ [{^p1, ^user}, {^p2, ^user}] = TestRepo.all(query)
196
+ end
197
+
198
+ test "has_many through association join" do
199
+ p1 = TestRepo.insert!(%Post{})
200
+ p2 = TestRepo.insert!(%Post{})
201
+
202
+ u1 = TestRepo.insert!(%User{name: "zzz"})
203
+ u2 = TestRepo.insert!(%User{name: "aaa"})
204
+
205
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
206
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
207
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id})
208
+ %Comment{} = TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id})
209
+
210
+ query = from p in Post, join: a in assoc(p, :comments_authors), select: {p, a}, order_by: [p.id, a.name]
211
+ assert [{^p1, ^u2}, {^p1, ^u1}, {^p1, ^u1}, {^p2, ^u2}] = TestRepo.all(query)
212
+ end
213
+
214
+ test "has_many through nested association joins" do
215
+ u1 = TestRepo.insert!(%User{name: "Alice"})
216
+ u2 = TestRepo.insert!(%User{name: "John"})
217
+
218
+ p1 = TestRepo.insert!(%Post{title: "p1", author_id: u1.id})
219
+ p2 = TestRepo.insert!(%Post{title: "p2", author_id: u1.id})
220
+
221
+ TestRepo.insert!(%Comment{text: "c1", author_id: u1.id, post_id: p1.id})
222
+ TestRepo.insert!(%Comment{text: "c2", author_id: u2.id, post_id: p1.id})
223
+ TestRepo.insert!(%Comment{text: "c3", author_id: u2.id, post_id: p2.id})
224
+ TestRepo.insert!(%Comment{text: "c4", post_id: p2.id})
225
+ TestRepo.insert!(%Comment{text: "c5", author_id: u1.id, post_id: p2.id})
226
+
227
+ assert %{
228
+ comments: [
229
+ %{text: "c1"},
230
+ %{text: "c5"}
231
+ ],
232
+ posts: [
233
+ %{title: "p1"} = p1,
234
+ %{title: "p2"} = p2
235
+ ]
236
+ } =
237
+ from(u in User)
238
+ |> join(:left, [u], p in assoc(u, :posts))
239
+ |> join(:left, [u], c in assoc(u, :comments))
240
+ |> join(:left, [_, p], c in assoc(p, :comments))
241
+ |> preload(
242
+ [user, posts, comments, post_comments],
243
+ comments: comments,
244
+ posts: {posts, comments: {post_comments, :author}}
245
+ )
246
+ |> TestRepo.get(u1.id)
247
+
248
+ assert [
249
+ %{text: "c1", author: %{name: "Alice"}},
250
+ %{text: "c2", author: %{name: "John"}}
251
+ ] = Enum.sort_by(p1.comments, & &1.text)
252
+
253
+ assert [
254
+ %{text: "c3", author: %{name: "John"}},
255
+ %{text: "c4", author: nil},
256
+ %{text: "c5", author: %{name: "Alice"}}
257
+ ] = Enum.sort_by(p2.comments, & &1.text)
258
+ end
259
+
260
+ test "many_to_many association join" do
261
+ p1 = TestRepo.insert!(%Post{title: "1"})
262
+ p2 = TestRepo.insert!(%Post{title: "2"})
263
+ _p = TestRepo.insert!(%Post{title: "3"})
264
+ u1 = TestRepo.insert!(%User{name: "john"})
265
+ u2 = TestRepo.insert!(%User{name: "mary"})
266
+
267
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: u1.id],
268
+ [post_id: p1.id, user_id: u2.id],
269
+ [post_id: p2.id, user_id: u2.id]]
270
+
271
+ query = from(p in Post, join: u in assoc(p, :users), select: {p, u}, order_by: p.id)
272
+ [{^p1, ^u1}, {^p1, ^u2}, {^p2, ^u2}] = TestRepo.all(query)
273
+ end
274
+
275
+ ## Association preload
276
+
277
+ test "has_many assoc selector" do
278
+ p1 = TestRepo.insert!(%Post{title: "1"})
279
+ p2 = TestRepo.insert!(%Post{title: "2"})
280
+
281
+ c1 = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
282
+ c2 = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
283
+ c3 = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
284
+
285
+ # Without on
286
+ query = from(p in Post, join: c in assoc(p, :comments), preload: [comments: c])
287
+ [p1, p2] = TestRepo.all(query)
288
+ assert p1.comments == [c1, c2]
289
+ assert p2.comments == [c3]
290
+
291
+ # With on
292
+ query = from(p in Post, left_join: c in assoc(p, :comments),
293
+ on: p.title == c.text, preload: [comments: c])
294
+ [p1, p2] = TestRepo.all(query)
295
+ assert p1.comments == [c1]
296
+ assert p2.comments == []
297
+ end
298
+
299
+ test "has_one assoc selector" do
300
+ p1 = TestRepo.insert!(%Post{title: "1"})
301
+ p2 = TestRepo.insert!(%Post{title: "2"})
302
+
303
+ pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id})
304
+ _pl = TestRepo.insert!(%Permalink{url: "2"})
305
+ pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: p2.id})
306
+
307
+ query = from(p in Post, join: pl in assoc(p, :permalink), preload: [permalink: pl])
308
+ assert [post1, post3] = TestRepo.all(query)
309
+
310
+ assert post1.permalink == pl1
311
+ assert post3.permalink == pl3
312
+ end
313
+
314
+ test "belongs_to assoc selector" do
315
+ p1 = TestRepo.insert!(%Post{title: "1"})
316
+ p2 = TestRepo.insert!(%Post{title: "2"})
317
+
318
+ TestRepo.insert!(%Permalink{url: "1", post_id: p1.id})
319
+ TestRepo.insert!(%Permalink{url: "2"})
320
+ TestRepo.insert!(%Permalink{url: "3", post_id: p2.id})
321
+
322
+ query = from(pl in Permalink, left_join: p in assoc(pl, :post), preload: [post: p], order_by: pl.id)
323
+ assert [pl1, pl2, pl3] = TestRepo.all(query)
324
+
325
+ assert pl1.post == p1
326
+ refute pl2.post
327
+ assert pl3.post == p2
328
+ end
329
+
330
+ test "many_to_many assoc selector" do
331
+ p1 = TestRepo.insert!(%Post{title: "1"})
332
+ p2 = TestRepo.insert!(%Post{title: "2"})
333
+ _p = TestRepo.insert!(%Post{title: "3"})
334
+ u1 = TestRepo.insert!(%User{name: "1"})
335
+ u2 = TestRepo.insert!(%User{name: "2"})
336
+
337
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: u1.id],
338
+ [post_id: p1.id, user_id: u2.id],
339
+ [post_id: p2.id, user_id: u2.id]]
340
+
341
+ # Without on
342
+ query = from(p in Post, left_join: u in assoc(p, :users), preload: [users: u], order_by: p.id)
343
+ [p1, p2, p3] = TestRepo.all(query)
344
+ assert Enum.sort_by(p1.users, & &1.name) == [u1, u2]
345
+ assert p2.users == [u2]
346
+ assert p3.users == []
347
+
348
+ # With on
349
+ query = from(p in Post, left_join: u in assoc(p, :users), on: p.title == u.name,
350
+ preload: [users: u], order_by: p.id)
351
+ [p1, p2, p3] = TestRepo.all(query)
352
+ assert p1.users == [u1]
353
+ assert p2.users == [u2]
354
+ assert p3.users == []
355
+ end
356
+
357
+ test "has_many through assoc selector" do
358
+ p1 = TestRepo.insert!(%Post{title: "1"})
359
+ p2 = TestRepo.insert!(%Post{title: "2"})
360
+
361
+ u1 = TestRepo.insert!(%User{name: "1"})
362
+ u2 = TestRepo.insert!(%User{name: "2"})
363
+
364
+ TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
365
+ TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id})
366
+ TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id})
367
+ TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id})
368
+
369
+ # Without on
370
+ query = from(p in Post, left_join: ca in assoc(p, :comments_authors),
371
+ preload: [comments_authors: ca])
372
+ [p1, p2] = TestRepo.all(query)
373
+ assert Enum.sort_by(p1.comments_authors, & &1.id) == [u1, u2]
374
+ assert p2.comments_authors == [u2]
375
+
376
+ # With on
377
+ query = from(p in Post, left_join: ca in assoc(p, :comments_authors),
378
+ on: ca.name == p.title, preload: [comments_authors: ca])
379
+ [p1, p2] = TestRepo.all(query)
380
+ assert p1.comments_authors == [u1]
381
+ assert p2.comments_authors == [u2]
382
+ end
383
+
384
+ test "has_many through-through assoc selector" do
385
+ %Post{id: pid1} = TestRepo.insert!(%Post{})
386
+ %Post{id: pid2} = TestRepo.insert!(%Post{})
387
+
388
+ %Permalink{} = TestRepo.insert!(%Permalink{post_id: pid1, url: "1"})
389
+ %Permalink{} = TestRepo.insert!(%Permalink{post_id: pid2, url: "2"})
390
+
391
+ %User{id: uid1} = TestRepo.insert!(%User{})
392
+ %User{id: uid2} = TestRepo.insert!(%User{})
393
+
394
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
395
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
396
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
397
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2})
398
+
399
+ query = from(p in Permalink, left_join: ca in assoc(p, :post_comments_authors),
400
+ preload: [post_comments_authors: ca], order_by: ca.id)
401
+
402
+ [l1, l2] = TestRepo.all(query)
403
+ [u1, u2] = l1.post_comments_authors
404
+ assert u1.id == uid1
405
+ assert u2.id == uid2
406
+
407
+ [u2] = l2.post_comments_authors
408
+ assert u2.id == uid2
409
+
410
+ # Insert some intermediary joins to check indexes won't be shuffled
411
+ query = from(p in Permalink,
412
+ left_join: assoc(p, :post),
413
+ left_join: ca in assoc(p, :post_comments_authors),
414
+ left_join: assoc(p, :post),
415
+ left_join: assoc(p, :post),
416
+ preload: [post_comments_authors: ca], order_by: ca.id)
417
+
418
+ [l1, l2] = TestRepo.all(query)
419
+ [u1, u2] = l1.post_comments_authors
420
+ assert u1.id == uid1
421
+ assert u2.id == uid2
422
+
423
+ [u2] = l2.post_comments_authors
424
+ assert u2.id == uid2
425
+ end
426
+
427
+ ## Nested
428
+
429
+ test "nested assoc" do
430
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
431
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
432
+
433
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
434
+ %User{id: uid2} = TestRepo.insert!(%User{name: "2"})
435
+
436
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1, author_id: uid1})
437
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid1, author_id: uid2})
438
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: pid2, author_id: uid2})
439
+
440
+ # use multiple associations to force parallel preloader
441
+ query = from p in Post,
442
+ left_join: c in assoc(p, :comments),
443
+ left_join: u in assoc(c, :author),
444
+ order_by: [p.id, c.id, u.id],
445
+ preload: [:permalink, comments: {c, author: {u, [:comments, :custom]}}],
446
+ select: {0, [p], 1, 2}
447
+
448
+ posts = TestRepo.all(query)
449
+ assert [p1, p2] = Enum.map(posts, fn {0, [p], 1, 2} -> p end)
450
+ assert p1.id == pid1
451
+ assert p2.id == pid2
452
+
453
+ assert [c1, c2] = p1.comments
454
+ assert [c3] = p2.comments
455
+ assert c1.id == cid1
456
+ assert c2.id == cid2
457
+ assert c3.id == cid3
458
+
459
+ assert c1.author.id == uid1
460
+ assert c2.author.id == uid2
461
+ assert c3.author.id == uid2
462
+ end
463
+
464
+ test "nested assoc with missing entries" do
465
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
466
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
467
+ %Post{id: pid3} = TestRepo.insert!(%Post{title: "2"})
468
+
469
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
470
+ %User{id: uid2} = TestRepo.insert!(%User{name: "2"})
471
+
472
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1, author_id: uid1})
473
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid1, author_id: nil})
474
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: pid3, author_id: uid2})
475
+
476
+ query = from p in Post,
477
+ left_join: c in assoc(p, :comments),
478
+ left_join: u in assoc(c, :author),
479
+ order_by: [p.id, c.id, u.id],
480
+ preload: [comments: {c, author: u}]
481
+
482
+ assert [p1, p2, p3] = TestRepo.all(query)
483
+ assert p1.id == pid1
484
+ assert p2.id == pid2
485
+ assert p3.id == pid3
486
+
487
+ assert [c1, c2] = p1.comments
488
+ assert [] = p2.comments
489
+ assert [c3] = p3.comments
490
+ assert c1.id == cid1
491
+ assert c2.id == cid2
492
+ assert c3.id == cid3
493
+
494
+ assert c1.author.id == uid1
495
+ assert c2.author == nil
496
+ assert c3.author.id == uid2
497
+ end
498
+
499
+ test "nested assoc with child preload" do
500
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
501
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
502
+
503
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
504
+ %User{id: uid2} = TestRepo.insert!(%User{name: "2"})
505
+
506
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1, author_id: uid1})
507
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid1, author_id: uid2})
508
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: pid2, author_id: uid2})
509
+
510
+ query = from p in Post,
511
+ left_join: c in assoc(p, :comments),
512
+ order_by: [p.id, c.id],
513
+ preload: [comments: {c, :author}],
514
+ select: p
515
+
516
+ assert [p1, p2] = TestRepo.all(query)
517
+ assert p1.id == pid1
518
+ assert p2.id == pid2
519
+
520
+ assert [c1, c2] = p1.comments
521
+ assert [c3] = p2.comments
522
+ assert c1.id == cid1
523
+ assert c2.id == cid2
524
+ assert c3.id == cid3
525
+
526
+ assert c1.author.id == uid1
527
+ assert c2.author.id == uid2
528
+ assert c3.author.id == uid2
529
+ end
530
+
531
+ test "nested assoc with sibling preload" do
532
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
533
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
534
+
535
+ %Permalink{id: plid1} = TestRepo.insert!(%Permalink{url: "1", post_id: pid2})
536
+
537
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1})
538
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid2})
539
+ %Comment{id: _} = TestRepo.insert!(%Comment{text: "3", post_id: pid2})
540
+
541
+ query = from p in Post,
542
+ left_join: c in assoc(p, :comments),
543
+ where: c.text in ~w(1 2),
544
+ preload: [:permalink, comments: c],
545
+ select: {0, [p], 1, 2}
546
+
547
+ posts = TestRepo.all(query)
548
+ assert [p1, p2] = Enum.map(posts, fn {0, [p], 1, 2} -> p end)
549
+ assert p1.id == pid1
550
+ assert p2.id == pid2
551
+
552
+ assert p2.permalink.id == plid1
553
+
554
+ assert [c1] = p1.comments
555
+ assert [c2] = p2.comments
556
+ assert c1.id == cid1
557
+ assert c2.id == cid2
558
+ end
559
+
560
+ test "mixing regular join and assoc selector" do
561
+ p1 = TestRepo.insert!(%Post{title: "1"})
562
+ p2 = TestRepo.insert!(%Post{title: "2"})
563
+
564
+ c1 = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
565
+ c2 = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
566
+ c3 = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
567
+
568
+ pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id})
569
+ _pl = TestRepo.insert!(%Permalink{url: "2"})
570
+ pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: p2.id})
571
+
572
+ # Without on
573
+ query = from(p in Post, join: pl in assoc(p, :permalink),
574
+ join: c in assoc(p, :comments),
575
+ preload: [permalink: pl],
576
+ select: {p, c})
577
+ [{p1, ^c1}, {p1, ^c2}, {p2, ^c3}] = TestRepo.all(query)
578
+ assert p1.permalink == pl1
579
+ assert p2.permalink == pl3
580
+ end
581
+
582
+ test "association with composite pk join" do
583
+ post = TestRepo.insert!(%Post{title: "1"})
584
+ user = TestRepo.insert!(%User{name: "1"})
585
+ TestRepo.insert!(%PostUserCompositePk{post_id: post.id, user_id: user.id})
586
+
587
+ query = from(p in Post, join: a in assoc(p, :post_user_composite_pk),
588
+ preload: [post_user_composite_pk: a], select: p)
589
+ assert [post] = TestRepo.all(query)
590
+ assert post.post_user_composite_pk
591
+ end
592
+
593
+ test "joining a through association with a nested preloads" do
594
+ post = TestRepo.insert!(%Post{title: "1"})
595
+ user = TestRepo.insert!(%User{name: "1"})
596
+ TestRepo.insert!(%Comment{text: "1", post_id: post.id})
597
+ TestRepo.insert!(%Permalink{post_id: post.id, user_id: user.id})
598
+
599
+ query =
600
+ from c in Comment,
601
+ join: pp in assoc(c, :post_permalink),
602
+ join: u in assoc(pp, :user),
603
+ preload: [post_permalink: {pp, [:post, user: u]}]
604
+
605
+ [comment] = TestRepo.all(query)
606
+
607
+ assert not Ecto.assoc_loaded?(comment.post)
608
+ assert %Permalink{user: %User{}, post: %Post{}} = comment.post_permalink
609
+ end
610
+
611
+ test "joining multiple through associations with a nested preloads" do
612
+ post = TestRepo.insert!(%Post{title: "1"})
613
+ user = TestRepo.insert!(%User{name: "1"})
614
+ TestRepo.insert!(%Comment{text: "1", post_id: post.id, author_id: user.id})
615
+ TestRepo.insert!(%Permalink{post_id: post.id, user_id: user.id})
616
+
617
+ query =
618
+ from c in Comment,
619
+ join: pp in assoc(c, :post_permalink),
620
+ join: ap in assoc(c, :author_permalink),
621
+ join: u1 in assoc(pp, :user),
622
+ join: u2 in assoc(ap, :user),
623
+ preload: [post_permalink: {pp, [:post, user: u1]}, author_permalink: {ap, [:post, user: u2]}]
624
+
625
+ [comment] = TestRepo.all(query)
626
+
627
+ assert not Ecto.assoc_loaded?(comment.post)
628
+ assert not Ecto.assoc_loaded?(comment.author)
629
+ assert %Permalink{user: %User{}, post: %Post{}} = comment.post_permalink
630
+ assert %Permalink{user: %User{}, post: %Post{}} = comment.author_permalink
631
+ end
632
+
633
+ test "joining nested through associations with a nested preloads" do
634
+ user = TestRepo.insert!(%User{name: "1"})
635
+ post = TestRepo.insert!(%Post{title: "1", author_id: user.id})
636
+ TestRepo.insert!(%Comment{text: "1", post_id: post.id})
637
+ TestRepo.insert!(%Permalink{post_id: post.id, user_id: user.id})
638
+
639
+ query =
640
+ from c in Comment,
641
+ join: pp in assoc(c, :post_permalink),
642
+ join: up in assoc(pp, :user_posts),
643
+ preload: [post_permalink: {pp, [:post, user_posts: {up, :comments}]}]
644
+
645
+ [comment] = TestRepo.all(query)
646
+
647
+ assert not Ecto.assoc_loaded?(comment.post)
648
+ assert %Permalink{post: %Post{}, user_posts: [%Post{}]} = comment.post_permalink
649
+ assert not Ecto.assoc_loaded?(comment.post_permalink.user)
650
+ end
651
+
652
+ test "joining and preloading through a subquery" do
653
+ %{id: p_id} = TestRepo.insert!(%Post{})
654
+ %{id: c1_id} = TestRepo.insert!(%Comment{post_id: p_id})
655
+ %{id: c2_id} = TestRepo.insert!(%Comment{post_id: p_id})
656
+
657
+ q =
658
+ from p1 in Post,
659
+ left_join: u in User,
660
+ on: p1.author_id == u.id,
661
+ inner_join: c in subquery(from c in Comment),
662
+ on: p1.id == c.post_id,
663
+ join: p2 in Post,
664
+ on: c.post_id == p2.id,
665
+ preload: [author: u, force_comments: {c, post: p2}]
666
+
667
+ assert [%Post{id: ^p_id, force_comments: comments}] = TestRepo.all(q)
668
+ [comment1, comment2] = Enum.sort_by(comments, & &1.id)
669
+ assert %Comment{id: ^c1_id, post: %Post{id: ^p_id}} = comment1
670
+ assert %Comment{id: ^c2_id, post: %Post{id: ^p_id}} = comment2
671
+ end
672
+ end
deps/ecto/integration_test/cases/preload.exs ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.PreloadTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.TestRepo
5
+ import Ecto.Query
6
+
7
+ alias Ecto.Integration.Post
8
+ alias Ecto.Integration.Comment
9
+ alias Ecto.Integration.Item
10
+ alias Ecto.Integration.Permalink
11
+ alias Ecto.Integration.User
12
+ alias Ecto.Integration.Custom
13
+ alias Ecto.Integration.Order
14
+
15
+ test "preload with parameter from select_merge" do
16
+ p1 = TestRepo.insert!(%Post{title: "p1"})
17
+ TestRepo.insert!(%Comment{text: "c1", post: p1})
18
+
19
+ comments =
20
+ from(c in Comment, select: struct(c, [:text]))
21
+ |> select_merge([c], %{post_id: c.post_id})
22
+ |> preload(:post)
23
+ |> TestRepo.all()
24
+
25
+ assert [%{text: "c1", post: %{title: "p1"}}] = comments
26
+ end
27
+
28
+ test "preload has_many" do
29
+ p1 = TestRepo.insert!(%Post{title: "1"})
30
+ p2 = TestRepo.insert!(%Post{title: "2"})
31
+ p3 = TestRepo.insert!(%Post{title: "3"})
32
+
33
+ # We use the same text to expose bugs in preload sorting
34
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
35
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
36
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
37
+ %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
38
+
39
+ assert %Ecto.Association.NotLoaded{} = p1.comments
40
+
41
+ [p3, p1, p2] = TestRepo.preload([p3, p1, p2], :comments)
42
+ assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id()
43
+ assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id()
44
+ assert [] = p3.comments
45
+ end
46
+
47
+ test "preload has_many multiple times" do
48
+ p1 = TestRepo.insert!(%Post{title: "1"})
49
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
50
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
51
+
52
+ [p1, p1] = TestRepo.preload([p1, p1], :comments)
53
+ assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id()
54
+
55
+ [p1, p1] = TestRepo.preload([p1, p1], :comments)
56
+ assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id()
57
+ end
58
+
59
+ test "preload has_one" do
60
+ p1 = TestRepo.insert!(%Post{title: "1"})
61
+ p2 = TestRepo.insert!(%Post{title: "2"})
62
+ p3 = TestRepo.insert!(%Post{title: "3"})
63
+
64
+ %Permalink{id: pid1} = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id})
65
+ %Permalink{} = TestRepo.insert!(%Permalink{url: "2", post_id: nil})
66
+ %Permalink{id: pid3} = TestRepo.insert!(%Permalink{url: "3", post_id: p3.id})
67
+
68
+ assert %Ecto.Association.NotLoaded{} = p1.permalink
69
+ assert %Ecto.Association.NotLoaded{} = p2.permalink
70
+
71
+ [p3, p1, p2] = TestRepo.preload([p3, p1, p2], :permalink)
72
+ assert %Permalink{id: ^pid1} = p1.permalink
73
+ refute p2.permalink
74
+ assert %Permalink{id: ^pid3} = p3.permalink
75
+ end
76
+
77
+ test "preload belongs_to" do
78
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
79
+ TestRepo.insert!(%Post{title: "2"})
80
+ %Post{id: pid3} = TestRepo.insert!(%Post{title: "3"})
81
+
82
+ pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: pid1})
83
+ pl2 = TestRepo.insert!(%Permalink{url: "2", post_id: nil})
84
+ pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: pid3})
85
+ assert %Ecto.Association.NotLoaded{} = pl1.post
86
+
87
+ [pl3, pl1, pl2] = TestRepo.preload([pl3, pl1, pl2], :post)
88
+ assert %Post{id: ^pid1} = pl1.post
89
+ refute pl2.post
90
+ assert %Post{id: ^pid3} = pl3.post
91
+ end
92
+
93
+ test "preload multiple belongs_to" do
94
+ %User{id: uid} = TestRepo.insert!(%User{name: "foo"})
95
+ %Post{id: pid} = TestRepo.insert!(%Post{title: "1"})
96
+ %Comment{id: cid} = TestRepo.insert!(%Comment{post_id: pid, author_id: uid})
97
+
98
+ comment = TestRepo.get!(Comment, cid)
99
+ comment = TestRepo.preload(comment, [:author, :post])
100
+ assert comment.author.id == uid
101
+ assert comment.post.id == pid
102
+ end
103
+
104
+ test "preload belongs_to with shared parent" do
105
+ %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
106
+ %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
107
+
108
+ c1 = TestRepo.insert!(%Comment{text: "1", post_id: pid1})
109
+ c2 = TestRepo.insert!(%Comment{text: "2", post_id: pid1})
110
+ c3 = TestRepo.insert!(%Comment{text: "3", post_id: pid2})
111
+
112
+ [c3, c1, c2] = TestRepo.preload([c3, c1, c2], :post)
113
+ assert %Post{id: ^pid1} = c1.post
114
+ assert %Post{id: ^pid1} = c2.post
115
+ assert %Post{id: ^pid2} = c3.post
116
+ end
117
+
118
+ test "preload many_to_many" do
119
+ p1 = TestRepo.insert!(%Post{title: "1"})
120
+ p2 = TestRepo.insert!(%Post{title: "2"})
121
+ p3 = TestRepo.insert!(%Post{title: "3"})
122
+
123
+ # We use the same name to expose bugs in preload sorting
124
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
125
+ %User{id: uid3} = TestRepo.insert!(%User{name: "2"})
126
+ %User{id: uid2} = TestRepo.insert!(%User{name: "2"})
127
+ %User{id: uid4} = TestRepo.insert!(%User{name: "3"})
128
+
129
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
130
+ [post_id: p1.id, user_id: uid2],
131
+ [post_id: p2.id, user_id: uid3],
132
+ [post_id: p2.id, user_id: uid4],
133
+ [post_id: p3.id, user_id: uid1],
134
+ [post_id: p3.id, user_id: uid4]]
135
+
136
+ assert %Ecto.Association.NotLoaded{} = p1.users
137
+
138
+ [p1, p2, p3] = TestRepo.preload([p1, p2, p3], :users)
139
+ assert [%User{id: ^uid1}, %User{id: ^uid2}] = p1.users |> sort_by_id
140
+ assert [%User{id: ^uid3}, %User{id: ^uid4}] = p2.users |> sort_by_id
141
+ assert [%User{id: ^uid1}, %User{id: ^uid4}] = p3.users |> sort_by_id
142
+ end
143
+
144
+ test "preload has_many through" do
145
+ %Post{id: pid1} = p1 = TestRepo.insert!(%Post{})
146
+ %Post{id: pid2} = p2 = TestRepo.insert!(%Post{})
147
+
148
+ %User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
149
+ %User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
150
+
151
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
152
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
153
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
154
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2})
155
+
156
+ [p1, p2] = TestRepo.preload([p1, p2], :comments_authors)
157
+
158
+ # Through was preloaded
159
+ [u1, u2] = p1.comments_authors |> sort_by_id
160
+ assert u1.id == uid1
161
+ assert u2.id == uid2
162
+
163
+ [u2] = p2.comments_authors
164
+ assert u2.id == uid2
165
+
166
+ # But we also preloaded everything along the way
167
+ assert [c1, c2, c3] = p1.comments |> sort_by_id
168
+ assert c1.author.id == uid1
169
+ assert c2.author.id == uid1
170
+ assert c3.author.id == uid2
171
+
172
+ assert [c4] = p2.comments
173
+ assert c4.author.id == uid2
174
+ end
175
+
176
+ test "preload has_one through" do
177
+ %Post{id: pid1} = TestRepo.insert!(%Post{})
178
+ %Post{id: pid2} = TestRepo.insert!(%Post{})
179
+
180
+ %Permalink{id: lid1} = TestRepo.insert!(%Permalink{post_id: pid1, url: "1"})
181
+ %Permalink{id: lid2} = TestRepo.insert!(%Permalink{post_id: pid2, url: "2"})
182
+
183
+ %Comment{} = c1 = TestRepo.insert!(%Comment{post_id: pid1})
184
+ %Comment{} = c2 = TestRepo.insert!(%Comment{post_id: pid1})
185
+ %Comment{} = c3 = TestRepo.insert!(%Comment{post_id: pid2})
186
+
187
+ [c1, c2, c3] = TestRepo.preload([c1, c2, c3], :post_permalink)
188
+
189
+ # Through was preloaded
190
+ assert c1.post.id == pid1
191
+ assert c1.post.permalink.id == lid1
192
+ assert c1.post_permalink.id == lid1
193
+
194
+ assert c2.post.id == pid1
195
+ assert c2.post.permalink.id == lid1
196
+ assert c2.post_permalink.id == lid1
197
+
198
+ assert c3.post.id == pid2
199
+ assert c3.post.permalink.id == lid2
200
+ assert c3.post_permalink.id == lid2
201
+ end
202
+
203
+ test "preload through with nil association" do
204
+ %Comment{} = c = TestRepo.insert!(%Comment{post_id: nil})
205
+
206
+ c = TestRepo.preload(c, [:post, :post_permalink])
207
+ assert c.post == nil
208
+ assert c.post_permalink == nil
209
+
210
+ c = TestRepo.preload(c, [:post, :post_permalink])
211
+ assert c.post == nil
212
+ assert c.post_permalink == nil
213
+ end
214
+
215
+ test "preload through with nil struct" do
216
+ %Comment{} = c = TestRepo.insert!(%Comment{})
217
+ [%Comment{}, nil] = TestRepo.preload([c, nil], [:post, :post_permalink])
218
+ end
219
+
220
+ test "preload has_many through-through" do
221
+ %Post{id: pid1} = TestRepo.insert!(%Post{})
222
+ %Post{id: pid2} = TestRepo.insert!(%Post{})
223
+
224
+ %Permalink{} = l1 = TestRepo.insert!(%Permalink{post_id: pid1, url: "1"})
225
+ %Permalink{} = l2 = TestRepo.insert!(%Permalink{post_id: pid2, url: "2"})
226
+
227
+ %User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
228
+ %User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
229
+
230
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
231
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
232
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
233
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2})
234
+
235
+ # With assoc query
236
+ [l1, l2] = TestRepo.preload([l1, l2], :post_comments_authors)
237
+
238
+ # Through was preloaded
239
+ [u1, u2] = l1.post_comments_authors |> sort_by_id
240
+ assert u1.id == uid1
241
+ assert u2.id == uid2
242
+
243
+ [u2] = l2.post_comments_authors
244
+ assert u2.id == uid2
245
+
246
+ # But we also preloaded everything along the way
247
+ assert l1.post.id == pid1
248
+ assert l1.post.comments != []
249
+
250
+ assert l2.post.id == pid2
251
+ assert l2.post.comments != []
252
+ end
253
+
254
+ test "preload has_many through many_to_many" do
255
+ %Post{} = p1 = TestRepo.insert!(%Post{})
256
+ %Post{} = p2 = TestRepo.insert!(%Post{})
257
+
258
+ %User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
259
+ %User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
260
+
261
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
262
+ [post_id: p1.id, user_id: uid2],
263
+ [post_id: p2.id, user_id: uid2]]
264
+
265
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{author_id: uid1})
266
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{author_id: uid1})
267
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{author_id: uid2})
268
+ %Comment{id: cid4} = TestRepo.insert!(%Comment{author_id: uid2})
269
+
270
+ [p1, p2] = TestRepo.preload([p1, p2], :users_comments)
271
+
272
+ # Through was preloaded
273
+ [c1, c2, c3, c4] = p1.users_comments |> sort_by_id
274
+ assert c1.id == cid1
275
+ assert c2.id == cid2
276
+ assert c3.id == cid3
277
+ assert c4.id == cid4
278
+
279
+ [c3, c4] = p2.users_comments |> sort_by_id
280
+ assert c3.id == cid3
281
+ assert c4.id == cid4
282
+
283
+ # But we also preloaded everything along the way
284
+ assert [u1, u2] = p1.users |> sort_by_id
285
+ assert u1.id == uid1
286
+ assert u2.id == uid2
287
+
288
+ assert [u2] = p2.users
289
+ assert u2.id == uid2
290
+ end
291
+
292
+ ## Empties
293
+
294
+ test "preload empty" do
295
+ assert TestRepo.preload([], :anything_goes) == []
296
+ end
297
+
298
+ test "preload has_many with no associated entries" do
299
+ p = TestRepo.insert!(%Post{title: "1"})
300
+ p = TestRepo.preload(p, :comments)
301
+
302
+ assert p.title == "1"
303
+ assert p.comments == []
304
+ end
305
+
306
+ test "preload has_one with no associated entries" do
307
+ p = TestRepo.insert!(%Post{title: "1"})
308
+ p = TestRepo.preload(p, :permalink)
309
+
310
+ assert p.title == "1"
311
+ assert p.permalink == nil
312
+ end
313
+
314
+ test "preload belongs_to with no associated entry" do
315
+ c = TestRepo.insert!(%Comment{text: "1"})
316
+ c = TestRepo.preload(c, :post)
317
+
318
+ assert c.text == "1"
319
+ assert c.post == nil
320
+ end
321
+
322
+ test "preload many_to_many with no associated entries" do
323
+ p = TestRepo.insert!(%Post{title: "1"})
324
+ p = TestRepo.preload(p, :users)
325
+
326
+ assert p.title == "1"
327
+ assert p.users == []
328
+ end
329
+
330
+ ## With queries
331
+
332
+ test "preload with 1-arity function" do
333
+ p1 = TestRepo.insert!(%Post{title: "1"})
334
+ p2 = TestRepo.insert!(%Post{title: "2"})
335
+ p3 = TestRepo.insert!(%Post{title: "3"})
336
+
337
+ # We use the same text to expose bugs in preload sorting
338
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
339
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
340
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
341
+ %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
342
+
343
+ assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
344
+ comments: fn _ -> TestRepo.all(Comment) end)
345
+ assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = pe1.comments
346
+ assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = pe2.comments
347
+ assert [] = pe3.comments
348
+ end
349
+
350
+ test "preload with 2-arity function" do
351
+ p = TestRepo.insert!(%Post{title: "1"})
352
+ c1 = TestRepo.insert!(%Comment{post_id: p.id})
353
+ c2 = TestRepo.insert!(%Comment{post_id: p.id})
354
+
355
+ # making a simple preloader so that it works across all adapters
356
+ preloader = fn parent_ids, assoc ->
357
+ %{related_key: related_key, queryable: queryable} = assoc
358
+
359
+ from(q in queryable, where: field(q, ^related_key) in ^parent_ids, order_by: q.id)
360
+ |> TestRepo.all()
361
+ end
362
+
363
+ assert p = TestRepo.preload(p, comments: preloader)
364
+ assert [^c1, ^c2] = p.comments
365
+ end
366
+
367
+ test "preload many_to_many with function" do
368
+ p1 = TestRepo.insert!(%Post{title: "1"})
369
+ p2 = TestRepo.insert!(%Post{title: "2"})
370
+ p3 = TestRepo.insert!(%Post{title: "3"})
371
+
372
+ # We use the same name to expose bugs in preload sorting
373
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
374
+ %User{id: uid3} = TestRepo.insert!(%User{name: "2"})
375
+ %User{id: uid2} = TestRepo.insert!(%User{name: "2"})
376
+ %User{id: uid4} = TestRepo.insert!(%User{name: "3"})
377
+
378
+ TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
379
+ [post_id: p1.id, user_id: uid2],
380
+ [post_id: p2.id, user_id: uid3],
381
+ [post_id: p2.id, user_id: uid4],
382
+ [post_id: p3.id, user_id: uid1],
383
+ [post_id: p3.id, user_id: uid4]]
384
+
385
+ wrong_preloader = fn post_ids ->
386
+ TestRepo.all(
387
+ from u in User,
388
+ join: pu in "posts_users",
389
+ on: true,
390
+ where: pu.post_id in ^post_ids and pu.user_id == u.id,
391
+ order_by: u.id,
392
+ select: map(u, [:id])
393
+ )
394
+ end
395
+
396
+ assert_raise RuntimeError, ~r/invalid custom preload for `users` on `Ecto.Integration.Post`/, fn ->
397
+ TestRepo.preload([p1, p2, p3], users: wrong_preloader)
398
+ end
399
+
400
+ right_preloader = fn post_ids ->
401
+ TestRepo.all(
402
+ from u in User,
403
+ join: pu in "posts_users",
404
+ on: true,
405
+ where: pu.post_id in ^post_ids and pu.user_id == u.id,
406
+ order_by: u.id,
407
+ select: {pu.post_id, map(u, [:id])}
408
+ )
409
+ end
410
+
411
+ [p1, p2, p3] = TestRepo.preload([p1, p2, p3], users: right_preloader)
412
+ assert p1.users == [%{id: uid1}, %{id: uid2}]
413
+ assert p2.users == [%{id: uid3}, %{id: uid4}]
414
+ assert p3.users == [%{id: uid1}, %{id: uid4}]
415
+ end
416
+
417
+ test "preload with query" do
418
+ p1 = TestRepo.insert!(%Post{title: "1"})
419
+ p2 = TestRepo.insert!(%Post{title: "2"})
420
+ p3 = TestRepo.insert!(%Post{title: "3"})
421
+
422
+ # We use the same text to expose bugs in preload sorting
423
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
424
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
425
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
426
+ %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
427
+
428
+ assert %Ecto.Association.NotLoaded{} = p1.comments
429
+
430
+ # With empty query
431
+ assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
432
+ comments: from(c in Comment, where: false))
433
+ assert [] = pe1.comments
434
+ assert [] = pe2.comments
435
+ assert [] = pe3.comments
436
+
437
+ # With custom select
438
+ assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
439
+ comments: from(c in Comment, select: c.id, order_by: c.id))
440
+ assert [^cid1, ^cid2] = pe1.comments
441
+ assert [^cid3, ^cid4] = pe2.comments
442
+ assert [] = pe3.comments
443
+
444
+ # With custom ordered query
445
+ assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
446
+ comments: from(c in Comment, order_by: [desc: c.text]))
447
+ assert [%Comment{id: ^cid2}, %Comment{id: ^cid1}] = pe1.comments
448
+ assert [%Comment{id: ^cid4}, %Comment{id: ^cid3}] = pe2.comments
449
+ assert [] = pe3.comments
450
+
451
+ # With custom ordered query with preload
452
+ assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
453
+ comments: {from(c in Comment, order_by: [desc: c.text]), :post})
454
+ assert [%Comment{id: ^cid2} = c2, %Comment{id: ^cid1} = c1] = pe1.comments
455
+ assert [%Comment{id: ^cid4} = c4, %Comment{id: ^cid3} = c3] = pe2.comments
456
+ assert [] = pe3.comments
457
+
458
+ assert c1.post.title == "1"
459
+ assert c2.post.title == "1"
460
+ assert c3.post.title == "2"
461
+ assert c4.post.title == "2"
462
+ end
463
+
464
+ test "preload through with query" do
465
+ %Post{id: pid1} = p1 = TestRepo.insert!(%Post{})
466
+
467
+ u1 = TestRepo.insert!(%User{name: "foo"})
468
+ u2 = TestRepo.insert!(%User{name: "bar"})
469
+ u3 = TestRepo.insert!(%User{name: "baz"})
470
+ u4 = TestRepo.insert!(%User{name: "norf"})
471
+
472
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u1.id})
473
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u1.id})
474
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u2.id})
475
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u3.id})
476
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u4.id})
477
+
478
+ np1 = TestRepo.preload(p1, comments_authors: from(u in User, where: u.name == "foo"))
479
+ assert np1.comments_authors == [u1]
480
+
481
+ assert_raise ArgumentError, ~r/Ecto expected a map\/struct with the key `id` but got: \d+/, fn ->
482
+ TestRepo.preload(p1, comments_authors: from(u in User, order_by: u.name, select: u.id))
483
+ end
484
+
485
+ # The subpreload order does not matter because the result is dictated by comments
486
+ np1 = TestRepo.preload(p1, comments_authors: from(u in User, order_by: u.name, select: %{id: u.id}))
487
+ assert np1.comments_authors ==
488
+ [%{id: u1.id}, %{id: u2.id}, %{id: u3.id}, %{id: u4.id}]
489
+ end
490
+
491
+ test "preload into a subquery source" do
492
+ %{id: p_id} = TestRepo.insert!(%Post{})
493
+ %{id: c_id} = TestRepo.insert!(%Comment{post_id: p_id})
494
+
495
+ q =
496
+ from c in subquery(from c in Comment),
497
+ join: p in Post,
498
+ on: c.post_id == p.id,
499
+ preload: [post: p]
500
+
501
+ assert [%Comment{id: ^c_id, post: %Post{id: ^p_id}}] = TestRepo.all(q)
502
+ end
503
+
504
+ ## With take
505
+
506
+ test "preload with take" do
507
+ p1 = TestRepo.insert!(%Post{title: "1"})
508
+ p2 = TestRepo.insert!(%Post{title: "2"})
509
+ _p = TestRepo.insert!(%Post{title: "3"})
510
+
511
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
512
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
513
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
514
+ %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
515
+
516
+ assert %Ecto.Association.NotLoaded{} = p1.comments
517
+
518
+ posts = TestRepo.all(from Post, preload: [:comments], select: [:id, comments: [:id, :post_id]])
519
+ [p1, p2, p3] = sort_by_id(posts)
520
+ assert p1.title == nil
521
+ assert p2.title == nil
522
+ assert p3.title == nil
523
+
524
+ assert [%{id: ^cid1, text: nil}, %{id: ^cid2, text: nil}] = sort_by_id(p1.comments)
525
+ assert [%{id: ^cid3, text: nil}, %{id: ^cid4, text: nil}] = sort_by_id(p2.comments)
526
+ assert [] = sort_by_id(p3.comments)
527
+ end
528
+
529
+ test "preload through with take" do
530
+ %Post{id: pid1} = TestRepo.insert!(%Post{})
531
+
532
+ %User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
533
+ %User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
534
+
535
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
536
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
537
+ %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
538
+
539
+ [p1] = TestRepo.all from Post, preload: [:comments_authors], select: [:id, comments_authors: :id]
540
+ [%{id: ^uid1, name: nil}, %{id: ^uid2, name: nil}] = p1.comments_authors |> sort_by_id
541
+ end
542
+
543
+ ## Nested
544
+
545
+ test "preload many assocs" do
546
+ p1 = TestRepo.insert!(%Post{title: "1"})
547
+ p2 = TestRepo.insert!(%Post{title: "2"})
548
+
549
+ assert [p2, p1] = TestRepo.preload([p2, p1], [:comments, :users])
550
+ assert p1.comments == []
551
+ assert p2.comments == []
552
+ assert p1.users == []
553
+ assert p2.users == []
554
+ end
555
+
556
+ test "preload nested" do
557
+ p1 = TestRepo.insert!(%Post{title: "1"})
558
+ p2 = TestRepo.insert!(%Post{title: "2"})
559
+
560
+ TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
561
+ TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
562
+ TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
563
+ TestRepo.insert!(%Comment{text: "4", post_id: p2.id})
564
+
565
+ assert [p2, p1] = TestRepo.preload([p2, p1], [comments: :post])
566
+ assert [c1, c2] = p1.comments
567
+ assert [c3, c4] = p2.comments
568
+ assert p1.id == c1.post.id
569
+ assert p1.id == c2.post.id
570
+ assert p2.id == c3.post.id
571
+ assert p2.id == c4.post.id
572
+ end
573
+
574
+ test "preload nested via custom query" do
575
+ p1 = TestRepo.insert!(%Post{title: "1"})
576
+ p2 = TestRepo.insert!(%Post{title: "2"})
577
+
578
+ TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
579
+ TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
580
+ TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
581
+ TestRepo.insert!(%Comment{text: "4", post_id: p2.id})
582
+
583
+ query = from(c in Comment, preload: :post, order_by: [desc: c.text])
584
+ assert [p2, p1] = TestRepo.preload([p2, p1], comments: query)
585
+ assert [c2, c1] = p1.comments
586
+ assert [c4, c3] = p2.comments
587
+ assert p1.id == c1.post.id
588
+ assert p1.id == c2.post.id
589
+ assert p2.id == c3.post.id
590
+ assert p2.id == c4.post.id
591
+ end
592
+
593
+ test "custom preload_order" do
594
+ post = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"})
595
+
596
+ TestRepo.insert!(%Comment{text: "2", post_id: post.id})
597
+ TestRepo.insert!(%Comment{text: "1", post_id: post.id})
598
+
599
+ post = TestRepo.preload(post, [:ordered_comments, :ordered_users])
600
+
601
+ # asc
602
+ assert [%{text: "1"}, %{text: "2"}] = post.ordered_comments
603
+
604
+ # desc
605
+ assert [%{name: "foo"}, %{name: "bar"}] = post.ordered_users
606
+ end
607
+
608
+ test "custom preload_order with mfa" do
609
+ post1 = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"})
610
+ post2 = TestRepo.insert!(%Post{users: [%User{name: "baz"}, %User{name: "foz"}], title: "2"})
611
+
612
+ [post1, post2] = TestRepo.preload([post1, post2], [:ordered_users_by_join_table], log: :error)
613
+
614
+ assert [%{name: "foo"}, %{name: "bar"}] = post1.ordered_users_by_join_table
615
+ assert [%{name: "foz"}, %{name: "baz"}] = post2.ordered_users_by_join_table
616
+ end
617
+
618
+ ## Others
619
+
620
+ @tag :invalid_prefix
621
+ test "preload custom prefix from schema" do
622
+ p = TestRepo.insert!(%Post{title: "1"})
623
+ p = Ecto.put_meta(p, prefix: "this_surely_does_not_exist")
624
+ # This preload should fail because it points to a prefix that does not exist
625
+ assert catch_error(TestRepo.preload(p, [:comments]))
626
+ end
627
+
628
+ @tag :invalid_prefix
629
+ test "preload custom prefix from options" do
630
+ p = TestRepo.insert!(%Post{title: "1"})
631
+ # This preload should fail because it points to a prefix that does not exist
632
+ assert catch_error(TestRepo.preload(p, [:comments], prefix: "this_surely_does_not_exist"))
633
+ end
634
+
635
+ test "preload with binary_id" do
636
+ c = TestRepo.insert!(%Custom{})
637
+ u = TestRepo.insert!(%User{custom_id: c.bid})
638
+
639
+ u = TestRepo.preload(u, :custom)
640
+ assert u.custom.bid == c.bid
641
+ end
642
+
643
+ test "preload raises with association set but without id" do
644
+ c1 = TestRepo.insert!(%Comment{text: "1"})
645
+ u1 = TestRepo.insert!(%User{name: "name"})
646
+ updated = %{c1 | author: u1, author_id: nil}
647
+
648
+ assert ExUnit.CaptureLog.capture_log(fn ->
649
+ assert TestRepo.preload(updated, [:author]).author == u1
650
+ end) =~ ~r/its association key `author_id` is nil/
651
+
652
+ assert TestRepo.preload(updated, [:author], force: true).author == nil
653
+ end
654
+
655
+ test "preload skips already loaded for cardinality one" do
656
+ %Post{id: pid} = TestRepo.insert!(%Post{title: "1"})
657
+
658
+ c1 = %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid})
659
+ c2 = %Comment{id: _cid} = TestRepo.insert!(%Comment{text: "2", post_id: nil})
660
+
661
+ [c1, c2] = TestRepo.preload([c1, c2], :post)
662
+ assert %Post{id: ^pid} = c1.post
663
+ assert c2.post == nil
664
+
665
+ [c1, c2] = TestRepo.preload([c1, c2], post: :comments)
666
+ assert [%Comment{id: ^cid1}] = c1.post.comments
667
+
668
+ TestRepo.update_all Post, set: [title: "0"]
669
+ TestRepo.update_all Comment, set: [post_id: pid]
670
+
671
+ # Preloading once again shouldn't change the result
672
+ [c1, c2] = TestRepo.preload([c1, c2], :post)
673
+ assert %Post{id: ^pid, title: "1", comments: [_|_]} = c1.post
674
+ assert c2.post == nil
675
+
676
+ [c1, c2] = TestRepo.preload([c1, %{c2 | post_id: pid}], :post, force: true)
677
+ assert %Post{id: ^pid, title: "0", comments: %Ecto.Association.NotLoaded{}} = c1.post
678
+ assert %Post{id: ^pid, title: "0", comments: %Ecto.Association.NotLoaded{}} = c2.post
679
+ end
680
+
681
+ test "preload skips already loaded for cardinality many" do
682
+ p1 = TestRepo.insert!(%Post{title: "1"})
683
+ p2 = TestRepo.insert!(%Post{title: "2"})
684
+
685
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
686
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
687
+
688
+ [p1, p2] = TestRepo.preload([p1, p2], :comments)
689
+ assert [%Comment{id: ^cid1}] = p1.comments
690
+ assert [%Comment{id: ^cid2}] = p2.comments
691
+
692
+ [p1, p2] = TestRepo.preload([p1, p2], comments: :post)
693
+ assert hd(p1.comments).post.id == p1.id
694
+ assert hd(p2.comments).post.id == p2.id
695
+
696
+ TestRepo.update_all Comment, set: [text: "0"]
697
+
698
+ # Preloading once again shouldn't change the result
699
+ [p1, p2] = TestRepo.preload([p1, p2], :comments)
700
+ assert [%Comment{id: ^cid1, text: "1", post: %Post{}}] = p1.comments
701
+ assert [%Comment{id: ^cid2, text: "2", post: %Post{}}] = p2.comments
702
+
703
+ [p1, p2] = TestRepo.preload([p1, p2], :comments, force: true)
704
+ assert [%Comment{id: ^cid1, text: "0", post: %Ecto.Association.NotLoaded{}}] = p1.comments
705
+ assert [%Comment{id: ^cid2, text: "0", post: %Ecto.Association.NotLoaded{}}] = p2.comments
706
+ end
707
+
708
+ test "preload keyword query" do
709
+ p1 = TestRepo.insert!(%Post{title: "1"})
710
+ p2 = TestRepo.insert!(%Post{title: "2"})
711
+ TestRepo.insert!(%Post{title: "3"})
712
+
713
+ %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
714
+ %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
715
+ %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
716
+ %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "4", post_id: p2.id})
717
+
718
+ # Regular query
719
+ query = from(p in Post, preload: [:comments], select: p)
720
+
721
+ assert [p1, p2, p3] = TestRepo.all(query) |> sort_by_id
722
+ assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id
723
+ assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id
724
+ assert [] = p3.comments
725
+
726
+ # Query with interpolated preload query
727
+ query = from(p in Post, preload: [comments: ^from(c in Comment, where: false)], select: p)
728
+
729
+ assert [p1, p2, p3] = TestRepo.all(query)
730
+ assert [] = p1.comments
731
+ assert [] = p2.comments
732
+ assert [] = p3.comments
733
+
734
+ # Now let's use an interpolated preload too
735
+ comments = [:comments]
736
+ query = from(p in Post, preload: ^comments, select: {0, [p], 1, 2})
737
+
738
+ posts = TestRepo.all(query)
739
+ [p1, p2, p3] = Enum.map(posts, fn {0, [p], 1, 2} -> p end) |> sort_by_id
740
+
741
+ assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id
742
+ assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id
743
+ assert [] = p3.comments
744
+ end
745
+
746
+
747
+ test "preload belongs_to in embedded_schema" do
748
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
749
+ item = %Item{user_id: uid1}
750
+
751
+ # Starts as not loaded
752
+ assert %Ecto.Association.NotLoaded{} = item.user
753
+
754
+ # Now we preload it
755
+ item = TestRepo.preload(item, :user)
756
+ assert %User{id: ^uid1} = item.user
757
+ end
758
+
759
+ describe "preload associations from nested embeds" do
760
+ setup do
761
+ %User{id: uid1} = TestRepo.insert!(%User{name: "1"})
762
+ %User{id: uid2} = TestRepo.insert!(%User{name: "2"})
763
+ %User{id: uid3} = TestRepo.insert!(%User{name: "3"})
764
+ item1 = %Item{id: 1, user_id: uid1}
765
+ item2 = %Item{id: 2, user_id: uid2}
766
+ item3 = %Item{id: 3, user_id: uid3}
767
+ order1 = %Order{items: [item1, item3, item2], item: item1}
768
+ order2 = %Order{items: [], item: nil}
769
+ order3 = %Order{items: nil, item: nil}
770
+ order4 = %Order{items: [item1, item2], item: item2}
771
+
772
+ [orders: [order1, order2, order3, order4]]
773
+ end
774
+
775
+ test "cannot preload embed without its associations", context do
776
+ assert_raise ArgumentError, ~r/cannot preload embedded field/, fn ->
777
+ TestRepo.preload(context.orders, :item)
778
+ end
779
+ end
780
+
781
+ test "embeds_one", context do
782
+ [nil | preloaded_orders] = [nil | context.orders] |> TestRepo.preload(item: :user)
783
+
784
+ expected_item_user =
785
+ Enum.map(context.orders, fn
786
+ %{item: nil} -> {nil, nil}
787
+ %{item: item} -> {item.id, item.user_id}
788
+ end)
789
+
790
+ actual_item_user =
791
+ Enum.map(preloaded_orders, fn
792
+ %{item: nil} -> {nil, nil}
793
+ %{item: item} -> {item.id, item.user.id}
794
+ end)
795
+
796
+ assert expected_item_user == actual_item_user
797
+ end
798
+
799
+ test "embeds_many", context do
800
+ [nil | preloaded_orders] = [nil | context.orders] |> TestRepo.preload(items: :user)
801
+
802
+ expected_items_user =
803
+ Enum.map(context.orders, fn
804
+ %{items: nil} -> {nil, nil}
805
+ %{items: items} -> Enum.map(items, & {&1.id, &1.user_id})
806
+ end)
807
+
808
+ actual_items_user =
809
+ Enum.map(preloaded_orders, fn
810
+ %{items: nil} -> {nil, nil}
811
+ %{items: items} -> Enum.map(items, & {&1.id, &1.user.id})
812
+ end)
813
+
814
+ assert expected_items_user == actual_items_user
815
+ end
816
+ end
817
+
818
+ defp sort_by_id(values) do
819
+ Enum.sort_by(values, &(&1.id))
820
+ end
821
+ end
deps/ecto/integration_test/cases/repo.exs ADDED
@@ -0,0 +1,2267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.RepoTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.TestRepo
5
+ import Ecto.Query
6
+
7
+ alias Ecto.Integration.Post
8
+ alias Ecto.Integration.Order
9
+ alias Ecto.Integration.User
10
+ alias Ecto.Integration.Comment
11
+ alias Ecto.Integration.Permalink
12
+ alias Ecto.Integration.Custom
13
+ alias Ecto.Integration.Barebone
14
+ alias Ecto.Integration.CompositePk
15
+ alias Ecto.Integration.PostUserCompositePk
16
+
17
+ test "returns already started for started repos" do
18
+ assert {:error, {:already_started, _}} = TestRepo.start_link()
19
+ end
20
+
21
+ test "supports unnamed repos" do
22
+ assert {:ok, pid} = TestRepo.start_link(name: nil)
23
+ assert Ecto.Repo.Queryable.all(pid, Post, Ecto.Repo.Supervisor.tuplet(pid, [])) == []
24
+ end
25
+
26
+ test "all empty" do
27
+ assert TestRepo.all(Post) == []
28
+ assert TestRepo.all(from p in Post) == []
29
+ end
30
+
31
+ test "all with in" do
32
+ TestRepo.insert!(%Post{title: "hello"})
33
+
34
+ # Works without the query cache.
35
+ assert_raise Ecto.Query.CastError, fn ->
36
+ TestRepo.all(from p in Post, where: p.title in ^nil)
37
+ end
38
+
39
+ assert [] = TestRepo.all from p in Post, where: p.title in []
40
+ assert [] = TestRepo.all from p in Post, where: p.title in ["1", "2", "3"]
41
+ assert [] = TestRepo.all from p in Post, where: p.title in ^[]
42
+
43
+ assert [_] = TestRepo.all from p in Post, where: p.title not in []
44
+ assert [_] = TestRepo.all from p in Post, where: p.title in ["1", "hello", "3"]
45
+ assert [_] = TestRepo.all from p in Post, where: p.title in ["1", ^"hello", "3"]
46
+ assert [_] = TestRepo.all from p in Post, where: p.title in ^["1", "hello", "3"]
47
+
48
+ # Still doesn't work after the query cache.
49
+ assert_raise Ecto.Query.CastError, fn ->
50
+ TestRepo.all(from p in Post, where: p.title in ^nil)
51
+ end
52
+ end
53
+
54
+ test "all using named from" do
55
+ TestRepo.insert!(%Post{title: "hello"})
56
+
57
+ query =
58
+ from(p in Post, as: :post)
59
+ |> where([post: p], p.title == "hello")
60
+
61
+ assert [_] = TestRepo.all query
62
+ end
63
+
64
+ test "all without schema" do
65
+ %Post{} = TestRepo.insert!(%Post{title: "title1"})
66
+ %Post{} = TestRepo.insert!(%Post{title: "title2"})
67
+
68
+ assert ["title1", "title2"] =
69
+ TestRepo.all(from(p in "posts", order_by: p.title, select: p.title))
70
+
71
+ assert [_] =
72
+ TestRepo.all(from(p in "posts", where: p.title == "title1", select: p.id))
73
+ end
74
+
75
+ test "all shares metadata" do
76
+ TestRepo.insert!(%Post{title: "title1"})
77
+ TestRepo.insert!(%Post{title: "title2"})
78
+
79
+ [post1, post2] = TestRepo.all(Post)
80
+ assert :erts_debug.same(post1.__meta__, post2.__meta__)
81
+
82
+ [new_post1, new_post2] = TestRepo.all(Post)
83
+ assert :erts_debug.same(post1.__meta__, new_post1.__meta__)
84
+ assert :erts_debug.same(post2.__meta__, new_post2.__meta__)
85
+ end
86
+
87
+ @tag :invalid_prefix
88
+ test "all with invalid prefix" do
89
+ assert catch_error(TestRepo.all("posts", prefix: "oops"))
90
+ end
91
+
92
+ test "insert, update and delete" do
93
+ post = %Post{title: "insert, update, delete", visits: 1}
94
+ meta = post.__meta__
95
+
96
+ assert %Post{} = inserted = TestRepo.insert!(post)
97
+ assert %Post{} = updated = TestRepo.update!(Ecto.Changeset.change(inserted, visits: 2))
98
+
99
+ deleted_meta = put_in meta.state, :deleted
100
+ assert %Post{__meta__: ^deleted_meta} = TestRepo.delete!(updated)
101
+
102
+ loaded_meta = put_in meta.state, :loaded
103
+ assert %Post{__meta__: ^loaded_meta} = TestRepo.insert!(post)
104
+
105
+ post = TestRepo.one(Post)
106
+ assert post.__meta__.state == :loaded
107
+ assert post.inserted_at
108
+ end
109
+
110
+ test "insert, update and delete with field source" do
111
+ permalink = %Permalink{url: "url"}
112
+ assert %Permalink{url: "url"} = inserted =
113
+ TestRepo.insert!(permalink)
114
+ assert %Permalink{url: "new"} = updated =
115
+ TestRepo.update!(Ecto.Changeset.change(inserted, url: "new"))
116
+ assert %Permalink{url: "new"} =
117
+ TestRepo.delete!(updated)
118
+ end
119
+
120
+ @tag :composite_pk
121
+ test "insert, update and delete with composite pk" do
122
+ c1 = TestRepo.insert!(%CompositePk{a: 1, b: 2, name: "first"})
123
+ c2 = TestRepo.insert!(%CompositePk{a: 1, b: 3, name: "second"})
124
+
125
+ assert CompositePk |> first |> TestRepo.one == c1
126
+ assert CompositePk |> last |> TestRepo.one == c2
127
+
128
+ changeset = Ecto.Changeset.cast(c1, %{name: "first change"}, ~w(name)a)
129
+ c1 = TestRepo.update!(changeset)
130
+ assert TestRepo.get_by!(CompositePk, %{a: 1, b: 2}) == c1
131
+
132
+ TestRepo.delete!(c2)
133
+ assert TestRepo.all(CompositePk) == [c1]
134
+
135
+ assert_raise ArgumentError, ~r"to have exactly one primary key", fn ->
136
+ TestRepo.get(CompositePk, [])
137
+ end
138
+
139
+ assert_raise ArgumentError, ~r"to have exactly one primary key", fn ->
140
+ TestRepo.get!(CompositePk, [1, 2])
141
+ end
142
+ end
143
+
144
+ @tag :composite_pk
145
+ test "insert, update and delete with associated composite pk" do
146
+ user = TestRepo.insert!(%User{})
147
+ post = TestRepo.insert!(%Post{title: "post title"})
148
+
149
+ user_post = TestRepo.insert!(%PostUserCompositePk{user_id: user.id, post_id: post.id})
150
+ assert TestRepo.get_by!(PostUserCompositePk, [user_id: user.id, post_id: post.id]) == user_post
151
+ TestRepo.delete!(user_post)
152
+ assert TestRepo.all(PostUserCompositePk) == []
153
+ end
154
+
155
+ @tag :invalid_prefix
156
+ test "insert, update and delete with invalid prefix" do
157
+ post = TestRepo.insert!(%Post{})
158
+ changeset = Ecto.Changeset.change(post, title: "foo")
159
+ assert catch_error(TestRepo.insert(%Post{}, prefix: "oops"))
160
+ assert catch_error(TestRepo.update(changeset, prefix: "oops"))
161
+ assert catch_error(TestRepo.delete(changeset, prefix: "oops"))
162
+
163
+ # Check we can still insert the post after the invalid prefix attempt
164
+ assert %Post{id: _} = TestRepo.insert!(%Post{})
165
+ end
166
+
167
+ test "insert and update with changeset" do
168
+ # On insert we merge the fields and changes
169
+ changeset = Ecto.Changeset.cast(%Post{visits: 13, title: "wrong"},
170
+ %{"title" => "hello", "temp" => "unknown"}, ~w(title temp)a)
171
+
172
+ post = TestRepo.insert!(changeset)
173
+ assert %Post{visits: 13, title: "hello", temp: "unknown"} = post
174
+ assert %Post{visits: 13, title: "hello", temp: "temp"} = TestRepo.get!(Post, post.id)
175
+
176
+ # On update we merge only fields, direct schema changes are discarded
177
+ changeset = Ecto.Changeset.cast(%{post | visits: 17},
178
+ %{"title" => "world", "temp" => "unknown"}, ~w(title temp)a)
179
+
180
+ assert %Post{visits: 17, title: "world", temp: "unknown"} = TestRepo.update!(changeset)
181
+ assert %Post{visits: 13, title: "world", temp: "temp"} = TestRepo.get!(Post, post.id)
182
+ end
183
+
184
+ test "insert and update with empty changeset" do
185
+ # On insert we merge the fields and changes
186
+ changeset = Ecto.Changeset.cast(%Permalink{}, %{}, ~w())
187
+ assert %Permalink{} = permalink = TestRepo.insert!(changeset)
188
+
189
+ # Assert we can update the same value twice,
190
+ # without changes, without triggering stale errors.
191
+ changeset = Ecto.Changeset.cast(permalink, %{}, ~w())
192
+ assert TestRepo.update!(changeset) == permalink
193
+ assert TestRepo.update!(changeset) == permalink
194
+ end
195
+
196
+ @tag :no_primary_key
197
+ test "insert with no primary key" do
198
+ assert %Barebone{num: nil} = TestRepo.insert!(%Barebone{})
199
+ assert %Barebone{num: 13} = TestRepo.insert!(%Barebone{num: 13})
200
+ end
201
+
202
+ @tag :read_after_writes
203
+ test "insert and update with changeset read after writes" do
204
+ defmodule RAW do
205
+ use Ecto.Schema
206
+
207
+ schema "comments" do
208
+ field :text, :string
209
+ field :lock_version, :integer, read_after_writes: true
210
+ end
211
+ end
212
+
213
+ changeset = Ecto.Changeset.cast(struct(RAW, %{}), %{}, ~w())
214
+
215
+ # If the field is nil, we will not send it
216
+ # and read the value back from the database.
217
+ assert %{id: cid, lock_version: 1} = raw = TestRepo.insert!(changeset)
218
+
219
+ # Set the counter to 11, so we can read it soon
220
+ TestRepo.update_all from(u in RAW, where: u.id == ^cid), set: [lock_version: 11]
221
+
222
+ # We will read back on update too
223
+ changeset = Ecto.Changeset.cast(raw, %{"text" => "0"}, ~w(text)a)
224
+ assert %{id: ^cid, lock_version: 11, text: "0"} = TestRepo.update!(changeset)
225
+ end
226
+
227
+ test "insert autogenerates for custom type" do
228
+ post = TestRepo.insert!(%Post{uuid: nil})
229
+ assert byte_size(post.uuid) == 36
230
+ assert TestRepo.get_by(Post, uuid: post.uuid) == post
231
+ end
232
+
233
+ @tag :id_type
234
+ test "insert autogenerates for custom id type" do
235
+ defmodule ID do
236
+ use Ecto.Schema
237
+
238
+ @primary_key {:id, CustomPermalink, autogenerate: true}
239
+ schema "posts" do
240
+ end
241
+ end
242
+
243
+ id = TestRepo.insert!(struct(ID, id: nil))
244
+ assert id.id
245
+ assert TestRepo.get_by(ID, id: "#{id.id}-hello") == id
246
+ end
247
+
248
+ @tag :id_type
249
+ @tag :assigns_id_type
250
+ test "insert with user-assigned primary key" do
251
+ assert %Post{id: 1} = TestRepo.insert!(%Post{id: 1})
252
+ end
253
+
254
+ @tag :id_type
255
+ @tag :assigns_id_type
256
+ test "insert and update with user-assigned primary key in changeset" do
257
+ changeset = Ecto.Changeset.cast(%Post{id: 11}, %{"id" => "13"}, ~w(id)a)
258
+ assert %Post{id: 13} = post = TestRepo.insert!(changeset)
259
+
260
+ changeset = Ecto.Changeset.cast(post, %{"id" => "15"}, ~w(id)a)
261
+ assert %Post{id: 15} = TestRepo.update!(changeset)
262
+ end
263
+
264
+ test "insert and fetch a schema with utc timestamps" do
265
+ datetime = DateTime.from_unix!(System.os_time(:second), :second)
266
+ TestRepo.insert!(%User{inserted_at: datetime})
267
+ assert [%{inserted_at: ^datetime}] = TestRepo.all(User)
268
+ end
269
+
270
+ test "optimistic locking in update/delete operations" do
271
+ import Ecto.Changeset, only: [cast: 3, optimistic_lock: 2]
272
+ base_comment = TestRepo.insert!(%Comment{})
273
+
274
+ changeset_ok =
275
+ base_comment
276
+ |> cast(%{"text" => "foo.bar"}, ~w(text)a)
277
+ |> optimistic_lock(:lock_version)
278
+ TestRepo.update!(changeset_ok)
279
+
280
+ changeset_stale =
281
+ base_comment
282
+ |> cast(%{"text" => "foo.bat"}, ~w(text)a)
283
+ |> optimistic_lock(:lock_version)
284
+
285
+ assert_raise Ecto.StaleEntryError, fn -> TestRepo.update!(changeset_stale) end
286
+ assert_raise Ecto.StaleEntryError, fn -> TestRepo.delete!(changeset_stale) end
287
+ end
288
+
289
+ test "optimistic locking in update operation with nil field" do
290
+ import Ecto.Changeset, only: [cast: 3, optimistic_lock: 3]
291
+
292
+ base_comment =
293
+ %Comment{}
294
+ |> cast(%{lock_version: nil}, [:lock_version])
295
+ |> TestRepo.insert!()
296
+
297
+ incrementer =
298
+ fn
299
+ nil -> 1
300
+ old_value -> old_value + 1
301
+ end
302
+
303
+ changeset_ok =
304
+ base_comment
305
+ |> cast(%{"text" => "foo.bar"}, ~w(text)a)
306
+ |> optimistic_lock(:lock_version, incrementer)
307
+
308
+ updated = TestRepo.update!(changeset_ok)
309
+ assert updated.text == "foo.bar"
310
+ assert updated.lock_version == 1
311
+ end
312
+
313
+ test "optimistic locking in delete operation with nil field" do
314
+ import Ecto.Changeset, only: [cast: 3, optimistic_lock: 3]
315
+
316
+ base_comment =
317
+ %Comment{}
318
+ |> cast(%{lock_version: nil}, [:lock_version])
319
+ |> TestRepo.insert!()
320
+
321
+ incrementer =
322
+ fn
323
+ nil -> 1
324
+ old_value -> old_value + 1
325
+ end
326
+
327
+ changeset_ok = optimistic_lock(base_comment, :lock_version, incrementer)
328
+ TestRepo.delete!(changeset_ok)
329
+
330
+ refute TestRepo.get(Comment, base_comment.id)
331
+ end
332
+
333
+ @tag :unique_constraint
334
+ test "unique constraint" do
335
+ changeset = Ecto.Changeset.change(%Post{}, uuid: Ecto.UUID.generate())
336
+ {:ok, _} = TestRepo.insert(changeset)
337
+
338
+ exception =
339
+ assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn ->
340
+ changeset
341
+ |> TestRepo.insert()
342
+ end
343
+
344
+ assert exception.message =~ "\"posts_uuid_index\" (unique_constraint)"
345
+ assert exception.message =~ "The changeset has not defined any constraint."
346
+ assert exception.message =~ "call `unique_constraint/3`"
347
+
348
+ message = ~r/constraint error when attempting to insert struct/
349
+ exception =
350
+ assert_raise Ecto.ConstraintError, message, fn ->
351
+ changeset
352
+ |> Ecto.Changeset.unique_constraint(:uuid, name: :posts_email_changeset)
353
+ |> TestRepo.insert()
354
+ end
355
+
356
+ assert exception.message =~ "\"posts_email_changeset\" (unique_constraint)"
357
+
358
+ {:error, changeset} =
359
+ changeset
360
+ |> Ecto.Changeset.unique_constraint(:uuid)
361
+ |> TestRepo.insert()
362
+ assert changeset.errors == [uuid: {"has already been taken", [constraint: :unique, constraint_name: "posts_uuid_index"]}]
363
+ assert changeset.data.__meta__.state == :built
364
+ end
365
+
366
+ @tag :unique_constraint
367
+ test "unique constraint from association" do
368
+ uuid = Ecto.UUID.generate()
369
+ post = & %Post{} |> Ecto.Changeset.change(uuid: &1) |> Ecto.Changeset.unique_constraint(:uuid)
370
+
371
+ {:error, changeset} =
372
+ TestRepo.insert %User{
373
+ comments: [%Comment{}],
374
+ permalink: %Permalink{},
375
+ posts: [post.(uuid), post.(uuid), post.(Ecto.UUID.generate())]
376
+ }
377
+
378
+ [_, p2, _] = changeset.changes.posts
379
+ assert p2.errors == [uuid: {"has already been taken", [constraint: :unique, constraint_name: "posts_uuid_index"]}]
380
+ end
381
+
382
+ @tag :id_type
383
+ @tag :unique_constraint
384
+ test "unique constraint with binary_id" do
385
+ changeset = Ecto.Changeset.change(%Custom{}, uuid: Ecto.UUID.generate())
386
+ {:ok, _} = TestRepo.insert(changeset)
387
+
388
+ {:error, changeset} =
389
+ changeset
390
+ |> Ecto.Changeset.unique_constraint(:uuid)
391
+ |> TestRepo.insert()
392
+ assert changeset.errors == [uuid: {"has already been taken", [constraint: :unique, constraint_name: "customs_uuid_index"]}]
393
+ assert changeset.data.__meta__.state == :built
394
+ end
395
+
396
+ test "unique pseudo-constraint violation error message with join table at the repository" do
397
+ post =
398
+ TestRepo.insert!(%Post{title: "some post"})
399
+ |> TestRepo.preload(:unique_users)
400
+
401
+ user =
402
+ TestRepo.insert!(%User{name: "some user"})
403
+
404
+ # Violate the unique composite index
405
+ {:error, changeset} =
406
+ post
407
+ |> Ecto.Changeset.change
408
+ |> Ecto.Changeset.put_assoc(:unique_users, [user, user])
409
+ |> TestRepo.update
410
+
411
+ errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
412
+ assert errors == %{unique_users: [%{}, %{id: ["has already been taken"]}]}
413
+ refute changeset.valid?
414
+ end
415
+
416
+ @tag :join
417
+ @tag :unique_constraint
418
+ test "unique constraint violation error message with join table in single changeset" do
419
+ post =
420
+ TestRepo.insert!(%Post{title: "some post"})
421
+ |> TestRepo.preload(:constraint_users)
422
+
423
+ user =
424
+ TestRepo.insert!(%User{name: "some user"})
425
+
426
+ # Violate the unique composite index
427
+ {:error, changeset} =
428
+ post
429
+ |> Ecto.Changeset.change
430
+ |> Ecto.Changeset.put_assoc(:constraint_users, [user, user])
431
+ |> Ecto.Changeset.unique_constraint(:user,
432
+ name: :posts_users_composite_pk_post_id_user_id_index,
433
+ message: "has already been assigned")
434
+ |> TestRepo.update
435
+
436
+ errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
437
+ assert errors == %{constraint_users: [%{}, %{user: ["has already been assigned"]}]}
438
+
439
+ refute changeset.valid?
440
+ end
441
+
442
+ @tag :join
443
+ @tag :unique_constraint
444
+ test "unique constraint violation error message with join table and separate changesets" do
445
+ post =
446
+ TestRepo.insert!(%Post{title: "some post"})
447
+ |> TestRepo.preload(:constraint_users)
448
+
449
+ user = TestRepo.insert!(%User{name: "some user"})
450
+
451
+ post
452
+ |> Ecto.Changeset.change
453
+ |> Ecto.Changeset.put_assoc(:constraint_users, [user])
454
+ |> TestRepo.update
455
+
456
+ # Violate the unique composite index
457
+ {:error, changeset} =
458
+ post
459
+ |> Ecto.Changeset.change
460
+ |> Ecto.Changeset.put_assoc(:constraint_users, [user])
461
+ |> Ecto.Changeset.unique_constraint(:user,
462
+ name: :posts_users_composite_pk_post_id_user_id_index,
463
+ message: "has already been assigned")
464
+ |> TestRepo.update
465
+
466
+ errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
467
+ assert errors == %{constraint_users: [%{user: ["has already been assigned"]}]}
468
+
469
+ refute changeset.valid?
470
+ end
471
+
472
+ @tag :foreign_key_constraint
473
+ test "foreign key constraint" do
474
+ changeset = Ecto.Changeset.change(%Comment{post_id: 0})
475
+
476
+ exception =
477
+ assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn ->
478
+ changeset
479
+ |> TestRepo.insert()
480
+ end
481
+
482
+ assert exception.message =~ "\"comments_post_id_fkey\" (foreign_key_constraint)"
483
+ assert exception.message =~ "The changeset has not defined any constraint."
484
+ assert exception.message =~ "call `foreign_key_constraint/3`"
485
+
486
+ message = ~r/constraint error when attempting to insert struct/
487
+ exception =
488
+ assert_raise Ecto.ConstraintError, message, fn ->
489
+ changeset
490
+ |> Ecto.Changeset.foreign_key_constraint(:post_id, name: :comments_post_id_other)
491
+ |> TestRepo.insert()
492
+ end
493
+
494
+ assert exception.message =~ "\"comments_post_id_other\" (foreign_key_constraint)"
495
+
496
+ {:error, changeset} =
497
+ changeset
498
+ |> Ecto.Changeset.foreign_key_constraint(:post_id)
499
+ |> TestRepo.insert()
500
+ assert changeset.errors == [post_id: {"does not exist", [constraint: :foreign, constraint_name: "comments_post_id_fkey"]}]
501
+ end
502
+
503
+ @tag :foreign_key_constraint
504
+ test "assoc constraint" do
505
+ changeset = Ecto.Changeset.change(%Comment{post_id: 0})
506
+
507
+ exception =
508
+ assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn ->
509
+ changeset
510
+ |> TestRepo.insert()
511
+ end
512
+
513
+ assert exception.message =~ "\"comments_post_id_fkey\" (foreign_key_constraint)"
514
+ assert exception.message =~ "The changeset has not defined any constraint."
515
+
516
+ message = ~r/constraint error when attempting to insert struct/
517
+ exception =
518
+ assert_raise Ecto.ConstraintError, message, fn ->
519
+ changeset
520
+ |> Ecto.Changeset.assoc_constraint(:post, name: :comments_post_id_other)
521
+ |> TestRepo.insert()
522
+ end
523
+
524
+ assert exception.message =~ "\"comments_post_id_other\" (foreign_key_constraint)"
525
+
526
+ {:error, changeset} =
527
+ changeset
528
+ |> Ecto.Changeset.assoc_constraint(:post)
529
+ |> TestRepo.insert()
530
+ assert changeset.errors == [post: {"does not exist", [constraint: :assoc, constraint_name: "comments_post_id_fkey"]}]
531
+ end
532
+
533
+ @tag :foreign_key_constraint
534
+ test "no assoc constraint error" do
535
+ user = TestRepo.insert!(%User{})
536
+ TestRepo.insert!(%Permalink{user_id: user.id})
537
+
538
+ exception =
539
+ assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to delete struct/, fn ->
540
+ TestRepo.delete!(user)
541
+ end
542
+
543
+ assert exception.message =~ "\"permalinks_user_id_fkey\" (foreign_key_constraint)"
544
+ assert exception.message =~ "The changeset has not defined any constraint."
545
+ end
546
+
547
+ @tag :foreign_key_constraint
548
+ test "no assoc constraint with changeset mismatch" do
549
+ user = TestRepo.insert!(%User{})
550
+ TestRepo.insert!(%Permalink{user_id: user.id})
551
+
552
+ message = ~r/constraint error when attempting to delete struct/
553
+ exception =
554
+ assert_raise Ecto.ConstraintError, message, fn ->
555
+ user
556
+ |> Ecto.Changeset.change
557
+ |> Ecto.Changeset.no_assoc_constraint(:permalink, name: :permalinks_user_id_pther)
558
+ |> TestRepo.delete()
559
+ end
560
+
561
+ assert exception.message =~ "\"permalinks_user_id_pther\" (foreign_key_constraint)"
562
+ end
563
+
564
+ @tag :foreign_key_constraint
565
+ test "no assoc constraint with changeset match" do
566
+ user = TestRepo.insert!(%User{})
567
+ TestRepo.insert!(%Permalink{user_id: user.id})
568
+
569
+ {:error, changeset} =
570
+ user
571
+ |> Ecto.Changeset.change
572
+ |> Ecto.Changeset.no_assoc_constraint(:permalink)
573
+ |> TestRepo.delete()
574
+ assert changeset.errors == [permalink: {"is still associated with this entry", [constraint: :no_assoc, constraint_name: "permalinks_user_id_fkey"]}]
575
+ end
576
+
577
+ @tag :foreign_key_constraint
578
+ test "insert and update with embeds during failing child foreign key" do
579
+ changeset =
580
+ Order
581
+ |> struct(%{})
582
+ |> order_changeset(%{item: %{price: 10}, permalink: %{post_id: 0}})
583
+
584
+ {:error, changeset} = TestRepo.insert(changeset)
585
+ assert %Ecto.Changeset{} = changeset.changes.item
586
+
587
+ order =
588
+ Order
589
+ |> struct(%{})
590
+ |> order_changeset(%{})
591
+ |> TestRepo.insert!()
592
+ |> TestRepo.preload([:permalink])
593
+
594
+ changeset = order_changeset(order, %{item: %{price: 10}, permalink: %{post_id: 0}})
595
+ assert %Ecto.Changeset{} = changeset.changes.item
596
+
597
+ {:error, changeset} = TestRepo.update(changeset)
598
+ assert %Ecto.Changeset{} = changeset.changes.item
599
+ end
600
+
601
+ def order_changeset(order, params) do
602
+ order
603
+ |> Ecto.Changeset.cast(params, [:permalink_id])
604
+ |> Ecto.Changeset.cast_embed(:item, with: &item_changeset/2)
605
+ |> Ecto.Changeset.cast_assoc(:permalink, with: &permalink_changeset/2)
606
+ end
607
+
608
+ def item_changeset(item, params) do
609
+ item
610
+ |> Ecto.Changeset.cast(params, [:price])
611
+ end
612
+
613
+ def permalink_changeset(comment, params) do
614
+ comment
615
+ |> Ecto.Changeset.cast(params, [:post_id])
616
+ |> Ecto.Changeset.assoc_constraint(:post)
617
+ end
618
+
619
+ test "unsafe_validate_unique/4" do
620
+ {:ok, inserted_post} = TestRepo.insert(%Post{title: "Greetings", visits: 13})
621
+ new_post_changeset = Post.changeset(%Post{}, %{title: "Greetings", visits: 17})
622
+
623
+ changeset = Ecto.Changeset.unsafe_validate_unique(new_post_changeset, [:title], TestRepo)
624
+ assert changeset.errors[:title] ==
625
+ {"has already been taken", validation: :unsafe_unique, fields: [:title]}
626
+
627
+ changeset = Ecto.Changeset.unsafe_validate_unique(new_post_changeset, [:title, :text], TestRepo)
628
+ assert changeset.errors[:title] == nil
629
+
630
+ update_changeset = Post.changeset(inserted_post, %{visits: 17})
631
+ changeset = Ecto.Changeset.unsafe_validate_unique(update_changeset, [:title], TestRepo)
632
+ assert changeset.errors[:title] == nil # cannot conflict with itself
633
+ end
634
+
635
+ test "unsafe_validate_unique/4 with composite keys" do
636
+ {:ok, inserted_post} = TestRepo.insert(%CompositePk{a: 123, b: 456, name: "UniqueName"})
637
+
638
+ different_pk = CompositePk.changeset(%CompositePk{}, %{name: "UniqueName", a: 789, b: 321})
639
+ changeset = Ecto.Changeset.unsafe_validate_unique(different_pk, [:name], TestRepo)
640
+ assert changeset.errors[:name] ==
641
+ {"has already been taken", validation: :unsafe_unique, fields: [:name]}
642
+
643
+ partial_pk = CompositePk.changeset(%CompositePk{}, %{name: "UniqueName", a: 789, b: 456})
644
+ changeset = Ecto.Changeset.unsafe_validate_unique(partial_pk, [:name], TestRepo)
645
+ assert changeset.errors[:name] ==
646
+ {"has already been taken", validation: :unsafe_unique, fields: [:name]}
647
+
648
+ update_changeset = CompositePk.changeset(inserted_post, %{name: "NewName"})
649
+ changeset = Ecto.Changeset.unsafe_validate_unique(update_changeset, [:name], TestRepo)
650
+ assert changeset.valid?
651
+ assert changeset.errors[:name] == nil # cannot conflict with itself
652
+ end
653
+
654
+ test "get(!)" do
655
+ post1 = TestRepo.insert!(%Post{title: "1"})
656
+ post2 = TestRepo.insert!(%Post{title: "2"})
657
+
658
+ assert post1 == TestRepo.get(Post, post1.id)
659
+ assert post2 == TestRepo.get(Post, to_string post2.id) # With casting
660
+
661
+ assert post1 == TestRepo.get!(Post, post1.id)
662
+ assert post2 == TestRepo.get!(Post, to_string post2.id) # With casting
663
+
664
+ TestRepo.delete!(post1)
665
+
666
+ assert TestRepo.get(Post, post1.id) == nil
667
+ assert_raise Ecto.NoResultsError, fn ->
668
+ TestRepo.get!(Post, post1.id)
669
+ end
670
+ end
671
+
672
+ test "get(!) with custom source" do
673
+ custom = Ecto.put_meta(%Custom{}, source: "posts")
674
+ custom = TestRepo.insert!(custom)
675
+ bid = custom.bid
676
+ assert %Custom{bid: ^bid, __meta__: %{source: "posts"}} =
677
+ TestRepo.get(from(c in {"posts", Custom}), bid)
678
+ end
679
+
680
+ test "get(!) with binary_id" do
681
+ custom = TestRepo.insert!(%Custom{})
682
+ bid = custom.bid
683
+ assert %Custom{bid: ^bid} = TestRepo.get(Custom, bid)
684
+ end
685
+
686
+ test "get_by(!)" do
687
+ post1 = TestRepo.insert!(%Post{title: "1", visits: 1})
688
+ post2 = TestRepo.insert!(%Post{title: "2", visits: 2})
689
+
690
+ assert post1 == TestRepo.get_by(Post, id: post1.id)
691
+ assert post1 == TestRepo.get_by(Post, title: post1.title)
692
+ assert post1 == TestRepo.get_by(Post, id: post1.id, title: post1.title)
693
+ assert post2 == TestRepo.get_by(Post, id: to_string(post2.id)) # With casting
694
+ assert nil == TestRepo.get_by(Post, title: "hey")
695
+ assert nil == TestRepo.get_by(Post, id: post2.id, visits: 3)
696
+
697
+ assert post1 == TestRepo.get_by!(Post, id: post1.id)
698
+ assert post1 == TestRepo.get_by!(Post, title: post1.title)
699
+ assert post1 == TestRepo.get_by!(Post, id: post1.id, visits: 1)
700
+ assert post2 == TestRepo.get_by!(Post, id: to_string(post2.id)) # With casting
701
+
702
+ assert post1 == TestRepo.get_by!(Post, %{id: post1.id})
703
+
704
+ assert_raise Ecto.NoResultsError, fn ->
705
+ TestRepo.get_by!(Post, id: post2.id, title: "hey")
706
+ end
707
+ end
708
+
709
+ test "reload" do
710
+ post1 = TestRepo.insert!(%Post{title: "1", visits: 1})
711
+ post2 = TestRepo.insert!(%Post{title: "2", visits: 2})
712
+
713
+ assert post1 == TestRepo.reload(post1)
714
+ assert [post1, post2] == TestRepo.reload([post1, post2])
715
+ assert [post1, post2, nil] == TestRepo.reload([post1, post2, %Post{id: 0}])
716
+ assert nil == TestRepo.reload(%Post{id: 0})
717
+
718
+ # keeps order as received in the params
719
+ assert [post2, post1] == TestRepo.reload([post2, post1])
720
+
721
+ TestRepo.update_all(Post, inc: [visits: 1])
722
+
723
+ assert [%{visits: 2}, %{visits: 3}] = TestRepo.reload([post1, post2])
724
+ end
725
+
726
+ test "reload ignores preloads" do
727
+ post = TestRepo.insert!(%Post{title: "1", visits: 1}) |> TestRepo.preload(:comments)
728
+
729
+ assert %{comments: %Ecto.Association.NotLoaded{}} = TestRepo.reload(post)
730
+ end
731
+
732
+ test "reload!" do
733
+ post1 = TestRepo.insert!(%Post{title: "1", visits: 1})
734
+ post2 = TestRepo.insert!(%Post{title: "2", visits: 2})
735
+
736
+ assert post1 == TestRepo.reload!(post1)
737
+ assert [post1, post2] == TestRepo.reload!([post1, post2])
738
+
739
+ assert_raise RuntimeError, ~r"could not reload", fn ->
740
+ TestRepo.reload!([post1, post2, %Post{id: -1}])
741
+ end
742
+
743
+ assert_raise Ecto.NoResultsError, fn ->
744
+ TestRepo.reload!(%Post{id: -1})
745
+ end
746
+
747
+ assert [post2, post1] == TestRepo.reload([post2, post1])
748
+
749
+ TestRepo.update_all(Post, inc: [visits: 1])
750
+
751
+ assert [%{visits: 2}, %{visits: 3}] = TestRepo.reload!([post1, post2])
752
+ end
753
+
754
+ test "first, last and one(!)" do
755
+ post1 = TestRepo.insert!(%Post{title: "1"})
756
+ post2 = TestRepo.insert!(%Post{title: "2"})
757
+
758
+ assert post1 == Post |> first |> TestRepo.one
759
+ assert post2 == Post |> last |> TestRepo.one
760
+
761
+ query = from p in Post, order_by: p.title
762
+ assert post1 == query |> first |> TestRepo.one
763
+ assert post2 == query |> last |> TestRepo.one
764
+
765
+ query = from p in Post, order_by: [desc: p.title], limit: 10
766
+ assert post2 == query |> first |> TestRepo.one
767
+ assert post1 == query |> last |> TestRepo.one
768
+
769
+ query = from p in Post, where: is_nil(p.id)
770
+ refute query |> first |> TestRepo.one
771
+ refute query |> last |> TestRepo.one
772
+ assert_raise Ecto.NoResultsError, fn -> query |> first |> TestRepo.one! end
773
+ assert_raise Ecto.NoResultsError, fn -> query |> last |> TestRepo.one! end
774
+ end
775
+
776
+ test "exists?" do
777
+ TestRepo.insert!(%Post{title: "1", visits: 2})
778
+ TestRepo.insert!(%Post{title: "2", visits: 1})
779
+
780
+ query = from p in Post, where: not is_nil(p.title), limit: 2
781
+ assert query |> TestRepo.exists? == true
782
+
783
+ query = from p in Post, where: p.title == "1", select: p.title
784
+ assert query |> TestRepo.exists? == true
785
+
786
+ query = from p in Post, where: is_nil(p.id)
787
+ assert query |> TestRepo.exists? == false
788
+
789
+ query = from p in Post, where: is_nil(p.id)
790
+ assert query |> TestRepo.exists? == false
791
+
792
+ query = from(p in Post, select: {p.visits, avg(p.visits)}, group_by: p.visits, having: avg(p.visits) > 1)
793
+ assert query |> TestRepo.exists? == true
794
+ end
795
+
796
+ test "aggregate" do
797
+ assert TestRepo.aggregate(Post, :max, :visits) == nil
798
+
799
+ TestRepo.insert!(%Post{visits: 10})
800
+ TestRepo.insert!(%Post{visits: 12})
801
+ TestRepo.insert!(%Post{visits: 14})
802
+ TestRepo.insert!(%Post{visits: 14})
803
+
804
+ # Barebones
805
+ assert TestRepo.aggregate(Post, :max, :visits) == 14
806
+ assert TestRepo.aggregate(Post, :min, :visits) == 10
807
+ assert TestRepo.aggregate(Post, :count, :visits) == 4
808
+ assert "50" = to_string(TestRepo.aggregate(Post, :sum, :visits))
809
+
810
+ # With order_by
811
+ query = from Post, order_by: [asc: :visits]
812
+ assert TestRepo.aggregate(query, :max, :visits) == 14
813
+
814
+ # With order_by and limit
815
+ query = from Post, order_by: [asc: :visits], limit: 2
816
+ assert TestRepo.aggregate(query, :max, :visits) == 12
817
+ end
818
+
819
+ @tag :decimal_precision
820
+ test "aggregate avg" do
821
+ TestRepo.insert!(%Post{visits: 10})
822
+ TestRepo.insert!(%Post{visits: 12})
823
+ TestRepo.insert!(%Post{visits: 14})
824
+ TestRepo.insert!(%Post{visits: 14})
825
+
826
+ assert "12.5" <> _ = to_string(TestRepo.aggregate(Post, :avg, :visits))
827
+ end
828
+
829
+ @tag :inline_order_by
830
+ test "aggregate with distinct" do
831
+ TestRepo.insert!(%Post{visits: 10})
832
+ TestRepo.insert!(%Post{visits: 12})
833
+ TestRepo.insert!(%Post{visits: 14})
834
+ TestRepo.insert!(%Post{visits: 14})
835
+
836
+ query = from Post, order_by: [asc: :visits], distinct: true
837
+ assert TestRepo.aggregate(query, :count, :visits) == 3
838
+ end
839
+
840
+ @tag :insert_cell_wise_defaults
841
+ test "insert all" do
842
+ assert {2, nil} = TestRepo.insert_all("comments", [[text: "1"], %{text: "2", lock_version: 2}])
843
+ assert {2, nil} = TestRepo.insert_all({"comments", Comment}, [[text: "3"], %{text: "4", lock_version: 2}])
844
+ assert [%Comment{text: "1", lock_version: 1},
845
+ %Comment{text: "2", lock_version: 2},
846
+ %Comment{text: "3", lock_version: 1},
847
+ %Comment{text: "4", lock_version: 2}] = TestRepo.all(Comment)
848
+
849
+ assert {2, nil} = TestRepo.insert_all(Post, [[], []])
850
+ assert [%Post{}, %Post{}] = TestRepo.all(Post)
851
+
852
+ assert {0, nil} = TestRepo.insert_all("posts", [])
853
+ assert {0, nil} = TestRepo.insert_all({"posts", Post}, [])
854
+ end
855
+
856
+ @tag :insert_select
857
+ test "insert all with query for single fields" do
858
+ comment = TestRepo.insert!(%Comment{text: "1", lock_version: 1})
859
+
860
+ text_query = from(c in Comment, select: c.text, where: [id: ^comment.id, lock_version: 1])
861
+
862
+ lock_version_query = from(c in Comment, select: c.lock_version, where: [id: ^comment.id])
863
+
864
+ rows = [
865
+ [text: "2", lock_version: lock_version_query],
866
+ [lock_version: lock_version_query, text: "3"],
867
+ [text: text_query],
868
+ [text: text_query, lock_version: lock_version_query],
869
+ [lock_version: 6, text: "6"]
870
+ ]
871
+ assert {5, nil} = TestRepo.insert_all(Comment, rows, [])
872
+
873
+ inserted_rows = Comment
874
+ |> where([c], c.id != ^comment.id)
875
+ |> TestRepo.all()
876
+
877
+ assert [%Comment{text: "2", lock_version: 1},
878
+ %Comment{text: "3", lock_version: 1},
879
+ %Comment{text: "1"},
880
+ %Comment{text: "1", lock_version: 1},
881
+ %Comment{text: "6", lock_version: 6}] = inserted_rows
882
+ end
883
+
884
+ describe "insert_all with source query" do
885
+ @tag :upsert_all
886
+ @tag :with_conflict_target
887
+ @tag :concat
888
+ test "insert_all with query and conflict target" do
889
+ {:ok, %Post{id: id}} = TestRepo.insert(%Post{
890
+ title: "A generic title"
891
+ })
892
+
893
+ source = from p in Post,
894
+ select: %{
895
+ title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id)
896
+ }
897
+
898
+ assert {1, _} = TestRepo.insert_all(Post, source, conflict_target: [:id], on_conflict: :replace_all)
899
+
900
+ expected_id = id + 1
901
+ expected_title = "A generic title suffix #{id}"
902
+
903
+ assert %Post{title: ^expected_title} = TestRepo.get(Post, expected_id)
904
+ end
905
+
906
+ @tag :returning
907
+ @tag :concat
908
+ test "insert_all with query and returning" do
909
+ {:ok, %Post{id: id}} = TestRepo.insert(%Post{
910
+ title: "A generic title"
911
+ })
912
+
913
+ source = from p in Post,
914
+ select: %{
915
+ title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id)
916
+ }
917
+
918
+ assert {1, returns} = TestRepo.insert_all(Post, source, returning: [:id, :title])
919
+
920
+ expected_id = id + 1
921
+ expected_title = "A generic title suffix #{id}"
922
+ assert [%Post{id: ^expected_id, title: ^expected_title}] = returns
923
+ end
924
+
925
+ @tag :upsert_all
926
+ @tag :without_conflict_target
927
+ @tag :concat
928
+ test "insert_all with query and on_conflict" do
929
+ {:ok, %Post{id: id}} = TestRepo.insert(%Post{
930
+ title: "A generic title"
931
+ })
932
+
933
+ source = from p in Post,
934
+ select: %{
935
+ title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id)
936
+ }
937
+
938
+ assert {1, _} = TestRepo.insert_all(Post, source, on_conflict: :replace_all)
939
+
940
+ expected_id = id + 1
941
+ expected_title = "A generic title suffix #{id}"
942
+
943
+ assert %Post{title: ^expected_title} = TestRepo.get(Post, expected_id)
944
+ end
945
+
946
+ @tag :concat
947
+ test "insert_all with query" do
948
+ {:ok, %Post{id: id}} = TestRepo.insert(%Post{
949
+ title: "A generic title"
950
+ })
951
+
952
+ source = from p in Post,
953
+ select: %{
954
+ title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id)
955
+ }
956
+
957
+ assert {1, _} = TestRepo.insert_all(Post, source)
958
+
959
+ expected_id = id + 1
960
+ expected_title = "A generic title suffix #{id}"
961
+
962
+ assert %Post{title: ^expected_title} = TestRepo.get(Post, expected_id)
963
+ end
964
+
965
+ test "insert_all with query and source field" do
966
+ %{id: post_id} = TestRepo.insert!(%Post{})
967
+ TestRepo.insert!(%Permalink{url: "url", title: "title"})
968
+
969
+ source = from p in Permalink, select: %{url: p.title, post_id: ^post_id}
970
+ assert {1, _} = TestRepo.insert_all(Permalink, source)
971
+ end
972
+ end
973
+
974
+ @tag :invalid_prefix
975
+ @tag :insert_cell_wise_defaults
976
+ test "insert all with invalid prefix" do
977
+ assert catch_error(TestRepo.insert_all(Post, [[], []], prefix: "oops"))
978
+ end
979
+
980
+ @tag :returning
981
+ @tag :insert_cell_wise_defaults
982
+ test "insert all with returning with schema" do
983
+ assert {0, []} = TestRepo.insert_all(Comment, [], returning: true)
984
+ assert {0, nil} = TestRepo.insert_all(Comment, [], returning: false)
985
+
986
+ {2, [c1, c2]} = TestRepo.insert_all(Comment, [[text: "1"], [text: "2"]], returning: [:id, :text])
987
+ assert %Comment{text: "1", __meta__: %{state: :loaded}} = c1
988
+ assert %Comment{text: "2", __meta__: %{state: :loaded}} = c2
989
+
990
+ {2, [c1, c2]} = TestRepo.insert_all(Comment, [[text: "3"], [text: "4"]], returning: true)
991
+ assert %Comment{text: "3", __meta__: %{state: :loaded}} = c1
992
+ assert %Comment{text: "4", __meta__: %{state: :loaded}} = c2
993
+ end
994
+
995
+ @tag :returning
996
+ @tag :insert_cell_wise_defaults
997
+ test "insert all with returning with schema with field source" do
998
+ assert {0, []} = TestRepo.insert_all(Permalink, [], returning: true)
999
+ assert {0, nil} = TestRepo.insert_all(Permalink, [], returning: false)
1000
+
1001
+ {2, [c1, c2]} = TestRepo.insert_all(Permalink, [[url: "1"], [url: "2"]], returning: [:id, :url])
1002
+ assert %Permalink{url: "1", __meta__: %{state: :loaded}} = c1
1003
+ assert %Permalink{url: "2", __meta__: %{state: :loaded}} = c2
1004
+
1005
+ {2, [c1, c2]} = TestRepo.insert_all(Permalink, [[url: "3"], [url: "4"]], returning: true)
1006
+ assert %Permalink{url: "3", __meta__: %{state: :loaded}} = c1
1007
+ assert %Permalink{url: "4", __meta__: %{state: :loaded}} = c2
1008
+ end
1009
+
1010
+ @tag :returning
1011
+ @tag :insert_cell_wise_defaults
1012
+ test "insert all with returning without schema" do
1013
+ {2, [c1, c2]} = TestRepo.insert_all("comments", [[text: "1"], [text: "2"]], returning: [:id, :text])
1014
+ assert %{id: _, text: "1"} = c1
1015
+ assert %{id: _, text: "2"} = c2
1016
+
1017
+ assert_raise ArgumentError, fn ->
1018
+ TestRepo.insert_all("comments", [[text: "1"], [text: "2"]], returning: true)
1019
+ end
1020
+ end
1021
+
1022
+ @tag :insert_cell_wise_defaults
1023
+ test "insert all with dumping" do
1024
+ uuid = Ecto.UUID.generate()
1025
+ assert {1, nil} = TestRepo.insert_all(Post, [%{uuid: uuid}])
1026
+ assert [%Post{uuid: ^uuid, title: nil}] = TestRepo.all(Post)
1027
+ end
1028
+
1029
+ @tag :insert_cell_wise_defaults
1030
+ test "insert all autogenerates for binary_id type" do
1031
+ custom = TestRepo.insert!(%Custom{bid: nil})
1032
+ assert custom.bid
1033
+ assert TestRepo.get(Custom, custom.bid)
1034
+ assert TestRepo.delete!(custom)
1035
+ refute TestRepo.get(Custom, custom.bid)
1036
+
1037
+ uuid = Ecto.UUID.generate()
1038
+ assert {2, nil} = TestRepo.insert_all(Custom, [%{uuid: uuid}, %{bid: custom.bid}])
1039
+ assert [%Custom{bid: bid2, uuid: nil},
1040
+ %Custom{bid: bid1, uuid: ^uuid}] = Enum.sort_by(TestRepo.all(Custom), & &1.uuid)
1041
+ assert bid1 && bid2
1042
+ assert custom.bid != bid1
1043
+ assert custom.bid == bid2
1044
+ end
1045
+
1046
+ describe "placeholders" do
1047
+ @describetag :placeholders
1048
+
1049
+ test "Repo.insert_all fills in placeholders" do
1050
+ placeholders = %{foo: 100, bar: "test"}
1051
+ bar_ph = {:placeholder, :bar}
1052
+ foo_ph = {:placeholder, :foo}
1053
+
1054
+ entries = [
1055
+ %{intensity: 1.0, title: bar_ph, posted: ~D[2020-12-21], visits: foo_ph},
1056
+ %{intensity: 2.0, title: bar_ph, posted: ~D[2000-12-21], visits: foo_ph}
1057
+ ] |> Enum.map(&Map.put(&1, :uuid, Ecto.UUID.generate))
1058
+
1059
+ TestRepo.insert_all(Post, entries, placeholders: placeholders)
1060
+
1061
+ query = from(p in Post, select: {p.intensity, p.title, p.visits})
1062
+ assert [{1.0, "test", 100}, {2.0, "test", 100}] == TestRepo.all(query)
1063
+ end
1064
+
1065
+ test "Repo.insert_all accepts non-atom placeholder keys" do
1066
+ placeholders = %{10 => "integer key", {:foo, :bar} => "tuple key"}
1067
+ entries = [%{text: {:placeholder, 10}}, %{text: {:placeholder, {:foo, :bar}}}]
1068
+ TestRepo.insert_all(Comment, entries, placeholders: placeholders)
1069
+
1070
+ query = from(c in Comment, select: c.text)
1071
+ assert ["integer key", "tuple key"] == TestRepo.all(query)
1072
+ end
1073
+
1074
+ test "Repo.insert_all fills in placeholders with keyword list entries" do
1075
+ TestRepo.insert_all(Barebone, [[num: {:placeholder, :foo}]], placeholders: %{foo: 100})
1076
+
1077
+ query = from(b in Barebone, select: b.num)
1078
+ assert [100] == TestRepo.all(query)
1079
+ end
1080
+
1081
+ @tag :upsert_all
1082
+ @tag :with_conflict_target
1083
+ test "Repo.insert_all upserts and fills in placeholders with conditioned on_conflict query" do
1084
+ do_not_update_title = "don't touch me"
1085
+
1086
+ posted_value =
1087
+ from p in Post, where: p.public == ^true and p.id > ^0, select: p.posted, limit: 1
1088
+
1089
+ on_conflict =
1090
+ from p in Post, update: [set: [title: "updated"]], where: p.title != ^do_not_update_title
1091
+
1092
+ placeholders = %{visits: 1, title: "title"}
1093
+
1094
+ post1 = [
1095
+ visits: {:placeholder, :visits},
1096
+ title: {:placeholder, :title},
1097
+ uuid: Ecto.UUID.generate(),
1098
+ posted: posted_value
1099
+ ]
1100
+
1101
+ post2 = [
1102
+ title: do_not_update_title,
1103
+ uuid: Ecto.UUID.generate(),
1104
+ posted: posted_value
1105
+ ]
1106
+
1107
+ assert TestRepo.insert_all(Post, [post1, post2],
1108
+ placeholders: placeholders,
1109
+ on_conflict: on_conflict,
1110
+ conflict_target: [:uuid]
1111
+ ) ==
1112
+ {2, nil}
1113
+
1114
+ # only update first post
1115
+ assert TestRepo.insert_all(Post, [post1, post2],
1116
+ placeholders: placeholders,
1117
+ on_conflict: on_conflict,
1118
+ conflict_target: [:uuid]
1119
+ ) ==
1120
+ {1, nil}
1121
+
1122
+ assert TestRepo.aggregate(where(Post, title: "updated"), :count) == 1
1123
+ end
1124
+ end
1125
+
1126
+ test "update all" do
1127
+ assert post1 = TestRepo.insert!(%Post{title: "1"})
1128
+ assert post2 = TestRepo.insert!(%Post{title: "2"})
1129
+ assert post3 = TestRepo.insert!(%Post{title: "3"})
1130
+
1131
+ assert {3, nil} = TestRepo.update_all(Post, set: [title: "x"])
1132
+
1133
+ assert %Post{title: "x"} = TestRepo.reload(post1)
1134
+ assert %Post{title: "x"} = TestRepo.reload(post2)
1135
+ assert %Post{title: "x"} = TestRepo.reload(post3)
1136
+
1137
+ assert {3, nil} = TestRepo.update_all("posts", [set: [title: nil]])
1138
+
1139
+ assert %Post{title: nil} = TestRepo.reload(post1)
1140
+ assert %Post{title: nil} = TestRepo.reload(post2)
1141
+ assert %Post{title: nil} = TestRepo.reload(post3)
1142
+ end
1143
+
1144
+ @tag :invalid_prefix
1145
+ test "update all with invalid prefix" do
1146
+ assert catch_error(TestRepo.update_all(Post, [set: [title: "x"]], prefix: "oops"))
1147
+ end
1148
+
1149
+ @tag :returning
1150
+ test "update all with returning with schema" do
1151
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1152
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1153
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1154
+
1155
+ assert {3, posts} = TestRepo.update_all(select(Post, [p], p), [set: [title: "x"]])
1156
+
1157
+ [p1, p2, p3] = Enum.sort_by(posts, & &1.id)
1158
+ assert %Post{id: ^id1, title: "x"} = p1
1159
+ assert %Post{id: ^id2, title: "x"} = p2
1160
+ assert %Post{id: ^id3, title: "x"} = p3
1161
+
1162
+ assert {3, posts} = TestRepo.update_all(select(Post, [:id, :visits]), [set: [visits: 11]])
1163
+
1164
+ [p1, p2, p3] = Enum.sort_by(posts, & &1.id)
1165
+ assert %Post{id: ^id1, title: nil, visits: 11} = p1
1166
+ assert %Post{id: ^id2, title: nil, visits: 11} = p2
1167
+ assert %Post{id: ^id3, title: nil, visits: 11} = p3
1168
+ end
1169
+
1170
+ @tag :returning
1171
+ test "update all with returning without schema" do
1172
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1173
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1174
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1175
+
1176
+ assert {3, posts} = TestRepo.update_all(select("posts", [:id, :title]), [set: [title: "x"]])
1177
+
1178
+ [p1, p2, p3] = Enum.sort_by(posts, & &1.id)
1179
+ assert p1 == %{id: id1, title: "x"}
1180
+ assert p2 == %{id: id2, title: "x"}
1181
+ assert p3 == %{id: id3, title: "x"}
1182
+ end
1183
+
1184
+ test "update all with filter" do
1185
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1186
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1187
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1188
+
1189
+ query = from(p in Post, where: p.title == "1" or p.title == "2",
1190
+ update: [set: [visits: ^17]])
1191
+ assert {2, nil} = TestRepo.update_all(query, set: [title: "x"])
1192
+
1193
+ assert %Post{title: "x", visits: 17} = TestRepo.get(Post, id1)
1194
+ assert %Post{title: "x", visits: 17} = TestRepo.get(Post, id2)
1195
+ assert %Post{title: "3", visits: nil} = TestRepo.get(Post, id3)
1196
+ end
1197
+
1198
+ test "update all no entries" do
1199
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1200
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1201
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1202
+
1203
+ query = from(p in Post, where: p.title == "4")
1204
+ assert {0, nil} = TestRepo.update_all(query, set: [title: "x"])
1205
+
1206
+ assert %Post{title: "1"} = TestRepo.get(Post, id1)
1207
+ assert %Post{title: "2"} = TestRepo.get(Post, id2)
1208
+ assert %Post{title: "3"} = TestRepo.get(Post, id3)
1209
+ end
1210
+
1211
+ test "update all increment syntax" do
1212
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1", visits: 0})
1213
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2", visits: 1})
1214
+
1215
+ # Positive
1216
+ query = from p in Post, where: not is_nil(p.id), update: [inc: [visits: 2]]
1217
+ assert {2, nil} = TestRepo.update_all(query, [])
1218
+
1219
+ assert %Post{visits: 2} = TestRepo.get(Post, id1)
1220
+ assert %Post{visits: 3} = TestRepo.get(Post, id2)
1221
+
1222
+ # Negative
1223
+ query = from p in Post, where: not is_nil(p.id), update: [inc: [visits: -1]]
1224
+ assert {2, nil} = TestRepo.update_all(query, [])
1225
+
1226
+ assert %Post{visits: 1} = TestRepo.get(Post, id1)
1227
+ assert %Post{visits: 2} = TestRepo.get(Post, id2)
1228
+ end
1229
+
1230
+ @tag :id_type
1231
+ test "update all with casting and dumping on id type field" do
1232
+ assert %Post{id: id1} = TestRepo.insert!(%Post{})
1233
+ assert {1, nil} = TestRepo.update_all(Post, set: [counter: to_string(id1)])
1234
+ assert %Post{counter: ^id1} = TestRepo.get(Post, id1)
1235
+ end
1236
+
1237
+ test "update all with casting and dumping" do
1238
+ visits = 13
1239
+ datetime = ~N[2014-01-16 20:26:51]
1240
+ assert %Post{id: id} = TestRepo.insert!(%Post{})
1241
+
1242
+ assert {1, nil} = TestRepo.update_all(Post, set: [visits: visits, inserted_at: datetime])
1243
+ assert %Post{visits: 13, inserted_at: ^datetime} = TestRepo.get(Post, id)
1244
+ end
1245
+
1246
+ test "delete all" do
1247
+ assert %Post{} = TestRepo.insert!(%Post{title: "1"})
1248
+ assert %Post{} = TestRepo.insert!(%Post{title: "2"})
1249
+ assert %Post{} = TestRepo.insert!(%Post{title: "3"})
1250
+
1251
+ assert {3, nil} = TestRepo.delete_all(Post)
1252
+ assert [] = TestRepo.all(Post)
1253
+ end
1254
+
1255
+ @tag :invalid_prefix
1256
+ test "delete all with invalid prefix" do
1257
+ assert catch_error(TestRepo.delete_all(Post, prefix: "oops"))
1258
+ end
1259
+
1260
+ @tag :returning
1261
+ test "delete all with returning with schema" do
1262
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1263
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1264
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1265
+
1266
+ assert {3, posts} = TestRepo.delete_all(select(Post, [p], p))
1267
+
1268
+ [p1, p2, p3] = Enum.sort_by(posts, & &1.id)
1269
+ assert %Post{id: ^id1, title: "1"} = p1
1270
+ assert %Post{id: ^id2, title: "2"} = p2
1271
+ assert %Post{id: ^id3, title: "3"} = p3
1272
+ end
1273
+
1274
+ @tag :returning
1275
+ test "delete all with returning without schema" do
1276
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1277
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1278
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1279
+
1280
+ assert {3, posts} = TestRepo.delete_all(select("posts", [:id, :title]))
1281
+
1282
+ [p1, p2, p3] = Enum.sort_by(posts, & &1.id)
1283
+ assert p1 == %{id: id1, title: "1"}
1284
+ assert p2 == %{id: id2, title: "2"}
1285
+ assert p3 == %{id: id3, title: "3"}
1286
+ end
1287
+
1288
+ test "delete all with filter" do
1289
+ assert %Post{} = TestRepo.insert!(%Post{title: "1"})
1290
+ assert %Post{} = TestRepo.insert!(%Post{title: "2"})
1291
+ assert %Post{} = TestRepo.insert!(%Post{title: "3"})
1292
+
1293
+ query = from(p in Post, where: p.title == "1" or p.title == "2")
1294
+ assert {2, nil} = TestRepo.delete_all(query)
1295
+ assert [%Post{}] = TestRepo.all(Post)
1296
+ end
1297
+
1298
+ test "delete all no entries" do
1299
+ assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
1300
+ assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
1301
+ assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
1302
+
1303
+ query = from(p in Post, where: p.title == "4")
1304
+ assert {0, nil} = TestRepo.delete_all(query)
1305
+ assert %Post{title: "1"} = TestRepo.get(Post, id1)
1306
+ assert %Post{title: "2"} = TestRepo.get(Post, id2)
1307
+ assert %Post{title: "3"} = TestRepo.get(Post, id3)
1308
+ end
1309
+
1310
+ test "virtual field" do
1311
+ assert %Post{id: id} = TestRepo.insert!(%Post{title: "1"})
1312
+ assert TestRepo.get(Post, id).temp == "temp"
1313
+ end
1314
+
1315
+ ## Query syntax
1316
+
1317
+ defmodule Foo do
1318
+ defstruct [:title]
1319
+ end
1320
+
1321
+ describe "query select" do
1322
+ test "expressions" do
1323
+ %Post{} = TestRepo.insert!(%Post{title: "1", visits: 13})
1324
+
1325
+ assert [{"1", 13}] ==
1326
+ TestRepo.all(from p in Post, select: {p.title, p.visits})
1327
+
1328
+ assert [["1", 13]] ==
1329
+ TestRepo.all(from p in Post, select: [p.title, p.visits])
1330
+
1331
+ assert [%{:title => "1", 3 => 13, "visits" => 13}] ==
1332
+ TestRepo.all(from p in Post, select: %{
1333
+ :title => p.title,
1334
+ "visits" => p.visits,
1335
+ 3 => p.visits
1336
+ })
1337
+
1338
+ assert [%{:title => "1", "1" => 13, "visits" => 13}] ==
1339
+ TestRepo.all(from p in Post, select: %{
1340
+ :title => p.title,
1341
+ p.title => p.visits,
1342
+ "visits" => p.visits
1343
+ })
1344
+
1345
+ assert [%Foo{title: "1"}] ==
1346
+ TestRepo.all(from p in Post, select: %Foo{title: p.title})
1347
+ end
1348
+
1349
+ test "map update" do
1350
+ %Post{} = TestRepo.insert!(%Post{title: "1", visits: 13})
1351
+
1352
+ assert [%Post{:title => "new title", visits: 13}] =
1353
+ TestRepo.all(from p in Post, select: %{p | title: "new title"})
1354
+
1355
+ assert [%Post{title: "new title", visits: 13}] =
1356
+ TestRepo.all(from p in Post, select: %Post{p | title: "new title"})
1357
+
1358
+ assert [%Post{:title => "1", visits: -1}] =
1359
+ TestRepo.all(from p in Post, select: %{p | visits: ^"-1"})
1360
+
1361
+ assert [%Post{title: "1", visits: -1}] =
1362
+ TestRepo.all(from p in Post, select: %Post{p | visits: ^"-1"})
1363
+
1364
+ assert_raise KeyError, fn ->
1365
+ TestRepo.all(from p in Post, select: %{p | unknown: "new title"})
1366
+ end
1367
+
1368
+ assert_raise BadMapError, fn ->
1369
+ TestRepo.all(from p in Post, select: %{p.title | title: "new title"})
1370
+ end
1371
+
1372
+ assert_raise BadStructError, fn ->
1373
+ TestRepo.all(from p in Post, select: %Foo{p | title: p.title})
1374
+ end
1375
+ end
1376
+
1377
+ test "map update on association" do
1378
+ p = TestRepo.insert!(%Post{})
1379
+ TestRepo.insert!(%Comment{post_id: p.id, text: "comment text"})
1380
+ TestRepo.insert!(%Comment{})
1381
+
1382
+ query =
1383
+ from(c in Comment, left_join: p in Post, on: c.post_id == p.id, select: %{p | temp: c.text})
1384
+
1385
+ assert [%Post{:temp => "comment text"}, nil] = TestRepo.all(query)
1386
+ end
1387
+
1388
+ test "take with structs" do
1389
+ %{id: pid1} = TestRepo.insert!(%Post{title: "1"})
1390
+ %{id: pid2} = TestRepo.insert!(%Post{title: "2"})
1391
+ %{id: pid3} = TestRepo.insert!(%Post{title: "3"})
1392
+
1393
+ [p1, p2, p3] = Post |> select([p], struct(p, [:title])) |> order_by([:title]) |> TestRepo.all
1394
+ refute p1.id
1395
+ assert p1.title == "1"
1396
+ assert match?(%Post{}, p1)
1397
+ refute p2.id
1398
+ assert p2.title == "2"
1399
+ assert match?(%Post{}, p2)
1400
+ refute p3.id
1401
+ assert p3.title == "3"
1402
+ assert match?(%Post{}, p3)
1403
+
1404
+ [p1, p2, p3] = Post |> select([:id]) |> order_by([:id]) |> TestRepo.all
1405
+ assert %Post{id: ^pid1} = p1
1406
+ assert %Post{id: ^pid2} = p2
1407
+ assert %Post{id: ^pid3} = p3
1408
+ end
1409
+
1410
+ test "take with maps" do
1411
+ %{id: pid1} = TestRepo.insert!(%Post{title: "1"})
1412
+ %{id: pid2} = TestRepo.insert!(%Post{title: "2"})
1413
+ %{id: pid3} = TestRepo.insert!(%Post{title: "3"})
1414
+
1415
+ [p1, p2, p3] = "posts" |> select([p], map(p, [:title])) |> order_by([:title]) |> TestRepo.all
1416
+ assert p1 == %{title: "1"}
1417
+ assert p2 == %{title: "2"}
1418
+ assert p3 == %{title: "3"}
1419
+
1420
+ [p1, p2, p3] = "posts" |> select([:id]) |> order_by([:id]) |> TestRepo.all
1421
+ assert p1 == %{id: pid1}
1422
+ assert p2 == %{id: pid2}
1423
+ assert p3 == %{id: pid3}
1424
+ end
1425
+
1426
+ test "take with preload assocs" do
1427
+ %{id: pid} = TestRepo.insert!(%Post{title: "post"})
1428
+ TestRepo.insert!(%Comment{post_id: pid, text: "comment"})
1429
+ fields = [:id, :title, comments: [:text, :post_id]]
1430
+
1431
+ [p] = Post |> preload(:comments) |> select([p], ^fields) |> TestRepo.all
1432
+ assert %Post{title: "post"} = p
1433
+ assert [%Comment{text: "comment"}] = p.comments
1434
+
1435
+ [p] = Post |> preload(:comments) |> select([p], struct(p, ^fields)) |> TestRepo.all
1436
+ assert %Post{title: "post"} = p
1437
+ assert [%Comment{text: "comment"}] = p.comments
1438
+
1439
+ [p] = Post |> preload(:comments) |> select([p], map(p, ^fields)) |> TestRepo.all
1440
+ assert p == %{id: pid, title: "post", comments: [%{text: "comment", post_id: pid}]}
1441
+ end
1442
+
1443
+ test "take with nil preload assoc" do
1444
+ %{id: cid} = TestRepo.insert!(%Comment{text: "comment"})
1445
+ fields = [:id, :text, post: [:title]]
1446
+
1447
+ [c] = Comment |> preload(:post) |> select([c], ^fields) |> TestRepo.all
1448
+ assert %Comment{id: ^cid, text: "comment", post: nil} = c
1449
+
1450
+ [c] = Comment |> preload(:post) |> select([c], struct(c, ^fields)) |> TestRepo.all
1451
+ assert %Comment{id: ^cid, text: "comment", post: nil} = c
1452
+
1453
+ [c] = Comment |> preload(:post) |> select([c], map(c, ^fields)) |> TestRepo.all
1454
+ assert c == %{id: cid, text: "comment", post: nil}
1455
+ end
1456
+
1457
+ test "take with join assocs" do
1458
+ %{id: pid} = TestRepo.insert!(%Post{title: "post"})
1459
+ %{id: cid} = TestRepo.insert!(%Comment{post_id: pid, text: "comment"})
1460
+ fields = [:id, :title, comments: [:text, :post_id, :id]]
1461
+ query = from p in Post, where: p.id == ^pid, join: c in assoc(p, :comments), preload: [comments: c]
1462
+
1463
+ p = TestRepo.one(from q in query, select: ^fields)
1464
+ assert %Post{title: "post"} = p
1465
+ assert [%Comment{text: "comment"}] = p.comments
1466
+
1467
+ p = TestRepo.one(from q in query, select: struct(q, ^fields))
1468
+ assert %Post{title: "post"} = p
1469
+ assert [%Comment{text: "comment"}] = p.comments
1470
+
1471
+ p = TestRepo.one(from q in query, select: map(q, ^fields))
1472
+ assert p == %{id: pid, title: "post", comments: [%{text: "comment", post_id: pid, id: cid}]}
1473
+ end
1474
+
1475
+ test "take with single nil column" do
1476
+ %Post{} = TestRepo.insert!(%Post{title: "1", counter: nil})
1477
+ assert %{counter: nil} =
1478
+ TestRepo.one(from p in Post, where: p.title == "1", select: [:counter])
1479
+ end
1480
+
1481
+ test "take with join assocs and single nil column" do
1482
+ %{id: post_id} = TestRepo.insert!(%Post{title: "1"}, counter: nil)
1483
+ TestRepo.insert!(%Comment{post_id: post_id, text: "comment"})
1484
+ assert %{counter: nil} ==
1485
+ TestRepo.one(from p in Post, join: c in assoc(p, :comments), where: p.title == "1", select: map(p, [:counter]))
1486
+ end
1487
+
1488
+ test "field source" do
1489
+ TestRepo.insert!(%Permalink{url: "url"})
1490
+ assert ["url"] = Permalink |> select([p], p.url) |> TestRepo.all()
1491
+ assert [1] = Permalink |> select([p], count(p.url)) |> TestRepo.all()
1492
+ end
1493
+
1494
+ test "merge" do
1495
+ date = Date.utc_today()
1496
+ %Post{id: post_id} = TestRepo.insert!(%Post{title: "1", counter: nil, posted: date, public: false})
1497
+
1498
+ # Merge on source
1499
+ assert [%Post{title: "2"}] =
1500
+ Post |> select([p], merge(p, %{title: "2"})) |> TestRepo.all()
1501
+ assert [%Post{title: "2"}] =
1502
+ Post |> select([p], p) |> select_merge([p], %{title: "2"}) |> TestRepo.all()
1503
+
1504
+ # Merge on struct
1505
+ assert [%Post{title: "2"}] =
1506
+ Post |> select([p], merge(%Post{title: p.title}, %{title: "2"})) |> TestRepo.all()
1507
+ assert [%Post{title: "2"}] =
1508
+ Post |> select([p], %Post{title: p.title}) |> select_merge([p], %{title: "2"}) |> TestRepo.all()
1509
+
1510
+ # Merge on map
1511
+ assert [%{title: "2"}] =
1512
+ Post |> select([p], merge(%{title: p.title}, %{title: "2"})) |> TestRepo.all()
1513
+ assert [%{title: "2"}] =
1514
+ Post |> select([p], %{title: p.title}) |> select_merge([p], %{title: "2"}) |> TestRepo.all()
1515
+
1516
+ # Merge on outer join with map
1517
+ %Permalink{} = TestRepo.insert!(%Permalink{post_id: post_id, url: "Q", title: "Z"})
1518
+
1519
+ # left join record is present
1520
+ assert [%{url: "Q", title: "1", posted: _date}] =
1521
+ Permalink
1522
+ |> join(:left, [l], p in Post, on: l.post_id == p.id)
1523
+ |> select([l, p], merge(l, map(p, ^~w(title posted)a)))
1524
+ |> TestRepo.all()
1525
+
1526
+ assert [%{url: "Q", title: "1", posted: _date}] =
1527
+ Permalink
1528
+ |> join(:left, [l], p in Post, on: l.post_id == p.id)
1529
+ |> select_merge([_l, p], map(p, ^~w(title posted)a))
1530
+ |> TestRepo.all()
1531
+
1532
+ # left join record is not present
1533
+ assert [%{url: "Q", title: "Z", posted: nil}] =
1534
+ Permalink
1535
+ |> join(:left, [l], p in Post, on: l.post_id == p.id and p.public == true)
1536
+ |> select([l, p], merge(l, map(p, ^~w(title posted)a)))
1537
+ |> TestRepo.all()
1538
+
1539
+ assert [%{url: "Q", title: "Z", posted: nil}] =
1540
+ Permalink
1541
+ |> join(:left, [l], p in Post, on: l.post_id == p.id and p.public == true)
1542
+ |> select_merge([_l, p], map(p, ^~w(title posted)a))
1543
+ |> TestRepo.all()
1544
+ end
1545
+
1546
+ test "merge with update on self" do
1547
+ %Post{} = TestRepo.insert!(%Post{title: "1", counter: 1})
1548
+
1549
+ assert [%Post{title: "1", counter: 2}] =
1550
+ Post |> select([p], merge(p, %{p | counter: 2})) |> TestRepo.all()
1551
+ assert [%Post{title: "1", counter: 2}] =
1552
+ Post |> select([p], p) |> select_merge([p], %{p | counter: 2}) |> TestRepo.all()
1553
+ end
1554
+
1555
+ test "merge within subquery" do
1556
+ %Post{} = TestRepo.insert!(%Post{title: "1", counter: 1})
1557
+
1558
+ subquery =
1559
+ Post
1560
+ |> select_merge([p], %{p | counter: 2})
1561
+ |> subquery()
1562
+
1563
+ assert [%Post{title: "1", counter: 2}] = TestRepo.all(subquery)
1564
+ end
1565
+
1566
+ @tag :selected_as_with_group_by
1567
+ test "selected_as/2 with group_by" do
1568
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3})
1569
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 2})
1570
+ TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil})
1571
+
1572
+ query =
1573
+ from p in Post,
1574
+ select: %{
1575
+ posted: selected_as(p.posted, :date),
1576
+ min_visits: p.visits |> coalesce(0) |> min()
1577
+ },
1578
+ group_by: selected_as(:date),
1579
+ order_by: p.posted
1580
+
1581
+ assert [%{posted: ~D[2020-12-20], min_visits: 0}, %{posted: ~D[2020-12-21], min_visits: 2}] =
1582
+ TestRepo.all(query)
1583
+ end
1584
+
1585
+ @tag :selected_as_with_order_by
1586
+ test "selected_as/2 with order_by" do
1587
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3})
1588
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 2})
1589
+ TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil})
1590
+
1591
+ base_query =
1592
+ from p in Post,
1593
+ select: %{
1594
+ posted: p.posted,
1595
+ min_visits: p.visits |> coalesce(0) |> min() |> selected_as(:min_visits)
1596
+ },
1597
+ group_by: p.posted
1598
+
1599
+ # ascending order
1600
+ results = base_query |> order_by(selected_as(:min_visits)) |> TestRepo.all()
1601
+
1602
+ assert [%{posted: ~D[2020-12-20], min_visits: 0}, %{posted: ~D[2020-12-21], min_visits: 2}] =
1603
+ results
1604
+
1605
+ # descending order
1606
+ results = base_query |> order_by([desc: selected_as(:min_visits)]) |> TestRepo.all()
1607
+
1608
+ assert [%{posted: ~D[2020-12-21], min_visits: 2}, %{posted: ~D[2020-12-20], min_visits: 0}] =
1609
+ results
1610
+ end
1611
+
1612
+ @tag :selected_as_with_order_by
1613
+ test "selected_as/2 respects custom types" do
1614
+ TestRepo.insert!(%Post{title: "title1", visits: 1})
1615
+ TestRepo.insert!(%Post{title: "title2"})
1616
+ uuid = Ecto.UUID.generate()
1617
+
1618
+ query =
1619
+ from p in Post,
1620
+ select: %{
1621
+ uuid: type(^uuid, Ecto.UUID) |> selected_as(:uuid),
1622
+ visits: p.visits |> coalesce(0) |> selected_as(:visits)
1623
+ },
1624
+ order_by: [selected_as(:uuid), selected_as(:visits)]
1625
+
1626
+ assert [%{uuid: ^uuid, visits: 0}, %{uuid: ^uuid, visits: 1}] = TestRepo.all(query)
1627
+ end
1628
+
1629
+ @tag :selected_as_with_order_by_expression
1630
+ test "selected_as/2 with order_by expression" do
1631
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3, intensity: 2.0})
1632
+ TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil, intensity: 10.0})
1633
+
1634
+ results =
1635
+ from(p in Post,
1636
+ select: %{
1637
+ posted: p.posted,
1638
+ visits: p.visits |> coalesce(0) |> selected_as(:num_visits),
1639
+ intensity: selected_as(p.intensity, :strength)
1640
+ },
1641
+ order_by: [desc: (selected_as(:num_visits) + selected_as(:strength))]
1642
+ )
1643
+ |> TestRepo.all()
1644
+
1645
+ assert [%{posted: ~D[2020-12-20], visits: 0}, %{posted: ~D[2020-12-21], visits: 3}] =
1646
+ results
1647
+ end
1648
+
1649
+ @tag :selected_as_with_having
1650
+ test "selected_as/2 with having" do
1651
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3})
1652
+ TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 2})
1653
+ TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil})
1654
+
1655
+ results =
1656
+ from(p in Post,
1657
+ select: %{
1658
+ posted: p.posted,
1659
+ min_visits: p.visits |> coalesce(0) |> min() |> selected_as(:min_visits)
1660
+ },
1661
+ group_by: p.posted,
1662
+ having: selected_as(:min_visits) > 0,
1663
+ or_having: not(selected_as(:min_visits) > 0),
1664
+ order_by: p.posted
1665
+ )
1666
+ |> TestRepo.all()
1667
+
1668
+ assert [%{posted: ~D[2020-12-20], min_visits: 0}, %{posted: ~D[2020-12-21], min_visits: 2}] = results
1669
+ end
1670
+ end
1671
+
1672
+ @tag :distinct_count
1673
+ test "query count distinct" do
1674
+ TestRepo.insert!(%Post{title: "1"})
1675
+ TestRepo.insert!(%Post{title: "1"})
1676
+ TestRepo.insert!(%Post{title: "2"})
1677
+
1678
+ assert [3] == Post |> select([p], count(p.title)) |> TestRepo.all
1679
+ assert [2] == Post |> select([p], count(p.title, :distinct)) |> TestRepo.all
1680
+ end
1681
+
1682
+ test "query where interpolation" do
1683
+ post1 = TestRepo.insert!(%Post{title: "hello"})
1684
+ post2 = TestRepo.insert!(%Post{title: "goodbye"})
1685
+
1686
+ assert [post1, post2] == Post |> where([], []) |> TestRepo.all |> Enum.sort_by(& &1.id)
1687
+ assert [post1] == Post |> where([], [title: "hello"]) |> TestRepo.all
1688
+ assert [post1] == Post |> where([], [title: "hello", id: ^post1.id]) |> TestRepo.all
1689
+
1690
+ params0 = []
1691
+ params1 = [title: "hello"]
1692
+ params2 = [title: "hello", id: post1.id]
1693
+ assert [post1, post2] == (from Post, where: ^params0) |> TestRepo.all |> Enum.sort_by(& &1.id)
1694
+ assert [post1] == (from Post, where: ^params1) |> TestRepo.all
1695
+ assert [post1] == (from Post, where: ^params2) |> TestRepo.all
1696
+
1697
+ post3 = TestRepo.insert!(%Post{title: "goodbye", uuid: nil})
1698
+ params3 = [title: "goodbye", uuid: post3.uuid]
1699
+ assert [post3] == (from Post, where: ^params3) |> TestRepo.all
1700
+ end
1701
+
1702
+ describe "upsert via insert" do
1703
+ @describetag :upsert
1704
+
1705
+ test "on conflict raise" do
1706
+ {:ok, inserted} = TestRepo.insert(%Post{title: "first"}, on_conflict: :raise)
1707
+ assert catch_error(TestRepo.insert(%Post{id: inserted.id, title: "second"}, on_conflict: :raise))
1708
+ end
1709
+
1710
+ test "on conflict ignore" do
1711
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1712
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing)
1713
+ assert inserted.id
1714
+ assert inserted.__meta__.state == :loaded
1715
+
1716
+ {:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing)
1717
+ assert not_inserted.id == nil
1718
+ assert not_inserted.__meta__.state == :loaded
1719
+ end
1720
+
1721
+ @tag :with_conflict_target
1722
+ test "on conflict and associations" do
1723
+ on_conflict = [set: [title: "second"]]
1724
+ post = %Post{uuid: Ecto.UUID.generate(),
1725
+ title: "first", comments: [%Comment{}]}
1726
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
1727
+ assert inserted.id
1728
+ end
1729
+
1730
+ @tag :with_conflict_target
1731
+ test "on conflict with inc" do
1732
+ uuid = "6fa459ea-ee8a-3ca4-894e-db77e160355e"
1733
+ post = %Post{title: "first", uuid: uuid}
1734
+ {:ok, _} = TestRepo.insert(post)
1735
+ post = %{title: "upsert", uuid: uuid}
1736
+ TestRepo.insert_all(Post, [post], on_conflict: [inc: [visits: 1]], conflict_target: :uuid)
1737
+ end
1738
+
1739
+ @tag :with_conflict_target
1740
+ test "on conflict ignore and conflict target" do
1741
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1742
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid])
1743
+ assert inserted.id
1744
+
1745
+ # Error on non-conflict target
1746
+ assert catch_error(TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:id]))
1747
+
1748
+ # Error on conflict target
1749
+ {:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid])
1750
+ assert not_inserted.id == nil
1751
+ end
1752
+
1753
+ @tag :without_conflict_target
1754
+ test "on conflict keyword list" do
1755
+ on_conflict = [set: [title: "second"]]
1756
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1757
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict)
1758
+ assert inserted.id
1759
+
1760
+ {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict)
1761
+ assert updated.id == inserted.id
1762
+ assert updated.title != "second"
1763
+ assert TestRepo.get!(Post, inserted.id).title == "second"
1764
+ end
1765
+
1766
+ @tag :with_conflict_target
1767
+ test "on conflict keyword list and conflict target" do
1768
+ on_conflict = [set: [title: "second"]]
1769
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1770
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
1771
+ assert inserted.id
1772
+
1773
+ # Error on non-conflict target
1774
+ assert catch_error(TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:id]))
1775
+
1776
+ {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
1777
+ assert updated.id == inserted.id
1778
+ assert updated.title != "second"
1779
+ assert TestRepo.get!(Post, inserted.id).title == "second"
1780
+ end
1781
+
1782
+ @tag :returning
1783
+ @tag :with_conflict_target
1784
+ test "on conflict keyword list and conflict target and returning" do
1785
+ {:ok, c1} = TestRepo.insert(%Post{})
1786
+ {:ok, c2} = TestRepo.insert(%Post{id: c1.id}, on_conflict: [set: [id: c1.id]], conflict_target: [:id], returning: [:id, :uuid])
1787
+ {:ok, c3} = TestRepo.insert(%Post{id: c1.id}, on_conflict: [set: [id: c1.id]], conflict_target: [:id], returning: true)
1788
+ {:ok, c4} = TestRepo.insert(%Post{id: c1.id}, on_conflict: [set: [id: c1.id]], conflict_target: [:id], returning: false)
1789
+
1790
+ assert c2.uuid == c1.uuid
1791
+ assert c3.uuid == c1.uuid
1792
+ assert c4.uuid != c1.uuid
1793
+ end
1794
+
1795
+ @tag :returning
1796
+ @tag :with_conflict_target
1797
+ test "on conflict keyword list and conflict target and returning and field source" do
1798
+ TestRepo.insert!(%Permalink{url: "old"})
1799
+ {:ok, c1} = TestRepo.insert(%Permalink{url: "old"},
1800
+ on_conflict: [set: [url: "new1"]],
1801
+ conflict_target: [:url],
1802
+ returning: [:url])
1803
+
1804
+ TestRepo.insert!(%Permalink{url: "old"})
1805
+ {:ok, c2} = TestRepo.insert(%Permalink{url: "old"},
1806
+ on_conflict: [set: [url: "new2"]],
1807
+ conflict_target: [:url],
1808
+ returning: true)
1809
+
1810
+ assert c1.url == "new1"
1811
+ assert c2.url == "new2"
1812
+ end
1813
+
1814
+ @tag :returning
1815
+ @tag :with_conflict_target
1816
+ test "on conflict ignore and returning" do
1817
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1818
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid])
1819
+ assert inserted.id
1820
+
1821
+ {:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid], returning: true)
1822
+ assert not_inserted.id == nil
1823
+ end
1824
+
1825
+ @tag :without_conflict_target
1826
+ test "on conflict query" do
1827
+ on_conflict = from Post, update: [set: [title: "second"]]
1828
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1829
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict)
1830
+ assert inserted.id
1831
+
1832
+ {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict)
1833
+ assert updated.id == inserted.id
1834
+ assert updated.title != "second"
1835
+ assert TestRepo.get!(Post, inserted.id).title == "second"
1836
+ end
1837
+
1838
+ @tag :with_conflict_target
1839
+ test "on conflict query and conflict target" do
1840
+ on_conflict = from Post, update: [set: [title: "second"]]
1841
+ post = %Post{title: "first", uuid: Ecto.UUID.generate()}
1842
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
1843
+ assert inserted.id
1844
+
1845
+ # Error on non-conflict target
1846
+ assert catch_error(TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:id]))
1847
+
1848
+ {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
1849
+ assert updated.id == inserted.id
1850
+ assert updated.title != "second"
1851
+ assert TestRepo.get!(Post, inserted.id).title == "second"
1852
+ end
1853
+
1854
+ @tag :with_conflict_target
1855
+ test "on conflict query having condition" do
1856
+ post = %Post{title: "first", counter: 1, uuid: Ecto.UUID.generate()}
1857
+ {:ok, inserted} = TestRepo.insert(post)
1858
+
1859
+ on_conflict = from Post, where: [counter: 2], update: [set: [title: "second"]]
1860
+
1861
+ insert_options = [
1862
+ on_conflict: on_conflict,
1863
+ conflict_target: [:uuid],
1864
+ stale_error_field: :counter
1865
+ ]
1866
+
1867
+ assert {:error, changeset} = TestRepo.insert(post, insert_options)
1868
+ assert changeset.errors == [counter: {"is stale", [stale: true]}]
1869
+
1870
+ assert TestRepo.get!(Post, inserted.id).title == "first"
1871
+ end
1872
+
1873
+ @tag :without_conflict_target
1874
+ test "on conflict replace_all" do
1875
+ post = %Post{title: "first", visits: 13, uuid: Ecto.UUID.generate()}
1876
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: :replace_all)
1877
+ assert inserted.id
1878
+
1879
+ post = %Post{title: "updated", visits: 17, uuid: post.uuid}
1880
+ post = TestRepo.insert!(post, on_conflict: :replace_all)
1881
+ assert post.id != inserted.id
1882
+ assert post.title == "updated"
1883
+ assert post.visits == 17
1884
+
1885
+ assert TestRepo.all(from p in Post, select: {p.id, p.title, p.visits}) ==
1886
+ [{post.id, "updated", 17}]
1887
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [1]
1888
+ end
1889
+
1890
+ @tag :with_conflict_target
1891
+ test "on conflict replace_all and conflict target" do
1892
+ post = %Post{title: "first", visits: 13, uuid: Ecto.UUID.generate()}
1893
+ {:ok, inserted} = TestRepo.insert(post, on_conflict: :replace_all, conflict_target: :uuid)
1894
+ assert inserted.id
1895
+
1896
+ post = %Post{title: "updated", visits: 17, uuid: post.uuid}
1897
+ post = TestRepo.insert!(post, on_conflict: :replace_all, conflict_target: :uuid)
1898
+ assert post.id != inserted.id
1899
+ assert post.title == "updated"
1900
+ assert post.visits == 17
1901
+
1902
+ assert TestRepo.all(from p in Post, select: {p.id, p.title, p.visits}) ==
1903
+ [{post.id, "updated", 17}]
1904
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [1]
1905
+ end
1906
+ end
1907
+
1908
+ describe "upsert via insert_all" do
1909
+ @describetag :upsert_all
1910
+
1911
+ test "on conflict raise" do
1912
+ post = [title: "first", uuid: Ecto.UUID.generate()]
1913
+ {1, nil} = TestRepo.insert_all(Post, [post], on_conflict: :raise)
1914
+ assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: :raise))
1915
+ end
1916
+
1917
+ test "on conflict ignore" do
1918
+ post = [title: "first", uuid: Ecto.UUID.generate()]
1919
+ assert TestRepo.insert_all(Post, [post], on_conflict: :nothing) == {1, nil}
1920
+
1921
+ # PG returns 0, MySQL returns 1
1922
+ {entries, nil} = TestRepo.insert_all(Post, [post], on_conflict: :nothing)
1923
+ assert entries == 0 or entries == 1
1924
+
1925
+ assert length(TestRepo.all(Post)) == 1
1926
+ end
1927
+
1928
+ @tag :with_conflict_target
1929
+ test "on conflict ignore and conflict target" do
1930
+ post = [title: "first", uuid: Ecto.UUID.generate()]
1931
+ assert TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:uuid]) ==
1932
+ {1, nil}
1933
+
1934
+ # Error on non-conflict target
1935
+ assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:id]))
1936
+
1937
+ # Error on conflict target
1938
+ assert TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:uuid]) ==
1939
+ {0, nil}
1940
+ end
1941
+
1942
+ @tag :with_conflict_target
1943
+ test "on conflict keyword list and conflict target" do
1944
+ on_conflict = [set: [title: "second"]]
1945
+ post = [title: "first", uuid: Ecto.UUID.generate()]
1946
+ {1, nil} = TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid])
1947
+
1948
+ # Error on non-conflict target
1949
+ assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id]))
1950
+
1951
+ # Error on conflict target
1952
+ assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
1953
+ {1, nil}
1954
+ assert TestRepo.all(from p in Post, select: p.title) == ["second"]
1955
+ end
1956
+
1957
+ @tag :with_conflict_target
1958
+ @tag :returning
1959
+ test "on conflict keyword list and conflict target and returning and source field" do
1960
+ on_conflict = [set: [url: "new"]]
1961
+ permalink = [url: "old"]
1962
+
1963
+ assert {1, [%Permalink{url: "old"}]} =
1964
+ TestRepo.insert_all(Permalink, [permalink],
1965
+ on_conflict: on_conflict, conflict_target: [:url], returning: [:url])
1966
+
1967
+ assert {1, [%Permalink{url: "new"}]} =
1968
+ TestRepo.insert_all(Permalink, [permalink],
1969
+ on_conflict: on_conflict, conflict_target: [:url], returning: [:url])
1970
+ end
1971
+
1972
+ @tag :with_conflict_target
1973
+ test "on conflict query and conflict target" do
1974
+ on_conflict = from p in Post, where: p.id > ^0, update: [set: [title: "second"]]
1975
+ post = [title: "first", uuid: Ecto.UUID.generate()]
1976
+ assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
1977
+ {1, nil}
1978
+
1979
+ # Error on non-conflict target
1980
+ assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id]))
1981
+
1982
+ # Error on conflict target
1983
+ assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
1984
+ {1, nil}
1985
+ assert TestRepo.all(from p in Post, select: p.title) == ["second"]
1986
+ end
1987
+
1988
+ @tag :insert_select
1989
+ @tag :with_conflict_target
1990
+ test "on conflict query and insert select and conflict target" do
1991
+ on_conflict = from p in Post, where: p.id > ^0, update: [set: [title: "second"]]
1992
+ visits_value = from p in Post, where: p.public == ^true and p.id > ^0, select: p.visits, limit: 1
1993
+ post = [title: "first", uuid: Ecto.UUID.generate(), visits: visits_value]
1994
+ assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
1995
+ {1, nil}
1996
+
1997
+ # Error on non-conflict target
1998
+ assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id]))
1999
+
2000
+ # Error on conflict target
2001
+ assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
2002
+ {1, nil}
2003
+ assert TestRepo.all(from p in Post, select: p.title) == ["second"]
2004
+ end
2005
+
2006
+ @tag :returning
2007
+ @tag :with_conflict_target
2008
+ test "on conflict query and conflict target and returning" do
2009
+ on_conflict = from Post, update: [set: [title: "second"]]
2010
+ post = [title: "first", uuid: Ecto.UUID.generate()]
2011
+ {1, [%{id: id}]} = TestRepo.insert_all(Post, [post], on_conflict: on_conflict,
2012
+ conflict_target: [:uuid], returning: [:id])
2013
+
2014
+ # Error on non-conflict target
2015
+ assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict,
2016
+ conflict_target: [:id], returning: [:id]))
2017
+
2018
+ # Error on conflict target
2019
+ {1, [%Post{id: ^id, title: "second"}]} =
2020
+ TestRepo.insert_all(Post, [post], on_conflict: on_conflict,
2021
+ conflict_target: [:uuid], returning: [:id, :title])
2022
+ end
2023
+
2024
+ @tag :with_conflict_target
2025
+ test "source (without an Ecto schema) on conflict query and conflict target" do
2026
+ on_conflict = [set: [title: "second"]]
2027
+ {:ok, uuid} = Ecto.UUID.dump(Ecto.UUID.generate())
2028
+ post = [title: "first", uuid: uuid]
2029
+ assert TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
2030
+ {1, nil}
2031
+
2032
+ # Error on non-conflict target
2033
+ assert catch_error(TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:id]))
2034
+
2035
+ # Error on conflict target
2036
+ assert TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
2037
+ {1, nil}
2038
+ assert TestRepo.all(from p in Post, select: p.title) == ["second"]
2039
+ end
2040
+
2041
+ @tag :without_conflict_target
2042
+ test "on conflict replace_all" do
2043
+ post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()}
2044
+ post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()}
2045
+
2046
+ {:ok, post_first} = TestRepo.insert(post_first, on_conflict: :replace_all)
2047
+ {:ok, post_second} = TestRepo.insert(post_second, on_conflict: :replace_all)
2048
+
2049
+ assert post_first.id
2050
+ assert post_second.id
2051
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2052
+
2053
+ # Multiple record change value: note IDS are also replaced
2054
+ changes = [%{id: post_first.id + 2, title: "first_updated",
2055
+ visits: 1, uuid: post_first.uuid},
2056
+ %{id: post_second.id + 2, title: "second_updated",
2057
+ visits: 2, uuid: post_second.uuid}]
2058
+
2059
+ TestRepo.insert_all(Post, changes, on_conflict: :replace_all)
2060
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2061
+
2062
+ updated_first = TestRepo.get(Post, post_first.id + 2)
2063
+ assert updated_first.title == "first_updated"
2064
+ assert updated_first.visits == 1
2065
+
2066
+ updated_second = TestRepo.get(Post, post_second.id + 2)
2067
+ assert updated_second.title == "second_updated"
2068
+ assert updated_second.visits == 2
2069
+ end
2070
+
2071
+ @tag :with_conflict_target
2072
+ test "on conflict replace_all and conflict_target" do
2073
+ post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()}
2074
+ post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()}
2075
+
2076
+ {:ok, post_first} = TestRepo.insert(post_first, on_conflict: :replace_all, conflict_target: :uuid)
2077
+ {:ok, post_second} = TestRepo.insert(post_second, on_conflict: :replace_all, conflict_target: :uuid)
2078
+
2079
+ assert post_first.id
2080
+ assert post_second.id
2081
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2082
+
2083
+ # Multiple record change value: note IDS are also replaced
2084
+ changes = [%{id: post_second.id + 1, title: "first_updated",
2085
+ visits: 1, uuid: post_first.uuid},
2086
+ %{id: post_second.id + 2, title: "second_updated",
2087
+ visits: 2, uuid: post_second.uuid}]
2088
+
2089
+ TestRepo.insert_all(Post, changes, on_conflict: :replace_all, conflict_target: :uuid)
2090
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2091
+
2092
+ updated_first = TestRepo.get(Post, post_second.id + 1)
2093
+ assert updated_first.title == "first_updated"
2094
+ assert updated_first.visits == 1
2095
+
2096
+ updated_second = TestRepo.get(Post, post_second.id + 2)
2097
+ assert updated_second.title == "second_updated"
2098
+ assert updated_second.visits == 2
2099
+ end
2100
+
2101
+ @tag :without_conflict_target
2102
+ test "on conflict replace_all_except" do
2103
+ post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()}
2104
+ post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()}
2105
+
2106
+ {:ok, post_first} = TestRepo.insert(post_first, on_conflict: {:replace_all_except, [:id]})
2107
+ {:ok, post_second} = TestRepo.insert(post_second, on_conflict: {:replace_all_except, [:id]})
2108
+
2109
+ assert post_first.id
2110
+ assert post_second.id
2111
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2112
+
2113
+ # Multiple record change value: note IDS are not replaced
2114
+ changes = [%{id: post_first.id + 2, title: "first_updated",
2115
+ visits: 1, uuid: post_first.uuid},
2116
+ %{id: post_second.id + 2, title: "second_updated",
2117
+ visits: 2, uuid: post_second.uuid}]
2118
+
2119
+ TestRepo.insert_all(Post, changes, on_conflict: {:replace_all_except, [:id]})
2120
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2121
+
2122
+ updated_first = TestRepo.get(Post, post_first.id)
2123
+ assert updated_first.title == "first_updated"
2124
+ assert updated_first.visits == 1
2125
+
2126
+ updated_second = TestRepo.get(Post, post_second.id)
2127
+ assert updated_second.title == "second_updated"
2128
+ assert updated_second.visits == 2
2129
+ end
2130
+
2131
+ @tag :with_conflict_target
2132
+ test "on conflict replace_all_except and conflict_target" do
2133
+ post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()}
2134
+ post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()}
2135
+
2136
+ {:ok, post_first} = TestRepo.insert(post_first, on_conflict: {:replace_all_except, [:id]}, conflict_target: :uuid)
2137
+ {:ok, post_second} = TestRepo.insert(post_second, on_conflict: {:replace_all_except, [:id]}, conflict_target: :uuid)
2138
+
2139
+ assert post_first.id
2140
+ assert post_second.id
2141
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2142
+
2143
+ # Multiple record change value: note IDS are not replaced
2144
+ changes = [%{id: post_first.id + 2, title: "first_updated",
2145
+ visits: 1, uuid: post_first.uuid},
2146
+ %{id: post_second.id + 2, title: "second_updated",
2147
+ visits: 2, uuid: post_second.uuid}]
2148
+
2149
+ TestRepo.insert_all(Post, changes, on_conflict: {:replace_all_except, [:id]}, conflict_target: :uuid)
2150
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2151
+
2152
+ updated_first = TestRepo.get(Post, post_first.id)
2153
+ assert updated_first.title == "first_updated"
2154
+ assert updated_first.visits == 1
2155
+
2156
+ updated_second = TestRepo.get(Post, post_second.id)
2157
+ assert updated_second.title == "second_updated"
2158
+ assert updated_second.visits == 2
2159
+ end
2160
+
2161
+ @tag :with_conflict_target
2162
+ test "on conflict replace and conflict_target" do
2163
+ post_first = %Post{title: "first", visits: 10, public: true, uuid: Ecto.UUID.generate()}
2164
+ post_second = %Post{title: "second", visits: 20, public: false, uuid: Ecto.UUID.generate()}
2165
+
2166
+ {:ok, post_first} = TestRepo.insert(post_first, on_conflict: {:replace, [:title, :visits]}, conflict_target: :uuid)
2167
+ {:ok, post_second} = TestRepo.insert(post_second, on_conflict: {:replace, [:title, :visits]}, conflict_target: :uuid)
2168
+
2169
+ assert post_first.id
2170
+ assert post_second.id
2171
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2172
+
2173
+ # Multiple record change value: note `public` field is not changed
2174
+ changes = [%{id: post_first.id, title: "first_updated", visits: 11, public: false, uuid: post_first.uuid},
2175
+ %{id: post_second.id, title: "second_updated", visits: 21, public: true, uuid: post_second.uuid}]
2176
+
2177
+ TestRepo.insert_all(Post, changes, on_conflict: {:replace, [:title, :visits]}, conflict_target: :uuid)
2178
+ assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
2179
+
2180
+ updated_first = TestRepo.get(Post, post_first.id)
2181
+ assert updated_first.title == "first_updated"
2182
+ assert updated_first.visits == 11
2183
+ assert updated_first.public == true
2184
+
2185
+ updated_second = TestRepo.get(Post, post_second.id)
2186
+ assert updated_second.title == "second_updated"
2187
+ assert updated_second.visits == 21
2188
+ assert updated_second.public == false
2189
+ end
2190
+ end
2191
+
2192
+ describe "values list" do
2193
+ @describetag :values_list
2194
+
2195
+ test "all" do
2196
+ uuid_module = uuid_module(TestRepo.__adapter__())
2197
+ uuid = uuid_module.generate()
2198
+
2199
+ # Without select
2200
+ values = [%{bid: uuid, visits: 1}, %{bid: uuid, visits: 2}]
2201
+ types = %{bid: uuid_module, visits: :integer}
2202
+ query = from v in values(values, types)
2203
+ assert TestRepo.all(query) == values
2204
+
2205
+ # With select
2206
+ query = select(query, [v], {v, v.bid})
2207
+ assert TestRepo.all(query) == Enum.map(values, &{&1, &1.bid})
2208
+ end
2209
+
2210
+ test "all with join" do
2211
+ uuid_module = uuid_module(TestRepo.__adapter__())
2212
+ uuid = uuid_module.generate()
2213
+
2214
+ values1 = [%{bid: uuid, visits: 1}, %{bid: uuid, visits: 2}]
2215
+ values2 = [%{bid: uuid, visits: 1}]
2216
+ types = %{bid: uuid_module, visits: :integer}
2217
+
2218
+ query =
2219
+ from v1 in values(values1, types),
2220
+ join: v2 in values(values2, types),
2221
+ on: v1.visits == v2.visits
2222
+
2223
+ assert TestRepo.all(query) == [%{bid: uuid, visits: 1}]
2224
+ end
2225
+
2226
+ test "delete_all" do
2227
+ uuid_module = uuid_module(TestRepo.__adapter__())
2228
+ uuid = uuid_module.generate()
2229
+
2230
+ _p1 = TestRepo.insert!(%Post{bid: uuid, visits: 1})
2231
+ p2 = TestRepo.insert!(%Post{bid: uuid, visits: 5})
2232
+
2233
+ values = [%{bid: uuid, visits: 1}, %{bid: nil, visits: 1}, %{bid: uuid, visits: 3}]
2234
+ types = %{bid: uuid_module, visits: :integer}
2235
+
2236
+ query =
2237
+ from p in Post,
2238
+ join: v in values(values, types),
2239
+ on: p.visits == v.visits
2240
+
2241
+ assert {1, _} = TestRepo.delete_all(query)
2242
+ assert TestRepo.all(Post) == [p2]
2243
+ end
2244
+
2245
+ test "update_all" do
2246
+ uuid_module = uuid_module(TestRepo.__adapter__())
2247
+ uuid = uuid_module.generate()
2248
+
2249
+ TestRepo.insert!(%Post{bid: uuid, visits: 1})
2250
+
2251
+ values = [%{bid: uuid, visits: 10}, %{bid: nil, visits: 2}]
2252
+ types = %{bid: uuid_module, visits: :integer}
2253
+
2254
+ query =
2255
+ from p in Post,
2256
+ join: v in values(values, types),
2257
+ on: p.bid == v.bid,
2258
+ update: [set: [visits: v.visits]]
2259
+
2260
+ assert {1, _} = TestRepo.update_all(query, [])
2261
+ assert [%{visits: 10}] = TestRepo.all(Post)
2262
+ end
2263
+
2264
+ defp uuid_module(Ecto.Adapters.Tds), do: Tds.Ecto.UUID
2265
+ defp uuid_module(_), do: Ecto.UUID
2266
+ end
2267
+ end
deps/ecto/integration_test/cases/type.exs ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.TypeTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.{Bitstring, Comment, Custom, Item, ItemColor, Order, Post, User, Tag, Usec}
5
+ alias Ecto.Integration.TestRepo
6
+ import Ecto.Query
7
+
8
+ @parameterized_type Ecto.ParameterizedType.init(Ecto.Enum, values: [:a, :b])
9
+
10
+ test "primitive types" do
11
+ integer = 1
12
+ float = 0.1
13
+ blob = <<0, 1>>
14
+ uuid = "00010203-0405-4607-8809-0a0b0c0d0e0f"
15
+ datetime = ~N[2014-01-16 20:26:51]
16
+
17
+ TestRepo.insert!(%Post{blob: blob, public: true, visits: integer, uuid: uuid,
18
+ counter: integer, inserted_at: datetime, intensity: float})
19
+
20
+ # nil
21
+ assert [nil] = TestRepo.all(from Post, select: nil)
22
+
23
+ # ID
24
+ assert [1] = TestRepo.all(from p in Post, where: p.counter == ^integer, select: p.counter)
25
+
26
+ # Integers
27
+ assert [1] = TestRepo.all(from p in Post, where: p.visits == ^integer, select: p.visits)
28
+ assert [1] = TestRepo.all(from p in Post, where: p.visits == 1, select: p.visits)
29
+ assert [3] = TestRepo.all(from p in Post, select: p.visits + 2)
30
+
31
+ # Floats
32
+ assert [0.1] = TestRepo.all(from p in Post, where: p.intensity == ^float, select: p.intensity)
33
+ assert [0.1] = TestRepo.all(from p in Post, where: p.intensity == 0.1, select: p.intensity)
34
+ assert [1500.0] = TestRepo.all(from p in Post, select: 1500.0)
35
+ assert [0.5] = TestRepo.all(from p in Post, select: p.intensity * 5)
36
+
37
+ # Booleans
38
+ assert [true] = TestRepo.all(from p in Post, where: p.public == ^true, select: p.public)
39
+ assert [true] = TestRepo.all(from p in Post, where: p.public == true, select: p.public)
40
+
41
+ # Binaries
42
+ assert [^blob] = TestRepo.all(from p in Post, where: p.blob == <<0, 1>>, select: p.blob)
43
+ assert [^blob] = TestRepo.all(from p in Post, where: p.blob == ^blob, select: p.blob)
44
+
45
+ # UUID
46
+ assert [^uuid] = TestRepo.all(from p in Post, where: p.uuid == ^uuid, select: p.uuid)
47
+
48
+ # NaiveDatetime
49
+ assert [^datetime] = TestRepo.all(from p in Post, where: p.inserted_at == ^datetime, select: p.inserted_at)
50
+
51
+ # Datetime
52
+ datetime = DateTime.from_unix!(System.os_time(:second), :second)
53
+ TestRepo.insert!(%User{inserted_at: datetime})
54
+ assert [^datetime] = TestRepo.all(from u in User, where: u.inserted_at == ^datetime, select: u.inserted_at)
55
+
56
+ # usec
57
+ naive_datetime = ~N[2014-01-16 20:26:51.000000]
58
+ datetime = DateTime.from_naive!(~N[2014-01-16 20:26:51.000000], "Etc/UTC")
59
+ TestRepo.insert!(%Usec{naive_datetime_usec: naive_datetime, utc_datetime_usec: datetime})
60
+ assert [^naive_datetime] = TestRepo.all(from u in Usec, where: u.naive_datetime_usec == ^naive_datetime, select: u.naive_datetime_usec)
61
+ assert [^datetime] = TestRepo.all(from u in Usec, where: u.utc_datetime_usec == ^datetime, select: u.utc_datetime_usec)
62
+
63
+ naive_datetime = ~N[2014-01-16 20:26:51.123000]
64
+ datetime = DateTime.from_naive!(~N[2014-01-16 20:26:51.123000], "Etc/UTC")
65
+ TestRepo.insert!(%Usec{naive_datetime_usec: naive_datetime, utc_datetime_usec: datetime})
66
+ assert [^naive_datetime] = TestRepo.all(from u in Usec, where: u.naive_datetime_usec == ^naive_datetime, select: u.naive_datetime_usec)
67
+ assert [^datetime] = TestRepo.all(from u in Usec, where: u.utc_datetime_usec == ^datetime, select: u.utc_datetime_usec)
68
+ end
69
+
70
+ @tag :bitstring_type
71
+ test "bitstring type" do
72
+ bitstring = <<2::3>>
73
+
74
+ TestRepo.insert!(%Bitstring{bs: bitstring, bs_with_size: <<5::10>>})
75
+
76
+ # Bitstrings
77
+ assert [^bitstring] = TestRepo.all(from p in Bitstring, where: p.bs == ^bitstring, select: p.bs)
78
+ assert [^bitstring] = TestRepo.all(from p in Bitstring, where: p.bs == <<2::3>>, select: p.bs)
79
+
80
+ assert [<<42::6>>] = TestRepo.all(from p in Bitstring, limit: 1, select: p.bs_with_default)
81
+ end
82
+
83
+ if Code.ensure_loaded?(Duration) do
84
+ @tag :duration_type
85
+ test "duration type" do
86
+ duration = %Duration{year: 1, month: 1, second: 1, microsecond: {100, 6}}
87
+
88
+ struct = %Ecto.Integration.Duration{
89
+ dur: duration,
90
+ dur_with_fields: duration,
91
+ dur_with_precision: duration,
92
+ dur_with_fields_and_precision: duration
93
+ }
94
+
95
+ TestRepo.insert!(struct)
96
+
97
+ persisted_duration =
98
+ from(d in Ecto.Integration.Duration, where: d.dur == ^duration)
99
+ |> TestRepo.one()
100
+
101
+ assert persisted_duration.dur == duration
102
+
103
+ # `:field` option set to MONTH so it ignores all units lower than `:month`
104
+ assert persisted_duration.dur_with_fields == %Duration{
105
+ year: 1,
106
+ month: 1,
107
+ microsecond: {0, 6}
108
+ }
109
+
110
+ assert persisted_duration.dur_with_precision == %Duration{
111
+ year: 1,
112
+ month: 1,
113
+ second: 1,
114
+ microsecond: {100, 4}
115
+ }
116
+
117
+ # `:field` option is set to HOUR TO SECOND so it ignores all units lower than `:second`
118
+ assert persisted_duration.dur_with_fields_and_precision == %Duration{
119
+ year: 1,
120
+ month: 1,
121
+ second: 1,
122
+ microsecond: {0, 1}
123
+ }
124
+
125
+ # `:default set in migration`
126
+ assert persisted_duration.dur_with_default == %Duration{month: 10, microsecond: {0, 6}}
127
+ end
128
+ end
129
+
130
+ @tag :select_not
131
+ test "primitive types boolean negate" do
132
+ TestRepo.insert!(%Post{public: true})
133
+ assert [false] = TestRepo.all(from p in Post, where: p.public == true, select: not p.public)
134
+ assert [true] = TestRepo.all(from p in Post, where: p.public == true, select: not not p.public)
135
+ end
136
+
137
+ test "aggregate types" do
138
+ datetime = ~N[2014-01-16 20:26:51]
139
+ TestRepo.insert!(%Post{inserted_at: datetime})
140
+ query = from p in Post, select: max(p.inserted_at)
141
+ assert [^datetime] = TestRepo.all(query)
142
+ end
143
+
144
+ # We don't specifically assert on the tuple content because
145
+ # some databases would return integer, others decimal.
146
+ # The important is that the type has been invoked for wrapping.
147
+ test "aggregate custom types" do
148
+ TestRepo.insert!(%Post{wrapped_visits: {:int, 10}})
149
+ query = from p in Post, select: sum(p.wrapped_visits)
150
+ assert [{:int, _}] = TestRepo.all(query)
151
+ end
152
+
153
+ @tag :aggregate_filters
154
+ test "aggregate filter types" do
155
+ datetime = ~N[2014-01-16 20:26:51]
156
+ TestRepo.insert!(%Post{inserted_at: datetime})
157
+ query = from p in Post, select: filter(max(p.inserted_at), p.public == ^true)
158
+ assert [^datetime] = TestRepo.all(query)
159
+ end
160
+
161
+ test "coalesce text type when default" do
162
+ TestRepo.insert!(%Post{blob: nil})
163
+ blob = <<0, 1>>
164
+ query = from p in Post, select: coalesce(p.blob, ^blob)
165
+ assert [^blob] = TestRepo.all(query)
166
+ end
167
+
168
+ test "coalesce text type when value" do
169
+ blob = <<0, 2>>
170
+ default_blob = <<0, 1>>
171
+ TestRepo.insert!(%Post{blob: blob})
172
+ query = from p in Post, select: coalesce(p.blob, ^default_blob)
173
+ assert [^blob] = TestRepo.all(query)
174
+ end
175
+
176
+ test "tagged types" do
177
+ %{id: post_id} = TestRepo.insert!(%Post{visits: 12})
178
+ TestRepo.insert!(%Comment{text: "#{post_id}", post_id: post_id})
179
+
180
+ # Numbers
181
+ assert [1] = TestRepo.all(from Post, select: type(^"1", :integer))
182
+ assert [1.0] = TestRepo.all(from Post, select: type(^1.0, :float))
183
+ assert [1] = TestRepo.all(from p in Post, select: type(^"1", p.visits))
184
+ assert [1.0] = TestRepo.all(from p in Post, select: type(^"1", p.intensity))
185
+
186
+ # Custom wrappers
187
+ assert [1] = TestRepo.all(from Post, select: type(^"1", CustomPermalink))
188
+
189
+ # Custom types
190
+ uuid = Ecto.UUID.generate()
191
+ assert [^uuid] = TestRepo.all(from Post, select: type(^uuid, Ecto.UUID))
192
+
193
+ # Parameterized types
194
+ assert [:a] = TestRepo.all(from Post, select: type(^"a", ^@parameterized_type))
195
+
196
+ # Math operations
197
+ assert [4] = TestRepo.all(from Post, select: type(2 + ^"2", :integer))
198
+ assert [4.0] = TestRepo.all(from Post, select: type(2.0 + ^"2", :float))
199
+ assert [4] = TestRepo.all(from p in Post, select: type(2 + ^"2", p.visits))
200
+ assert [4.0] = TestRepo.all(from p in Post, select: type(2.0 + ^"2", p.intensity))
201
+
202
+ # Comparison expression
203
+ assert [12] = TestRepo.all(from p in Post, select: type(coalesce(p.visits, 0), :integer))
204
+ assert [1.0] = TestRepo.all(from p in Post, select: type(coalesce(p.intensity, 1.0), :float))
205
+
206
+ # parent_as/1
207
+ child = from c in Comment, where: type(parent_as(:posts).id, :string) == c.text, select: c.post_id
208
+ query = from p in Post, as: :posts, where: p.id in subquery(child), select: p.id
209
+ assert [post_id] == TestRepo.all(query)
210
+ end
211
+
212
+ test "binary id type" do
213
+ assert %Custom{} = custom = TestRepo.insert!(%Custom{})
214
+ bid = custom.bid
215
+ assert [^bid] = TestRepo.all(from c in Custom, select: c.bid)
216
+ assert [^bid] = TestRepo.all(from c in Custom, select: type(^bid, :binary_id))
217
+ end
218
+
219
+ @tag :like_match_blob
220
+ test "text type as blob" do
221
+ assert %Post{} = post = TestRepo.insert!(%Post{blob: <<0, 1, 2>>})
222
+ id = post.id
223
+ assert post.blob == <<0, 1, 2>>
224
+ assert [^id] = TestRepo.all(from p in Post, where: like(p.blob, ^<<0, 1, 2>>), select: p.id)
225
+ end
226
+
227
+ @tag :like_match_blob
228
+ @tag :text_type_as_string
229
+ test "text type as string" do
230
+ assert %Post{} = post = TestRepo.insert!(%Post{blob: "hello"})
231
+ id = post.id
232
+ assert post.blob == "hello"
233
+ assert [^id] = TestRepo.all(from p in Post, where: like(p.blob, ^"hello"), select: p.id)
234
+ end
235
+
236
+ @tag :array_type
237
+ test "array type" do
238
+ ints = [1, 2, 3]
239
+ tag = TestRepo.insert!(%Tag{ints: ints})
240
+
241
+ assert TestRepo.all(from t in Tag, where: t.ints == ^[], select: t.ints) == []
242
+ assert TestRepo.all(from t in Tag, where: t.ints == ^[1, 2, 3], select: t.ints) == [ints]
243
+
244
+ # Both sides interpolation
245
+ assert TestRepo.all(from t in Tag, where: ^"b" in ^["a", "b", "c"], select: t.ints) == [ints]
246
+ assert TestRepo.all(from t in Tag, where: ^"b" in [^"a", ^"b", ^"c"], select: t.ints) == [ints]
247
+
248
+ # Querying
249
+ assert TestRepo.all(from t in Tag, where: t.ints == [1, 2, 3], select: t.ints) == [ints]
250
+ assert TestRepo.all(from t in Tag, where: 0 in t.ints, select: t.ints) == []
251
+ assert TestRepo.all(from t in Tag, where: 1 in t.ints, select: t.ints) == [ints]
252
+
253
+ # Update
254
+ tag = TestRepo.update!(Ecto.Changeset.change tag, ints: nil)
255
+ assert TestRepo.get!(Tag, tag.id).ints == nil
256
+
257
+ tag = TestRepo.update!(Ecto.Changeset.change tag, ints: [3, 2, 1])
258
+ assert TestRepo.get!(Tag, tag.id).ints == [3, 2, 1]
259
+
260
+ # Update all
261
+ {1, _} = TestRepo.update_all(Tag, push: [ints: 0])
262
+ assert TestRepo.get!(Tag, tag.id).ints == [3, 2, 1, 0]
263
+
264
+ {1, _} = TestRepo.update_all(Tag, pull: [ints: 2])
265
+ assert TestRepo.get!(Tag, tag.id).ints == [3, 1, 0]
266
+
267
+ {1, _} = TestRepo.update_all(Tag, set: [ints: nil])
268
+ assert TestRepo.get!(Tag, tag.id).ints == nil
269
+ end
270
+
271
+ @tag :array_type
272
+ test "array type with custom types" do
273
+ uuids = ["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"]
274
+ TestRepo.insert!(%Tag{uuids: ["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"]})
275
+
276
+ assert TestRepo.all(from t in Tag, where: t.uuids == ^[], select: t.uuids) == []
277
+ assert TestRepo.all(from t in Tag, where: t.uuids == ^["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"],
278
+ select: t.uuids) == [uuids]
279
+
280
+ {1, _} = TestRepo.update_all(Tag, set: [uuids: nil])
281
+ assert TestRepo.all(from t in Tag, select: t.uuids) == [nil]
282
+ end
283
+
284
+ @tag :array_type
285
+ test "array type with nil in array" do
286
+ tag = TestRepo.insert!(%Tag{ints: [1, nil, 3]})
287
+ assert tag.ints == [1, nil, 3]
288
+ end
289
+
290
+ @tag :map_type
291
+ test "untyped map" do
292
+ post1 = TestRepo.insert!(%Post{meta: %{"foo" => "bar", "baz" => "bat"}})
293
+ post2 = TestRepo.insert!(%Post{meta: %{foo: "bar", baz: "bat"}})
294
+
295
+ assert TestRepo.all(from p in Post, where: p.id == ^post1.id, select: p.meta) ==
296
+ [%{"foo" => "bar", "baz" => "bat"}]
297
+ assert TestRepo.all(from p in Post, where: p.id == ^post2.id, select: p.meta) ==
298
+ [%{"foo" => "bar", "baz" => "bat"}]
299
+ end
300
+
301
+ @tag :map_type
302
+ test "typed string map" do
303
+ post1 = TestRepo.insert!(%Post{links: %{"foo" => "http://foo.com", "bar" => "http://bar.com"}})
304
+ post2 = TestRepo.insert!(%Post{links: %{foo: "http://foo.com", bar: "http://bar.com"}})
305
+
306
+ assert TestRepo.all(from p in Post, where: p.id == ^post1.id, select: p.links) ==
307
+ [%{"foo" => "http://foo.com", "bar" => "http://bar.com"}]
308
+ assert TestRepo.all(from p in Post, where: p.id == ^post2.id, select: p.links) ==
309
+ [%{"foo" => "http://foo.com", "bar" => "http://bar.com"}]
310
+ end
311
+
312
+ @tag :map_type
313
+ test "typed float map" do
314
+ post = TestRepo.insert!(%Post{intensities: %{"foo" => 1.0, "bar" => 416500.0}})
315
+
316
+ # Note we are using === since we want to check integer vs float
317
+ assert TestRepo.all(from p in Post, where: p.id == ^post.id, select: p.intensities) ===
318
+ [%{"foo" => 1.0, "bar" => 416500.0}]
319
+ end
320
+
321
+ @tag :map_type
322
+ test "map type on update" do
323
+ post = TestRepo.insert!(%Post{meta: %{"world" => "hello"}})
324
+ assert TestRepo.get!(Post, post.id).meta == %{"world" => "hello"}
325
+
326
+ post = TestRepo.update!(Ecto.Changeset.change post, meta: %{hello: "world"})
327
+ assert TestRepo.get!(Post, post.id).meta == %{"hello" => "world"}
328
+
329
+ query = from(p in Post, where: p.id == ^post.id)
330
+ TestRepo.update_all(query, set: [meta: %{world: "hello"}])
331
+ assert TestRepo.get!(Post, post.id).meta == %{"world" => "hello"}
332
+ end
333
+
334
+ @tag :map_type
335
+ test "embeds one" do
336
+ item = %Item{price: 123, valid_at: ~D[2014-01-16]}
337
+
338
+ order =
339
+ %Order{}
340
+ |> Ecto.Changeset.change
341
+ |> Ecto.Changeset.put_embed(:item, item)
342
+ |> TestRepo.insert!()
343
+
344
+ dbitem = TestRepo.get!(Order, order.id).item
345
+ assert item.reference == dbitem.reference
346
+ assert item.price == dbitem.price
347
+ assert item.valid_at == dbitem.valid_at
348
+ assert dbitem.id
349
+
350
+ [dbitem] = TestRepo.all(from o in Order, select: o.item)
351
+ assert item.reference == dbitem.reference
352
+ assert item.price == dbitem.price
353
+ assert item.valid_at == dbitem.valid_at
354
+ assert dbitem.id
355
+
356
+ {1, _} = TestRepo.update_all(Order, set: [item: %{dbitem | price: 456}])
357
+ assert TestRepo.get!(Order, order.id).item.price == 456
358
+ end
359
+
360
+ @tag :map_type
361
+ @tag :json_extract_path
362
+ test "json_extract_path with primitive values" do
363
+ order = %Order{metadata:
364
+ %{
365
+ :id => 123,
366
+ :time => ~T[09:00:00],
367
+ "code" => "good",
368
+ "'single quoted'" => "bar",
369
+ "\"double quoted\"" => "baz",
370
+ "enabled" => true,
371
+ "extra" => [%{"enabled" => false}]
372
+ }
373
+ }
374
+
375
+ order = TestRepo.insert!(order)
376
+
377
+ assert TestRepo.one(from o in Order, select: json_extract_path(o.metadata, ^["id"])) == 123
378
+ assert TestRepo.one(from o in Order, select: o.metadata["bad"]) == nil
379
+ assert TestRepo.one(from o in Order, select: o.metadata["bad"]["bad"]) == nil
380
+
381
+ field = "id"
382
+ assert TestRepo.one(from o in Order, select: o.metadata[^field]) == 123
383
+ assert TestRepo.one(from o in Order, select: o.metadata["time"]) == "09:00:00"
384
+ assert TestRepo.one(from o in Order, select: o.metadata["'single quoted'"]) == "bar"
385
+ assert TestRepo.one(from o in Order, select: o.metadata["';"]) == nil
386
+ assert TestRepo.one(from o in Order, select: o.metadata["\"double quoted\""]) == "baz"
387
+ assert TestRepo.one(from o in Order, select: o.metadata["enabled"]) == true
388
+ assert TestRepo.one(from o in Order, select: o.metadata["extra"][0]["enabled"]) == false
389
+
390
+ # where
391
+ assert TestRepo.one(from o in Order, where: o.metadata["id"] == 123, select: o.id) == order.id
392
+ assert TestRepo.one(from o in Order, where: o.metadata["id"] == 456, select: o.id) == nil
393
+ assert TestRepo.one(from o in Order, where: o.metadata["code"] == "good", select: o.id) == order.id
394
+ assert TestRepo.one(from o in Order, where: o.metadata["code"] == "bad", select: o.id) == nil
395
+ assert TestRepo.one(from o in Order, where: o.metadata["enabled"] == true, select: o.id) == order.id
396
+ assert TestRepo.one(from o in Order, where: o.metadata["extra"][0]["enabled"] == false, select: o.id) == order.id
397
+ end
398
+
399
+ @tag :map_type
400
+ @tag :json_extract_path
401
+ test "json_extract_path with arrays and objects" do
402
+ order = %Order{metadata: %{tags: [%{name: "red"}, %{name: "green"}]}}
403
+ order = TestRepo.insert!(order)
404
+
405
+ assert TestRepo.one(from o in Order, select: o.metadata["tags"][0]["name"]) == "red"
406
+ assert TestRepo.one(from o in Order, select: o.metadata["tags"][99]["name"]) == nil
407
+
408
+ index = 1
409
+ assert TestRepo.one(from o in Order, select: o.metadata["tags"][^index]["name"]) == "green"
410
+
411
+ # where
412
+ assert TestRepo.one(from o in Order, where: o.metadata["tags"][0]["name"] == "red", select: o.id) == order.id
413
+ assert TestRepo.one(from o in Order, where: o.metadata["tags"][0]["name"] == "blue", select: o.id) == nil
414
+ assert TestRepo.one(from o in Order, where: o.metadata["tags"][99]["name"] == "red", select: o.id) == nil
415
+ end
416
+
417
+ @tag :map_type
418
+ @tag :json_extract_path
419
+ test "json_extract_path with embeds" do
420
+ order = %Order{items: [%{valid_at: ~D[2020-01-01]}]}
421
+ TestRepo.insert!(order)
422
+
423
+ assert TestRepo.one(from o in Order, select: o.items[0]["valid_at"]) == "2020-01-01"
424
+ end
425
+
426
+ @tag :map_type
427
+ @tag :json_extract_path
428
+ test "json_extract_path with custom field source" do
429
+ order = TestRepo.insert!(%Order{metadata: %{tags: [%{name: "red"}, %{name: "green"}]}})
430
+
431
+ assert TestRepo.one(from o in Order, where: o.metadata["tags"][0]["name"] == "red", select: o.id) == order.id
432
+ end
433
+
434
+ @tag :map_type
435
+ @tag :map_type_schemaless
436
+ test "embeds one with custom type" do
437
+ item = %Item{price: 123, reference: "PREFIX-EXAMPLE"}
438
+
439
+ order =
440
+ %Order{}
441
+ |> Ecto.Changeset.change
442
+ |> Ecto.Changeset.put_embed(:item, item)
443
+ |> TestRepo.insert!()
444
+
445
+ dbitem = TestRepo.get!(Order, order.id).item
446
+ assert dbitem.reference == "PREFIX-EXAMPLE"
447
+ assert [%{"reference" => "EXAMPLE"}] = TestRepo.all(from o in "orders", select: o.item)
448
+ end
449
+
450
+ @tag :map_type
451
+ test "empty embeds one" do
452
+ order = TestRepo.insert!(%Order{})
453
+ assert order.item == nil
454
+ assert TestRepo.get!(Order, order.id).item == nil
455
+ end
456
+
457
+ @tag :map_type
458
+ @tag :array_type
459
+ test "embeds many" do
460
+ item = %Item{price: 123, valid_at: ~D[2014-01-16]}
461
+ tag =
462
+ %Tag{}
463
+ |> Ecto.Changeset.change
464
+ |> Ecto.Changeset.put_embed(:items, [item])
465
+ tag = TestRepo.insert!(tag)
466
+
467
+ [dbitem] = TestRepo.get!(Tag, tag.id).items
468
+ assert item.price == dbitem.price
469
+ assert item.valid_at == dbitem.valid_at
470
+ assert dbitem.id
471
+
472
+ [[dbitem]] = TestRepo.all(from t in Tag, select: t.items)
473
+ assert item.price == dbitem.price
474
+ assert item.valid_at == dbitem.valid_at
475
+ assert dbitem.id
476
+
477
+ {1, _} = TestRepo.update_all(Tag, set: [items: [%{dbitem | price: 456}]])
478
+ assert (TestRepo.get!(Tag, tag.id).items |> hd).price == 456
479
+ end
480
+
481
+ @tag :map_type
482
+ @tag :array_type
483
+ test "empty embeds many" do
484
+ tag = TestRepo.insert!(%Tag{})
485
+ assert tag.items == []
486
+ assert TestRepo.get!(Tag, tag.id).items == []
487
+ end
488
+
489
+ @tag :map_type
490
+ @tag :array_type
491
+ test "nested embeds" do
492
+ red = %ItemColor{name: "red"}
493
+ blue = %ItemColor{name: "blue"}
494
+ item = %Item{
495
+ primary_color: red,
496
+ secondary_colors: [blue]
497
+ }
498
+
499
+ order =
500
+ %Order{}
501
+ |> Ecto.Changeset.change
502
+ |> Ecto.Changeset.put_embed(:item, item)
503
+ order = TestRepo.insert!(order)
504
+
505
+ dbitem = TestRepo.get!(Order, order.id).item
506
+ assert dbitem.primary_color.name == "red"
507
+ assert Enum.map(dbitem.secondary_colors, & &1.name) == ["blue"]
508
+ assert dbitem.id
509
+ assert dbitem.primary_color.id
510
+
511
+ [dbitem] = TestRepo.all(from o in Order, select: o.item)
512
+ assert dbitem.primary_color.name == "red"
513
+ assert Enum.map(dbitem.secondary_colors, & &1.name) == ["blue"]
514
+ assert dbitem.id
515
+ assert dbitem.primary_color.id
516
+ end
517
+
518
+ @tag :decimal_type
519
+ test "decimal type" do
520
+ decimal = Decimal.new("1.0")
521
+ TestRepo.insert!(%Post{cost: decimal})
522
+
523
+ [cost] = TestRepo.all(from p in Post, where: p.cost == ^decimal, select: p.cost)
524
+ assert Decimal.equal?(decimal, cost)
525
+ [cost] = TestRepo.all(from p in Post, where: p.cost == ^1.0, select: p.cost)
526
+ assert Decimal.equal?(decimal, cost)
527
+ [cost] = TestRepo.all(from p in Post, where: p.cost == ^1, select: p.cost)
528
+ assert Decimal.equal?(decimal, cost)
529
+ [cost] = TestRepo.all(from p in Post, where: p.cost == 1.0, select: p.cost)
530
+ assert Decimal.equal?(decimal, cost)
531
+ [cost] = TestRepo.all(from p in Post, where: p.cost == 1, select: p.cost)
532
+ assert Decimal.equal?(decimal, cost)
533
+ [cost] = TestRepo.all(from p in Post, select: p.cost * 2)
534
+ assert Decimal.equal?(Decimal.new("2.0"), cost)
535
+ [cost] = TestRepo.all(from p in Post, select: p.cost - p.cost)
536
+ assert Decimal.equal?(Decimal.new("0.0"), cost)
537
+ end
538
+
539
+ @tag :decimal_type
540
+ @tag :decimal_precision
541
+ test "decimal typed aggregations" do
542
+ decimal = Decimal.new("1.0")
543
+ TestRepo.insert!(%Post{cost: decimal})
544
+
545
+ assert [1] = TestRepo.all(from p in Post, select: type(sum(p.cost), :integer))
546
+ assert [1.0] = TestRepo.all(from p in Post, select: type(sum(p.cost), :float))
547
+ [cost] = TestRepo.all(from p in Post, select: type(sum(p.cost), :decimal))
548
+ assert Decimal.equal?(decimal, cost)
549
+ end
550
+
551
+ @tag :decimal_type
552
+ test "on coalesce with mixed types" do
553
+ decimal = Decimal.new("1.0")
554
+ TestRepo.insert!(%Post{cost: decimal})
555
+ [cost] = TestRepo.all(from p in Post, select: coalesce(p.cost, 0))
556
+ assert Decimal.equal?(decimal, cost)
557
+ end
558
+
559
+ @tag :union_with_literals
560
+ test "unions with literals" do
561
+ TestRepo.insert!(%Post{})
562
+ TestRepo.insert!(%Post{})
563
+
564
+ query1 = from(p in Post, select: %{n: 1})
565
+ query2 = from(p in Post, select: %{n: 2})
566
+
567
+ assert TestRepo.all(union_all(query1, ^query2)) ==
568
+ [%{n: 1}, %{n: 1}, %{n: 2}, %{n: 2}]
569
+
570
+ query1 = from(p in Post, select: %{n: 1.0})
571
+ query2 = from(p in Post, select: %{n: 2.0})
572
+
573
+ assert TestRepo.all(union_all(query1, ^query2)) ==
574
+ [%{n: 1.0}, %{n: 1.0}, %{n: 2.0}, %{n: 2.0}]
575
+
576
+ query1 = from(p in Post, select: %{n: "foo"})
577
+ query2 = from(p in Post, select: %{n: "bar"})
578
+
579
+ assert TestRepo.all(union_all(query1, ^query2)) ==
580
+ [%{n: "foo"}, %{n: "foo"}, %{n: "bar"}, %{n: "bar"}]
581
+ end
582
+
583
+ test "schemaless types" do
584
+ TestRepo.insert!(%Post{visits: 123})
585
+ assert [123] = TestRepo.all(from p in "posts", select: type(p.visits, :integer))
586
+ end
587
+
588
+ test "schemaless calendar types" do
589
+ datetime = ~N[2014-01-16 20:26:51]
590
+ assert {1, _} =
591
+ TestRepo.insert_all("posts", [[inserted_at: datetime]])
592
+ assert {1, _} =
593
+ TestRepo.update_all("posts", set: [inserted_at: datetime])
594
+ assert [_] =
595
+ TestRepo.all(from p in "posts", where: p.inserted_at >= ^datetime, select: p.inserted_at)
596
+ assert [_] =
597
+ TestRepo.all(from p in "posts", where: p.inserted_at in [^datetime], select: p.inserted_at)
598
+ assert [_] =
599
+ TestRepo.all(from p in "posts", where: p.inserted_at in ^[datetime], select: p.inserted_at)
600
+ end
601
+ end
deps/ecto/integration_test/cases/windows.exs ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Integration.WindowsTest do
2
+ use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true)
3
+
4
+ alias Ecto.Integration.TestRepo
5
+ import Ecto.Query
6
+
7
+ alias Ecto.Integration.{Comment, User, Post}
8
+
9
+ test "over" do
10
+ u1 = TestRepo.insert!(%User{name: "Tester"})
11
+ u2 = TestRepo.insert!(%User{name: "Developer"})
12
+ c1 = TestRepo.insert!(%Comment{text: "1", author_id: u1.id})
13
+ c2 = TestRepo.insert!(%Comment{text: "2", author_id: u1.id})
14
+ c3 = TestRepo.insert!(%Comment{text: "3", author_id: u1.id})
15
+ c4 = TestRepo.insert!(%Comment{text: "4", author_id: u2.id})
16
+
17
+ # Over nothing
18
+ query = from(c in Comment, select: [c, count(c.id) |> over()])
19
+ assert [[^c1, 4], [^c2, 4], [^c3, 4], [^c4, 4]] = TestRepo.all(query)
20
+
21
+ # Over partition
22
+ query = from(c in Comment, select: [c, count(c.id) |> over(partition_by: c.author_id)])
23
+ assert [[^c1, 3], [^c2, 3], [^c3, 3], [^c4, 1]] = TestRepo.all(query)
24
+
25
+ # Over window
26
+ query = from(c in Comment, windows: [w: [partition_by: c.author_id]], select: [c, count(c.id) |> over(:w)])
27
+ assert [[^c1, 3], [^c2, 3], [^c3, 3], [^c4, 1]] = TestRepo.all(query)
28
+ end
29
+
30
+ test "frame" do
31
+ posts = Enum.map(0..6, &%{counter: &1, visits: round(:math.pow(2, &1))})
32
+ TestRepo.insert_all(Post, posts)
33
+
34
+ n = 1
35
+ query = from(p in Post,
36
+ windows: [w: [order_by: p.counter, frame: fragment("ROWS BETWEEN ? PRECEDING AND ? FOLLOWING", ^n, ^n)]],
37
+ select: [p.counter, sum(p.visits) |> over(:w)]
38
+ )
39
+ assert [[0, 3], [1, 7], [2, 14], [3, 28], [4, 56], [5, 112], [6, 96]] = TestRepo.all(query)
40
+
41
+ query = from(p in Post,
42
+ windows: [w: [order_by: p.counter, frame: fragment("ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING")]],
43
+ select: [p.counter, sum(p.visits) |> over(:w)]
44
+ )
45
+ assert [[0, 126], [1, 124], [2, 120], [3, 112], [4, 96], [5, 64], [6, nil]] = TestRepo.all(query)
46
+
47
+ query = from(p in Post,
48
+ windows: [w: [order_by: p.counter, frame: fragment("ROWS CURRENT ROW")]],
49
+ select: [p.counter, sum(p.visits) |> over(:w)]
50
+ )
51
+ assert [[0, 1], [1, 2], [2, 4], [3, 8], [4, 16], [5, 32], [6, 64]] = TestRepo.all(query)
52
+ end
53
+ end
deps/ecto/integration_test/support/schemas.exs ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Code.require_file("types.exs", __DIR__)
2
+
3
+ defmodule Ecto.Integration.Schema do
4
+ defmacro __using__(_) do
5
+ quote do
6
+ use Ecto.Schema
7
+
8
+ type =
9
+ Application.compile_env(:ecto, :primary_key_type) ||
10
+ raise ":primary_key_type not set in :ecto application"
11
+
12
+ @primary_key {:id, type, autogenerate: true}
13
+ @foreign_key_type type
14
+ end
15
+ end
16
+ end
17
+
18
+ defmodule Ecto.Integration.Post do
19
+ @moduledoc """
20
+ This module is used to test:
21
+
22
+ * Overall functionality
23
+ * Overall types
24
+ * Non-null timestamps
25
+ * Relationships
26
+ * Dependent callbacks
27
+
28
+ """
29
+ use Ecto.Integration.Schema
30
+ import Ecto.Changeset
31
+ import Ecto.Query, only: [dynamic: 2]
32
+
33
+ schema "posts" do
34
+ field :counter, :id # Same as integer
35
+ field :title, :string
36
+ field :blob, :binary
37
+ field :temp, :string, default: "temp", virtual: true
38
+ field :public, :boolean, default: true
39
+ field :cost, :decimal
40
+ field :visits, :integer
41
+ field :wrapped_visits, WrappedInteger
42
+ field :intensity, :float
43
+ field :bid, :binary_id
44
+ field :uuid, Ecto.Integration.TestRepo.uuid(), autogenerate: true
45
+ field :meta, :map
46
+ field :links, {:map, :string}
47
+ field :intensities, {:map, :float}
48
+ field :posted, :date
49
+ has_many :comments, Ecto.Integration.Comment, on_delete: :delete_all, on_replace: :delete
50
+ has_many :force_comments, Ecto.Integration.Comment, on_replace: :delete_if_exists
51
+ has_many :ordered_comments, Ecto.Integration.Comment, preload_order: [:text]
52
+ # The post<->permalink relationship should be marked as uniq
53
+ has_one :permalink, Ecto.Integration.Permalink, on_delete: :delete_all, on_replace: :delete
54
+ has_one :force_permalink, Ecto.Integration.Permalink, on_replace: :delete_if_exists
55
+ has_one :update_permalink, Ecto.Integration.Permalink, foreign_key: :post_id, on_delete: :delete_all, on_replace: :update
56
+ has_many :comments_authors, through: [:comments, :author]
57
+ belongs_to :author, Ecto.Integration.User
58
+ many_to_many :users, Ecto.Integration.User,
59
+ join_through: "posts_users", on_delete: :delete_all, on_replace: :delete
60
+ many_to_many :ordered_users, Ecto.Integration.User, join_through: "posts_users", preload_order: [desc: :name]
61
+ many_to_many :ordered_users_by_join_table, Ecto.Integration.User,
62
+ join_through: "posts_users", preload_order: {__MODULE__, :preload_order, []}
63
+ many_to_many :unique_users, Ecto.Integration.User,
64
+ join_through: "posts_users", unique: true
65
+ many_to_many :constraint_users, Ecto.Integration.User,
66
+ join_through: Ecto.Integration.PostUserCompositePk
67
+ has_many :users_comments, through: [:users, :comments]
68
+ has_many :comments_authors_permalinks, through: [:comments_authors, :permalink]
69
+ has_one :post_user_composite_pk, Ecto.Integration.PostUserCompositePk
70
+ timestamps()
71
+ end
72
+
73
+ def preload_order() do
74
+ [desc: dynamic([assoc, join], join.user_id)]
75
+ end
76
+
77
+ def changeset(schema, params) do
78
+ cast(schema, params, ~w(counter title blob temp public cost visits
79
+ intensity bid uuid meta posted)a)
80
+ end
81
+ end
82
+
83
+ defmodule Ecto.Integration.Comment do
84
+ @moduledoc """
85
+ This module is used to test:
86
+
87
+ * Optimistic lock
88
+ * Relationships
89
+ * Dependent callbacks
90
+
91
+ """
92
+ use Ecto.Integration.Schema
93
+
94
+ schema "comments" do
95
+ field :text, :string
96
+ field :lock_version, :integer, default: 1
97
+ belongs_to :post, Ecto.Integration.Post
98
+ belongs_to :author, Ecto.Integration.User
99
+ has_one :post_permalink, through: [:post, :permalink]
100
+ has_one :author_permalink, through: [:author, :permalink]
101
+ end
102
+
103
+ def changeset(schema, params) do
104
+ Ecto.Changeset.cast(schema, params, [:text])
105
+ end
106
+ end
107
+
108
+ defmodule Ecto.Integration.Permalink do
109
+ @moduledoc """
110
+ This module is used to test:
111
+
112
+ * Field sources
113
+ * Relationships
114
+ * Dependent callbacks
115
+
116
+ """
117
+ use Ecto.Integration.Schema
118
+
119
+ schema "permalinks" do
120
+ field :url, :string, source: :uniform_resource_locator
121
+ field :title, :string
122
+ field :posted, :date, virtual: true
123
+ belongs_to :post, Ecto.Integration.Post, on_replace: :nilify
124
+ belongs_to :update_post, Ecto.Integration.Post, on_replace: :update, foreign_key: :post_id, define_field: false
125
+ belongs_to :user, Ecto.Integration.User
126
+ has_many :post_comments_authors, through: [:post, :comments_authors]
127
+ has_many :user_posts, through: [:user, :posts]
128
+ end
129
+
130
+ def changeset(schema, params) do
131
+ Ecto.Changeset.cast(schema, params, [:url, :title])
132
+ end
133
+ end
134
+
135
+ defmodule Ecto.Integration.PostUser do
136
+ @moduledoc """
137
+ This module is used to test:
138
+
139
+ * Many to many associations join_through with schema
140
+
141
+ """
142
+ use Ecto.Integration.Schema
143
+
144
+ schema "posts_users_pk" do
145
+ belongs_to :user, Ecto.Integration.User
146
+ belongs_to :post, Ecto.Integration.Post
147
+ timestamps()
148
+ end
149
+ end
150
+
151
+ defmodule Ecto.Integration.User do
152
+ @moduledoc """
153
+ This module is used to test:
154
+
155
+ * UTC Timestamps
156
+ * Relationships
157
+ * Dependent callbacks
158
+
159
+ """
160
+ use Ecto.Integration.Schema
161
+
162
+ schema "users" do
163
+ field :name, :string
164
+ has_many :comments, Ecto.Integration.Comment, foreign_key: :author_id, on_delete: :nilify_all, on_replace: :nilify
165
+ has_one :permalink, Ecto.Integration.Permalink, on_replace: :nilify
166
+ has_many :posts, Ecto.Integration.Post, foreign_key: :author_id, on_delete: :nothing, on_replace: :delete
167
+ belongs_to :custom, Ecto.Integration.Custom, references: :bid, type: :binary_id
168
+ many_to_many :schema_posts, Ecto.Integration.Post, join_through: Ecto.Integration.PostUser
169
+ many_to_many :unique_posts, Ecto.Integration.Post, join_through: Ecto.Integration.PostUserCompositePk
170
+
171
+ has_many :related_2nd_order_posts, through: [:posts, :users, :posts]
172
+ has_many :users_through_schema_posts, through: [:schema_posts, :users]
173
+
174
+ has_many :v2_comments, Ecto.Integration.Comment, foreign_key: :author_id, where: [lock_version: 2]
175
+ has_many :v2_comments_posts, through: [:v2_comments, :post]
176
+ has_many :co_commenters, through: [:comments, :post, :comments_authors]
177
+
178
+ timestamps(type: :utc_datetime)
179
+ end
180
+ end
181
+
182
+ defmodule Ecto.Integration.Custom do
183
+ @moduledoc """
184
+ This module is used to test:
185
+
186
+ * binary_id primary key
187
+ * Tying another schemas to an existing schema
188
+
189
+ Due to the second item, it must be a subset of posts.
190
+ """
191
+ use Ecto.Integration.Schema
192
+
193
+ @primary_key {:bid, :binary_id, autogenerate: true}
194
+ schema "customs" do
195
+ field :uuid, Ecto.Integration.TestRepo.uuid()
196
+ many_to_many :customs, Ecto.Integration.Custom,
197
+ join_through: "customs_customs", join_keys: [custom_id1: :bid, custom_id2: :bid],
198
+ on_delete: :delete_all, on_replace: :delete
199
+ end
200
+ end
201
+
202
+ defmodule Ecto.Integration.Barebone do
203
+ @moduledoc """
204
+ This module is used to test:
205
+
206
+ * A schema without primary keys
207
+
208
+ """
209
+ use Ecto.Integration.Schema
210
+
211
+ @primary_key false
212
+ schema "barebones" do
213
+ field :num, :integer
214
+ end
215
+ end
216
+
217
+ defmodule Ecto.Integration.Tag do
218
+ @moduledoc """
219
+ This module is used to test:
220
+
221
+ * The array type
222
+ * Embedding many schemas (uses array)
223
+
224
+ """
225
+ use Ecto.Integration.Schema
226
+
227
+ schema "tags" do
228
+ field :ints, {:array, :integer}
229
+ field :uuids, {:array, Ecto.Integration.TestRepo.uuid()}
230
+ embeds_many :items, Ecto.Integration.Item
231
+ end
232
+ end
233
+
234
+ defmodule Ecto.Integration.Item do
235
+ @moduledoc """
236
+ This module is used to test:
237
+
238
+ * Embedding
239
+ * Preloading associations in embedded schemas
240
+
241
+ """
242
+ use Ecto.Schema
243
+
244
+ embedded_schema do
245
+ field :reference, PrefixedString
246
+ field :price, :integer
247
+ field :valid_at, :date
248
+
249
+ embeds_one :primary_color, Ecto.Integration.ItemColor
250
+ embeds_many :secondary_colors, Ecto.Integration.ItemColor
251
+
252
+ belongs_to :user, Ecto.Integration.User
253
+ end
254
+ end
255
+
256
+ defmodule Ecto.Integration.ItemColor do
257
+ @moduledoc """
258
+ This module is used to test:
259
+
260
+ * Nested embeds
261
+
262
+ """
263
+ use Ecto.Schema
264
+
265
+ embedded_schema do
266
+ field :name, :string
267
+ end
268
+ end
269
+
270
+ defmodule Ecto.Integration.Order do
271
+ @moduledoc """
272
+ This module is used to test:
273
+
274
+ * Text columns
275
+ * Embedding one schema
276
+ * Preloading items inside embeds_many
277
+ * Preloading items inside embeds_one
278
+ * Field source with json_extract_path
279
+
280
+ """
281
+ use Ecto.Integration.Schema
282
+
283
+ schema "orders" do
284
+ field :metadata, :map, source: :meta
285
+ embeds_one :item, Ecto.Integration.Item
286
+ embeds_many :items, Ecto.Integration.Item
287
+ belongs_to :permalink, Ecto.Integration.Permalink
288
+ end
289
+ end
290
+
291
+ defmodule Ecto.Integration.CompositePk do
292
+ @moduledoc """
293
+ This module is used to test:
294
+
295
+ * Composite primary keys
296
+
297
+ """
298
+ use Ecto.Integration.Schema
299
+ import Ecto.Changeset
300
+
301
+ @primary_key false
302
+ schema "composite_pk" do
303
+ field :a, :integer, primary_key: true
304
+ field :b, :integer, primary_key: true
305
+ field :name, :string
306
+ end
307
+ def changeset(schema, params) do
308
+ cast(schema, params, ~w(a b name)a)
309
+ end
310
+ end
311
+
312
+ defmodule Ecto.Integration.CorruptedPk do
313
+ @moduledoc """
314
+ This module is used to test:
315
+
316
+ * Primary keys that is not unique on a DB side
317
+
318
+ """
319
+ use Ecto.Integration.Schema
320
+
321
+ @primary_key false
322
+ schema "corrupted_pk" do
323
+ field :a, :string, primary_key: true
324
+ end
325
+ end
326
+
327
+ defmodule Ecto.Integration.PostUserCompositePk do
328
+ @moduledoc """
329
+ This module is used to test:
330
+
331
+ * Composite primary keys for 2 belongs_to fields
332
+
333
+ """
334
+ use Ecto.Integration.Schema
335
+
336
+ @primary_key false
337
+ schema "posts_users_composite_pk" do
338
+ belongs_to :user, Ecto.Integration.User, primary_key: true
339
+ belongs_to :post, Ecto.Integration.Post, primary_key: true
340
+ timestamps()
341
+ end
342
+ end
343
+
344
+ defmodule Ecto.Integration.Usec do
345
+ @moduledoc """
346
+ This module is used to test:
347
+
348
+ * usec datetime types
349
+
350
+ """
351
+ use Ecto.Integration.Schema
352
+
353
+ schema "usecs" do
354
+ field :naive_datetime_usec, :naive_datetime_usec
355
+ field :utc_datetime_usec, :utc_datetime_usec
356
+ end
357
+ end
358
+
359
+ defmodule Ecto.Integration.Logging do
360
+ @moduledoc """
361
+ This module is used to test:
362
+
363
+ * Logging the casted version of parameters without array types
364
+
365
+ """
366
+ use Ecto.Integration.Schema
367
+
368
+ @primary_key {:bid, :binary_id, autogenerate: true}
369
+ schema "loggings" do
370
+ field :int, :integer
371
+ field :uuid, Ecto.Integration.TestRepo.uuid()
372
+ timestamps()
373
+ end
374
+ end
375
+
376
+ defmodule Ecto.Integration.ArrayLogging do
377
+ @moduledoc """
378
+ This module is used to test:
379
+
380
+ * Logging the casted version of parameters with array types
381
+
382
+ """
383
+ use Ecto.Integration.Schema
384
+
385
+ schema "array_loggings" do
386
+ field :uuids, {:array, Ecto.Integration.TestRepo.uuid()}
387
+ timestamps()
388
+ end
389
+ end
390
+
391
+ defmodule Ecto.Integration.Bitstring do
392
+ @moduledoc """
393
+ This module is used to test:
394
+
395
+ * Bitstring type
396
+
397
+ """
398
+ use Ecto.Integration.Schema
399
+
400
+ schema "bitstrings" do
401
+ field :bs, :bitstring
402
+ field :bs_with_default, :bitstring
403
+ field :bs_with_size, :bitstring
404
+ end
405
+ end
406
+
407
+ if Code.ensure_loaded?(Duration) do
408
+ defmodule Ecto.Integration.Duration do
409
+ @moduledoc """
410
+ This module is used to test:
411
+ * Duration type
412
+ """
413
+ use Ecto.Integration.Schema
414
+
415
+ schema "durations" do
416
+ field :dur, :duration
417
+ field :dur_with_fields, :duration
418
+ field :dur_with_precision, :duration
419
+ field :dur_with_fields_and_precision, :duration
420
+ field :dur_with_default, :duration
421
+ end
422
+ end
423
+ end
deps/ecto/integration_test/support/types.exs ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule CustomPermalink do
2
+ def type, do: :id
3
+
4
+ def cast(string) when is_binary(string) do
5
+ case Integer.parse(string) do
6
+ {int, _} -> {:ok, int}
7
+ :error -> :error
8
+ end
9
+ end
10
+
11
+ def cast(integer) when is_integer(integer), do: {:ok, integer}
12
+ def cast(_), do: :error
13
+
14
+ def load(integer) when is_integer(integer), do: {:ok, integer}
15
+ def dump(integer) when is_integer(integer), do: {:ok, integer}
16
+ end
17
+
18
+ defmodule PrefixedString do
19
+ use Ecto.Type
20
+ def type(), do: :string
21
+ def cast(string), do: {:ok, string}
22
+ def load(string), do: {:ok, "PREFIX-" <> string}
23
+ def dump("PREFIX-" <> string), do: {:ok, string}
24
+ def dump(_string), do: :error
25
+ def embed_as(_), do: :dump
26
+ end
27
+
28
+ defmodule WrappedInteger do
29
+ use Ecto.Type
30
+ def type(), do: :integer
31
+ def cast(integer), do: {:ok, {:int, integer}}
32
+ def load(integer), do: {:ok, {:int, integer}}
33
+ def dump({:int, integer}), do: {:ok, integer}
34
+ end
35
+
36
+ defmodule ParameterizedPrefixedString do
37
+ use Ecto.ParameterizedType
38
+ def init(opts), do: Enum.into(opts, %{})
39
+ def type(_), do: :string
40
+
41
+ def cast(data, %{prefix: prefix}) do
42
+ if String.starts_with?(data, [prefix <> "-"]) do
43
+ {:ok, data}
44
+ else
45
+ {:ok, prefix <> "-" <> data}
46
+ end
47
+ end
48
+
49
+ def load(string, _, %{prefix: prefix}), do: {:ok, prefix <> "-" <> string}
50
+ def dump(nil, _, _), do: {:ok, nil}
51
+ def dump(data, _, %{prefix: _prefix}), do: {:ok, data |> String.split("-") |> List.last()}
52
+ def embed_as(_, _), do: :dump
53
+ end
deps/ecto/lib/ecto.ex ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto do
2
+ @moduledoc ~S"""
3
+ Ecto is split into 4 main components:
4
+
5
+ * `Ecto.Repo` - repositories are wrappers around the data store.
6
+ Via the repository, we can create, update, destroy and query
7
+ existing entries. A repository needs an adapter and credentials
8
+ to communicate to the database
9
+
10
+ * `Ecto.Schema` - schemas are used to map external data into Elixir
11
+ structs. We often use them to map database tables to Elixir data but
12
+ they have many other use cases
13
+
14
+ * `Ecto.Query` - written in Elixir syntax, queries are used to retrieve
15
+ information from a given repository. Ecto queries are secure and composable
16
+
17
+ * `Ecto.Changeset` - changesets provide a way to track and validate changes
18
+ before they are applied to the data
19
+
20
+ In summary:
21
+
22
+ * `Ecto.Repo` - **where** the data is
23
+ * `Ecto.Schema` - **what** the data is
24
+ * `Ecto.Query` - **how to read** the data
25
+ * `Ecto.Changeset` - **how to change** the data
26
+
27
+ Besides the four components above, most developers use Ecto to interact
28
+ with SQL databases, such as PostgreSQL and MySQL via the
29
+ [`ecto_sql`](https://hexdocs.pm/ecto_sql) project. `ecto_sql` provides many
30
+ conveniences for working with SQL databases as well as the ability to version
31
+ how your database changes through time via
32
+ [database migrations](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.html#module-migrations).
33
+
34
+ If you want to quickly check a sample application using Ecto, please check
35
+ the [getting started guide](https://hexdocs.pm/ecto/getting-started.html) and
36
+ the accompanying sample application. [Ecto's README](https://github.com/elixir-ecto/ecto)
37
+ also links to other resources.
38
+
39
+ In the following sections, we will provide an overview of those components and
40
+ how they interact with each other. Feel free to access their respective module
41
+ documentation for more specific examples, options and configuration.
42
+
43
+ ## Repositories
44
+
45
+ `Ecto.Repo` is a wrapper around the database. We can define a
46
+ repository as follows:
47
+
48
+ defmodule Repo do
49
+ use Ecto.Repo,
50
+ otp_app: :my_app,
51
+ adapter: Ecto.Adapters.Postgres
52
+ end
53
+
54
+ Where the configuration for the Repo must be in your application
55
+ environment, usually defined in your `config/config.exs`:
56
+
57
+ config :my_app, Repo,
58
+ database: "ecto_simple",
59
+ username: "postgres",
60
+ password: "postgres",
61
+ hostname: "localhost",
62
+ # OR use a URL to connect instead
63
+ url: "postgres://postgres:postgres@localhost/ecto_simple"
64
+
65
+ Each repository in Ecto defines a `start_link/0` function that needs to be invoked
66
+ before using the repository. In general, this function is not called directly,
67
+ but is used as part of your application supervision tree.
68
+
69
+ If your application was generated with a supervisor (by passing `--sup` to `mix new`)
70
+ you will have a `lib/my_app/application.ex` file containing the application start
71
+ callback that defines and starts your supervisor. You just need to edit the `start/2`
72
+ function to start the repo as a supervisor on your application's supervisor:
73
+
74
+ def start(_type, _args) do
75
+ children = [
76
+ MyApp.Repo,
77
+ ]
78
+
79
+ opts = [strategy: :one_for_one, name: MyApp.Supervisor]
80
+ Supervisor.start_link(children, opts)
81
+ end
82
+
83
+ ## Schema
84
+
85
+ Schemas allow developers to define the shape of their data.
86
+ Let's see an example:
87
+
88
+ defmodule Weather do
89
+ use Ecto.Schema
90
+
91
+ # weather is the DB table
92
+ schema "weather" do
93
+ field :city, :string
94
+ field :temp_lo, :integer
95
+ field :temp_hi, :integer
96
+ field :prcp, :float, default: 0.0
97
+ end
98
+ end
99
+
100
+ By defining a schema, Ecto automatically defines a struct with
101
+ the schema fields:
102
+
103
+ iex> weather = %Weather{temp_lo: 30}
104
+ iex> weather.temp_lo
105
+ 30
106
+
107
+ The schema also allows us to interact with a repository:
108
+
109
+ iex> weather = %Weather{temp_lo: 0, temp_hi: 23}
110
+ iex> Repo.insert!(weather)
111
+ %Weather{...}
112
+
113
+ After persisting `weather` to the database, it will return a new copy of
114
+ `%Weather{}` with the primary key (the `id`) set. We can use this value
115
+ to read a struct back from the repository:
116
+
117
+ # Get the struct back
118
+ iex> weather = Repo.get Weather, 1
119
+ %Weather{id: 1, ...}
120
+
121
+ # Delete it
122
+ iex> Repo.delete!(weather)
123
+ %Weather{...}
124
+
125
+ > NOTE: by using `Ecto.Schema`, an `:id` field with type `:id` (:id means :integer) is
126
+ > generated by default, which is the primary key of the schema. If you want
127
+ > to use a different primary key, you can declare custom `@primary_key`
128
+ > before the `schema/2` call. Consult the `Ecto.Schema` documentation
129
+ > for more information.
130
+
131
+ Notice how the storage (repository) and the data are decoupled. This provides
132
+ two main benefits:
133
+
134
+ * By having structs as data, we guarantee they are light-weight,
135
+ serializable structures. In many languages, the data is often represented
136
+ by large, complex objects, with entwined state transactions, which makes
137
+ serialization, maintenance and understanding hard;
138
+
139
+ * You do not need to define schemas in order to interact with repositories,
140
+ operations like `all`, `insert_all` and so on allow developers to directly
141
+ access and modify the data, keeping the database at your fingertips when
142
+ necessary;
143
+
144
+ ## Changesets
145
+
146
+ Although in the example above we have directly inserted and deleted the
147
+ struct in the repository, operations on top of schemas are done through
148
+ changesets so Ecto can efficiently track changes.
149
+
150
+ Changesets allow developers to filter, cast, and validate changes before
151
+ we apply them to the data. Imagine the given schema:
152
+
153
+ defmodule User do
154
+ use Ecto.Schema
155
+
156
+ import Ecto.Changeset
157
+
158
+ schema "users" do
159
+ field :name
160
+ field :email
161
+ field :age, :integer
162
+ end
163
+
164
+ def changeset(user, params \\ %{}) do
165
+ user
166
+ |> cast(params, [:name, :email, :age])
167
+ |> validate_required([:name, :email])
168
+ |> validate_format(:email, ~r/@/)
169
+ |> validate_inclusion(:age, 18..100)
170
+ end
171
+ end
172
+
173
+ The `changeset/2` function first invokes `Ecto.Changeset.cast/4` with
174
+ the struct, the parameters and a list of allowed fields; this returns a changeset.
175
+ The parameters is a map with binary keys and values that will be cast based
176
+ on the type defined by the schema.
177
+
178
+ Any parameter that was not explicitly listed in the fields list will be ignored.
179
+
180
+ After casting, the changeset is given to many `Ecto.Changeset.validate_*`
181
+ functions that validate only the **changed fields**. In other words:
182
+ if a field was not given as a parameter, it won't be validated at all.
183
+ For example, if the params map contain only the "name" and "email" keys,
184
+ the "age" validation won't run.
185
+
186
+ Once a changeset is built, it can be given to functions like `insert` and
187
+ `update` in the repository that will return an `:ok` or `:error` tuple:
188
+
189
+ case Repo.update(changeset) do
190
+ {:ok, user} ->
191
+ # user updated
192
+ {:error, changeset} ->
193
+ # an error occurred
194
+ end
195
+
196
+ The benefit of having explicit changesets is that we can easily provide
197
+ different changesets for different use cases. For example, one
198
+ could easily provide specific changesets for registering and updating
199
+ users:
200
+
201
+ def registration_changeset(user, params) do
202
+ # Changeset on create
203
+ end
204
+
205
+ def update_changeset(user, params) do
206
+ # Changeset on update
207
+ end
208
+
209
+ Changesets are also capable of transforming database constraints,
210
+ like unique indexes and foreign key checks, into errors. Allowing
211
+ developers to keep their database consistent while still providing
212
+ proper feedback to end users. Check `Ecto.Changeset.unique_constraint/3`
213
+ for some examples as well as the other `_constraint` functions.
214
+
215
+ ## Query
216
+
217
+ Last but not least, Ecto allows you to write queries in Elixir and send
218
+ them to the repository, which translates them to the underlying database.
219
+ Let's see an example:
220
+
221
+ import Ecto.Query, only: [from: 2]
222
+
223
+ query = from u in User,
224
+ where: u.age > 18 or is_nil(u.email),
225
+ select: u
226
+
227
+ # Returns %User{} structs matching the query
228
+ Repo.all(query)
229
+
230
+ In the example above we relied on our schema but queries can also be
231
+ made directly against a table by giving the table name as a string. In
232
+ such cases, the data to be fetched must be explicitly outlined:
233
+
234
+ query = from u in "users",
235
+ where: u.age > 18 or is_nil(u.email),
236
+ select: %{name: u.name, age: u.age}
237
+
238
+ # Returns maps as defined in select
239
+ Repo.all(query)
240
+
241
+ Queries are defined and extended with the `from` macro. The supported
242
+ keywords are:
243
+
244
+ * `:distinct`
245
+ * `:where`
246
+ * `:order_by`
247
+ * `:offset`
248
+ * `:limit`
249
+ * `:lock`
250
+ * `:group_by`
251
+ * `:having`
252
+ * `:join`
253
+ * `:select`
254
+ * `:preload`
255
+
256
+ Examples and detailed documentation for each of those are available
257
+ in the `Ecto.Query` module. Functions supported in queries are listed
258
+ in `Ecto.Query.API`.
259
+
260
+ When writing a query, you are inside Ecto's query syntax. In order to
261
+ access params values or invoke Elixir functions, you need to use the `^`
262
+ operator, which is overloaded by Ecto:
263
+
264
+ def min_age(min) do
265
+ from u in User, where: u.age > ^min
266
+ end
267
+
268
+ Besides `Repo.all/1` which returns all entries, repositories also
269
+ provide `Repo.one/1` which returns one entry or nil, `Repo.one!/1`
270
+ which returns one entry or raises, `Repo.get/2` which fetches
271
+ entries for a particular ID and more.
272
+
273
+ Finally, if you need an escape hatch, Ecto provides fragments
274
+ (see `Ecto.Query.API.fragment/1`) to inject SQL (and non-SQL)
275
+ fragments into queries. Also, most adapters provide direct
276
+ APIs for queries, like `Ecto.Adapters.SQL.query/4`, allowing
277
+ developers to completely bypass Ecto queries.
278
+
279
+ ## Other topics
280
+
281
+ ### Associations
282
+
283
+ Ecto supports defining associations on schemas:
284
+
285
+ defmodule Post do
286
+ use Ecto.Schema
287
+
288
+ schema "posts" do
289
+ has_many :comments, Comment
290
+ end
291
+ end
292
+
293
+ defmodule Comment do
294
+ use Ecto.Schema
295
+
296
+ schema "comments" do
297
+ field :title, :string
298
+ belongs_to :post, Post
299
+ end
300
+ end
301
+
302
+ When an association is defined, Ecto also defines a field in the schema
303
+ with the association name. By default, associations are not loaded into
304
+ this field:
305
+
306
+ iex> post = Repo.get(Post, 42)
307
+ iex> post.comments
308
+ #Ecto.Association.NotLoaded<...>
309
+
310
+ However, developers can use the preload functionality in queries to
311
+ automatically pre-populate the field:
312
+
313
+ Repo.all from p in Post, preload: [:comments]
314
+
315
+ Preloading can also be done with a pre-defined join value:
316
+
317
+ Repo.all from p in Post,
318
+ join: c in assoc(p, :comments),
319
+ where: c.votes > p.votes,
320
+ preload: [comments: c]
321
+
322
+ Finally, for the simple cases, preloading can also be done after
323
+ a collection was fetched:
324
+
325
+ posts = Repo.all(Post) |> Repo.preload(:comments)
326
+
327
+ The `Ecto` module also provides conveniences for working
328
+ with associations. For example, `Ecto.assoc/3` returns a query
329
+ with all associated data to a given struct:
330
+
331
+ import Ecto
332
+
333
+ # Get all comments for the given post
334
+ Repo.all assoc(post, :comments)
335
+
336
+ # Or build a query on top of the associated comments
337
+ query = from c in assoc(post, :comments), where: not is_nil(c.title)
338
+ Repo.all(query)
339
+
340
+ Another function in `Ecto` is `build_assoc/3`, which allows
341
+ someone to build an associated struct with the proper fields:
342
+
343
+ Repo.transaction fn ->
344
+ post = Repo.insert!(%Post{title: "Hello", body: "world"})
345
+
346
+ # Build a comment from post
347
+ comment = Ecto.build_assoc(post, :comments, body: "Excellent!")
348
+
349
+ Repo.insert!(comment)
350
+ end
351
+
352
+ In the example above, `Ecto.build_assoc/3` is equivalent to:
353
+
354
+ %Comment{post_id: post.id, body: "Excellent!"}
355
+
356
+ You can find more information about defining associations and each
357
+ respective association module in `Ecto.Schema` docs.
358
+
359
+ > NOTE: Ecto does not lazy load associations. While lazily loading
360
+ > associations may sound convenient at first, in the long run it
361
+ > becomes a source of confusion and performance issues.
362
+
363
+ ### Embeds
364
+
365
+ Ecto also supports embeds. While associations keep parent and child
366
+ entries in different tables, embeds stores the child along side the
367
+ parent.
368
+
369
+ Databases like MongoDB have native support for embeds. Databases
370
+ like PostgreSQL uses a mixture of JSONB (`embeds_one/3`) and ARRAY
371
+ columns to provide this functionality.
372
+
373
+ Check `Ecto.Schema.embeds_one/3` and `Ecto.Schema.embeds_many/3`
374
+ for more information.
375
+
376
+ ### Mix tasks and generators
377
+
378
+ Ecto provides many tasks to help your workflow as well as code generators.
379
+ You can find all available tasks by typing `mix help` inside a project
380
+ with Ecto listed as a dependency.
381
+
382
+ Ecto generators will automatically open the generated files if you have
383
+ `ECTO_EDITOR` set in your environment variable.
384
+
385
+ #### Repo resolution
386
+
387
+ Ecto requires developers to specify the key `:ecto_repos` in their
388
+ application configuration before using tasks like `ecto.create` and
389
+ `ecto.migrate`. For example:
390
+
391
+ config :my_app, :ecto_repos, [MyApp.Repo]
392
+
393
+ config :my_app, MyApp.Repo,
394
+ database: "ecto_simple",
395
+ username: "postgres",
396
+ password: "postgres",
397
+ hostname: "localhost"
398
+
399
+ """
400
+
401
+ @doc """
402
+ Returns the schema primary keys as a keyword list.
403
+ """
404
+ @spec primary_key(Ecto.Schema.t()) :: Keyword.t()
405
+ def primary_key(%{__struct__: schema} = struct) do
406
+ Enum.map(schema.__schema__(:primary_key), fn field ->
407
+ {field, Map.fetch!(struct, field)}
408
+ end)
409
+ end
410
+
411
+ @doc """
412
+ Returns the schema primary keys as a keyword list.
413
+
414
+ Raises `Ecto.NoPrimaryKeyFieldError` if the schema has no
415
+ primary key field.
416
+ """
417
+ @spec primary_key!(Ecto.Schema.t()) :: Keyword.t()
418
+ def primary_key!(%{__struct__: schema} = struct) do
419
+ case primary_key(struct) do
420
+ [] -> raise Ecto.NoPrimaryKeyFieldError, schema: schema
421
+ pk -> pk
422
+ end
423
+ end
424
+
425
+ @doc """
426
+ Builds a struct from the given `assoc` in `struct`.
427
+
428
+ ## Examples
429
+
430
+ If the relationship is a `has_one` or `has_many` and
431
+ the primary key is set in the parent struct, the key will
432
+ automatically be set in the built association:
433
+
434
+ iex> post = Repo.get(Post, 13)
435
+ %Post{id: 13}
436
+ iex> build_assoc(post, :comments)
437
+ %Comment{id: nil, post_id: 13}
438
+
439
+ Note though it doesn't happen with `belongs_to` cases, as the
440
+ key is often the primary key and such is usually generated
441
+ dynamically:
442
+
443
+ iex> comment = Repo.get(Comment, 13)
444
+ %Comment{id: 13, post_id: 25}
445
+ iex> build_assoc(comment, :post)
446
+ %Post{id: nil}
447
+
448
+ You can also pass the attributes, which can be a map or
449
+ a keyword list, to set the struct's fields except the
450
+ association key.
451
+
452
+ iex> build_assoc(post, :comments, text: "cool")
453
+ %Comment{id: nil, post_id: 13, text: "cool"}
454
+
455
+ iex> build_assoc(post, :comments, %{text: "cool"})
456
+ %Comment{id: nil, post_id: 13, text: "cool"}
457
+
458
+ iex> build_assoc(post, :comments, post_id: 1)
459
+ %Comment{id: nil, post_id: 13}
460
+
461
+ The given attributes are expected to be structured data.
462
+ If you want to build an association with external data,
463
+ such as a request parameters, you can use `Ecto.Changeset.cast/3`
464
+ after `build_assoc/3`:
465
+
466
+ parent
467
+ |> Ecto.build_assoc(:child)
468
+ |> Ecto.Changeset.cast(params, [:field1, :field2])
469
+
470
+ """
471
+ def build_assoc(%{__struct__: schema} = struct, assoc, attributes \\ %{}) do
472
+ assoc = Ecto.Association.association_from_schema!(schema, assoc)
473
+ assoc.__struct__.build(assoc, struct, drop_meta(attributes))
474
+ end
475
+
476
+ defp drop_meta(%{} = attrs), do: Map.drop(attrs, [:__struct__, :__meta__])
477
+ defp drop_meta([_ | _] = attrs), do: Keyword.drop(attrs, [:__struct__, :__meta__])
478
+
479
+ @doc """
480
+ Builds a query for the association in the given struct or structs.
481
+
482
+ ## Examples
483
+
484
+ In the example below, we get all comments associated to the given
485
+ post:
486
+
487
+ post = Repo.get Post, 1
488
+ Repo.all Ecto.assoc(post, :comments)
489
+
490
+ `assoc/3` can also receive a list of posts, as long as the posts are
491
+ not empty:
492
+
493
+ posts = Repo.all from p in Post, where: is_nil(p.published_at)
494
+ Repo.all Ecto.assoc(posts, :comments)
495
+
496
+ This function can also be used to dynamically load through associations
497
+ by giving it a list. For example, to get all authors for all comments for
498
+ the given posts, do:
499
+
500
+ posts = Repo.all from p in Post, where: is_nil(p.published_at)
501
+ Repo.all Ecto.assoc(posts, [:comments, :author])
502
+
503
+ ## Options
504
+
505
+ * `:prefix` - the prefix to fetch assocs from. By default, queries
506
+ will use the same prefix as the first struct in the given collection.
507
+ This option allows the prefix to be changed.
508
+
509
+ """
510
+ def assoc(struct_or_structs, assocs, opts \\ []) do
511
+ [assoc | assocs] = List.wrap(assocs)
512
+
513
+ structs =
514
+ case struct_or_structs do
515
+ nil -> raise ArgumentError, "cannot retrieve association #{inspect(assoc)} for nil"
516
+ [] -> raise ArgumentError, "cannot retrieve association #{inspect(assoc)} for empty list"
517
+ struct_or_structs -> List.wrap(struct_or_structs)
518
+ end
519
+
520
+ sample = hd(structs)
521
+ prefix = assoc_prefix(sample, opts)
522
+ schema = sample.__struct__
523
+ refl = %{owner_key: owner_key} = Ecto.Association.association_from_schema!(schema, assoc)
524
+
525
+ values =
526
+ Enum.uniq(
527
+ for(
528
+ struct <- structs,
529
+ assert_struct!(schema, struct),
530
+ key = Map.fetch!(struct, owner_key),
531
+ do: key
532
+ )
533
+ )
534
+
535
+ case assocs do
536
+ [] ->
537
+ %module{} = refl
538
+ %{module.assoc_query(refl, nil, values) | prefix: prefix}
539
+
540
+ assocs ->
541
+ %{
542
+ Ecto.Association.filter_through_chain(schema, [assoc | assocs], values)
543
+ | prefix: prefix
544
+ }
545
+ end
546
+ end
547
+
548
+ defp assoc_prefix(sample, opts) do
549
+ case Keyword.fetch(opts, :prefix) do
550
+ {:ok, prefix} ->
551
+ prefix
552
+
553
+ :error ->
554
+ case sample do
555
+ %{__meta__: %{prefix: prefix}} -> prefix
556
+ # Must be an embedded schema
557
+ _ -> nil
558
+ end
559
+ end
560
+ end
561
+
562
+ @doc """
563
+ Checks if an association is loaded.
564
+
565
+ ## Examples
566
+
567
+ iex> post = Repo.get(Post, 1)
568
+ iex> Ecto.assoc_loaded?(post.comments)
569
+ false
570
+ iex> post = post |> Repo.preload(:comments)
571
+ iex> Ecto.assoc_loaded?(post.comments)
572
+ true
573
+
574
+ """
575
+ def assoc_loaded?(%Ecto.Association.NotLoaded{}), do: false
576
+ def assoc_loaded?(list) when is_list(list), do: true
577
+ def assoc_loaded?(%_{}), do: true
578
+ def assoc_loaded?(nil), do: true
579
+
580
+ @doc """
581
+ Resets fields in a struct to their default values.
582
+
583
+ ## Examples
584
+
585
+ iex> post = post |> Repo.preload(:author)
586
+ %Post{title: "hello world", author: %Author{}}
587
+ iex> Ecto.reset_fields(post, [:title, :author])
588
+ %Post{
589
+ title: "default title",
590
+ author: #Ecto.Association.NotLoaded<association :author is not loaded>
591
+ }
592
+
593
+ """
594
+ @spec reset_fields(Ecto.Schema.t(), list()) :: Ecto.Schema.t()
595
+ def reset_fields(struct, []), do: struct
596
+
597
+ def reset_fields(%{__struct__: schema} = struct, fields) do
598
+ default_struct = schema.__struct__()
599
+ default_fields = Map.take(default_struct, fields)
600
+ Map.merge(struct, default_fields)
601
+ end
602
+
603
+ @doc """
604
+ Gets the metadata from the given struct.
605
+ """
606
+ def get_meta(struct, :context),
607
+ do: struct.__meta__.context
608
+
609
+ def get_meta(struct, :state),
610
+ do: struct.__meta__.state
611
+
612
+ def get_meta(struct, :source),
613
+ do: struct.__meta__.source
614
+
615
+ def get_meta(struct, :prefix),
616
+ do: struct.__meta__.prefix
617
+
618
+ @doc """
619
+ Returns a new struct with updated metadata.
620
+
621
+ It is possible to set:
622
+
623
+ * `:source` - changes the struct query source
624
+ * `:prefix` - changes the struct query prefix
625
+ * `:context` - changes the struct meta context
626
+ * `:state` - changes the struct state
627
+
628
+ Please refer to the `Ecto.Schema.Metadata` module for more information.
629
+ """
630
+ @spec put_meta(Ecto.Schema.schema(), meta) :: Ecto.Schema.schema()
631
+ when meta: [
632
+ source: Ecto.Schema.source(),
633
+ prefix: Ecto.Schema.prefix(),
634
+ context: Ecto.Schema.Metadata.context(),
635
+ state: Ecto.Schema.Metadata.state()
636
+ ]
637
+ def put_meta(%{__meta__: meta} = struct, opts) do
638
+ case put_or_noop_meta(opts, meta, false) do
639
+ :noop -> struct
640
+ meta -> %{struct | __meta__: meta}
641
+ end
642
+ end
643
+
644
+ defp put_or_noop_meta([{key, value} | t], meta, updated?) do
645
+ case meta do
646
+ %{^key => ^value} -> put_or_noop_meta(t, meta, updated?)
647
+ _ -> put_or_noop_meta(t, put_meta(meta, key, value), true)
648
+ end
649
+ end
650
+
651
+ defp put_or_noop_meta([], meta, true), do: meta
652
+ defp put_or_noop_meta([], _meta, false), do: :noop
653
+
654
+ defp put_meta(meta, :state, state) do
655
+ if state in [:built, :loaded, :deleted] do
656
+ %{meta | state: state}
657
+ else
658
+ raise ArgumentError, "invalid state #{inspect(state)}"
659
+ end
660
+ end
661
+
662
+ defp put_meta(meta, :source, source) do
663
+ %{meta | source: source}
664
+ end
665
+
666
+ defp put_meta(meta, :prefix, prefix) do
667
+ %{meta | prefix: prefix}
668
+ end
669
+
670
+ defp put_meta(meta, :context, context) do
671
+ %{meta | context: context}
672
+ end
673
+
674
+ defp put_meta(_meta, key, _value) do
675
+ raise ArgumentError, "unknown meta key #{inspect(key)}"
676
+ end
677
+
678
+ defp assert_struct!(module, %{__struct__: struct}) do
679
+ if struct != module do
680
+ raise ArgumentError,
681
+ "expected a homogeneous list containing the same struct, " <>
682
+ "got: #{inspect(module)} and #{inspect(struct)}"
683
+ else
684
+ true
685
+ end
686
+ end
687
+
688
+ @doc """
689
+ Loads previously dumped `data` in the given `format` into a schema.
690
+
691
+ The first argument can be an embedded schema module, or a map (of types) and
692
+ determines the return value: a struct or a map, respectively.
693
+
694
+ The second argument `data` specifies fields and values that are to be loaded.
695
+ It can be a map, a keyword list, or a `{fields, values}` tuple. Fields can be
696
+ atoms or strings.
697
+
698
+ The third argument `format` is the format the data has been dumped as. For
699
+ example, databases may dump embedded to `:json`, this function allows such
700
+ dumped data to be put back into the schemas. If custom types are used,
701
+ Ecto will invoke the `c:Ecto.Type.embed_as/1` callback to decide if the data
702
+ should be loaded using `cast` or `load`.
703
+
704
+ Fields that are not present in the schema (or `types` map) are ignored.
705
+ If any of the values has invalid type, an error is raised.
706
+
707
+ Note that if you want to load data into a non-embedded schema that was
708
+ directly persisted into a given repository, then use `c:Ecto.Repo.load/2`.
709
+
710
+ ## Examples
711
+
712
+ iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT users.settings FROM users", [])
713
+ iex> Enum.map(result.rows, fn [settings] -> Ecto.embedded_load(Setting, Jason.decode!(settings), :json) end)
714
+ [%Setting{...}, ...]
715
+ """
716
+ @spec embedded_load(
717
+ module_or_map :: module | map(),
718
+ data :: map(),
719
+ format :: atom()
720
+ ) :: Ecto.Schema.t() | map()
721
+ def embedded_load(schema_or_types, data, format) do
722
+ Ecto.Schema.Loader.unsafe_load(
723
+ schema_or_types,
724
+ data,
725
+ &Ecto.Type.embedded_load(&1, &2, format)
726
+ )
727
+ end
728
+
729
+ @doc """
730
+ Dumps the given struct defined by an embedded schema.
731
+
732
+ This converts the given embedded schema to a map to be serialized
733
+ with the given format. For example:
734
+
735
+ iex> Ecto.embedded_dump(%Post{}, :json)
736
+ %{title: "hello"}
737
+
738
+ """
739
+ @spec embedded_dump(Ecto.Schema.t(), format :: atom()) :: map()
740
+ def embedded_dump(%schema{} = data, format) do
741
+ Ecto.Schema.Loader.safe_dump(
742
+ data,
743
+ schema.__schema__(:dump),
744
+ &Ecto.Type.embedded_dump(&1, &2, format)
745
+ )
746
+ end
747
+ end
deps/ecto/lib/ecto/adapter.ex ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Adapter do
2
+ @moduledoc """
3
+ Specifies the minimal API required from adapters.
4
+ """
5
+
6
+ @type t :: module
7
+
8
+ @typedoc """
9
+ The metadata returned by the adapter `c:init/1`.
10
+
11
+ It must be a map and Ecto itself will always inject
12
+ two keys into the meta:
13
+
14
+ * the `:cache` key, which as ETS table that can be used as a cache (if available)
15
+ * the `:pid` key, which is the PID returned by the child spec returned in `c:init/1`
16
+
17
+ """
18
+ @type adapter_meta :: %{optional(:stacktrace) => boolean(), optional(any()) => any()}
19
+
20
+ @doc """
21
+ The callback invoked in case the adapter needs to inject code.
22
+ """
23
+ @macrocallback __before_compile__(env :: Macro.Env.t()) :: Macro.t()
24
+
25
+ @doc """
26
+ Ensure all applications necessary to run the adapter are started.
27
+ """
28
+ @callback ensure_all_started(
29
+ config :: Keyword.t(),
30
+ type :: :permanent | :transient | :temporary
31
+ ) ::
32
+ {:ok, [atom]} | {:error, atom}
33
+
34
+ @doc """
35
+ Initializes the adapter supervision tree by returning the children and adapter metadata.
36
+ """
37
+ @callback init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec(), adapter_meta}
38
+
39
+ @doc """
40
+ Checks out a connection for the duration of the given function.
41
+
42
+ In case the adapter provides a pool, this guarantees all of the code
43
+ inside the given `fun` runs against the same connection, which
44
+ might improve performance by for instance allowing multiple related
45
+ calls to the datastore to share cache information:
46
+
47
+ Repo.checkout(fn ->
48
+ for _ <- 1..100 do
49
+ Repo.insert!(%Post{})
50
+ end
51
+ end)
52
+
53
+ If the adapter does not provide a pool, just calling the passed function
54
+ and returning its result are enough.
55
+
56
+ If the adapter provides a pool, it is supposed to "check out" one of the
57
+ pool connections for the duration of the function call. Which connection
58
+ is checked out is not passed to the calling function, so it should be done
59
+ using a stateful method like using the current process' dictionary, process
60
+ tracking, or some kind of other lookup method. Make sure that this stored
61
+ connection is then used in the other callbacks implementations, such as
62
+ `Ecto.Adapter.Queryable` and `Ecto.Adapter.Schema`.
63
+ """
64
+ @callback checkout(adapter_meta, config :: Keyword.t(), (-> result)) :: result when result: var
65
+
66
+ @doc """
67
+ Returns true if a connection has been checked out.
68
+ """
69
+ @callback checked_out?(adapter_meta) :: boolean
70
+
71
+ @doc """
72
+ Returns the loaders for a given type.
73
+
74
+ It receives the primitive type and the Ecto type (which may be
75
+ primitive as well). It returns a list of loaders with the given
76
+ type usually at the end.
77
+
78
+ This allows developers to properly translate values coming from
79
+ the adapters into Ecto ones. For example, if the database does not
80
+ support booleans but instead returns 0 and 1 for them, you could
81
+ add:
82
+
83
+ def loaders(:boolean, type), do: [&bool_decode/1, type]
84
+ def loaders(_primitive, type), do: [type]
85
+
86
+ defp bool_decode(0), do: {:ok, false}
87
+ defp bool_decode(1), do: {:ok, true}
88
+
89
+ All adapters are required to implement a clause for `:binary_id` types,
90
+ since they are adapter specific. If your adapter does not provide binary
91
+ ids, you may simply use `Ecto.UUID`:
92
+
93
+ def loaders(:binary_id, type), do: [Ecto.UUID, type]
94
+ def loaders(_primitive, type), do: [type]
95
+
96
+ """
97
+ @callback loaders(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) ::
98
+ [(term -> {:ok, term} | :error) | Ecto.Type.t()]
99
+
100
+ @doc """
101
+ Returns the dumpers for a given type.
102
+
103
+ It receives the primitive type and the Ecto type (which may be
104
+ primitive as well). It returns a list of dumpers with the given
105
+ type usually at the beginning.
106
+
107
+ This allows developers to properly translate values coming from
108
+ the Ecto into adapter ones. For example, if the database does not
109
+ support booleans but instead returns 0 and 1 for them, you could
110
+ add:
111
+
112
+ def dumpers(:boolean, type), do: [type, &bool_encode/1]
113
+ def dumpers(_primitive, type), do: [type]
114
+
115
+ defp bool_encode(false), do: {:ok, 0}
116
+ defp bool_encode(true), do: {:ok, 1}
117
+
118
+ All adapters are required to implement a clause for :binary_id types,
119
+ since they are adapter specific. If your adapter does not provide
120
+ binary ids, you may simply use `Ecto.UUID`:
121
+
122
+ def dumpers(:binary_id, type), do: [type, Ecto.UUID]
123
+ def dumpers(_primitive, type), do: [type]
124
+
125
+ """
126
+ @callback dumpers(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) ::
127
+ [(term -> {:ok, term} | :error) | Ecto.Type.t()]
128
+
129
+ @doc """
130
+ Returns the adapter metadata from its `c:init/1` callback.
131
+
132
+ It expects a process name of a repository. The name is either
133
+ an atom or a PID. For a given repository, you often want to
134
+ call this function based on the repository dynamic repo:
135
+
136
+ Ecto.Adapter.lookup_meta(repo.get_dynamic_repo())
137
+
138
+ """
139
+ def lookup_meta(repo_name_or_pid) do
140
+ Ecto.Repo.Registry.lookup(repo_name_or_pid)
141
+ end
142
+ end
deps/ecto/lib/ecto/adapter/queryable.ex ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Adapter.Queryable do
2
+ @moduledoc """
3
+ Specifies the query API required from adapters.
4
+
5
+ If your adapter is only able to respond to one or a couple of the query functions,
6
+ add custom implementations of those functions directly to the Repo
7
+ by using `c:Ecto.Adapter.__before_compile__/1` instead.
8
+ """
9
+
10
+ @typedoc "Proxy type to the adapter meta"
11
+ @type adapter_meta :: Ecto.Adapter.adapter_meta()
12
+
13
+ @typedoc "Ecto.Query metadata fields (stored in cache)"
14
+ @type query_meta :: %{sources: tuple, preloads: term, select: map}
15
+
16
+ @typedoc """
17
+ Cache query metadata that is passed to `c:execute/5`.
18
+
19
+ The cache can be in 3 states, documented below.
20
+
21
+ If `{:nocache, prepared}` is given, it means the query was
22
+ not and cannot be cached. The `prepared` value is the value
23
+ returned by `c:prepare/2`.
24
+
25
+ If `{:cache, cache_function, prepared}` is given, it means
26
+ the query can be cached and it must be cached by calling
27
+ the `cache_function` function with the cache entry of your
28
+ choice. Once `cache_function` is called, the next time the
29
+ same query is given to `c:execute/5`, it will receive the
30
+ `:cached` tuple.
31
+
32
+ If `{:cached, update_function, reset_function, cached}` is
33
+ given, it means the query has been cached. You may call
34
+ `update_function/1` if you want to update the cached result.
35
+ Or you may call `reset_function/1`, with a new prepared query,
36
+ to force the query to be cached again. If `reset_function/1`
37
+ is called, the next time the same query is given to
38
+ `c:execute/5`, it will receive the `:cache` tuple.
39
+ """
40
+ @type query_cache :: {:nocache, prepared}
41
+ | {:cache, cache_function :: (cached -> :ok), prepared}
42
+ | {:cached, update_function :: (cached -> :ok), reset_function :: (prepared -> :ok), cached}
43
+
44
+ @type prepared :: term
45
+ @type cached :: term
46
+ @type options :: Keyword.t()
47
+ @type selected :: term
48
+
49
+ @doc """
50
+ Commands invoked to prepare a query.
51
+
52
+ It is used on `c:Ecto.Repo.all/2`, `c:Ecto.Repo.update_all/3`,
53
+ and `c:Ecto.Repo.delete_all/2`. It returns a tuple, indicating if
54
+ this query can be cached or not, and the `prepared` query.
55
+ The `prepared` query is any term that will be passed to the
56
+ adapter's `c:execute/5`.
57
+ """
58
+ @callback prepare(atom :: :all | :update_all | :delete_all, query :: Ecto.Query.t()) ::
59
+ {:cache, prepared} | {:nocache, prepared}
60
+
61
+ @doc """
62
+ Executes a previously prepared query.
63
+
64
+ The `query_meta` field is a map containing some of the fields
65
+ found in the `Ecto.Query` struct, after they have been normalized.
66
+ For example, the values `selected` by the query, which then have
67
+ to be returned, can be found in `query_meta`.
68
+
69
+ The `query_cache` and its state is documented in `t:query_cache/0`.
70
+
71
+ The `params` is the list of query parameters. For example, for
72
+ a query such as `from Post, where: [id: ^123]`, `params` will be
73
+ `[123]`.
74
+
75
+ Finally, `options` is a keyword list of options given to the
76
+ `Repo` operation that triggered the adapter call. Any option is
77
+ allowed, as this is a mechanism to allow users of Ecto to customize
78
+ how the adapter behaves per operation.
79
+
80
+ It must return a tuple containing the number of entries and
81
+ the result set as a list of lists. The entries in the actual
82
+ list will depend on what has been selected by the query. The
83
+ result set may also be `nil`, if no value is being selected.
84
+ """
85
+ @callback execute(adapter_meta, query_meta, query_cache, params :: list(), options) ::
86
+ {non_neg_integer, [[selected]] | nil}
87
+
88
+ @doc """
89
+ Streams a previously prepared query.
90
+
91
+ See `c:execute/5` for a description of arguments.
92
+
93
+ It returns a stream of values.
94
+ """
95
+ @callback stream(adapter_meta, query_meta, query_cache, params :: list(), options) ::
96
+ Enumerable.t
97
+
98
+ @doc """
99
+ Plans and prepares a query for the given repo, leveraging its query cache.
100
+
101
+ This operation uses the query cache if one is available.
102
+ """
103
+ def prepare_query(operation, repo_name_or_pid, queryable) do
104
+ %{adapter: adapter, cache: cache} = Ecto.Repo.Registry.lookup(repo_name_or_pid)
105
+
106
+ {_meta, prepared, _cast_params, dump_params} =
107
+ queryable
108
+ |> Ecto.Queryable.to_query()
109
+ |> Ecto.Query.Planner.ensure_select(operation == :all)
110
+ |> Ecto.Query.Planner.query(operation, cache, adapter, 0)
111
+
112
+ {prepared, dump_params}
113
+ end
114
+
115
+ @doc """
116
+ Plans a query using the given adapter.
117
+
118
+ This does not expect the repository and therefore does not leverage the cache.
119
+ """
120
+ def plan_query(operation, adapter, queryable) do
121
+ query = Ecto.Queryable.to_query(queryable)
122
+ {query, params, _key} = Ecto.Query.Planner.plan(query, operation, adapter)
123
+ {cast_params, dump_params} = Enum.unzip(params)
124
+ {query, _} = Ecto.Query.Planner.normalize(query, operation, adapter, 0)
125
+ {query, cast_params, dump_params}
126
+ end
127
+ end
deps/ecto/lib/ecto/adapter/schema.ex ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Adapter.Schema do
2
+ @moduledoc """
3
+ Specifies the schema API required from adapters.
4
+ """
5
+
6
+ @typedoc "Proxy type to the adapter meta"
7
+ @type adapter_meta :: Ecto.Adapter.adapter_meta()
8
+
9
+ @typedoc "Ecto.Schema metadata fields"
10
+ @type schema_meta :: %{
11
+ autogenerate_id: {schema_field :: atom, source_field :: atom, Ecto.Type.t()},
12
+ context: term,
13
+ prefix: binary | nil,
14
+ schema: atom,
15
+ source: binary
16
+ }
17
+
18
+ @type fields :: Keyword.t()
19
+ @type filters :: Keyword.t()
20
+ @type constraints :: Keyword.t()
21
+ @type returning :: [atom]
22
+ @type placeholders :: [term]
23
+ @type options :: Keyword.t()
24
+
25
+ @type on_conflict ::
26
+ {:raise, list(), []}
27
+ | {:nothing, list(), [atom]}
28
+ | {[atom], list(), [atom]}
29
+ | {Ecto.Query.t(), list(), [atom]}
30
+
31
+ @doc """
32
+ Called to autogenerate a value for id/embed_id/binary_id.
33
+
34
+ Returns the autogenerated value, or nil if it must be
35
+ autogenerated inside the storage or raise if not supported.
36
+ """
37
+ @callback autogenerate(field_type :: :id | :binary_id | :embed_id) :: term | nil
38
+
39
+ @doc """
40
+ Inserts multiple entries into the data store.
41
+
42
+ In case an `Ecto.Query` given as any of the field values by the user,
43
+ it will be sent to the adapter as a tuple with in the shape of
44
+ `{query, params}`.
45
+ """
46
+ @callback insert_all(
47
+ adapter_meta,
48
+ schema_meta,
49
+ header :: [atom],
50
+ [[{atom, term | {Ecto.Query.t(), list()}}]],
51
+ on_conflict,
52
+ returning,
53
+ placeholders,
54
+ options
55
+ ) :: {non_neg_integer, [[term]] | nil}
56
+
57
+ @doc """
58
+ Inserts a single new struct in the data store.
59
+
60
+ ## Autogenerate
61
+
62
+ The primary key will be automatically included in `returning` if the
63
+ field has type `:id` or `:binary_id` and no value was set by the
64
+ developer or none was autogenerated by the adapter.
65
+ """
66
+ @callback insert(adapter_meta, schema_meta, fields, on_conflict, returning, options) ::
67
+ {:ok, fields} | {:invalid, constraints}
68
+
69
+ @doc """
70
+ Updates a single struct with the given filters.
71
+
72
+ While `filters` can be any record column, it is expected that
73
+ at least the primary key (or any other key that uniquely
74
+ identifies an existing record) be given as a filter. Therefore,
75
+ in case there is no record matching the given filters,
76
+ `{:error, :stale}` is returned.
77
+ """
78
+ @callback update(adapter_meta, schema_meta, fields, filters, returning, options) ::
79
+ {:ok, fields} | {:invalid, constraints} | {:error, :stale}
80
+
81
+ @doc """
82
+ Deletes a single struct with the given filters.
83
+
84
+ While `filters` can be any record column, it is expected that
85
+ at least the primary key (or any other key that uniquely
86
+ identifies an existing record) be given as a filter. Therefore,
87
+ in case there is no record matching the given filters,
88
+ `{:error, :stale}` is returned.
89
+ """
90
+ @callback delete(adapter_meta, schema_meta, filters, returning, options) ::
91
+ {:ok, fields} | {:invalid, constraints} | {:error, :stale}
92
+ end
deps/ecto/lib/ecto/adapter/storage.ex ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Adapter.Storage do
2
+ @moduledoc """
3
+ Specifies the adapter storage API.
4
+ """
5
+
6
+ @doc """
7
+ Creates the storage given by options.
8
+
9
+ Returns `:ok` if it was created successfully.
10
+
11
+ Returns `{:error, :already_up}` if the storage has already been created or
12
+ `{:error, term}` in case anything else goes wrong.
13
+
14
+ ## Examples
15
+
16
+ storage_up(username: "postgres",
17
+ database: "ecto_test",
18
+ hostname: "localhost")
19
+
20
+ """
21
+ @callback storage_up(options :: Keyword.t) :: :ok | {:error, :already_up} | {:error, term}
22
+
23
+ @doc """
24
+ Drops the storage given by options.
25
+
26
+ Returns `:ok` if it was dropped successfully.
27
+
28
+ Returns `{:error, :already_down}` if the storage has already been dropped or
29
+ `{:error, term}` in case anything else goes wrong.
30
+
31
+ ## Examples
32
+
33
+ storage_down(username: "postgres",
34
+ database: "ecto_test",
35
+ hostname: "localhost")
36
+
37
+ """
38
+ @callback storage_down(options :: Keyword.t) :: :ok | {:error, :already_down} | {:error, term}
39
+
40
+ @doc """
41
+ Returns the status of a storage given by options.
42
+
43
+ Can return `:up`, `:down` or `{:error, term}` in case anything goes wrong.
44
+
45
+ ## Examples
46
+
47
+ storage_status(username: "postgres",
48
+ database: "ecto_test",
49
+ hostname: "localhost")
50
+
51
+ """
52
+ @callback storage_status(options :: Keyword.t()) :: :up | :down | {:error, term()}
53
+ end
deps/ecto/lib/ecto/adapter/transaction.ex ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Adapter.Transaction do
2
+ @moduledoc """
3
+ Specifies the adapter transactions API.
4
+ """
5
+
6
+ @type adapter_meta :: Ecto.Adapter.adapter_meta()
7
+
8
+ @doc """
9
+ Runs the given function inside a transaction.
10
+
11
+ Returns `{:ok, value}` if the transaction was successful where `value`
12
+ is the value returned by the function or `{:error, value}` if the transaction
13
+ was rolled back where `value` is the value given to `rollback/1`.
14
+ """
15
+ @callback transaction(adapter_meta, options :: Keyword.t(), function :: fun) ::
16
+ {:ok, any} | {:error, any}
17
+
18
+ @doc """
19
+ Returns true if the given process is inside a transaction.
20
+ """
21
+ @callback in_transaction?(adapter_meta) :: boolean
22
+
23
+ @doc """
24
+ Rolls back the current transaction.
25
+
26
+ The transaction will return the value given as `{:error, value}`.
27
+
28
+ See `c:Ecto.Repo.rollback/1`.
29
+ """
30
+ @callback rollback(adapter_meta, value :: any) :: no_return
31
+ end
deps/ecto/lib/ecto/application.ex ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Application do
2
+ @moduledoc false
3
+ use Application
4
+
5
+ def start(_type, _args) do
6
+ children = [
7
+ Ecto.Repo.Registry
8
+ ]
9
+
10
+ opts = [strategy: :one_for_one, name: Ecto.Supervisor]
11
+ Supervisor.start_link(children, opts)
12
+ end
13
+ end
deps/ecto/lib/ecto/association.ex ADDED
@@ -0,0 +1,1711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Ecto.Query, only: [from: 1, from: 2, join: 4, join: 5, distinct: 3, where: 3]
2
+
3
+ defmodule Ecto.Association.NotLoaded do
4
+ @moduledoc """
5
+ Struct returned by associations when they are not loaded.
6
+
7
+ The fields are:
8
+
9
+ * `__field__` - the association field in `owner`
10
+ * `__owner__` - the schema that owns the association
11
+ * `__cardinality__` - the cardinality of the association
12
+ """
13
+
14
+ @type t :: %__MODULE__{
15
+ __field__: atom(),
16
+ __owner__: any(),
17
+ __cardinality__: atom()
18
+ }
19
+
20
+ defstruct [:__field__, :__owner__, :__cardinality__]
21
+
22
+ defimpl Inspect do
23
+ def inspect(not_loaded, _opts) do
24
+ msg = "association #{inspect(not_loaded.__field__)} is not loaded"
25
+ ~s(#Ecto.Association.NotLoaded<#{msg}>)
26
+ end
27
+ end
28
+ end
29
+
30
+ defmodule Ecto.Association do
31
+ @moduledoc false
32
+
33
+ @type t :: %{
34
+ required(:__struct__) => atom,
35
+ required(:on_cast) => nil | fun,
36
+ required(:cardinality) => :one | :many,
37
+ required(:relationship) => :parent | :child,
38
+ required(:owner) => atom,
39
+ required(:owner_key) => atom,
40
+ required(:field) => atom,
41
+ required(:unique) => boolean,
42
+ optional(atom) => any
43
+ }
44
+
45
+ alias Ecto.Query.Builder.OrderBy
46
+
47
+ @doc """
48
+ Helper to check if a queryable is compiled.
49
+ """
50
+ def ensure_compiled(queryable, env) do
51
+ if not is_atom(queryable) or queryable in env.context_modules do
52
+ :skip
53
+ else
54
+ case Code.ensure_compiled(queryable) do
55
+ {:module, _} -> :compiled
56
+ {:error, :unavailable} -> :skip
57
+ {:error, _} -> :not_found
58
+ end
59
+ end
60
+ end
61
+
62
+ @doc """
63
+ Builds the association struct.
64
+
65
+ The struct must be defined in the module that implements the
66
+ callback and it must contain at least the following keys:
67
+
68
+ * `:cardinality` - tells if the association is one to one
69
+ or one/many to many
70
+
71
+ * `:field` - tells the field in the owner struct where the
72
+ association should be stored
73
+
74
+ * `:owner` - the owner module of the association
75
+
76
+ * `:owner_key` - the key in the owner with the association value
77
+
78
+ * `:relationship` - if the relationship to the specified schema is
79
+ of a `:child` or a `:parent`
80
+
81
+ """
82
+ @callback struct(module, field :: atom, opts :: Keyword.t()) :: t
83
+
84
+ @doc """
85
+ Invoked after the schema is compiled to validate associations.
86
+
87
+ Useful for checking if associated modules exist without running
88
+ into deadlocks.
89
+ """
90
+ @callback after_compile_validation(t, Macro.Env.t()) :: :ok | {:error, String.t()}
91
+
92
+ @doc """
93
+ Builds a struct for the given association.
94
+
95
+ The struct to build from is given as argument in case default values
96
+ should be set in the struct.
97
+
98
+ Invoked by `Ecto.build_assoc/3`.
99
+ """
100
+ @callback build(t, owner :: Ecto.Schema.t(), %{atom => term} | [Keyword.t()]) :: Ecto.Schema.t()
101
+
102
+ @doc """
103
+ Returns an association join query.
104
+
105
+ This callback receives the association struct and it must return
106
+ a query that retrieves all associated entries using joins up to
107
+ the owner association.
108
+
109
+ For example, a `has_many :comments` inside a `Post` module would
110
+ return:
111
+
112
+ from c in Comment, join: p in Post, on: c.post_id == p.id
113
+
114
+ Note all the logic must be expressed inside joins, as fields like
115
+ `where` and `order_by` won't be used by the caller.
116
+
117
+ This callback is invoked when `join: assoc(p, :comments)` is used
118
+ inside queries.
119
+ """
120
+ @callback joins_query(t) :: Ecto.Query.t()
121
+
122
+ @doc """
123
+ Returns the association query on top of the given query.
124
+
125
+ If the query is `nil`, the association target must be used.
126
+
127
+ This callback receives the association struct and it must return
128
+ a query that retrieves all associated entries with the given
129
+ values for the owner key.
130
+
131
+ This callback is used by `Ecto.assoc/2` and when preloading.
132
+ """
133
+ @callback assoc_query(t, Ecto.Query.t() | nil, values :: [term]) :: Ecto.Query.t()
134
+
135
+ @doc """
136
+ Returns information used by the preloader.
137
+ """
138
+ @callback preload_info(t) ::
139
+ {:assoc, t, {integer, atom} | {integer, atom, Ecto.Type.t()}}
140
+ | {:through, t, [atom]}
141
+
142
+ @doc """
143
+ Performs the repository change on the association.
144
+
145
+ Receives the parent changeset, the current changesets
146
+ and the repository action options. Must return the
147
+ persisted struct (or nil) or the changeset error.
148
+ """
149
+ @callback on_repo_change(
150
+ t,
151
+ parent :: Ecto.Changeset.t(),
152
+ changeset :: Ecto.Changeset.t(),
153
+ Ecto.Adapter.t(),
154
+ Keyword.t()
155
+ ) ::
156
+ {:ok, Ecto.Schema.t() | nil} | {:error, Ecto.Changeset.t()}
157
+
158
+ @doc """
159
+ Retrieves the association from the given schema.
160
+ """
161
+ def association_from_schema!(schema, assoc) do
162
+ schema.__schema__(:association, assoc) ||
163
+ raise ArgumentError, "schema #{inspect(schema)} does not have association #{inspect(assoc)}"
164
+ end
165
+
166
+ @doc """
167
+ Returns the association key for the given module with the given suffix.
168
+
169
+ ## Examples
170
+
171
+ iex> Ecto.Association.association_key(Hello.World, :id)
172
+ :world_id
173
+
174
+ iex> Ecto.Association.association_key(Hello.HTTP, :id)
175
+ :http_id
176
+
177
+ iex> Ecto.Association.association_key(Hello.HTTPServer, :id)
178
+ :http_server_id
179
+
180
+ """
181
+ def association_key(module, suffix) do
182
+ prefix = module |> Module.split() |> List.last() |> Macro.underscore()
183
+ :"#{prefix}_#{suffix}"
184
+ end
185
+
186
+ @doc """
187
+ Build an association query through the given associations from the specified owner table
188
+ and through the given associations. Finally filter by the provided values of the owner_key of
189
+ the first relationship in the chain. Used in Ecto.assoc/2.
190
+ """
191
+ def filter_through_chain(owner, through, values) do
192
+ chain_through(owner, through, nil, values)
193
+ |> distinct([x], true)
194
+ end
195
+
196
+ @doc """
197
+ Join the target table given a list of associations to go through starting from the owner table.
198
+ """
199
+ def join_through_chain(owner, through, query) do
200
+ chain_through(owner, through, query, nil)
201
+ end
202
+
203
+ # This function is used by both join_through_chain/3 and filter_through_chain/3 since the algorithm for both
204
+ # is nearly identical barring a few differences.
205
+ defp chain_through(owner, through, join_to, values) do
206
+ # Flatten the chain of throughs. If any of the associations is a HasThrough this allows us to expand it so we have
207
+ # a list of atomic associations to join through.
208
+ {_, through} = flatten_through_chain(owner, through, [])
209
+
210
+ # If we're joining then we're going forward from the owner table to the destination table.
211
+ # Otherwise we're going backward from the destination table then filtering by values.
212
+ chain_direction = if(join_to != nil, do: :forward, else: :backward)
213
+
214
+ # This stage produces a list of joins represented as a keyword list with the following structure:
215
+ # [
216
+ # [schema: (The Schema), in_key: (The key used to join into the table), out_key: (The key used to join with the next), where: (The condition KW list)]
217
+ # ]
218
+ relation_list = resolve_through_tables(owner, through, chain_direction)
219
+
220
+ # Filter out the joins which are redundant
221
+ filtered_list =
222
+ Enum.with_index(relation_list)
223
+ |> Enum.filter(fn
224
+ # We always keep the first table in the chain since it's our source table for the query
225
+ {_, 0} ->
226
+ true
227
+
228
+ {rel, _} ->
229
+ # If the condition is not empty we need to join to the table. Otherwise if the in_key and out_key is the same
230
+ # then this join is redundant since we can just join to the next table in the chain.
231
+ rel.in_key != rel.out_key or rel.where != []
232
+ end)
233
+ |> Enum.map(&elem(&1, 0))
234
+
235
+ # If we're preloading we don't need the last table since it is the owner table.
236
+ filtered_list = if(join_to == nil, do: Enum.drop(filtered_list, -1), else: filtered_list)
237
+
238
+ [source | joins] = filtered_list
239
+
240
+ source_schema = source.schema
241
+ query = join_to || from(s in source_schema)
242
+
243
+ counter = Ecto.Query.Builder.count_binds(query) - 1
244
+
245
+ # We need to create the query by joining all the tables, and also we need the out_key of the final table to use
246
+ # for the final WHERE clause with values.
247
+ {_, query, _, dest_out_key} =
248
+ Enum.reduce(joins, {source, query, counter, source.out_key}, fn
249
+ curr_rel, {prev_rel, query, counter, _} ->
250
+ related_queryable = curr_rel.schema
251
+
252
+ next =
253
+ join(query, :inner, [{src, counter}], dest in ^related_queryable,
254
+ on: field(src, ^prev_rel.out_key) == field(dest, ^curr_rel.in_key)
255
+ )
256
+ |> combine_joins_query(curr_rel.where, counter + 1)
257
+
258
+ {curr_rel, next, counter + 1, curr_rel.out_key}
259
+ end)
260
+
261
+ final_bind = Ecto.Query.Builder.count_binds(query) - 1
262
+
263
+ values = List.wrap(values)
264
+
265
+ query =
266
+ case {join_to, values} do
267
+ {nil, [single_value]} ->
268
+ where(query, [{dest, final_bind}], field(dest, ^dest_out_key) == ^single_value)
269
+
270
+ {nil, values} ->
271
+ where(query, [{dest, final_bind}], field(dest, ^dest_out_key) in ^values)
272
+
273
+ {_, _} ->
274
+ query
275
+ end
276
+
277
+ combine_assoc_query(query, source.where || [])
278
+ end
279
+
280
+ defp flatten_through_chain(owner, [], acc), do: {owner, acc}
281
+
282
+ defp flatten_through_chain(owner, [assoc | tl], acc) do
283
+ refl = association_from_schema!(owner, assoc)
284
+
285
+ case refl do
286
+ %{through: nested_throughs} ->
287
+ {owner, acc} = flatten_through_chain(owner, nested_throughs, acc)
288
+ flatten_through_chain(owner, tl, acc)
289
+
290
+ _ ->
291
+ flatten_through_chain(refl.related, tl, acc ++ [assoc])
292
+ end
293
+ end
294
+
295
+ defp resolve_through_tables(owner, through, :backward) do
296
+ # This step generates a list of maps with the following keys:
297
+ # [
298
+ # %{schema: ..., out_key: ..., in_key: ..., where: ...}
299
+ # ]
300
+ # This is a list of all tables that we will need to join to follow the chain of throughs and which key is used
301
+ # to join in and out of the table, along with the where condition for that table. The final table of the chain will
302
+ # be "owner", and the first table of the chain will be the final destination table of all the throughs.
303
+ initial_owner_map = %{schema: owner, out_key: nil, in_key: nil, where: nil}
304
+
305
+ Enum.reduce(through, {owner, [initial_owner_map]}, fn assoc, {owner, table_list} ->
306
+ refl = association_from_schema!(owner, assoc)
307
+ [owner_map | table_list] = table_list
308
+
309
+ table_list =
310
+ case refl do
311
+ %{
312
+ join_through: join_through,
313
+ join_keys: join_keys,
314
+ join_where: join_where,
315
+ where: where
316
+ } ->
317
+ [{owner_join_key, owner_key}, {related_join_key, related_key}] = join_keys
318
+
319
+ owner_map = %{owner_map | in_key: owner_key}
320
+
321
+ join_map = %{
322
+ schema: join_through,
323
+ out_key: owner_join_key,
324
+ in_key: related_join_key,
325
+ where: join_where
326
+ }
327
+
328
+ related_map = %{schema: refl.related, out_key: related_key, in_key: nil, where: where}
329
+
330
+ [related_map, join_map, owner_map | table_list]
331
+
332
+ _ ->
333
+ owner_map = %{owner_map | in_key: refl.owner_key}
334
+
335
+ related_map = %{
336
+ schema: refl.related,
337
+ out_key: refl.related_key,
338
+ in_key: nil,
339
+ where: refl.where
340
+ }
341
+
342
+ [related_map, owner_map | table_list]
343
+ end
344
+
345
+ {refl.related, table_list}
346
+ end)
347
+ |> elem(1)
348
+ end
349
+
350
+ defp resolve_through_tables(owner, through, :forward) do
351
+ # In the forward case (joining) we need to reverse the list and swap the in_key for the out_key
352
+ # since we've changed directions.
353
+ resolve_through_tables(owner, through, :backward)
354
+ |> Enum.reverse()
355
+ |> Enum.map(fn %{out_key: out_key, in_key: in_key} = join ->
356
+ %{join | out_key: in_key, in_key: out_key}
357
+ end)
358
+ end
359
+
360
+ @doc """
361
+ Add the default assoc query where clauses to a join.
362
+
363
+ This handles only `where` and converts it to a `join`,
364
+ as that is the only information propagate in join queries.
365
+ """
366
+ def combine_joins_query(query, [], _binding), do: query
367
+
368
+ def combine_joins_query(%{joins: joins} = query, [_ | _] = conditions, binding) do
369
+ {joins, [join_expr]} = Enum.split(joins, -1)
370
+ %{on: %{params: params, expr: expr} = join_on} = join_expr
371
+ {expr, params} = expand_where(conditions, expr, Enum.reverse(params), length(params), binding)
372
+ %{query | joins: joins ++ [%{join_expr | on: %{join_on | expr: expr, params: params}}]}
373
+ end
374
+
375
+ @doc """
376
+ Add the default assoc query where clauses a provided query.
377
+ """
378
+ def combine_assoc_query(query, []), do: query
379
+
380
+ def combine_assoc_query(%{wheres: []} = query, conditions) do
381
+ {expr, params} = expand_where(conditions, true, [], 0, 0)
382
+
383
+ bool_expr = %Ecto.Query.BooleanExpr{
384
+ op: :and,
385
+ expr: expr,
386
+ params: params,
387
+ line: __ENV__.line,
388
+ file: __ENV__.file
389
+ }
390
+
391
+ %{query | wheres: [bool_expr]}
392
+ end
393
+
394
+ def combine_assoc_query(%{wheres: wheres} = query, conditions) do
395
+ {wheres, [where_expr]} = Enum.split(wheres, -1)
396
+ %{params: params, expr: expr} = where_expr
397
+ {expr, params} = expand_where(conditions, expr, Enum.reverse(params), length(params), 0)
398
+ %{query | wheres: wheres ++ [%{where_expr | expr: expr, params: params}]}
399
+ end
400
+
401
+ defp expand_where(conditions, expr, params, counter, binding) do
402
+ conjoin_exprs = fn
403
+ true, r -> r
404
+ l, r -> {:and, [], [l, r]}
405
+ end
406
+
407
+ {expr, params, _counter} =
408
+ Enum.reduce(conditions, {expr, params, counter}, fn
409
+ {key, nil}, {expr, params, counter} ->
410
+ expr = conjoin_exprs.(expr, {:is_nil, [], [to_field(binding, key)]})
411
+ {expr, params, counter}
412
+
413
+ {key, {:not, nil}}, {expr, params, counter} ->
414
+ expr = conjoin_exprs.(expr, {:not, [], [{:is_nil, [], [to_field(binding, key)]}]})
415
+ {expr, params, counter}
416
+
417
+ {key, {:fragment, frag}}, {expr, params, counter} when is_binary(frag) ->
418
+ pieces = Ecto.Query.Builder.fragment_pieces(frag, [to_field(binding, key)])
419
+ expr = conjoin_exprs.(expr, {:fragment, [], pieces})
420
+ {expr, params, counter}
421
+
422
+ {key, {:in, value}}, {expr, params, counter} when is_list(value) ->
423
+ expr = conjoin_exprs.(expr, {:in, [], [to_field(binding, key), {:^, [], [counter]}]})
424
+ {expr, [{value, {:in, {binding, key}}} | params], counter + 1}
425
+
426
+ {key, value}, {expr, params, counter} ->
427
+ expr = conjoin_exprs.(expr, {:==, [], [to_field(binding, key), {:^, [], [counter]}]})
428
+ {expr, [{value, {binding, key}} | params], counter + 1}
429
+ end)
430
+
431
+ {expr, Enum.reverse(params)}
432
+ end
433
+
434
+ defp to_field(binding, field),
435
+ do: {{:., [], [{:&, [], [binding]}, field]}, [], []}
436
+
437
+ @doc """
438
+ Build a join query with the given `through` associations starting at `counter`.
439
+ """
440
+ def joins_query(query, through, counter) do
441
+ Enum.reduce(through, {query, counter}, fn current, {acc, counter} ->
442
+ query = join(acc, :inner, [{x, counter}], assoc(x, ^current))
443
+ {query, counter + 1}
444
+ end)
445
+ |> elem(0)
446
+ end
447
+
448
+ @doc """
449
+ Retrieves related module from queryable.
450
+
451
+ ## Examples
452
+
453
+ iex> Ecto.Association.related_from_query({"custom_source", Schema}, :comments_v1)
454
+ Schema
455
+
456
+ iex> Ecto.Association.related_from_query(Schema, :comments_v1)
457
+ Schema
458
+
459
+ iex> Ecto.Association.related_from_query("wrong", :comments_v1)
460
+ ** (ArgumentError) association :comments_v1 queryable must be a schema or a {source, schema}. got: "wrong"
461
+ """
462
+ def related_from_query(atom, _name) when is_atom(atom), do: atom
463
+
464
+ def related_from_query({source, schema}, _name) when is_binary(source) and is_atom(schema),
465
+ do: schema
466
+
467
+ def related_from_query(queryable, name) do
468
+ raise ArgumentError,
469
+ "association #{inspect(name)} queryable must be a schema or " <>
470
+ "a {source, schema}. got: #{inspect(queryable)}"
471
+ end
472
+
473
+ @doc """
474
+ Applies default values into the struct.
475
+ """
476
+ def apply_defaults(struct, defaults, _owner) when is_list(defaults) do
477
+ struct(struct, defaults)
478
+ end
479
+
480
+ def apply_defaults(struct, {mod, fun, args}, owner) do
481
+ apply(mod, fun, [struct.__struct__(), owner | args])
482
+ end
483
+
484
+ @doc """
485
+ Validates `defaults` for association named `name`.
486
+ """
487
+ def validate_defaults!(_module, _name, {mod, fun, args} = defaults)
488
+ when is_atom(mod) and is_atom(fun) and is_list(args),
489
+ do: defaults
490
+
491
+ def validate_defaults!(module, _name, fun) when is_atom(fun),
492
+ do: {module, fun, []}
493
+
494
+ def validate_defaults!(_module, _name, defaults) when is_list(defaults),
495
+ do: defaults
496
+
497
+ def validate_defaults!(_module, name, defaults) do
498
+ raise ArgumentError,
499
+ "expected defaults for #{inspect(name)} to be a keyword list " <>
500
+ "or a {module, fun, args} tuple, got: `#{inspect(defaults)}`"
501
+ end
502
+
503
+ @doc """
504
+ Validates `preload_order` for association named `name`.
505
+ """
506
+ def validate_preload_order!(_name, {mod, fun, args} = preload_order)
507
+ when is_atom(mod) and is_atom(fun) and is_list(args),
508
+ do: preload_order
509
+
510
+ def validate_preload_order!(name, preload_order) when is_list(preload_order) do
511
+ Enum.map(preload_order, fn
512
+ field when is_atom(field) ->
513
+ field
514
+
515
+ {direction, field} when is_atom(direction) and is_atom(field) ->
516
+ unless OrderBy.valid_direction?(direction) do
517
+ raise ArgumentError,
518
+ "expected `:preload_order` for #{inspect(name)} to be a keyword list or a list of atoms/fields, " <>
519
+ "got: `#{inspect(preload_order)}`, " <>
520
+ "`#{inspect(direction)}` is not a valid direction"
521
+ end
522
+
523
+ {direction, field}
524
+
525
+ item ->
526
+ raise ArgumentError,
527
+ "expected `:preload_order` for #{inspect(name)} to be a keyword list or a list of atoms/fields, " <>
528
+ "got: `#{inspect(preload_order)}`, " <>
529
+ "`#{inspect(item)}` is not valid"
530
+ end)
531
+ end
532
+
533
+ def validate_preload_order!(name, preload_order) do
534
+ raise ArgumentError,
535
+ "expected `:preload_order` for #{inspect(name)} to be a keyword list, a list of atoms/fields " <>
536
+ "or a {Mod, fun, args} tuple, got: `#{inspect(preload_order)}`"
537
+ end
538
+
539
+ @doc """
540
+ Merges source from query into to the given schema.
541
+
542
+ In case the query does not have a source, returns
543
+ the schema unchanged.
544
+ """
545
+ def merge_source(schema, query)
546
+
547
+ def merge_source(%{__meta__: %{source: source}} = struct, {source, _}) do
548
+ struct
549
+ end
550
+
551
+ def merge_source(struct, {source, _}) do
552
+ Ecto.put_meta(struct, source: source)
553
+ end
554
+
555
+ def merge_source(struct, _query) do
556
+ struct
557
+ end
558
+
559
+ @doc """
560
+ Updates the prefix of a changeset based on the metadata.
561
+ """
562
+ def update_parent_prefix(
563
+ %{data: %{__meta__: %{prefix: prefix}}} = changeset,
564
+ %{__meta__: %{prefix: prefix}}
565
+ ),
566
+ do: changeset
567
+
568
+ def update_parent_prefix(
569
+ %{data: %{__meta__: %{prefix: nil}}} = changeset,
570
+ %{__meta__: %{prefix: prefix}}
571
+ ),
572
+ do: update_in(changeset.data, &Ecto.put_meta(&1, prefix: prefix))
573
+
574
+ def update_parent_prefix(changeset, _),
575
+ do: changeset
576
+
577
+ @doc """
578
+ Performs the repository action in the related changeset,
579
+ returning `{:ok, data}` or `{:error, changes}`.
580
+ """
581
+ def on_repo_change(%{data: struct}, [], _adapter, _opts) do
582
+ {:ok, struct}
583
+ end
584
+
585
+ def on_repo_change(changeset, assocs, adapter, opts) do
586
+ %{data: struct, changes: changes, action: action} = changeset
587
+
588
+ {struct, changes, _halt, valid?} =
589
+ Enum.reduce(assocs, {struct, changes, false, true}, fn {refl, value}, acc ->
590
+ on_repo_change(refl, value, changeset, action, adapter, opts, acc)
591
+ end)
592
+
593
+ case valid? do
594
+ true -> {:ok, struct}
595
+ false -> {:error, changes}
596
+ end
597
+ end
598
+
599
+ defp on_repo_change(
600
+ %{cardinality: :one, field: field} = meta,
601
+ nil,
602
+ parent_changeset,
603
+ _repo_action,
604
+ adapter,
605
+ opts,
606
+ {parent, changes, halt, valid?}
607
+ ) do
608
+ if not halt, do: maybe_replace_one!(meta, nil, parent, parent_changeset, adapter, opts)
609
+ {Map.put(parent, field, nil), Map.put(changes, field, nil), halt, valid?}
610
+ end
611
+
612
+ defp on_repo_change(
613
+ %{cardinality: :one, field: field, __struct__: mod} = meta,
614
+ %{action: action, data: current} = changeset,
615
+ parent_changeset,
616
+ repo_action,
617
+ adapter,
618
+ opts,
619
+ {parent, changes, halt, valid?}
620
+ ) do
621
+ check_action!(meta, action, repo_action)
622
+ if not halt, do: maybe_replace_one!(meta, current, parent, parent_changeset, adapter, opts)
623
+
624
+ case on_repo_change_unless_halted(halt, mod, meta, parent_changeset, changeset, adapter, opts) do
625
+ {:ok, struct} ->
626
+ {Map.put(parent, field, struct), Map.put(changes, field, changeset), halt, valid?}
627
+
628
+ {:error, error_changeset} ->
629
+ {parent, Map.put(changes, field, error_changeset),
630
+ halted?(halt, changeset, error_changeset), false}
631
+ end
632
+ end
633
+
634
+ defp on_repo_change(
635
+ %{cardinality: :many, field: field, __struct__: mod} = meta,
636
+ changesets,
637
+ parent_changeset,
638
+ repo_action,
639
+ adapter,
640
+ opts,
641
+ {parent, changes, halt, all_valid?}
642
+ ) do
643
+ {changesets, structs, halt, valid?} =
644
+ Enum.reduce(changesets, {[], [], halt, true}, fn
645
+ %{action: action} = changeset, {changesets, structs, halt, valid?} ->
646
+ check_action!(meta, action, repo_action)
647
+
648
+ case on_repo_change_unless_halted(
649
+ halt,
650
+ mod,
651
+ meta,
652
+ parent_changeset,
653
+ changeset,
654
+ adapter,
655
+ opts
656
+ ) do
657
+ {:ok, nil} ->
658
+ {[changeset | changesets], structs, halt, valid?}
659
+
660
+ {:ok, struct} ->
661
+ {[changeset | changesets], [struct | structs], halt, valid?}
662
+
663
+ {:error, error_changeset} ->
664
+ {[error_changeset | changesets], structs, halted?(halt, changeset, error_changeset),
665
+ false}
666
+ end
667
+ end)
668
+
669
+ if valid? do
670
+ {Map.put(parent, field, Enum.reverse(structs)),
671
+ Map.put(changes, field, Enum.reverse(changesets)), halt, all_valid?}
672
+ else
673
+ {parent, Map.put(changes, field, Enum.reverse(changesets)), halt, false}
674
+ end
675
+ end
676
+
677
+ defp check_action!(%{related: schema}, :delete, :insert) do
678
+ raise ArgumentError,
679
+ "got action :delete in changeset for associated #{inspect(schema)} while inserting"
680
+ end
681
+
682
+ defp check_action!(_, _, _), do: :ok
683
+
684
+ defp halted?(true, _, _), do: true
685
+ defp halted?(_, %{valid?: true}, %{valid?: false}), do: true
686
+ defp halted?(_, _, _), do: false
687
+
688
+ defp on_repo_change_unless_halted(true, _mod, _meta, _parent, changeset, _adapter, _opts) do
689
+ {:error, changeset}
690
+ end
691
+
692
+ defp on_repo_change_unless_halted(false, mod, meta, parent, changeset, adapter, opts) do
693
+ mod.on_repo_change(meta, parent, changeset, adapter, opts)
694
+ end
695
+
696
+ defp maybe_replace_one!(
697
+ %{field: field, __struct__: mod} = meta,
698
+ current,
699
+ parent,
700
+ parent_changeset,
701
+ adapter,
702
+ opts
703
+ ) do
704
+ previous = Map.get(parent, field)
705
+
706
+ if replaceable?(previous) and primary_key!(previous) != primary_key!(current) do
707
+ changeset = %{Ecto.Changeset.change(previous) | action: :replace}
708
+
709
+ case mod.on_repo_change(meta, parent_changeset, changeset, adapter, opts) do
710
+ {:ok, _} ->
711
+ :ok
712
+
713
+ {:error, changeset} ->
714
+ raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset
715
+ end
716
+ end
717
+ end
718
+
719
+ defp maybe_replace_one!(_, _, _, _, _, _), do: :ok
720
+
721
+ defp replaceable?(nil), do: false
722
+ defp replaceable?(%Ecto.Association.NotLoaded{}), do: false
723
+ defp replaceable?(%{__meta__: %{state: :built}}), do: false
724
+ defp replaceable?(_), do: true
725
+
726
+ defp primary_key!(nil), do: []
727
+ defp primary_key!(struct), do: Ecto.primary_key!(struct)
728
+ end
729
+
730
+ defmodule Ecto.Association.Has do
731
+ @moduledoc """
732
+ The association struct for `has_one` and `has_many` associations.
733
+
734
+ Its fields are:
735
+
736
+ * `cardinality` - The association cardinality
737
+ * `field` - The name of the association field on the schema
738
+ * `owner` - The schema where the association was defined
739
+ * `related` - The schema that is associated
740
+ * `owner_key` - The key on the `owner` schema used for the association
741
+ * `related_key` - The key on the `related` schema used for the association
742
+ * `queryable` - The real query to use for querying association
743
+ * `on_delete` - The action taken on associations when schema is deleted
744
+ * `on_replace` - The action taken on associations when schema is replaced
745
+ * `defaults` - Default fields used when building the association
746
+ * `relationship` - The relationship to the specified schema, default is `:child`
747
+ * `preload_order` - Default `order_by` of the association, used only by preload
748
+ """
749
+
750
+ @behaviour Ecto.Association
751
+ @on_delete_opts [:nothing, :nilify_all, :delete_all]
752
+ @on_replace_opts [:raise, :mark_as_invalid, :delete, :delete_if_exists, :nilify]
753
+ @has_one_on_replace_opts @on_replace_opts ++ [:update]
754
+ defstruct [
755
+ :cardinality,
756
+ :field,
757
+ :owner,
758
+ :related,
759
+ :owner_key,
760
+ :related_key,
761
+ :on_cast,
762
+ :queryable,
763
+ :on_delete,
764
+ :on_replace,
765
+ where: [],
766
+ unique: true,
767
+ defaults: [],
768
+ relationship: :child,
769
+ ordered: false,
770
+ preload_order: []
771
+ ]
772
+
773
+ @impl true
774
+ def after_compile_validation(%{queryable: queryable, related_key: related_key}, env) do
775
+ compiled = Ecto.Association.ensure_compiled(queryable, env)
776
+
777
+ cond do
778
+ compiled == :skip ->
779
+ :ok
780
+
781
+ compiled == :not_found ->
782
+ {:error, "associated schema #{inspect(queryable)} does not exist"}
783
+
784
+ not function_exported?(queryable, :__schema__, 2) ->
785
+ {:error, "associated module #{inspect(queryable)} is not an Ecto schema"}
786
+
787
+ is_nil(queryable.__schema__(:type, related_key)) ->
788
+ {:error, "associated schema #{inspect(queryable)} does not have field `#{related_key}`"}
789
+
790
+ true ->
791
+ :ok
792
+ end
793
+ end
794
+
795
+ @impl true
796
+ def struct(module, name, opts) do
797
+ queryable = Keyword.fetch!(opts, :queryable)
798
+ cardinality = Keyword.fetch!(opts, :cardinality)
799
+ related = Ecto.Association.related_from_query(queryable, name)
800
+
801
+ ref =
802
+ module
803
+ |> Module.get_attribute(:primary_key)
804
+ |> get_ref(opts[:references], name)
805
+
806
+ unless Module.get_attribute(module, :ecto_fields)[ref] do
807
+ raise ArgumentError,
808
+ "schema does not have the field #{inspect(ref)} used by " <>
809
+ "association #{inspect(name)}, please set the :references option accordingly"
810
+ end
811
+
812
+ if opts[:through] do
813
+ raise ArgumentError,
814
+ "invalid association #{inspect(name)}. When using the :through " <>
815
+ "option, the schema should not be passed as second argument"
816
+ end
817
+
818
+ on_delete = Keyword.get(opts, :on_delete, :nothing)
819
+
820
+ unless on_delete in @on_delete_opts do
821
+ raise ArgumentError,
822
+ "invalid :on_delete option for #{inspect(name)}. " <>
823
+ "The only valid options are: " <>
824
+ Enum.map_join(@on_delete_opts, ", ", &"`#{inspect(&1)}`")
825
+ end
826
+
827
+ on_replace = Keyword.get(opts, :on_replace, :raise)
828
+ on_replace_opts = if cardinality == :one, do: @has_one_on_replace_opts, else: @on_replace_opts
829
+
830
+ unless on_replace in on_replace_opts do
831
+ raise ArgumentError,
832
+ "invalid `:on_replace` option for #{inspect(name)}. " <>
833
+ "The only valid options are: " <>
834
+ Enum.map_join(@on_replace_opts, ", ", &"`#{inspect(&1)}`")
835
+ end
836
+
837
+ defaults = Ecto.Association.validate_defaults!(module, name, opts[:defaults] || [])
838
+ preload_order = Ecto.Association.validate_preload_order!(name, opts[:preload_order] || [])
839
+ where = opts[:where] || []
840
+
841
+ unless is_list(where) do
842
+ raise ArgumentError,
843
+ "expected `:where` for #{inspect(name)} to be a keyword list, got: `#{inspect(where)}`"
844
+ end
845
+
846
+ %__MODULE__{
847
+ field: name,
848
+ cardinality: cardinality,
849
+ owner: module,
850
+ related: related,
851
+ owner_key: ref,
852
+ related_key: opts[:foreign_key] || Ecto.Association.association_key(module, ref),
853
+ queryable: queryable,
854
+ on_delete: on_delete,
855
+ on_replace: on_replace,
856
+ defaults: defaults,
857
+ where: where,
858
+ preload_order: preload_order
859
+ }
860
+ end
861
+
862
+ defp get_ref(primary_key, nil, name) when primary_key in [nil, false] do
863
+ raise ArgumentError,
864
+ "need to set :references option for " <>
865
+ "association #{inspect(name)} when schema has no primary key"
866
+ end
867
+
868
+ defp get_ref(primary_key, nil, _name), do: elem(primary_key, 0)
869
+ defp get_ref(_primary_key, references, _name), do: references
870
+
871
+ @impl true
872
+ def build(%{owner_key: owner_key, related_key: related_key} = refl, owner, attributes) do
873
+ data = refl |> build(owner) |> struct(attributes)
874
+ %{data | related_key => Map.get(owner, owner_key)}
875
+ end
876
+
877
+ @impl true
878
+ def joins_query(
879
+ %{related_key: related_key, owner: owner, owner_key: owner_key, queryable: queryable} =
880
+ assoc
881
+ ) do
882
+ from(o in owner, join: q in ^queryable, on: field(q, ^related_key) == field(o, ^owner_key))
883
+ |> Ecto.Association.combine_joins_query(assoc.where, 1)
884
+ end
885
+
886
+ @impl true
887
+ def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, [value]) do
888
+ from(x in (query || queryable), where: field(x, ^related_key) == ^value)
889
+ |> Ecto.Association.combine_assoc_query(assoc.where)
890
+ end
891
+
892
+ @impl true
893
+ def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, values) do
894
+ from(x in (query || queryable), where: field(x, ^related_key) in ^values)
895
+ |> Ecto.Association.combine_assoc_query(assoc.where)
896
+ end
897
+
898
+ @impl true
899
+ def preload_info(%{related_key: related_key} = refl) do
900
+ {:assoc, refl, {0, related_key}}
901
+ end
902
+
903
+ @impl true
904
+ def on_repo_change(
905
+ %{on_replace: :delete_if_exists} = refl,
906
+ parent_changeset,
907
+ %{action: :replace} = changeset,
908
+ adapter,
909
+ opts
910
+ ) do
911
+ try do
912
+ on_repo_change(%{refl | on_replace: :delete}, parent_changeset, changeset, adapter, opts)
913
+ rescue
914
+ Ecto.StaleEntryError -> {:ok, nil}
915
+ end
916
+ end
917
+
918
+ def on_repo_change(
919
+ %{on_replace: on_replace} = refl,
920
+ %{data: parent} = parent_changeset,
921
+ %{action: :replace} = changeset,
922
+ adapter,
923
+ opts
924
+ ) do
925
+ changeset =
926
+ case on_replace do
927
+ :nilify -> %{changeset | action: :update}
928
+ :update -> %{changeset | action: :update}
929
+ :delete -> %{changeset | action: :delete}
930
+ end
931
+
932
+ changeset = Ecto.Association.update_parent_prefix(changeset, parent)
933
+
934
+ case on_repo_change(refl, %{parent_changeset | data: nil}, changeset, adapter, opts) do
935
+ {:ok, _} -> {:ok, nil}
936
+ {:error, changeset} -> {:error, changeset}
937
+ end
938
+ end
939
+
940
+ def on_repo_change(assoc, parent_changeset, changeset, _adapter, opts) do
941
+ %{data: parent, repo: repo} = parent_changeset
942
+ %{action: action, changes: changes} = changeset
943
+
944
+ {key, value} = parent_key(assoc, parent)
945
+ changeset = update_parent_key(changeset, action, key, value)
946
+ changeset = Ecto.Association.update_parent_prefix(changeset, parent)
947
+
948
+ case apply(repo, action, [changeset, opts]) do
949
+ {:ok, _} = ok ->
950
+ if action == :delete, do: {:ok, nil}, else: ok
951
+
952
+ {:error, changeset} ->
953
+ original = Map.get(changes, key)
954
+ {:error, put_in(changeset.changes[key], original)}
955
+ end
956
+ end
957
+
958
+ defp update_parent_key(changeset, :delete, _key, _value),
959
+ do: changeset
960
+
961
+ defp update_parent_key(changeset, _action, key, value),
962
+ do: Ecto.Changeset.put_change(changeset, key, value)
963
+
964
+ defp parent_key(%{related_key: related_key}, nil) do
965
+ {related_key, nil}
966
+ end
967
+
968
+ defp parent_key(%{owner_key: owner_key, related_key: related_key}, owner) do
969
+ {related_key, Map.get(owner, owner_key)}
970
+ end
971
+
972
+ ## Relation callbacks
973
+ @behaviour Ecto.Changeset.Relation
974
+
975
+ @impl true
976
+ def build(%{related: related, queryable: queryable, defaults: defaults}, owner) do
977
+ related
978
+ |> Ecto.Association.apply_defaults(defaults, owner)
979
+ |> Ecto.Association.merge_source(queryable)
980
+ end
981
+
982
+ ## On delete callbacks
983
+
984
+ @doc false
985
+ def delete_all(refl, parent, repo_name, opts) do
986
+ if query = on_delete_query(refl, parent) do
987
+ Ecto.Repo.Queryable.delete_all(repo_name, query, opts)
988
+ end
989
+ end
990
+
991
+ @doc false
992
+ def nilify_all(%{related_key: related_key} = refl, parent, repo_name, opts) do
993
+ if query = on_delete_query(refl, parent) do
994
+ Ecto.Repo.Queryable.update_all(repo_name, query, [set: [{related_key, nil}]], opts)
995
+ end
996
+ end
997
+
998
+ defp on_delete_query(
999
+ %{owner_key: owner_key, related_key: related_key, queryable: queryable},
1000
+ parent
1001
+ ) do
1002
+ if value = Map.get(parent, owner_key) do
1003
+ query = from x in queryable, where: field(x, ^related_key) == ^value
1004
+
1005
+ parent
1006
+ |> Ecto.get_meta(:prefix)
1007
+ |> case do
1008
+ nil -> query
1009
+ prefix -> Ecto.Query.put_query_prefix(query, prefix)
1010
+ end
1011
+ end
1012
+ end
1013
+ end
1014
+
1015
+ defmodule Ecto.Association.HasThrough do
1016
+ @moduledoc """
1017
+ The association struct for `has_one` and `has_many` through associations.
1018
+
1019
+ Its fields are:
1020
+
1021
+ * `cardinality` - The association cardinality
1022
+ * `field` - The name of the association field on the schema
1023
+ * `owner` - The schema where the association was defined
1024
+ * `owner_key` - The key on the `owner` schema used for the association
1025
+ * `through` - The through associations
1026
+ * `relationship` - The relationship to the specified schema, default `:child`
1027
+ """
1028
+
1029
+ @behaviour Ecto.Association
1030
+ defstruct [
1031
+ :cardinality,
1032
+ :field,
1033
+ :owner,
1034
+ :owner_key,
1035
+ :through,
1036
+ :on_cast,
1037
+ relationship: :child,
1038
+ unique: true,
1039
+ ordered: false
1040
+ ]
1041
+
1042
+ @impl true
1043
+ def after_compile_validation(_, _) do
1044
+ :ok
1045
+ end
1046
+
1047
+ @impl true
1048
+ def struct(module, name, opts) do
1049
+ through = Keyword.fetch!(opts, :through)
1050
+
1051
+ refl =
1052
+ case through do
1053
+ [h, _ | _] ->
1054
+ Module.get_attribute(module, :ecto_assocs)[h]
1055
+
1056
+ _ ->
1057
+ raise ArgumentError,
1058
+ ":through expects a list with at least two entries: " <>
1059
+ "the association in the current module and one step through, got: #{inspect(through)}"
1060
+ end
1061
+
1062
+ unless refl do
1063
+ raise ArgumentError,
1064
+ "schema does not have the association #{inspect(hd(through))} " <>
1065
+ "used by association #{inspect(name)}, please ensure the association exists and " <>
1066
+ "is defined before the :through one"
1067
+ end
1068
+
1069
+ %__MODULE__{
1070
+ field: name,
1071
+ cardinality: Keyword.fetch!(opts, :cardinality),
1072
+ through: through,
1073
+ owner: module,
1074
+ owner_key: refl.owner_key
1075
+ }
1076
+ end
1077
+
1078
+ @impl true
1079
+ def build(%{field: name}, %{__struct__: owner}, _attributes) do
1080
+ raise ArgumentError,
1081
+ "cannot build through association `#{inspect(name)}` for #{inspect(owner)}. " <>
1082
+ "Instead build the intermediate steps explicitly."
1083
+ end
1084
+
1085
+ @impl true
1086
+ def preload_info(%{through: through} = refl) do
1087
+ {:through, refl, through}
1088
+ end
1089
+
1090
+ @impl true
1091
+ def on_repo_change(%{field: name}, _, _, _, _) do
1092
+ raise ArgumentError,
1093
+ "cannot insert/update/delete through associations `#{inspect(name)}` via the repository. " <>
1094
+ "Instead build the intermediate steps explicitly."
1095
+ end
1096
+
1097
+ @impl true
1098
+ def joins_query(%{owner: owner, through: through}) do
1099
+ Ecto.Association.join_through_chain(owner, through, from(x in owner))
1100
+ end
1101
+
1102
+ @impl true
1103
+ def assoc_query(%{owner: owner, through: through}, _, values) do
1104
+ Ecto.Association.filter_through_chain(owner, through, values)
1105
+ end
1106
+ end
1107
+
1108
+ defmodule Ecto.Association.BelongsTo do
1109
+ @moduledoc """
1110
+ The association struct for a `belongs_to` association.
1111
+
1112
+ Its fields are:
1113
+
1114
+ * `cardinality` - The association cardinality
1115
+ * `field` - The name of the association field on the schema
1116
+ * `owner` - The schema where the association was defined
1117
+ * `owner_key` - The key on the `owner` schema used for the association
1118
+ * `related` - The schema that is associated
1119
+ * `related_key` - The key on the `related` schema used for the association
1120
+ * `queryable` - The real query to use for querying association
1121
+ * `defaults` - Default fields used when building the association
1122
+ * `relationship` - The relationship to the specified schema, default `:parent`
1123
+ * `on_replace` - The action taken on associations when schema is replaced
1124
+ """
1125
+
1126
+ @behaviour Ecto.Association
1127
+ @on_replace_opts [:raise, :mark_as_invalid, :delete, :delete_if_exists, :nilify, :update]
1128
+ defstruct [
1129
+ :field,
1130
+ :owner,
1131
+ :related,
1132
+ :owner_key,
1133
+ :related_key,
1134
+ :queryable,
1135
+ :on_cast,
1136
+ :on_replace,
1137
+ where: [],
1138
+ defaults: [],
1139
+ cardinality: :one,
1140
+ relationship: :parent,
1141
+ unique: true,
1142
+ ordered: false
1143
+ ]
1144
+
1145
+ @impl true
1146
+ def after_compile_validation(%{queryable: queryable, related_key: related_key}, env) do
1147
+ compiled = Ecto.Association.ensure_compiled(queryable, env)
1148
+
1149
+ cond do
1150
+ compiled == :skip ->
1151
+ :ok
1152
+
1153
+ compiled == :not_found ->
1154
+ {:error, "associated schema #{inspect(queryable)} does not exist"}
1155
+
1156
+ not function_exported?(queryable, :__schema__, 2) ->
1157
+ {:error, "associated module #{inspect(queryable)} is not an Ecto schema"}
1158
+
1159
+ is_nil(queryable.__schema__(:type, related_key)) ->
1160
+ {:error, "associated schema #{inspect(queryable)} does not have field `#{related_key}`"}
1161
+
1162
+ true ->
1163
+ :ok
1164
+ end
1165
+ end
1166
+
1167
+ @impl true
1168
+ def struct(module, name, opts) do
1169
+ ref = if ref = opts[:references], do: ref, else: :id
1170
+ queryable = Keyword.fetch!(opts, :queryable)
1171
+ related = Ecto.Association.related_from_query(queryable, name)
1172
+ on_replace = Keyword.get(opts, :on_replace, :raise)
1173
+
1174
+ unless on_replace in @on_replace_opts do
1175
+ raise ArgumentError,
1176
+ "invalid `:on_replace` option for #{inspect(name)}. " <>
1177
+ "The only valid options are: " <>
1178
+ Enum.map_join(@on_replace_opts, ", ", &"`#{inspect(&1)}`")
1179
+ end
1180
+
1181
+ defaults = Ecto.Association.validate_defaults!(module, name, opts[:defaults] || [])
1182
+ where = opts[:where] || []
1183
+
1184
+ unless is_list(where) do
1185
+ raise ArgumentError,
1186
+ "expected `:where` for #{inspect(name)} to be a keyword list, got: `#{inspect(where)}`"
1187
+ end
1188
+
1189
+ %__MODULE__{
1190
+ field: name,
1191
+ owner: module,
1192
+ related: related,
1193
+ owner_key: Keyword.fetch!(opts, :foreign_key),
1194
+ related_key: ref,
1195
+ queryable: queryable,
1196
+ on_replace: on_replace,
1197
+ defaults: defaults,
1198
+ where: where
1199
+ }
1200
+ end
1201
+
1202
+ @impl true
1203
+ def build(refl, owner, attributes) do
1204
+ refl
1205
+ |> build(owner)
1206
+ |> struct(attributes)
1207
+ end
1208
+
1209
+ @impl true
1210
+ def joins_query(
1211
+ %{related_key: related_key, owner: owner, owner_key: owner_key, queryable: queryable} =
1212
+ assoc
1213
+ ) do
1214
+ from(o in owner, join: q in ^queryable, on: field(q, ^related_key) == field(o, ^owner_key))
1215
+ |> Ecto.Association.combine_joins_query(assoc.where, 1)
1216
+ end
1217
+
1218
+ @impl true
1219
+ def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, [value]) do
1220
+ from(x in (query || queryable), where: field(x, ^related_key) == ^value)
1221
+ |> Ecto.Association.combine_assoc_query(assoc.where)
1222
+ end
1223
+
1224
+ @impl true
1225
+ def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, values) do
1226
+ from(x in (query || queryable), where: field(x, ^related_key) in ^values)
1227
+ |> Ecto.Association.combine_assoc_query(assoc.where)
1228
+ end
1229
+
1230
+ @impl true
1231
+ def preload_info(%{related_key: related_key} = refl) do
1232
+ {:assoc, refl, {0, related_key}}
1233
+ end
1234
+
1235
+ @impl true
1236
+ def on_repo_change(%{on_replace: :nilify}, _, %{action: :replace}, _adapter, _opts) do
1237
+ {:ok, nil}
1238
+ end
1239
+
1240
+ def on_repo_change(
1241
+ %{on_replace: :delete_if_exists} = refl,
1242
+ parent_changeset,
1243
+ %{action: :replace} = changeset,
1244
+ adapter,
1245
+ opts
1246
+ ) do
1247
+ try do
1248
+ on_repo_change(%{refl | on_replace: :delete}, parent_changeset, changeset, adapter, opts)
1249
+ rescue
1250
+ Ecto.StaleEntryError -> {:ok, nil}
1251
+ end
1252
+ end
1253
+
1254
+ def on_repo_change(
1255
+ %{on_replace: on_replace} = refl,
1256
+ parent_changeset,
1257
+ %{action: :replace} = changeset,
1258
+ adapter,
1259
+ opts
1260
+ ) do
1261
+ changeset =
1262
+ case on_replace do
1263
+ :delete -> %{changeset | action: :delete}
1264
+ :update -> %{changeset | action: :update}
1265
+ end
1266
+
1267
+ on_repo_change(refl, parent_changeset, changeset, adapter, opts)
1268
+ end
1269
+
1270
+ def on_repo_change(
1271
+ _refl,
1272
+ %{data: parent, repo: repo},
1273
+ %{action: action} = changeset,
1274
+ _adapter,
1275
+ opts
1276
+ ) do
1277
+ changeset = Ecto.Association.update_parent_prefix(changeset, parent)
1278
+
1279
+ case apply(repo, action, [changeset, opts]) do
1280
+ {:ok, _} = ok ->
1281
+ if action == :delete, do: {:ok, nil}, else: ok
1282
+
1283
+ {:error, changeset} ->
1284
+ {:error, changeset}
1285
+ end
1286
+ end
1287
+
1288
+ ## Relation callbacks
1289
+ @behaviour Ecto.Changeset.Relation
1290
+
1291
+ @impl true
1292
+ def build(%{related: related, queryable: queryable, defaults: defaults}, owner) do
1293
+ related
1294
+ |> Ecto.Association.apply_defaults(defaults, owner)
1295
+ |> Ecto.Association.merge_source(queryable)
1296
+ end
1297
+ end
1298
+
1299
+ defmodule Ecto.Association.ManyToMany do
1300
+ @moduledoc """
1301
+ The association struct for `many_to_many` associations.
1302
+
1303
+ Its fields are:
1304
+
1305
+ * `cardinality` - The association cardinality
1306
+ * `field` - The name of the association field on the schema
1307
+ * `owner` - The schema where the association was defined
1308
+ * `related` - The schema that is associated
1309
+ * `owner_key` - The key on the `owner` schema used for the association
1310
+ * `queryable` - The real query to use for querying association
1311
+ * `on_delete` - The action taken on associations when schema is deleted
1312
+ * `on_replace` - The action taken on associations when schema is replaced
1313
+ * `defaults` - Default fields used when building the association
1314
+ * `relationship` - The relationship to the specified schema, default `:child`
1315
+ * `join_keys` - The keyword list with many to many join keys
1316
+ * `join_through` - Atom (representing a schema) or a string (representing a table)
1317
+ for many to many associations
1318
+ * `join_defaults` - A list of defaults for join associations
1319
+ * `preload_order` - Default `order_by` of the association, used only by preload
1320
+ """
1321
+
1322
+ @behaviour Ecto.Association
1323
+ @on_delete_opts [:nothing, :delete_all]
1324
+ @on_replace_opts [:raise, :mark_as_invalid, :delete]
1325
+
1326
+ defstruct [
1327
+ :field,
1328
+ :owner,
1329
+ :related,
1330
+ :owner_key,
1331
+ :queryable,
1332
+ :on_delete,
1333
+ :on_replace,
1334
+ :join_keys,
1335
+ :join_through,
1336
+ :on_cast,
1337
+ where: [],
1338
+ join_where: [],
1339
+ defaults: [],
1340
+ join_defaults: [],
1341
+ relationship: :child,
1342
+ cardinality: :many,
1343
+ unique: false,
1344
+ ordered: false,
1345
+ preload_order: []
1346
+ ]
1347
+
1348
+ @impl true
1349
+ def after_compile_validation(%{queryable: queryable, join_through: join_through}, env) do
1350
+ compiled = Ecto.Association.ensure_compiled(queryable, env)
1351
+ join_compiled = Ecto.Association.ensure_compiled(join_through, env)
1352
+
1353
+ cond do
1354
+ compiled == :skip ->
1355
+ :ok
1356
+
1357
+ compiled == :not_found ->
1358
+ {:error, "associated schema #{inspect(queryable)} does not exist"}
1359
+
1360
+ not function_exported?(queryable, :__schema__, 2) ->
1361
+ {:error, "associated module #{inspect(queryable)} is not an Ecto schema"}
1362
+
1363
+ join_compiled == :skip ->
1364
+ :ok
1365
+
1366
+ join_compiled == :not_found ->
1367
+ {:error, ":join_through schema #{inspect(join_through)} does not exist"}
1368
+
1369
+ not function_exported?(join_through, :__schema__, 2) ->
1370
+ {:error, ":join_through module #{inspect(join_through)} is not an Ecto schema"}
1371
+
1372
+ true ->
1373
+ :ok
1374
+ end
1375
+ end
1376
+
1377
+ @impl true
1378
+ def struct(module, name, opts) do
1379
+ queryable = Keyword.fetch!(opts, :queryable)
1380
+ related = Ecto.Association.related_from_query(queryable, name)
1381
+
1382
+ join_keys = opts[:join_keys]
1383
+ join_through = opts[:join_through]
1384
+ validate_join_through(name, join_through)
1385
+
1386
+ {owner_key, join_keys} =
1387
+ case join_keys do
1388
+ [{join_owner_key, owner_key}, {join_related_key, related_key}]
1389
+ when is_atom(join_owner_key) and is_atom(owner_key) and
1390
+ is_atom(join_related_key) and is_atom(related_key) ->
1391
+ {owner_key, join_keys}
1392
+
1393
+ nil ->
1394
+ {:id, default_join_keys(module, related)}
1395
+
1396
+ _ ->
1397
+ raise ArgumentError,
1398
+ "many_to_many #{inspect(name)} expect :join_keys to be a keyword list " <>
1399
+ "with two entries, the first being how the join table should reach " <>
1400
+ "the current schema and the second how the join table should reach " <>
1401
+ "the associated schema. For example: #{inspect(default_join_keys(module, related))}"
1402
+ end
1403
+
1404
+ unless Module.get_attribute(module, :ecto_fields)[owner_key] do
1405
+ raise ArgumentError,
1406
+ "schema does not have the field #{inspect(owner_key)} used by " <>
1407
+ "association #{inspect(name)}, please set the :join_keys option accordingly"
1408
+ end
1409
+
1410
+ on_delete = Keyword.get(opts, :on_delete, :nothing)
1411
+ on_replace = Keyword.get(opts, :on_replace, :raise)
1412
+
1413
+ unless on_delete in @on_delete_opts do
1414
+ raise ArgumentError,
1415
+ "invalid :on_delete option for #{inspect(name)}. " <>
1416
+ "The only valid options are: " <>
1417
+ Enum.map_join(@on_delete_opts, ", ", &"`#{inspect(&1)}`")
1418
+ end
1419
+
1420
+ unless on_replace in @on_replace_opts do
1421
+ raise ArgumentError,
1422
+ "invalid `:on_replace` option for #{inspect(name)}. " <>
1423
+ "The only valid options are: " <>
1424
+ Enum.map_join(@on_replace_opts, ", ", &"`#{inspect(&1)}`")
1425
+ end
1426
+
1427
+ where = opts[:where] || []
1428
+ join_where = opts[:join_where] || []
1429
+ defaults = Ecto.Association.validate_defaults!(module, name, opts[:defaults] || [])
1430
+ join_defaults = Ecto.Association.validate_defaults!(module, name, opts[:join_defaults] || [])
1431
+ preload_order = Ecto.Association.validate_preload_order!(name, opts[:preload_order] || [])
1432
+
1433
+ unless is_list(where) do
1434
+ raise ArgumentError,
1435
+ "expected `:where` for #{inspect(name)} to be a keyword list, got: `#{inspect(where)}`"
1436
+ end
1437
+
1438
+ unless is_list(join_where) do
1439
+ raise ArgumentError,
1440
+ "expected `:join_where` for #{inspect(name)} to be a keyword list, got: `#{inspect(join_where)}`"
1441
+ end
1442
+
1443
+ if opts[:join_defaults] && is_binary(join_through) do
1444
+ raise ArgumentError, ":join_defaults has no effect for a :join_through without a schema"
1445
+ end
1446
+
1447
+ %__MODULE__{
1448
+ field: name,
1449
+ cardinality: Keyword.fetch!(opts, :cardinality),
1450
+ owner: module,
1451
+ related: related,
1452
+ owner_key: owner_key,
1453
+ join_keys: join_keys,
1454
+ join_where: join_where,
1455
+ join_through: join_through,
1456
+ join_defaults: join_defaults,
1457
+ queryable: queryable,
1458
+ on_delete: on_delete,
1459
+ on_replace: on_replace,
1460
+ unique: Keyword.get(opts, :unique, false),
1461
+ defaults: defaults,
1462
+ where: where,
1463
+ preload_order: preload_order
1464
+ }
1465
+ end
1466
+
1467
+ defp default_join_keys(module, related) do
1468
+ [
1469
+ {Ecto.Association.association_key(module, :id), :id},
1470
+ {Ecto.Association.association_key(related, :id), :id}
1471
+ ]
1472
+ end
1473
+
1474
+ @impl true
1475
+ def joins_query(
1476
+ %{owner: owner, queryable: queryable, join_through: join_through, join_keys: join_keys} =
1477
+ assoc
1478
+ ) do
1479
+ [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys
1480
+
1481
+ from(o in owner,
1482
+ join: j in ^join_through,
1483
+ on: field(j, ^join_owner_key) == field(o, ^owner_key),
1484
+ join: q in ^queryable,
1485
+ on: field(j, ^join_related_key) == field(q, ^related_key)
1486
+ )
1487
+ |> Ecto.Association.combine_joins_query(assoc.where, 2)
1488
+ |> Ecto.Association.combine_joins_query(assoc.join_where, 1)
1489
+ end
1490
+
1491
+ def assoc_query(%{queryable: queryable} = refl, values) do
1492
+ assoc_query(refl, queryable, values)
1493
+ end
1494
+
1495
+ @impl true
1496
+ def assoc_query(assoc, query, values) do
1497
+ %{queryable: queryable, join_through: join_through, join_keys: join_keys, owner: owner} =
1498
+ assoc
1499
+
1500
+ [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys
1501
+
1502
+ owner_key_type = owner.__schema__(:type, owner_key)
1503
+
1504
+ # We only need to join in the "join table". Preload and Ecto.assoc expressions can then filter
1505
+ # by &1.join_owner_key in ^... to filter down to the associated entries in the related table.
1506
+ query =
1507
+ from(q in (query || queryable),
1508
+ join: j in ^join_through,
1509
+ on: field(q, ^related_key) == field(j, ^join_related_key),
1510
+ where: field(j, ^join_owner_key) in type(^values, {:in, ^owner_key_type})
1511
+ )
1512
+ |> Ecto.Association.combine_assoc_query(assoc.where)
1513
+
1514
+ Ecto.Association.combine_joins_query(query, assoc.join_where, length(query.joins))
1515
+ end
1516
+
1517
+ @impl true
1518
+ def build(refl, owner, attributes) do
1519
+ refl
1520
+ |> build(owner)
1521
+ |> struct(attributes)
1522
+ end
1523
+
1524
+ @impl true
1525
+ def preload_info(%{join_keys: [{join_owner_key, owner_key}, {_, _}], owner: owner} = refl) do
1526
+ owner_key_type = owner.__schema__(:type, owner_key)
1527
+
1528
+ # When preloading use the last bound table (which is the join table) and the join_owner_key
1529
+ # to filter out related entities to the owner structs we're preloading with.
1530
+ {:assoc, refl, {-1, join_owner_key, owner_key_type}}
1531
+ end
1532
+
1533
+ @impl true
1534
+ def on_repo_change(
1535
+ %{on_replace: :delete} = refl,
1536
+ parent_changeset,
1537
+ %{action: :replace} = changeset,
1538
+ adapter,
1539
+ opts
1540
+ ) do
1541
+ on_repo_change(refl, parent_changeset, %{changeset | action: :delete}, adapter, opts)
1542
+ end
1543
+
1544
+ def on_repo_change(
1545
+ %{join_keys: join_keys, join_through: join_through, join_where: join_where},
1546
+ %{repo: repo, data: owner},
1547
+ %{action: :delete, data: related},
1548
+ adapter,
1549
+ opts
1550
+ ) do
1551
+ [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys
1552
+ owner_value = dump!(:delete, join_through, owner, owner_key, adapter)
1553
+ related_value = dump!(:delete, join_through, related, related_key, adapter)
1554
+
1555
+ query =
1556
+ join_through
1557
+ |> where([j], field(j, ^join_owner_key) == ^owner_value)
1558
+ |> where([j], field(j, ^join_related_key) == ^related_value)
1559
+ |> Ecto.Association.combine_assoc_query(join_where)
1560
+
1561
+ query = %{query | prefix: owner.__meta__.prefix}
1562
+ repo.delete_all(query, opts)
1563
+ {:ok, nil}
1564
+ end
1565
+
1566
+ def on_repo_change(
1567
+ %{field: field, join_through: join_through, join_keys: join_keys} = refl,
1568
+ %{repo: repo, data: owner} = parent_changeset,
1569
+ %{action: action} = changeset,
1570
+ adapter,
1571
+ opts
1572
+ ) do
1573
+ changeset = Ecto.Association.update_parent_prefix(changeset, owner)
1574
+
1575
+ case apply(repo, action, [changeset, opts]) do
1576
+ {:ok, related} ->
1577
+ [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys
1578
+
1579
+ if insert_join?(parent_changeset, changeset, field, related_key) do
1580
+ owner_value = dump!(:insert, join_through, owner, owner_key, adapter)
1581
+ related_value = dump!(:insert, join_through, related, related_key, adapter)
1582
+ data = %{join_owner_key => owner_value, join_related_key => related_value}
1583
+
1584
+ case insert_join(join_through, refl, parent_changeset, data, opts) do
1585
+ {:error, join_changeset} ->
1586
+ {:error,
1587
+ %{
1588
+ changeset
1589
+ | errors: join_changeset.errors ++ changeset.errors,
1590
+ valid?: join_changeset.valid? and changeset.valid?
1591
+ }}
1592
+
1593
+ _ ->
1594
+ {:ok, related}
1595
+ end
1596
+ else
1597
+ {:ok, related}
1598
+ end
1599
+
1600
+ {:error, changeset} ->
1601
+ {:error, changeset}
1602
+ end
1603
+ end
1604
+
1605
+ defp validate_join_through(name, nil) do
1606
+ raise ArgumentError,
1607
+ "many_to_many #{inspect(name)} associations require the :join_through option to be given"
1608
+ end
1609
+
1610
+ defp validate_join_through(_, join_through)
1611
+ when is_atom(join_through) or is_binary(join_through) do
1612
+ :ok
1613
+ end
1614
+
1615
+ defp validate_join_through(name, _join_through) do
1616
+ raise ArgumentError,
1617
+ "many_to_many #{inspect(name)} associations require the :join_through option to be " <>
1618
+ "an atom (representing a schema) or a string (representing a table)"
1619
+ end
1620
+
1621
+ defp insert_join?(%{action: :insert}, _, _field, _related_key), do: true
1622
+ defp insert_join?(_, %{action: :insert}, _field, _related_key), do: true
1623
+
1624
+ defp insert_join?(%{data: owner}, %{data: related}, field, related_key) do
1625
+ current_key = Map.fetch!(related, related_key)
1626
+
1627
+ not Enum.any?(Map.fetch!(owner, field), fn child ->
1628
+ Map.get(child, related_key) == current_key
1629
+ end)
1630
+ end
1631
+
1632
+ defp insert_join(join_through, _refl, %{repo: repo, data: owner}, data, opts)
1633
+ when is_binary(join_through) do
1634
+ opts = Keyword.put_new(opts, :prefix, owner.__meta__.prefix)
1635
+ repo.insert_all(join_through, [data], opts)
1636
+ end
1637
+
1638
+ defp insert_join(join_through, refl, parent_changeset, data, opts) when is_atom(join_through) do
1639
+ %{repo: repo, constraints: constraints, data: owner} = parent_changeset
1640
+
1641
+ changeset =
1642
+ join_through
1643
+ |> Ecto.Association.apply_defaults(refl.join_defaults, owner)
1644
+ |> Map.merge(data)
1645
+ |> Ecto.Changeset.change()
1646
+ |> Map.put(:constraints, constraints)
1647
+ |> put_new_prefix(owner.__meta__.prefix)
1648
+
1649
+ repo.insert(changeset, opts)
1650
+ end
1651
+
1652
+ defp put_new_prefix(%{data: %{__meta__: %{prefix: prefix}}} = changeset, prefix),
1653
+ do: changeset
1654
+
1655
+ defp put_new_prefix(%{data: %{__meta__: %{prefix: nil}}} = changeset, prefix),
1656
+ do: update_in(changeset.data, &Ecto.put_meta(&1, prefix: prefix))
1657
+
1658
+ defp put_new_prefix(changeset, _),
1659
+ do: changeset
1660
+
1661
+ defp field!(op, struct, field) do
1662
+ Map.get(struct, field) ||
1663
+ raise "could not #{op} join entry because `#{field}` is nil in #{inspect(struct)}"
1664
+ end
1665
+
1666
+ defp dump!(action, join_through, struct, field, adapter) when is_binary(join_through) do
1667
+ value = field!(action, struct, field)
1668
+ type = struct.__struct__.__schema__(:type, field)
1669
+
1670
+ case Ecto.Type.adapter_dump(adapter, type, value) do
1671
+ {:ok, value} ->
1672
+ value
1673
+
1674
+ :error ->
1675
+ raise Ecto.ChangeError,
1676
+ "value `#{inspect(value)}` for `#{inspect(struct.__struct__)}.#{field}` " <>
1677
+ "in `#{action}` does not match type #{Ecto.Type.format(type)}"
1678
+ end
1679
+ end
1680
+
1681
+ defp dump!(action, join_through, struct, field, _) when is_atom(join_through) do
1682
+ field!(action, struct, field)
1683
+ end
1684
+
1685
+ ## Relation callbacks
1686
+ @behaviour Ecto.Changeset.Relation
1687
+
1688
+ @impl true
1689
+ def build(%{related: related, queryable: queryable, defaults: defaults}, owner) do
1690
+ related
1691
+ |> Ecto.Association.apply_defaults(defaults, owner)
1692
+ |> Ecto.Association.merge_source(queryable)
1693
+ end
1694
+
1695
+ ## On delete callbacks
1696
+
1697
+ @doc false
1698
+ def delete_all(refl, parent, repo_name, opts) do
1699
+ %{join_through: join_through, join_keys: join_keys, owner: owner} = refl
1700
+ [{join_owner_key, owner_key}, {_, _}] = join_keys
1701
+
1702
+ if value = Map.get(parent, owner_key) do
1703
+ owner_type = owner.__schema__(:type, owner_key)
1704
+
1705
+ query =
1706
+ from j in join_through, where: field(j, ^join_owner_key) == type(^value, ^owner_type)
1707
+
1708
+ Ecto.Repo.Queryable.delete_all(repo_name, query, opts)
1709
+ end
1710
+ end
1711
+ end
deps/ecto/lib/ecto/changeset.ex ADDED
The diff for this file is too large to render. See raw diff
 
deps/ecto/lib/ecto/changeset/relation.ex ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Changeset.Relation do
2
+ @moduledoc false
3
+
4
+ require Logger
5
+ alias Ecto.Changeset
6
+ alias Ecto.Association.NotLoaded
7
+
8
+ @type t :: %{required(:__struct__) => atom(),
9
+ required(:cardinality) => :one | :many,
10
+ required(:on_replace) => :raise | :mark_as_invalid | atom,
11
+ required(:relationship) => :parent | :child,
12
+ required(:ordered) => boolean,
13
+ required(:owner) => atom,
14
+ required(:related) => atom,
15
+ required(:field) => atom,
16
+ optional(atom()) => any()}
17
+
18
+ @doc """
19
+ Builds the related data.
20
+ """
21
+ @callback build(t, owner :: Ecto.Schema.t) :: Ecto.Schema.t
22
+
23
+ @doc """
24
+ Returns empty container for relation.
25
+ """
26
+ def empty(%{cardinality: cardinality}), do: cardinality_to_empty(cardinality)
27
+
28
+ defp cardinality_to_empty(:one), do: nil
29
+ defp cardinality_to_empty(:many), do: []
30
+
31
+ @doc """
32
+ Checks if the container can be considered empty.
33
+ """
34
+ def empty?(%{cardinality: _}, %NotLoaded{}), do: true
35
+ def empty?(%{cardinality: :many}, []), do: true
36
+ def empty?(%{cardinality: :many}, changes), do: filter_empty(changes) == []
37
+ def empty?(%{cardinality: :one}, nil), do: true
38
+ def empty?(%{}, _), do: false
39
+
40
+ @doc """
41
+ Filter empty changes
42
+ """
43
+ def filter_empty(changes) do
44
+ Enum.filter(changes, fn
45
+ %Changeset{action: action} when action in [:replace, :delete] -> false
46
+ _ -> true
47
+ end)
48
+ end
49
+
50
+ @doc """
51
+ Applies related changeset changes
52
+ """
53
+ def apply_changes(%{cardinality: :one}, nil) do
54
+ nil
55
+ end
56
+
57
+ def apply_changes(%{cardinality: :one}, changeset) do
58
+ apply_changes(changeset)
59
+ end
60
+
61
+ def apply_changes(%{cardinality: :many}, changesets) do
62
+ for changeset <- changesets,
63
+ struct = apply_changes(changeset),
64
+ do: struct
65
+ end
66
+
67
+ defp apply_changes(%Changeset{action: :delete}), do: nil
68
+ defp apply_changes(%Changeset{action: :replace}), do: nil
69
+ defp apply_changes(changeset), do: Changeset.apply_changes(changeset)
70
+
71
+ @doc """
72
+ Loads the relation with the given struct.
73
+
74
+ Loading will fail if the association is not loaded but the struct is.
75
+ """
76
+ def load!(%{__meta__: %{state: :built}}, %NotLoaded{__cardinality__: cardinality}) do
77
+ cardinality_to_empty(cardinality)
78
+ end
79
+
80
+ def load!(struct, %NotLoaded{__field__: field}) do
81
+ raise "attempting to cast or change association `#{field}` " <>
82
+ "from `#{inspect struct.__struct__}` that was not loaded. Please preload your " <>
83
+ "associations before manipulating them through changesets"
84
+ end
85
+
86
+ def load!(_struct, loaded), do: loaded
87
+
88
+ @doc """
89
+ Casts related according to the `on_cast` function.
90
+ """
91
+ def cast(%{cardinality: :one} = relation, _owner, nil, current, _on_cast) do
92
+ case current && on_replace(relation, current) do
93
+ :error -> {:error, {"is invalid", [type: expected_type(relation)]}}
94
+ _ -> {:ok, nil, true}
95
+ end
96
+ end
97
+
98
+ def cast(%{cardinality: :one} = relation, owner, params, current, on_cast) when is_list(params) do
99
+ if Keyword.keyword?(params) do
100
+ cast(relation, owner, Map.new(params), current, on_cast)
101
+ else
102
+ {:error, {"is invalid", [type: expected_type(relation)]}}
103
+ end
104
+ end
105
+
106
+ def cast(%{related: mod} = relation, owner, params, current, on_cast) do
107
+ pks = mod.__schema__(:primary_key)
108
+ fun = &do_cast(relation, owner, &1, &2, &3, &4, on_cast)
109
+ data_pk = data_pk(pks)
110
+ param_pk = param_pk(mod, pks)
111
+
112
+ with :error <- cast_or_change(relation, params, current, data_pk, param_pk, fun) do
113
+ {:error, {"is invalid", [type: expected_type(relation)]}}
114
+ end
115
+ end
116
+
117
+ defp do_cast(meta, owner, params, struct, allowed_actions, idx, {module, fun, args})
118
+ when is_atom(module) and is_atom(fun) and is_list(args) do
119
+ IO.warn "passing a MFA to :with in cast_assoc/cast_embed is deprecated, please pass an anonymous function instead"
120
+
121
+ on_cast = fn changeset, attrs ->
122
+ apply(module, fun, [changeset, attrs | args])
123
+ end
124
+
125
+ do_cast(meta, owner, params, struct, allowed_actions, idx, on_cast)
126
+ end
127
+
128
+ defp do_cast(relation, owner, params, nil = _struct, allowed_actions, idx, on_cast) do
129
+ {:ok,
130
+ relation
131
+ |> apply_on_cast(on_cast, relation.__struct__.build(relation, owner), params, idx)
132
+ |> put_new_action(:insert)
133
+ |> check_action!(allowed_actions)}
134
+ end
135
+
136
+ defp do_cast(relation, _owner, nil = _params, current, _allowed_actions, _idx, _on_cast) do
137
+ on_replace(relation, current)
138
+ end
139
+
140
+ defp do_cast(relation, _owner, params, struct, allowed_actions, idx, on_cast) do
141
+ {:ok,
142
+ relation
143
+ |> apply_on_cast(on_cast, struct, params, idx)
144
+ |> put_new_action(:update)
145
+ |> check_action!(allowed_actions)}
146
+ end
147
+
148
+ defp apply_on_cast(%{cardinality: :many}, on_cast, struct, params, idx) when is_function(on_cast, 3) do
149
+ on_cast.(struct, params, idx)
150
+ end
151
+
152
+ defp apply_on_cast(%{cardinality: :one, field: field}, on_cast, _struct, _params, _idx) when is_function(on_cast, 3) do
153
+ raise ArgumentError, "invalid :with function for relation #{inspect(field)} " <>
154
+ "of cardinality one. Expected a function of arity 2"
155
+ end
156
+
157
+ defp apply_on_cast(_relation, on_cast, struct, params, _idx) when is_function(on_cast, 2) do
158
+ on_cast.(struct, params)
159
+ end
160
+
161
+ @doc """
162
+ Wraps related structs in changesets.
163
+ """
164
+ def change(%{cardinality: :one} = relation, nil, current) do
165
+ case current && on_replace(relation, current) do
166
+ :error -> {:error, {"is invalid", [type: expected_type(relation)]}}
167
+ _ -> {:ok, nil, true}
168
+ end
169
+ end
170
+
171
+ def change(%{related: mod} = relation, value, current) do
172
+ get_pks = data_pk(mod.__schema__(:primary_key))
173
+ with :error <- cast_or_change(relation, value, current, get_pks, get_pks,
174
+ &do_change(relation, &1, &2, &3, &4)) do
175
+ {:error, {"is invalid", [type: expected_type(relation)]}}
176
+ end
177
+ end
178
+
179
+ # This may be an insert or an update, get all fields.
180
+ defp do_change(relation, %{__struct__: _} = changeset_or_struct, nil, _allowed_actions, _idx) do
181
+ changeset = Changeset.change(changeset_or_struct)
182
+ {:ok,
183
+ changeset
184
+ |> assert_changeset_struct!(relation)
185
+ |> put_new_action(action_from_changeset(changeset, nil))}
186
+ end
187
+
188
+ defp do_change(relation, nil, current, _allowed_actions, _idx) do
189
+ on_replace(relation, current)
190
+ end
191
+
192
+ defp do_change(relation, %Changeset{} = changeset, _current, allowed_actions, _idx) do
193
+ {:ok,
194
+ changeset
195
+ |> assert_changeset_struct!(relation)
196
+ |> put_new_action(:update)
197
+ |> check_action!(allowed_actions)}
198
+ end
199
+
200
+ defp do_change(_relation, %{__struct__: _} = struct, _current, allowed_actions, _idx) do
201
+ {:ok,
202
+ struct
203
+ |> Ecto.Changeset.change
204
+ |> put_new_action(:update)
205
+ |> check_action!(allowed_actions)}
206
+ end
207
+
208
+ defp do_change(relation, changes, current, allowed_actions, idx)
209
+ when is_list(changes) or is_map(changes) do
210
+ changeset = Ecto.Changeset.change(current || relation.__struct__.build(relation, nil), changes)
211
+ changeset = put_new_action(changeset, action_from_changeset(changeset, current))
212
+ do_change(relation, changeset, current, allowed_actions, idx)
213
+ end
214
+
215
+ defp action_from_changeset(%{data: %{__meta__: %{state: state}}}, _current) do
216
+ case state do
217
+ :built -> :insert
218
+ :loaded -> :update
219
+ :deleted -> :delete
220
+ end
221
+ end
222
+
223
+ defp action_from_changeset(_, nil) do
224
+ :insert
225
+ end
226
+
227
+ defp action_from_changeset(_, _current) do
228
+ :update
229
+ end
230
+
231
+ defp assert_changeset_struct!(%{data: %{__struct__: mod}} = changeset, %{related: mod}) do
232
+ changeset
233
+ end
234
+ defp assert_changeset_struct!(%{data: data}, %{related: mod}) do
235
+ raise ArgumentError, "expected changeset data to be a #{mod} struct, got: #{inspect data}"
236
+ end
237
+
238
+ @doc """
239
+ Handles the changeset or struct when being replaced.
240
+ """
241
+ def on_replace(%{on_replace: :mark_as_invalid}, _changeset_or_struct) do
242
+ :error
243
+ end
244
+
245
+ def on_replace(%{on_replace: :raise, field: name, owner: owner}, _) do
246
+ raise """
247
+ you are attempting to change relation #{inspect name} of
248
+ #{inspect owner} but the `:on_replace` option of this relation
249
+ is set to `:raise`.
250
+
251
+ By default it is not possible to replace or delete embeds and
252
+ associations during `cast`. Therefore Ecto requires the parameters
253
+ given to `cast` to have IDs matching the data currently associated
254
+ to #{inspect owner}. Failing to do so results in this error message.
255
+
256
+ If you want to replace data or automatically delete any data
257
+ not sent to `cast`, please set the appropriate `:on_replace`
258
+ option when defining the relation. The docs for `Ecto.Changeset`
259
+ covers the supported options in the "Associations, embeds and on
260
+ replace" section.
261
+
262
+ However, if you don't want to allow data to be replaced or
263
+ deleted, only updated, make sure that:
264
+
265
+ * If you are attempting to update an existing entry, you
266
+ are including the entry primary key (ID) in the data.
267
+
268
+ * If you have a relationship with many children, all children
269
+ must be given on update.
270
+
271
+ """
272
+ end
273
+
274
+ def on_replace(_relation, changeset_or_struct) do
275
+ {:ok, Changeset.change(changeset_or_struct) |> put_new_action(:replace)}
276
+ end
277
+
278
+ defp raise_if_updating_with_struct!(%{field: name, owner: owner}, %{__struct__: _} = new) do
279
+ raise """
280
+ you have set that the relation #{inspect name} of #{inspect owner}
281
+ has `:on_replace` set to `:update` but you are giving it a struct/
282
+ changeset to put_assoc/put_change.
283
+
284
+ Since you have set `:on_replace` to `:update`, you are only allowed
285
+ to update the existing entry by giving updated fields as a map or
286
+ keyword list or set it to nil.
287
+
288
+ If you indeed want to replace the existing #{inspect name}, you have
289
+ to change the foreign key field directly.
290
+
291
+ Got: #{inspect new}
292
+ """
293
+ end
294
+
295
+ defp raise_if_updating_with_struct!(_, _) do
296
+ true
297
+ end
298
+
299
+ defp cast_or_change(%{cardinality: :one} = relation, value, current, current_pks_fun, new_pks_fun, fun)
300
+ when is_map(value) or is_list(value) or is_nil(value) do
301
+ single_change(relation, value, current_pks_fun, new_pks_fun, fun, current)
302
+ end
303
+
304
+ defp cast_or_change(%{cardinality: :many}, [], [], _current_pks, _new_pks, _fun) do
305
+ {:ok, [], true}
306
+ end
307
+
308
+ defp cast_or_change(%{cardinality: :many} = relation, value, current, current_pks_fun, new_pks_fun, fun)
309
+ when is_list(value) do
310
+ {current_pks, current_map} = process_current(current, current_pks_fun, relation)
311
+ %{unique: unique, ordered: ordered, related: mod} = relation
312
+ change_pks_fun = change_pk(mod.__schema__(:primary_key))
313
+ ordered = if ordered, do: current_pks, else: []
314
+ map_changes(value, new_pks_fun, change_pks_fun, fun, current_map, [], true, true, unique && %{}, 0, ordered)
315
+ end
316
+
317
+ defp cast_or_change(_, _, _, _, _, _), do: :error
318
+
319
+ # single change
320
+
321
+ defp single_change(_relation, nil, _current_pks_fun, _new_pks_fun, fun, current) do
322
+ single_change(nil, current, fun, [:update, :delete], false)
323
+ end
324
+
325
+ defp single_change(_relation, new, _current_pks_fun, _new_pks_fun, fun, nil) do
326
+ single_change(new, nil, fun, [:insert], false)
327
+ end
328
+
329
+ defp single_change(%{on_replace: on_replace} = relation, new, current_pks_fun, new_pks_fun, fun, current) do
330
+ pk_values = new_pks_fun.(new)
331
+
332
+ if (pk_values == current_pks_fun.(current) and pk_values != []) or
333
+ (on_replace == :update and raise_if_updating_with_struct!(relation, new)) do
334
+ single_change(new, current, fun, allowed_actions(pk_values), true)
335
+ else
336
+ case on_replace(relation, current) do
337
+ {:ok, _changeset} -> single_change(new, nil, fun, [:insert], false)
338
+ :error -> :error
339
+ end
340
+ end
341
+ end
342
+
343
+ defp single_change(new, current, fun, allowed_actions, skippable?) do
344
+ case fun.(new, current, allowed_actions, nil) do
345
+ {:ok, %{action: :ignore}} ->
346
+ :ignore
347
+ {:ok, changeset} ->
348
+ if skippable? and skip?(changeset) do
349
+ :ignore
350
+ else
351
+ {:ok, changeset, changeset.valid?}
352
+ end
353
+ :error ->
354
+ :error
355
+ end
356
+ end
357
+
358
+ # map changes
359
+
360
+ defp map_changes([changes | rest], new_pks, change_pks, fun, current, acc, valid?, skip?, unique, idx, ordered)
361
+ when is_map(changes) or is_list(changes) do
362
+ pk_values = new_pks.(changes)
363
+ {struct, current, allowed_actions} = pop_current(current, pk_values)
364
+
365
+ case fun.(changes, struct, allowed_actions, idx) do
366
+ {:ok, %{action: :ignore}} ->
367
+ ordered = pop_ordered(pk_values, ordered)
368
+ map_changes(rest, new_pks, change_pks, fun, current, acc, valid?, skip?, unique, idx + 1, ordered)
369
+ {:ok, changeset} ->
370
+ pk_values = change_pks.(changeset)
371
+ changeset = maybe_add_error_on_pk(changeset, pk_values, unique)
372
+ acc = [changeset | acc]
373
+ valid? = valid? and changeset.valid?
374
+ skip? = (struct != nil) and skip? and skip?(changeset)
375
+ unique = unique && Map.put(unique, pk_values, true)
376
+ ordered = pop_ordered(pk_values, ordered)
377
+ map_changes(rest, new_pks, change_pks, fun, current, acc, valid?, skip?, unique, idx + 1, ordered)
378
+ :error ->
379
+ :error
380
+ end
381
+ end
382
+
383
+ defp map_changes([], _new_pks, _change_pks, fun, current, acc, valid?, skip?, _unique, _idx, ordered) do
384
+ current_structs = Enum.map(current, &elem(&1, 1))
385
+ skip? = skip? and ordered == []
386
+ reduce_delete_changesets(current_structs, fun, Enum.reverse(acc), valid?, skip?)
387
+ end
388
+
389
+ defp map_changes(_params, _new_pks, _change_pks, _fun, _current, _acc, _valid?, _skip?, _unique, _idx, _ordered) do
390
+ :error
391
+ end
392
+
393
+ defp pop_ordered(pk_values, [pk_values | tail]), do: tail
394
+ defp pop_ordered(_pk_values, tail), do: tail
395
+
396
+ defp maybe_add_error_on_pk(%{data: %{__struct__: schema}} = changeset, pk_values, unique) do
397
+ if is_map(unique) and not missing_pks?(pk_values) and Map.has_key?(unique, pk_values) do
398
+ Enum.reduce(schema.__schema__(:primary_key), changeset, fn pk, acc ->
399
+ Changeset.add_error(acc, pk, "has already been taken")
400
+ end)
401
+ else
402
+ changeset
403
+ end
404
+ end
405
+
406
+ defp missing_pks?(pk_values) do
407
+ pk_values == [] or Enum.any?(pk_values, &is_nil/1)
408
+ end
409
+
410
+ defp allowed_actions(pk_values) do
411
+ if Enum.all?(pk_values, &is_nil/1) do
412
+ [:insert, :update, :delete]
413
+ else
414
+ [:update, :delete]
415
+ end
416
+ end
417
+
418
+ defp reduce_delete_changesets([struct | rest], fun, acc, valid?, _skip?) do
419
+ case fun.(nil, struct, [:update, :delete], nil) do
420
+ {:ok, changeset} ->
421
+ valid? = valid? and changeset.valid?
422
+ reduce_delete_changesets(rest, fun, [changeset | acc], valid?, false)
423
+
424
+ :error ->
425
+ :error
426
+ end
427
+ end
428
+
429
+ defp reduce_delete_changesets([], _fun, _acc, _valid?, true), do: :ignore
430
+ defp reduce_delete_changesets([], _fun, acc, valid?, false), do: {:ok, acc, valid?}
431
+
432
+ # helpers
433
+
434
+ defp check_action!(changeset, allowed_actions) do
435
+ action = changeset.action
436
+
437
+ cond do
438
+ action in allowed_actions ->
439
+ changeset
440
+
441
+ action == :ignore ->
442
+ changeset
443
+
444
+ action == :insert ->
445
+ raise "cannot insert related #{inspect changeset.data} " <>
446
+ "because it is already associated with the given struct"
447
+
448
+ action == :replace ->
449
+ raise "cannot replace related #{inspect changeset.data}. " <>
450
+ "This typically happens when you are calling put_assoc/put_embed " <>
451
+ "with the results of a previous put_assoc/put_embed/cast_assoc/cast_embed " <>
452
+ "operation, which is not supported. You must call such operations only once " <>
453
+ "per embed/assoc, in order for Ecto to track changes efficiently"
454
+
455
+ true ->
456
+ raise "cannot #{action} related #{inspect changeset.data} because " <>
457
+ "it already exists and it is not currently associated with the " <>
458
+ "given struct. Ecto forbids casting existing records through " <>
459
+ "the association field for security reasons. Instead, set " <>
460
+ "the foreign key value accordingly"
461
+ end
462
+ end
463
+
464
+ defp process_current(nil, _get_pks, _relation),
465
+ do: {[], %{}}
466
+
467
+ defp process_current(current, get_pks, relation) do
468
+ {pks, {map, counter}} =
469
+ Enum.map_reduce(current, {%{}, 0}, fn struct, {acc, counter} ->
470
+ pks = get_pks.(struct)
471
+ key = if pks == [], do: map_size(acc), else: pks
472
+ {pks, {Map.put(acc, key, struct), counter + 1}}
473
+ end)
474
+
475
+ if map_size(map) != counter do
476
+ Logger.warning """
477
+ found duplicate primary keys for association/embed `#{inspect(relation.field)}` \
478
+ in `#{inspect(relation.owner)}`. In case of duplicate IDs, only the last entry \
479
+ with the same ID will be kept. Make sure that all entries in `#{inspect(relation.field)}` \
480
+ have an ID and the IDs are unique between them
481
+ """
482
+ end
483
+
484
+ {pks, map}
485
+ end
486
+
487
+ defp pop_current(current, pk_values) do
488
+ case Map.pop(current, pk_values) do
489
+ {nil, current} -> {nil, current, [:insert]}
490
+ {struct, current} -> {struct, current, allowed_actions(pk_values)}
491
+ end
492
+ end
493
+
494
+ defp data_pk(pks) do
495
+ fn
496
+ %Changeset{data: data} -> Enum.map(pks, &Map.get(data, &1))
497
+ map when is_map(map) -> Enum.map(pks, &Map.get(map, &1))
498
+ list when is_list(list) -> Enum.map(pks, &Keyword.get(list, &1))
499
+ end
500
+ end
501
+
502
+ defp param_pk(mod, pks) do
503
+ pks = Enum.map(pks, &{&1, Atom.to_string(&1), mod.__schema__(:type, &1)})
504
+ fn params ->
505
+ Enum.map pks, fn {atom_key, string_key, type} ->
506
+ original = Map.get(params, string_key) || Map.get(params, atom_key)
507
+ case Ecto.Type.cast(type, original) do
508
+ {:ok, value} -> value
509
+ _ -> original
510
+ end
511
+ end
512
+ end
513
+ end
514
+
515
+ defp change_pk(pks) do
516
+ fn %Changeset{} = cs ->
517
+ Enum.map(pks, fn pk ->
518
+ case cs.changes do
519
+ %{^pk => pk_value} -> pk_value
520
+ _ -> Map.get(cs.data, pk)
521
+ end
522
+ end)
523
+ end
524
+ end
525
+
526
+ defp put_new_action(%{action: action} = changeset, new_action) when is_nil(action),
527
+ do: Map.put(changeset, :action, new_action)
528
+ defp put_new_action(changeset, _new_action),
529
+ do: changeset
530
+
531
+ defp skip?(%{valid?: true, changes: empty, action: :update}) when empty == %{},
532
+ do: true
533
+ defp skip?(_changeset),
534
+ do: false
535
+
536
+ defp expected_type(%{cardinality: :one}), do: :map
537
+ defp expected_type(%{cardinality: :many}), do: {:array, :map}
538
+
539
+ ## Surface changes on insert
540
+
541
+ def surface_changes(%{changes: changes, types: types} = changeset, struct, fields) do
542
+ {changes, errors} =
543
+ Enum.reduce fields, {changes, []}, fn field, {changes, errors} ->
544
+ case {struct, changes, types} do
545
+ # User has explicitly changed it
546
+ {_, %{^field => _}, _} ->
547
+ {changes, errors}
548
+
549
+ # Handle associations specially
550
+ {_, _, %{^field => {tag, embed_or_assoc}}} when tag in [:assoc, :embed] ->
551
+ # This is partly reimplementing the logic behind put_relation
552
+ # in Ecto.Changeset but we need to do it in a way where we have
553
+ # control over the current value.
554
+ value = not_loaded_to_empty(Map.get(struct, field))
555
+ empty = empty(embed_or_assoc)
556
+ case change(embed_or_assoc, value, empty) do
557
+ {:ok, change, _} when change != empty ->
558
+ {Map.put(changes, field, change), errors}
559
+ {:error, error} ->
560
+ {changes, [{field, error}]}
561
+ _ -> # :ignore or ok with change == empty
562
+ {changes, errors}
563
+ end
564
+
565
+ # Struct has a non nil value
566
+ {%{^field => value}, _, %{^field => _}} when value != nil ->
567
+ {Map.put(changes, field, value), errors}
568
+
569
+ {_, _, _} ->
570
+ {changes, errors}
571
+ end
572
+ end
573
+
574
+ case errors do
575
+ [] -> %{changeset | changes: changes}
576
+ _ -> %{changeset | errors: errors ++ changeset.errors, valid?: false, changes: changes}
577
+ end
578
+ end
579
+
580
+ defp not_loaded_to_empty(%NotLoaded{__cardinality__: cardinality}),
581
+ do: cardinality_to_empty(cardinality)
582
+
583
+ defp not_loaded_to_empty(loaded), do: loaded
584
+ end
deps/ecto/lib/ecto/embedded.ex ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Embedded do
2
+ @moduledoc """
3
+ The embedding struct for `embeds_one` and `embeds_many`.
4
+
5
+ Its fields are:
6
+
7
+ * `cardinality` - The association cardinality
8
+ * `field` - The name of the association field on the schema
9
+ * `owner` - The schema where the association was defined
10
+ * `related` - The schema that is embedded
11
+ * `on_cast` - Function name to call by default when casting embeds
12
+ * `on_replace` - The action taken on associations when schema is replaced
13
+
14
+ """
15
+ alias __MODULE__
16
+ alias Ecto.Changeset
17
+ alias Ecto.Changeset.Relation
18
+
19
+ use Ecto.ParameterizedType
20
+
21
+ @behaviour Relation
22
+ @on_replace_opts [:raise, :mark_as_invalid, :delete]
23
+ @embeds_one_on_replace_opts @on_replace_opts ++ [:update]
24
+
25
+ defstruct [
26
+ :cardinality,
27
+ :field,
28
+ :owner,
29
+ :related,
30
+ :on_cast,
31
+ on_replace: :raise,
32
+ unique: true,
33
+ ordered: true
34
+ ]
35
+
36
+ ## Parameterized API
37
+
38
+ # We treat even embed_many as maps, as that's often the
39
+ # most efficient format to encode them in the database.
40
+ @impl Ecto.ParameterizedType
41
+ def type(_), do: {:map, :any}
42
+
43
+ @impl Ecto.ParameterizedType
44
+ def init(opts) do
45
+ opts = Keyword.put_new(opts, :on_replace, :raise)
46
+ cardinality = Keyword.fetch!(opts, :cardinality)
47
+
48
+ on_replace_opts =
49
+ if cardinality == :one, do: @embeds_one_on_replace_opts, else: @on_replace_opts
50
+
51
+ unless opts[:on_replace] in on_replace_opts do
52
+ raise ArgumentError,
53
+ "invalid `:on_replace` option for #{inspect(Keyword.fetch!(opts, :field))}. " <>
54
+ "The only valid options are: " <>
55
+ Enum.map_join(on_replace_opts, ", ", &"`#{inspect(&1)}`")
56
+ end
57
+
58
+ struct(%Embedded{}, opts)
59
+ end
60
+
61
+ @impl Ecto.ParameterizedType
62
+ def load(nil, _fun, %{cardinality: :one}), do: {:ok, nil}
63
+
64
+ def load(value, fun, %{cardinality: :one, related: schema, field: field}) when is_map(value) do
65
+ {:ok, load_field(field, schema, value, fun)}
66
+ end
67
+
68
+ def load(nil, _fun, %{cardinality: :many}), do: {:ok, []}
69
+
70
+ def load(value, fun, %{cardinality: :many, related: schema, field: field})
71
+ when is_list(value) do
72
+ {:ok, Enum.map(value, &load_field(field, schema, &1, fun))}
73
+ end
74
+
75
+ def load(_value, _fun, _embed) do
76
+ :error
77
+ end
78
+
79
+ defp load_field(_field, schema, value, loader) when is_map(value) do
80
+ Ecto.Schema.Loader.unsafe_load(schema, value, loader)
81
+ end
82
+
83
+ defp load_field(field, _schema, value, _fun) do
84
+ raise ArgumentError, "cannot load embed `#{field}`, expected a map but got: #{inspect(value)}"
85
+ end
86
+
87
+ @impl Ecto.ParameterizedType
88
+ def dump(nil, _, _), do: {:ok, nil}
89
+
90
+ def dump(value, fun, %{cardinality: :one, related: schema, field: field}) when is_map(value) do
91
+ {:ok, dump_field(field, schema, value, schema.__schema__(:dump), fun, _one_embed? = true)}
92
+ end
93
+
94
+ def dump(value, fun, %{cardinality: :many, related: schema, field: field})
95
+ when is_list(value) do
96
+ types = schema.__schema__(:dump)
97
+ {:ok, Enum.map(value, &dump_field(field, schema, &1, types, fun, _one_embed? = false))}
98
+ end
99
+
100
+ def dump(_value, _fun, _embed) do
101
+ :error
102
+ end
103
+
104
+ defp dump_field(_field, schema, %{__struct__: schema} = struct, types, dumper, _one_embed?) do
105
+ Ecto.Schema.Loader.safe_dump(struct, types, dumper)
106
+ end
107
+
108
+ defp dump_field(field, schema, value, _types, _dumper, one_embed?) do
109
+ one_or_many =
110
+ if one_embed?,
111
+ do: "a struct #{inspect(schema)} value",
112
+ else: "a list of #{inspect(schema)} struct values"
113
+
114
+ raise ArgumentError,
115
+ "cannot dump embed `#{field}`, expected #{one_or_many} but got: #{inspect(value)}"
116
+ end
117
+
118
+ @impl Ecto.ParameterizedType
119
+ def cast(nil, %{cardinality: :one}), do: {:ok, nil}
120
+
121
+ def cast(%{__struct__: schema} = struct, %{cardinality: :one, related: schema}) do
122
+ {:ok, struct}
123
+ end
124
+
125
+ def cast(nil, %{cardinality: :many}), do: {:ok, []}
126
+
127
+ def cast(value, %{cardinality: :many, related: schema}) when is_list(value) do
128
+ if Enum.all?(value, &Kernel.match?(%{__struct__: ^schema}, &1)) do
129
+ {:ok, value}
130
+ else
131
+ :error
132
+ end
133
+ end
134
+
135
+ def cast(_value, _embed) do
136
+ :error
137
+ end
138
+
139
+ @impl Ecto.ParameterizedType
140
+ def embed_as(_, _), do: :dump
141
+
142
+ ## End of parameterized API
143
+
144
+ # Callback invoked by repository to prepare embeds.
145
+ #
146
+ # It replaces the changesets for embeds inside changes
147
+ # by actual structs so it can be dumped by adapters and
148
+ # loaded into the schema struct afterwards.
149
+ @doc false
150
+ def prepare(changeset, embeds, adapter, repo_action) do
151
+ %{changes: changes, types: types, repo: repo} = changeset
152
+ prepare(Map.take(changes, embeds), types, adapter, repo, repo_action)
153
+ end
154
+
155
+ defp prepare(embeds, _types, _adapter, _repo, _repo_action) when embeds == %{} do
156
+ embeds
157
+ end
158
+
159
+ defp prepare(embeds, types, adapter, repo, repo_action) do
160
+ Enum.reduce(embeds, embeds, fn {name, changeset_or_changesets}, acc ->
161
+ {:embed, embed} = Map.get(types, name)
162
+ Map.put(acc, name, prepare_each(embed, changeset_or_changesets, adapter, repo, repo_action))
163
+ end)
164
+ end
165
+
166
+ defp prepare_each(%{cardinality: :one}, nil, _adapter, _repo, _repo_action) do
167
+ nil
168
+ end
169
+
170
+ defp prepare_each(%{cardinality: :one} = embed, changeset, adapter, repo, repo_action) do
171
+ action = normalize_action(changeset.action, repo_action, embed)
172
+ changeset = run_prepare(changeset, repo)
173
+ to_struct(changeset, action, embed, adapter)
174
+ end
175
+
176
+ defp prepare_each(%{cardinality: :many} = embed, changesets, adapter, repo, repo_action) do
177
+ for changeset <- changesets,
178
+ action = normalize_action(changeset.action, repo_action, embed),
179
+ changeset = run_prepare(changeset, repo),
180
+ prepared = to_struct(changeset, action, embed, adapter),
181
+ do: prepared
182
+ end
183
+
184
+ defp to_struct(%Changeset{valid?: false}, _action, %{related: schema}, _adapter) do
185
+ raise ArgumentError,
186
+ "changeset for embedded #{inspect(schema)} is invalid, " <>
187
+ "but the parent changeset was not marked as invalid"
188
+ end
189
+
190
+ defp to_struct(%Changeset{data: %{__struct__: actual}}, _action, %{related: expected}, _adapter)
191
+ when actual != expected do
192
+ raise ArgumentError,
193
+ "expected changeset for embedded schema `#{inspect(expected)}`, " <>
194
+ "got: #{inspect(actual)}"
195
+ end
196
+
197
+ defp to_struct(%Changeset{changes: changes, data: schema}, :update, _embed, _adapter)
198
+ when changes == %{} do
199
+ schema
200
+ end
201
+
202
+ defp to_struct(%Changeset{}, :delete, _embed, _adapter) do
203
+ nil
204
+ end
205
+
206
+ defp to_struct(%Changeset{data: data} = changeset, action, %{related: schema}, adapter) do
207
+ %{data: struct, changes: changes} =
208
+ changeset =
209
+ maybe_surface_changes(changeset, data, schema, action)
210
+
211
+ embeds = prepare(changeset, schema.__schema__(:embeds), adapter, action)
212
+
213
+ changes
214
+ |> Map.merge(embeds)
215
+ |> autogenerate_id(struct, action, schema, adapter)
216
+ |> autogenerate(action, schema)
217
+ |> apply_embeds(struct)
218
+ end
219
+
220
+ defp maybe_surface_changes(changeset, data, schema, :insert) do
221
+ Relation.surface_changes(changeset, data, schema.__schema__(:fields))
222
+ end
223
+
224
+ defp maybe_surface_changes(changeset, _data, _schema, _action) do
225
+ changeset
226
+ end
227
+
228
+ defp run_prepare(changeset, repo) do
229
+ changeset = %{changeset | repo: repo}
230
+
231
+ Enum.reduce(Enum.reverse(changeset.prepare), changeset, fn fun, acc ->
232
+ case fun.(acc) do
233
+ %Ecto.Changeset{} = acc ->
234
+ acc
235
+
236
+ other ->
237
+ raise "expected function #{inspect(fun)} given to Ecto.Changeset.prepare_changes/2 " <>
238
+ "to return an Ecto.Changeset, got: `#{inspect(other)}`"
239
+ end
240
+ end)
241
+ end
242
+
243
+ defp apply_embeds(changes, struct) do
244
+ struct(struct, changes)
245
+ end
246
+
247
+ defp normalize_action(:replace, _, %{on_replace: :delete}), do: :delete
248
+ defp normalize_action(:update, :insert, _), do: :insert
249
+ defp normalize_action(action, _, _), do: action
250
+
251
+ defp autogenerate_id(changes, _struct, :insert, schema, adapter) do
252
+ case schema.__schema__(:autogenerate_id) do
253
+ {key, _source, :binary_id} ->
254
+ Map.put_new_lazy(changes, key, fn -> adapter.autogenerate(:embed_id) end)
255
+
256
+ {_key, _source, :id} ->
257
+ raise ArgumentError,
258
+ "embedded schema `#{inspect(schema)}` cannot autogenerate `:id` primary keys, " <>
259
+ "those are typically used for auto-incrementing constraints. " <>
260
+ "Maybe you meant to use `:binary_id` instead?"
261
+
262
+ nil ->
263
+ changes
264
+ end
265
+ end
266
+
267
+ defp autogenerate_id(changes, struct, :update, _schema, _adapter) do
268
+ for {_, nil} <- Ecto.primary_key(struct) do
269
+ raise Ecto.NoPrimaryKeyValueError, struct: struct
270
+ end
271
+
272
+ changes
273
+ end
274
+
275
+ defp autogenerate(changes, action, schema) do
276
+ autogen_fields = action |> action_to_auto() |> schema.__schema__()
277
+
278
+ Enum.reduce(autogen_fields, changes, fn {fields, {mod, fun, args}}, acc ->
279
+ case Enum.reject(fields, &Map.has_key?(changes, &1)) do
280
+ [] ->
281
+ acc
282
+
283
+ fields ->
284
+ generated = apply(mod, fun, args)
285
+ Enum.reduce(fields, acc, &Map.put(&2, &1, generated))
286
+ end
287
+ end)
288
+ end
289
+
290
+ defp action_to_auto(:insert), do: :autogenerate
291
+ defp action_to_auto(:update), do: :autoupdate
292
+
293
+ @impl Relation
294
+ def build(%Embedded{related: related}, _owner) do
295
+ related.__struct__()
296
+ end
297
+
298
+ def preload_info(_embed) do
299
+ :embed
300
+ end
301
+ end
deps/ecto/lib/ecto/enum.ex ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Enum do
2
+ @moduledoc """
3
+ A custom type that maps atoms to strings or integers.
4
+
5
+ `Ecto.Enum` must be used whenever you want to keep atom values in a field.
6
+ Since atoms cannot be persisted to the database, `Ecto.Enum` converts them
7
+ to strings or integers when writing to the database and converts them back
8
+ to atoms when loading data. It can be used in your schemas as follows:
9
+
10
+ # Stored as strings
11
+ field :status, Ecto.Enum, values: [:foo, :bar, :baz]
12
+
13
+ or
14
+
15
+ # Stored as integers
16
+ field :status, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]
17
+
18
+ Therefore, the type to be used in your migrations for enum fields depends
19
+ on the choice above. For the cases above, one would do, respectively:
20
+
21
+ add :status, :string
22
+
23
+ or
24
+
25
+ add :status, :integer
26
+
27
+ Some databases also support enum types, which you could use in combination
28
+ with the above.
29
+
30
+ Composite types, such as `:array`, are also supported which allow selecting
31
+ multiple values per record:
32
+
33
+ field :roles, {:array, Ecto.Enum}, values: [:author, :editor, :admin]
34
+
35
+ Overall, `:values` must be a list of atoms or a keyword list. Values will be
36
+ cast to atoms safely and only if the atom exists in the list (otherwise an
37
+ error will be raised). Attempting to load any string/integer not represented
38
+ by an atom in the list will be invalid.
39
+
40
+ The helper function `mappings/2` returns the mappings for a given schema and
41
+ field, which can be used in places like form drop-downs. See `mappings/2` for
42
+ examples.
43
+
44
+ If you want the values only, you can use `values/2`, and if you want
45
+ the "dump-able" values only, you can use `dump_values/2`.
46
+
47
+ ## Embeds
48
+
49
+ `Ecto.Enum` allows to customize how fields are dumped within embeds through the
50
+ `:embed_as` option. Two alternatives are supported: `:values`, which will save
51
+ the enum keys (and not their respective mapping), and `:dumped`, which will save
52
+ the dumped value. The default is `:values`. For example, assuming the following
53
+ schema:
54
+
55
+ defmodule EnumSchema do
56
+ use Ecto.Schema
57
+
58
+ schema "my_schema" do
59
+ embeds_one :embed, Embed do
60
+ field :embed_as_values, Ecto.Enum, values: [foo: 1, bar: 2], embed_as: :values
61
+ field :embed_as_dump, Ecto.Enum, values: [foo: 1, bar: 2], embed_as: :dumped
62
+ end
63
+ end
64
+ end
65
+
66
+ The `:embed_as_values` field value will save `:foo` or `:bar`, while the
67
+ `:embed_as_dump` field value will save `1` or `2`.
68
+ """
69
+
70
+ use Ecto.ParameterizedType
71
+
72
+ @impl true
73
+ def type(params), do: params.type
74
+
75
+ @impl true
76
+ def init(opts) do
77
+ values = opts[:values]
78
+
79
+ {type, mappings} =
80
+ cond do
81
+ is_list(values) and Enum.all?(values, &is_atom/1) ->
82
+ validate_unique!(values)
83
+ {:string, Enum.map(values, fn atom -> {atom, to_string(atom)} end)}
84
+
85
+ type = Keyword.keyword?(values) and infer_type(Keyword.values(values)) ->
86
+ validate_unique!(Keyword.keys(values))
87
+ validate_unique!(Keyword.values(values))
88
+ {type, values}
89
+
90
+ true ->
91
+ raise ArgumentError, """
92
+ Ecto.Enum types must have a values option specified as a list of atoms or a
93
+ keyword list with a mapping from atoms to either integer or string values.
94
+
95
+ For example:
96
+
97
+ field :my_field, Ecto.Enum, values: [:foo, :bar]
98
+
99
+ or
100
+
101
+ field :my_field, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]
102
+ """
103
+ end
104
+
105
+ on_load = Map.new(mappings, fn {key, val} -> {val, key} end)
106
+ on_dump = Map.new(mappings)
107
+ on_cast = Map.new(mappings, fn {key, _} -> {Atom.to_string(key), key} end)
108
+
109
+ embed_as =
110
+ case Keyword.get(opts, :embed_as, :values) do
111
+ :values ->
112
+ :self
113
+
114
+ :dumped ->
115
+ :dump
116
+
117
+ other ->
118
+ raise ArgumentError, """
119
+ the `:embed_as` option for `Ecto.Enum` accepts either `:values` or `:dumped`,
120
+ received: `#{inspect(other)}`
121
+ """
122
+ end
123
+
124
+ %{
125
+ on_load: on_load,
126
+ on_dump: on_dump,
127
+ on_cast: on_cast,
128
+ mappings: mappings,
129
+ embed_as: embed_as,
130
+ type: type
131
+ }
132
+ end
133
+
134
+ defp validate_unique!(values) do
135
+ if length(Enum.uniq(values)) != length(values) do
136
+ raise ArgumentError, """
137
+ Ecto.Enum type values must be unique.
138
+
139
+ For example:
140
+
141
+ field :my_field, Ecto.Enum, values: [:foo, :bar, :foo]
142
+
143
+ is invalid, while
144
+
145
+ field :my_field, Ecto.Enum, values: [:foo, :bar, :baz]
146
+
147
+ is valid
148
+ """
149
+ end
150
+ end
151
+
152
+ defp infer_type(values) do
153
+ cond do
154
+ Enum.all?(values, &is_integer/1) -> :integer
155
+ Enum.all?(values, &is_binary/1) -> :string
156
+ true -> nil
157
+ end
158
+ end
159
+
160
+ @impl true
161
+ def cast(nil, _params), do: {:ok, nil}
162
+
163
+ def cast(data, params) do
164
+ case params do
165
+ %{on_load: %{^data => as_atom}} ->
166
+ {:ok, as_atom}
167
+
168
+ %{on_dump: %{^data => _}} ->
169
+ {:ok, data}
170
+
171
+ %{on_cast: %{^data => as_atom}} ->
172
+ {:ok, as_atom}
173
+
174
+ params ->
175
+ {:error, validation: :inclusion, enum: Map.keys(params.on_cast)}
176
+ end
177
+ end
178
+
179
+ @impl true
180
+ def load(nil, _, _), do: {:ok, nil}
181
+
182
+ def load(data, _loader, %{on_load: on_load}) do
183
+ case on_load do
184
+ %{^data => as_atom} -> {:ok, as_atom}
185
+ _ -> :error
186
+ end
187
+ end
188
+
189
+ @impl true
190
+ def dump(nil, _, _), do: {:ok, nil}
191
+
192
+ def dump(data, _dumper, %{on_dump: on_dump}) do
193
+ case on_dump do
194
+ %{^data => as_string} -> {:ok, as_string}
195
+ _ -> :error
196
+ end
197
+ end
198
+
199
+ @impl true
200
+ def equal?(a, b, _params), do: a == b
201
+
202
+ @impl true
203
+ def embed_as(_, %{embed_as: embed_as}), do: embed_as
204
+
205
+ @impl true
206
+ def format(%{mappings: mappings}) do
207
+ "#Ecto.Enum<values: #{inspect(Keyword.keys(mappings))}>"
208
+ end
209
+
210
+ @doc """
211
+ Returns the possible values for a given schema or types map and field.
212
+
213
+ These values are the atoms that represent the different possible values
214
+ of the field.
215
+
216
+ ## Examples
217
+
218
+ Assuming this schema:
219
+
220
+ defmodule MySchema do
221
+ use Ecto.Schema
222
+
223
+ schema "my_schema" do
224
+ field :my_string_enum, Ecto.Enum, values: [:foo, :bar, :baz]
225
+ field :my_integer_enum, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]
226
+ end
227
+ end
228
+
229
+ Then:
230
+
231
+ Ecto.Enum.values(MySchema, :my_string_enum)
232
+ #=> [:foo, :bar, :baz]
233
+
234
+ Ecto.Enum.values(MySchema, :my_integer_enum)
235
+ #=> [:foo, :bar, :baz]
236
+
237
+ """
238
+ @spec values(module | map, atom) :: [atom()]
239
+ def values(schema_or_types, field) do
240
+ schema_or_types
241
+ |> mappings(field)
242
+ |> Keyword.keys()
243
+ end
244
+
245
+ @doc """
246
+ Returns the possible dump values for a given schema or types map and field
247
+
248
+ "Dump values" are the values that can be dumped in the database. For enums stored
249
+ as strings, these are the strings that will be dumped in the database. For enums
250
+ stored as integers, these are the integers that will be dumped in the database.
251
+
252
+ ## Examples
253
+
254
+ Assuming this schema:
255
+
256
+ defmodule MySchema do
257
+ use Ecto.Schema
258
+
259
+ schema "my_schema" do
260
+ field :my_string_enum, Ecto.Enum, values: [:foo, :bar, :baz]
261
+ field :my_integer_enum, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]
262
+ end
263
+ end
264
+
265
+ Then:
266
+
267
+ Ecto.Enum.dump_values(MySchema, :my_string_enum)
268
+ #=> ["foo", "bar", "baz"]
269
+
270
+ Ecto.Enum.dump_values(MySchema, :my_integer_enum)
271
+ #=> [1, 2, 5]
272
+
273
+ `schema_or_types` can also be a types map. See `mappings/2` for more information.
274
+ """
275
+ @spec dump_values(module | map, atom) :: [String.t()] | [integer()]
276
+ def dump_values(schema_or_types, field) do
277
+ schema_or_types
278
+ |> mappings(field)
279
+ |> Keyword.values()
280
+ end
281
+
282
+ @doc """
283
+ Returns the mappings between values and dumped values.
284
+
285
+ ## Examples
286
+
287
+ Assuming this schema:
288
+
289
+ defmodule MySchema do
290
+ use Ecto.Schema
291
+
292
+ schema "my_schema" do
293
+ field :my_string_enum, Ecto.Enum, values: [:foo, :bar, :baz]
294
+ field :my_integer_enum, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]
295
+ end
296
+ end
297
+
298
+ Here are some examples of using `mappings/2` with it:
299
+
300
+ Ecto.Enum.mappings(MySchema, :my_string_enum)
301
+ #=> [foo: "foo", bar: "bar", baz: "baz"]
302
+
303
+ Ecto.Enum.mappings(MySchema, :my_integer_enum)
304
+ #=> [foo: 1, bar: 2, baz: 5]
305
+
306
+ Examples of calling `mappings/2` with a types map:
307
+
308
+ schemaless_types = %{
309
+ my_enum: Ecto.ParameterizedType.init(Ecto.Enum, values: [:foo, :bar, :baz]),
310
+ my_integer_enum: Ecto.ParameterizedType.init(Ecto.Enum, values: [foo: 1, bar: 2, baz: 5])
311
+ }
312
+
313
+ Ecto.Enum.mappings(schemaless_types, :my_enum)
314
+ #=> [foo: "foo", bar: "bar", baz: "baz"]
315
+ Ecto.Enum.mappings(schemaless_types, :my_integer_enum)
316
+ #=> [foo: 1, bar: 2, baz: 5]
317
+
318
+ """
319
+ @spec mappings(module | map, atom) :: keyword(String.t() | integer())
320
+ def mappings(schema_or_types, field)
321
+
322
+ def mappings(types, field) when is_map(types) do
323
+ case types do
324
+ %{^field => {:parameterized, {Ecto.Enum, %{mappings: mappings}}}} -> mappings
325
+ %{^field => {_, {:parameterized, {Ecto.Enum, %{mappings: mappings}}}}} -> mappings
326
+ %{^field => _} -> raise ArgumentError, "#{field} is not an Ecto.Enum field"
327
+ %{} -> raise ArgumentError, "#{field} does not exist"
328
+ end
329
+ end
330
+
331
+ def mappings(schema, field) when is_atom(schema) do
332
+ try do
333
+ schema.__changeset__()
334
+ rescue
335
+ _ in UndefinedFunctionError ->
336
+ raise ArgumentError, "#{inspect(schema)} is not an Ecto schema or types map"
337
+ else
338
+ %{} = types -> mappings(types, field)
339
+ end
340
+ end
341
+ end
deps/ecto/lib/ecto/exceptions.ex ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Query.CompileError do
2
+ @moduledoc """
3
+ Raised at compilation time when the query cannot be compiled.
4
+ """
5
+ defexception [:message]
6
+ end
7
+
8
+ defmodule Ecto.Query.CastError do
9
+ @moduledoc """
10
+ Raised at runtime when a value cannot be cast.
11
+ """
12
+ defexception [:type, :value, :message]
13
+
14
+ def exception(opts) do
15
+ value = Keyword.fetch!(opts, :value)
16
+ type = Keyword.fetch!(opts, :type)
17
+ msg = Keyword.fetch!(opts, :message)
18
+ %__MODULE__{value: value, type: type, message: msg}
19
+ end
20
+ end
21
+
22
+ defmodule Ecto.QueryError do
23
+ @moduledoc """
24
+ Raised at runtime when the query is invalid.
25
+ """
26
+ defexception [:message]
27
+
28
+ def exception(opts) do
29
+ message = Keyword.fetch!(opts, :message)
30
+ query = Keyword.fetch!(opts, :query)
31
+ hint = Keyword.get(opts, :hint)
32
+
33
+ message = """
34
+ #{message} in query:
35
+
36
+ #{Inspect.Ecto.Query.to_string(query)}
37
+ """
38
+
39
+ file = opts[:file]
40
+ line = opts[:line]
41
+
42
+ message =
43
+ if file && line do
44
+ relative = Path.relative_to_cwd(file)
45
+ Exception.format_file_line(relative, line) <> " " <> message
46
+ else
47
+ message
48
+ end
49
+
50
+ message =
51
+ if hint do
52
+ message <> "\n" <> hint <> "\n"
53
+ else
54
+ message
55
+ end
56
+
57
+ %__MODULE__{message: message}
58
+ end
59
+ end
60
+
61
+ defmodule Ecto.SubQueryError do
62
+ @moduledoc """
63
+ Raised at runtime when a subquery is invalid.
64
+ """
65
+ defexception [:message, :exception]
66
+
67
+ def exception(opts) do
68
+ exception = Keyword.fetch!(opts, :exception)
69
+ query = Keyword.fetch!(opts, :query)
70
+
71
+ message = """
72
+ the following exception happened when compiling a subquery.
73
+
74
+ #{Exception.format(:error, exception, []) |> String.replace("\n", "\n ")}
75
+
76
+ The subquery originated from the following query:
77
+
78
+ #{Inspect.Ecto.Query.to_string(query)}
79
+ """
80
+
81
+ %__MODULE__{message: message, exception: exception}
82
+ end
83
+ end
84
+
85
+ defmodule Ecto.InvalidChangesetError do
86
+ @moduledoc """
87
+ Raised when we cannot perform an action because the
88
+ changeset is invalid.
89
+ """
90
+ defexception [:action, :changeset]
91
+
92
+ def message(%{action: action, changeset: changeset}) do
93
+ changes = extract_changes(changeset)
94
+ errors = Ecto.Changeset.traverse_errors(changeset, & &1)
95
+
96
+ """
97
+ could not perform #{action} because changeset is invalid.
98
+
99
+ Errors
100
+
101
+ #{pretty(errors)}
102
+
103
+ Applied changes
104
+
105
+ #{pretty(changes)}
106
+
107
+ Params
108
+
109
+ #{pretty(changeset.params)}
110
+
111
+ Changeset
112
+
113
+ #{pretty(changeset)}
114
+ """
115
+ end
116
+
117
+ defp pretty(term) do
118
+ inspect(term, pretty: true)
119
+ |> String.split("\n")
120
+ |> Enum.map_join("\n", &(" " <> &1))
121
+ end
122
+
123
+ defp extract_changes(%Ecto.Changeset{changes: changes}) do
124
+ Enum.reduce(changes, %{}, fn {key, value}, acc ->
125
+ case value do
126
+ %Ecto.Changeset{action: :delete} -> acc
127
+ _ -> Map.put(acc, key, extract_changes(value))
128
+ end
129
+ end)
130
+ end
131
+
132
+ defp extract_changes([%Ecto.Changeset{action: :delete} | tail]),
133
+ do: extract_changes(tail)
134
+
135
+ defp extract_changes([%Ecto.Changeset{} = changeset | tail]),
136
+ do: [extract_changes(changeset) | extract_changes(tail)]
137
+
138
+ defp extract_changes(other),
139
+ do: other
140
+ end
141
+
142
+ defmodule Ecto.CastError do
143
+ @moduledoc """
144
+ Raised when a changeset can't cast a value.
145
+ """
146
+ defexception [:message, :type, :value]
147
+
148
+ def exception(opts) do
149
+ type = Keyword.fetch!(opts, :type)
150
+ value = Keyword.fetch!(opts, :value)
151
+ msg = opts[:message] || "cannot cast #{inspect(value)} to #{Ecto.Type.format(type)}"
152
+ %__MODULE__{message: msg, type: type, value: value}
153
+ end
154
+ end
155
+
156
+ defmodule Ecto.InvalidURLError do
157
+ defexception [:message, :url]
158
+
159
+ def exception(opts) do
160
+ url = Keyword.fetch!(opts, :url)
161
+ msg = Keyword.fetch!(opts, :message)
162
+ msg = "invalid URL #{url}, #{msg}. The parsed URL is: #{inspect(URI.parse(url))}"
163
+ %__MODULE__{message: msg, url: url}
164
+ end
165
+ end
166
+
167
+ defmodule Ecto.NoPrimaryKeyFieldError do
168
+ @moduledoc """
169
+ Raised at runtime when an operation that requires a primary key is invoked
170
+ with a schema that does not define a primary key by using `@primary_key false`
171
+ """
172
+ defexception [:message, :schema]
173
+
174
+ def exception(opts) do
175
+ schema = Keyword.fetch!(opts, :schema)
176
+ message = "schema `#{inspect(schema)}` has no primary key"
177
+ %__MODULE__{message: message, schema: schema}
178
+ end
179
+ end
180
+
181
+ defmodule Ecto.NoPrimaryKeyValueError do
182
+ @moduledoc """
183
+ Raised at runtime when an operation that requires a primary key is invoked
184
+ with a schema missing value for its primary key
185
+ """
186
+ defexception [:message, :struct]
187
+
188
+ def exception(opts) do
189
+ struct = Keyword.fetch!(opts, :struct)
190
+ message = "struct `#{inspect(struct)}` is missing primary key value"
191
+ %__MODULE__{message: message, struct: struct}
192
+ end
193
+ end
194
+
195
+ defmodule Ecto.ChangeError do
196
+ defexception [:message]
197
+ end
198
+
199
+ defmodule Ecto.NoResultsError do
200
+ defexception [:message]
201
+
202
+ def exception(opts) do
203
+ query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query()
204
+
205
+ msg = """
206
+ expected at least one result but got none in query:
207
+
208
+ #{Inspect.Ecto.Query.to_string(query)}
209
+ """
210
+
211
+ %__MODULE__{message: msg}
212
+ end
213
+ end
214
+
215
+ defmodule Ecto.MultipleResultsError do
216
+ defexception [:message]
217
+
218
+ def exception(opts) do
219
+ query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query()
220
+ count = Keyword.fetch!(opts, :count)
221
+
222
+ msg = """
223
+ expected at most one result but got #{count} in query:
224
+
225
+ #{Inspect.Ecto.Query.to_string(query)}
226
+ """
227
+
228
+ %__MODULE__{message: msg}
229
+ end
230
+ end
231
+
232
+ defmodule Ecto.MultiplePrimaryKeyError do
233
+ defexception [:message]
234
+
235
+ def exception(opts) do
236
+ operation = Keyword.fetch!(opts, :operation)
237
+ source = Keyword.fetch!(opts, :source)
238
+ params = Keyword.fetch!(opts, :params)
239
+ count = Keyword.fetch!(opts, :count)
240
+
241
+ msg = """
242
+ expected #{operation} on #{source} to return at most one entry but got #{count} entries.
243
+
244
+ This typically means the field(s) set as primary_key in your schema/source
245
+ are not enough to uniquely identify entries in the repository.
246
+
247
+ Those are the parameters sent to the repository:
248
+
249
+ #{inspect(params)}
250
+ """
251
+
252
+ %__MODULE__{message: msg}
253
+ end
254
+ end
255
+
256
+ defmodule Ecto.MigrationError do
257
+ defexception [:message]
258
+ end
259
+
260
+ defmodule Ecto.StaleEntryError do
261
+ defexception [:message, :changeset]
262
+
263
+ def exception(opts) do
264
+ action = Keyword.fetch!(opts, :action)
265
+ changeset = Keyword.fetch!(opts, :changeset)
266
+
267
+ msg = """
268
+ attempted to #{action} a stale struct:
269
+
270
+ #{inspect(changeset.data)}
271
+
272
+ This typically happens when the struct no longer exists in the database \
273
+ or a database trigger/rule has forbidden the action. If stale entries are \
274
+ expected, you may use `:stale_error_field` to convert this into a changeset \
275
+ error, or set `:allow_stale` to true if you would like stale operations to \
276
+ be considered a success (such as a stale deletion)
277
+ """
278
+
279
+ %__MODULE__{message: msg, changeset: changeset}
280
+ end
281
+ end
282
+
283
+ defmodule Ecto.ConstraintError do
284
+ defexception [:type, :constraint, :message]
285
+
286
+ def exception(opts) do
287
+ type = Keyword.fetch!(opts, :type)
288
+ constraint = Keyword.fetch!(opts, :constraint)
289
+ changeset = Keyword.fetch!(opts, :changeset)
290
+ action = Keyword.fetch!(opts, :action)
291
+
292
+ constraints =
293
+ case changeset.constraints do
294
+ [] ->
295
+ "The changeset has not defined any constraint."
296
+
297
+ constraints ->
298
+ "The changeset defined the following constraints:\n\n" <>
299
+ Enum.map_join(
300
+ constraints,
301
+ "\n",
302
+ &" * #{inspect(&1.constraint)} (#{&1.type}_constraint)"
303
+ )
304
+ end
305
+
306
+ msg = """
307
+ constraint error when attempting to #{action} struct:
308
+
309
+ * #{inspect(constraint)} (#{type}_constraint)
310
+
311
+ If you would like to stop this constraint violation from raising an
312
+ exception and instead add it as an error to your changeset, please
313
+ call `#{type}_constraint/3` on your changeset with the constraint
314
+ `:name` as an option.
315
+
316
+ #{constraints}
317
+ """
318
+
319
+ %__MODULE__{message: msg, type: type, constraint: constraint}
320
+ end
321
+ end
deps/ecto/lib/ecto/json.ex ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if Code.ensure_loaded?(Jason.Encoder) do
2
+ defimpl Jason.Encoder, for: Ecto.Association.NotLoaded do
3
+ def encode(%{__owner__: owner, __field__: field}, _) do
4
+ raise """
5
+ cannot encode association #{inspect(field)} from #{inspect(owner)} to \
6
+ JSON because the association was not loaded.
7
+
8
+ You can either preload the association:
9
+
10
+ Repo.preload(#{inspect(owner)}, #{inspect(field)})
11
+
12
+ Or choose to not encode the association when converting the struct \
13
+ to JSON by explicitly listing the JSON fields in your schema:
14
+
15
+ defmodule #{inspect(owner)} do
16
+ # ...
17
+
18
+ @derive {Jason.Encoder, only: [:name, :title, ...]}
19
+ schema ... do
20
+
21
+ You can also use the :except option instead of :only if you would \
22
+ prefer to skip some fields.
23
+ """
24
+ end
25
+ end
26
+
27
+ defimpl Jason.Encoder, for: Ecto.Schema.Metadata do
28
+ def encode(%{schema: schema}, _) do
29
+ raise """
30
+ cannot encode metadata from the :__meta__ field for #{inspect(schema)} \
31
+ to JSON. This metadata is used internally by Ecto and should never be \
32
+ exposed externally.
33
+
34
+ You can either map the schemas to remove the :__meta__ field before \
35
+ encoding or explicitly list the JSON fields in your schema:
36
+
37
+ defmodule #{inspect(schema)} do
38
+ # ...
39
+
40
+ @derive {Jason.Encoder, only: [:name, :title, ...]}
41
+ schema ... do
42
+
43
+ You can also use the :except option instead of :only if you would \
44
+ prefer to skip some fields.
45
+ """
46
+ end
47
+ end
48
+ end
deps/ecto/lib/ecto/multi.ex ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Multi do
2
+ @moduledoc """
3
+ `Ecto.Multi` is a data structure for grouping multiple Repo operations.
4
+
5
+ `Ecto.Multi` makes it possible to pack operations that should be
6
+ performed in a single database transaction and gives a way to introspect
7
+ the queued operations without actually performing them. Each operation
8
+ is given a name that is unique and will identify its result in case of
9
+ success or failure.
10
+
11
+ If a multi is valid (i.e. all the changesets in it are valid),
12
+ all operations will be executed in the order they were added.
13
+
14
+ The `Ecto.Multi` structure should be considered opaque. You can use
15
+ `%Ecto.Multi{}` to pattern match the type, but accessing fields or
16
+ directly modifying them is not advised.
17
+
18
+ `Ecto.Multi.to_list/1` returns a canonical representation of the
19
+ structure that can be used for introspection.
20
+
21
+ ## Changesets
22
+
23
+ If multi contains operations that accept changesets (like `insert/4`,
24
+ `update/4` or `delete/4`) they will be checked before starting the
25
+ transaction. If any changeset has errors, the transaction won't even
26
+ be started and the error will be immediately returned.
27
+
28
+ Note: `insert/4`, `update/4`, `insert_or_update/4`, and `delete/4`
29
+ variants that accept a function do not perform these checks since
30
+ the functions are executed after the transaction has started.
31
+
32
+ ## Run
33
+
34
+ Multi allows you to run arbitrary functions as part of your transaction
35
+ via `run/3` and `run/5`. This is especially useful when an operation
36
+ depends on the value of a previous operation. For this reason, the
37
+ function given as a callback to `run/3` and `run/5` will receive the repo
38
+ as the first argument, and all changes performed by the multi so far as a
39
+ map for the second argument.
40
+
41
+ The function given to `run` must return `{:ok, value}` or `{:error, value}`
42
+ as its result. Returning an error will abort any further operations
43
+ and make the whole multi fail.
44
+
45
+ ## Example
46
+
47
+ Let's look at an example definition and usage. The use case we'll be
48
+ looking into is resetting a password. We need to update the account
49
+ with proper information, log the request and remove all current sessions:
50
+
51
+ defmodule PasswordManager do
52
+ alias Ecto.Multi
53
+
54
+ def reset(account, params) do
55
+ Multi.new()
56
+ |> Multi.update(:account, Account.password_reset_changeset(account, params))
57
+ |> Multi.insert(:log, Log.password_reset_changeset(account, params))
58
+ |> Multi.delete_all(:sessions, Ecto.assoc(account, :sessions))
59
+ end
60
+ end
61
+
62
+ We can later execute it in the integration layer using Repo:
63
+
64
+ Repo.transaction(PasswordManager.reset(account, params))
65
+
66
+ By pattern matching on the result we can differentiate different conditions:
67
+
68
+ case result do
69
+ {:ok, %{account: account, log: log, sessions: sessions}} ->
70
+ # Operation was successful, we can access results (exactly the same
71
+ # we would get from running corresponding Repo functions) under keys
72
+ # we used for naming the operations.
73
+ {:error, failed_operation, failed_value, changes_so_far} ->
74
+ # One of the operations failed. We can access the operation's failure
75
+ # value (like changeset for operations on changesets) to prepare a
76
+ # proper response. We also get access to the results of any operations
77
+ # that succeeded before the indicated operation failed. However, any
78
+ # successful operations would have been rolled back.
79
+ end
80
+
81
+ We can also easily unit test our transaction without actually running it.
82
+ Since changesets can use in-memory-data, we can use an account that is
83
+ constructed in memory as well (without persisting it to the database):
84
+
85
+ test "dry run password reset" do
86
+ account = %Account{password: "letmein"}
87
+ multi = PasswordManager.reset(account, params)
88
+
89
+ assert [
90
+ {:account, {:update, account_changeset, []}},
91
+ {:log, {:insert, log_changeset, []}},
92
+ {:sessions, {:delete_all, query, []}}
93
+ ] = Ecto.Multi.to_list(multi)
94
+
95
+ # We can introspect changesets and query to see if everything
96
+ # is as expected, for example:
97
+ assert account_changeset.valid?
98
+ assert log_changeset.valid?
99
+ assert inspect(query) == "#Ecto.Query<from a in Session>"
100
+ end
101
+
102
+ The name of each operation does not have to be an atom. This can be particularly
103
+ useful when you wish to update a collection of changesets at once, and track their
104
+ errors individually:
105
+
106
+ accounts = [%Account{id: 1}, %Account{id: 2}]
107
+
108
+ Enum.reduce(accounts, Multi.new(), fn account, multi ->
109
+ Multi.update(
110
+ multi,
111
+ {:account, account.id},
112
+ Account.password_reset_changeset(account, params)
113
+ )
114
+ end)
115
+ """
116
+
117
+ alias __MODULE__
118
+ alias Ecto.Changeset
119
+
120
+ defstruct operations: [], names: MapSet.new()
121
+
122
+ @typedoc """
123
+ Map of changes made so far during the current transaction. For any Multi
124
+ which returns `{:ok, result}`, its `t:name/0` is added as a key and its
125
+ result as the value.
126
+ """
127
+ @type changes :: map
128
+ @type run :: (Ecto.Repo.t(), changes -> {:ok | :error, any})
129
+ @type fun(result) :: (changes -> result)
130
+ @type merge :: (changes -> t) | {module, atom, [any]}
131
+ @typep schema_or_source :: binary | {binary, module} | module
132
+ @typep operation ::
133
+ {:changeset, Changeset.t(), Keyword.t()}
134
+ | {:run, run}
135
+ | {:put, any}
136
+ | {:inspect, Keyword.t()}
137
+ | {:merge, merge}
138
+ | {:update_all, Ecto.Query.t(), Keyword.t()}
139
+ | {:delete_all, Ecto.Query.t(), Keyword.t()}
140
+ | {:insert_all, schema_or_source, [map | Keyword.t()], Keyword.t()}
141
+ @typep operations :: [{name, operation}]
142
+
143
+ @typep names :: MapSet.t()
144
+
145
+ @typedoc """
146
+ Name of an operation in the Multi. Can be any term, as long as it is unique
147
+ within the list of operations; for example, `:insert_post` or `{:delete_post,
148
+ 5}`.
149
+ """
150
+ @type name :: any
151
+
152
+ @typedoc """
153
+ Result of a failed transaction using a Multi.
154
+ """
155
+ @type failure ::
156
+ {:error, failed_operation :: Ecto.Multi.name(), failed_value :: any(),
157
+ changes_so_far :: %{Ecto.Multi.name() => any}}
158
+
159
+ @type t :: %__MODULE__{operations: operations, names: names}
160
+
161
+ @doc """
162
+ Returns an empty `Ecto.Multi` struct.
163
+
164
+ ## Example
165
+
166
+ iex> Ecto.Multi.new() |> Ecto.Multi.to_list()
167
+ []
168
+
169
+ """
170
+ @spec new :: t
171
+ def new do
172
+ %Multi{}
173
+ end
174
+
175
+ @doc """
176
+ Appends the second multi to the first one.
177
+
178
+ All names must be unique between both structures.
179
+
180
+ ## Example
181
+
182
+ iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end)
183
+ iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end)
184
+ iex> Ecto.Multi.append(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
185
+ [:left, :right]
186
+
187
+ """
188
+ @spec append(t, t) :: t
189
+ def append(lhs, rhs) do
190
+ merge_structs(lhs, rhs, &(&2 ++ &1))
191
+ end
192
+
193
+ @doc """
194
+ Prepends the second multi to the first one.
195
+
196
+ All names must be unique between both structures.
197
+
198
+ ## Example
199
+
200
+ iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end)
201
+ iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end)
202
+ iex> Ecto.Multi.prepend(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
203
+ [:right, :left]
204
+
205
+ """
206
+ @spec prepend(t, t) :: t
207
+ def prepend(lhs, rhs) do
208
+ merge_structs(lhs, rhs, &(&1 ++ &2))
209
+ end
210
+
211
+ defp merge_structs(%Multi{} = lhs, %Multi{} = rhs, joiner) do
212
+ %{names: lhs_names, operations: lhs_ops} = lhs
213
+ %{names: rhs_names, operations: rhs_ops} = rhs
214
+
215
+ case MapSet.intersection(lhs_names, rhs_names) |> MapSet.to_list() do
216
+ [] ->
217
+ %Multi{names: MapSet.union(lhs_names, rhs_names), operations: joiner.(lhs_ops, rhs_ops)}
218
+
219
+ common ->
220
+ raise ArgumentError, """
221
+ error when merging the following Ecto.Multi structs:
222
+
223
+ #{Kernel.inspect(lhs)}
224
+
225
+ #{Kernel.inspect(rhs)}
226
+
227
+ both declared operations: #{Kernel.inspect(common)}
228
+ """
229
+ end
230
+ end
231
+
232
+ @doc """
233
+ Merges a multi returned dynamically by an anonymous function.
234
+
235
+ This function is useful when the multi to be merged requires information
236
+ from the original multi. Hence the second argument is an anonymous function
237
+ that receives the multi changes so far. The anonymous function must return
238
+ another multi.
239
+
240
+ If you would prefer to simply merge two multis together, see `append/2` or
241
+ `prepend/2`.
242
+
243
+ Duplicated operations are not allowed.
244
+
245
+ ## Example
246
+
247
+ multi =
248
+ Ecto.Multi.new()
249
+ |> Ecto.Multi.insert(:post, %Post{title: "first"})
250
+
251
+ multi
252
+ |> Ecto.Multi.merge(fn %{post: post} ->
253
+ Ecto.Multi.new()
254
+ |> Ecto.Multi.insert(:comment, Ecto.build_assoc(post, :comments))
255
+ end)
256
+ |> MyApp.Repo.transaction()
257
+ """
258
+ @spec merge(t, (changes -> t)) :: t
259
+ def merge(%Multi{} = multi, merge) when is_function(merge, 1) do
260
+ Map.update!(multi, :operations, &[{:merge, {:merge, merge}} | &1])
261
+ end
262
+
263
+ @doc """
264
+ Merges a multi returned dynamically by calling `module` and `function` with `args`.
265
+
266
+ Similar to `merge/2`, but allows to pass module name, function and arguments.
267
+ The function should return an `Ecto.Multi`, and receives changes so far
268
+ as the first argument (prepended to those passed in the call to the function).
269
+
270
+ Duplicated operations are not allowed.
271
+ """
272
+ @spec merge(t, module, function, args) :: t when function: atom, args: [any]
273
+ def merge(%Multi{} = multi, mod, fun, args)
274
+ when is_atom(mod) and is_atom(fun) and is_list(args) do
275
+ Map.update!(multi, :operations, &[{:merge, {:merge, {mod, fun, args}}} | &1])
276
+ end
277
+
278
+ @doc """
279
+ Adds an insert operation to the multi.
280
+
281
+ The `name` must be unique from other statements in the multi.
282
+
283
+ The remaining arguments and options are the same as in `c:Ecto.Repo.insert/2`.
284
+
285
+ ## Example
286
+
287
+ Ecto.Multi.new()
288
+ |> Ecto.Multi.insert(:insert, %Post{title: "first"})
289
+ |> MyApp.Repo.transaction()
290
+
291
+ Ecto.Multi.new()
292
+ |> Ecto.Multi.insert(:post, %Post{title: "first"})
293
+ |> Ecto.Multi.insert(:comment, fn %{post: post} ->
294
+ Ecto.build_assoc(post, :comments)
295
+ end)
296
+ |> MyApp.Repo.transaction()
297
+
298
+ """
299
+ @spec insert(
300
+ t,
301
+ name,
302
+ Changeset.t() | Ecto.Schema.t() | fun(Changeset.t() | Ecto.Schema.t()),
303
+ Keyword.t()
304
+ ) :: t
305
+ def insert(multi, name, changeset_or_struct_or_fun, opts \\ [])
306
+
307
+ def insert(multi, name, %Changeset{} = changeset, opts) do
308
+ add_changeset(multi, :insert, name, changeset, opts)
309
+ end
310
+
311
+ def insert(multi, name, %_{} = struct, opts) do
312
+ insert(multi, name, Changeset.change(struct), opts)
313
+ end
314
+
315
+ def insert(multi, name, fun, opts) when is_function(fun, 1) do
316
+ run(multi, name, operation_fun({:insert, fun}, opts))
317
+ end
318
+
319
+ @doc """
320
+ Adds an update operation to the multi.
321
+
322
+ The `name` must be unique from other statements in the multi.
323
+
324
+ The remaining arguments and options are the same as in `c:Ecto.Repo.update/2`.
325
+
326
+ ## Example
327
+
328
+ post = MyApp.Repo.get!(Post, 1)
329
+ changeset = Ecto.Changeset.change(post, title: "New title")
330
+ Ecto.Multi.new()
331
+ |> Ecto.Multi.update(:update, changeset)
332
+ |> MyApp.Repo.transaction()
333
+
334
+ Ecto.Multi.new()
335
+ |> Ecto.Multi.insert(:post, %Post{title: "first"})
336
+ |> Ecto.Multi.update(:fun, fn %{post: post} ->
337
+ Ecto.Changeset.change(post, title: "New title")
338
+ end)
339
+ |> MyApp.Repo.transaction()
340
+
341
+ """
342
+ @spec update(t, name, Changeset.t() | fun(Changeset.t()), Keyword.t()) :: t
343
+ def update(multi, name, changeset_or_fun, opts \\ [])
344
+
345
+ def update(multi, name, %Changeset{} = changeset, opts) do
346
+ add_changeset(multi, :update, name, changeset, opts)
347
+ end
348
+
349
+ def update(multi, name, fun, opts) when is_function(fun, 1) do
350
+ run(multi, name, operation_fun({:update, fun}, opts))
351
+ end
352
+
353
+ @doc """
354
+ Inserts or updates a changeset depending on whether the changeset was persisted or not.
355
+
356
+ The `name` must be unique from other statements in the multi.
357
+
358
+ The remaining arguments and options are the same as in `c:Ecto.Repo.insert_or_update/2`.
359
+
360
+ ## Example
361
+
362
+ changeset = Post.changeset(%Post{}, %{title: "New title"})
363
+ Ecto.Multi.new()
364
+ |> Ecto.Multi.insert_or_update(:insert_or_update, changeset)
365
+ |> MyApp.Repo.transaction()
366
+
367
+ Ecto.Multi.new()
368
+ |> Ecto.Multi.run(:post, fn repo, _changes ->
369
+ {:ok, repo.get(Post, 1) || %Post{}}
370
+ end)
371
+ |> Ecto.Multi.insert_or_update(:update, fn %{post: post} ->
372
+ Ecto.Changeset.change(post, title: "New title")
373
+ end)
374
+ |> MyApp.Repo.transaction()
375
+
376
+ """
377
+ @spec insert_or_update(t, name, Changeset.t() | fun(Changeset.t()), Keyword.t()) :: t
378
+ def insert_or_update(multi, name, changeset_or_fun, opts \\ [])
379
+
380
+ def insert_or_update(
381
+ multi,
382
+ name,
383
+ %Changeset{data: %{__meta__: %{state: :loaded}}} = changeset,
384
+ opts
385
+ ) do
386
+ add_changeset(multi, :update, name, changeset, opts)
387
+ end
388
+
389
+ def insert_or_update(multi, name, %Changeset{} = changeset, opts) do
390
+ add_changeset(multi, :insert, name, changeset, opts)
391
+ end
392
+
393
+ def insert_or_update(multi, name, fun, opts) when is_function(fun, 1) do
394
+ run(multi, name, operation_fun({:insert_or_update, fun}, opts))
395
+ end
396
+
397
+ @doc """
398
+ Adds a delete operation to the multi.
399
+
400
+ The `name` must be unique from other statements in the multi.
401
+
402
+ The remaining arguments and options are the same as in `c:Ecto.Repo.delete/2`.
403
+
404
+ ## Example
405
+
406
+ post = MyApp.Repo.get!(Post, 1)
407
+ Ecto.Multi.new()
408
+ |> Ecto.Multi.delete(:delete, post)
409
+ |> MyApp.Repo.transaction()
410
+
411
+ Ecto.Multi.new()
412
+ |> Ecto.Multi.run(:post, fn repo, _changes ->
413
+ case repo.get(Post, 1) do
414
+ nil -> {:error, :not_found}
415
+ post -> {:ok, post}
416
+ end
417
+ end)
418
+ |> Ecto.Multi.delete(:delete, fn %{post: post} ->
419
+ # Others validations
420
+ post
421
+ end)
422
+ |> MyApp.Repo.transaction()
423
+
424
+ """
425
+ @spec delete(
426
+ t,
427
+ name,
428
+ Changeset.t() | Ecto.Schema.t() | fun(Changeset.t() | Ecto.Schema.t()),
429
+ Keyword.t()
430
+ ) :: t
431
+ def delete(multi, name, changeset_or_struct_fun, opts \\ [])
432
+
433
+ def delete(multi, name, %Changeset{} = changeset, opts) do
434
+ add_changeset(multi, :delete, name, changeset, opts)
435
+ end
436
+
437
+ def delete(multi, name, %_{} = struct, opts) do
438
+ delete(multi, name, Changeset.change(struct), opts)
439
+ end
440
+
441
+ def delete(multi, name, fun, opts) when is_function(fun, 1) do
442
+ run(multi, name, operation_fun({:delete, fun}, opts))
443
+ end
444
+
445
+ @doc """
446
+ Runs a query expecting one result and stores it in the multi.
447
+
448
+ The `name` must be unique from other statements in the multi.
449
+
450
+ The remaining arguments and options are the same as in `c:Ecto.Repo.one/2`.
451
+
452
+ ## Example
453
+
454
+ Ecto.Multi.new()
455
+ |> Ecto.Multi.one(:post, Post)
456
+ |> Ecto.Multi.one(:author, fn %{post: post} ->
457
+ from(a in Author, where: a.id == ^post.author_id)
458
+ end)
459
+ |> MyApp.Repo.transaction()
460
+ """
461
+ @spec one(
462
+ t,
463
+ name,
464
+ queryable :: Ecto.Queryable.t() | fun(Ecto.Queryable.t()),
465
+ opts :: Keyword.t()
466
+ ) :: t
467
+ def one(multi, name, queryable_or_fun, opts \\ [])
468
+
469
+ def one(multi, name, fun, opts) when is_function(fun, 1) do
470
+ run(multi, name, operation_fun({:one, fun}, opts))
471
+ end
472
+
473
+ def one(multi, name, queryable, opts) do
474
+ run(multi, name, operation_fun({:one, fn _ -> queryable end}, opts))
475
+ end
476
+
477
+ @doc """
478
+ Runs a query and stores all entries in the multi.
479
+
480
+ The `name` must be unique from other statements in the multi.
481
+
482
+ The remaining arguments and options are the same as in `c:Ecto.Repo.all/2` does.
483
+
484
+ ## Example
485
+
486
+ Ecto.Multi.new()
487
+ |> Ecto.Multi.all(:all, Post)
488
+ |> MyApp.Repo.transaction()
489
+
490
+ Ecto.Multi.new()
491
+ |> Ecto.Multi.all(:all, fn _changes -> Post end)
492
+ |> MyApp.Repo.transaction()
493
+ """
494
+ @spec all(
495
+ t,
496
+ name,
497
+ queryable :: Ecto.Queryable.t() | fun(Ecto.Queryable.t()),
498
+ opts :: Keyword.t()
499
+ ) :: t
500
+ def all(multi, name, queryable_or_fun, opts \\ [])
501
+
502
+ def all(multi, name, fun, opts) when is_function(fun, 1) do
503
+ run(multi, name, operation_fun({:all, fun}, opts))
504
+ end
505
+
506
+ def all(multi, name, queryable, opts) do
507
+ run(multi, name, operation_fun({:all, fn _ -> queryable end}, opts))
508
+ end
509
+
510
+ @doc """
511
+ Checks if there exists an entry matching the given query and stores a boolean in the multi.
512
+
513
+ The `name` must be unique from other statements in the multi.
514
+
515
+ The remaining arguments and options are the same as in `c:Ecto.Repo.exists?/2`.
516
+
517
+ ## Example
518
+
519
+ Ecto.Multi.new()
520
+ |> Ecto.Multi.exists?(:post, Post)
521
+ |> MyApp.Repo.transaction()
522
+
523
+ Ecto.Multi.new()
524
+ |> Ecto.Multi.exists?(:post, fn _changes -> Post end)
525
+ |> MyApp.Repo.transaction()
526
+ """
527
+ @spec exists?(
528
+ t,
529
+ name,
530
+ queryable :: Ecto.Queryable.t() | fun(Ecto.Queryable.t()),
531
+ opts :: Keyword.t()
532
+ ) :: t
533
+ def exists?(multi, name, queryable_or_fun, opts \\ [])
534
+
535
+ def exists?(multi, name, fun, opts) when is_function(fun, 1) do
536
+ run(multi, name, operation_fun({:exists?, fun}, opts))
537
+ end
538
+
539
+ def exists?(multi, name, queryable, opts) do
540
+ run(multi, name, operation_fun({:exists?, fn _ -> queryable end}, opts))
541
+ end
542
+
543
+ defp add_changeset(multi, action, name, changeset, opts) when is_list(opts) do
544
+ add_operation(multi, name, {:changeset, put_action(changeset, action), opts})
545
+ end
546
+
547
+ defp put_action(%{action: nil} = changeset, action) do
548
+ %{changeset | action: action}
549
+ end
550
+
551
+ defp put_action(%{action: action} = changeset, action) do
552
+ changeset
553
+ end
554
+
555
+ defp put_action(%{action: original}, action) do
556
+ raise ArgumentError,
557
+ "you provided a changeset with an action already set " <>
558
+ "to #{Kernel.inspect(original)} when trying to #{action} it"
559
+ end
560
+
561
+ @doc """
562
+ Causes the multi to fail with the given value.
563
+
564
+ Running the multi in a transaction will execute
565
+ no previous steps and returns the value of the first
566
+ error added.
567
+ """
568
+ @spec error(t, name, error :: term) :: t
569
+ def error(multi, name, value) do
570
+ add_operation(multi, name, {:error, value})
571
+ end
572
+
573
+ @doc """
574
+ Adds a function to run as part of the multi.
575
+
576
+ The function should return either `{:ok, value}` or `{:error, value}`,
577
+ and receives the repo as the first argument, and the changes so far
578
+ as the second argument.
579
+
580
+ ## Example
581
+
582
+ Ecto.Multi.run(multi, :write, fn _repo, %{image: image} ->
583
+ with :ok <- File.write(image.name, image.contents) do
584
+ {:ok, nil}
585
+ end
586
+ end)
587
+ """
588
+ @spec run(t, name, run) :: t
589
+ def run(multi, name, run) when is_function(run, 2) do
590
+ add_operation(multi, name, {:run, run})
591
+ end
592
+
593
+ @doc """
594
+ Adds a function to run as part of the multi.
595
+
596
+ Similar to `run/3`, but allows to pass module name, function and arguments.
597
+ The function should return either `{:ok, value}` or `{:error, value}`, and
598
+ receives the repo as the first argument, and the changes so far as the
599
+ second argument (prepended to those passed in the call to the function).
600
+ """
601
+ @spec run(t, name, module, function, args) :: t when function: atom, args: [any]
602
+ def run(multi, name, mod, fun, args)
603
+ when is_atom(mod) and is_atom(fun) and is_list(args) do
604
+ add_operation(multi, name, {:run, {mod, fun, args}})
605
+ end
606
+
607
+ @doc """
608
+ Adds an insert_all operation to the multi.
609
+
610
+ Accepts the same arguments and options as `c:Ecto.Repo.insert_all/3` does.
611
+
612
+ ## Example
613
+
614
+ posts = [%{title: "My first post"}, %{title: "My second post"}]
615
+ Ecto.Multi.new()
616
+ |> Ecto.Multi.insert_all(:insert_all, Post, posts)
617
+ |> MyApp.Repo.transaction()
618
+
619
+ Ecto.Multi.new()
620
+ |> Ecto.Multi.run(:post, fn repo, _changes ->
621
+ case repo.get(Post, 1) do
622
+ nil -> {:error, :not_found}
623
+ post -> {:ok, post}
624
+ end
625
+ end)
626
+ |> Ecto.Multi.insert_all(:insert_all, Comment, fn %{post: post} ->
627
+ # Others validations
628
+
629
+ entries
630
+ |> Enum.map(fn comment ->
631
+ Map.put(comment, :post_id, post.id)
632
+ end)
633
+ end)
634
+ |> MyApp.Repo.transaction()
635
+
636
+ """
637
+ @spec insert_all(
638
+ t,
639
+ name,
640
+ schema_or_source,
641
+ entries_or_query_or_fun ::
642
+ [map | Keyword.t()] | fun([map | Keyword.t()]) | Ecto.Query.t(),
643
+ Keyword.t()
644
+ ) :: t
645
+ def insert_all(multi, name, schema_or_source, entries_or_query_or_fun, opts \\ [])
646
+
647
+ def insert_all(multi, name, schema_or_source, entries_fun, opts)
648
+ when is_function(entries_fun, 1) and is_list(opts) do
649
+ run(multi, name, operation_fun({:insert_all, schema_or_source, entries_fun}, opts))
650
+ end
651
+
652
+ def insert_all(multi, name, schema_or_source, entries_or_query, opts) when is_list(opts) do
653
+ add_operation(multi, name, {:insert_all, schema_or_source, entries_or_query, opts})
654
+ end
655
+
656
+ @doc """
657
+ Adds an update_all operation to the multi.
658
+
659
+ Accepts the same arguments and options as `c:Ecto.Repo.update_all/3` does.
660
+
661
+ ## Example
662
+
663
+ Ecto.Multi.new()
664
+ |> Ecto.Multi.update_all(:update_all, Post, set: [title: "New title"])
665
+ |> MyApp.Repo.transaction()
666
+
667
+ Ecto.Multi.new()
668
+ |> Ecto.Multi.run(:post, fn repo, _changes ->
669
+ case repo.get(Post, 1) do
670
+ nil -> {:error, :not_found}
671
+ post -> {:ok, post}
672
+ end
673
+ end)
674
+ |> Ecto.Multi.update_all(:update_all, fn %{post: post} ->
675
+ # Others validations
676
+ from(c in Comment, where: c.post_id == ^post.id, update: [set: [title: "New title"]])
677
+ end, [])
678
+ |> MyApp.Repo.transaction()
679
+
680
+ """
681
+ @spec update_all(
682
+ t,
683
+ name,
684
+ Ecto.Queryable.t() | fun(Ecto.Queryable.t()),
685
+ Keyword.t(),
686
+ Keyword.t()
687
+ ) :: t
688
+ def update_all(multi, name, queryable_or_fun, updates, opts \\ [])
689
+
690
+ def update_all(multi, name, queryable_fun, updates, opts)
691
+ when is_function(queryable_fun, 1) and is_list(opts) do
692
+ run(multi, name, operation_fun({:update_all, queryable_fun, updates}, opts))
693
+ end
694
+
695
+ def update_all(multi, name, queryable, updates, opts) when is_list(opts) do
696
+ query = Ecto.Queryable.to_query(queryable)
697
+ add_operation(multi, name, {:update_all, query, updates, opts})
698
+ end
699
+
700
+ @doc """
701
+ Adds a delete_all operation to the multi.
702
+
703
+ Accepts the same arguments and options as `c:Ecto.Repo.delete_all/2` does.
704
+
705
+ ## Example
706
+
707
+ queryable = from(p in Post, where: p.id < 5)
708
+ Ecto.Multi.new()
709
+ |> Ecto.Multi.delete_all(:delete_all, queryable)
710
+ |> MyApp.Repo.transaction()
711
+
712
+ Ecto.Multi.new()
713
+ |> Ecto.Multi.run(:post, fn repo, _changes ->
714
+ case repo.get(Post, 1) do
715
+ nil -> {:error, :not_found}
716
+ post -> {:ok, post}
717
+ end
718
+ end)
719
+ |> Ecto.Multi.delete_all(:delete_all, fn %{post: post} ->
720
+ # Others validations
721
+ from(c in Comment, where: c.post_id == ^post.id)
722
+ end)
723
+ |> MyApp.Repo.transaction()
724
+
725
+ """
726
+ @spec delete_all(t, name, Ecto.Queryable.t() | fun(Ecto.Queryable.t()), Keyword.t()) :: t
727
+ def delete_all(multi, name, queryable_or_fun, opts \\ [])
728
+
729
+ def delete_all(multi, name, fun, opts) when is_function(fun, 1) and is_list(opts) do
730
+ run(multi, name, operation_fun({:delete_all, fun}, opts))
731
+ end
732
+
733
+ def delete_all(multi, name, queryable, opts) when is_list(opts) do
734
+ query = Ecto.Queryable.to_query(queryable)
735
+ add_operation(multi, name, {:delete_all, query, opts})
736
+ end
737
+
738
+ defp add_operation(%Multi{} = multi, name, operation) do
739
+ %{operations: operations, names: names} = multi
740
+
741
+ if MapSet.member?(names, name) do
742
+ raise "#{Kernel.inspect(name)} is already a member of the Ecto.Multi: \n#{Kernel.inspect(multi)}"
743
+ else
744
+ %{multi | operations: [{name, operation} | operations], names: MapSet.put(names, name)}
745
+ end
746
+ end
747
+
748
+ @doc """
749
+ Returns the list of operations stored in `multi`.
750
+
751
+ Always use this function when you need to access the operations you
752
+ have defined in `Ecto.Multi`. Inspecting the `Ecto.Multi` struct internals
753
+ directly is discouraged.
754
+ """
755
+ @spec to_list(t) :: [{name, term}]
756
+ def to_list(%Multi{operations: operations}) do
757
+ operations
758
+ |> Enum.reverse()
759
+ |> Enum.map(&format_operation/1)
760
+ end
761
+
762
+ defp format_operation({name, {:changeset, changeset, opts}}),
763
+ do: {name, {changeset.action, changeset, opts}}
764
+
765
+ defp format_operation(other),
766
+ do: other
767
+
768
+ @doc """
769
+ Adds a value to the changes so far under the given name.
770
+
771
+ The given `value` is added to the multi before the transaction starts.
772
+ If you would like to run arbitrary functions as part of your transaction,
773
+ see `run/3` or `run/5`.
774
+
775
+ ## Example
776
+
777
+ Imagine there is an existing company schema that you retrieved from
778
+ the database. You can insert it as a change in the multi using `put/3`:
779
+
780
+ Ecto.Multi.new()
781
+ |> Ecto.Multi.put(:company, company)
782
+ |> Ecto.Multi.insert(:user, fn changes -> User.changeset(changes.company) end)
783
+ |> Ecto.Multi.insert(:person, fn changes -> Person.changeset(changes.user, changes.company) end)
784
+ |> MyApp.Repo.transaction()
785
+
786
+ In the example above there isn't a large benefit in putting the
787
+ `company` in the multi, because you could also access the
788
+ `company` variable directly inside the anonymous function.
789
+
790
+ However, the benefit of `put/3` is when composing `Ecto.Multi`s.
791
+ If the insert operations above were defined in another module,
792
+ you could use `put(:company, company)` to inject changes that
793
+ will be accessed by other functions down the chain, removing
794
+ the need to pass both `multi` and `company` values around.
795
+ """
796
+ @spec put(t, name, any) :: t
797
+ def put(multi, name, value) do
798
+ add_operation(multi, name, {:put, value})
799
+ end
800
+
801
+ @doc """
802
+ Inspects results from a Multi
803
+
804
+ By default, the name is shown as a label to the inspect, custom labels are
805
+ supported through the `IO.inspect/2` `label` option.
806
+
807
+ ## Options
808
+
809
+ All options for IO.inspect/2 are supported, it also support the following ones:
810
+
811
+ * `:only` - A field or a list of fields to inspect, will print the entire
812
+ map by default.
813
+
814
+ ## Examples
815
+
816
+ Ecto.Multi.new()
817
+ |> Ecto.Multi.insert(:person_a, changeset)
818
+ |> Ecto.Multi.insert(:person_b, changeset)
819
+ |> Ecto.Multi.inspect()
820
+ |> MyApp.Repo.transaction()
821
+
822
+ Prints:
823
+ %{person_a: %Person{...}, person_b: %Person{...}}
824
+
825
+ We can use the `:only` option to limit which fields will be printed:
826
+
827
+ Ecto.Multi.new()
828
+ |> Ecto.Multi.insert(:person_a, changeset)
829
+ |> Ecto.Multi.insert(:person_b, changeset)
830
+ |> Ecto.Multi.inspect(only: :person_a)
831
+ |> MyApp.Repo.transaction()
832
+
833
+ Prints:
834
+ %{person_a: %Person{...}}
835
+
836
+ """
837
+ @spec inspect(t, Keyword.t()) :: t
838
+ def inspect(multi, opts \\ []) do
839
+ Map.update!(multi, :operations, &[{:inspect, {:inspect, opts}} | &1])
840
+ end
841
+
842
+ @doc false
843
+ @spec __apply__(t, Ecto.Repo.t(), fun, (term -> no_return)) :: {:ok, term} | {:error, term}
844
+ def __apply__(%Multi{} = multi, repo, wrap, return) do
845
+ operations = Enum.reverse(multi.operations)
846
+
847
+ with {:ok, operations} <- check_operations_valid(operations) do
848
+ apply_operations(operations, multi.names, repo, wrap, return)
849
+ end
850
+ end
851
+
852
+ defp check_operations_valid(operations) do
853
+ Enum.find_value(operations, &invalid_operation/1) || {:ok, operations}
854
+ end
855
+
856
+ defp invalid_operation({name, {:changeset, %{valid?: false} = changeset, _}}),
857
+ do: {:error, {name, changeset, %{}}}
858
+
859
+ defp invalid_operation({name, {:error, value}}),
860
+ do: {:error, {name, value, %{}}}
861
+
862
+ defp invalid_operation(_operation),
863
+ do: nil
864
+
865
+ defp apply_operations([], _names, _repo, _wrap, _return), do: {:ok, %{}}
866
+
867
+ defp apply_operations(operations, names, repo, wrap, return) do
868
+ wrap.(fn ->
869
+ operations
870
+ |> Enum.reduce({%{}, names}, &apply_operation(&1, repo, wrap, return, &2))
871
+ |> elem(0)
872
+ end)
873
+ end
874
+
875
+ defp apply_operation({_, {:merge, merge}}, repo, wrap, return, {acc, names}) do
876
+ case __apply__(apply_merge_fun(merge, acc), repo, wrap, return) do
877
+ {:ok, value} ->
878
+ merge_results(acc, value, names)
879
+
880
+ {:error, {name, value, nested_acc}} ->
881
+ {acc, _names} = merge_results(acc, nested_acc, names)
882
+ return.({name, value, acc})
883
+ end
884
+ end
885
+
886
+ defp apply_operation({_name, {:inspect, opts}}, _repo, _wrap_, _return, {acc, names}) do
887
+ if opts[:only] do
888
+ acc |> Map.take(List.wrap(opts[:only])) |> IO.inspect(opts)
889
+ else
890
+ IO.inspect(acc, opts)
891
+ end
892
+
893
+ {acc, names}
894
+ end
895
+
896
+ defp apply_operation({name, operation}, repo, wrap, return, {acc, names}) do
897
+ case apply_operation(operation, acc, {wrap, return}, repo) do
898
+ {:ok, value} ->
899
+ {Map.put(acc, name, value), names}
900
+
901
+ {:error, value} ->
902
+ return.({name, value, acc})
903
+
904
+ other ->
905
+ raise "expected Ecto.Multi callback named `#{Kernel.inspect(name)}` to return either {:ok, value} or {:error, value}, got: #{Kernel.inspect(other)}"
906
+ end
907
+ end
908
+
909
+ defp apply_operation({:changeset, changeset, opts}, _acc, _apply_args, repo),
910
+ do: apply(repo, changeset.action, [changeset, opts])
911
+
912
+ defp apply_operation({:run, run}, acc, _apply_args, repo),
913
+ do: apply_run_fun(run, repo, acc)
914
+
915
+ defp apply_operation({:error, value}, _acc, _apply_args, _repo),
916
+ do: {:error, value}
917
+
918
+ defp apply_operation({:insert_all, source, entries, opts}, _acc, _apply_args, repo),
919
+ do: {:ok, repo.insert_all(source, entries, opts)}
920
+
921
+ defp apply_operation({:update_all, query, updates, opts}, _acc, _apply_args, repo),
922
+ do: {:ok, repo.update_all(query, updates, opts)}
923
+
924
+ defp apply_operation({:delete_all, query, opts}, _acc, _apply_args, repo),
925
+ do: {:ok, repo.delete_all(query, opts)}
926
+
927
+ defp apply_operation({:put, value}, _acc, _apply_args, _repo),
928
+ do: {:ok, value}
929
+
930
+ defp apply_merge_fun({mod, fun, args}, acc), do: apply(mod, fun, [acc | args])
931
+ defp apply_merge_fun(fun, acc), do: apply(fun, [acc])
932
+
933
+ defp apply_run_fun({mod, fun, args}, repo, acc), do: apply(mod, fun, [repo, acc | args])
934
+ defp apply_run_fun(fun, repo, acc), do: apply(fun, [repo, acc])
935
+
936
+ defp merge_results(changes, new_changes, names) do
937
+ new_names = new_changes |> Map.keys() |> MapSet.new()
938
+
939
+ case MapSet.intersection(names, new_names) |> MapSet.to_list() do
940
+ [] ->
941
+ {Map.merge(changes, new_changes), MapSet.union(names, new_names)}
942
+
943
+ common ->
944
+ raise "cannot merge multi, the following operations were found in " <>
945
+ "both Ecto.Multi: #{Kernel.inspect(common)}"
946
+ end
947
+ end
948
+
949
+ defp operation_fun({:update_all, queryable_fun, updates}, opts) do
950
+ fn repo, changes ->
951
+ {:ok, repo.update_all(queryable_fun.(changes), updates, opts)}
952
+ end
953
+ end
954
+
955
+ defp operation_fun({:insert_all, schema_or_source, entries_fun}, opts) do
956
+ fn repo, changes ->
957
+ {:ok, repo.insert_all(schema_or_source, entries_fun.(changes), opts)}
958
+ end
959
+ end
960
+
961
+ defp operation_fun({:delete_all, fun}, opts) do
962
+ fn repo, changes ->
963
+ {:ok, repo.delete_all(fun.(changes), opts)}
964
+ end
965
+ end
966
+
967
+ defp operation_fun({:one, fun}, opts) do
968
+ fn repo, changes ->
969
+ {:ok, repo.one(fun.(changes), opts)}
970
+ end
971
+ end
972
+
973
+ defp operation_fun({:all, fun}, opts) do
974
+ fn repo, changes ->
975
+ {:ok, repo.all(fun.(changes), opts)}
976
+ end
977
+ end
978
+
979
+ defp operation_fun({:exists?, fun}, opts) do
980
+ fn repo, changes ->
981
+ {:ok, repo.exists?(fun.(changes), opts)}
982
+ end
983
+ end
984
+
985
+ defp operation_fun({operation, fun}, opts) do
986
+ fn repo, changes ->
987
+ apply(repo, operation, [fun.(changes), opts])
988
+ end
989
+ end
990
+ end
deps/ecto/lib/ecto/parameterized_type.ex ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.ParameterizedType do
2
+ @moduledoc """
3
+ Parameterized types are Ecto types that can be customized per field.
4
+
5
+ Parameterized types allow a set of options to be specified in the schema
6
+ which are initialized on compilation and passed to the callback functions
7
+ as the last argument.
8
+
9
+ For example, `field :foo, :string` behaves the same for every field.
10
+ On the other hand, `field :foo, Ecto.Enum, values: [:foo, :bar, :baz]`
11
+ will likely have a different set of values per field.
12
+
13
+ Note that options are specified as a keyword, but it is idiomatic to
14
+ convert them to maps inside `c:init/1` for easier pattern matching in
15
+ other callbacks.
16
+
17
+ Parameterized types are a superset of regular types. In other words,
18
+ with parameterized types you can do everything a regular type does,
19
+ and more. For example, parameterized types can handle `nil` values
20
+ in both `load` and `dump` callbacks, they can customize `cast` behavior
21
+ per query and per changeset, and also control how values are embedded.
22
+
23
+ However, parameterized types are also more complex. Therefore, if
24
+ everything you need to achieve can be done with basic types, they
25
+ should be preferred to parameterized ones.
26
+
27
+ ## Examples
28
+
29
+ To create a parameterized type, create a module as shown below:
30
+
31
+ defmodule MyApp.MyType do
32
+ use Ecto.ParameterizedType
33
+
34
+ def type(_params), do: :string
35
+
36
+ def init(opts) do
37
+ validate_opts(opts)
38
+ Enum.into(opts, %{})
39
+ end
40
+
41
+ def cast(data, params) do
42
+ ...
43
+ {:ok, cast_data}
44
+ end
45
+
46
+ def load(data, _loader, params) do
47
+ ...
48
+ {:ok, loaded_data}
49
+ end
50
+
51
+ def dump(data, dumper, params) do
52
+ ...
53
+ {:ok, dumped_data}
54
+ end
55
+
56
+ def equal?(a, b, _params) do
57
+ a == b
58
+ end
59
+ end
60
+
61
+ To use this type in a schema field, specify the type and parameters like this:
62
+
63
+ schema "foo" do
64
+ field :bar, MyApp.MyType, opt1: :baz, opt2: :boo
65
+ end
66
+
67
+ To use this type in places where you need it to be initialized (for example,
68
+ schemaless changesets), you can use `init/2`.
69
+
70
+ > #### `use Ecto.ParameterizedType` {: .info}
71
+ >
72
+ > When you `use Ecto.ParameterizedType`, it will set
73
+ > `@behaviour Ecto.ParameterizedType` and define default, overridable
74
+ > implementations for `c:embed_as/2` and `c:equal?/3`.
75
+ """
76
+
77
+ @typedoc """
78
+ The keyword options passed from the Schema's field macro into `c:init/1`
79
+ """
80
+ @type opts :: keyword()
81
+
82
+ @typedoc """
83
+ The parameters for the ParameterizedType
84
+
85
+ This is the value passed back from `c:init/1` and subsequently passed
86
+ as the last argument to all callbacks. Idiomatically it is a map.
87
+ """
88
+ @type params :: term()
89
+
90
+ @doc """
91
+ Callback to convert the options specified in the field macro into parameters
92
+ to be used in other callbacks.
93
+
94
+ This function is called at compile time, and should raise if invalid values are
95
+ specified. It is idiomatic that the parameters returned from this are a map.
96
+ `field` and `schema` will be injected into the options automatically.
97
+
98
+ For example, this schema specification
99
+
100
+ schema "my_table" do
101
+ field :my_field, MyParameterizedType, opt1: :foo, opt2: nil
102
+ end
103
+
104
+ will result in the call:
105
+
106
+ MyParameterizedType.init([schema: "my_table", field: :my_field, opt1: :foo, opt2: nil])
107
+
108
+ """
109
+ @callback init(opts :: opts()) :: params()
110
+
111
+ @doc """
112
+ Casts the given input to the ParameterizedType with the given parameters.
113
+
114
+ If the parameterized type is also a composite type,
115
+ the inner type can be cast by calling `Ecto.Type.cast/2`
116
+ directly.
117
+
118
+ For more information on casting, see `c:Ecto.Type.cast/1`.
119
+ """
120
+ @callback cast(data :: term, params()) ::
121
+ {:ok, term} | :error | {:error, keyword()}
122
+
123
+ @doc """
124
+ Loads the given term into a ParameterizedType.
125
+
126
+ It receives a `loader` function in case the parameterized
127
+ type is also a composite type. In order to load the inner
128
+ type, the `loader` must be called with the inner type and
129
+ the inner value as argument.
130
+
131
+ For more information on loading, see `c:Ecto.Type.load/1`.
132
+ Note that this callback *will* be called when loading a `nil`
133
+ value, unlike `c:Ecto.Type.load/1`.
134
+ """
135
+ @callback load(value :: any(), loader :: function(), params()) :: {:ok, value :: any()} | :error
136
+
137
+ @doc """
138
+ Dumps the given term into an Ecto native type.
139
+
140
+ It receives a `dumper` function in case the parameterized
141
+ type is also a composite type. In order to dump the inner
142
+ type, the `dumper` must be called with the inner type and
143
+ the inner value as argument.
144
+
145
+ For more information on dumping, see `c:Ecto.Type.dump/1`.
146
+ Note that this callback *will* be called when dumping a `nil`
147
+ value, unlike `c:Ecto.Type.dump/1`.
148
+ """
149
+ @callback dump(value :: any(), dumper :: function(), params()) :: {:ok, value :: any()} | :error
150
+
151
+ @doc """
152
+ Returns the underlying schema type for the ParameterizedType.
153
+
154
+ For more information on schema types, see `c:Ecto.Type.type/0`
155
+ """
156
+ @callback type(params()) :: Ecto.Type.t()
157
+
158
+ @doc """
159
+ Checks if two terms are semantically equal.
160
+ """
161
+ @callback equal?(value1 :: any(), value2 :: any(), params()) :: boolean()
162
+
163
+ @doc """
164
+ Dictates how the type should be treated inside embeds.
165
+
166
+ For more information on embedding, see `c:Ecto.Type.embed_as/1`
167
+ """
168
+ @callback embed_as(format :: atom(), params()) :: :self | :dump
169
+
170
+ @doc """
171
+ Generates a loaded version of the data.
172
+
173
+ This callback is invoked when a parameterized type is given
174
+ to `field` with the `:autogenerate` flag.
175
+ """
176
+ @callback autogenerate(params()) :: term()
177
+
178
+ @doc """
179
+ Formats output when a ParameterizedType is printed in exceptions and
180
+ other logs.
181
+
182
+ Note this callback is not used when constructing `Ecto.Changeset` validation
183
+ errors. See the `:message` option of most `Ecto.Changeset` validation
184
+ functions for how to customize error messaging on a per `Ecto.Changeset` basis.
185
+ """
186
+ @callback format(params()) :: String.t()
187
+
188
+ @optional_callbacks autogenerate: 1, format: 1
189
+
190
+ @doc """
191
+ Inits a parameterized type given by `type` with `opts`.
192
+
193
+ Useful when manually initializing a type for schemaless changesets.
194
+ """
195
+ def init(type, opts) do
196
+ {:parameterized, {type, type.init(opts)}}
197
+ end
198
+
199
+ @doc false
200
+ defmacro __using__(_) do
201
+ quote location: :keep do
202
+ @behaviour Ecto.ParameterizedType
203
+
204
+ @doc false
205
+ def embed_as(_, _), do: :self
206
+
207
+ @doc false
208
+ def equal?(term1, term2, _params), do: term1 == term2
209
+
210
+ defoverridable embed_as: 2, equal?: 3
211
+ end
212
+ end
213
+ end
deps/ecto/lib/ecto/query.ex ADDED
The diff for this file is too large to render. See raw diff
 
deps/ecto/lib/ecto/query/api.ex ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Query.API do
2
+ @moduledoc """
3
+ Lists all functions allowed in the query API.
4
+
5
+ * Comparison operators: `==`, `!=`, `<=`, `>=`, `<`, `>`
6
+ * Arithmetic operators: `+`, `-`, `*`, `/`
7
+ * Boolean operators: `and`, `or`, `not`
8
+ * Inclusion operator: `in/2`
9
+ * Subquery operators: `any`, `all` and `exists`
10
+ * Search functions: `like/2` and `ilike/2`
11
+ * Null check functions: `is_nil/1`
12
+ * Aggregates: `count/0`, `count/1`, `avg/1`, `sum/1`, `min/1`, `max/1`
13
+ * Date/time intervals: `datetime_add/3`, `date_add/3`, `from_now/2`, `ago/2`
14
+ * Inside select: `struct/2`, `map/2`, `merge/2`, `selected_as/2` and literals (map, tuples, lists, etc)
15
+ * General: `fragment/1`, `field/2`, `type/2`, `as/1`, `parent_as/1`, `selected_as/1`
16
+
17
+ Note the functions in this module exist for documentation
18
+ purposes and one should never need to invoke them directly.
19
+ Furthermore, it is possible to define your own macros and
20
+ use them in Ecto queries (see docs for `fragment/1`).
21
+
22
+ ## Intervals
23
+
24
+ Ecto supports following values for `interval` option: `"year"`, `"month"`,
25
+ `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`, `"millisecond"`, and
26
+ `"microsecond"`.
27
+
28
+ `Date`/`Time` functions like `datetime_add/3`, `date_add/3`, `from_now/2`,
29
+ `ago/2` take `interval` as an argument.
30
+
31
+ ## Window API
32
+
33
+ Ecto also supports many of the windows functions found
34
+ in SQL databases. See `Ecto.Query.WindowAPI` for more
35
+ information.
36
+
37
+ ## About the arithmetic operators
38
+
39
+ The Ecto implementation of these operators provide only
40
+ a thin layer above the adapters. So if your adapter allows you
41
+ to use them in a certain way (like adding a date and an
42
+ interval in PostgreSQL), it should work just fine in Ecto
43
+ queries.
44
+ """
45
+
46
+ @dialyzer :no_return
47
+
48
+ @doc """
49
+ Binary `==` operation.
50
+ """
51
+ def left == right, do: doc!([left, right])
52
+
53
+ @doc """
54
+ Binary `!=` operation.
55
+ """
56
+ def left != right, do: doc!([left, right])
57
+
58
+ @doc """
59
+ Binary `<=` operation.
60
+ """
61
+ def left <= right, do: doc!([left, right])
62
+
63
+ @doc """
64
+ Binary `>=` operation.
65
+ """
66
+ def left >= right, do: doc!([left, right])
67
+
68
+ @doc """
69
+ Binary `<` operation.
70
+ """
71
+ def left < right, do: doc!([left, right])
72
+
73
+ @doc """
74
+ Binary `>` operation.
75
+ """
76
+ def left > right, do: doc!([left, right])
77
+
78
+ @doc """
79
+ Binary `+` operation.
80
+ """
81
+ def left + right, do: doc!([left, right])
82
+
83
+ @doc """
84
+ Binary `-` operation.
85
+ """
86
+ def left - right, do: doc!([left, right])
87
+
88
+ @doc """
89
+ Binary `*` operation.
90
+ """
91
+ def left * right, do: doc!([left, right])
92
+
93
+ @doc """
94
+ Binary `/` operation.
95
+ """
96
+ def left / right, do: doc!([left, right])
97
+
98
+ @doc """
99
+ Binary `and` operation.
100
+ """
101
+ def left and right, do: doc!([left, right])
102
+
103
+ @doc """
104
+ Binary `or` operation.
105
+ """
106
+ def left or right, do: doc!([left, right])
107
+
108
+ @doc """
109
+ Unary `not` operation.
110
+
111
+ It is used to negate values in `:where`. It is also used to match
112
+ the assert the opposite of `in/2`, `is_nil/1`, and `exists/1`.
113
+ For example:
114
+
115
+ from p in Post, where: p.id not in [1, 2, 3]
116
+
117
+ from p in Post, where: not is_nil(p.title)
118
+
119
+ # Retrieve all the posts that doesn't have comments.
120
+ from p in Post,
121
+ as: :post,
122
+ where:
123
+ not exists(
124
+ from(
125
+ c in Comment,
126
+ where: parent_as(:post).id == c.post_id
127
+ )
128
+ )
129
+
130
+ """
131
+ def not value, do: doc!([value])
132
+
133
+ @doc """
134
+ Checks if the left-value is included in the right one.
135
+
136
+ from p in Post, where: p.id in [1, 2, 3]
137
+
138
+ The right side may either be a literal list, an interpolated list,
139
+ any struct that implements the `Enumerable` protocol, or even a
140
+ column in the database with array type:
141
+
142
+ from p in Post, where: "elixir" in p.tags
143
+
144
+ Additionally, the right side may also be a subquery, which should return
145
+ a single column:
146
+
147
+ from c in Comment, where: c.post_id in subquery(
148
+ from(p in Post, where: p.created_at > ^since, select: p.id)
149
+ )
150
+ """
151
+ def left in right, do: doc!([left, right])
152
+
153
+ @doc """
154
+ Evaluates to true if the provided subquery returns 1 or more rows.
155
+
156
+ from p in Post,
157
+ as: :post,
158
+ where:
159
+ exists(
160
+ from(
161
+ c in Comment,
162
+ where: parent_as(:post).id == c.post_id and c.replies_count > 5,
163
+ select: 1
164
+ )
165
+ )
166
+
167
+ This is best used in conjunction with `parent_as` to correlate the subquery
168
+ with the parent query to test some condition on related rows in a different table.
169
+ In the above example the query returns posts which have at least one comment that
170
+ has more than 5 replies.
171
+ """
172
+ def exists(subquery), do: doc!([subquery])
173
+
174
+ @doc """
175
+ Tests whether one or more values returned from the provided subquery match in a comparison operation.
176
+
177
+ from p in Product, where: p.id == any(
178
+ from(li in LineItem, select: [li.product_id], where: li.created_at > ^since and li.qty >= 10)
179
+ )
180
+
181
+ A product matches in the above example if a line item was created since the provided date where the customer purchased
182
+ at least 10 units.
183
+
184
+ Both `any` and `all` must be given a subquery as an argument, and they must be used on the right hand side of a comparison.
185
+ Both can be used with every comparison operator: `==`, `!=`, `>`, `>=`, `<`, `<=`.
186
+ """
187
+ def any(subquery), do: doc!([subquery])
188
+
189
+ @doc """
190
+ Evaluates whether all values returned from the provided subquery match in a comparison operation.
191
+
192
+ from p in Post, where: p.visits >= all(
193
+ from(p in Post, select: avg(p.visits), group_by: [p.category_id])
194
+ )
195
+
196
+ For a post to match in the above example it must be visited at least as much as the average post in all categories.
197
+
198
+ from p in Post, where: p.visits == all(
199
+ from(p in Post, select: max(p.visits))
200
+ )
201
+
202
+ The above example matches all the posts which are tied for being the most visited.
203
+
204
+ Both `any` and `all` must be given a subquery as an argument, and they must be used on the right hand side of a comparison.
205
+ Both can be used with every comparison operator: `==`, `!=`, `>`, `>=`, `<`, `<=`.
206
+ """
207
+ def all(subquery), do: doc!([subquery])
208
+
209
+ @doc """
210
+ Searches for `search` in `string`.
211
+
212
+ from p in Post, where: like(p.body, "Chapter%")
213
+
214
+ Translates to the underlying SQL LIKE query, therefore
215
+ its behaviour is dependent on the database. In particular,
216
+ PostgreSQL will do a case-sensitive operation, while the
217
+ majority of other databases will be case-insensitive. For
218
+ performing a case-insensitive `like` in PostgreSQL, see `ilike/2`.
219
+
220
+ You should be very careful when allowing user sent data to be used
221
+ as part of LIKE query, since they allow to perform
222
+ [LIKE-injections](https://githubengineering.com/like-injection/).
223
+ """
224
+ def like(string, search), do: doc!([string, search])
225
+
226
+ @doc """
227
+ Searches for `search` in `string` in a case insensitive fashion.
228
+
229
+ from p in Post, where: ilike(p.body, "Chapter%")
230
+
231
+ Translates to the underlying SQL ILIKE query. This operation is
232
+ only available on PostgreSQL.
233
+ """
234
+ def ilike(string, search), do: doc!([string, search])
235
+
236
+ @doc """
237
+ Checks if the given value is nil.
238
+
239
+ from p in Post, where: is_nil(p.published_at)
240
+
241
+ To check if a given value is not nil use:
242
+
243
+ from p in Post, where: not is_nil(p.published_at)
244
+ """
245
+ def is_nil(value), do: doc!([value])
246
+
247
+ @doc """
248
+ Counts the entries in the table.
249
+
250
+ from p in Post, select: count()
251
+ """
252
+ def count, do: doc!([])
253
+
254
+ @doc """
255
+ Counts the given entry.
256
+
257
+ from p in Post, select: count(p.id)
258
+ """
259
+ def count(value), do: doc!([value])
260
+
261
+ @doc """
262
+ Counts the distinct values in given entry.
263
+
264
+ from p in Post, select: count(p.id, :distinct)
265
+ """
266
+ def count(value, :distinct), do: doc!([value, :distinct])
267
+
268
+ @doc """
269
+ Takes the first value which is not null, or null if they both are.
270
+
271
+ In SQL, COALESCE takes any number of arguments, but in ecto
272
+ it only takes two, so it must be chained to achieve the same
273
+ effect.
274
+
275
+ from p in Payment, select: p.value |> coalesce(p.backup_value) |> coalesce(0)
276
+ """
277
+ def coalesce(value, expr), do: doc!([value, expr])
278
+
279
+ @doc """
280
+ Applies the given expression as a FILTER clause against an
281
+ aggregate. This is currently only supported by Postgres.
282
+
283
+ from p in Payment, select: filter(avg(p.value), p.value > 0 and p.value < 100)
284
+
285
+ from p in Payment, select: avg(p.value) |> filter(p.value < 0)
286
+ """
287
+ def filter(value, filter), do: doc!([value, filter])
288
+
289
+ @doc """
290
+ Calculates the average for the given entry.
291
+
292
+ from p in Payment, select: avg(p.value)
293
+ """
294
+ def avg(value), do: doc!([value])
295
+
296
+ @doc """
297
+ Calculates the sum for the given entry.
298
+
299
+ from p in Payment, select: sum(p.value)
300
+ """
301
+ def sum(value), do: doc!([value])
302
+
303
+ @doc """
304
+ Calculates the minimum for the given entry.
305
+
306
+ from p in Payment, select: min(p.value)
307
+ """
308
+ def min(value), do: doc!([value])
309
+
310
+ @doc """
311
+ Calculates the maximum for the given entry.
312
+
313
+ from p in Payment, select: max(p.value)
314
+ """
315
+ def max(value), do: doc!([value])
316
+
317
+ @doc """
318
+ Adds a given interval to a datetime.
319
+
320
+ The first argument is a `datetime`, the second one is the count
321
+ for the interval, which may be either positive or negative and
322
+ the interval value:
323
+
324
+ # Get all items published since the last month
325
+ from p in Post, where: p.published_at >
326
+ datetime_add(^NaiveDateTime.utc_now(), -1, "month")
327
+
328
+ In the example above, we used `datetime_add/3` to subtract one month
329
+ from the current datetime and compared it with the `p.published_at`.
330
+ If you want to perform operations on date, `date_add/3` could be used.
331
+
332
+ See [Intervals](#module-intervals) for supported `interval` values.
333
+ """
334
+ def datetime_add(datetime, count, interval), do: doc!([datetime, count, interval])
335
+
336
+ @doc """
337
+ Adds a given interval to a date.
338
+
339
+ See `datetime_add/3` for more information.
340
+
341
+ See [Intervals](#module-intervals) for supported `interval` values.
342
+ """
343
+ def date_add(date, count, interval), do: doc!([date, count, interval])
344
+
345
+ @doc """
346
+ Adds the given interval to the current time in UTC.
347
+
348
+ The current time in UTC is retrieved from Elixir and
349
+ not from the database.
350
+
351
+ See [Intervals](#module-intervals) for supported `interval` values.
352
+
353
+ ## Examples
354
+
355
+ from a in Account, where: a.expires_at < from_now(3, "month")
356
+
357
+ """
358
+ def from_now(count, interval), do: doc!([count, interval])
359
+
360
+ @doc """
361
+ Subtracts the given interval from the current time in UTC.
362
+
363
+ The current time in UTC is retrieved from Elixir and
364
+ not from the database.
365
+
366
+ See [Intervals](#module-intervals) for supported `interval` values.
367
+
368
+ ## Examples
369
+
370
+ from p in Post, where: p.published_at > ago(3, "month")
371
+ """
372
+ def ago(count, interval), do: doc!([count, interval])
373
+
374
+ @doc """
375
+ Send fragments directly to the database.
376
+
377
+ It is not possible to represent all possible database queries using
378
+ Ecto's query syntax. When such is required, it is possible to use
379
+ fragments to send any expression to the database:
380
+
381
+ def unpublished_by_title(title) do
382
+ from p in Post,
383
+ where: is_nil(p.published_at) and
384
+ fragment("lower(?)", p.title) == ^title
385
+ end
386
+
387
+ Every occurrence of the `?` character will be interpreted as a place
388
+ for parameters, which must be given as additional arguments to
389
+ `fragment`. If the literal character `?` is required as part of the
390
+ fragment, it can be escaped with `\\\\?` (one escape for strings,
391
+ another for fragment).
392
+
393
+ In the example above, we are using the lower procedure in the
394
+ database to downcase the title column.
395
+
396
+ It is very important to keep in mind that Ecto is unable to do any
397
+ type casting when fragments are used. Therefore it may be necessary
398
+ to explicitly cast parameters via `type/2`:
399
+
400
+ fragment("lower(?)", p.title) == type(^title, :string)
401
+
402
+ ## Literals
403
+
404
+ Sometimes you need to interpolate a literal value into a fragment,
405
+ instead of a parameter. For example, you may need to pass a table
406
+ name or a collation, such as:
407
+
408
+ collation = "es_ES"
409
+ fragment("? COLLATE ?", ^name, ^collation)
410
+
411
+ The example above won't work because `collation` will be passed
412
+ as a parameter, while it has to be a literal part of the query.
413
+
414
+ You can address this by telling Ecto that variable is a literal:
415
+
416
+ fragment("? COLLATE ?", ^name, literal(^collation))
417
+
418
+ Ecto will then escape it and make it part of the query.
419
+
420
+ > #### Literals and query caching {: .warning}
421
+ >
422
+ > Because literals are made part of the query, each interpolated
423
+ > literal will generate a separate query, with its own cache.
424
+
425
+ ## Splicing
426
+
427
+ Sometimes you may need to interpolate a variable number of arguments
428
+ into the same fragment. For example, when overriding Ecto's default
429
+ `where` behaviour for Postgres:
430
+
431
+ from p in Post, where: fragment("? in (?, ?)", p.id, val1, val2)
432
+
433
+ The example above will only work if you know the number of arguments
434
+ upfront. If it can vary, the above will not work.
435
+
436
+ You can address this by telling Ecto to splice a list argument into
437
+ the fragment:
438
+
439
+ from p in Post, where: fragment("? in (?)", p.id, splice(^val_list))
440
+
441
+ This will let Ecto know it should expand the values of the list into
442
+ separate fragment arguments. For example:
443
+
444
+ from p in Post, where: fragment("? in (?)", p.id, splice(^[1, 2, 3]))
445
+
446
+ would be expanded into
447
+
448
+ from p in Post, where: fragment("? in (?,?,?)", p.id, ^1, ^2, ^3)
449
+
450
+ ## Defining custom functions using macros and fragment
451
+
452
+ You can add a custom Ecto query function using macros. For example
453
+ to expose SQL's coalesce function you can define this macro:
454
+
455
+ defmodule CustomFunctions do
456
+ defmacro coalesce(left, right) do
457
+ quote do
458
+ fragment("coalesce(?, ?)", unquote(left), unquote(right))
459
+ end
460
+ end
461
+ end
462
+
463
+ To have coalesce/2 available, just import the module that defines it.
464
+
465
+ import CustomFunctions
466
+
467
+ The only downside is that it will show up as a fragment when
468
+ inspecting the Elixir query. Other than that, it should be
469
+ equivalent to a built-in Ecto query function.
470
+
471
+ ## Keyword fragments
472
+
473
+ In order to support databases that do not have string-based
474
+ queries, like MongoDB, fragments also allow keywords to be given:
475
+
476
+ from p in Post,
477
+ where: fragment(title: ["$eq": ^some_value])
478
+
479
+ """
480
+ def fragment(fragments), do: doc!([fragments])
481
+
482
+ @doc """
483
+ Allows a literal identifier to be injected into a fragment:
484
+
485
+ collation = "es_ES"
486
+ fragment("? COLLATE ?", ^name, literal(^collation))
487
+
488
+ The example above will inject `collation` into the query as
489
+ a literal identifier instead of a query parameter. Note that
490
+ each different value of `collation` will emit a different query,
491
+ which will be independently prepared and cached.
492
+ """
493
+ def literal(binary), do: doc!([binary])
494
+
495
+ @doc """
496
+ Allows a list argument to be spliced into a fragment.
497
+
498
+ from p in Post, where: fragment("? in (?)", p.id, splice(^[1, 2, 3]))
499
+
500
+ The example above will be transformed at runtime into the following:
501
+
502
+ from p in Post, where: fragment("? in (?,?,?)", p.id, ^1, ^2, ^3)
503
+
504
+ You may only splice runtime values. For example, this would not work because
505
+ query bindings are compile-time constructs:
506
+
507
+ from p in Post, where: fragment("concat(?)", splice(^[p.count, " ", "count"])
508
+ """
509
+ def splice(list), do: doc!([list])
510
+
511
+ @doc """
512
+ Creates a values list/constant table.
513
+
514
+ A values list can be used as a source in a query, both in `Ecto.Query.from/2`
515
+ and `Ecto.Query.join/5`.
516
+
517
+ The first argument is a list of maps representing the values of the constant table.
518
+ An error is raised if the list is empty or if every map does not have exactly the
519
+ same fields.
520
+
521
+ The second argument is a map of types corresponding to the fields in the first argument.
522
+ Each field must be given a type or an error is raised. Any type that can be specified in
523
+ a schema may be used.
524
+
525
+ Queries using a values list are not cacheable by Ecto.
526
+
527
+ ## Select example
528
+
529
+ values = [%{id: 1, text: "abc"}, %{id: 2, text: "xyz"}]
530
+ types = %{id: :integer, text: :string}
531
+
532
+ query =
533
+ from v1 in values(values, types),
534
+ join: v2 in values(values, types),
535
+ on: v1.id == v2.id
536
+
537
+ Repo.all(query)
538
+
539
+ ## Delete example
540
+ values = [%{id: 1, text: "abc"}, %{id: 2, text: "xyz"}]
541
+ types = %{id: :integer, text: :string}
542
+
543
+ query =
544
+ from p in Post,
545
+ join: v in values(values, types),
546
+ on: p.id == v.id,
547
+ where: p.counter == ^0
548
+
549
+ Repo.delete_all(query)
550
+
551
+ ## Update example
552
+ values = [%{id: 1, text: "abc"}, %{id: 2, text: "xyz"}]
553
+ types = %{id: :integer, text: :string}
554
+
555
+ query =
556
+ from p in Post,
557
+ join: v in values(values, types),
558
+ on: p.id == v.id,
559
+ update: [set: [text: v.text]]
560
+
561
+ Repo.update_all(query, [])
562
+ """
563
+ def values(values, types), do: doc!([values, types])
564
+
565
+ @doc """
566
+ Allows a field to be dynamically accessed.
567
+
568
+ def at_least_four(doors_or_tires) do
569
+ from c in Car,
570
+ where: field(c, ^doors_or_tires) >= 4
571
+ end
572
+
573
+ In the example above, both `at_least_four(:doors)` and `at_least_four(:tires)`
574
+ would be valid calls as the field is dynamically generated.
575
+ """
576
+ def field(source, field), do: doc!([source, field])
577
+
578
+ @doc """
579
+ Used in `select` to specify which struct fields should be returned.
580
+
581
+ For example, if you don't need all fields to be returned
582
+ as part of a struct, you can filter it to include only certain
583
+ fields by using `struct/2`:
584
+
585
+ from p in Post,
586
+ select: struct(p, [:title, :body])
587
+
588
+ `struct/2` can also be used to dynamically select fields:
589
+
590
+ fields = [:title, :body]
591
+ from p in Post, select: struct(p, ^fields)
592
+
593
+ As a convenience, `select` allows developers to take fields
594
+ without an explicit call to `struct/2`:
595
+
596
+ from p in Post, select: [:title, :body]
597
+
598
+ Or even dynamically:
599
+
600
+ fields = [:title, :body]
601
+ from p in Post, select: ^fields
602
+
603
+ For preloads, the selected fields may be specified from the parent:
604
+
605
+ from(city in City, preload: :country,
606
+ select: struct(city, [:country_id, :name, country: [:id, :population]]))
607
+
608
+ If the same source is selected multiple times with a `struct`,
609
+ the fields are merged in order to avoid fetching multiple copies
610
+ from the database. In other words, the expression below:
611
+
612
+ from(city in City, preload: :country,
613
+ select: {struct(city, [:country_id]), struct(city, [:name])})
614
+
615
+ is expanded to:
616
+
617
+ from(city in City, preload: :country,
618
+ select: {struct(city, [:country_id, :name]), struct(city, [:country_id, :name])})
619
+
620
+ **IMPORTANT**: When filtering fields for associations, you
621
+ MUST include the foreign keys used in the relationship,
622
+ otherwise Ecto will be unable to find associated records.
623
+ """
624
+ def struct(source, fields), do: doc!([source, fields])
625
+
626
+ @doc """
627
+ Used in `select` to specify which fields should be returned as a map.
628
+
629
+ For example, if you don't need all fields to be returned or
630
+ neither need a struct, you can use `map/2` to achieve both:
631
+
632
+ from p in Post,
633
+ select: map(p, [:title, :body])
634
+
635
+ `map/2` can also be used to dynamically select fields:
636
+
637
+ fields = [:title, :body]
638
+ from p in Post, select: map(p, ^fields)
639
+
640
+ If the same source is selected multiple times with a `map`,
641
+ the fields are merged in order to avoid fetching multiple copies
642
+ from the database. In other words, the expression below:
643
+
644
+ from(city in City, preload: :country,
645
+ select: {map(city, [:country_id]), map(city, [:name])})
646
+
647
+ is expanded to:
648
+
649
+ from(city in City, preload: :country,
650
+ select: {map(city, [:country_id, :name]), map(city, [:country_id, :name])})
651
+
652
+ For preloads, the selected fields may be specified from the parent:
653
+
654
+ from(city in City, preload: :country,
655
+ select: map(city, [:country_id, :name, country: [:id, :population]]))
656
+
657
+ It's also possible to select a struct from one source but only a subset of
658
+ fields from one of its associations:
659
+
660
+ from(city in City, preload: :country,
661
+ select: %{city | country: map(country: [:id, :population])})
662
+
663
+ **IMPORTANT**: When filtering fields for associations, you
664
+ MUST include the foreign keys used in the relationship,
665
+ otherwise Ecto will be unable to find associated records.
666
+ """
667
+ def map(source, fields), do: doc!([source, fields])
668
+
669
+ @doc """
670
+ Merges the map on the right over the map on the left.
671
+
672
+ If the map on the left side is a struct, Ecto will check
673
+ all of the field on the right previously exist on the left
674
+ before merging.
675
+
676
+ from(city in City, select: merge(city, %{virtual_field: "some_value"}))
677
+
678
+ This function is primarily used by `Ecto.Query.select_merge/3`
679
+ to merge different select clauses.
680
+ """
681
+ def merge(left_map, right_map), do: doc!([left_map, right_map])
682
+
683
+ @doc """
684
+ Returns value from the `json_field` pointed to by `path`.
685
+
686
+ from(post in Post, select: json_extract_path(post.meta, ["author", "name"]))
687
+
688
+ The path can be dynamic:
689
+
690
+ path = ["author", "name"]
691
+ from(post in Post, select: json_extract_path(post.meta, ^path))
692
+
693
+ And the field can also be dynamic in combination with it:
694
+
695
+ path = ["author", "name"]
696
+ from(post in Post, select: json_extract_path(field(post, :meta), ^path))
697
+
698
+ The query can be also rewritten as:
699
+
700
+ from(post in Post, select: post.meta["author"]["name"])
701
+
702
+ Path elements can be integers to access values in JSON arrays:
703
+
704
+ from(post in Post, select: post.meta["tags"][0]["name"])
705
+
706
+ Any element of the path can be dynamic:
707
+
708
+ field = "name"
709
+ from(post in Post, select: post.meta["author"][^field])
710
+
711
+ ## Warning: indexes on PostgreSQL
712
+
713
+ PostgreSQL supports indexing on jsonb columns via GIN indexes.
714
+ Whenever comparing the value of a jsonb field against a string
715
+ or integer, Ecto will use the containment operator @> which
716
+ is optimized. You can even use the more efficient `jsonb_path_ops`
717
+ GIN index variant. For more information, consult PostgreSQL's docs
718
+ on [JSON indexing](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING).
719
+
720
+ ## Warning: return types
721
+
722
+ The underlying data in the JSON column is returned without any
723
+ additional decoding. This means "null" JSON values are not the
724
+ same as SQL's "null". For example, the `Repo.all` operation below
725
+ returns an empty list because `p.meta["author"]` returns JSON's
726
+ null and therefore `is_nil` does not succeed:
727
+
728
+ Repo.insert!(%Post{meta: %{author: nil}})
729
+ Repo.all(from(post in Post, where: is_nil(p.meta["author"])))
730
+
731
+ Similarly, other types, such as datetimes, are returned as strings.
732
+ This means conditions like `post.meta["published_at"] > from_now(-1, "day")`
733
+ may return incorrect results or fail as the underlying database
734
+ tries to compare incompatible types. You can, however, use `type/2`
735
+ to force the types on the database level.
736
+ """
737
+ def json_extract_path(json_field, path), do: doc!([json_field, path])
738
+
739
+ @doc """
740
+ Casts the given value to the given type at the database level.
741
+
742
+ Most of the times, Ecto is able to proper cast interpolated
743
+ values due to its type checking mechanism. In some situations
744
+ though, you may want to tell Ecto that a parameter has some
745
+ particular type:
746
+
747
+ type(^title, :string)
748
+
749
+ It is also possible to say the type must match the same of a column:
750
+
751
+ type(^title, p.title)
752
+
753
+ Or a parameterized type, which must be previously initialized
754
+ with `Ecto.ParameterizedType.init/2`:
755
+
756
+ @my_enum Ecto.ParameterizedType.init(Ecto.Enum, values: [:foo, :bar, :baz])
757
+ type(^title, ^@my_enum)
758
+
759
+ Ecto will ensure `^title` is cast to the given type and enforce such
760
+ type at the database level. If the value is returned in a `select`,
761
+ Ecto will also enforce the proper type throughout.
762
+
763
+ When performing arithmetic operations, `type/2` can be used to cast
764
+ all the parameters in the operation to the same type:
765
+
766
+ from p in Post,
767
+ select: type(p.visits + ^a_float + ^a_integer, :decimal)
768
+
769
+ Inside `select`, `type/2` can also be used to cast fragments:
770
+
771
+ type(fragment("NOW"), :naive_datetime)
772
+
773
+ Or to type fields from schemaless queries:
774
+
775
+ from p in "posts", select: type(p.cost, :decimal)
776
+
777
+ Or to type aggregation results:
778
+
779
+ from p in Post, select: type(avg(p.cost), :integer)
780
+ from p in Post, select: type(filter(avg(p.cost), p.cost > 0), :integer)
781
+
782
+ Or to type comparison expression results:
783
+
784
+ from p in Post, select: type(coalesce(p.cost, 0), :integer)
785
+
786
+ Or to type fields from a parent query using `parent_as/1`:
787
+
788
+ child = from c in Comment, where: type(parent_as(:posts).id, :string) == c.text
789
+ from Post, as: :posts, inner_lateral_join: c in subquery(child), select: c.text
790
+
791
+ ## `type` vs `fragment`
792
+
793
+ `type/2` is all about Ecto types. Therefore, you can perform `type(expr, :string)`
794
+ but not `type(expr, :text)`, because `:text` is not an actual Ecto type. If you want
795
+ to perform casting exclusively at the database level, you can use fragment. For example,
796
+ in PostgreSQL, you might do `fragment("?::text", p.column)`.
797
+ """
798
+ def type(interpolated_value, type), do: doc!([interpolated_value, type])
799
+
800
+ @doc """
801
+ Refer to a named atom binding.
802
+
803
+ See the "Named bindings" section in `Ecto.Query` for more information.
804
+ """
805
+ def as(binding), do: doc!([binding])
806
+
807
+ @doc """
808
+ Refer to a named atom binding in the parent query.
809
+
810
+ This is available only inside subqueries.
811
+
812
+ See the "Named bindings" section in `Ecto.Query` for more information.
813
+ """
814
+ def parent_as(binding), do: doc!([binding])
815
+
816
+ @doc """
817
+ Refer to an alias of a selected value.
818
+
819
+ This can be used to refer to aliases created using `selected_as/2`. If
820
+ the alias hasn't been created using `selected_as/2`, an error will be raised.
821
+
822
+ Each database has its own rules governing which clauses can reference these aliases.
823
+ If an error is raised mentioning an unknown column, most likely the alias is being
824
+ referenced somewhere that is not allowed. Consult the documentation for the database
825
+ to ensure the alias is being referenced correctly.
826
+ """
827
+ def selected_as(name), do: doc!([name])
828
+
829
+ @doc """
830
+ Creates an alias for the given selected value.
831
+
832
+ When working with calculated values, an alias can be used to simplify
833
+ the query. Otherwise, the entire expression would need to be copied when
834
+ referencing it outside of select statements.
835
+
836
+ This comes in handy when, for instance, you would like to use the calculated
837
+ value in `Ecto.Query.group_by/3` or `Ecto.Query.order_by/3`:
838
+
839
+ from p in Post,
840
+ select: %{
841
+ posted: selected_as(p.posted, :date),
842
+ sum_visits: p.visits |> coalesce(0) |> sum() |> selected_as(:sum_visits)
843
+ },
844
+ group_by: selected_as(:date),
845
+ order_by: selected_as(:sum_visits)
846
+
847
+ The name of the alias must be an atom and it can only be used in the outer most
848
+ select expression, otherwise an error is raised. Please note that the alias name
849
+ does not have to match the key when `select` returns a map, struct or keyword list.
850
+
851
+ Using this in conjunction with `selected_as/1` is recommended to ensure only defined aliases
852
+ are referenced.
853
+
854
+ ## Subqueries and CTEs
855
+
856
+ Subqueries and CTEs automatically alias the selected fields, for example, one can write:
857
+
858
+ # Subquery
859
+ s = from p in Post, select: %{visits: coalesce(p.visits, 0)}
860
+ from(s in subquery(s), select: s.visits)
861
+
862
+ # CTE
863
+ cte_query = from p in Post, select: %{visits: coalesce(p.visits, 0)}
864
+ Post |> with_cte("cte", as: ^cte_query) |> join(:inner, [p], c in "cte") |> select([p, c], c.visits)
865
+
866
+ However, one can also use `selected_as` to override the default naming:
867
+
868
+ # Subquery
869
+ s = from p in Post, select: %{visits: coalesce(p.visits, 0) |> selected_as(:num_visits)}
870
+ from(s in subquery(s), select: s.num_visits)
871
+
872
+ # CTE
873
+ cte_query = from p in Post, select: %{visits: coalesce(p.visits, 0) |> selected_as(:num_visits)}
874
+ Post |> with_cte("cte", as: ^cte_query) |> join(:inner, [p], c in "cte") |> select([p, c], c.num_visits)
875
+
876
+ The name given to `selected_as/2` can also be referenced in `selected_as/1`,
877
+ as in regular queries.
878
+ """
879
+ def selected_as(selected_value, name), do: doc!([selected_value, name])
880
+
881
+ defp doc!(_) do
882
+ raise "the functions in Ecto.Query.API should not be invoked directly, " <>
883
+ "they serve for documentation purposes only"
884
+ end
885
+ end
deps/ecto/lib/ecto/query/builder.ex ADDED
@@ -0,0 +1,1542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Query.Builder do
2
+ @moduledoc false
3
+
4
+ alias Ecto.Query
5
+
6
+ @comparisons [
7
+ is_nil: 1,
8
+ ==: 2,
9
+ !=: 2,
10
+ <: 2,
11
+ >: 2,
12
+ <=: 2,
13
+ >=: 2
14
+ ]
15
+
16
+ @dynamic_aggregates [
17
+ max: 1,
18
+ min: 1,
19
+ first_value: 1,
20
+ last_value: 1,
21
+ nth_value: 2,
22
+ lag: 3,
23
+ lead: 3,
24
+ lag: 2,
25
+ lead: 2,
26
+ lag: 1,
27
+ lead: 1
28
+ ]
29
+
30
+ @static_aggregates [
31
+ count: {0, :integer},
32
+ count: {1, :integer},
33
+ count: {2, :integer},
34
+ avg: {1, :any},
35
+ sum: {1, :any},
36
+ row_number: {0, :integer},
37
+ rank: {0, :integer},
38
+ dense_rank: {0, :integer},
39
+ percent_rank: {0, :any},
40
+ cume_dist: {0, :any},
41
+ ntile: {1, :integer}
42
+ ]
43
+
44
+ @select_alias_dummy_value []
45
+
46
+ @typedoc """
47
+ Quoted types store primitive types and types in the format
48
+ {source, quoted}. The latter are handled directly in the planner,
49
+ never forwarded to Ecto.Type.
50
+
51
+ The Ecto.Type module concerns itself only with runtime types,
52
+ which include all primitive types and custom user types. Also
53
+ note custom user types do not show up during compilation time.
54
+ """
55
+ @type quoted_type :: Ecto.Type.primitive() | {non_neg_integer, atom | Macro.t()}
56
+
57
+ @typedoc """
58
+ The accumulator during escape.
59
+
60
+ If the subqueries field is available, subquery escaping must take place.
61
+ """
62
+ @type acc :: %{
63
+ optional(:subqueries) => list(Macro.t()),
64
+ optional(:take) => %{non_neg_integer => Macro.t()},
65
+ optional(any) => any
66
+ }
67
+
68
+ @doc """
69
+ Smart escapes a query expression and extracts interpolated values in
70
+ a map.
71
+
72
+ Everything that is a query expression will be escaped, interpolated
73
+ expressions (`^foo`) will be moved to a map unescaped and replaced
74
+ with `^index` in the query where index is a number indexing into the
75
+ map.
76
+ """
77
+ @spec escape(
78
+ Macro.t(),
79
+ quoted_type | {:in, quoted_type} | {:out, quoted_type} | {:splice, quoted_type},
80
+ {list, acc},
81
+ Keyword.t(),
82
+ Macro.Env.t() | {Macro.Env.t(), fun}
83
+ ) :: {Macro.t(), {list, acc}}
84
+ def escape(expr, type, params_acc, vars, env)
85
+
86
+ # var.x - where var is bound
87
+ def escape({{:., _, [callee, field]}, _, []}, _type, params_acc, vars, _env)
88
+ when is_atom(field) do
89
+ {escape_field!(callee, field, vars), params_acc}
90
+ end
91
+
92
+ # field macro
93
+ def escape({:field, _, [callee, field]}, _type, params_acc, vars, _env) do
94
+ {escape_field!(callee, field, vars), params_acc}
95
+ end
96
+
97
+ # param interpolation
98
+ def escape({:^, _, [arg]}, type, {params, acc}, _vars, _env) do
99
+ expr = {:{}, [], [:^, [], [length(params)]]}
100
+ params = [{arg, type} | params]
101
+ {expr, {params, acc}}
102
+ end
103
+
104
+ # tagged types
105
+ def escape({:type, _, [{:^, _, [arg]}, type]}, _type, {params, acc}, vars, env) do
106
+ type = validate_type!(type, vars, env)
107
+ expr = {:{}, [], [:type, [], [{:{}, [], [:^, [], [length(params)]]}, type]]}
108
+ params = [{arg, type} | params]
109
+ {expr, {params, acc}}
110
+ end
111
+
112
+ def escape(
113
+ {:type, _, [{{:., _, [{var, _, context}, field]}, _, []} = expr, type]},
114
+ _type,
115
+ params_acc,
116
+ vars,
117
+ env
118
+ )
119
+ when is_atom(var) and is_atom(context) and is_atom(field) do
120
+ escape_with_type(expr, type, params_acc, vars, env)
121
+ end
122
+
123
+ def escape({:type, _, [{:coalesce, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) do
124
+ escape_with_type(expr, type, params_acc, vars, env)
125
+ end
126
+
127
+ def escape({:type, _, [{:field, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) do
128
+ escape_with_type(expr, type, params_acc, vars, env)
129
+ end
130
+
131
+ def escape({:type, _, [{math_op, _, [_, _]} = op_expr, type]}, _type, params_acc, vars, env)
132
+ when math_op in ~w(+ - * /)a do
133
+ escape_with_type(op_expr, type, params_acc, vars, env)
134
+ end
135
+
136
+ def escape({:type, _, [{fun, _, args} = expr, type]}, _type, params_acc, vars, env)
137
+ when is_list(args) and fun in ~w(fragment avg count max min sum over filter)a do
138
+ escape_with_type(expr, type, params_acc, vars, env)
139
+ end
140
+
141
+ def escape(
142
+ {:type, _, [{:json_extract_path, _, [_ | _]} = expr, type]},
143
+ _type,
144
+ params_acc,
145
+ vars,
146
+ env
147
+ ) do
148
+ escape_with_type(expr, type, params_acc, vars, env)
149
+ end
150
+
151
+ def escape(
152
+ {:type, _, [{{:., _, [Access, :get]}, _, _} = access_expr, type]},
153
+ _type,
154
+ params_acc,
155
+ vars,
156
+ env
157
+ ) do
158
+ escape_with_type(access_expr, type, params_acc, vars, env)
159
+ end
160
+
161
+ def escape(
162
+ {:type, _, [{{:., _, [{:parent_as, _, [_parent]}, _field]}, _, []} = expr, type]},
163
+ _type,
164
+ params_acc,
165
+ vars,
166
+ env
167
+ ) do
168
+ escape_with_type(expr, type, params_acc, vars, env)
169
+ end
170
+
171
+ def escape({:type, meta, [expr, type]}, given_type, params_acc, vars, env) do
172
+ case Macro.expand_once(expr, get_env(env)) do
173
+ ^expr ->
174
+ error!("""
175
+ the first argument of type/2 must be one of:
176
+
177
+ * interpolations, such as ^value
178
+ * fields, such as p.foo or field(p, :foo)
179
+ * fragments, such as fragment("foo(?)", value)
180
+ * an arithmetic expression (+, -, *, /)
181
+ * an aggregation or window expression (avg, count, min, max, sum, over, filter)
182
+ * a conditional expression (coalesce)
183
+ * access/json paths (p.column[0].field)
184
+ * parent_as/1 (parent_as(:parent).field)
185
+
186
+ Got: #{Macro.to_string(expr)}
187
+ """)
188
+
189
+ expanded ->
190
+ escape({:type, meta, [expanded, type]}, given_type, params_acc, vars, env)
191
+ end
192
+ end
193
+
194
+ # fragments
195
+ def escape({:fragment, _, [query]}, _type, params_acc, vars, env) when is_list(query) do
196
+ {escaped, params_acc} =
197
+ Enum.map_reduce(query, params_acc, &escape_kw_fragment(&1, &2, vars, env))
198
+
199
+ {{:{}, [], [:fragment, [], [escaped]]}, params_acc}
200
+ end
201
+
202
+ def escape({:fragment, _, [{:^, _, [var]} = _expr]}, _type, params_acc, _vars, _env) do
203
+ expr = quote do: Ecto.Query.Builder.fragment!(unquote(var))
204
+ {{:{}, [], [:fragment, [], [expr]]}, params_acc}
205
+ end
206
+
207
+ def escape({:fragment, _, [query | frags]}, _type, params_acc, vars, env) do
208
+ pieces = expand_and_split_fragment(query, env)
209
+
210
+ if length(pieces) != length(frags) + 1 do
211
+ error!(
212
+ "fragment(...) expects extra arguments in the same amount of question marks in string. " <>
213
+ "It received #{length(frags)} extra argument(s) but expected #{length(pieces) - 1}"
214
+ )
215
+ end
216
+
217
+ {frags, params_acc} = Enum.map_reduce(frags, params_acc, &escape_fragment(&1, &2, vars, env))
218
+ {{:{}, [], [:fragment, [], merge_fragments(pieces, frags)]}, params_acc}
219
+ end
220
+
221
+ # subqueries
222
+ def escape({:subquery, _, [expr]}, _, {params, %{subqueries: subqueries} = acc}, _vars, _env) do
223
+ subquery = quote(do: Ecto.Query.subquery(unquote(expr)))
224
+ index = length(subqueries)
225
+ # used both in ast and in parameters, as a placeholder.
226
+ expr = {:subquery, index}
227
+ acc = %{acc | subqueries: [subquery | subqueries]}
228
+ {expr, {[expr | params], acc}}
229
+ end
230
+
231
+ # interval
232
+
233
+ def escape({:from_now, meta, [count, interval]}, type, params_acc, vars, env) do
234
+ utc = quote do: ^DateTime.utc_now()
235
+ escape({:datetime_add, meta, [utc, count, interval]}, type, params_acc, vars, env)
236
+ end
237
+
238
+ def escape({:ago, meta, [count, interval]}, type, params_acc, vars, env) do
239
+ utc = quote do: ^DateTime.utc_now()
240
+
241
+ count =
242
+ case count do
243
+ {:^, meta, [value]} ->
244
+ negate = quote do: Ecto.Query.Builder.negate!(unquote(value))
245
+ {:^, meta, [negate]}
246
+
247
+ value ->
248
+ {:-, [], [value]}
249
+ end
250
+
251
+ escape({:datetime_add, meta, [utc, count, interval]}, type, params_acc, vars, env)
252
+ end
253
+
254
+ def escape({:datetime_add, _, [datetime, count, interval]} = expr, type, params_acc, vars, env) do
255
+ assert_type!(expr, type, {:supertype, :datetime})
256
+ {datetime, params_acc} = escape(datetime, {:supertype, :datetime}, params_acc, vars, env)
257
+ {count, interval, params_acc} = escape_interval(count, interval, params_acc, vars, env)
258
+ {{:{}, [], [:datetime_add, [], [datetime, count, interval]]}, params_acc}
259
+ end
260
+
261
+ def escape({:date_add, _, [date, count, interval]} = expr, type, params_acc, vars, env) do
262
+ assert_type!(expr, type, :date)
263
+ {date, params_acc} = escape(date, :date, params_acc, vars, env)
264
+ {count, interval, params_acc} = escape_interval(count, interval, params_acc, vars, env)
265
+ {{:{}, [], [:date_add, [], [date, count, interval]]}, params_acc}
266
+ end
267
+
268
+ # json
269
+ def escape({:json_extract_path, _, [field, path]}, type, params_acc, vars, env) do
270
+ validate_json_field!(field)
271
+
272
+ path = escape_json_path(path)
273
+ {field, params_acc} = escape(field, type, params_acc, vars, env)
274
+ {{:{}, [], [:json_extract_path, [], [field, path]]}, params_acc}
275
+ end
276
+
277
+ def escape({{:., meta, [Access, :get]}, _, [left, _]} = expr, type, params_acc, vars, env) do
278
+ case left do
279
+ {{:., _, _}, _, _} ->
280
+ {expr, path} = parse_access_get(expr, [])
281
+ escape({:json_extract_path, meta, [expr, path]}, type, params_acc, vars, env)
282
+
283
+ _ ->
284
+ error!("`#{Macro.to_string(expr)}` is not a valid query expression")
285
+ end
286
+ end
287
+
288
+ # sigils
289
+ def escape({name, _, [_, []]} = sigil, type, params_acc, vars, _env)
290
+ when name in ~w(sigil_s sigil_S sigil_w sigil_W)a do
291
+ {literal(sigil, type, vars), params_acc}
292
+ end
293
+
294
+ # lists
295
+ def escape(list, type, params_acc, vars, env) when is_list(list) do
296
+ if Enum.all?(list, &(is_binary(&1) or is_number(&1) or is_boolean(&1))) do
297
+ {literal(list, type, vars), params_acc}
298
+ else
299
+ fun =
300
+ case type do
301
+ {:array, inner_type} ->
302
+ &escape(&1, inner_type, &2, vars, env)
303
+
304
+ _ ->
305
+ # In case we don't have an array nor a literal at compile-time,
306
+ # such as p.links == [^value], we don't do any casting nor validation.
307
+ # We may want to tackle this if the expression above is ever used.
308
+ &escape(&1, :any, &2, vars, env)
309
+ end
310
+
311
+ Enum.map_reduce(list, params_acc, fun)
312
+ end
313
+ end
314
+
315
+ # literals
316
+ def escape({:<<>>, _, args} = expr, type, params_acc, vars, _env) do
317
+ valid? =
318
+ Enum.all?(args, fn
319
+ {:"::", _, [left, _]} -> is_integer(left) or is_binary(left)
320
+ left -> is_integer(left) or is_binary(left)
321
+ end)
322
+
323
+ unless valid? do
324
+ error!(
325
+ "`#{Macro.to_string(expr)}` is not a valid query expression. " <>
326
+ "Only literal binaries and strings are allowed, " <>
327
+ "dynamic values need to be explicitly interpolated in queries with ^"
328
+ )
329
+ end
330
+
331
+ {literal(expr, type, vars), params_acc}
332
+ end
333
+
334
+ def escape({:-, _, [number]}, type, params_acc, vars, _env) when is_number(number),
335
+ do: {literal(-number, type, vars), params_acc}
336
+
337
+ def escape(number, type, params_acc, vars, _env) when is_number(number),
338
+ do: {literal(number, type, vars), params_acc}
339
+
340
+ def escape(binary, type, params_acc, vars, _env) when is_binary(binary),
341
+ do: {literal(binary, type, vars), params_acc}
342
+
343
+ def escape(nil, _type, params_acc, _vars, _env),
344
+ do: {nil, params_acc}
345
+
346
+ def escape(atom, type, params_acc, vars, _env) when is_atom(atom),
347
+ do: {literal(atom, type, vars), params_acc}
348
+
349
+ # negate any expression
350
+ def escape({:-, meta, arg}, type, params_acc, vars, env) do
351
+ {escaped_arg, params_acc} = escape(arg, type, params_acc, vars, env)
352
+ expr = {:{}, [], [:-, meta, escaped_arg]}
353
+ {expr, params_acc}
354
+ end
355
+
356
+ # comparison operators
357
+ def escape({comp_op, _, [left, right]} = expr, type, params_acc, vars, env)
358
+ when comp_op in ~w(== != < > <= >=)a do
359
+ assert_type!(expr, type, :boolean)
360
+
361
+ if is_nil(left) or is_nil(right) do
362
+ error!(
363
+ "comparison with nil is forbidden as it is unsafe. " <>
364
+ "If you want to check if a value is nil, use is_nil/1 instead"
365
+ )
366
+ end
367
+
368
+ ltype = quoted_type(right, vars)
369
+ rtype = quoted_type(left, vars)
370
+
371
+ {left, params_acc} = escape(left, ltype, params_acc, vars, env)
372
+ {right, params_acc} = escape(right, rtype, params_acc, vars, env)
373
+
374
+ {params, acc} = params_acc
375
+ {{:{}, [], [comp_op, [], [left, right]]}, {params |> wrap_nil(left) |> wrap_nil(right), acc}}
376
+ end
377
+
378
+ # mathematical operators
379
+ def escape({math_op, _, [left, right]}, type, params_acc, vars, env)
380
+ when math_op in ~w(+ - * /)a do
381
+ {left, params_acc} = escape(left, type, params_acc, vars, env)
382
+ {right, params_acc} = escape(right, type, params_acc, vars, env)
383
+
384
+ {{:{}, [], [math_op, [], [left, right]]}, params_acc}
385
+ end
386
+
387
+ # in operator
388
+ def escape({:in, _, [left, right]} = expr, type, params_acc, vars, env)
389
+ when is_list(right)
390
+ when is_tuple(right) and elem(right, 0) in ~w(sigil_w sigil_W @)a do
391
+ assert_type!(expr, type, :boolean)
392
+
393
+ right = Macro.expand_once(right, get_env(env))
394
+ {:array, ltype} = quoted_type(right, vars)
395
+ rtype = {:array, quoted_type(left, vars)}
396
+
397
+ {left, params_acc} = escape(left, ltype, params_acc, vars, env)
398
+ {right, params_acc} = escape(right, rtype, params_acc, vars, env)
399
+ {{:{}, [], [:in, [], [left, right]]}, params_acc}
400
+ end
401
+
402
+ def escape({:in, _, [left, right]} = expr, type, params_acc, vars, env) do
403
+ assert_type!(expr, type, :boolean)
404
+
405
+ ltype = {:out, quoted_type(right, vars)}
406
+ rtype = {:in, quoted_type(left, vars)}
407
+
408
+ {left, params_acc} = escape(left, ltype, params_acc, vars, env)
409
+ {right, params_acc} = escape(right, rtype, params_acc, vars, env)
410
+
411
+ # Remove any type wrapper from the right side
412
+ right =
413
+ case right do
414
+ {:{}, [], [:type, [], [right, _]]} -> right
415
+ _ -> right
416
+ end
417
+
418
+ {{:{}, [], [:in, [], [left, right]]}, params_acc}
419
+ end
420
+
421
+ def escape({:count, _, [arg, :distinct]}, type, params_acc, vars, env) do
422
+ {arg, params_acc} = escape(arg, type, params_acc, vars, env)
423
+ expr = {:{}, [], [:count, [], [arg, :distinct]]}
424
+ {expr, params_acc}
425
+ end
426
+
427
+ def escape({:filter, _, [aggregate]}, type, params_acc, vars, env) do
428
+ escape(aggregate, type, params_acc, vars, env)
429
+ end
430
+
431
+ def escape({:filter, _, [aggregate, filter_expr]}, type, params_acc, vars, env) do
432
+ {aggregate, params_acc} = escape(aggregate, type, params_acc, vars, env)
433
+ {filter_expr, params_acc} = escape(filter_expr, :boolean, params_acc, vars, env)
434
+ {{:{}, [], [:filter, [], [aggregate, filter_expr]]}, params_acc}
435
+ end
436
+
437
+ def escape({:coalesce, _, [left, right]}, type, params_acc, vars, env) do
438
+ {left, params_acc} = escape(left, type, params_acc, vars, env)
439
+ {right, params_acc} = escape(right, type, params_acc, vars, env)
440
+ {{:{}, [], [:coalesce, [], [left, right]]}, params_acc}
441
+ end
442
+
443
+ def escape({:over, _, [{agg_name, _, agg_args} | over_args]}, type, params_acc, vars, env) do
444
+ aggregate = {agg_name, [], agg_args || []}
445
+ {aggregate, params_acc} = escape_window_function(aggregate, type, params_acc, vars, env)
446
+ {window, params_acc} = escape_window_description(over_args, params_acc, vars, env)
447
+ {{:{}, [], [:over, [], [aggregate, window]]}, params_acc}
448
+ end
449
+
450
+ def escape({:selected_as, _, [_expr, _name]}, _type, _params_acc, _vars, _env) do
451
+ error!("""
452
+ selected_as/2 can only be used at the root of a select statement. \
453
+ If you are trying to use it inside of an expression, consider putting the \
454
+ expression inside of `selected_as/2` instead. For instance, instead of:
455
+
456
+ from p in Post, select: coalesce(selected_as(p.visits, :v), 0)
457
+
458
+ use:
459
+
460
+ from p in Post, select: selected_as(coalesce(p.visits, 0), :v)
461
+ """)
462
+ end
463
+
464
+ def escape({:selected_as, _, [name]}, _type, params_acc, _vars, _env) do
465
+ name = quoted_atom!(name, "selected_as/1")
466
+ expr = {:{}, [], [:selected_as, [], [name]]}
467
+ {expr, params_acc}
468
+ end
469
+
470
+ def escape({quantifier, meta, [subquery]}, type, params_acc, vars, env)
471
+ when quantifier in [:all, :any, :exists] do
472
+ {subquery, params_acc} = escape({:subquery, meta, [subquery]}, type, params_acc, vars, env)
473
+ {{:{}, [], [quantifier, [], [subquery]]}, params_acc}
474
+ end
475
+
476
+ def escape({:=, _, _} = expr, _type, _params_acc, _vars, _env) do
477
+ error!(
478
+ "`#{Macro.to_string(expr)}` is not a valid query expression. " <>
479
+ "The match operator is not supported: `=`. " <>
480
+ "Did you mean to use `==` instead?"
481
+ )
482
+ end
483
+
484
+ def escape({op, _, _}, _type, _params_acc, _vars, _env) when op in ~w(|| && !)a do
485
+ error!(
486
+ "short-circuit operators are not supported: `#{op}`. " <>
487
+ "Instead use boolean operators: `and`, `or`, and `not`"
488
+ )
489
+ end
490
+
491
+ # Tuple
492
+ def escape({left, right}, type, params_acc, vars, env) do
493
+ escape({:{}, [], [left, right]}, type, params_acc, vars, env)
494
+ end
495
+
496
+ # Tuple
497
+ def escape({:{}, _, list}, {:tuple, types}, params_acc, vars, env) do
498
+ if Enum.count(list) == Enum.count(types) do
499
+ {list, params_acc} =
500
+ list
501
+ |> Enum.zip(types)
502
+ |> Enum.map_reduce(params_acc, fn {expr, type}, params_acc ->
503
+ escape(expr, type, params_acc, vars, env)
504
+ end)
505
+
506
+ expr = {:{}, [], [:{}, [], list]}
507
+ {expr, params_acc}
508
+ else
509
+ escape({:{}, [], list}, :any, params_acc, vars, env)
510
+ end
511
+ end
512
+
513
+ # Tuple
514
+ def escape({:{}, _, _}, _, _, _, _) do
515
+ error!("Tuples can only be used in comparisons with literal tuples of the same size")
516
+ end
517
+
518
+ # Unnecessary parentheses around an expression
519
+ def escape({:__block__, _, [expr]}, type, params_acc, vars, env) do
520
+ escape(expr, type, params_acc, vars, env)
521
+ end
522
+
523
+ # Other functions - no type casting
524
+ def escape({name, _, args} = expr, type, params_acc, vars, env)
525
+ when is_atom(name) and is_list(args) do
526
+ case call_type(name, length(args)) do
527
+ {in_type, out_type} ->
528
+ assert_type!(expr, type, out_type)
529
+ escape_call(expr, in_type, params_acc, vars, env)
530
+
531
+ nil ->
532
+ try_expansion(expr, type, params_acc, vars, env)
533
+ end
534
+ end
535
+
536
+ # Finally handle vars
537
+ def escape({var, _, context}, _type, params_acc, vars, _env)
538
+ when is_atom(var) and is_atom(context) do
539
+ {escape_var!(var, vars), params_acc}
540
+ end
541
+
542
+ # Raise nice error messages for fun calls.
543
+ def escape({fun, _, args} = other, _type, _params_acc, _vars, _env)
544
+ when is_atom(fun) and is_list(args) do
545
+ error!("""
546
+ `#{Macro.to_string(other)}` is not a valid query expression. \
547
+ If you are trying to invoke a function that is not supported by Ecto, \
548
+ you can use fragments:
549
+
550
+ fragment("some_function(?, ?, ?)", m.some_field, 1)
551
+
552
+ See Ecto.Query.API to learn more about the supported functions and \
553
+ Ecto.Query.API.fragment/1 to learn more about fragments.
554
+ """)
555
+ end
556
+
557
+ # Raise nice error message for remote calls
558
+ def escape({{:., _, [_, fun]}, _, _} = other, type, params_acc, vars, env)
559
+ when is_atom(fun) do
560
+ try_expansion(other, type, params_acc, vars, env)
561
+ end
562
+
563
+ # For everything else we raise
564
+ def escape(other, _type, _params_acc, _vars, _env) do
565
+ error!("`#{Macro.to_string(other)}` is not a valid query expression")
566
+ end
567
+
568
+ defp escape_with_type(expr, {:^, _, [type]}, params_acc, vars, env) do
569
+ {expr, params_acc} = escape(expr, :any, params_acc, vars, env)
570
+ {{:{}, [], [:type, [], [expr, type]]}, params_acc}
571
+ end
572
+
573
+ defp escape_with_type(expr, type, params_acc, vars, env) do
574
+ type = validate_type!(type, vars, env)
575
+ {expr, params_acc} = escape(expr, type, params_acc, vars, env)
576
+ {{:{}, [], [:type, [], [expr, escape_type(type)]]}, params_acc}
577
+ end
578
+
579
+ defp escape_type({:parameterized, _} = param), do: Macro.escape(param)
580
+ defp escape_type(type), do: type
581
+
582
+ defp validate_json_field!({{:., _, _}, _, _}), do: :ok
583
+ defp validate_json_field!({:field, _, _}), do: :ok
584
+
585
+ defp validate_json_field!(unsupported_field),
586
+ do: error!("`#{Macro.to_string(unsupported_field)}` is not a valid json field")
587
+
588
+ defp wrap_nil(params, {:{}, _, [:^, _, [ix]]}),
589
+ do: wrap_nil(params, length(params) - ix - 1, [])
590
+
591
+ defp wrap_nil(params, _other), do: params
592
+
593
+ defp wrap_nil([{val, type} | params], 0, acc) do
594
+ val = quote do: Ecto.Query.Builder.not_nil!(unquote(val))
595
+ Enum.reverse(acc, [{val, type} | params])
596
+ end
597
+
598
+ defp wrap_nil([pair | params], i, acc) do
599
+ wrap_nil(params, i - 1, [pair | acc])
600
+ end
601
+
602
+ defp expand_and_split_fragment(query, env) do
603
+ case Macro.expand(query, get_env(env)) do
604
+ binary when is_binary(binary) ->
605
+ split_fragment(binary, "")
606
+
607
+ _ ->
608
+ error!(bad_fragment_message(Macro.to_string(query)))
609
+ end
610
+ end
611
+
612
+ defp bad_fragment_message(arg) do
613
+ "to prevent SQL injection attacks, fragment(...) does not allow strings " <>
614
+ "to be interpolated as the first argument via the `^` operator, got: `#{arg}`"
615
+ end
616
+
617
+ defp split_fragment(<<>>, consumed),
618
+ do: [consumed]
619
+
620
+ defp split_fragment(<<??, rest::binary>>, consumed),
621
+ do: [consumed | split_fragment(rest, "")]
622
+
623
+ defp split_fragment(<<?\\, ??, rest::binary>>, consumed),
624
+ do: split_fragment(rest, consumed <> <<??>>)
625
+
626
+ defp split_fragment(<<first::utf8, rest::binary>>, consumed),
627
+ do: split_fragment(rest, consumed <> <<first::utf8>>)
628
+
629
+ @doc "Returns fragment pieces, given a fragment string and arguments."
630
+ def fragment_pieces(frag, args) do
631
+ frag
632
+ |> split_fragment("")
633
+ |> merge_fragments(args)
634
+ end
635
+
636
+ defp escape_window_description([], params_acc, _vars, _env),
637
+ do: {[], params_acc}
638
+
639
+ defp escape_window_description([window_name], params_acc, _vars, _env)
640
+ when is_atom(window_name),
641
+ do: {window_name, params_acc}
642
+
643
+ defp escape_window_description([kw], params_acc, vars, env) do
644
+ case Ecto.Query.Builder.Windows.escape(kw, params_acc, vars, env) do
645
+ {runtime, [], params_acc} ->
646
+ {runtime, params_acc}
647
+
648
+ {_, [{key, _} | _], _} ->
649
+ error!(
650
+ "windows definitions given to over/2 do not allow interpolations at the root of " <>
651
+ "`#{key}`. Please use Ecto.Query.windows/3 to explicitly define a window instead"
652
+ )
653
+ end
654
+ end
655
+
656
+ defp escape_window_function(expr, type, params_acc, vars, env) do
657
+ expr
658
+ |> validate_window_function!(env)
659
+ |> escape(type, params_acc, vars, env)
660
+ end
661
+
662
+ defp validate_window_function!({:fragment, _, _} = expr, _env), do: expr
663
+
664
+ defp validate_window_function!({agg, _, args} = expr, env)
665
+ when is_atom(agg) and is_list(args) do
666
+ if Code.ensure_loaded?(Ecto.Query.WindowAPI) and
667
+ function_exported?(Ecto.Query.WindowAPI, agg, length(args)) do
668
+ expr
669
+ else
670
+ case Macro.expand_once(expr, get_env(env)) do
671
+ ^expr ->
672
+ error!(
673
+ "unknown window function #{agg}/#{length(args)}. " <>
674
+ "See Ecto.Query.WindowAPI for all available functions"
675
+ )
676
+
677
+ expr ->
678
+ validate_window_function!(expr, env)
679
+ end
680
+ end
681
+ end
682
+
683
+ defp validate_window_function!(expr, _), do: expr
684
+
685
+ defp escape_call({name, _, args}, type, params_acc, vars, env) do
686
+ {args, params_acc} = Enum.map_reduce(args, params_acc, &escape(&1, type, &2, vars, env))
687
+ expr = {:{}, [], [name, [], args]}
688
+ {expr, params_acc}
689
+ end
690
+
691
+ defp escape_field!({var, _, context}, field, vars)
692
+ when is_atom(var) and is_atom(context) do
693
+ var = escape_var!(var, vars)
694
+ field = quoted_atom!(field, "field/2")
695
+ dot = {:{}, [], [:., [], [var, field]]}
696
+ {:{}, [], [dot, [], []]}
697
+ end
698
+
699
+ defp escape_field!({kind, _, [value]}, field, _vars)
700
+ when kind in [:as, :parent_as] do
701
+ value = late_binding!(kind, value)
702
+ as = {:{}, [], [kind, [], [value]]}
703
+ field = quoted_atom!(field, "field/2")
704
+ dot = {:{}, [], [:., [], [as, field]]}
705
+ {:{}, [], [dot, [], []]}
706
+ end
707
+
708
+ defp escape_field!(expr, field, _vars) do
709
+ error!("""
710
+ cannot fetch field `#{Macro.to_string(field)}` from `#{Macro.to_string(expr)}`. Can only fetch fields from:
711
+
712
+ * sources, such as `p` in `from p in Post`
713
+ * named bindings, such as `as(:post)` in `from Post, as: :post`
714
+ * parent named bindings, such as `parent_as(:post)` in a subquery
715
+ """)
716
+ end
717
+
718
+ defp escape_interval(count, interval, params_acc, vars, env) do
719
+ type =
720
+ cond do
721
+ is_float(count) -> :float
722
+ is_integer(count) -> :integer
723
+ true -> :decimal
724
+ end
725
+
726
+ {count, params_acc} = escape(count, type, params_acc, vars, env)
727
+ {count, quoted_interval!(interval), params_acc}
728
+ end
729
+
730
+ defp escape_kw_fragment({key, [{_, _} | _] = exprs}, params_acc, vars, env) when is_atom(key) do
731
+ {escaped, params_acc} =
732
+ Enum.map_reduce(exprs, params_acc, &escape_kw_fragment(&1, &2, vars, env))
733
+
734
+ {{key, escaped}, params_acc}
735
+ end
736
+
737
+ defp escape_kw_fragment({key, expr}, params_acc, vars, env) when is_atom(key) do
738
+ {escaped, params_acc} = escape(expr, :any, params_acc, vars, env)
739
+ {{key, escaped}, params_acc}
740
+ end
741
+
742
+ defp escape_kw_fragment({key, _expr}, _params_acc, _vars, _env) do
743
+ error!(
744
+ "fragment(...) with keywords accepts only atoms as keys, got `#{Macro.to_string(key)}`"
745
+ )
746
+ end
747
+
748
+ defp escape_fragment({:literal, _meta, [expr]}, params_acc, _vars, _env) do
749
+ case expr do
750
+ {:^, _, [expr]} ->
751
+ checked = quote do: Ecto.Query.Builder.literal!(unquote(expr))
752
+ escaped = {:{}, [], [:literal, [], [checked]]}
753
+ {escaped, params_acc}
754
+
755
+ _ ->
756
+ error!(
757
+ "literal/1 in fragment expects an interpolated value, such as literal(^value), got `#{Macro.to_string(expr)}`"
758
+ )
759
+ end
760
+ end
761
+
762
+ defp escape_fragment({:splice, _meta, [splice]}, params_acc, vars, env) do
763
+ case splice do
764
+ {:^, _, [value]} = expr ->
765
+ checked = quote do: Ecto.Query.Builder.splice!(unquote(value))
766
+ length = quote do: length(unquote(checked))
767
+ {expr, params_acc} = escape(expr, {:splice, :any}, params_acc, vars, env)
768
+ escaped = {:{}, [], [:splice, [], [expr, length]]}
769
+ {escaped, params_acc}
770
+
771
+ _ ->
772
+ error!(
773
+ "splice/1 in fragment expects an interpolated value, such as splice(^value), got `#{Macro.to_string(splice)}`"
774
+ )
775
+ end
776
+ end
777
+
778
+ defp escape_fragment(expr, params_acc, vars, env) do
779
+ escape(expr, :any, params_acc, vars, env)
780
+ end
781
+
782
+ defp merge_fragments([h1 | t1], [h2 | t2]),
783
+ do: [{:raw, h1}, {:expr, h2} | merge_fragments(t1, t2)]
784
+
785
+ defp merge_fragments([h1], []),
786
+ do: [{:raw, h1}]
787
+
788
+ for {agg, arity} <- @dynamic_aggregates do
789
+ defp call_type(unquote(agg), unquote(arity)), do: {:any, :any}
790
+ end
791
+
792
+ for {agg, {arity, return}} <- @static_aggregates do
793
+ defp call_type(unquote(agg), unquote(arity)), do: {:any, unquote(return)}
794
+ end
795
+
796
+ for {comp, arity} <- @comparisons do
797
+ defp call_type(unquote(comp), unquote(arity)), do: {:any, :boolean}
798
+ end
799
+
800
+ defp call_type(:or, 2), do: {:boolean, :boolean}
801
+ defp call_type(:and, 2), do: {:boolean, :boolean}
802
+ defp call_type(:not, 1), do: {:boolean, :boolean}
803
+ defp call_type(:like, 2), do: {:string, :boolean}
804
+ defp call_type(:ilike, 2), do: {:string, :boolean}
805
+ defp call_type(_, _), do: nil
806
+
807
+ defp assert_type!(expr, type, actual) do
808
+ cond do
809
+ not is_atom(type) and not Ecto.Type.primitive?(type) ->
810
+ :ok
811
+
812
+ Ecto.Type.match?(type, actual) ->
813
+ :ok
814
+
815
+ true ->
816
+ error!(
817
+ "expression `#{Macro.to_string(expr)}` does not type check. " <>
818
+ "It returns a value of type #{inspect(actual)} but a value of " <>
819
+ "type #{inspect(type)} is expected"
820
+ )
821
+ end
822
+ end
823
+
824
+ @doc """
825
+ Validates the type with the given vars.
826
+ """
827
+ def validate_type!({:parameterized, _} = type, _vars, _env),
828
+ do: type
829
+
830
+ def validate_type!({composite, type}, vars, env),
831
+ do: {composite, validate_type!(type, vars, env)}
832
+
833
+ def validate_type!({:^, _, [type]}, _vars, _env),
834
+ do: type
835
+
836
+ def validate_type!({:__aliases__, _, _} = type, _vars, env),
837
+ do: Macro.expand(type, get_env(env))
838
+
839
+ def validate_type!(type, _vars, _env) when is_atom(type),
840
+ do: type
841
+
842
+ def validate_type!({{:., _, [{var, _, context}, field]}, _, []}, vars, _env)
843
+ when is_atom(var) and is_atom(context) and is_atom(field),
844
+ do: {find_var!(var, vars), field}
845
+
846
+ def validate_type!({:field, _, [{var, _, context}, field]}, vars, _env)
847
+ when is_atom(var) and is_atom(context) and is_atom(field),
848
+ do: {find_var!(var, vars), field}
849
+
850
+ def validate_type!({:field, _, [{var, _, context}, {:^, _, [field]}]}, vars, _env)
851
+ when is_atom(var) and is_atom(context),
852
+ do: {find_var!(var, vars), field}
853
+
854
+ def validate_type!(type, _vars, _env) do
855
+ error!(
856
+ "type/2 expects an alias, atom, initialized parameterized type or " <>
857
+ "source.field as second argument, got: `#{Macro.to_string(type)}`"
858
+ )
859
+ end
860
+
861
+ @always_tagged [:binary]
862
+
863
+ defp literal(value, expected, vars),
864
+ do: do_literal(value, expected, quoted_type(value, vars))
865
+
866
+ defp do_literal(value, _, current) when current in @always_tagged,
867
+ do:
868
+ {:%, [],
869
+ [Ecto.Query.Tagged, {:%{}, [], [value: value, type: normalize_type(value, current)]}]}
870
+
871
+ defp do_literal(value, :any, _current),
872
+ do: value
873
+
874
+ defp do_literal(value, expected, expected),
875
+ do: value
876
+
877
+ defp do_literal(value, expected, _current),
878
+ do: {:%, [], [Ecto.Query.Tagged, {:%{}, [], [value: value, type: expected]}]}
879
+
880
+ @doc """
881
+ Escape the params entries list.
882
+ """
883
+ @spec escape_params(list()) :: list()
884
+ def escape_params(list), do: Enum.reverse(list)
885
+
886
+ @doc """
887
+ Escape the select alias map
888
+ """
889
+ @spec escape_select_aliases(map()) :: Macro.t()
890
+ def escape_select_aliases(%{} = aliases), do: {:%{}, [], Map.to_list(aliases)}
891
+
892
+ @doc """
893
+ Escapes a variable according to the given binds.
894
+
895
+ A escaped variable is represented internally as
896
+ `&0`, `&1` and so on.
897
+ """
898
+ @spec escape_var!(atom, Keyword.t()) :: Macro.t()
899
+ def escape_var!(var, vars) do
900
+ {:{}, [], [:&, [], [find_var!(var, vars)]]}
901
+ end
902
+
903
+ @doc """
904
+ Escapes a list of bindings as a list of atoms.
905
+
906
+ Only variables or `{:atom, value}` tuples are allowed in the `bindings` list,
907
+ otherwise an `Ecto.Query.CompileError` is raised.
908
+
909
+ ## Examples
910
+
911
+ iex> escape_binding(%Ecto.Query{}, quote(do: [x, y, z]), __ENV__)
912
+ {%Ecto.Query{}, [x: 0, y: 1, z: 2]}
913
+
914
+ iex> escape_binding(%Ecto.Query{}, quote(do: [{x, 0}, {z, 2}]), __ENV__)
915
+ {%Ecto.Query{}, [x: 0, z: 2]}
916
+
917
+ iex> escape_binding(%Ecto.Query{}, quote(do: [x, y, x]), __ENV__)
918
+ ** (Ecto.Query.CompileError) variable `x` is bound twice
919
+
920
+ iex> escape_binding(%Ecto.Query{}, quote(do: [a, b, :foo]), __ENV__)
921
+ ** (Ecto.Query.CompileError) binding list should contain only variables or `{as, var}` tuples, got: :foo
922
+
923
+ """
924
+ @spec escape_binding(Macro.t(), list, Macro.Env.t()) :: {Macro.t(), Keyword.t()}
925
+ def escape_binding(query, binding, _env) when is_list(binding) do
926
+ vars = binding |> Enum.with_index() |> Enum.map(&escape_bind/1)
927
+ assert_no_duplicate_binding!(vars)
928
+
929
+ {positional_vars, named_vars} = Enum.split_while(vars, &(not named_bind?(&1)))
930
+ assert_named_binds_in_tail!(named_vars, binding)
931
+
932
+ {query, positional_binds} = calculate_positional_binds(query, positional_vars)
933
+ {query, named_binds} = calculate_named_binds(query, named_vars)
934
+ {query, positional_binds ++ named_binds}
935
+ end
936
+
937
+ def escape_binding(_query, bind, _env) do
938
+ error!(
939
+ "binding should be list of variables and `{as, var}` tuples " <>
940
+ "at the end, got: #{Macro.to_string(bind)}"
941
+ )
942
+ end
943
+
944
+ defp named_bind?({kind, _, _}), do: kind == :named
945
+
946
+ defp assert_named_binds_in_tail!(named_vars, binding) do
947
+ if Enum.all?(named_vars, &named_bind?/1) do
948
+ :ok
949
+ else
950
+ error!(
951
+ "named binds in the form of `{as, var}` tuples must be at the end " <>
952
+ "of the binding list, got: #{Macro.to_string(binding)}"
953
+ )
954
+ end
955
+ end
956
+
957
+ defp assert_no_duplicate_binding!(vars) do
958
+ bound_vars = for {_, var, _} <- vars, var != :_, do: var
959
+
960
+ case bound_vars -- Enum.uniq(bound_vars) do
961
+ [] -> :ok
962
+ [var | _] -> error!("variable `#{var}` is bound twice")
963
+ end
964
+ end
965
+
966
+ defp calculate_positional_binds(query, vars) do
967
+ case Enum.split_while(vars, &(elem(&1, 1) != :...)) do
968
+ {vars, []} ->
969
+ vars = for {:pos, var, count} <- vars, do: {var, count}
970
+ {query, vars}
971
+
972
+ {vars, [_ | tail]} ->
973
+ query =
974
+ quote do
975
+ query = Ecto.Queryable.to_query(unquote(query))
976
+ escape_count = Ecto.Query.Builder.count_binds(query)
977
+ query
978
+ end
979
+
980
+ tail =
981
+ tail
982
+ |> Enum.with_index(-length(tail))
983
+ |> Enum.map(fn {{:pos, k, _}, count} ->
984
+ {k, quote(do: escape_count + unquote(count))}
985
+ end)
986
+
987
+ vars = for {:pos, var, count} <- vars, do: {var, count}
988
+ {query, vars ++ tail}
989
+ end
990
+ end
991
+
992
+ defp calculate_named_binds(query, []), do: {query, []}
993
+
994
+ defp calculate_named_binds(query, vars) do
995
+ assignments =
996
+ for {:named, key, name} <- vars do
997
+ quote do
998
+ unquote({key, [], __MODULE__}) = unquote(__MODULE__).count_alias!(query, unquote(name))
999
+ end
1000
+ end
1001
+
1002
+ query =
1003
+ quote do
1004
+ query = Ecto.Queryable.to_query(unquote(query))
1005
+ unquote_splicing(assignments)
1006
+ query
1007
+ end
1008
+
1009
+ pairs =
1010
+ for {:named, key, _name} <- vars do
1011
+ {key, {key, [], __MODULE__}}
1012
+ end
1013
+
1014
+ {query, pairs}
1015
+ end
1016
+
1017
+ @doc """
1018
+ Count the alias for the given query.
1019
+ """
1020
+ def count_alias!(%{aliases: aliases} = query, name) do
1021
+ case aliases do
1022
+ %{^name => ix} ->
1023
+ ix
1024
+
1025
+ %{} ->
1026
+ raise Ecto.QueryError, message: "unknown bind name `#{inspect(name)}`", query: query
1027
+ end
1028
+ end
1029
+
1030
+ defp escape_bind({{:..., _, _context}, ix}),
1031
+ do: {:pos, :..., ix}
1032
+
1033
+ defp escape_bind({{var, _, context}, ix}) when is_atom(var) and is_atom(context),
1034
+ do: {:pos, var, ix}
1035
+
1036
+ defp escape_bind({{{var, _, context}, ix}, _}) when is_atom(var) and is_atom(context),
1037
+ do: {:pos, var, ix}
1038
+
1039
+ defp escape_bind({{name, {var, _, context}}, _ix})
1040
+ when is_atom(name) and is_atom(var) and is_atom(context),
1041
+ do: {:named, var, name}
1042
+
1043
+ defp escape_bind({{{:^, _, [expr]}, {var, _, context}}, _ix})
1044
+ when is_atom(var) and is_atom(context),
1045
+ do: {:named, var, expr}
1046
+
1047
+ defp escape_bind({bind, _ix}),
1048
+ do:
1049
+ error!(
1050
+ "binding list should contain only variables or " <>
1051
+ "`{as, var}` tuples, got: #{Macro.to_string(bind)}"
1052
+ )
1053
+
1054
+ defp try_expansion(expr, type, params, vars, %Macro.Env{} = env) do
1055
+ try_expansion(expr, type, params, vars, {env, &escape/5})
1056
+ end
1057
+
1058
+ defp try_expansion(expr, type, params, vars, {env, fun}) do
1059
+ case Macro.expand_once(expr, env) do
1060
+ ^expr ->
1061
+ error!("""
1062
+ `#{Macro.to_string(expr)}` is not a valid query expression.
1063
+
1064
+ * If you intended to call an Elixir function or introduce a value,
1065
+ you need to explicitly interpolate it with ^
1066
+
1067
+ * If you intended to call a database function, please check the documentation
1068
+ for Ecto.Query.API to see the supported database expressions
1069
+
1070
+ * If you intended to extend Ecto's query DSL, make sure that you have required
1071
+ the module or imported the relevant function. Note that you need macros to
1072
+ extend Ecto's querying capabilities
1073
+ """)
1074
+
1075
+ expanded ->
1076
+ fun.(expanded, type, params, vars, env)
1077
+ end
1078
+ end
1079
+
1080
+ @doc """
1081
+ Finds the index value for the given var in vars or raises.
1082
+ """
1083
+ def find_var!(var, vars) do
1084
+ vars[var] ||
1085
+ error!(
1086
+ "unbound variable `#{var}` in query. If you are attempting to interpolate a value, use ^var"
1087
+ )
1088
+ end
1089
+
1090
+ @doc """
1091
+ Checks if the field is an atom at compilation time or
1092
+ delegates the check to runtime for interpolation.
1093
+ """
1094
+ def quoted_atom!({:^, _, [expr]}, used_ref),
1095
+ do: quote(do: Ecto.Query.Builder.atom!(unquote(expr), unquote(used_ref)))
1096
+
1097
+ def quoted_atom!(atom, _used_ref) when is_atom(atom),
1098
+ do: atom
1099
+
1100
+ def quoted_atom!(other, used_ref),
1101
+ do:
1102
+ error!(
1103
+ "expected literal atom or interpolated value in #{used_ref}, got: " <>
1104
+ "`#{Macro.to_string(other)}`"
1105
+ )
1106
+
1107
+ @doc """
1108
+ Called by escaper at runtime to verify that value is an atom.
1109
+ """
1110
+ def atom!(atom, _used_ref) when is_atom(atom),
1111
+ do: atom
1112
+
1113
+ def atom!(other, used_ref),
1114
+ do: error!("expected atom in #{used_ref}, got: `#{inspect(other)}`")
1115
+
1116
+ @doc """
1117
+ Checks if the value of a late binding is an interpolation or
1118
+ a quoted atom.
1119
+ """
1120
+ def late_binding!(kind, value) do
1121
+ case value do
1122
+ {:^, _, [value]} ->
1123
+ value
1124
+
1125
+ other ->
1126
+ quoted_atom!(other, "#{kind}/1")
1127
+ end
1128
+ end
1129
+
1130
+ defp escape_json_path(path) when is_list(path) do
1131
+ Enum.map(path, &quoted_json_path_element!/1)
1132
+ end
1133
+
1134
+ defp escape_json_path({:^, _, [path]}) do
1135
+ quote do
1136
+ path = Ecto.Query.Builder.json_path!(unquote(path))
1137
+ Enum.map(path, &Ecto.Query.Builder.json_path_element!/1)
1138
+ end
1139
+ end
1140
+
1141
+ defp escape_json_path(other) do
1142
+ error!(
1143
+ "expected JSON path to be a literal list or interpolated value, got: `#{Macro.to_string(other)}`"
1144
+ )
1145
+ end
1146
+
1147
+ defp quoted_json_path_element!({:^, _, [expr]}),
1148
+ do: quote(do: Ecto.Query.Builder.json_path_element!(unquote(expr)))
1149
+
1150
+ defp quoted_json_path_element!(binary) when is_binary(binary),
1151
+ do: binary
1152
+
1153
+ defp quoted_json_path_element!(integer) when is_integer(integer),
1154
+ do: integer
1155
+
1156
+ defp quoted_json_path_element!(other),
1157
+ do:
1158
+ error!(
1159
+ "expected JSON path to contain literal strings, literal integers, or interpolated values, got: " <>
1160
+ "`#{Macro.to_string(other)}`"
1161
+ )
1162
+
1163
+ @doc """
1164
+ Called by escaper at runtime to verify that value is a string or an integer.
1165
+ """
1166
+ def json_path_element!(binary) when is_binary(binary),
1167
+ do: binary
1168
+
1169
+ def json_path_element!(integer) when is_integer(integer),
1170
+ do: integer
1171
+
1172
+ def json_path_element!(other),
1173
+ do: error!("expected string or integer in json_extract_path/2, got: `#{inspect(other)}`")
1174
+
1175
+ @doc """
1176
+ Called by escaper at runtime to verify that path is a list
1177
+ """
1178
+ def json_path!(path) when is_list(path),
1179
+ do: path
1180
+
1181
+ def json_path!(path),
1182
+ do: error!("expected `path` to be a list in json_extract_path/2, got: `#{inspect(path)}`")
1183
+
1184
+ @doc """
1185
+ Called by escaper at runtime to verify that a value is not nil.
1186
+ """
1187
+ def not_nil!(nil) do
1188
+ raise ArgumentError,
1189
+ "comparison with nil is forbidden as it is unsafe. " <>
1190
+ "If you want to check if a value is nil, use is_nil/1 instead"
1191
+ end
1192
+
1193
+ def not_nil!(not_nil) do
1194
+ not_nil
1195
+ end
1196
+
1197
+ @doc """
1198
+ Checks if the field is a valid interval at compilation time or
1199
+ delegate the check to runtime for interpolation.
1200
+ """
1201
+ def quoted_interval!({:^, _, [expr]}),
1202
+ do: quote(do: Ecto.Query.Builder.interval!(unquote(expr)))
1203
+
1204
+ def quoted_interval!(other),
1205
+ do: interval!(other)
1206
+
1207
+ @doc """
1208
+ Called by escaper at runtime to verify fragment keywords.
1209
+ """
1210
+ def fragment!(kw) do
1211
+ if Keyword.keyword?(kw) do
1212
+ kw
1213
+ else
1214
+ raise ArgumentError, bad_fragment_message(inspect(kw))
1215
+ end
1216
+ end
1217
+
1218
+ @doc """
1219
+ Called by escaper at runtime to verify literal in fragments.
1220
+ """
1221
+ def literal!(literal) do
1222
+ if is_binary(literal) do
1223
+ literal
1224
+ else
1225
+ raise ArgumentError,
1226
+ "literal(^value) expects `value` to be a string, got `#{inspect(literal)}`"
1227
+ end
1228
+ end
1229
+
1230
+ @doc """
1231
+ Called by escaper at runtime to verify splice in fragments.
1232
+ """
1233
+ def splice!(value) do
1234
+ if is_list(value) do
1235
+ value
1236
+ else
1237
+ raise ArgumentError,
1238
+ "splice(^value) expects `value` to be a list, got `#{inspect(value)}`"
1239
+ end
1240
+ end
1241
+
1242
+ @doc """
1243
+ Called by escaper at runtime to verify that value is a valid interval.
1244
+ """
1245
+ @interval ~w(year month week day hour minute second millisecond microsecond)
1246
+ def interval!(interval) when interval in @interval,
1247
+ do: interval
1248
+
1249
+ def interval!(other_string) when is_binary(other_string),
1250
+ do:
1251
+ error!(
1252
+ "invalid interval: `#{inspect(other_string)}` (expected one of #{Enum.join(@interval, ", ")})"
1253
+ )
1254
+
1255
+ def interval!(not_string),
1256
+ do: error!("invalid interval: `#{inspect(not_string)}` (expected a string)")
1257
+
1258
+ @doc """
1259
+ Negates the given number.
1260
+ """
1261
+ def negate!(%Decimal{} = decimal), do: Decimal.negate(decimal)
1262
+ def negate!(number) when is_number(number), do: -number
1263
+
1264
+ @doc """
1265
+ Returns the type of an expression at build time.
1266
+ """
1267
+ @spec quoted_type(Macro.t(), Keyword.t()) :: quoted_type
1268
+
1269
+ # Fields
1270
+ def quoted_type({{:., _, [{var, _, context}, field]}, _, []}, vars)
1271
+ when is_atom(var) and is_atom(context) and is_atom(field),
1272
+ do: {find_var!(var, vars), field}
1273
+
1274
+ def quoted_type({{:., _, [{kind, _, [value]}, field]}, _, []}, _vars)
1275
+ when kind in [:as, :parent_as] do
1276
+ value = late_binding!(kind, value)
1277
+ {{:{}, [], [kind, [], [value]]}, field}
1278
+ end
1279
+
1280
+ def quoted_type({:field, _, [{var, _, context}, field]}, vars)
1281
+ when is_atom(var) and is_atom(context) and is_atom(field),
1282
+ do: {find_var!(var, vars), field}
1283
+
1284
+ def quoted_type({:field, _, [{kind, _, [value]}, field]}, _vars)
1285
+ when kind in [:as, :parent_as] and is_atom(field) do
1286
+ value = late_binding!(kind, value)
1287
+ {{:{}, [], [kind, [], [value]]}, field}
1288
+ end
1289
+
1290
+ # Unquoting code here means the second argument of field will
1291
+ # always be unquoted twice, one by the type checking and another
1292
+ # in the query itself. We are assuming this is not an issue
1293
+ # as the solution is somewhat complicated.
1294
+ def quoted_type({:field, _, [{var, _, context}, {:^, _, [code]}]}, vars)
1295
+ when is_atom(var) and is_atom(context),
1296
+ do: {find_var!(var, vars), code}
1297
+
1298
+ def quoted_type({:field, _, [{kind, _, [value]}, {:^, _, [code]}]}, _vars)
1299
+ when kind in [:as, :parent_as] do
1300
+ value = late_binding!(kind, value)
1301
+ {{:{}, [], [kind, [], [value]]}, code}
1302
+ end
1303
+
1304
+ # Interval
1305
+ def quoted_type({:datetime_add, _, [_, _, _]}, _vars), do: :naive_datetime
1306
+ def quoted_type({:date_add, _, [_, _, _]}, _vars), do: :date
1307
+
1308
+ # Tagged
1309
+ def quoted_type({:<<>>, _, _}, _vars), do: :binary
1310
+ def quoted_type({:type, _, [_, type]}, _vars), do: type
1311
+
1312
+ # Sigils
1313
+ def quoted_type({sigil, _, [_, []]}, _vars) when sigil in ~w(sigil_s sigil_S)a, do: :string
1314
+
1315
+ def quoted_type({sigil, _, [_, []]}, _vars) when sigil in ~w(sigil_w sigil_W)a,
1316
+ do: {:array, :string}
1317
+
1318
+ # Lists
1319
+ def quoted_type(list, vars) when is_list(list) do
1320
+ case list |> Enum.map(&quoted_type(&1, vars)) |> Enum.uniq() do
1321
+ [type] -> {:array, type}
1322
+ _ -> {:array, :any}
1323
+ end
1324
+ end
1325
+
1326
+ # Negative numbers
1327
+ def quoted_type({:-, _, [number]}, _vars) when is_integer(number), do: :integer
1328
+ def quoted_type({:-, _, [number]}, _vars) when is_float(number), do: :float
1329
+
1330
+ # Dynamic aggregates
1331
+ for {agg, arity} <- @dynamic_aggregates do
1332
+ args = 1..arity |> Enum.map(fn _ -> Macro.var(:_, __MODULE__) end) |> tl()
1333
+
1334
+ def quoted_type({unquote(agg), _, [expr, unquote_splicing(args)]}, vars) do
1335
+ quoted_type(expr, vars)
1336
+ end
1337
+ end
1338
+
1339
+ # Literals
1340
+ def quoted_type(literal, _vars) when is_float(literal), do: :float
1341
+ def quoted_type(literal, _vars) when is_binary(literal), do: :string
1342
+ def quoted_type(literal, _vars) when is_boolean(literal), do: :boolean
1343
+ def quoted_type(literal, _vars) when is_atom(literal) and not is_nil(literal), do: :atom
1344
+ def quoted_type(literal, _vars) when is_integer(literal), do: :integer
1345
+
1346
+ # Tuples
1347
+ def quoted_type({left, right}, vars), do: quoted_type({:{}, [], [left, right]}, vars)
1348
+ def quoted_type({:{}, _, elems}, vars), do: {:tuple, Enum.map(elems, &quoted_type(&1, vars))}
1349
+
1350
+ def quoted_type({name, _, args}, _vars) when is_atom(name) and is_list(args) do
1351
+ case call_type(name, length(args)) do
1352
+ {_in, out} -> out
1353
+ nil -> :any
1354
+ end
1355
+ end
1356
+
1357
+ def quoted_type(_, _vars), do: :any
1358
+
1359
+ defp get_env({env, _}), do: env
1360
+ defp get_env(env), do: env
1361
+
1362
+ defp normalize_type(value, :binary),
1363
+ do: quote(do: (is_binary(unquote(value)) && :binary) || :bitstring)
1364
+
1365
+ @doc """
1366
+ Raises a query building error.
1367
+ """
1368
+ def error!(message) when is_binary(message) do
1369
+ {:current_stacktrace, [_ | t]} = Process.info(self(), :current_stacktrace)
1370
+
1371
+ t =
1372
+ Enum.drop_while(t, fn
1373
+ {mod, _, _, _} ->
1374
+ String.starts_with?(Atom.to_string(mod), ["Elixir.Ecto.Query.", "Elixir.Enum"])
1375
+
1376
+ _ ->
1377
+ false
1378
+ end)
1379
+
1380
+ reraise Ecto.Query.CompileError, [message: message], t
1381
+ end
1382
+
1383
+ @doc """
1384
+ Counts the bindings in a query expression.
1385
+
1386
+ ## Examples
1387
+
1388
+ iex> count_binds(%Ecto.Query{joins: [1,2,3]})
1389
+ 4
1390
+
1391
+ """
1392
+ @spec count_binds(Ecto.Query.t()) :: non_neg_integer
1393
+ def count_binds(%Query{joins: joins}) do
1394
+ 1 + length(joins)
1395
+ end
1396
+
1397
+ @doc """
1398
+ Bump interpolations by the length of parameters.
1399
+ """
1400
+ def bump_interpolations(expr, []), do: expr
1401
+
1402
+ def bump_interpolations(expr, params) do
1403
+ len = length(params)
1404
+
1405
+ Macro.prewalk(expr, fn
1406
+ {:^, meta, [counter]} when is_integer(counter) -> {:^, meta, [len + counter]}
1407
+ other -> other
1408
+ end)
1409
+ end
1410
+
1411
+ @doc """
1412
+ Bump subqueries by the count of pre-existing subqueries.
1413
+ """
1414
+ def bump_subqueries(expr, []), do: expr
1415
+
1416
+ def bump_subqueries(expr, subqueries) do
1417
+ len = length(subqueries)
1418
+
1419
+ Macro.prewalk(expr, fn
1420
+ {:subquery, counter} -> {:subquery, len + counter}
1421
+ other -> other
1422
+ end)
1423
+ end
1424
+
1425
+ @doc """
1426
+ Called by the select escaper at compile time and dynamic builder at runtime to track select aliases
1427
+ """
1428
+ def add_select_alias(aliases, name) when is_map(aliases) and is_atom(name) do
1429
+ case aliases do
1430
+ %{^name => _} ->
1431
+ error!(
1432
+ "the alias `#{inspect(name)}` has been specified more than once using `selected_as/2`"
1433
+ )
1434
+
1435
+ aliases ->
1436
+ Map.put(aliases, name, @select_alias_dummy_value)
1437
+ end
1438
+ end
1439
+
1440
+ def add_select_alias(aliases, name) do
1441
+ aliases =
1442
+ case aliases do
1443
+ %{} -> Macro.escape(aliases)
1444
+ aliases -> aliases
1445
+ end
1446
+
1447
+ quote do: Ecto.Query.Builder.add_select_alias(unquote(aliases), unquote(name))
1448
+ end
1449
+
1450
+ @doc """
1451
+ Applies a query at compilation time or at runtime.
1452
+
1453
+ This function is responsible for checking if a given query is an
1454
+ `Ecto.Query` struct at compile time. If it is not it will act
1455
+ accordingly.
1456
+
1457
+ If a query is available, it invokes the `apply` function in the
1458
+ given `module`, otherwise, it delegates the call to runtime.
1459
+
1460
+ It is important to keep in mind the complexities introduced
1461
+ by this function. In particular, a %Query{} is a mixture of escaped
1462
+ and unescaped expressions which makes it impossible for this
1463
+ function to properly escape or unescape it at compile/runtime.
1464
+ For this reason, the apply function should be ready to handle
1465
+ arguments in both escaped and unescaped form.
1466
+
1467
+ For example, take into account the `Builder.OrderBy`:
1468
+
1469
+ select = %Ecto.Query.QueryExpr{expr: expr, file: env.file, line: env.line}
1470
+ Builder.apply_query(query, __MODULE__, [order_by], env)
1471
+
1472
+ `expr` is already an escaped expression and we must not escape
1473
+ it again. However, it is wrapped in an Ecto.Query.QueryExpr,
1474
+ which must be escaped! Furthermore, the `apply/2` function
1475
+ in `Builder.OrderBy` very likely will inject the QueryExpr inside
1476
+ Query, which again, is a mixture of escaped and unescaped expressions.
1477
+
1478
+ That said, you need to obey the following rules:
1479
+
1480
+ 1. In order to call this function, the arguments must be escapable
1481
+ values supported by the `escape/1` function below;
1482
+
1483
+ 2. The apply function may not manipulate the given arguments,
1484
+ with exception to the query.
1485
+
1486
+ In particular, when invoked at compilation time, all arguments
1487
+ (except the query) will be escaped, so they can be injected into
1488
+ the query properly, but they will be in their runtime form
1489
+ when invoked at runtime.
1490
+ """
1491
+ @spec apply_query(Macro.t(), Macro.t(), Macro.t(), Macro.Env.t()) :: Macro.t()
1492
+ def apply_query(query, module, args, env) do
1493
+ case Macro.expand(query, env) |> unescape_query() do
1494
+ %Query{} = compiletime_query ->
1495
+ apply(module, :apply, [compiletime_query | args])
1496
+ |> escape_query()
1497
+
1498
+ runtime_query ->
1499
+ quote do
1500
+ # Unquote the query before `module.apply()` for any binding variable.
1501
+ query = unquote(runtime_query)
1502
+ unquote(module).apply(query, unquote_splicing(args))
1503
+ end
1504
+ end
1505
+ end
1506
+
1507
+ # Unescapes an `Ecto.Query` struct.
1508
+ @spec unescape_query(Macro.t()) :: Query.t() | Macro.t()
1509
+ defp unescape_query({:%, _, [Query, {:%{}, _, list}]}) do
1510
+ struct(Query, list)
1511
+ end
1512
+
1513
+ defp unescape_query({:%{}, _, list} = ast) do
1514
+ if List.keyfind(list, :__struct__, 0) == {:__struct__, Query} do
1515
+ Map.new(list)
1516
+ else
1517
+ ast
1518
+ end
1519
+ end
1520
+
1521
+ defp unescape_query(other) do
1522
+ other
1523
+ end
1524
+
1525
+ # Escapes an `Ecto.Query` and associated structs.
1526
+ @spec escape_query(Query.t()) :: Macro.t()
1527
+ defp escape_query(%Query{} = query), do: {:%{}, [], Map.to_list(query)}
1528
+
1529
+ defp parse_access_get({{:., _, [Access, :get]}, _, [left, right]}, acc) do
1530
+ parse_access_get(left, [right | acc])
1531
+ end
1532
+
1533
+ defp parse_access_get({{:., _, [{var, _, context}, field]}, _, []} = expr, acc)
1534
+ when is_atom(var) and is_atom(context) and is_atom(field) do
1535
+ {expr, acc}
1536
+ end
1537
+
1538
+ defp parse_access_get({{:., _, [{kind, _, [_]}, field]}, _, []} = expr, acc)
1539
+ when kind in [:as, :parent_as] and is_atom(field) do
1540
+ {expr, acc}
1541
+ end
1542
+ end
deps/ecto/lib/ecto/query/builder/combination.ex ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Combination do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Builds a quoted expression.
10
+
11
+ The quoted expression should evaluate to a query at runtime.
12
+ If possible, it does all calculations at compile time to avoid
13
+ runtime work.
14
+ """
15
+ @spec build(atom, Macro.t, Macro.t, Macro.Env.t) :: Macro.t
16
+ def build(kind, query, {:^, _, [expr]}, env) do
17
+ expr = quote do: Ecto.Queryable.to_query(unquote(expr))
18
+ Builder.apply_query(query, __MODULE__, [[{kind, expr}]], env)
19
+ end
20
+
21
+ def build(kind, _query, other, _env) do
22
+ Builder.error! "`#{Macro.to_string(other)}` is not a valid #{kind}. " <>
23
+ "#{kind} must always be an interpolated query, such as ^existing_query"
24
+ end
25
+
26
+ @doc """
27
+ The callback applied by `build/4` to build the query.
28
+ """
29
+ @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
30
+ def apply(%Ecto.Query{combinations: combinations} = query, value) do
31
+ %{query | combinations: combinations ++ value}
32
+ end
33
+ def apply(query, value) do
34
+ apply(Ecto.Queryable.to_query(query), value)
35
+ end
36
+ end
deps/ecto/lib/ecto/query/builder/cte.ex ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 3]
2
+
3
+ defmodule Ecto.Query.Builder.CTE do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Escapes the CTE name.
10
+
11
+ iex> escape(quote(do: "FOO"), __ENV__)
12
+ "FOO"
13
+
14
+ """
15
+ @spec escape(Macro.t, Macro.Env.t) :: Macro.t
16
+ def escape(name, _env) when is_bitstring(name), do: name
17
+
18
+ def escape({:^, _, [expr]}, _env), do: expr
19
+
20
+ def escape(expr, env) do
21
+ case Macro.expand_once(expr, env) do
22
+ ^expr ->
23
+ Builder.error! "`#{Macro.to_string(expr)}` is not a valid CTE name. " <>
24
+ "It must be a literal string or an interpolated variable."
25
+
26
+ expr ->
27
+ escape(expr, env)
28
+ end
29
+ end
30
+
31
+ @doc """
32
+ Builds a quoted expression.
33
+
34
+ The quoted expression should evaluate to a query at runtime.
35
+ If possible, it does all calculations at compile time to avoid
36
+ runtime work.
37
+ """
38
+ @spec build(Macro.t, Macro.t, Macro.t, nil | boolean(), nil | :all | :update_all | :delete_all , Macro.Env.t) :: Macro.t
39
+ def build(query, name, cte, materialized, operation, env) do
40
+ Builder.apply_query(query, __MODULE__, [escape(name, env), build_cte(name, cte, env), materialized, operation], env)
41
+ end
42
+
43
+ @spec build_cte(Macro.t, Macro.t, Macro.Env.t) :: Macro.t
44
+ def build_cte(_name, {:^, _, [expr]}, _env) do
45
+ quote do: Ecto.Queryable.to_query(unquote(expr))
46
+ end
47
+
48
+ def build_cte(_name, {:fragment, _, _} = fragment, env) do
49
+ {expr, {params, _acc}} = Builder.escape(fragment, :any, {[], %{}}, [], env)
50
+ params = Builder.escape_params(params)
51
+
52
+ quote do
53
+ %Ecto.Query.QueryExpr{
54
+ expr: unquote(expr),
55
+ params: unquote(params),
56
+ file: unquote(env.file),
57
+ line: unquote(env.line)
58
+ }
59
+ end
60
+ end
61
+
62
+ def build_cte(name, cte, env) do
63
+ case Macro.expand_once(cte, env) do
64
+ ^cte ->
65
+ Builder.error! "`#{Macro.to_string(cte)}` is not a valid CTE (named: #{Macro.to_string(name)}). " <>
66
+ "The CTE must be an interpolated query, such as ^existing_query or a fragment."
67
+
68
+ cte ->
69
+ build_cte(name, cte, env)
70
+ end
71
+ end
72
+
73
+ @doc """
74
+ The callback applied by `build/4` to build the query.
75
+ """
76
+ @spec apply(Ecto.Queryable.t, bitstring, Ecto.Queryable.t, nil | boolean(), nil | :all | :update_all | :delete_all) :: Ecto.Query.t
77
+ # Runtime
78
+ def apply(query, name, with_query, materialized, nil) do
79
+ apply(query, name, with_query, materialized, :all)
80
+ end
81
+
82
+ def apply(_query, _name, _with_query, _materialized, operation)
83
+ when operation not in [:all, :update_all, :delete_all] do
84
+ Builder.error!("`operation` option must be one of :all, :update_all, or :delete_all")
85
+ end
86
+
87
+ def apply(%Ecto.Query{with_ctes: with_expr} = query, name, %_{} = with_query, materialized, operation) do
88
+ %{query | with_ctes: apply_cte(with_expr, name, with_query, materialized, operation)}
89
+ end
90
+
91
+ # Compile
92
+ def apply(%Ecto.Query{with_ctes: with_expr} = query, name, with_query, materialized, operation) do
93
+ update = quote do
94
+ Ecto.Query.Builder.CTE.apply_cte(unquote(with_expr), unquote(name), unquote(with_query), unquote(materialized), unquote(operation))
95
+ end
96
+
97
+ %{query | with_ctes: update}
98
+ end
99
+
100
+ # Runtime catch-all
101
+ def apply(query, name, with_query, materialized, operation) do
102
+ apply(Ecto.Queryable.to_query(query), name, with_query, materialized, operation)
103
+ end
104
+
105
+ @doc false
106
+ def apply_cte(nil, name, with_query, materialized, operation) when is_boolean(materialized) do
107
+ %Ecto.Query.WithExpr{queries: [{name, %{materialized: materialized, operation: operation}, with_query}]}
108
+ end
109
+
110
+ def apply_cte(nil, name, with_query, _materialized, operation) do
111
+ %Ecto.Query.WithExpr{queries: [{name, %{operation: operation}, with_query}]}
112
+ end
113
+
114
+ def apply_cte(%Ecto.Query.WithExpr{queries: queries} = with_expr, name, with_query, materialized, operation) when is_boolean(materialized) do
115
+ %{with_expr | queries: List.keystore(queries, name, 0, {name, %{materialized: materialized, operation: operation}, with_query})}
116
+ end
117
+
118
+ def apply_cte(%Ecto.Query.WithExpr{queries: queries} = with_expr, name, with_query, _materialized, operation) do
119
+ %{with_expr | queries: List.keystore(queries, name, 0, {name, %{operation: operation}, with_query})}
120
+ end
121
+ end
deps/ecto/lib/ecto/query/builder/distinct.ex ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Distinct do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Escapes a list of quoted expressions.
10
+
11
+ iex> escape(quote do true end, {[], %{}}, [], __ENV__)
12
+ {true, {[], %{}}}
13
+
14
+ iex> escape(quote do [x.x, 13] end, {[], %{}}, [x: 0], __ENV__)
15
+ {[asc: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]},
16
+ asc: 13],
17
+ {[], %{}}}
18
+
19
+ """
20
+ @spec escape(Macro.t, {list, term}, Keyword.t, Macro.Env.t) :: {Macro.t, {list, term}}
21
+ def escape(expr, params_acc, _vars, _env) when is_boolean(expr) do
22
+ {expr, params_acc}
23
+ end
24
+
25
+ def escape(expr, params_acc, vars, env) do
26
+ Builder.OrderBy.escape(:distinct, expr, params_acc, vars, env)
27
+ end
28
+
29
+ @doc """
30
+ Called at runtime to verify distinct.
31
+ """
32
+ def distinct!(query, distinct, file, line) when is_boolean(distinct) do
33
+ apply(query, %Ecto.Query.ByExpr{expr: distinct, params: [], line: line, file: file})
34
+ end
35
+ def distinct!(query, distinct, file, line) do
36
+ {expr, params, subqueries} =
37
+ Builder.OrderBy.order_by_or_distinct!(:distinct, query, distinct, [])
38
+
39
+ expr = %Ecto.Query.ByExpr{
40
+ expr: expr,
41
+ params: Enum.reverse(params),
42
+ line: line,
43
+ file: file,
44
+ subqueries: subqueries
45
+ }
46
+
47
+ apply(query, expr)
48
+ end
49
+
50
+ @doc """
51
+ Builds a quoted expression.
52
+
53
+ The quoted expression should evaluate to a query at runtime.
54
+ If possible, it does all calculations at compile time to avoid
55
+ runtime work.
56
+ """
57
+ @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
58
+ def build(query, _binding, {:^, _, [var]}, env) do
59
+ quote do
60
+ Ecto.Query.Builder.Distinct.distinct!(unquote(query), unquote(var), unquote(env.file), unquote(env.line))
61
+ end
62
+ end
63
+
64
+ def build(query, binding, expr, env) do
65
+ {query, binding} = Builder.escape_binding(query, binding, env)
66
+ {expr, {params, acc}} = escape(expr, {[], %{subqueries: []}}, binding, env)
67
+ params = Builder.escape_params(params)
68
+
69
+ distinct = quote do: %Ecto.Query.ByExpr{
70
+ expr: unquote(expr),
71
+ params: unquote(params),
72
+ subqueries: unquote(acc.subqueries),
73
+ file: unquote(env.file),
74
+ line: unquote(env.line)}
75
+ Builder.apply_query(query, __MODULE__, [distinct], env)
76
+ end
77
+
78
+ @doc """
79
+ The callback applied by `build/4` to build the query.
80
+ """
81
+ @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
82
+ def apply(%Ecto.Query{distinct: nil} = query, expr) do
83
+ %{query | distinct: expr}
84
+ end
85
+ def apply(%Ecto.Query{}, _expr) do
86
+ Builder.error! "only one distinct expression is allowed in query"
87
+ end
88
+ def apply(query, expr) do
89
+ apply(Ecto.Queryable.to_query(query), expr)
90
+ end
91
+ end
deps/ecto/lib/ecto/query/builder/dynamic.ex ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Dynamic do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+ alias Ecto.Query.Builder.Select
8
+
9
+ @doc """
10
+ Builds a dynamic expression.
11
+ """
12
+ @spec build([Macro.t], Macro.t, Macro.Env.t) :: Macro.t
13
+ def build(binding, expr, env) do
14
+ {query, vars} = Builder.escape_binding(quote(do: query), binding, env)
15
+ {expr, {params, acc}} = escape(expr, {[], %{subqueries: [], aliases: %{}}}, vars, env)
16
+ aliases = escape_select_aliases(acc.aliases)
17
+ params = Builder.escape_params(params)
18
+
19
+ quote do
20
+ %Ecto.Query.DynamicExpr{fun: fn query ->
21
+ _ = unquote(query)
22
+ {unquote(expr), unquote(params), unquote(Enum.reverse(acc.subqueries)), unquote(aliases)}
23
+ end,
24
+ binding: unquote(Macro.escape(binding)),
25
+ file: unquote(env.file),
26
+ line: unquote(env.line)}
27
+ end
28
+ end
29
+
30
+ defp escape({:selected_as, _, [_, _]} = expr, _params_acc, vars, env) do
31
+ Select.escape(expr, vars, env)
32
+ end
33
+
34
+ defp escape({:%{}, _, _} = expr, _params_acc, vars, env) do
35
+ Select.escape(expr, vars, env)
36
+ end
37
+
38
+ defp escape(expr, params_acc, vars, env) do
39
+ Builder.escape(expr, :any, params_acc, vars, {env, &escape_expansion/5})
40
+ end
41
+
42
+ defp escape_expansion(expr, _type, params_acc, vars, env) do
43
+ escape(expr, params_acc, vars, env)
44
+ end
45
+
46
+ defp escape_select_aliases(%{} = aliases), do: Builder.escape_select_aliases(aliases)
47
+ defp escape_select_aliases(aliases), do: aliases
48
+
49
+ @doc """
50
+ Expands a dynamic expression for insertion into the given query.
51
+ """
52
+ def fully_expand(query, %{file: file, line: line, binding: binding} = dynamic) do
53
+ {expr, {binding, params, subqueries, _aliases, _count}} = expand(query, dynamic, {binding, [], [], %{}, 0})
54
+ {expr, binding, Enum.reverse(params), Enum.reverse(subqueries), file, line}
55
+ end
56
+
57
+ @doc """
58
+ Expands a dynamic expression as part of an existing expression.
59
+
60
+ Any dynamic expression parameter is prepended and the parameters
61
+ list is not reversed. This is useful when the dynamic expression
62
+ is given in the middle of an expression.
63
+ """
64
+ def partially_expand(query, %{binding: binding} = dynamic, params, subqueries, aliases, count) do
65
+ {expr, {_binding, params, subqueries, aliases, count}} =
66
+ expand(query, dynamic, {binding, params, subqueries, aliases, count})
67
+
68
+ {expr, params, subqueries, aliases, count}
69
+ end
70
+
71
+ def partially_expand(kind, query, %{binding: binding} = dynamic, params, count) do
72
+ {expr, {_binding, params, subqueries, _aliases, count}} =
73
+ expand(query, dynamic, {binding, params, [], %{}, count})
74
+
75
+ if subqueries != [] do
76
+ raise ArgumentError, "subqueries are not allowed in `#{kind}` expressions"
77
+ end
78
+
79
+ {expr, params, count}
80
+ end
81
+
82
+ defp expand(query, %{fun: fun}, {binding, params, subqueries, aliases, count}) do
83
+ {dynamic_expr, dynamic_params, dynamic_subqueries, dynamic_aliases} = fun.(query)
84
+ aliases = merge_aliases(aliases, dynamic_aliases)
85
+
86
+ Macro.postwalk(dynamic_expr, {binding, params, subqueries, aliases, count}, fn
87
+ {:^, meta, [ix]}, {binding, params, subqueries, aliases, count} ->
88
+ case Enum.fetch!(dynamic_params, ix) do
89
+ {%Ecto.Query.DynamicExpr{binding: new_binding} = dynamic, _} ->
90
+ binding = if length(new_binding) > length(binding), do: new_binding, else: binding
91
+ expand(query, dynamic, {binding, params, subqueries, aliases, count})
92
+
93
+ param ->
94
+ {{:^, meta, [count]}, {binding, [param | params], subqueries, aliases, count + 1}}
95
+ end
96
+
97
+ {:subquery, i}, {binding, params, subqueries, aliases, count} ->
98
+ subquery = Enum.fetch!(dynamic_subqueries, i)
99
+ ix = length(subqueries)
100
+ {{:subquery, ix}, {binding, [{:subquery, ix} | params], [subquery | subqueries], aliases, count + 1}}
101
+
102
+ expr, acc ->
103
+ {expr, acc}
104
+ end)
105
+ end
106
+
107
+ defp merge_aliases(old_aliases, new_aliases) do
108
+ Enum.reduce(new_aliases, old_aliases, fn {alias, _}, aliases ->
109
+ Builder.add_select_alias(aliases, alias)
110
+ end)
111
+ end
112
+ end
deps/ecto/lib/ecto/query/builder/filter.ex ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 3]
2
+
3
+ defmodule Ecto.Query.Builder.Filter do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Escapes a where or having clause.
10
+
11
+ It allows query expressions that evaluate to a boolean
12
+ or a keyword list of field names and values. In a keyword
13
+ list multiple key value pairs will be joined with "and".
14
+
15
+ Returned is `{expression, {params, %{subqueries: subqueries}}}` which is
16
+ a valid escaped expression, see `Macro.escape/2`. Both `params`
17
+ and `subqueries` are reversed.
18
+ """
19
+ @spec escape(:where | :having | :on, Macro.t, non_neg_integer, Keyword.t, Macro.Env.t) :: {Macro.t, {list, Builder.acc()}}
20
+ def escape(_kind, [], _binding, _vars, _env) do
21
+ {true, {[], %{subqueries: []}}}
22
+ end
23
+
24
+ def escape(kind, expr, binding, vars, env) when is_list(expr) do
25
+ {parts, params_acc} =
26
+ Enum.map_reduce(expr, {[], %{subqueries: []}}, fn
27
+ {field, nil}, _params_acc ->
28
+ Builder.error! "nil given for `#{field}`. Comparison with nil is forbidden as it is unsafe. " <>
29
+ "Instead write a query with is_nil/1, for example: is_nil(s.#{field})"
30
+
31
+ {field, value}, params_acc when is_atom(field) ->
32
+ value = check_for_nils(value, field)
33
+ {value, params_acc} = Builder.escape(value, {binding, field}, params_acc, vars, env)
34
+ {{:{}, [], [:==, [], [to_escaped_field(binding, field), value]]}, params_acc}
35
+
36
+ _, _params_acc ->
37
+ Builder.error! "expected a keyword list at compile time in #{kind}, " <>
38
+ "got: `#{Macro.to_string expr}`. If you would like to " <>
39
+ "pass a list dynamically, please interpolate the whole list with ^"
40
+ end)
41
+
42
+ expr = Enum.reduce parts, &{:{}, [], [:and, [], [&2, &1]]}
43
+ {expr, params_acc}
44
+ end
45
+
46
+ def escape(_kind, expr, _binding, vars, env) do
47
+ Builder.escape(expr, :boolean, {[], %{subqueries: []}}, vars, env)
48
+ end
49
+
50
+ @doc """
51
+ Builds a quoted expression.
52
+
53
+ The quoted expression should evaluate to a query at runtime.
54
+ If possible, it does all calculations at compile time to avoid
55
+ runtime work.
56
+ """
57
+ @spec build(:where | :having, :and | :or, Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
58
+ def build(kind, op, query, _binding, {:^, _, [var]}, env) do
59
+ quote do
60
+ Ecto.Query.Builder.Filter.filter!(unquote(kind), unquote(op), unquote(query),
61
+ unquote(var), 0, unquote(env.file), unquote(env.line))
62
+ end
63
+ end
64
+
65
+ def build(kind, op, query, binding, expr, env) do
66
+ {query, binding} = Builder.escape_binding(query, binding, env)
67
+ {expr, {params, acc}} = escape(kind, expr, 0, binding, env)
68
+
69
+ params = Builder.escape_params(params)
70
+ subqueries = Enum.reverse(acc.subqueries)
71
+
72
+ expr = quote do: %Ecto.Query.BooleanExpr{
73
+ expr: unquote(expr),
74
+ op: unquote(op),
75
+ params: unquote(params),
76
+ subqueries: unquote(subqueries),
77
+ file: unquote(env.file),
78
+ line: unquote(env.line)}
79
+ Builder.apply_query(query, __MODULE__, [kind, expr], env)
80
+ end
81
+
82
+ @doc """
83
+ The callback applied by `build/4` to build the query.
84
+ """
85
+ @spec apply(Ecto.Queryable.t, :where | :having, term) :: Ecto.Query.t
86
+ def apply(query, _, %{expr: true}) do
87
+ query
88
+ end
89
+ def apply(%Ecto.Query{wheres: wheres} = query, :where, expr) do
90
+ %{query | wheres: wheres ++ [expr]}
91
+ end
92
+ def apply(%Ecto.Query{havings: havings} = query, :having, expr) do
93
+ %{query | havings: havings ++ [expr]}
94
+ end
95
+ def apply(query, kind, expr) do
96
+ apply(Ecto.Queryable.to_query(query), kind, expr)
97
+ end
98
+
99
+ @doc """
100
+ Builds a filter based on the given arguments.
101
+
102
+ This is shared by having, where and join's on expressions.
103
+ """
104
+ def filter!(kind, query, %Ecto.Query.DynamicExpr{} = dynamic, _binding, _file, _line) do
105
+ {expr, _binding, params, subqueries, file, line} =
106
+ Ecto.Query.Builder.Dynamic.fully_expand(query, dynamic)
107
+
108
+ if subqueries != [] do
109
+ raise ArgumentError, "subqueries are not allowed in `#{kind}` expressions"
110
+ end
111
+
112
+ {expr, params, file, line}
113
+ end
114
+
115
+ def filter!(_kind, _query, bool, _binding, file, line) when is_boolean(bool) do
116
+ {bool, [], file, line}
117
+ end
118
+
119
+ def filter!(kind, _query, kw, binding, file, line) when is_list(kw) do
120
+ {expr, params} = kw!(kind, kw, binding)
121
+ {expr, params, file, line}
122
+ end
123
+
124
+ def filter!(kind, _query, other, _binding, _file, _line) do
125
+ raise ArgumentError, "expected a keyword list or dynamic expression in `#{kind}`, got: `#{inspect other}`"
126
+ end
127
+
128
+ @doc """
129
+ Builds the filter and applies it to the given query as boolean operator.
130
+ """
131
+ def filter!(:where, op, query, %Ecto.Query.DynamicExpr{} = dynamic, _binding, _file, _line) do
132
+ {expr, _binding, params, subqueries, file, line} =
133
+ Ecto.Query.Builder.Dynamic.fully_expand(query, dynamic)
134
+
135
+ boolean = %Ecto.Query.BooleanExpr{
136
+ expr: expr,
137
+ params: params,
138
+ line: line,
139
+ file: file,
140
+ op: op,
141
+ subqueries: subqueries
142
+ }
143
+
144
+ apply(query, :where, boolean)
145
+ end
146
+
147
+ def filter!(kind, op, query, expr, binding, file, line) do
148
+ {expr, params, file, line} = filter!(kind, query, expr, binding, file, line)
149
+ boolean = %Ecto.Query.BooleanExpr{expr: expr, params: params, line: line, file: file, op: op}
150
+ apply(query, kind, boolean)
151
+ end
152
+
153
+ defp kw!(kind, kw, binding) do
154
+ case kw!(kw, binding, 0, [], [], kind, kw) do
155
+ {[], params} -> {true, params}
156
+ {parts, params} -> {Enum.reduce(parts, &{:and, [], [&2, &1]}), params}
157
+ end
158
+ end
159
+
160
+ defp kw!([{field, nil}|_], _binding, _counter, _exprs, _params, _kind, _original) when is_atom(field) do
161
+ raise ArgumentError, "nil given for #{inspect field}. Comparison with nil is forbidden as it is unsafe. " <>
162
+ "Instead write a query with is_nil/1, for example: is_nil(s.#{field})"
163
+ end
164
+ defp kw!([{field, value}|t], binding, counter, exprs, params, kind, original) when is_atom(field) do
165
+ kw!(t, binding, counter + 1,
166
+ [{:==, [], [to_field(binding, field), {:^, [], [counter]}]}|exprs],
167
+ [{value, {binding, field}}|params],
168
+ kind, original)
169
+ end
170
+ defp kw!([], _binding, _counter, exprs, params, _kind, _original) do
171
+ {Enum.reverse(exprs), Enum.reverse(params)}
172
+ end
173
+ defp kw!(_, _binding, _counter, _exprs, _params, kind, original) do
174
+ raise ArgumentError, "expected a keyword list in `#{kind}`, got: `#{inspect original}`"
175
+ end
176
+
177
+ defp to_field(binding, field),
178
+ do: {{:., [], [{:&, [], [binding]}, field]}, [], []}
179
+ defp to_escaped_field(binding, field),
180
+ do: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [binding]]}, field]]}, [], []]}
181
+
182
+ defp check_for_nils({:^, _, [var]}, field) do
183
+ quote do
184
+ ^Ecto.Query.Builder.Filter.not_nil!(unquote(var), unquote(field))
185
+ end
186
+ end
187
+
188
+ defp check_for_nils(value, _field), do: value
189
+
190
+ def not_nil!(nil, field) do
191
+ raise ArgumentError, "nil given for `#{field}`. comparison with nil is forbidden as it is unsafe. " <>
192
+ "Instead write a query with is_nil/1, for example: is_nil(s.#{field})"
193
+ end
194
+
195
+ def not_nil!(other, _field), do: other
196
+ end
deps/ecto/lib/ecto/query/builder/from.ex ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Query.Builder.From do
2
+ @moduledoc false
3
+
4
+ alias Ecto.Query.Builder
5
+
6
+ @doc """
7
+ Handles from expressions.
8
+
9
+ The expressions may either contain an `in` expression or not.
10
+ The right side is always expected to Queryable.
11
+
12
+ ## Examples
13
+
14
+ iex> escape(quote(do: MySchema), __ENV__)
15
+ {MySchema, []}
16
+
17
+ iex> escape(quote(do: p in posts), __ENV__)
18
+ {quote(do: posts), [p: 0]}
19
+
20
+ iex> escape(quote(do: p in {"posts", MySchema}), __ENV__)
21
+ {{"posts", MySchema}, [p: 0]}
22
+
23
+ iex> escape(quote(do: [p, q] in posts), __ENV__)
24
+ {quote(do: posts), [p: 0, q: 1]}
25
+
26
+ iex> escape(quote(do: [_, _] in abc), __ENV__)
27
+ {quote(do: abc), [_: 0, _: 1]}
28
+
29
+ iex> escape(quote(do: other), __ENV__)
30
+ {quote(do: other), []}
31
+
32
+ iex> escape(quote(do: x() in other), __ENV__)
33
+ ** (Ecto.Query.CompileError) binding list should contain only variables or `{as, var}` tuples, got: x()
34
+
35
+ """
36
+ @spec escape(Macro.t(), Macro.Env.t()) :: {Macro.t(), Keyword.t()}
37
+ def escape({:in, _, [var, query]}, env) do
38
+ query = escape_source(query, env)
39
+ Builder.escape_binding(query, List.wrap(var), env)
40
+ end
41
+
42
+ def escape(query, env) do
43
+ query = escape_source(query, env)
44
+ {query, []}
45
+ end
46
+
47
+ defp escape_source(query, env) do
48
+ case Macro.expand_once(query, env) do
49
+ {:fragment, _, _} = fragment ->
50
+ {fragment, {params, _acc}} = Builder.escape(fragment, :any, {[], %{}}, [], env)
51
+ {fragment, Builder.escape_params(params)}
52
+
53
+ {:values, _, [values_list, types]} ->
54
+ prelude = quote do: values = Ecto.Query.Values.new(unquote(values_list), unquote(types))
55
+ types = quote do: values.types
56
+ num_rows = quote do: values.num_rows
57
+ params = quote do: Ecto.Query.Builder.escape_params(values.params)
58
+ {{:{}, [], [:values, [], [types, num_rows]]}, prelude, params}
59
+
60
+ ^query ->
61
+ case query do
62
+ {left, right} -> {left, Macro.expand(right, env)}
63
+ _ -> query
64
+ end
65
+
66
+ other ->
67
+ escape_source(other, env)
68
+ end
69
+ end
70
+
71
+ @typep hints :: [String.t() | Macro.t()]
72
+
73
+ @doc """
74
+ Builds a quoted expression.
75
+
76
+ The quoted expression should evaluate to a query at runtime.
77
+ If possible, it does all calculations at compile time to avoid
78
+ runtime work.
79
+ """
80
+ @spec build(Macro.t(), Macro.Env.t(), atom, {:ok, Ecto.Schema.prefix | nil} | nil, hints) ::
81
+ {Macro.t(), Keyword.t(), non_neg_integer | nil}
82
+ def build(query, env, as, prefix, hints) do
83
+ hints = Enum.map(hints, &hint!(&1))
84
+
85
+ prefix = case prefix do
86
+ nil -> nil
87
+ {:ok, prefix} when is_binary(prefix) or is_nil(prefix) -> {:ok, prefix}
88
+ {:ok, {:^, _, [prefix]}} -> {:ok, prefix}
89
+ {:ok, prefix} -> Builder.error!("`prefix` must be a compile time string or an interpolated value using ^, got: #{Macro.to_string(prefix)}")
90
+ end
91
+
92
+ as = case as do
93
+ {:^, _, [as]} -> as
94
+ as when is_atom(as) -> as
95
+ as -> Builder.error!("`as` must be a compile time atom or an interpolated value using ^, got: #{Macro.to_string(as)}")
96
+ end
97
+
98
+ {query, binds} = escape(query, env)
99
+
100
+ case query do
101
+ schema when is_atom(schema) ->
102
+ # Get the source at runtime so no unnecessary compile time
103
+ # dependencies between modules are added
104
+ source = quote(do: unquote(schema).__schema__(:source))
105
+ {:ok, prefix} = prefix || {:ok, quote(do: unquote(schema).__schema__(:prefix))}
106
+ {query(prefix, {source, schema}, [], as, hints, env.file, env.line), binds, 1}
107
+
108
+ source when is_binary(source) ->
109
+ {:ok, prefix} = prefix || {:ok, nil}
110
+ # When a binary is used, there is no schema
111
+ {query(prefix, {source, nil}, [], as, hints, env.file, env.line), binds, 1}
112
+
113
+ {source, schema} when is_binary(source) and is_atom(schema) ->
114
+ {:ok, prefix} = prefix || {:ok, quote(do: unquote(schema).__schema__(:prefix))}
115
+ {query(prefix, {source, schema}, [], as, hints, env.file, env.line), binds, 1}
116
+
117
+ {{:{}, _, [:fragment, _, _]} = fragment, params} ->
118
+ {:ok, prefix} = prefix || {:ok, nil}
119
+ {query(prefix, fragment, params, as, hints, env.file, env.line), binds, 1}
120
+
121
+ {{:{}, _, [:values, _, _]} = values, prelude, params} ->
122
+ {:ok, prefix} = prefix || {:ok, nil}
123
+ query = query(prefix, values, params, as, hints, env.file, env.line)
124
+
125
+ quoted =
126
+ quote do
127
+ unquote(prelude)
128
+ unquote(query)
129
+ end
130
+
131
+ {quoted, binds, 1}
132
+
133
+ _other ->
134
+ quoted =
135
+ quote do
136
+ Ecto.Query.Builder.From.apply(unquote(query), unquote(length(binds)), unquote(as), unquote(prefix), unquote(hints))
137
+ end
138
+
139
+ {quoted, binds, nil}
140
+ end
141
+ end
142
+
143
+ defp query(prefix, source, params, as, hints, file, line) do
144
+ aliases = if as, do: [{as, 0}], else: []
145
+ from_fields = [source: source, params: params, as: as, prefix: prefix, hints: hints, file: file, line: line]
146
+
147
+ query_fields = [
148
+ from: {:%, [], [Ecto.Query.FromExpr, {:%{}, [], from_fields}]},
149
+ aliases: {:%{}, [], aliases}
150
+ ]
151
+
152
+ {:%, [], [Ecto.Query, {:%{}, [], query_fields}]}
153
+ end
154
+
155
+ @doc """
156
+ Validates hints at compile time and runtime
157
+ """
158
+ def hint!(hint) when is_binary(hint), do: hint
159
+
160
+ def hint!({:unsafe_fragment, _, [fragment]}) do
161
+ case fragment do
162
+ {:^, _, [value]} ->
163
+ quote do: Ecto.Query.Builder.From.hint!(unquote(value))
164
+
165
+ _ ->
166
+ Builder.error!(
167
+ "`unsafe_fragment/1` in `hints` expects an interpolated value, such as " <>
168
+ "unsafe_fragment(^value), got: `#{Macro.to_string(fragment)}`"
169
+ )
170
+ end
171
+ end
172
+
173
+ def hint!(other) do
174
+ Builder.error!(
175
+ "`hints` must be a compile time string, unsafe fragment of the form `unsafe_fragment(^...)`, " <>
176
+ "or list containing either, got: `#{Macro.to_string(other)}`"
177
+ )
178
+ end
179
+
180
+ @doc """
181
+ The callback applied by `build/2` to build the query.
182
+ """
183
+ @spec apply(Ecto.Queryable.t(), non_neg_integer, Macro.t(), {:ok, Ecto.Schema.prefix} | nil, hints) :: Ecto.Query.t()
184
+ def apply(query, binds, as, prefix, hints) do
185
+ query =
186
+ query
187
+ |> Ecto.Queryable.to_query()
188
+ |> maybe_apply_as(as)
189
+ |> maybe_apply_prefix(prefix)
190
+ |> maybe_apply_hints(hints)
191
+
192
+ check_binds(query, binds)
193
+ query
194
+ end
195
+
196
+ defp maybe_apply_as(query, nil), do: query
197
+
198
+ defp maybe_apply_as(%{from: %{as: from_as}}, as) when not is_nil(from_as) do
199
+ Builder.error!(
200
+ "can't apply alias `#{inspect(as)}`, binding in `from` is already aliased to `#{inspect(from_as)}`"
201
+ )
202
+ end
203
+
204
+ defp maybe_apply_as(%{from: from, aliases: aliases} = query, as) do
205
+ if Map.has_key?(aliases, as) do
206
+ Builder.error!("alias `#{inspect(as)}` already exists")
207
+ else
208
+ %{query | aliases: Map.put(aliases, as, 0), from: %{from | as: as}}
209
+ end
210
+ end
211
+
212
+ defp maybe_apply_prefix(query, nil), do: query
213
+
214
+ defp maybe_apply_prefix(query, {:ok, prefix}) do
215
+ update_in query.from.prefix, fn
216
+ nil ->
217
+ prefix
218
+
219
+ from_prefix ->
220
+ Builder.error!(
221
+ "can't apply prefix `#{inspect(prefix)}`, `from` is already prefixed to `#{inspect(from_prefix)}`"
222
+ )
223
+ end
224
+ end
225
+
226
+ defp maybe_apply_hints(query, []), do: query
227
+ defp maybe_apply_hints(query, hints), do: update_in(query.from.hints, &(&1 ++ hints))
228
+
229
+ defp check_binds(query, count) do
230
+ if count > 1 and count > Builder.count_binds(query) do
231
+ Builder.error!(
232
+ "`from` in query expression specified #{count} " <>
233
+ "binds but query contains #{Builder.count_binds(query)} binds"
234
+ )
235
+ end
236
+ end
237
+ end
deps/ecto/lib/ecto/query/builder/group_by.ex ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.GroupBy do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Escapes a list of quoted expressions.
10
+
11
+ See `Ecto.Builder.escape/2`.
12
+
13
+ iex> escape(:group_by, quote do [x.x, 13] end, {[], %{}}, [x: 0], __ENV__)
14
+ {[{:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]},
15
+ 13],
16
+ {[], %{}}}
17
+ """
18
+ @spec escape(:group_by | :partition_by, Macro.t, {list, term}, Keyword.t, Macro.Env.t) ::
19
+ {Macro.t, {list, term}}
20
+ def escape(kind, expr, params_acc, vars, env) do
21
+ expr
22
+ |> List.wrap
23
+ |> Enum.map_reduce(params_acc, &do_escape(&1, &2, kind, vars, env))
24
+ end
25
+
26
+ defp do_escape({:^, _, [expr]}, params_acc, kind, _vars, _env) do
27
+ {quote(do: Ecto.Query.Builder.GroupBy.field!(unquote(kind), unquote(expr))), params_acc}
28
+ end
29
+
30
+ defp do_escape(field, params_acc, _kind, _vars, _env) when is_atom(field) do
31
+ {Macro.escape(to_field(field)), params_acc}
32
+ end
33
+
34
+ defp do_escape(expr, params_acc, _kind, vars, env) do
35
+ Builder.escape(expr, :any, params_acc, vars, env)
36
+ end
37
+
38
+ @doc """
39
+ Called at runtime to verify a field.
40
+ """
41
+ def field!(_kind, field) when is_atom(field),
42
+ do: to_field(field)
43
+ def field!(kind, other) do
44
+ raise ArgumentError,
45
+ "expected a field as an atom in `#{kind}`, got: `#{inspect other}`"
46
+ end
47
+
48
+ @doc """
49
+ Shared between group_by and partition_by.
50
+ """
51
+ def group_or_partition_by!(kind, query, exprs, params) do
52
+ {expr, {params, _, subqueries}} =
53
+ Enum.map_reduce(List.wrap(exprs), {params, length(params), []}, fn
54
+ field, params_count when is_atom(field) ->
55
+ {to_field(field), params_count}
56
+
57
+ %Ecto.Query.DynamicExpr{} = dynamic, {params, count, subqueries} ->
58
+ {expr, params, subqueries, _aliases, count} = Builder.Dynamic.partially_expand(query, dynamic, params, subqueries, %{}, count)
59
+ {expr, {params, count, subqueries}}
60
+
61
+ other, _params_count ->
62
+ raise ArgumentError,
63
+ "expected a list of fields and dynamics in `#{kind}`, got: `#{inspect other}`"
64
+ end)
65
+
66
+ {expr, params, subqueries}
67
+ end
68
+
69
+ defp to_field(field), do: {{:., [], [{:&, [], [0]}, field]}, [], []}
70
+
71
+ @doc """
72
+ Called at runtime to assemble group_by.
73
+ """
74
+ def group_by!(query, group_by, file, line) do
75
+ {expr, params, subqueries} = group_or_partition_by!(:group_by, query, group_by, [])
76
+ expr = %Ecto.Query.ByExpr{expr: expr, params: Enum.reverse(params), line: line, file: file, subqueries: subqueries}
77
+ apply(query, expr)
78
+ end
79
+
80
+ @doc """
81
+ Builds a quoted expression.
82
+
83
+ The quoted expression should evaluate to a query at runtime.
84
+ If possible, it does all calculations at compile time to avoid
85
+ runtime work.
86
+ """
87
+ @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
88
+ def build(query, _binding, {:^, _, [var]}, env) do
89
+ quote do
90
+ Ecto.Query.Builder.GroupBy.group_by!(unquote(query), unquote(var), unquote(env.file), unquote(env.line))
91
+ end
92
+ end
93
+
94
+ def build(query, binding, expr, env) do
95
+ {query, binding} = Builder.escape_binding(query, binding, env)
96
+ {expr, {params, acc}} = escape(:group_by, expr, {[], %{subqueries: []}}, binding, env)
97
+ params = Builder.escape_params(params)
98
+
99
+ group_by = quote do: %Ecto.Query.ByExpr{
100
+ expr: unquote(expr),
101
+ params: unquote(params),
102
+ subqueries: unquote(acc.subqueries),
103
+ file: unquote(env.file),
104
+ line: unquote(env.line)}
105
+ Builder.apply_query(query, __MODULE__, [group_by], env)
106
+ end
107
+
108
+ @doc """
109
+ The callback applied by `build/4` to build the query.
110
+ """
111
+ @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
112
+ def apply(%Ecto.Query{group_bys: group_bys} = query, expr) do
113
+ %{query | group_bys: group_bys ++ [expr]}
114
+ end
115
+ def apply(query, expr) do
116
+ apply(Ecto.Queryable.to_query(query), expr)
117
+ end
118
+ end
deps/ecto/lib/ecto/query/builder/join.ex ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Join do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+ alias Ecto.Query.{JoinExpr, QueryExpr}
8
+
9
+ @doc """
10
+ Escapes a join expression (not including the `on` expression).
11
+
12
+ It returns a tuple containing the binds, the on expression (if available)
13
+ and the association expression.
14
+
15
+ ## Examples
16
+
17
+ iex> escape(quote(do: x in "foo"), [], __ENV__)
18
+ {:x, {"foo", nil}, nil, nil, []}
19
+
20
+ iex> escape(quote(do: "foo"), [], __ENV__)
21
+ {:_, {"foo", nil}, nil, nil, []}
22
+
23
+ iex> escape(quote(do: x in Sample), [], __ENV__)
24
+ {:x, {nil, Sample}, nil, nil, []}
25
+
26
+ iex> escape(quote(do: x in __MODULE__), [], __ENV__)
27
+ {:x, {nil, __MODULE__}, nil, nil, []}
28
+
29
+ iex> escape(quote(do: x in {"foo", :sample}), [], __ENV__)
30
+ {:x, {"foo", :sample}, nil, nil, []}
31
+
32
+ iex> escape(quote(do: x in {"foo", Sample}), [], __ENV__)
33
+ {:x, {"foo", Sample}, nil, nil, []}
34
+
35
+ iex> escape(quote(do: x in {"foo", __MODULE__}), [], __ENV__)
36
+ {:x, {"foo", __MODULE__}, nil, nil, []}
37
+
38
+ iex> escape(quote(do: c in assoc(p, :comments)), [p: 0], __ENV__)
39
+ {:c, nil, {0, :comments}, nil, []}
40
+
41
+ iex> escape(quote(do: x in fragment("foo")), [], __ENV__)
42
+ {:x, {:{}, [], [:fragment, [], [raw: "foo"]]}, nil, nil, []}
43
+
44
+ """
45
+ @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {atom, Macro.t | nil, Macro.t | nil, list}
46
+ def escape({:in, _, [{var, _, context}, expr]}, vars, env)
47
+ when is_atom(var) and is_atom(context) do
48
+ {_, expr, assoc, prelude, params} = escape(expr, vars, env)
49
+ {var, expr, assoc, prelude, params}
50
+ end
51
+
52
+ def escape({:subquery, _, [expr]}, _vars, _env) do
53
+ {:_, quote(do: Ecto.Query.subquery(unquote(expr))), nil, nil, []}
54
+ end
55
+
56
+ def escape({:subquery, _, [expr, opts]}, _vars, _env) do
57
+ {:_, quote(do: Ecto.Query.subquery(unquote(expr), unquote(opts))), nil, nil, []}
58
+ end
59
+
60
+ def escape({:fragment, _, [_ | _]} = expr, vars, env) do
61
+ {expr, {params, _acc}} = Builder.escape(expr, :any, {[], %{}}, vars, env)
62
+ {:_, expr, nil, nil, params}
63
+ end
64
+
65
+ def escape({:values, _, [values_list, types]}, _vars, _env) do
66
+ prelude = quote do: values = Ecto.Query.Values.new(unquote(values_list), unquote(types))
67
+ types = quote do: values.types
68
+ num_rows = quote do: values.num_rows
69
+ params = quote do: values.params
70
+ {:_, {:{}, [], [:values, [], [types, num_rows]]}, nil, prelude, params}
71
+ end
72
+
73
+ def escape({string, schema} = join, _vars, env) when is_binary(string) do
74
+ case Macro.expand(schema, env) do
75
+ schema when is_atom(schema) ->
76
+ {:_, {string, schema}, nil, nil, []}
77
+
78
+ _ ->
79
+ Builder.error! "malformed join `#{Macro.to_string(join)}` in query expression"
80
+ end
81
+ end
82
+
83
+ def escape({:assoc, _, [{var, _, context}, field]}, vars, _env)
84
+ when is_atom(var) and is_atom(context) do
85
+ ensure_field!(field)
86
+ var = Builder.find_var!(var, vars)
87
+ field = Builder.quoted_atom!(field, "field/2")
88
+ {:_, nil, {var, field}, nil, []}
89
+ end
90
+
91
+ def escape({:^, _, [expr]}, _vars, _env) do
92
+ {:_, quote(do: Ecto.Query.Builder.Join.join!(unquote(expr))), nil, nil, []}
93
+ end
94
+
95
+ def escape(string, _vars, _env) when is_binary(string) do
96
+ {:_, {string, nil}, nil, nil, []}
97
+ end
98
+
99
+ def escape(schema, _vars, _env) when is_atom(schema) do
100
+ {:_, {nil, schema}, nil, nil, []}
101
+ end
102
+
103
+ def escape(join, vars, env) do
104
+ case Macro.expand(join, env) do
105
+ ^join ->
106
+ Builder.error! "malformed join `#{Macro.to_string(join)}` in query expression"
107
+ join ->
108
+ escape(join, vars, env)
109
+ end
110
+ end
111
+
112
+ @doc """
113
+ Called at runtime to check dynamic joins.
114
+ """
115
+ def join!(expr) when is_atom(expr),
116
+ do: {nil, expr}
117
+ def join!(expr) when is_binary(expr),
118
+ do: {expr, nil}
119
+ def join!({source, module}) when is_binary(source) and is_atom(module),
120
+ do: {source, module}
121
+ def join!(expr),
122
+ do: Ecto.Queryable.to_query(expr)
123
+
124
+ @doc """
125
+ Builds a quoted expression.
126
+
127
+ The quoted expression should evaluate to a query at runtime.
128
+ If possible, it does all calculations at compile time to avoid
129
+ runtime work.
130
+ """
131
+ @spec build(Macro.t, atom, [Macro.t], Macro.t, Macro.t, Macro.t, atom, nil | {:ok, Ecto.Schema.prefix}, nil | String.t | [String.t], Macro.Env.t) ::
132
+ {Macro.t, Keyword.t, non_neg_integer | nil}
133
+ def build(query, qual, binding, expr, count_bind, on, as, prefix, maybe_hints, env) do
134
+ {:ok, prefix} = prefix || {:ok, nil}
135
+ hints = List.wrap(maybe_hints)
136
+
137
+ unless Enum.all?(hints, &is_binary/1) do
138
+ Builder.error!(
139
+ "`hints` must be a compile time string or list of strings, " <>
140
+ "got: `#{Macro.to_string(maybe_hints)}`"
141
+ )
142
+ end
143
+
144
+ prefix = case prefix do
145
+ nil -> nil
146
+ prefix when is_binary(prefix) -> prefix
147
+ {:^, _, [prefix]} -> prefix
148
+ prefix -> Builder.error!("`prefix` must be a compile time string or an interpolated value using ^, got: #{Macro.to_string(prefix)}")
149
+ end
150
+
151
+ as = case as do
152
+ {:^, _, [as]} -> as
153
+ as when is_atom(as) -> as
154
+ as -> Builder.error!("`as` must be a compile time atom or an interpolated value using ^, got: #{Macro.to_string(as)}")
155
+ end
156
+
157
+ {query, binding} = Builder.escape_binding(query, binding, env)
158
+ {join_bind, join_source, join_assoc, join_prelude, join_params} = escape(expr, binding, env)
159
+ join_params = escape_params(join_params)
160
+
161
+ join_qual = validate_qual(qual)
162
+ validate_bind(join_bind, binding)
163
+
164
+ {count_bind, query} =
165
+ if is_nil(count_bind) do
166
+ query =
167
+ quote do
168
+ query = Ecto.Queryable.to_query(unquote(query))
169
+ join_count = Builder.count_binds(query)
170
+ query
171
+ end
172
+ {quote(do: join_count), query}
173
+ else
174
+ {count_bind, query}
175
+ end
176
+
177
+ binding = binding ++ [{join_bind, count_bind}]
178
+
179
+ next_bind =
180
+ if is_integer(count_bind) do
181
+ count_bind + 1
182
+ else
183
+ quote(do: unquote(count_bind) + 1)
184
+ end
185
+
186
+ join = [
187
+ as: as,
188
+ assoc: join_assoc,
189
+ file: env.file,
190
+ line: env.line,
191
+ params: join_params,
192
+ prefix: prefix,
193
+ qual: join_qual,
194
+ source: join_source,
195
+ hints: hints
196
+ ]
197
+
198
+ on = ensure_on(on, join_assoc, join_qual, join_source, env)
199
+ query = build_on(on, join_prelude, join, as, query, binding, count_bind, env)
200
+ {query, binding, next_bind}
201
+ end
202
+
203
+ defp escape_params(params) when is_list(params) do
204
+ Builder.escape_params(params)
205
+ end
206
+
207
+ defp escape_params(params) do
208
+ quote do: Builder.escape_params(unquote(params))
209
+ end
210
+
211
+ def build_on({:^, _, [var]}, join_prelude, join, as, query, _binding, count_bind, env) do
212
+ quote do
213
+ query = unquote(query)
214
+ unquote(join_prelude)
215
+
216
+ Ecto.Query.Builder.Join.join!(
217
+ query,
218
+ %JoinExpr{unquote_splicing(join), on: %QueryExpr{}},
219
+ unquote(var),
220
+ unquote(as),
221
+ unquote(count_bind),
222
+ unquote(env.file),
223
+ unquote(env.line)
224
+ )
225
+ end
226
+ end
227
+
228
+ def build_on(on, join_prelude, join, as, query, binding, count_bind, env) do
229
+ case Ecto.Query.Builder.Filter.escape(:on, on, count_bind, binding, env) do
230
+ {_on_expr, {_on_params, %{subqueries: [_ | _]}}} ->
231
+ raise ArgumentError, "invalid expression for join `:on`, subqueries aren't supported"
232
+
233
+ {on_expr, {on_params, _acc}} ->
234
+ on_params = Builder.escape_params(on_params)
235
+
236
+ join =
237
+ quote do
238
+ unquote(join_prelude)
239
+
240
+ %JoinExpr{
241
+ unquote_splicing(join),
242
+ on: %QueryExpr{
243
+ expr: unquote(on_expr),
244
+ params: unquote(on_params),
245
+ line: unquote(env.line),
246
+ file: unquote(env.file)
247
+ }
248
+ }
249
+ end
250
+
251
+ Builder.apply_query(query, __MODULE__, [join, as, count_bind], env)
252
+ end
253
+ end
254
+
255
+ defp ensure_on(on, _assoc, _qual, _source, _env) when on != nil, do: on
256
+
257
+ defp ensure_on(nil, _assoc = nil, qual, source, env) when qual not in [:cross, :cross_lateral] do
258
+ maybe_source =
259
+ with {source, alias} <- source,
260
+ source when source != nil <- source || alias do
261
+ " on #{inspect(source)}"
262
+ else
263
+ _ -> ""
264
+ end
265
+
266
+ stacktrace = Macro.Env.stacktrace(env)
267
+ IO.warn("missing `:on` in join#{maybe_source}, defaulting to `on: true`.", stacktrace)
268
+
269
+ true
270
+ end
271
+
272
+ defp ensure_on(nil, _assoc, _qual, _source, _env), do: true
273
+
274
+ @doc """
275
+ Applies the join expression to the query.
276
+ """
277
+ def apply(%Ecto.Query{joins: joins} = query, expr, nil, _count_bind) do
278
+ %{query | joins: joins ++ [expr]}
279
+ end
280
+ def apply(%Ecto.Query{joins: joins, aliases: aliases} = query, expr, as, count_bind) do
281
+ aliases =
282
+ case aliases do
283
+ %{} -> runtime_aliases(aliases, as, count_bind)
284
+ _ -> compile_aliases(aliases, as, count_bind)
285
+ end
286
+
287
+ %{query | joins: joins ++ [expr], aliases: aliases}
288
+ end
289
+ def apply(query, expr, as, count_bind) do
290
+ apply(Ecto.Queryable.to_query(query), expr, as, count_bind)
291
+ end
292
+
293
+ @doc """
294
+ Called at runtime to build aliases.
295
+ """
296
+ def runtime_aliases(aliases, nil, _), do: aliases
297
+
298
+ def runtime_aliases(aliases, name, join_count) when is_integer(join_count) do
299
+ if Map.has_key?(aliases, name) do
300
+ Builder.error! "alias `#{inspect name}` already exists"
301
+ else
302
+ Map.put(aliases, name, join_count)
303
+ end
304
+ end
305
+
306
+ defp compile_aliases({:%{}, meta, aliases}, name, join_count)
307
+ when is_atom(name) and is_integer(join_count) do
308
+ {:%{}, meta, aliases |> Map.new |> runtime_aliases(name, join_count) |> Map.to_list}
309
+ end
310
+
311
+ defp compile_aliases(aliases, name, join_count) do
312
+ quote do
313
+ Ecto.Query.Builder.Join.runtime_aliases(unquote(aliases), unquote(name), unquote(join_count))
314
+ end
315
+ end
316
+
317
+ @doc """
318
+ Called at runtime to build a join.
319
+ """
320
+ def join!(query, join, expr, as, count_bind, file, line) do
321
+ # join without expanded :on is built and applied to the query,
322
+ # so that expansion of dynamic :on accounts for the new binding
323
+ {on_expr, on_params, on_file, on_line} =
324
+ Ecto.Query.Builder.Filter.filter!(:on, apply(query, join, as, count_bind), expr, count_bind, file, line)
325
+
326
+ join = %{join | on: %QueryExpr{expr: on_expr, params: on_params, line: on_line, file: on_file}}
327
+ apply(query, join, as, count_bind)
328
+ end
329
+
330
+ defp validate_qual(qual) when is_atom(qual) do
331
+ qual!(qual)
332
+ end
333
+
334
+ defp validate_qual(qual) do
335
+ quote(do: Ecto.Query.Builder.Join.qual!(unquote(qual)))
336
+ end
337
+
338
+ defp validate_bind(bind, all) do
339
+ if bind != :_ and bind in all do
340
+ Builder.error! "variable `#{bind}` is already defined in query"
341
+ end
342
+ end
343
+
344
+ @qualifiers [:inner, :inner_lateral, :left, :left_lateral, :right, :full, :cross, :cross_lateral]
345
+
346
+ @doc """
347
+ Called at runtime to check dynamic qualifier.
348
+ """
349
+ def qual!(qual) when qual in @qualifiers, do: qual
350
+ def qual!(qual) do
351
+ raise ArgumentError,
352
+ "invalid join qualifier `#{inspect qual}`, accepted qualifiers are: " <>
353
+ Enum.map_join(@qualifiers, ", ", &"`#{inspect &1}`")
354
+ end
355
+
356
+ defp ensure_field!({var, _, _}) when var != :^ do
357
+ Builder.error! "you passed the variable `#{var}` to `assoc/2`. Did you mean to pass the atom `:#{var}`?"
358
+ end
359
+ defp ensure_field!(_), do: true
360
+ end
deps/ecto/lib/ecto/query/builder/limit_offset.ex ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 3]
2
+
3
+ defmodule Ecto.Query.Builder.LimitOffset do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Validates `with_ties` at runtime.
10
+ """
11
+ @spec with_ties!(any) :: boolean
12
+ def with_ties!(with_ties) when is_boolean(with_ties), do: with_ties
13
+
14
+ def with_ties!(with_ties),
15
+ do: raise("`with_ties` expression must evaluate to a boolean at runtime, got: `#{inspect(with_ties)}`")
16
+
17
+ @doc """
18
+ Builds a quoted expression.
19
+
20
+ The quoted expression should evaluate to a query at runtime.
21
+ If possible, it does all calculations at compile time to avoid
22
+ runtime work.
23
+ """
24
+ @spec build(:limit | :with_ties | :offset, Macro.t(), [Macro.t()], Macro.t(), Macro.Env.t()) ::
25
+ Macro.t()
26
+ def build(type, query, binding, expr, env) do
27
+ {query, vars} = Builder.escape_binding(query, binding, env)
28
+ {expr, {params, _acc}} = escape(type, expr, {[], %{}}, vars, env)
29
+ params = Builder.escape_params(params)
30
+ quoted = build_quoted(type, expr, params, env)
31
+
32
+ Builder.apply_query(query, __MODULE__, [type, quoted], env)
33
+ end
34
+
35
+ defp escape(type, expr, params_acc, vars, env) when type in [:limit, :offset] do
36
+ Builder.escape(expr, :integer, params_acc, vars, env)
37
+ end
38
+
39
+ defp escape(:with_ties, expr, params_acc, _vars, _env) when is_boolean(expr) do
40
+ {expr, params_acc}
41
+ end
42
+
43
+ defp escape(:with_ties, {:^, _, [expr]}, params_acc, _vars, _env) do
44
+ {quote(do: Ecto.Query.Builder.LimitOffset.with_ties!(unquote(expr))), params_acc}
45
+ end
46
+
47
+ defp escape(:with_ties, expr, _params_acc, _vars, _env) do
48
+ Builder.error!(
49
+ "`with_ties` expression must be a compile time boolean or an interpolated value using ^, got: `#{Macro.to_string(expr)}`"
50
+ )
51
+ end
52
+
53
+ defp build_quoted(:limit, expr, params, env) do
54
+ quote do: %Ecto.Query.LimitExpr{
55
+ expr: unquote(expr),
56
+ params: unquote(params),
57
+ file: unquote(env.file),
58
+ line: unquote(env.line)
59
+ }
60
+ end
61
+
62
+ defp build_quoted(:offset, expr, params, env) do
63
+ quote do: %Ecto.Query.QueryExpr{
64
+ expr: unquote(expr),
65
+ params: unquote(params),
66
+ file: unquote(env.file),
67
+ line: unquote(env.line)
68
+ }
69
+ end
70
+
71
+ defp build_quoted(:with_ties, expr, _params, _env), do: expr
72
+
73
+ @doc """
74
+ The callback applied by `build/4` to build the query.
75
+ """
76
+ @spec apply(Ecto.Queryable.t(), :limit | :with_ties | :offset, term) :: Ecto.Query.t()
77
+ def apply(%Ecto.Query{} = query, :limit, expr) do
78
+ %{query | limit: expr}
79
+ end
80
+
81
+ def apply(%Ecto.Query{limit: limit} = query, :with_ties, expr) do
82
+ %{query | limit: apply_limit(limit, expr)}
83
+ end
84
+
85
+ def apply(%Ecto.Query{} = query, :offset, expr) do
86
+ %{query | offset: expr}
87
+ end
88
+
89
+ def apply(query, kind, expr) do
90
+ apply(Ecto.Queryable.to_query(query), kind, expr)
91
+ end
92
+
93
+ @doc """
94
+ Applies the `with_ties` value to the `limit` struct.
95
+ """
96
+ def apply_limit(nil, _with_ties) do
97
+ Builder.error!("`with_ties` can only be applied to queries containing a `limit`")
98
+ end
99
+
100
+ # Runtime
101
+ def apply_limit(%_{} = limit, with_ties) do
102
+ %{limit | with_ties: with_ties}
103
+ end
104
+
105
+ # Compile
106
+ def apply_limit(limit, with_ties) do
107
+ quote do
108
+ Ecto.Query.Builder.LimitOffset.apply_limit(unquote(limit), unquote(with_ties))
109
+ end
110
+ end
111
+ end
deps/ecto/lib/ecto/query/builder/lock.ex ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Lock do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Escapes the lock code.
10
+
11
+ iex> escape(quote(do: "FOO"), [], __ENV__)
12
+ "FOO"
13
+
14
+ """
15
+ @spec escape(Macro.t(), Keyword.t, Macro.Env.t) :: Macro.t()
16
+ def escape(lock, _vars, _env) when is_binary(lock), do: lock
17
+
18
+ def escape({:fragment, _, [_ | _]} = expr, vars, env) do
19
+ {expr, {params, _acc}} = Builder.escape(expr, :any, {[], %{}}, vars, env)
20
+
21
+ if params != [] do
22
+ Builder.error!("value interpolation is not allowed in :lock")
23
+ end
24
+
25
+ expr
26
+ end
27
+
28
+ def escape(other, _, _) do
29
+ Builder.error!(
30
+ "`#{Macro.to_string(other)}` is not a valid lock. " <>
31
+ "For security reasons, a lock must always be a literal string or a fragment"
32
+ )
33
+ end
34
+
35
+ @doc """
36
+ Builds a quoted expression.
37
+
38
+ The quoted expression should evaluate to a query at runtime.
39
+ If possible, it does all calculations at compile time to avoid
40
+ runtime work.
41
+ """
42
+ @spec build(Macro.t(), Macro.t(), Macro.t(), Macro.Env.t()) :: Macro.t()
43
+ def build(query, binding, expr, env) do
44
+ {query, binding} = Builder.escape_binding(query, binding, env)
45
+ Builder.apply_query(query, __MODULE__, [escape(expr, binding, env)], env)
46
+ end
47
+
48
+ @doc """
49
+ The callback applied by `build/4` to build the query.
50
+ """
51
+ @spec apply(Ecto.Queryable.t(), term) :: Ecto.Query.t()
52
+ def apply(%Ecto.Query{} = query, value) do
53
+ %{query | lock: value}
54
+ end
55
+
56
+ def apply(query, value) do
57
+ apply(Ecto.Queryable.to_query(query), value)
58
+ end
59
+ end
deps/ecto/lib/ecto/query/builder/order_by.ex ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 3]
2
+
3
+ defmodule Ecto.Query.Builder.OrderBy do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @directions [
9
+ :asc,
10
+ :asc_nulls_last,
11
+ :asc_nulls_first,
12
+ :desc,
13
+ :desc_nulls_last,
14
+ :desc_nulls_first
15
+ ]
16
+
17
+ @doc """
18
+ Returns `true` if term is a valid order_by direction; otherwise returns `false`.
19
+
20
+ ## Examples
21
+
22
+ iex> valid_direction?(:asc)
23
+ true
24
+
25
+ iex> valid_direction?(:desc)
26
+ true
27
+
28
+ iex> valid_direction?(:invalid)
29
+ false
30
+
31
+ """
32
+ def valid_direction?(term), do: term in @directions
33
+
34
+ @doc """
35
+ Escapes an order by query.
36
+
37
+ The query is escaped to a list of `{direction, expression}`
38
+ pairs at runtime. Escaping also validates direction is one of
39
+ `:asc`, `:asc_nulls_last`, `:asc_nulls_first`, `:desc`,
40
+ `:desc_nulls_last` or `:desc_nulls_first`.
41
+
42
+ ## Examples
43
+
44
+ iex> escape(:order_by, quote do [x.x, desc: 13] end, {[], %{}}, [x: 0], __ENV__)
45
+ {[asc: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]},
46
+ desc: 13],
47
+ {[], %{}}}
48
+
49
+ """
50
+ @spec escape(:order_by | :distinct, Macro.t(), {list, term}, Keyword.t(), Macro.Env.t()) ::
51
+ {Macro.t(), {list, term}}
52
+ def escape(kind, expr, params_acc, vars, env) do
53
+ expr
54
+ |> Macro.expand_once(get_env(env))
55
+ |> List.wrap()
56
+ |> Enum.map_reduce(params_acc, &do_escape(&1, &2, kind, vars, env))
57
+ end
58
+
59
+ defp do_escape({dir, {:^, _, [expr]}}, params_acc, kind, _vars, _env) do
60
+ {{quoted_dir!(kind, dir),
61
+ quote(do: Ecto.Query.Builder.OrderBy.field!(unquote(kind), unquote(expr)))}, params_acc}
62
+ end
63
+
64
+ defp do_escape({:^, _, [expr]}, params_acc, kind, _vars, _env) do
65
+ {{:asc, quote(do: Ecto.Query.Builder.OrderBy.field!(unquote(kind), unquote(expr)))},
66
+ params_acc}
67
+ end
68
+
69
+ defp do_escape({dir, field}, params_acc, kind, _vars, _env) when is_atom(field) do
70
+ {{quoted_dir!(kind, dir), Macro.escape(to_field(field))}, params_acc}
71
+ end
72
+
73
+ defp do_escape(field, params_acc, _kind, _vars, _env) when is_atom(field) do
74
+ {{:asc, Macro.escape(to_field(field))}, params_acc}
75
+ end
76
+
77
+ defp do_escape({dir, expr}, params_acc, kind, vars, env) do
78
+ {ast, params_acc} = Builder.escape(expr, :any, params_acc, vars, env)
79
+ {{quoted_dir!(kind, dir), ast}, params_acc}
80
+ end
81
+
82
+ defp do_escape(expr, params_acc, _kind, vars, env) do
83
+ {ast, params_acc} = Builder.escape(expr, :any, params_acc, vars, env)
84
+ {{:asc, ast}, params_acc}
85
+ end
86
+
87
+ defp get_env({env, _}), do: env
88
+ defp get_env(env), do: env
89
+
90
+ @doc """
91
+ Checks the variable is a quoted direction at compilation time or
92
+ delegate the check to runtime for interpolation.
93
+ """
94
+ def quoted_dir!(kind, {:^, _, [expr]}),
95
+ do: quote(do: Ecto.Query.Builder.OrderBy.dir!(unquote(kind), unquote(expr)))
96
+
97
+ def quoted_dir!(_kind, dir) when dir in @directions,
98
+ do: dir
99
+
100
+ def quoted_dir!(kind, other) do
101
+ Builder.error!(
102
+ "expected #{Enum.map_join(@directions, ", ", &inspect/1)} or interpolated value " <>
103
+ "in `#{kind}`, got: `#{inspect(other)}`"
104
+ )
105
+ end
106
+
107
+ @doc """
108
+ Called at runtime to verify the direction.
109
+ """
110
+ def dir!(_kind, dir) when dir in @directions,
111
+ do: dir
112
+
113
+ def dir!(kind, other) do
114
+ raise ArgumentError,
115
+ "expected one of #{Enum.map_join(@directions, ", ", &inspect/1)} " <>
116
+ "in `#{kind}`, got: `#{inspect(other)}`"
117
+ end
118
+
119
+ @doc """
120
+ Called at runtime to verify a field.
121
+ """
122
+ def field!(_kind, field) when is_atom(field) do
123
+ to_field(field)
124
+ end
125
+
126
+ def field!(kind, %Ecto.Query.DynamicExpr{} = dynamic_expression) do
127
+ raise ArgumentError,
128
+ "expected a field as an atom in `#{kind}`, got: `#{inspect(dynamic_expression)}`. " <>
129
+ "To use dynamic expressions, you need to interpolate at root level, as in: " <>
130
+ "`^[asc: dynamic, desc: :id]`"
131
+ end
132
+
133
+ def field!(kind, other) do
134
+ raise ArgumentError, "expected a field as an atom in `#{kind}`, got: `#{inspect(other)}`"
135
+ end
136
+
137
+ defp to_field(field), do: {{:., [], [{:&, [], [0]}, field]}, [], []}
138
+
139
+ @doc """
140
+ Shared between order_by and distinct.
141
+ """
142
+ def order_by_or_distinct!(kind, query, exprs, params) do
143
+ {expr, {params, _, subqueries}} =
144
+ Enum.map_reduce(List.wrap(exprs), {params, length(params), []}, fn
145
+ {dir, expr}, params_count when dir in @directions ->
146
+ {expr, params} = dynamic_or_field!(kind, expr, query, params_count)
147
+ {{dir, expr}, params}
148
+
149
+ expr, params_count ->
150
+ {expr, params} = dynamic_or_field!(kind, expr, query, params_count)
151
+ {{:asc, expr}, params}
152
+ end)
153
+
154
+ {expr, params, subqueries}
155
+ end
156
+
157
+ @doc """
158
+ Called at runtime to assemble order_by.
159
+ """
160
+ def order_by!(query, exprs, op, file, line) do
161
+ {expr, params, subqueries} = order_by_or_distinct!(:order_by, query, exprs, [])
162
+ expr = %Ecto.Query.ByExpr{expr: expr, params: Enum.reverse(params), line: line, file: file, subqueries: subqueries}
163
+ apply(query, expr, op)
164
+ end
165
+
166
+ defp dynamic_or_field!(
167
+ _kind,
168
+ %Ecto.Query.DynamicExpr{} = dynamic,
169
+ query,
170
+ {params, count, subqueries}
171
+ ) do
172
+ {expr, params, subqueries, _aliases, count} =
173
+ Ecto.Query.Builder.Dynamic.partially_expand(
174
+ query,
175
+ dynamic,
176
+ params,
177
+ subqueries,
178
+ %{},
179
+ count
180
+ )
181
+
182
+ {expr, {params, count, subqueries}}
183
+ end
184
+
185
+ defp dynamic_or_field!(_kind, field, _query, params_count) when is_atom(field) do
186
+ {to_field(field), params_count}
187
+ end
188
+
189
+ defp dynamic_or_field!(kind, other, _query, _params_count) do
190
+ raise ArgumentError,
191
+ "`#{kind}` interpolated on root expects a field or a keyword list " <>
192
+ "with the direction as keys and fields or dynamics as values, got: `#{inspect(other)}`"
193
+ end
194
+
195
+ @doc """
196
+ Builds a quoted expression.
197
+
198
+ The quoted expression should evaluate to a query at runtime.
199
+ If possible, it does all calculations at compile time to avoid
200
+ runtime work.
201
+ """
202
+ @spec build(Macro.t(), [Macro.t()], Macro.t(), :append | :prepend, Macro.Env.t()) :: Macro.t()
203
+ def build(query, _binding, {:^, _, [var]}, op, env) do
204
+ quote do
205
+ Ecto.Query.Builder.OrderBy.order_by!(
206
+ unquote(query),
207
+ unquote(var),
208
+ unquote(op),
209
+ unquote(env.file),
210
+ unquote(env.line)
211
+ )
212
+ end
213
+ end
214
+
215
+ def build(query, binding, expr, op, env) do
216
+ {query, binding} = Builder.escape_binding(query, binding, env)
217
+ {expr, {params, acc}} = escape(:order_by, expr, {[], %{subqueries: []}}, binding, env)
218
+ params = Builder.escape_params(params)
219
+
220
+ order_by =
221
+ quote do: %Ecto.Query.ByExpr{
222
+ expr: unquote(expr),
223
+ params: unquote(params),
224
+ subqueries: unquote(acc.subqueries),
225
+ file: unquote(env.file),
226
+ line: unquote(env.line)
227
+ }
228
+
229
+ Builder.apply_query(query, __MODULE__, [order_by, op], env)
230
+ end
231
+
232
+ @doc """
233
+ The callback applied by `build/4` to build the query.
234
+ """
235
+ @spec apply(Ecto.Queryable.t(), term, term) :: Ecto.Query.t()
236
+ def apply(%Ecto.Query{order_bys: orders} = query, expr, op) do
237
+ %{query | order_bys: update_order_bys(orders, expr, op)}
238
+ end
239
+
240
+ def apply(query, expr, op) do
241
+ apply(Ecto.Queryable.to_query(query), expr, op)
242
+ end
243
+
244
+ @doc """
245
+ Updates the `order_bys` value for a query.
246
+ """
247
+ def update_order_bys(orders, expr, :append), do: orders ++ [expr]
248
+ def update_order_bys(orders, expr, :prepend), do: [expr | orders]
249
+
250
+ def update_order_bys(orders, expr, mode) do
251
+ quote do
252
+ Ecto.Query.Builder.OrderBy.update_order_bys(unquote(orders), unquote(expr), unquote(mode))
253
+ end
254
+ end
255
+ end
deps/ecto/lib/ecto/query/builder/preload.ex ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 3]
2
+
3
+ defmodule Ecto.Query.Builder.Preload do
4
+ @moduledoc false
5
+ alias Ecto.Query.Builder
6
+
7
+ @doc """
8
+ Escapes a preload.
9
+
10
+ A preload may be an atom, a list of atoms or a keyword list
11
+ nested as a rose tree.
12
+
13
+ iex> escape(:foo, [])
14
+ {[:foo], []}
15
+
16
+ iex> escape([foo: :bar], [])
17
+ {[foo: [:bar]], []}
18
+
19
+ iex> escape([:foo, :bar], [])
20
+ {[:foo, :bar], []}
21
+
22
+ iex> escape([foo: [:bar, bar: :bat]], [])
23
+ {[foo: [:bar, bar: [:bat]]], []}
24
+
25
+ iex> escape([foo: {:^, [], ["external"]}], [])
26
+ {[foo: "external"], []}
27
+
28
+ iex> escape([foo: [:bar, {:^, [], ["external"]}], baz: :bat], [])
29
+ {[foo: [:bar, "external"], baz: [:bat]], []}
30
+
31
+ iex> escape([foo: {:c, [], nil}], [c: 1])
32
+ {[], [foo: {1, []}]}
33
+
34
+ iex> escape([foo: {{:c, [], nil}, bar: {:l, [], nil}}], [c: 1, l: 2])
35
+ {[], [foo: {1, [bar: {2, []}]}]}
36
+
37
+ iex> escape([foo: {:c, [], nil}, bar: {:l, [], nil}], [c: 1, l: 2])
38
+ {[], [foo: {1, []}, bar: {2, []}]}
39
+
40
+ iex> escape([foo: {{:c, [], nil}, :bar}], [c: 1])
41
+ {[foo: [:bar]], [foo: {1, []}]}
42
+
43
+ iex> escape([foo: [bar: {:c, [], nil}]], [c: 1])
44
+ ** (Ecto.Query.CompileError) cannot preload join association `:bar` with binding `c` because parent preload is not a join association
45
+
46
+ """
47
+ @spec escape(Macro.t, Keyword.t) :: {[Macro.t], [Macro.t]}
48
+ def escape(preloads, vars) do
49
+ {preloads, assocs} = escape(preloads, :both, [], [], vars)
50
+ {Enum.reverse(preloads), Enum.reverse(assocs)}
51
+ end
52
+
53
+ defp escape(atom, _mode, preloads, assocs, _vars) when is_atom(atom) do
54
+ {[atom|preloads], assocs}
55
+ end
56
+
57
+ defp escape(list, mode, preloads, assocs, vars) when is_list(list) do
58
+ Enum.reduce list, {preloads, assocs}, fn item, acc ->
59
+ escape_each(item, mode, acc, vars)
60
+ end
61
+ end
62
+
63
+ defp escape({:^, _, [inner]}, _mode, preloads, assocs, _vars) do
64
+ {[inner|preloads], assocs}
65
+ end
66
+
67
+ defp escape(other, _mode, _preloads, _assocs, _vars) do
68
+ Builder.error! "`#{Macro.to_string other}` is not a valid preload expression. " <>
69
+ "preload expects an atom, a list of atoms or a keyword list with " <>
70
+ "more preloads as values. Use ^ on the outermost preload to interpolate a value"
71
+ end
72
+
73
+ defp escape_each({key, {:^, _, [inner]}}, _mode, {preloads, assocs}, _vars) do
74
+ key = escape_key(key)
75
+ {[{key, inner}|preloads], assocs}
76
+ end
77
+
78
+ defp escape_each({key, {var, _, context}}, mode, {preloads, assocs}, vars) when is_atom(context) do
79
+ assert_assoc!(mode, key, var)
80
+ key = escape_key(key)
81
+ idx = Builder.find_var!(var, vars)
82
+ {preloads, [{key, {idx, []}}|assocs]}
83
+ end
84
+
85
+ defp escape_each({key, {{var, _, context}, list}}, mode, {preloads, assocs}, vars) when is_atom(context) do
86
+ assert_assoc!(mode, key, var)
87
+ key = escape_key(key)
88
+ idx = Builder.find_var!(var, vars)
89
+ {inner_preloads, inner_assocs} = escape(list, :assoc, [], [], vars)
90
+ assocs = [{key, {idx, Enum.reverse(inner_assocs)}}|assocs]
91
+
92
+ case inner_preloads do
93
+ [] -> {preloads, assocs}
94
+ _ -> {[{key, Enum.reverse(inner_preloads)}|preloads], assocs}
95
+ end
96
+ end
97
+
98
+ defp escape_each({key, list}, _mode, {preloads, assocs}, vars) do
99
+ key = escape_key(key)
100
+ {inner_preloads, []} = escape(list, :preload, [], [], vars)
101
+ {[{key, Enum.reverse(inner_preloads)}|preloads], assocs}
102
+ end
103
+
104
+ defp escape_each(other, mode, {preloads, assocs}, vars) do
105
+ escape(other, mode, preloads, assocs, vars)
106
+ end
107
+
108
+ defp escape_key(atom) when is_atom(atom) do
109
+ atom
110
+ end
111
+
112
+ defp escape_key({:^, _, [expr]}) do
113
+ quote(do: Ecto.Query.Builder.Preload.key!(unquote(expr)))
114
+ end
115
+
116
+ defp escape_key(other) do
117
+ Builder.error! "malformed key in preload `#{Macro.to_string(other)}` in query expression"
118
+ end
119
+
120
+ @doc """
121
+ Called at runtime to check dynamic preload keys.
122
+ """
123
+ def key!(key) when is_atom(key),
124
+ do: key
125
+ def key!(key) do
126
+ raise ArgumentError,
127
+ "expected key in preload to be an atom, got: `#{inspect key}`"
128
+ end
129
+
130
+ @doc """
131
+ Applies the preloaded value into the query.
132
+
133
+ The quoted expression should evaluate to a query at runtime.
134
+ If possible, it does all calculations at compile time to avoid
135
+ runtime work.
136
+ """
137
+ @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
138
+ def build(query, _binding, {:^, _, [expr]}, _env) do
139
+ quote do
140
+ Ecto.Query.Builder.Preload.preload!(unquote(query), unquote(expr))
141
+ end
142
+ end
143
+
144
+ def build(query, binding, expr, env) do
145
+ {query, binding} = Builder.escape_binding(query, binding, env)
146
+ {preloads, assocs} = escape(expr, binding)
147
+ Builder.apply_query(query, __MODULE__, [Enum.reverse(preloads), Enum.reverse(assocs)], env)
148
+ end
149
+
150
+ @doc """
151
+ The callback applied by `build/4` to build the query.
152
+ """
153
+ @spec apply(Ecto.Queryable.t, term, term) :: Ecto.Query.t
154
+ def apply(%Ecto.Query{preloads: p, assocs: a} = query, preloads, assocs) do
155
+ %{query | preloads: p ++ preloads, assocs: a ++ assocs}
156
+ end
157
+ def apply(query, preloads, assocs) do
158
+ apply(Ecto.Queryable.to_query(query), preloads, assocs)
159
+ end
160
+
161
+ @doc """
162
+ Called at runtime to assemble preload.
163
+ """
164
+ def preload!(query, preload) do
165
+ {preloads, assocs} = expand(preload, query)
166
+ apply(query, preloads, assocs)
167
+ end
168
+
169
+ @doc """
170
+ Expands preloads at runtime.
171
+
172
+ ## Examples
173
+
174
+ iex> expand(:foo, [])
175
+ {[:foo], []}
176
+
177
+ iex> expand([foo: :bar], [])
178
+ {[foo: :bar], []}
179
+
180
+ iex> expand([:foo, :bar], [])
181
+ {[:foo, :bar], []}
182
+
183
+ iex> expand([foo: [:bar, bar: :bat]], [])
184
+ {[foo: [:bar, bar: :bat]], []}
185
+
186
+ iex> expand([:a, :b, c: [:d]], [])
187
+ {[:a, :b, c: [:d]], []}
188
+
189
+ iex> expand([foo: ["external"]], [])
190
+ ** (ArgumentError) `"external"` is not a valid preload expression, expected an atom or a list.
191
+
192
+ iex> require Ecto.Query
193
+ iex> expand([b: Ecto.Query.dynamic([_a, b], b)], Ecto.Query.from(a in "a", join: b in "b", on: true))
194
+ {[], [b: {1, []}]}
195
+
196
+ iex> require Ecto.Query
197
+ iex> expand(
198
+ ...> [b: {Ecto.Query.dynamic([_a, b], b), c: Ecto.Query.dynamic([_a, _b, c], c)}],
199
+ ...> Ecto.Query.from(a in "a", join: b in "b", on: true, join: c in "c", on: true)
200
+ ...> )
201
+ {[], [b: {1, [c: {2, []}]}]}
202
+ """
203
+ def expand(preloads, query) do
204
+ expand(preloads, query, :both, [], [])
205
+ end
206
+
207
+ defp expand(atom, _query, _mode, preloads, assocs) when is_atom(atom) do
208
+ {[atom|preloads], assocs}
209
+ end
210
+
211
+ defp expand(list, query, mode, preloads, assocs) when is_list(list) do
212
+ {preloads, assocs} =
213
+ Enum.reduce(list, {preloads, assocs}, fn item, acc ->
214
+ expand_each(item, query, mode, acc)
215
+ end)
216
+
217
+ {Enum.reverse(preloads), Enum.reverse(assocs)}
218
+ end
219
+
220
+ defp expand(other, _query, _mode, _preloads, _assocs) do
221
+ raise ArgumentError,
222
+ "`#{inspect(other)}` is not a valid preload expression, " <>
223
+ "expected an atom or a list."
224
+ end
225
+
226
+ defp expand_each(atom, _query, _mode, {preloads, assocs}) when is_atom(atom) do
227
+ {[atom|preloads], assocs}
228
+ end
229
+
230
+ defp expand_each({key, atom}, _query, _mode, {preloads, assocs}) when is_atom(atom) do
231
+ assert_key!(key)
232
+
233
+ {[{key, atom}|preloads], assocs}
234
+ end
235
+
236
+ defp expand_each({key, %Ecto.Query.DynamicExpr{} = dynamic}, query, mode, {preloads, assocs}) do
237
+ assert_key!(key)
238
+ assert_assoc!(mode, key)
239
+
240
+ idx = expand_dynamic(dynamic, query)
241
+ {preloads, [{key, {idx, []}}|assocs]}
242
+ end
243
+
244
+ defp expand_each({key, {%Ecto.Query.DynamicExpr{} = dynamic, inner}}, query, mode, {preloads, assocs}) do
245
+ assert_key!(key)
246
+ assert_assoc!(mode, key)
247
+
248
+ idx = expand_dynamic(dynamic, query)
249
+ {inner_preloads, inner_assocs} = expand(inner, query, :assoc, [], [])
250
+ assocs = [{key, {idx, inner_assocs}}|assocs]
251
+
252
+ case inner_preloads do
253
+ [] -> {preloads, assocs}
254
+ _ -> {[{key, inner_preloads}|preloads], assocs}
255
+ end
256
+ end
257
+
258
+ defp expand_each({key, {query_or_fun, inner}}, query, _mode, {preloads, assocs}) do
259
+ assert_key!(key)
260
+ assert_query_or_fun!(query_or_fun, key)
261
+
262
+ {inner_preloads, []} = expand(inner, query, :preload, [], [])
263
+ {[{key, {query_or_fun, inner_preloads}}|preloads], assocs}
264
+ end
265
+
266
+ defp expand_each({key, list}, query, _mode, {preloads, assocs}) when is_list(list) do
267
+ assert_key!(key)
268
+
269
+ {inner_preloads, []} = expand(list, query, :preload, [], [])
270
+ {[{key, inner_preloads}|preloads], assocs}
271
+ end
272
+
273
+ defp expand_each({key, query_or_fun}, _query, _mode, {preloads, assocs}) do
274
+ assert_key!(key)
275
+ assert_query_or_fun!(query_or_fun, key)
276
+
277
+ {[{key, query_or_fun}|preloads], assocs}
278
+ end
279
+
280
+ defp expand_each(other, query, mode, {preloads, assocs}) do
281
+ expand(other, query, mode, preloads, assocs)
282
+ end
283
+
284
+ defp expand_dynamic(%Ecto.Query.DynamicExpr{} = dynamic, query) do
285
+ case Builder.Dynamic.fully_expand(query, dynamic) do
286
+ {{:&, [], [idx]}, _, _, _, _, _} when is_integer(idx) ->
287
+ idx
288
+
289
+ _ ->
290
+ raise ArgumentError,
291
+ "invalid dynamic in preload: `#{inspect(dynamic)}`. " <>
292
+ "Dynamic expressions in preload must evaluate to a single binding, as in: " <>
293
+ "`dynamic([comments: c], c)`"
294
+ end
295
+ end
296
+
297
+ defp assert_key!(key), do: key!(key) && :ok
298
+
299
+ defp assert_query_or_fun!(%Ecto.Query{}, _key), do: :ok
300
+ defp assert_query_or_fun!(fun, _key) when is_function(fun, 1), do: :ok
301
+ defp assert_query_or_fun!(other, key) do
302
+ raise ArgumentError,
303
+ "invalid preload for key `#{inspect(key)}`: #{inspect(other)}. " <>
304
+ "Preloads can be a query, a function (arity 1), or a dynamic that " <>
305
+ "evaluates to a single binding."
306
+ end
307
+
308
+ defp assert_assoc!(mode, _atom) when mode in [:both, :assoc], do: :ok
309
+ defp assert_assoc!(_mode, atom) do
310
+ raise ArgumentError,
311
+ "cannot preload join association `#{inspect(atom)}` " <>
312
+ "because parent preload is not a join association"
313
+ end
314
+
315
+ defp assert_assoc!(mode, _atom, _var) when mode in [:both, :assoc], do: :ok
316
+ defp assert_assoc!(_mode, atom, var) do
317
+ Builder.error!(
318
+ "cannot preload join association `#{Macro.to_string atom}` with binding `#{var}` " <>
319
+ "because parent preload is not a join association"
320
+ )
321
+ end
322
+ end
deps/ecto/lib/ecto/query/builder/select.ex ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Select do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+
8
+ @doc """
9
+ Escapes a select.
10
+
11
+ It allows tuples, lists and variables at the top level. Inside the
12
+ tuples and lists query expressions are allowed.
13
+
14
+ ## Examples
15
+
16
+ iex> escape({1, 2}, [], __ENV__)
17
+ {{:{}, [], [:{}, [], [1, 2]]}, {[], %{take: %{}, subqueries: [], aliases: %{}}}}
18
+
19
+ iex> escape([1, 2], [], __ENV__)
20
+ {[1, 2], {[], %{take: %{}, subqueries: [], aliases: %{}}}}
21
+
22
+ iex> escape(quote(do: x), [x: 0], __ENV__)
23
+ {{:{}, [], [:&, [], [0]]}, {[], %{take: %{}, subqueries: [], aliases: %{}}}}
24
+
25
+ """
26
+ @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {Macro.t, {list, %{take: map, subqueries: list}}}
27
+ def escape(atom, _vars, _env)
28
+ when is_atom(atom) and not is_boolean(atom) and atom != nil do
29
+ Builder.error! """
30
+ #{inspect(atom)} is not a valid query expression, :select expects a query expression or a list of fields
31
+ """
32
+ end
33
+
34
+ def escape(other, vars, env) do
35
+ cond do
36
+ take?(other) ->
37
+ {
38
+ {:{}, [], [:&, [], [0]]},
39
+ {[], %{take: %{0 => {:any, Macro.expand(other, env)}}, subqueries: [], aliases: %{}}}
40
+ }
41
+
42
+ maybe_take?(other) ->
43
+ Builder.error! """
44
+ Cannot mix fields with interpolations, such as: `select: [:foo, ^:bar, :baz]`. \
45
+ Instead interpolate all fields at once, such as: `select: ^[:foo, :bar, :baz]`. \
46
+ Got: #{Macro.to_string(other)}.
47
+ """
48
+
49
+ true ->
50
+ {expr, {params, acc}} = escape(other, {[], %{take: %{}, subqueries: [], aliases: %{}}}, vars, env)
51
+ acc = %{acc | subqueries: Enum.reverse(acc.subqueries)}
52
+ {expr, {params, acc}}
53
+ end
54
+ end
55
+
56
+ # Tuple
57
+ defp escape({left, right}, params_acc, vars, env) do
58
+ escape({:{}, [], [left, right]}, params_acc, vars, env)
59
+ end
60
+
61
+ # Tuple
62
+ defp escape({:{}, _, list}, params_acc, vars, env) do
63
+ {list, params_acc} = Enum.map_reduce(list, params_acc, &escape(&1, &2, vars, env))
64
+ expr = {:{}, [], [:{}, [], list]}
65
+ {expr, params_acc}
66
+ end
67
+
68
+ # Struct
69
+ defp escape({:%, _, [name, map]}, params_acc, vars, env) do
70
+ name = Macro.expand(name, env)
71
+ {escaped_map, params_acc} = escape(map, params_acc, vars, env)
72
+ {{:{}, [], [:%, [], [name, escaped_map]]}, params_acc}
73
+ end
74
+
75
+ # Map
76
+ defp escape({:%{}, _, [{:|, _, [data, pairs]}]}, params_acc, vars, env) do
77
+ {escaped_data, params_acc} = escape(data, params_acc, vars, env)
78
+ {pairs, params_acc} = escape_pairs(pairs, data, params_acc, vars, env)
79
+ {{:{}, [], [:%{}, [], [{:{}, [], [:|, [], [escaped_data, pairs]]}]]}, params_acc}
80
+ end
81
+
82
+ # Merge
83
+ defp escape({:merge, _, [left, {kind, _, _} = right]}, params_acc, vars, env)
84
+ when kind in [:%{}, :map] do
85
+ {left, params_acc} = escape(left, params_acc, vars, env)
86
+ {right, params_acc} = escape(right, params_acc, vars, env)
87
+ {{:{}, [], [:merge, [], [left, right]]}, params_acc}
88
+ end
89
+
90
+ defp escape({:merge, _, [_left, right]}, _params_acc, _vars, _env) do
91
+ Builder.error! "expected the second argument of merge/2 in select to be a map, got: `#{Macro.to_string(right)}`"
92
+ end
93
+
94
+ # Map
95
+ defp escape({:%{}, _, pairs}, params_acc, vars, env) do
96
+ {pairs, params_acc} = escape_pairs(pairs, nil, params_acc, vars, env)
97
+ {{:{}, [], [:%{}, [], pairs]}, params_acc}
98
+ end
99
+
100
+ # List
101
+ defp escape(list, params_acc, vars, env) when is_list(list) do
102
+ Enum.map_reduce(list, params_acc, &escape(&1, &2, vars, env))
103
+ end
104
+
105
+ # map/struct(var, [:foo, :bar])
106
+ defp escape({tag, _, [{var, _, context}, fields]}, {params, acc}, vars, env)
107
+ when tag in [:map, :struct] and is_atom(var) and is_atom(context) do
108
+ taken = escape_fields(fields, tag, env)
109
+ expr = Builder.escape_var!(var, vars)
110
+ acc = add_take(acc, Builder.find_var!(var, vars), {tag, taken})
111
+ {expr, {params, acc}}
112
+ end
113
+
114
+ # aliased values
115
+ defp escape({:selected_as, _, [expr, name]}, {params, acc}, vars, env) do
116
+ name = Builder.quoted_atom!(name, "selected_as/2")
117
+ {escaped, {params, acc}} = Builder.escape(expr, :any, {params, acc}, vars, env)
118
+ expr = {:{}, [], [:selected_as, [], [escaped, name]]}
119
+ aliases = Builder.add_select_alias(acc.aliases, name)
120
+ {expr, {params, %{acc | aliases: aliases}}}
121
+ end
122
+
123
+ defp escape(expr, params_acc, vars, env) do
124
+ Builder.escape(expr, :any, params_acc, vars, {env, &escape_expansion/5})
125
+ end
126
+
127
+ defp escape_expansion(expr, _type, params_acc, vars, env) do
128
+ escape(expr, params_acc, vars, env)
129
+ end
130
+
131
+ defp escape_pairs(pairs, update_data, params_acc, vars, env) do
132
+ Enum.map_reduce(pairs, params_acc, fn {k, v}, acc ->
133
+ v = tag_update_param(update_data, k, v)
134
+ {k, acc} = escape_key(k, acc, vars, env)
135
+ {v, acc} = escape(v, acc, vars, env)
136
+ {{k, v}, acc}
137
+ end)
138
+ end
139
+
140
+ defp tag_update_param({var, _, context}, field, {:^, _,[_]} = param) when is_atom(var) and is_atom(context) do
141
+ {:type, [], [param, {{:., [], [{var, [], context}, field]}, [], []}]}
142
+ end
143
+
144
+ defp tag_update_param(_, _, value), do: value
145
+
146
+ defp escape_key(k, params_acc, _vars, _env) when is_atom(k) do
147
+ {k, params_acc}
148
+ end
149
+
150
+ defp escape_key({:^, _, [k]}, params_acc, _vars, _env) do
151
+ checked = quote do: Ecto.Query.Builder.Select.map_key!(unquote(k))
152
+ {checked, params_acc}
153
+ end
154
+
155
+ defp escape_key(k, params_acc, vars, env) do
156
+ escape(k, params_acc, vars, env)
157
+ end
158
+
159
+ defp escape_fields({:^, _, [interpolated]}, tag, _env) do
160
+ quote do
161
+ Ecto.Query.Builder.Select.fields!(unquote(tag), unquote(interpolated))
162
+ end
163
+ end
164
+ defp escape_fields(expr, tag, env) do
165
+ case Macro.expand(expr, env) do
166
+ fields when is_list(fields) ->
167
+ fields
168
+ _ ->
169
+ Builder.error!(
170
+ "`#{tag}/2` in `select` expects either a literal or " <>
171
+ "an interpolated (1) list of atom fields, (2) dynamic, or " <>
172
+ "(3) map with dynamic values"
173
+ )
174
+ end
175
+ end
176
+
177
+ @doc """
178
+ Called at runtime to verify a field.
179
+ """
180
+ def fields!(tag, fields) do
181
+ if take?(fields) do
182
+ fields
183
+ else
184
+ raise ArgumentError,
185
+ "expected a list of fields in `#{tag}/2` inside `select`, got: `#{inspect fields}`"
186
+ end
187
+ end
188
+
189
+ @doc """
190
+ Called at runtime to verify a map key
191
+ """
192
+ def map_key!(key) when is_binary(key), do: key
193
+ def map_key!(key) when is_integer(key), do: key
194
+ def map_key!(key) when is_float(key), do: key
195
+ def map_key!(key) when is_atom(key), do: key
196
+
197
+ def map_key!(other) do
198
+ Builder.error!(
199
+ "interpolated map keys in `:select` can only be atoms, strings or numbers, got: #{inspect(other)}"
200
+ )
201
+ end
202
+
203
+ # atom list sigils
204
+ defp take?({name, _, [_, modifiers]}) when name in ~w(sigil_w sigil_W)a do
205
+ ?a in modifiers
206
+ end
207
+
208
+ defp take?(fields) do
209
+ is_list(fields) and Enum.all?(fields, fn
210
+ {k, v} when is_atom(k) -> take?(List.wrap(v))
211
+ k when is_atom(k) -> true
212
+ _ -> false
213
+ end)
214
+ end
215
+
216
+ defp maybe_take?(fields) do
217
+ is_list(fields) and Enum.any?(fields, fn
218
+ {k, v} when is_atom(k) -> maybe_take?(List.wrap(v))
219
+ k when is_atom(k) -> true
220
+ _ -> false
221
+ end)
222
+ end
223
+
224
+ @doc """
225
+ Called at runtime for interpolated/dynamic selects.
226
+ """
227
+ def select!(kind, query, fields, file, line) when is_map(fields) do
228
+ {expr, {params, subqueries, aliases, _count}} = expand_nested(fields, {[], [], %{}, 0}, query)
229
+
230
+ %Ecto.Query.SelectExpr{
231
+ expr: expr,
232
+ params: Enum.reverse(params),
233
+ subqueries: Enum.reverse(subqueries),
234
+ aliases: aliases,
235
+ file: file,
236
+ line: line
237
+ }
238
+ |> apply_or_merge(kind, query)
239
+ end
240
+
241
+ def select!(kind, query, fields, file, line) do
242
+ take = %{0 => {:any, fields!(:select, fields)}}
243
+
244
+ %Ecto.Query.SelectExpr{expr: {:&, [], [0]}, take: take, file: file, line: line}
245
+ |> apply_or_merge(kind, query)
246
+ end
247
+
248
+ defp apply_or_merge(select, kind, query) do
249
+ if kind == :select do
250
+ apply(query, select)
251
+ else
252
+ merge(query, select)
253
+ end
254
+ end
255
+
256
+ defp expand_nested(%Ecto.Query.DynamicExpr{} = dynamic, {params, subqueries, aliases, count}, query) do
257
+ {expr, params, subqueries, aliases, count} =
258
+ Ecto.Query.Builder.Dynamic.partially_expand(query, dynamic, params, subqueries, aliases, count)
259
+
260
+ {expr, {params, subqueries, aliases, count}}
261
+ end
262
+
263
+ defp expand_nested(%Ecto.SubQuery{} = subquery, {params, subqueries, aliases, count}, _query) do
264
+ index = length(subqueries)
265
+ # used both in ast and in parameters, as a placeholder.
266
+ expr = {:subquery, index}
267
+ params = [expr | params]
268
+ subqueries = [subquery | subqueries]
269
+ count = count + 1
270
+
271
+ {expr, {params, subqueries, aliases, count}}
272
+ end
273
+
274
+ defp expand_nested(%type{} = fields, acc, query) do
275
+ {fields, acc} = fields |> Map.from_struct() |> expand_nested(acc, query)
276
+ {{:%, [], [type, fields]}, acc}
277
+ end
278
+
279
+ defp expand_nested(fields, acc, query) when is_map(fields) do
280
+ {fields, acc} = fields |> Enum.map_reduce(acc, &expand_nested_pair(&1, &2, query))
281
+ {{:%{}, [], fields}, acc}
282
+ end
283
+
284
+ defp expand_nested(invalid, _acc, query) when is_list(invalid) or is_tuple(invalid) do
285
+ raise Ecto.QueryError,
286
+ query: query,
287
+ message:
288
+ "Interpolated map values in :select can only be " <>
289
+ "maps, structs, dynamics, subqueries and literals. Got #{inspect(invalid)}"
290
+ end
291
+
292
+ defp expand_nested(other, acc, _query) do
293
+ {other, acc}
294
+ end
295
+
296
+ defp expand_nested_pair({key, val}, acc, query) do
297
+ {val, acc} = expand_nested(val, acc, query)
298
+ {{key, val}, acc}
299
+ end
300
+
301
+ @doc """
302
+ Builds a quoted expression.
303
+
304
+ The quoted expression should evaluate to a query at runtime.
305
+ If possible, it does all calculations at compile time to avoid
306
+ runtime work.
307
+ """
308
+ @spec build(:select | :merge, Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
309
+
310
+ def build(kind, query, _binding, {:^, _, [var]}, env) do
311
+ quote do
312
+ Ecto.Query.Builder.Select.select!(unquote(kind), unquote(query), unquote(var),
313
+ unquote(env.file), unquote(env.line))
314
+ end
315
+ end
316
+
317
+ def build(kind, query, binding, expr, env) do
318
+ {query, binding} = Builder.escape_binding(query, binding, env)
319
+ {expr, {params, acc}} = escape(expr, binding, env)
320
+ params = Builder.escape_params(params)
321
+ take = {:%{}, [], Map.to_list(acc.take)}
322
+ aliases = escape_aliases(acc.aliases)
323
+
324
+ select = quote do: %Ecto.Query.SelectExpr{
325
+ expr: unquote(expr),
326
+ params: unquote(params),
327
+ file: unquote(env.file),
328
+ line: unquote(env.line),
329
+ take: unquote(take),
330
+ subqueries: unquote(acc.subqueries),
331
+ aliases: unquote(aliases)}
332
+
333
+ if kind == :select do
334
+ Builder.apply_query(query, __MODULE__, [select], env)
335
+ else
336
+ quote do
337
+ query = unquote(query)
338
+ Builder.Select.merge(query, unquote(select))
339
+ end
340
+ end
341
+ end
342
+
343
+ defp escape_aliases(%{} = aliases), do: {:%{}, [], Map.to_list(aliases)}
344
+ defp escape_aliases(aliases), do: aliases
345
+
346
+ @doc """
347
+ The callback applied by `build/5` to build the query.
348
+ """
349
+ @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
350
+ def apply(%Ecto.Query{select: nil} = query, expr) do
351
+ %{query | select: expr}
352
+ end
353
+ def apply(%Ecto.Query{}, _expr) do
354
+ Builder.error! "only one select expression is allowed in query"
355
+ end
356
+ def apply(query, expr) do
357
+ apply(Ecto.Queryable.to_query(query), expr)
358
+ end
359
+
360
+ @doc """
361
+ The callback applied by `build/5` when merging.
362
+ """
363
+ def merge(%Ecto.Query{select: nil} = query, new_select) do
364
+ merge(query, new_select, {:&, [], [0]}, [], [], %{}, %{}, new_select)
365
+ end
366
+ def merge(%Ecto.Query{select: old_select} = query, new_select) do
367
+ %{expr: old_expr, params: old_params, subqueries: old_subqueries, take: old_take, aliases: old_aliases} = old_select
368
+ merge(query, old_select, old_expr, old_params, old_subqueries, old_take, old_aliases, new_select)
369
+ end
370
+ def merge(query, expr) do
371
+ merge(Ecto.Queryable.to_query(query), expr)
372
+ end
373
+
374
+ defp merge(query, select, old_expr, old_params, old_subqueries, old_take, old_aliases, new_select) do
375
+ %{expr: new_expr, params: new_params, subqueries: new_subqueries, take: new_take, aliases: new_aliases} = new_select
376
+
377
+ new_expr =
378
+ new_expr
379
+ |> Ecto.Query.Builder.bump_interpolations(old_params)
380
+ |> Ecto.Query.Builder.bump_subqueries(old_subqueries)
381
+
382
+ expr =
383
+ case {classify_merge(old_expr, old_take), classify_merge(new_expr, new_take)} do
384
+ {_, _} when old_expr == new_expr ->
385
+ new_expr
386
+
387
+ {{:source, meta, ix}, {:source, _, ix}} ->
388
+ {:&, meta, [ix]}
389
+
390
+ {{:struct, meta, name, old_fields}, {:map, _, new_fields}} when old_params == [] ->
391
+ cond do
392
+ new_fields == [] ->
393
+ old_expr
394
+
395
+ Keyword.keyword?(old_fields) and Keyword.keyword?(new_fields) ->
396
+ {:%, meta, [name, {:%{}, meta, Keyword.merge(old_fields, new_fields)}]}
397
+
398
+ true ->
399
+ {:merge, [], [old_expr, new_expr]}
400
+ end
401
+
402
+ {{:map, meta, old_fields}, {:map, _, new_fields}} ->
403
+ cond do
404
+ old_fields == [] ->
405
+ new_expr
406
+
407
+ new_fields == [] ->
408
+ old_expr
409
+
410
+ true ->
411
+ require_distinct_keys? = old_params != []
412
+
413
+ case merge_map_fields(old_fields, new_fields, require_distinct_keys?) do
414
+ fields when is_list(fields) ->
415
+ {:%{}, meta, fields}
416
+
417
+ :error ->
418
+ {:merge, [], [old_expr, new_expr]}
419
+ end
420
+ end
421
+
422
+ {_, {:map, _, _}} ->
423
+ {:merge, [], [old_expr, new_expr]}
424
+
425
+ {_, _} ->
426
+ message = """
427
+ cannot select_merge #{merge_argument_to_error(new_expr, query)} into \
428
+ #{merge_argument_to_error(old_expr, query)}, those select expressions \
429
+ are incompatible. You can only select_merge:
430
+
431
+ * a source (such as post) with another source (of the same type)
432
+ * a source (such as post) with a map
433
+ * a struct with a map
434
+ * a map with a map
435
+
436
+ Incompatible merge found
437
+ """
438
+
439
+ raise Ecto.QueryError, query: query, message: message
440
+ end
441
+
442
+ select = %{
443
+ select | expr: expr,
444
+ params: old_params ++ bump_subquery_params(new_params, old_subqueries),
445
+ subqueries: old_subqueries ++ new_subqueries,
446
+ take: merge_take(query, old_expr, old_take, new_take),
447
+ aliases: merge_aliases(old_aliases, new_aliases)
448
+ }
449
+
450
+ %{query | select: select}
451
+ end
452
+
453
+ defp classify_merge({:&, meta, [ix]}, take) when is_integer(ix) do
454
+ case take do
455
+ %{^ix => {:map, _}} -> {:map, meta, :runtime}
456
+ _ -> {:source, meta, ix}
457
+ end
458
+ end
459
+
460
+ defp classify_merge({:%, meta, [name, {:%{}, _, fields}]}, _take)
461
+ when fields == [] or tuple_size(hd(fields)) == 2 do
462
+ {:struct, meta, name, fields}
463
+ end
464
+
465
+ defp classify_merge({:%{}, meta, fields}, _take)
466
+ when fields == [] or tuple_size(hd(fields)) == 2 do
467
+ {:map, meta, fields}
468
+ end
469
+
470
+ defp classify_merge({:%{}, meta, _}, _take) do
471
+ {:map, meta, :runtime}
472
+ end
473
+
474
+ defp classify_merge(_, _take) do
475
+ :error
476
+ end
477
+
478
+ defp merge_map_fields(old_fields, new_fields, false) do
479
+ if Keyword.keyword?(old_fields) and Keyword.keyword?(new_fields) do
480
+ Keyword.merge(old_fields, new_fields)
481
+ else
482
+ :error
483
+ end
484
+ end
485
+
486
+ defp merge_map_fields(old_fields, new_fields, true) when is_list(old_fields) do
487
+ if Keyword.keyword?(new_fields) do
488
+ valid? =
489
+ Enum.reduce_while(old_fields, true, fn
490
+ {k, _v}, _ when is_atom(k) ->
491
+ if Keyword.has_key?(new_fields, k),
492
+ do: {:halt, false},
493
+ else: {:cont, true}
494
+
495
+ _, _ ->
496
+ {:halt, false}
497
+ end)
498
+
499
+ if valid?, do: old_fields ++ new_fields, else: :error
500
+ else
501
+ :error
502
+ end
503
+ end
504
+
505
+ defp merge_map_fields(_, _, true), do: :error
506
+
507
+ defp merge_argument_to_error({:&, _, [0]}, %{from: %{source: {source, alias}}}) do
508
+ "source #{inspect(source || alias)}"
509
+ end
510
+
511
+ defp merge_argument_to_error({:&, _, [ix]}, _query) do
512
+ "join (at position #{ix})"
513
+ end
514
+
515
+ defp merge_argument_to_error(other, _query) do
516
+ Macro.to_string(other)
517
+ end
518
+
519
+ defp add_take(acc, key, value) do
520
+ take = Map.update(acc.take, key, value, &merge_take_kind_and_fields(key, &1, value))
521
+ %{acc | take: take}
522
+ end
523
+
524
+ defp bump_subquery_params(new_params, old_subqueries) do
525
+ len = length(old_subqueries)
526
+
527
+ Enum.map(new_params, fn
528
+ {:subquery, counter} -> {:subquery, len + counter}
529
+ other -> other
530
+ end)
531
+ end
532
+
533
+ defp merge_take(query, old_expr, %{} = old_take, %{} = new_take) do
534
+ Enum.reduce(new_take, old_take, fn {binding, {new_kind, new_fields} = new_value}, acc ->
535
+ case acc do
536
+ %{^binding => old_value} ->
537
+ Map.put(acc, binding, merge_take_kind_and_fields(binding, old_value, new_value))
538
+
539
+ %{} ->
540
+ # If merging with a schema, add the schema's query fields. This comes in handy if the user
541
+ # is merging fields with load_in_query = false.
542
+ # If merging with a schemaless source, do nothing so the planner can take all the fields.
543
+ case old_expr do
544
+ {:&, _, [^binding]} ->
545
+ source = Enum.at([query.from | query.joins], binding).source
546
+
547
+ case source do
548
+ {_, schema} when schema != nil ->
549
+ Map.put(acc, binding, {new_kind, Enum.uniq(new_fields ++ schema.__schema__(:query_fields))})
550
+
551
+ _ ->
552
+ acc
553
+ end
554
+
555
+ _ ->
556
+ Map.put(acc, binding, new_value)
557
+ end
558
+ end
559
+ end)
560
+ end
561
+
562
+ defp merge_take_kind_and_fields(binding, {old_kind, old_fields}, {new_kind, new_fields}) do
563
+ {merge_take_kind(binding, old_kind, new_kind), Enum.uniq(old_fields ++ new_fields)}
564
+ end
565
+
566
+ defp merge_take_kind(_, kind, kind), do: kind
567
+ defp merge_take_kind(_, :any, kind), do: kind
568
+ defp merge_take_kind(_, kind, :any), do: kind
569
+ defp merge_take_kind(binding, old, new) do
570
+ Builder.error! "cannot select_merge because the binding at position #{binding} " <>
571
+ "was previously specified as a `#{old}` and later as `#{new}`"
572
+ end
573
+
574
+ defp merge_aliases(old_aliases, new_aliases) do
575
+ Enum.reduce(new_aliases, old_aliases, fn {alias, _}, aliases ->
576
+ Builder.add_select_alias(aliases, alias)
577
+ end)
578
+ end
579
+ end
deps/ecto/lib/ecto/query/builder/update.ex ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Update do
4
+ @moduledoc false
5
+
6
+ @keys [:set, :inc, :push, :pull]
7
+ alias Ecto.Query.Builder
8
+
9
+ @doc """
10
+ Escapes a list of quoted expressions.
11
+
12
+ iex> escape([], [], __ENV__)
13
+ {[], [], []}
14
+
15
+ iex> escape([set: []], [], __ENV__)
16
+ {[], [], []}
17
+
18
+ iex> escape(quote(do: ^[set: []]), [], __ENV__)
19
+ {[], [set: []], []}
20
+
21
+ iex> escape(quote(do: [set: ^[foo: 1]]), [], __ENV__)
22
+ {[], [set: [foo: 1]], []}
23
+
24
+ iex> escape(quote(do: [set: [foo: ^1]]), [], __ENV__)
25
+ {[], [set: [foo: 1]], []}
26
+
27
+ """
28
+ @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {Macro.t, Macro.t, list}
29
+ def escape(expr, vars, env) when is_list(expr) do
30
+ escape_op(expr, [], [], [], vars, env)
31
+ end
32
+
33
+ def escape({:^, _, [v]}, _vars, _env) do
34
+ {[], v, []}
35
+ end
36
+
37
+ def escape(expr, _vars, _env) do
38
+ compile_error!(expr)
39
+ end
40
+
41
+ defp escape_op([{k, v}|t], compile, runtime, params, vars, env) when is_atom(k) and is_list(v) do
42
+ validate_op!(k)
43
+ {compile_values, runtime_values, params} = escape_kw(k, v, params, vars, env)
44
+ compile =
45
+ if compile_values == [], do: compile, else: [{k, Enum.reverse(compile_values)} | compile]
46
+ runtime =
47
+ if runtime_values == [], do: runtime, else: [{k, Enum.reverse(runtime_values)} | runtime]
48
+ escape_op(t, compile, runtime, params, vars, env)
49
+ end
50
+
51
+ defp escape_op([{k, {:^, _, [v]}}|t], compile, runtime, params, vars, env) when is_atom(k) do
52
+ validate_op!(k)
53
+ escape_op(t, compile, [{k, v}|runtime], params, vars, env)
54
+ end
55
+
56
+ defp escape_op([], compile, runtime, params, _vars, _env) do
57
+ {Enum.reverse(compile), Enum.reverse(runtime), params}
58
+ end
59
+
60
+ defp escape_op(expr, _compile, _runtime, _params, _vars, _env) do
61
+ compile_error!(expr)
62
+ end
63
+
64
+ defp escape_kw(op, kw, params, vars, env) do
65
+ Enum.reduce kw, {[], [], params}, fn
66
+ {k, {:^, _, [v]}}, {compile, runtime, params} when is_atom(k) ->
67
+ {compile, [{k, v} | runtime], params}
68
+ {k, v}, {compile, runtime, params} ->
69
+ k = escape_field!(k)
70
+ {v, {params, _acc}} = Builder.escape(v, type_for_key(op, {0, k}), {params, %{}}, vars, env)
71
+ {[{k, v} | compile], runtime, params}
72
+ _, _acc ->
73
+ Builder.error! "malformed #{inspect op} in update `#{Macro.to_string(kw)}`, " <>
74
+ "expected a keyword list"
75
+ end
76
+ end
77
+
78
+ defp escape_field!({:^, _, [k]}), do: quote(do: Ecto.Query.Builder.Update.field!(unquote(k)))
79
+ defp escape_field!(k) when is_atom(k), do: k
80
+
81
+ defp escape_field!(k) do
82
+ Builder.error!(
83
+ "expected an atom field or an interpolated field in `update`, got `#{inspect(k)}`"
84
+ )
85
+ end
86
+
87
+ def field!(field) when is_atom(field), do: field
88
+
89
+ def field!(other) do
90
+ raise ArgumentError, "expected a field as an atom in `update`, got: `#{inspect other}`"
91
+ end
92
+
93
+ defp compile_error!(expr) do
94
+ Builder.error! "malformed update `#{Macro.to_string(expr)}` in query expression, " <>
95
+ "expected a keyword list with set/push/pull as keys with field-value " <>
96
+ "pairs as values"
97
+ end
98
+
99
+ @doc """
100
+ Builds a quoted expression.
101
+
102
+ The quoted expression should evaluate to a query at runtime.
103
+ If possible, it does all calculations at compile time to avoid
104
+ runtime work.
105
+ """
106
+ @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
107
+ def build(query, binding, expr, env) do
108
+ {query, binding} = Builder.escape_binding(query, binding, env)
109
+ {compile, runtime, params} = escape(expr, binding, env)
110
+
111
+ query =
112
+ if compile == [] do
113
+ query
114
+ else
115
+ params = Builder.escape_params(params)
116
+
117
+ update = quote do
118
+ %Ecto.Query.QueryExpr{expr: unquote(compile), params: unquote(params),
119
+ file: unquote(env.file), line: unquote(env.line)}
120
+ end
121
+
122
+ Builder.apply_query(query, __MODULE__, [update], env)
123
+ end
124
+
125
+ if runtime == [] do
126
+ query
127
+ else
128
+ quote do
129
+ Ecto.Query.Builder.Update.update!(unquote(query), unquote(runtime),
130
+ unquote(env.file), unquote(env.line))
131
+ end
132
+ end
133
+ end
134
+
135
+ @doc """
136
+ The callback applied by `build/4` to build the query.
137
+ """
138
+ @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
139
+ def apply(%Ecto.Query{updates: updates} = query, expr) do
140
+ %{query | updates: updates ++ [expr]}
141
+ end
142
+ def apply(query, expr) do
143
+ apply(Ecto.Queryable.to_query(query), expr)
144
+ end
145
+
146
+ @doc """
147
+ If there are interpolated updates at compile time,
148
+ we need to handle them at runtime. We do such in
149
+ this callback.
150
+ """
151
+ def update!(query, runtime, file, line) when is_list(runtime) do
152
+ {runtime, {params, _count}} =
153
+ Enum.map_reduce runtime, {[], 0}, fn
154
+ {k, v}, acc when is_atom(k) and is_list(v) ->
155
+ validate_op!(k)
156
+ {v, params} = runtime_field!(query, k, v, acc)
157
+ {{k, v}, params}
158
+ _, _ ->
159
+ runtime_error!(runtime)
160
+ end
161
+
162
+ expr = %Ecto.Query.QueryExpr{expr: runtime, params: Enum.reverse(params),
163
+ file: file, line: line}
164
+
165
+ apply(query, expr)
166
+ end
167
+
168
+ def update!(_query, runtime, _file, _line) do
169
+ runtime_error!(runtime)
170
+ end
171
+
172
+ defp runtime_field!(query, key, kw, acc) do
173
+ Enum.map_reduce kw, acc, fn
174
+ {k, %Ecto.Query.DynamicExpr{} = v}, {params, count} when is_atom(k) ->
175
+ {v, params, count} = Ecto.Query.Builder.Dynamic.partially_expand(:update, query, v, params, count)
176
+ {{k, v}, {params, count}}
177
+ {k, v}, {params, count} when is_atom(k) ->
178
+ params = [{v, type_for_key(key, {0, k})} | params]
179
+ {{k, {:^, [], [count]}}, {params, count + 1}}
180
+ _, _acc ->
181
+ raise ArgumentError, "malformed #{inspect key} in update `#{inspect(kw)}`, " <>
182
+ "expected a keyword list"
183
+ end
184
+ end
185
+
186
+ defp runtime_error!(value) do
187
+ raise ArgumentError,
188
+ "malformed update `#{inspect(value)}` in query expression, " <>
189
+ "expected a keyword list with set/push/pull as keys with field-value pairs as values"
190
+ end
191
+
192
+ defp validate_op!(key) when key in @keys, do: :ok
193
+ defp validate_op!(key), do: Builder.error! "unknown key `#{inspect(key)}` in update"
194
+
195
+ # Out means the given type must be taken out of an array
196
+ # It is the opposite of "left in right" in the query API.
197
+ defp type_for_key(:push, type), do: {:out, type}
198
+ defp type_for_key(:pull, type), do: {:out, type}
199
+ defp type_for_key(_, type), do: type
200
+ end
deps/ecto/lib/ecto/query/builder/windows.ex ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [apply: 2]
2
+
3
+ defmodule Ecto.Query.Builder.Windows do
4
+ @moduledoc false
5
+
6
+ alias Ecto.Query.Builder
7
+ alias Ecto.Query.Builder.{GroupBy, OrderBy}
8
+ @sort_order [:partition_by, :order_by, :frame]
9
+
10
+ @doc """
11
+ Escapes a window params.
12
+
13
+ ## Examples
14
+
15
+ iex> escape(quote do [order_by: [desc: 13]] end, {[], %{}}, [x: 0], __ENV__)
16
+ {[order_by: [desc: 13]], [], {[], %{}}}
17
+
18
+ """
19
+ @spec escape([Macro.t], {list, term}, Keyword.t, Macro.Env.t | {Macro.Env.t, fun})
20
+ :: {Macro.t, [{atom, term}], {list, term}}
21
+ def escape(kw, params_acc, vars, env) when is_list(kw) do
22
+ {compile, runtime} = sort(@sort_order, kw, :compile, [], [])
23
+ {compile, params_acc} = Enum.map_reduce(compile, params_acc, &escape_compile(&1, &2, vars, env))
24
+ {compile, runtime, params_acc}
25
+ end
26
+
27
+ def escape(kw, _params_acc, _vars, _env) do
28
+ error!(kw)
29
+ end
30
+
31
+ defp sort([key | keys], kw, mode, compile, runtime) do
32
+ case Keyword.pop(kw, key) do
33
+ {nil, kw} ->
34
+ sort(keys, kw, mode, compile, runtime)
35
+
36
+ {{:^, _, [var]}, kw} ->
37
+ sort(keys, kw, :runtime, compile, [{key, var} | runtime])
38
+
39
+ {_, _} when mode == :runtime ->
40
+ [{runtime_key, _} | _] = runtime
41
+ raise ArgumentError, "window has an interpolated value under `#{runtime_key}` " <>
42
+ "and therefore `#{key}` must also be interpolated"
43
+
44
+ {expr, kw} ->
45
+ sort(keys, kw, mode, [{key, expr} | compile], runtime)
46
+ end
47
+ end
48
+
49
+ defp sort([], [], _mode, compile, runtime) do
50
+ {Enum.reverse(compile), Enum.reverse(runtime)}
51
+ end
52
+
53
+ defp sort([], kw, _mode, _compile, _runtime) do
54
+ error!(kw)
55
+ end
56
+
57
+ defp escape_compile({:partition_by, fields}, params_acc, vars, env) do
58
+ {fields, params_acc} = GroupBy.escape(:partition_by, fields, params_acc, vars, env)
59
+ {{:partition_by, fields}, params_acc}
60
+ end
61
+
62
+ defp escape_compile({:order_by, fields}, params_acc, vars, env) do
63
+ {fields, params_acc} = OrderBy.escape(:order_by, fields, params_acc, vars, env)
64
+ {{:order_by, fields}, params_acc}
65
+ end
66
+
67
+ defp escape_compile({:frame, frame_clause}, params_acc, vars, env) do
68
+ {frame_clause, params_acc} = escape_frame(frame_clause, params_acc, vars, env)
69
+ {{:frame, frame_clause}, params_acc}
70
+ end
71
+
72
+ defp escape_frame({:fragment, _, _} = fragment, params_acc, vars, env) do
73
+ Builder.escape(fragment, :any, params_acc, vars, env)
74
+ end
75
+ defp escape_frame(other, _, _, _) do
76
+ Builder.error!("expected a dynamic or fragment in `:frame`, got: `#{inspect other}`")
77
+ end
78
+
79
+ defp error!(other) do
80
+ Builder.error!(
81
+ "expected window definition to be a keyword list " <>
82
+ "with partition_by, order_by or frame as keys, got: `#{inspect other}`"
83
+ )
84
+ end
85
+
86
+ @doc """
87
+ Builds a quoted expression.
88
+
89
+ The quoted expression should evaluate to a query at runtime.
90
+ If possible, it does all calculations at compile time to avoid
91
+ runtime work.
92
+ """
93
+ @spec build(Macro.t, [Macro.t], Keyword.t, Macro.Env.t) :: Macro.t
94
+ def build(query, binding, windows, env) when is_list(windows) do
95
+ {query, binding} = Builder.escape_binding(query, binding, env)
96
+
97
+ {compile, runtime} =
98
+ windows
99
+ |> Enum.map(&escape_window(binding, &1, env))
100
+ |> Enum.split_with(&elem(&1, 2) == [])
101
+
102
+ compile = Enum.map(compile, &build_compile_window(&1, env))
103
+ runtime = Enum.map(runtime, &build_runtime_window(&1, env))
104
+ query = Builder.apply_query(query, __MODULE__, [compile], env)
105
+
106
+ if runtime == [] do
107
+ query
108
+ else
109
+ quote do
110
+ Ecto.Query.Builder.Windows.runtime!(
111
+ unquote(query),
112
+ unquote(runtime),
113
+ unquote(env.file),
114
+ unquote(env.line)
115
+ )
116
+ end
117
+ end
118
+ end
119
+
120
+ def build(_, _, windows, _) do
121
+ Builder.error!(
122
+ "expected window definitions to be a keyword list with window names as keys and " <>
123
+ "a keyword list with the window definition as value, got: `#{inspect windows}`"
124
+ )
125
+ end
126
+
127
+ defp escape_window(vars, {name, expr}, env) do
128
+ {compile_acc, runtime_acc, {params, acc}} = escape(expr, {[], %{subqueries: []}}, vars, env)
129
+ {name, compile_acc, runtime_acc, Builder.escape_params(params), acc}
130
+ end
131
+
132
+ defp build_compile_window({name, compile_acc, _, params, acc}, env) do
133
+ {name,
134
+ quote do
135
+ %Ecto.Query.ByExpr{
136
+ expr: unquote(compile_acc),
137
+ params: unquote(params),
138
+ subqueries: unquote(acc.subqueries),
139
+ file: unquote(env.file),
140
+ line: unquote(env.line)
141
+ }
142
+ end}
143
+ end
144
+
145
+ defp build_runtime_window({name, compile_acc, runtime_acc, params, acc}, _env) do
146
+ {:{}, [], [name, Enum.reverse(compile_acc), runtime_acc, Enum.reverse(params), {:%{}, [], Map.to_list(acc)}]}
147
+ end
148
+
149
+ @doc """
150
+ Invoked for runtime windows.
151
+ """
152
+ def runtime!(query, runtime, file, line) do
153
+ windows =
154
+ Enum.map(runtime, fn {name, compile_acc, runtime_acc, params, escape_acc} ->
155
+ {{acc, subqueries}, params} = do_runtime_window!(runtime_acc, query, {compile_acc, escape_acc.subqueries}, params)
156
+ expr = %Ecto.Query.ByExpr{expr: Enum.reverse(acc), params: Enum.reverse(params), file: file, line: line, subqueries: subqueries}
157
+ {name, expr}
158
+ end)
159
+
160
+ apply(query, windows)
161
+ end
162
+
163
+ defp do_runtime_window!([{:order_by, order_by} | kw], query, {acc, subqueries_acc}, params) do
164
+ {order_by, params, subqueries} = OrderBy.order_by_or_distinct!(:order_by, query, order_by, params)
165
+
166
+ do_runtime_window!(kw, query, {[{:order_by, order_by} | acc], subqueries_acc ++ subqueries}, params)
167
+ end
168
+
169
+ defp do_runtime_window!([{:partition_by, partition_by} | kw], query, {acc, subqueries_acc}, params) do
170
+ {partition_by, params, subqueries} = GroupBy.group_or_partition_by!(:partition_by, query, partition_by, params)
171
+
172
+ do_runtime_window!(kw, query, {[{:partition_by, partition_by} | acc], subqueries_acc ++ subqueries}, params)
173
+ end
174
+
175
+ defp do_runtime_window!([{:frame, frame} | kw], query, {acc, subqueries_acc}, params) do
176
+ case frame do
177
+ %Ecto.Query.DynamicExpr{} ->
178
+ {frame, params, _count} = Builder.Dynamic.partially_expand(:windows, query, frame, params, length(params))
179
+ do_runtime_window!(kw, query, {[{:frame, frame} | acc], subqueries_acc}, params)
180
+
181
+ _ ->
182
+ raise ArgumentError,
183
+ "expected a dynamic or fragment in `:frame`, got: `#{inspect frame}`"
184
+ end
185
+ end
186
+
187
+ defp do_runtime_window!([], _query, acc, params), do: {acc, params}
188
+
189
+ @doc """
190
+ The callback applied by `build/4` to build the query.
191
+ """
192
+ @spec apply(Ecto.Queryable.t, Keyword.t) :: Ecto.Query.t
193
+ def apply(%Ecto.Query{windows: windows} = query, definitions) do
194
+ merged = Keyword.merge(windows, definitions, fn name, _, _ ->
195
+ Builder.error! "window with name #{name} is already defined"
196
+ end)
197
+
198
+ %{query | windows: merged}
199
+ end
200
+
201
+ def apply(query, definitions) do
202
+ apply(Ecto.Queryable.to_query(query), definitions)
203
+ end
204
+ end
deps/ecto/lib/ecto/query/inspect.ex ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Inspect.Algebra
2
+ import Kernel, except: [to_string: 1]
3
+
4
+ alias Ecto.Query.{DynamicExpr, JoinExpr, QueryExpr, WithExpr, LimitExpr}
5
+
6
+ defimpl Inspect, for: Ecto.Query.DynamicExpr do
7
+ def inspect(%DynamicExpr{binding: binding} = dynamic, opts) do
8
+ binding =
9
+ Enum.map(binding, fn
10
+ {{:^, _, [as]}, bind} when is_atom(as) -> {as, bind}
11
+ other -> other
12
+ end)
13
+
14
+ dynamic = %{dynamic | binding: binding}
15
+
16
+ joins =
17
+ binding
18
+ |> Enum.drop(1)
19
+ |> Enum.with_index()
20
+ |> Enum.map(&%JoinExpr{ix: &1})
21
+
22
+ aliases =
23
+ for({as, _} when is_atom(as) <- binding, do: as)
24
+ |> Enum.with_index()
25
+ |> Map.new()
26
+
27
+ query = %Ecto.Query{joins: joins, aliases: aliases}
28
+
29
+ {expr, binding, params, subqueries, _, _} =
30
+ Ecto.Query.Builder.Dynamic.fully_expand(query, dynamic)
31
+
32
+ names =
33
+ Enum.map(binding, fn
34
+ {_, {name, _, _}} -> name
35
+ {name, _, _} -> name
36
+ end)
37
+
38
+ query_expr = %{expr: expr, params: params, subqueries: subqueries}
39
+ inspected = Inspect.Ecto.Query.expr(expr, List.to_tuple(names), query_expr)
40
+
41
+ container_doc("dynamic(", [Macro.to_string(binding), inspected], ")", opts, fn str, _ ->
42
+ str
43
+ end)
44
+ end
45
+ end
46
+
47
+ defimpl Inspect, for: Ecto.Query do
48
+ @doc false
49
+ def inspect(query, opts) do
50
+ list =
51
+ Enum.map(to_list(query), fn
52
+ {key, string} ->
53
+ concat(Atom.to_string(key) <> ": ", string)
54
+
55
+ string ->
56
+ string
57
+ end)
58
+
59
+ result = container_doc("#Ecto.Query<", list, ">", opts, fn str, _ -> str end)
60
+
61
+ case query.with_ctes do
62
+ %WithExpr{recursive: recursive, queries: [_ | _] = queries} ->
63
+ with_ctes =
64
+ Enum.map(queries, fn {name, cte_opts, query} ->
65
+ cte =
66
+ case query do
67
+ %Ecto.Query{} -> __MODULE__.inspect(query, opts)
68
+ %Ecto.Query.QueryExpr{} -> expr(query, {})
69
+ end
70
+
71
+ concat([
72
+ "|> with_cte(\"" <> name <> "\", materialized: ",
73
+ inspect(cte_opts[:materialized]),
74
+ ", as: ",
75
+ cte,
76
+ ")"
77
+ ])
78
+ end)
79
+
80
+ result = if recursive, do: glue(result, "\n", "|> recursive_ctes(true)"), else: result
81
+ [result | with_ctes] |> Enum.intersperse(break("\n")) |> concat()
82
+
83
+ _ ->
84
+ result
85
+ end
86
+ end
87
+
88
+ @doc false
89
+ def to_string(query) do
90
+ Enum.map_join(to_list(query), ",\n ", fn
91
+ {key, string} ->
92
+ Atom.to_string(key) <> ": " <> string
93
+
94
+ string ->
95
+ string
96
+ end)
97
+ end
98
+
99
+ defp to_list(query) do
100
+ names =
101
+ query
102
+ |> collect_sources()
103
+ |> generate_letters()
104
+ |> generate_names()
105
+ |> List.to_tuple()
106
+
107
+ from = bound_from(query.from, elem(names, 0), names)
108
+ joins = joins(query.joins, names)
109
+ preloads = preloads(query.preloads)
110
+ assocs = assocs(query.assocs, names)
111
+ windows = windows(query.windows, names)
112
+ combinations = combinations(query.combinations)
113
+ limit = limit(query.limit, names)
114
+
115
+ wheres = bool_exprs(%{and: :where, or: :or_where}, query.wheres, names)
116
+ group_bys = kw_exprs(:group_by, query.group_bys, names)
117
+ havings = bool_exprs(%{and: :having, or: :or_having}, query.havings, names)
118
+ order_bys = kw_exprs(:order_by, query.order_bys, names)
119
+ updates = kw_exprs(:update, query.updates, names)
120
+
121
+ lock = kw_inspect(:lock, query.lock)
122
+ offset = kw_expr(:offset, query.offset, names)
123
+ select = kw_expr(:select, query.select, names)
124
+ distinct = kw_expr(:distinct, query.distinct, names)
125
+
126
+ Enum.concat([
127
+ from,
128
+ joins,
129
+ wheres,
130
+ group_bys,
131
+ havings,
132
+ windows,
133
+ combinations,
134
+ order_bys,
135
+ limit,
136
+ offset,
137
+ lock,
138
+ distinct,
139
+ updates,
140
+ select,
141
+ preloads,
142
+ assocs
143
+ ])
144
+ end
145
+
146
+ defp bound_from(nil, name, _names), do: ["from #{name} in query"]
147
+
148
+ defp bound_from(from, name, names) do
149
+ ["from #{name} in #{inspect_source(from, names)}"] ++ kw_as_and_prefix(from)
150
+ end
151
+
152
+ defp inspect_source(%{source: %Ecto.Query{} = query}, _names), do: "^" <> inspect(query)
153
+
154
+ defp inspect_source(%{source: %Ecto.SubQuery{query: query}}, _names),
155
+ do: "subquery(#{to_string(query)})"
156
+
157
+ defp inspect_source(%{source: {source, nil}}, _names), do: inspect(source)
158
+ defp inspect_source(%{source: {nil, schema}}, _names), do: inspect(schema)
159
+
160
+ defp inspect_source(%{source: {:fragment, _, _} = source} = part, names),
161
+ do: "#{expr(source, names, part)}"
162
+
163
+ defp inspect_source(%{source: {:values, _, [types | _]}}, _names) do
164
+ fields = Keyword.keys(types)
165
+ "values (#{Enum.join(fields, ", ")})"
166
+ end
167
+
168
+ defp inspect_source(%{source: {source, schema}}, _names) do
169
+ inspect(if source == schema.__schema__(:source), do: schema, else: {source, schema})
170
+ end
171
+
172
+ defp joins(joins, names) do
173
+ joins
174
+ |> Enum.with_index()
175
+ |> Enum.flat_map(fn {expr, ix} -> join(expr, elem(names, expr.ix || ix + 1), names) end)
176
+ end
177
+
178
+ defp join(%JoinExpr{qual: qual, assoc: {ix, right}, on: on} = join, name, names) do
179
+ string = "#{name} in assoc(#{elem(names, ix)}, #{inspect(right)})"
180
+ [{join_qual(qual), string}] ++ kw_as_and_prefix(join) ++ maybe_on(on, names)
181
+ end
182
+
183
+ defp join(%JoinExpr{qual: qual, on: on} = join, name, names) do
184
+ string = "#{name} in #{inspect_source(join, names)}"
185
+ [{join_qual(qual), string}] ++ kw_as_and_prefix(join) ++ [on: expr(on, names)]
186
+ end
187
+
188
+ defp maybe_on(%QueryExpr{expr: true}, _names), do: []
189
+ defp maybe_on(%QueryExpr{} = on, names), do: [on: expr(on, names)]
190
+
191
+ defp preloads([]), do: []
192
+ defp preloads(preloads), do: [preload: inspect(preloads)]
193
+
194
+ defp assocs([], _names), do: []
195
+ defp assocs(assocs, names), do: [preload: expr(assocs(assocs), names, %{})]
196
+
197
+ defp assocs(assocs) do
198
+ Enum.map(assocs, fn
199
+ {field, {idx, []}} ->
200
+ {field, {:&, [], [idx]}}
201
+
202
+ {field, {idx, children}} ->
203
+ {field, {{:&, [], [idx]}, assocs(children)}}
204
+ end)
205
+ end
206
+
207
+ defp windows(windows, names) do
208
+ Enum.map(windows, &window(&1, names))
209
+ end
210
+
211
+ defp window({name, %{expr: definition} = part}, names) do
212
+ {:windows, "[#{name}: " <> expr(definition, names, part) <> "]"}
213
+ end
214
+
215
+ defp combinations(combinations) do
216
+ Enum.map(combinations, fn {key, val} -> {key, "(" <> to_string(val) <> ")"} end)
217
+ end
218
+
219
+ defp limit(nil, _names), do: []
220
+
221
+ defp limit(%LimitExpr{with_ties: false} = limit, names) do
222
+ [{:limit, expr(limit, names)}]
223
+ end
224
+
225
+ defp limit(%LimitExpr{with_ties: with_ties} = limit, names) do
226
+ [{:limit, expr(limit, names)}] ++ kw_inspect(:with_ties, with_ties)
227
+ end
228
+
229
+ defp bool_exprs(keys, exprs, names) do
230
+ Enum.map(exprs, fn %{expr: expr, op: op} = part ->
231
+ {Map.fetch!(keys, op), expr(expr, names, part)}
232
+ end)
233
+ end
234
+
235
+ defp kw_exprs(key, exprs, names) do
236
+ Enum.map(exprs, &{key, expr(&1, names)})
237
+ end
238
+
239
+ defp kw_expr(_key, nil, _names), do: []
240
+ defp kw_expr(key, expr, names), do: [{key, expr(expr, names)}]
241
+
242
+ defp kw_inspect(_key, nil), do: []
243
+ defp kw_inspect(key, val), do: [{key, inspect(val)}]
244
+
245
+ defp kw_as_and_prefix(%{as: as, prefix: prefix}) do
246
+ kw_inspect(:as, as) ++ kw_inspect(:prefix, prefix)
247
+ end
248
+
249
+ defp expr(%{expr: expr} = part, names) do
250
+ expr(expr, names, part)
251
+ end
252
+
253
+ @doc false
254
+ def expr(expr, names, part) do
255
+ expr
256
+ |> Macro.traverse(:ok, &{prewalk(&1, names), &2}, &{postwalk(&1, names, part), &2})
257
+ |> elem(0)
258
+ |> macro_to_string()
259
+ end
260
+
261
+ defp macro_to_string(expr), do: Macro.to_string(expr)
262
+
263
+ # Tagged values
264
+ defp prewalk(%Ecto.Query.Tagged{value: value, tag: nil}, _) do
265
+ value
266
+ end
267
+
268
+ defp prewalk(%Ecto.Query.Tagged{value: value, tag: tag}, _) do
269
+ {:type, [], [value, tag]}
270
+ end
271
+
272
+ defp prewalk({{:., dot_meta, [{:&, _, [ix]}, field]}, meta, []}, names) do
273
+ {{:., dot_meta, [binding(names, ix), field]}, meta, []}
274
+ end
275
+
276
+ defp prewalk(node, _) do
277
+ node
278
+ end
279
+
280
+ # Convert variables to proper names
281
+ defp postwalk({:&, _, [ix]}, names, part) do
282
+ binding_to_expr(ix, names, part)
283
+ end
284
+
285
+ # Remove parens from field calls
286
+ defp postwalk({{:., _, [_, _]} = dot, meta, []}, _names, _part) do
287
+ {dot, [no_parens: true] ++ meta, []}
288
+ end
289
+
290
+ # Interpolated unknown value
291
+ defp postwalk({:^, _, [_ix, _len]}, _names, _part) do
292
+ {:^, [], [{:..., [], nil}]}
293
+ end
294
+
295
+ # Interpolated known value
296
+ defp postwalk({:^, _, [ix]}, _, %{params: params}) do
297
+ value =
298
+ case Enum.at(params || [], ix) do
299
+ # Wrap the head in a block so it is not treated as a charlist
300
+ {[head | tail], _type} -> [{:__block__, [], [head]} | tail]
301
+ {value, _type} -> value
302
+ _ -> {:..., [], nil}
303
+ end
304
+
305
+ {:^, [], [value]}
306
+ end
307
+
308
+ # Types need to be converted back to AST for fields
309
+ defp postwalk({:type, meta, [expr, type]}, names, part) do
310
+ {:type, meta, [expr, type_to_expr(type, names, part)]}
311
+ end
312
+
313
+ # For keyword and interpolated fragments use normal escaping
314
+ defp postwalk({:fragment, _, [{_, _} | _] = parts}, _names, _part) do
315
+ {:fragment, [], unmerge_fragments(parts, "", [])}
316
+ end
317
+
318
+ # Subqueries
319
+ defp postwalk({:subquery, i}, _names, %{subqueries: subqueries}) do
320
+ {:subquery, [], [Enum.fetch!(subqueries, i).query]}
321
+ end
322
+
323
+ # Jason
324
+ defp postwalk({:json_extract_path, _, [expr, path]}, _names, _part) do
325
+ Enum.reduce(path, expr, fn element, acc ->
326
+ {{:., [], [Access, :get]}, [], [acc, element]}
327
+ end)
328
+ end
329
+
330
+ defp postwalk(node, _names, _part) do
331
+ node
332
+ end
333
+
334
+ defp binding_to_expr(ix, names, part) do
335
+ case part do
336
+ %{take: %{^ix => {:any, fields}}} when ix == 0 ->
337
+ fields
338
+
339
+ %{take: %{^ix => {tag, fields}}} ->
340
+ {tag, [], [binding(names, ix), fields]}
341
+
342
+ _ ->
343
+ binding(names, ix)
344
+ end
345
+ end
346
+
347
+ defp type_to_expr({ix, type}, names, part) when is_integer(ix) do
348
+ {{:., [], [binding_to_expr(ix, names, part), type]}, [no_parens: true], []}
349
+ end
350
+
351
+ defp type_to_expr({composite, type}, names, part) when is_atom(composite) do
352
+ {composite, type_to_expr(type, names, part)}
353
+ end
354
+
355
+ defp type_to_expr(type, _names, _part) do
356
+ type
357
+ end
358
+
359
+ defp unmerge_fragments([{:raw, s}, {:expr, v} | t], frag, args) do
360
+ unmerge_fragments(t, frag <> s <> "?", [v | args])
361
+ end
362
+
363
+ defp unmerge_fragments([{:raw, s}], frag, args) do
364
+ [frag <> s | Enum.reverse(args)]
365
+ end
366
+
367
+ defp join_qual(:inner), do: :join
368
+ defp join_qual(:inner_lateral), do: :inner_lateral_join
369
+ defp join_qual(:left), do: :left_join
370
+ defp join_qual(:left_lateral), do: :left_lateral_join
371
+ defp join_qual(:right), do: :right_join
372
+ defp join_qual(:full), do: :full_join
373
+ defp join_qual(:cross), do: :cross_join
374
+ defp join_qual(:cross_lateral), do: :cross_lateral_join
375
+
376
+ defp collect_sources(%{from: nil, joins: joins}) do
377
+ ["query" | join_sources(joins)]
378
+ end
379
+
380
+ defp collect_sources(%{from: %{source: source}, joins: joins}) do
381
+ [from_sources(source) | join_sources(joins)]
382
+ end
383
+
384
+ defp from_sources(%Ecto.SubQuery{query: query}), do: from_sources(query.from.source)
385
+ defp from_sources({source, schema}), do: schema || source
386
+ defp from_sources(nil), do: "query"
387
+ defp from_sources({:fragment, _, _}), do: "fragment"
388
+ defp from_sources({:values, _, _}), do: "values"
389
+
390
+ defp join_sources(joins) do
391
+ joins
392
+ |> Enum.sort_by(& &1.ix)
393
+ |> Enum.map(fn
394
+ %JoinExpr{assoc: {_var, assoc}} ->
395
+ assoc
396
+
397
+ %JoinExpr{source: {:fragment, _, _}} ->
398
+ "fragment"
399
+
400
+ %JoinExpr{source: %Ecto.Query{from: from}} ->
401
+ from_sources(from.source)
402
+
403
+ %JoinExpr{source: source} ->
404
+ from_sources(source)
405
+ end)
406
+ end
407
+
408
+ defp generate_letters(sources) do
409
+ Enum.map(sources, fn source ->
410
+ source
411
+ |> Kernel.to_string()
412
+ |> normalize_source()
413
+ |> String.first()
414
+ |> String.downcase()
415
+ end)
416
+ end
417
+
418
+ defp generate_names(letters) do
419
+ {names, _} = Enum.map_reduce(letters, 0, &{:"#{&1}#{&2}", &2 + 1})
420
+ names
421
+ end
422
+
423
+ defp binding(names, pos) do
424
+ try do
425
+ {elem(names, pos), [], nil}
426
+ rescue
427
+ ArgumentError -> {:"unknown_binding_#{pos}!", [], nil}
428
+ end
429
+ end
430
+
431
+ defp normalize_source("Elixir." <> _ = source),
432
+ do: source |> Module.split() |> List.last()
433
+
434
+ defp normalize_source(source),
435
+ do: source
436
+ end
deps/ecto/lib/ecto/query/planner.ex ADDED
@@ -0,0 +1,2699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Query.Planner do
2
+ # Normalizes a query and its parameters.
3
+ @moduledoc false
4
+
5
+ alias Ecto.Query.{
6
+ BooleanExpr,
7
+ ByExpr,
8
+ DynamicExpr,
9
+ FromExpr,
10
+ JoinExpr,
11
+ QueryExpr,
12
+ SelectExpr,
13
+ LimitExpr
14
+ }
15
+
16
+ if map_size(%Ecto.Query{}) != 21 do
17
+ raise "Ecto.Query match out of date in builder"
18
+ end
19
+
20
+ @parent_as __MODULE__
21
+ @aggs ~w(count avg min max sum row_number rank dense_rank percent_rank cume_dist ntile lag lead first_value last_value nth_value)a
22
+
23
+ @doc """
24
+ Converts a query to a list of joins.
25
+
26
+ The from is moved as last join with the where conditions as its "on"
27
+ in order to keep proper binding order.
28
+ """
29
+ def query_to_joins(qual, source, %{wheres: wheres, joins: joins}, position) do
30
+ on = %QueryExpr{file: __ENV__.file, line: __ENV__.line, expr: true, params: []}
31
+
32
+ on =
33
+ Enum.reduce(wheres, on, fn %BooleanExpr{op: op, expr: expr, params: params}, acc ->
34
+ merge_expr_and_params(op, acc, expr, params)
35
+ end)
36
+
37
+ join = %JoinExpr{qual: qual, source: source, file: __ENV__.file, line: __ENV__.line, on: on}
38
+ last = length(joins) + position
39
+
40
+ mapping = fn
41
+ 0 -> last
42
+ ix -> ix + position - 1
43
+ end
44
+
45
+ for {%{on: on} = join, ix} <- Enum.with_index(joins ++ [join]) do
46
+ %{join | on: rewrite_sources(on, mapping), ix: ix + position}
47
+ end
48
+ end
49
+
50
+ defp merge_expr_and_params(
51
+ op,
52
+ %QueryExpr{expr: left_expr, params: left_params} = struct,
53
+ right_expr,
54
+ right_params
55
+ ) do
56
+ right_expr = Ecto.Query.Builder.bump_interpolations(right_expr, left_params)
57
+ %{struct | expr: merge_expr(op, left_expr, right_expr), params: left_params ++ right_params}
58
+ end
59
+
60
+ defp merge_expr(_op, left, true), do: left
61
+ defp merge_expr(_op, true, right), do: right
62
+ defp merge_expr(op, left, right), do: {op, [], [left, right]}
63
+
64
+ @doc """
65
+ Rewrites the given query expression sources using the given mapping.
66
+ """
67
+ def rewrite_sources(%{expr: expr, params: params} = part, mapping) do
68
+ expr =
69
+ Macro.prewalk(expr, fn
70
+ %Ecto.Query.Tagged{type: type, tag: tag} = tagged ->
71
+ %{tagged | type: rewrite_type(type, mapping), tag: rewrite_type(tag, mapping)}
72
+
73
+ {:&, meta, [ix]} ->
74
+ {:&, meta, [mapping.(ix)]}
75
+
76
+ other ->
77
+ other
78
+ end)
79
+
80
+ params =
81
+ Enum.map(params, fn
82
+ {val, type} ->
83
+ {val, rewrite_type(type, mapping)}
84
+
85
+ val ->
86
+ val
87
+ end)
88
+
89
+ %{part | expr: expr, params: params}
90
+ end
91
+
92
+ defp rewrite_type({composite, {ix, field}}, mapping) when is_integer(ix) do
93
+ {composite, {mapping.(ix), field}}
94
+ end
95
+
96
+ defp rewrite_type({ix, field}, mapping) when is_integer(ix) do
97
+ {mapping.(ix), field}
98
+ end
99
+
100
+ defp rewrite_type(other, _mapping) do
101
+ other
102
+ end
103
+
104
+ @doc """
105
+ Define the query cache table.
106
+ """
107
+ def new_query_cache(atom_name) do
108
+ :ets.new(atom_name || __MODULE__, [:set, :public, read_concurrency: true])
109
+ end
110
+
111
+ @doc """
112
+ Plans the query for execution.
113
+
114
+ Planning happens in multiple steps:
115
+
116
+ 1. First the query is planned by retrieving
117
+ its cache key, casting and merging parameters
118
+
119
+ 2. Then a cache lookup is done, if the query is
120
+ cached, we are done
121
+
122
+ 3. If there is no cache, we need to actually
123
+ normalize and validate the query, asking the
124
+ adapter to prepare it
125
+
126
+ 4. The query is sent to the adapter to be generated
127
+
128
+ ## Cache
129
+
130
+ All entries in the query, except the preload and sources
131
+ field, should be part of the cache key.
132
+
133
+ The cache value is the compiled query by the adapter
134
+ along-side the select expression.
135
+ """
136
+ def query(query, operation, cache, adapter, counter) do
137
+ {query, params, key} = plan(query, operation, adapter)
138
+ {cast_params, dump_params} = Enum.unzip(params)
139
+ query_with_cache(key, query, operation, cache, adapter, counter, cast_params, dump_params)
140
+ end
141
+
142
+ defp query_with_cache(key, query, operation, cache, adapter, counter, cast_params, dump_params) do
143
+ case query_lookup(key, query, operation, cache, adapter, counter) do
144
+ {_, select, prepared} ->
145
+ {build_meta(query, select), {:nocache, prepared}, cast_params, dump_params}
146
+
147
+ {_key, :cached, select, cached} ->
148
+ update = &cache_update(cache, key, &1)
149
+ reset = &cache_reset(cache, key, &1)
150
+ {build_meta(query, select), {:cached, update, reset, cached}, cast_params, dump_params}
151
+
152
+ {_key, :cache, select, prepared} ->
153
+ update = &cache_update(cache, key, &1)
154
+ {build_meta(query, select), {:cache, update, prepared}, cast_params, dump_params}
155
+ end
156
+ end
157
+
158
+ defp query_lookup(:nocache, query, operation, _cache, adapter, counter) do
159
+ query_without_cache(query, operation, adapter, counter)
160
+ end
161
+
162
+ defp query_lookup(key, query, operation, cache, adapter, counter) do
163
+ case :ets.lookup(cache, key) do
164
+ [term] -> term
165
+ [] -> query_prepare(query, operation, adapter, counter, cache, key)
166
+ end
167
+ end
168
+
169
+ defp query_prepare(query, operation, adapter, counter, cache, key) do
170
+ case query_without_cache(query, operation, adapter, counter) do
171
+ {:cache, select, prepared} ->
172
+ cache_insert(cache, key, {key, :cache, select, prepared})
173
+
174
+ {:nocache, _, _} = nocache ->
175
+ nocache
176
+ end
177
+ end
178
+
179
+ defp cache_insert(cache, key, elem) do
180
+ case :ets.insert_new(cache, elem) do
181
+ true ->
182
+ elem
183
+
184
+ false ->
185
+ [elem] = :ets.lookup(cache, key)
186
+ elem
187
+ end
188
+ end
189
+
190
+ defp cache_update(cache, key, cached) do
191
+ _ = :ets.update_element(cache, key, [{2, :cached}, {4, cached}])
192
+ :ok
193
+ end
194
+
195
+ defp cache_reset(cache, key, prepared) do
196
+ _ = :ets.update_element(cache, key, [{2, :cache}, {4, prepared}])
197
+ :ok
198
+ end
199
+
200
+ defp query_without_cache(query, operation, adapter, counter) do
201
+ {query, select} = normalize(query, operation, adapter, counter)
202
+ {cache, prepared} = adapter.prepare(operation, query)
203
+ {cache, select, prepared}
204
+ end
205
+
206
+ defp build_meta(%{sources: sources, preloads: preloads}, select) do
207
+ %{select: select, preloads: preloads, sources: sources}
208
+ end
209
+
210
+ @doc """
211
+ Prepares the query for cache.
212
+
213
+ This means all the parameters from query expressions are
214
+ merged into a single value and their entries are pruned
215
+ from the query.
216
+
217
+ This function is called by the backend before invoking
218
+ any cache mechanism.
219
+ """
220
+ @spec plan(Ecto.Query.t(), atom(), module, map()) ::
221
+ {planned_query :: Ecto.Query.t(), parameters :: list(), cache_key :: any()}
222
+ def plan(query, operation, adapter, cte_names \\ %{}) do
223
+ {query, cte_names} = plan_ctes(query, adapter, cte_names)
224
+ query = plan_sources(query, adapter, cte_names)
225
+ plan_subquery = &plan_subquery(&1, query, nil, adapter, false, cte_names)
226
+
227
+ query
228
+ |> plan_assocs()
229
+ |> plan_combinations(adapter, cte_names)
230
+ |> plan_expr_subqueries(:wheres, plan_subquery)
231
+ |> plan_expr_subqueries(:havings, plan_subquery)
232
+ |> plan_expr_subqueries(:order_bys, plan_subquery)
233
+ |> plan_expr_subqueries(:group_bys, plan_subquery)
234
+ |> plan_expr_subquery(:distinct, plan_subquery)
235
+ |> plan_expr_subquery(:select, plan_subquery)
236
+ |> plan_windows(plan_subquery)
237
+ |> plan_cache(operation, adapter)
238
+ rescue
239
+ e ->
240
+ # Reraise errors so we ignore the planner inner stacktrace
241
+ filter_and_reraise(e, __STACKTRACE__)
242
+ end
243
+
244
+ @doc """
245
+ Prepare all sources, by traversing and expanding from, joins, subqueries.
246
+ """
247
+ def plan_sources(query, adapter, cte_names) do
248
+ {from, source} = plan_from(query, adapter, cte_names)
249
+
250
+ # Set up the initial source so we can refer
251
+ # to the parent in subqueries in joins
252
+ query = %{query | sources: {source}}
253
+
254
+ {joins, sources, tail_sources} =
255
+ plan_joins(query, [source], length(query.joins), adapter, cte_names)
256
+
257
+ %{
258
+ query
259
+ | from: from,
260
+ joins: joins |> Enum.reverse(),
261
+ sources: (tail_sources ++ sources) |> Enum.reverse() |> List.to_tuple()
262
+ }
263
+ end
264
+
265
+ defp plan_from(%{from: nil} = query, _adapter, _cte_names) do
266
+ error!(query, "query must have a from expression")
267
+ end
268
+
269
+ defp plan_from(
270
+ %{from: %{source: {kind, _, _}}, preloads: preloads, assocs: assocs} = query,
271
+ _adapter,
272
+ _cte_names
273
+ )
274
+ when kind in [:fragment, :values] and (assocs != [] or preloads != []) do
275
+ error!(query, "cannot preload associations with a #{kind} source")
276
+ end
277
+
278
+ defp plan_from(%{from: from} = query, adapter, cte_names) do
279
+ plan_source(query, from, adapter, cte_names)
280
+ end
281
+
282
+ defp plan_source(
283
+ query,
284
+ %{source: %Ecto.SubQuery{} = subquery, prefix: prefix} = expr,
285
+ adapter,
286
+ cte_names
287
+ ) do
288
+ subquery = plan_subquery(subquery, query, prefix, adapter, true, cte_names)
289
+ {%{expr | source: subquery}, subquery}
290
+ end
291
+
292
+ defp plan_source(query, %{source: {nil, schema}} = expr, _adapter, cte_names)
293
+ when is_atom(schema) and schema != nil do
294
+ source = schema.__schema__(:source)
295
+ source_prefix = plan_source_schema_prefix(expr, schema)
296
+
297
+ prefix =
298
+ case cte_names do
299
+ %{^source => _} -> source_prefix
300
+ _ -> source_prefix || query.prefix
301
+ end
302
+
303
+ {%{expr | source: {source, schema}}, {source, schema, prefix}}
304
+ end
305
+
306
+ defp plan_source(query, %{source: {source, schema}, prefix: prefix} = expr, _adapter, cte_names)
307
+ when is_binary(source) and is_atom(schema) do
308
+ prefix =
309
+ case cte_names do
310
+ %{^source => _} -> prefix
311
+ _ -> prefix || query.prefix
312
+ end
313
+
314
+ {expr, {source, schema, prefix}}
315
+ end
316
+
317
+ defp plan_source(
318
+ _query,
319
+ %{source: {kind, _, _} = source, prefix: nil} = expr,
320
+ _adapter,
321
+ _cte_names
322
+ )
323
+ when kind in [:fragment, :values],
324
+ do: {expr, source}
325
+
326
+ defp plan_source(query, %{source: {kind, _, _}, prefix: prefix} = expr, _adapter, _cte_names)
327
+ when kind in [:fragment, :values],
328
+ do: error!(query, expr, "cannot set prefix: #{inspect(prefix)} option for #{kind} sources")
329
+
330
+ defp plan_subquery(subquery, query, prefix, adapter, source?, cte_names) do
331
+ %{query: inner_query} = subquery
332
+
333
+ inner_query = %{
334
+ inner_query
335
+ | prefix: prefix || subquery.query.prefix || query.prefix,
336
+ aliases: Map.put(inner_query.aliases, @parent_as, query)
337
+ }
338
+
339
+ {inner_query, params, key} = plan(inner_query, :all, adapter, cte_names)
340
+ assert_no_subquery_assocs!(inner_query)
341
+
342
+ {inner_query, select} =
343
+ inner_query
344
+ |> ensure_select(true)
345
+ |> normalize_subquery_select(adapter, source?)
346
+
347
+ {_, inner_query} = pop_in(inner_query.aliases[@parent_as])
348
+ %{subquery | query: inner_query, params: params, cache: key, select: select}
349
+ rescue
350
+ e -> raise Ecto.SubQueryError, query: query, exception: e
351
+ end
352
+
353
+ # The prefix for form are computed upfront, but not for joins
354
+ defp plan_source_schema_prefix(%FromExpr{prefix: prefix}, _schema),
355
+ do: prefix
356
+
357
+ defp plan_source_schema_prefix(%JoinExpr{prefix: prefix}, schema),
358
+ do: prefix || schema.__schema__(:prefix)
359
+
360
+ defp assert_no_subquery_assocs!(%{assocs: assocs, preloads: preloads} = query)
361
+ when assocs != [] or preloads != [] do
362
+ error!(query, "cannot preload associations in subquery")
363
+ end
364
+
365
+ defp assert_no_subquery_assocs!(query) do
366
+ query
367
+ end
368
+
369
+ defp normalize_subquery_select(query, adapter, source?) do
370
+ {schema_or_source, expr, %{select: select} = query} =
371
+ rewrite_subquery_select_expr(query, source?)
372
+
373
+ {expr, _} = prewalk(expr, :select, query, select, 0, adapter)
374
+
375
+ {{:map, types}, fields, _from} =
376
+ collect_fields(expr, [], :none, query, select.take, true, %{})
377
+
378
+ # types must take into account selected_as/2 aliases so that the correct fields are
379
+ # referenced when the outer query selects the entire subquery
380
+ types = normalize_subquery_types(types, Enum.reverse(fields), query.select.aliases, [])
381
+ {query, subquery_source(schema_or_source, types)}
382
+ end
383
+
384
+ defp normalize_subquery_types(types, _fields, select_aliases, _acc)
385
+ when select_aliases == %{} do
386
+ types
387
+ end
388
+
389
+ defp normalize_subquery_types([], [], _aliases, acc) do
390
+ Enum.reverse(acc)
391
+ end
392
+
393
+ defp normalize_subquery_types(
394
+ [{alias, _} = type | types],
395
+ [{alias, _} | fields],
396
+ select_aliases,
397
+ acc
398
+ ) do
399
+ normalize_subquery_types(types, fields, select_aliases, [type | acc])
400
+ end
401
+
402
+ defp normalize_subquery_types(
403
+ [{source_alias, type_value} | types],
404
+ [field | fields],
405
+ select_aliases,
406
+ acc
407
+ ) do
408
+ if Map.has_key?(select_aliases, source_alias) do
409
+ raise ArgumentError, """
410
+ the alias, #{inspect(source_alias)}, provided to `selected_as/2` conflicts
411
+ with the subquery's automatic aliasing.
412
+
413
+ For example, the following query is not allowed because the alias `:y`
414
+ given to `selected_as/2` is also used by the subquery to automatically
415
+ alias `s.y`:
416
+
417
+ s = from(s in Schema, select: %{x: selected_as(s.x, :y), y: s.y})
418
+ from s in subquery(s)
419
+ """
420
+ end
421
+
422
+ type =
423
+ case field do
424
+ {select_alias, _} -> {select_alias, type_value}
425
+ _ -> {source_alias, type_value}
426
+ end
427
+
428
+ normalize_subquery_types(types, fields, select_aliases, [type | acc])
429
+ end
430
+
431
+ defp subquery_source(nil, types), do: {:map, types}
432
+ defp subquery_source(name, types) when is_atom(name), do: {:struct, name, types}
433
+
434
+ defp subquery_source({:source, schema, prefix, types}, only) do
435
+ types =
436
+ Enum.map(only, fn {field, {:value, type}} -> {field, Keyword.get(types, field, type)} end)
437
+
438
+ {:source, schema, prefix, types}
439
+ end
440
+
441
+ defp rewrite_subquery_select_expr(%{select: select} = query, source?) do
442
+ %{expr: expr, take: take} = select
443
+
444
+ case subquery_select(expr, take, query) do
445
+ {schema_or_source, fields} ->
446
+ expr = {:%{}, [], fields}
447
+ {schema_or_source, expr, put_in(query.select.expr, expr)}
448
+
449
+ :error when source? ->
450
+ error!(
451
+ query,
452
+ "subquery/cte must select a source (t), a field (t.field) or a map, got: `#{Macro.to_string(expr)}`"
453
+ )
454
+
455
+ :error ->
456
+ expr = {:%{}, [], [result: expr]}
457
+ {nil, expr, put_in(query.select.expr, expr)}
458
+ end
459
+ end
460
+
461
+ defp subquery_select({:merge, _, [left, right]}, take, query) do
462
+ {left_struct, left_fields} = subquery_select(left, take, query)
463
+ {right_struct, right_fields} = subquery_select(right, take, query)
464
+ {left_struct || right_struct, Keyword.merge(left_fields, right_fields)}
465
+ end
466
+
467
+ defp subquery_select({:%, _, [name, map]}, take, query) do
468
+ {_, fields} = subquery_select(map, take, query)
469
+ {name, fields}
470
+ end
471
+
472
+ defp subquery_select({:%{}, _, [{:|, _, [{:&, [], [ix]}, pairs]}]} = expr, take, query) do
473
+ assert_subquery_fields!(query, expr, pairs)
474
+ drop = Map.new(pairs, fn {key, _} -> {key, nil} end)
475
+ {source, _} = source_take!(:select, query, take, ix, ix, drop)
476
+
477
+ # In case of map updates, we need to remove duplicated fields
478
+ # at query time because we use the field names as aliases and
479
+ # duplicate aliases will lead to invalid queries.
480
+ kept_keys = subquery_source_fields(source) -- Keyword.keys(pairs)
481
+ {keep_source_or_struct(source), subquery_fields(kept_keys, ix) ++ pairs}
482
+ end
483
+
484
+ defp subquery_select({:%{}, _, pairs} = expr, _take, query) do
485
+ assert_subquery_fields!(query, expr, pairs)
486
+ {nil, pairs}
487
+ end
488
+
489
+ defp subquery_select({:&, _, [ix]}, take, query) do
490
+ {source, _} = source_take!(:select, query, take, ix, ix, %{})
491
+ fields = subquery_source_fields(source)
492
+ {keep_source_or_struct(source), subquery_fields(fields, ix)}
493
+ end
494
+
495
+ defp subquery_select({{:., _, [{:&, _, [_]}, field]}, _, []} = expr, _take, _query) do
496
+ {nil, [{field, expr}]}
497
+ end
498
+
499
+ defp subquery_select(_expr, _take, _query) do
500
+ :error
501
+ end
502
+
503
+ defp subquery_fields(fields, ix) do
504
+ for field <- fields do
505
+ {field, {{:., [], [{:&, [], [ix]}, field]}, [], []}}
506
+ end
507
+ end
508
+
509
+ defp keep_source_or_struct({:source, _, _, _} = source), do: source
510
+ defp keep_source_or_struct({:struct, name, _}), do: name
511
+ defp keep_source_or_struct(_), do: nil
512
+
513
+ defp subquery_source_fields({:source, _, _, types}), do: Keyword.keys(types)
514
+ defp subquery_source_fields({:struct, _, types}), do: Keyword.keys(types)
515
+ defp subquery_source_fields({:map, types}), do: Keyword.keys(types)
516
+
517
+ defp subquery_type_for({:source, _, _, fields}, field), do: Keyword.fetch(fields, field)
518
+
519
+ defp subquery_type_for({:struct, _name, types}, field),
520
+ do: subquery_type_for_value(types, field)
521
+
522
+ defp subquery_type_for({:map, types}, field), do: subquery_type_for_value(types, field)
523
+
524
+ defp subquery_type_for_value(types, field) do
525
+ case Keyword.fetch(types, field) do
526
+ {:ok, {:value, type}} -> {:ok, type}
527
+ {:ok, _} -> {:ok, :any}
528
+ :error -> :error
529
+ end
530
+ end
531
+
532
+ defp assert_subquery_fields!(query, expr, pairs) do
533
+ Enum.each(pairs, fn
534
+ {key, _} when not is_atom(key) ->
535
+ error!(
536
+ query,
537
+ "only atom keys are allowed when selecting a map in subquery, got: `#{Macro.to_string(expr)}`"
538
+ )
539
+
540
+ {key, value} ->
541
+ if valid_subquery_value?(value) do
542
+ {key, value}
543
+ else
544
+ error!(
545
+ query,
546
+ "atoms, structs, maps, lists, tuples and sources are not allowed as map values in subquery, got: `#{Macro.to_string(expr)}`"
547
+ )
548
+ end
549
+ end)
550
+ end
551
+
552
+ defp valid_subquery_value?({_, _}), do: false
553
+ defp valid_subquery_value?(args) when is_list(args), do: false
554
+
555
+ defp valid_subquery_value?({container, _, args})
556
+ when container in [:{}, :%{}, :&, :%] and is_list(args),
557
+ do: false
558
+
559
+ defp valid_subquery_value?(nil), do: true
560
+ defp valid_subquery_value?(arg) when is_atom(arg), do: is_boolean(arg)
561
+ defp valid_subquery_value?(_), do: true
562
+
563
+ defp plan_joins(query, sources, offset, adapter, cte_names) do
564
+ plan_joins(query.joins, query, [], sources, [], 1, offset, adapter, cte_names)
565
+ end
566
+
567
+ defp plan_joins(
568
+ [%JoinExpr{assoc: {ix, assoc}, qual: qual, on: on, prefix: prefix} = join | t],
569
+ query,
570
+ joins,
571
+ sources,
572
+ tail_sources,
573
+ counter,
574
+ offset,
575
+ adapter,
576
+ cte_names
577
+ ) do
578
+ source = fetch_source!(sources, ix)
579
+ schema = schema_for_association_join!(query, join, source)
580
+ refl = schema.__schema__(:association, assoc)
581
+
582
+ unless refl do
583
+ error!(query, join, "could not find association `#{assoc}` on schema #{inspect(schema)}")
584
+ end
585
+
586
+ # If we have the following join:
587
+ #
588
+ # from p in Post,
589
+ # join: p in assoc(p, :comments)
590
+ #
591
+ # The callback below will return a query that contains only
592
+ # joins in a way it starts with the Post and ends in the
593
+ # Comment.
594
+ #
595
+ # This means we need to rewrite the joins below to properly
596
+ # shift the &... identifier in a way that:
597
+ #
598
+ # &0 -> becomes assoc ix
599
+ # &LAST_JOIN -> becomes counter
600
+ #
601
+ # All values in the middle should be shifted by offset,
602
+ # all values after join are already correct.
603
+ child = refl.__struct__.joins_query(refl)
604
+
605
+ # Rewrite prefixes:
606
+ # 1. the child query has the parent query prefix
607
+ # (note the child query should NEVER have a prefix)
608
+ # 2. from and joins can have their prefixes explicitly
609
+ # overwritten by the join prefix
610
+ child = rewrite_prefix(child, query.prefix)
611
+ child = update_in(child.from, &rewrite_prefix(&1, prefix))
612
+ child = update_in(child.joins, &Enum.map(&1, fn join -> rewrite_prefix(join, prefix) end))
613
+
614
+ last_ix = length(child.joins)
615
+ source_ix = counter
616
+
617
+ {_, child_from_source} = plan_source(child, child.from, adapter, cte_names)
618
+
619
+ {child_joins, child_sources, child_tail} =
620
+ plan_joins(child, [child_from_source], offset + last_ix - 1, adapter, cte_names)
621
+
622
+ # Rewrite joins indexes as mentioned above
623
+ child_joins = Enum.map(child_joins, &rewrite_join(&1, qual, ix, last_ix, source_ix, offset))
624
+
625
+ # Drop the last resource which is the association owner (it is reversed)
626
+ child_sources = Enum.drop(child_sources, -1)
627
+
628
+ [current_source | child_sources] = child_sources
629
+ child_sources = child_tail ++ child_sources
630
+
631
+ plan_joins(
632
+ t,
633
+ query,
634
+ attach_on(child_joins, on) ++ joins,
635
+ [current_source | sources],
636
+ child_sources ++ tail_sources,
637
+ counter + 1,
638
+ offset + length(child_sources),
639
+ adapter,
640
+ cte_names
641
+ )
642
+ end
643
+
644
+ defp plan_joins(
645
+ [
646
+ %JoinExpr{source: %Ecto.Query{} = join_query, qual: qual, on: on, prefix: prefix} =
647
+ join
648
+ | t
649
+ ],
650
+ query,
651
+ joins,
652
+ sources,
653
+ tail_sources,
654
+ counter,
655
+ offset,
656
+ adapter,
657
+ cte_names
658
+ ) do
659
+ case join_query do
660
+ %{
661
+ order_bys: [],
662
+ limit: nil,
663
+ offset: nil,
664
+ group_bys: [],
665
+ joins: [],
666
+ havings: [],
667
+ preloads: [],
668
+ assocs: [],
669
+ distinct: nil,
670
+ lock: nil
671
+ } ->
672
+ join_query = rewrite_prefix(join_query, query.prefix)
673
+ from = rewrite_prefix(join_query.from, prefix)
674
+ {from, source} = plan_source(join_query, from, adapter, cte_names)
675
+ [join] = attach_on(query_to_joins(qual, from.source, join_query, counter), on)
676
+
677
+ plan_joins(
678
+ t,
679
+ query,
680
+ [join | joins],
681
+ [source | sources],
682
+ tail_sources,
683
+ counter + 1,
684
+ offset,
685
+ adapter,
686
+ cte_names
687
+ )
688
+
689
+ _ ->
690
+ error!(query, join, """
691
+ invalid query was interpolated in a join.
692
+ If you want to pass a query to a join, you must either:
693
+
694
+ 1. Make sure the query only has `where` conditions (which will be converted to ON clauses)
695
+ 2. Or wrap the query in a subquery by calling subquery(query)
696
+ """)
697
+ end
698
+ end
699
+
700
+ defp plan_joins(
701
+ [%JoinExpr{} = join | t],
702
+ query,
703
+ joins,
704
+ sources,
705
+ tail_sources,
706
+ counter,
707
+ offset,
708
+ adapter,
709
+ cte_names
710
+ ) do
711
+ {join, source} = plan_source(query, %{join | ix: counter}, adapter, cte_names)
712
+
713
+ plan_joins(
714
+ t,
715
+ query,
716
+ [join | joins],
717
+ [source | sources],
718
+ tail_sources,
719
+ counter + 1,
720
+ offset,
721
+ adapter,
722
+ cte_names
723
+ )
724
+ end
725
+
726
+ defp plan_joins(
727
+ [],
728
+ _query,
729
+ joins,
730
+ sources,
731
+ tail_sources,
732
+ _counter,
733
+ _offset,
734
+ _adapter,
735
+ _cte_names
736
+ ) do
737
+ {joins, sources, tail_sources}
738
+ end
739
+
740
+ defp attach_on([%{on: on} = h | t], %{expr: expr, params: params}) do
741
+ [%{h | on: merge_expr_and_params(:and, on, expr, params)} | t]
742
+ end
743
+
744
+ defp rewrite_prefix(expr, nil), do: expr
745
+ defp rewrite_prefix(%{prefix: nil} = expr, prefix), do: %{expr | prefix: prefix}
746
+ defp rewrite_prefix(expr, _prefix), do: expr
747
+
748
+ defp rewrite_join(%{on: on, ix: join_ix} = join, qual, ix, last_ix, source_ix, inc_ix) do
749
+ expr =
750
+ Macro.prewalk(on.expr, fn
751
+ {:&, meta, [join_ix]} ->
752
+ {:&, meta, [rewrite_ix(join_ix, ix, last_ix, source_ix, inc_ix)]}
753
+
754
+ expr = %Ecto.Query.Tagged{type: {type_ix, type}} when is_integer(type_ix) ->
755
+ %{expr | type: {rewrite_ix(type_ix, ix, last_ix, source_ix, inc_ix), type}}
756
+
757
+ other ->
758
+ other
759
+ end)
760
+
761
+ params = Enum.map(on.params, &rewrite_param_ix(&1, ix, last_ix, source_ix, inc_ix))
762
+
763
+ %{
764
+ join
765
+ | on: %{on | expr: expr, params: params},
766
+ qual: qual,
767
+ ix: rewrite_ix(join_ix, ix, last_ix, source_ix, inc_ix)
768
+ }
769
+ end
770
+
771
+ # We need to replace the source by the one from the assoc
772
+ defp rewrite_ix(0, ix, _last_ix, _source_ix, _inc_x), do: ix
773
+
774
+ # The last entry will have the current source index
775
+ defp rewrite_ix(last_ix, _ix, last_ix, source_ix, _inc_x), do: source_ix
776
+
777
+ # All above last are already correct
778
+ defp rewrite_ix(join_ix, _ix, last_ix, _source_ix, _inc_ix) when join_ix > last_ix, do: join_ix
779
+
780
+ # All others need to be incremented by the offset sources
781
+ defp rewrite_ix(join_ix, _ix, _last_ix, _source_ix, inc_ix), do: join_ix + inc_ix
782
+
783
+ defp rewrite_param_ix({value, {upper, {type_ix, field}}}, ix, last_ix, source_ix, inc_ix)
784
+ when is_integer(type_ix) do
785
+ {value, {upper, {rewrite_ix(type_ix, ix, last_ix, source_ix, inc_ix), field}}}
786
+ end
787
+
788
+ defp rewrite_param_ix({value, {type_ix, field}}, ix, last_ix, source_ix, inc_ix)
789
+ when is_integer(type_ix) do
790
+ {value, {rewrite_ix(type_ix, ix, last_ix, source_ix, inc_ix), field}}
791
+ end
792
+
793
+ defp rewrite_param_ix(param, _, _, _, _), do: param
794
+
795
+ defp fetch_source!(sources, ix) when is_integer(ix) do
796
+ case Enum.reverse(sources) |> Enum.fetch(ix) do
797
+ {:ok, source} ->
798
+ source
799
+
800
+ :error ->
801
+ raise ArgumentError, "could not find a source with index `#{ix}` in `#{inspect(sources)}"
802
+ end
803
+ end
804
+
805
+ defp fetch_source!(_, ix) do
806
+ raise ArgumentError,
807
+ "invalid binding index: `#{inspect(ix)}` (check if you're binding using a valid :as atom)"
808
+ end
809
+
810
+ defp schema_for_association_join!(query, join, source) do
811
+ case source do
812
+ {:fragment, _, _} ->
813
+ error!(query, join, "cannot perform association joins on fragment sources")
814
+
815
+ {source, nil, _} ->
816
+ error!(
817
+ query,
818
+ join,
819
+ "cannot perform association join on #{inspect(source)} " <>
820
+ "because it does not have a schema"
821
+ )
822
+
823
+ {_, schema, _} ->
824
+ schema
825
+
826
+ %Ecto.SubQuery{select: {:source, {_, schema}, _, _}} ->
827
+ schema
828
+
829
+ %Ecto.SubQuery{select: {:struct, schema, _}} ->
830
+ schema
831
+
832
+ %Ecto.SubQuery{} ->
833
+ error!(
834
+ query,
835
+ join,
836
+ "can only perform association joins on subqueries " <>
837
+ "that return a source with schema in select"
838
+ )
839
+
840
+ _ ->
841
+ error!(query, join, "can only perform association joins on sources with a schema")
842
+ end
843
+ end
844
+
845
+ # An optimized version of plan subqueries that only modifies the query when necessary.
846
+ defp plan_expr_subqueries(query, key, fun) do
847
+ query
848
+ |> Map.fetch!(key)
849
+ |> plan_expr_subqueries([], query, key, fun)
850
+ end
851
+
852
+ defp plan_expr_subqueries([%{subqueries: []} = head | tail], acc, query, key, fun) do
853
+ plan_expr_subqueries(tail, [head | acc], query, key, fun)
854
+ end
855
+
856
+ defp plan_expr_subqueries([head | tail], acc, query, key, fun) do
857
+ exprs =
858
+ Enum.reduce([head | tail], acc, fn
859
+ %{subqueries: []} = expr, acc ->
860
+ [expr | acc]
861
+
862
+ %{subqueries: subqueries} = expr, acc ->
863
+ [%{expr | subqueries: Enum.map(subqueries, fun)} | acc]
864
+ end)
865
+
866
+ %{query | key => Enum.reverse(exprs)}
867
+ end
868
+
869
+ defp plan_expr_subqueries([], _acc, query, _key, _fun) do
870
+ query
871
+ end
872
+
873
+ defp plan_expr_subquery(query, key, fun) do
874
+ with %{^key => %{subqueries: [_ | _] = subqueries} = expr} <- query do
875
+ %{query | key => %{expr | subqueries: Enum.map(subqueries, fun)}}
876
+ end
877
+ end
878
+
879
+ defp plan_windows(%{windows: []} = query, _fun), do: query
880
+
881
+ defp plan_windows(query, fun) do
882
+ windows =
883
+ Enum.map(query.windows, fn
884
+ {key, %{subqueries: []} = window} ->
885
+ {key, window}
886
+
887
+ {key, %{subqueries: subqueries} = window} ->
888
+ {key, %{window | subqueries: Enum.map(subqueries, fun)}}
889
+ end)
890
+
891
+ %{query | windows: windows}
892
+ end
893
+
894
+ @doc """
895
+ Prepare the parameters by merging and casting them according to sources.
896
+ """
897
+ def plan_cache(query, operation, adapter) do
898
+ {query, params, cache} = traverse_cache(query, operation, {[], []}, adapter)
899
+ {query, Enum.reverse(params), cache}
900
+ end
901
+
902
+ defp traverse_cache(query, operation, cache_params, adapter) do
903
+ fun = &{&3, merge_cache(&1, &2, &3, &4, operation, adapter)}
904
+ {query, {cache, params}} = traverse_exprs(query, operation, cache_params, fun)
905
+ {query, params, finalize_cache(query, operation, cache)}
906
+ end
907
+
908
+ defp merge_cache(:from, query, from, {cache, params}, _operation, adapter) do
909
+ {key, params} = source_cache(from, params)
910
+ {params, source_cacheable?} = cast_and_merge_params(:from, query, from, params, adapter)
911
+ {merge_cache({:from, key, from.hints}, cache, source_cacheable? and key != :nocache), params}
912
+ end
913
+
914
+ defp merge_cache(kind, query, expr, {cache, params}, _operation, adapter)
915
+ when kind in ~w(select distinct limit offset)a do
916
+ if expr do
917
+ {params, cacheable?} = cast_and_merge_params(kind, query, expr, params, adapter)
918
+ {merge_cache({kind, expr_to_cache(expr)}, cache, cacheable?), params}
919
+ else
920
+ {cache, params}
921
+ end
922
+ end
923
+
924
+ defp merge_cache(kind, query, exprs, {cache, params}, _operation, adapter)
925
+ when kind in ~w(where update group_by having order_by)a do
926
+ {expr_cache, {params, cacheable?}} =
927
+ Enum.map_reduce(exprs, {params, true}, fn expr, {params, cacheable?} ->
928
+ {params, current_cacheable?} = cast_and_merge_params(kind, query, expr, params, adapter)
929
+ {expr_to_cache(expr), {params, cacheable? and current_cacheable?}}
930
+ end)
931
+
932
+ case expr_cache do
933
+ [] -> {cache, params}
934
+ _ -> {merge_cache({kind, expr_cache}, cache, cacheable?), params}
935
+ end
936
+ end
937
+
938
+ defp merge_cache(:join, query, exprs, {cache, params}, _operation, adapter) do
939
+ {expr_cache, {params, cacheable?}} =
940
+ Enum.map_reduce(exprs, {params, true}, fn
941
+ %JoinExpr{on: on, qual: qual, hints: hints} = join, {params, cacheable?} ->
942
+ {key, params} = source_cache(join, params)
943
+ {params, join_cacheable?} = cast_and_merge_params(:join, query, join, params, adapter)
944
+ {params, on_cacheable?} = cast_and_merge_params(:join, query, on, params, adapter)
945
+
946
+ {{qual, key, on.expr, hints},
947
+ {params, cacheable? and join_cacheable? and on_cacheable? and key != :nocache}}
948
+ end)
949
+
950
+ case expr_cache do
951
+ [] -> {cache, params}
952
+ _ -> {merge_cache({:join, expr_cache}, cache, cacheable?), params}
953
+ end
954
+ end
955
+
956
+ defp merge_cache(:windows, query, exprs, {cache, params}, _operation, adapter) do
957
+ {expr_cache, {params, cacheable?}} =
958
+ Enum.map_reduce(exprs, {params, true}, fn {key, expr}, {params, cacheable?} ->
959
+ {params, current_cacheable?} =
960
+ cast_and_merge_params(:windows, query, expr, params, adapter)
961
+
962
+ {{key, expr_to_cache(expr)}, {params, cacheable? and current_cacheable?}}
963
+ end)
964
+
965
+ case expr_cache do
966
+ [] -> {cache, params}
967
+ _ -> {merge_cache({:windows, expr_cache}, cache, cacheable?), params}
968
+ end
969
+ end
970
+
971
+ defp merge_cache(:combination, _query, combinations, cache_and_params, operation, adapter) do
972
+ # In here we add each combination as its own entry in the cache key.
973
+ # We could group them to avoid multiple keys, but since they are uncommon, we keep it simple.
974
+ Enum.reduce(combinations, cache_and_params, fn {modifier, query}, {cache, params} ->
975
+ {_, params, inner_cache} = traverse_cache(query, operation, {[], params}, adapter)
976
+ {merge_cache({modifier, inner_cache}, cache, inner_cache != :nocache), params}
977
+ end)
978
+ end
979
+
980
+ defp merge_cache(:with_cte, _query, nil, cache_and_params, _operation, _adapter) do
981
+ cache_and_params
982
+ end
983
+
984
+ defp merge_cache(:with_cte, query, with_expr, cache_and_params, _operation, adapter) do
985
+ %{queries: queries, recursive: recursive} = with_expr
986
+ key = if recursive, do: :recursive_cte, else: :non_recursive_cte
987
+
988
+ # In here we add each cte as its own entry in the cache key.
989
+ # We could group them to avoid multiple keys, but since they are uncommon, we keep it simple.
990
+ Enum.reduce(queries, cache_and_params, fn
991
+ {name, opts, %Ecto.Query{} = query}, {cache, params} ->
992
+ {_, params, inner_cache} = traverse_cache(query, :all, {[], params}, adapter)
993
+
994
+ {merge_cache(
995
+ {key, name, opts[:materialized], opts[:operation], inner_cache},
996
+ cache,
997
+ inner_cache != :nocache
998
+ ), params}
999
+
1000
+ {name, opts, %Ecto.Query.QueryExpr{} = query_expr}, {cache, params} ->
1001
+ {params, cacheable?} =
1002
+ cast_and_merge_params(:with_cte, query, query_expr, params, adapter)
1003
+
1004
+ {merge_cache(
1005
+ {key, name, opts[:materialized], opts[:operation], expr_to_cache(query_expr)},
1006
+ cache,
1007
+ cacheable?
1008
+ ), params}
1009
+ end)
1010
+ end
1011
+
1012
+ defp expr_to_cache(%QueryExpr{expr: expr}), do: expr
1013
+
1014
+ defp expr_to_cache(%SelectExpr{expr: expr, subqueries: []}), do: expr
1015
+
1016
+ defp expr_to_cache(%SelectExpr{expr: expr, subqueries: subqueries}) do
1017
+ {expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)}
1018
+ end
1019
+
1020
+ defp expr_to_cache(%ByExpr{expr: expr, subqueries: []}), do: expr
1021
+
1022
+ defp expr_to_cache(%ByExpr{expr: expr, subqueries: subqueries}) do
1023
+ {expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)}
1024
+ end
1025
+
1026
+ defp expr_to_cache(%BooleanExpr{op: op, expr: expr, subqueries: []}), do: {op, expr}
1027
+
1028
+ defp expr_to_cache(%BooleanExpr{op: op, expr: expr, subqueries: subqueries}) do
1029
+ # Alternate implementation could be replace {:subquery, i} expression in expr.
1030
+ # Current strategy appends [{:subquery, i, cache}], where cache is the cache key for this subquery.
1031
+ {op, expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)}
1032
+ end
1033
+
1034
+ defp expr_to_cache(%LimitExpr{expr: expr, with_ties: with_ties}), do: {with_ties, expr}
1035
+
1036
+ @spec cast_and_merge_params(atom, Ecto.Query.t(), any, list, module) ::
1037
+ {params :: list, cacheable? :: boolean}
1038
+ defp cast_and_merge_params(kind, query, expr, params, adapter) do
1039
+ Enum.reduce(expr.params, {params, true}, fn
1040
+ {:subquery, i}, {acc, cacheable?} ->
1041
+ # This is the place holder to intersperse subquery parameters.
1042
+ %Ecto.SubQuery{params: subparams, cache: cache} = Enum.fetch!(expr.subqueries, i)
1043
+ {Enum.reverse(subparams, acc), cacheable? and cache != :nocache}
1044
+
1045
+ {v, type}, {acc, cacheable?} ->
1046
+ case cast_param(kind, query, expr, v, type, adapter) do
1047
+ {cast_v, {:in, dump_v}} -> {split_variadic_params(cast_v, dump_v, acc), false}
1048
+ {cast_v, {:splice, dump_v}} -> {split_variadic_params(cast_v, dump_v, acc), cacheable?}
1049
+ cast_v_and_dump_v -> {[cast_v_and_dump_v | acc], cacheable?}
1050
+ end
1051
+ end)
1052
+ end
1053
+
1054
+ defp split_variadic_params(cast_v, dump_v, acc) do
1055
+ Enum.zip(cast_v, dump_v) |> Enum.reverse(acc)
1056
+ end
1057
+
1058
+ defp merge_cache(_left, _right, false), do: :nocache
1059
+ defp merge_cache(_left, :nocache, true), do: :nocache
1060
+ defp merge_cache(left, right, true), do: [left | right]
1061
+
1062
+ defp finalize_cache(_query, _operation, :nocache) do
1063
+ :nocache
1064
+ end
1065
+
1066
+ defp finalize_cache(query, operation, cache) do
1067
+ %{assocs: assocs, prefix: prefix, lock: lock, select: select, aliases: aliases} = query
1068
+ aliases = Map.delete(aliases, @parent_as)
1069
+
1070
+ cache =
1071
+ case select do
1072
+ %{take: take} when take != %{} ->
1073
+ [take: take] ++ cache
1074
+
1075
+ _ ->
1076
+ cache
1077
+ end
1078
+
1079
+ cache =
1080
+ cache
1081
+ |> prepend_if(assocs != [], assocs: assocs)
1082
+ |> prepend_if(prefix != nil, prefix: prefix)
1083
+ |> prepend_if(lock != nil, lock: lock)
1084
+ |> prepend_if(aliases != %{}, aliases: aliases)
1085
+
1086
+ [operation | cache]
1087
+ end
1088
+
1089
+ defp prepend_if(cache, true, prepend), do: prepend ++ cache
1090
+ defp prepend_if(cache, false, _prepend), do: cache
1091
+
1092
+ defp source_cache(%{source: {_, nil} = source, prefix: prefix}, params),
1093
+ do: {{source, prefix}, params}
1094
+
1095
+ defp source_cache(%{source: {bin, schema}, prefix: prefix}, params),
1096
+ do: {{bin, schema, schema.__schema__(:hash), prefix}, params}
1097
+
1098
+ defp source_cache(%{source: {:fragment, _, _} = source, prefix: prefix}, params),
1099
+ do: {{source, prefix}, params}
1100
+
1101
+ defp source_cache(%{source: {:values, _, _}}, params),
1102
+ do: {:nocache, params}
1103
+
1104
+ defp source_cache(%{source: %Ecto.SubQuery{params: inner, cache: key}}, params),
1105
+ do: {key, Enum.reverse(inner, params)}
1106
+
1107
+ defp cast_param(_kind, query, expr, %DynamicExpr{}, _type, _value) do
1108
+ error!(
1109
+ query,
1110
+ expr,
1111
+ "invalid dynamic expression",
1112
+ "dynamic expressions can only be interpolated at the top level of where, having, group_by, order_by, select, update or a join's on"
1113
+ )
1114
+ end
1115
+
1116
+ defp cast_param(_kind, query, expr, [{key, _} | _], _type, _value) when is_atom(key) do
1117
+ error!(
1118
+ query,
1119
+ expr,
1120
+ "invalid keyword list",
1121
+ "keyword lists are only allowed at the top level of where, having, distinct, order_by, update or a join's on"
1122
+ )
1123
+ end
1124
+
1125
+ defp cast_param(_kind, query, expr, %x{}, {:in, _type}, _value)
1126
+ when x in [Ecto.Query, Ecto.SubQuery] do
1127
+ error!(
1128
+ query,
1129
+ expr,
1130
+ "an #{inspect(x)} struct is not supported as right-side value of `in` operator",
1131
+ "Did you mean to write `expr in subquery(query)` instead?"
1132
+ )
1133
+ end
1134
+
1135
+ defp cast_param(kind, query, expr, v, type, adapter) do
1136
+ type = field_type!(kind, query, expr, type)
1137
+
1138
+ with {:ok, type} <- normalize_param(kind, type, v),
1139
+ {:ok, cast_v} <- cast_param(kind, type, v),
1140
+ {:ok, dump_v} <- dump_param(adapter, type, cast_v) do
1141
+ {cast_v, dump_v}
1142
+ else
1143
+ {:error, message} ->
1144
+ e =
1145
+ Ecto.QueryError.exception(
1146
+ message: message,
1147
+ query: query,
1148
+ file: expr.file,
1149
+ line: expr.line
1150
+ )
1151
+
1152
+ raise Ecto.Query.CastError, value: v, type: type, message: Exception.message(e)
1153
+ end
1154
+ end
1155
+
1156
+ @doc """
1157
+ Prepare association fields found in the query.
1158
+ """
1159
+ def plan_assocs(query) do
1160
+ plan_assocs(query, 0, query.assocs)
1161
+ query
1162
+ end
1163
+
1164
+ defp plan_assocs(_query, _ix, []), do: :ok
1165
+
1166
+ defp plan_assocs(query, ix, assocs) do
1167
+ # We validate the schema exists when preparing joins.
1168
+ parent_schema =
1169
+ case get_preload_source!(query, ix) do
1170
+ {_, schema, _} ->
1171
+ schema
1172
+
1173
+ %Ecto.SubQuery{select: {:source, {_, schema}, _, _}} ->
1174
+ schema
1175
+ end
1176
+
1177
+ Enum.each(assocs, fn {assoc, {child_ix, child_assocs}} ->
1178
+ refl = parent_schema.__schema__(:association, assoc)
1179
+
1180
+ unless refl do
1181
+ error!(
1182
+ query,
1183
+ "field `#{inspect(parent_schema)}.#{assoc}` " <>
1184
+ "in preload is not an association"
1185
+ )
1186
+ end
1187
+
1188
+ case find_source_expr(query, child_ix) do
1189
+ %JoinExpr{qual: qual} when qual in [:inner, :left, :inner_lateral, :left_lateral] ->
1190
+ :ok
1191
+
1192
+ %JoinExpr{qual: qual} ->
1193
+ error!(
1194
+ query,
1195
+ "association `#{inspect(parent_schema)}.#{assoc}` " <>
1196
+ "in preload requires an inner, left or lateral join, got #{qual} join"
1197
+ )
1198
+
1199
+ _ ->
1200
+ :ok
1201
+ end
1202
+
1203
+ plan_assocs(query, child_ix, child_assocs)
1204
+ end)
1205
+ end
1206
+
1207
+ defp plan_combinations(query, adapter, cte_names) do
1208
+ combinations =
1209
+ Enum.map(query.combinations, fn {type, combination_query} ->
1210
+ {prepared_query, _params, _key} =
1211
+ combination_query |> attach_prefix(query) |> plan(:all, adapter, cte_names)
1212
+
1213
+ prepared_query = prepared_query |> ensure_select(true)
1214
+ {type, prepared_query}
1215
+ end)
1216
+
1217
+ %{query | combinations: combinations}
1218
+ end
1219
+
1220
+ defp plan_ctes(%Ecto.Query{with_ctes: nil} = query, _adapter, cte_names), do: {query, cte_names}
1221
+
1222
+ defp plan_ctes(%Ecto.Query{with_ctes: %{queries: queries}} = query, adapter, cte_names) do
1223
+ {queries, cte_names} =
1224
+ Enum.map_reduce(queries, cte_names, fn
1225
+ {name, opts, %Ecto.Query{} = cte_query}, cte_names ->
1226
+ cte_names = Map.put(cte_names, name, [])
1227
+
1228
+ {planned_query, _params, _key} =
1229
+ cte_query |> attach_prefix(query) |> plan(:all, adapter, cte_names)
1230
+
1231
+ planned_query = planned_query |> ensure_select(true)
1232
+ {{name, opts, planned_query}, cte_names}
1233
+
1234
+ {name, opts, other}, cte_names ->
1235
+ {{name, opts, other}, cte_names}
1236
+ end)
1237
+
1238
+ {put_in(query.with_ctes.queries, queries), cte_names}
1239
+ end
1240
+
1241
+ defp find_source_expr(query, 0) do
1242
+ query.from
1243
+ end
1244
+
1245
+ defp find_source_expr(query, ix) do
1246
+ Enum.find(query.joins, &(&1.ix == ix))
1247
+ end
1248
+
1249
+ @doc """
1250
+ Used for customizing the query returning result.
1251
+ """
1252
+ def ensure_select(%{select: select} = query, _fields) when select != nil do
1253
+ query
1254
+ end
1255
+
1256
+ def ensure_select(%{select: nil}, []) do
1257
+ raise ArgumentError, ":returning expects at least one field to be given, got an empty list"
1258
+ end
1259
+
1260
+ def ensure_select(%{select: nil} = query, fields) when is_list(fields) do
1261
+ %{
1262
+ query
1263
+ | select: %SelectExpr{
1264
+ expr: {:&, [], [0]},
1265
+ take: %{0 => {:any, fields}},
1266
+ line: __ENV__.line,
1267
+ file: __ENV__.file
1268
+ }
1269
+ }
1270
+ end
1271
+
1272
+ def ensure_select(%{select: nil, from: %{source: {_, nil}}} = query, true) do
1273
+ error!(query, "queries that do not have a schema need to explicitly pass a :select clause")
1274
+ end
1275
+
1276
+ def ensure_select(%{select: nil, from: %{source: {:fragment, _, _}}} = query, true) do
1277
+ error!(query, "queries from a fragment need to explicitly pass a :select clause")
1278
+ end
1279
+
1280
+ def ensure_select(%{select: nil} = query, true) do
1281
+ %{query | select: %SelectExpr{expr: {:&, [], [0]}, line: __ENV__.line, file: __ENV__.file}}
1282
+ end
1283
+
1284
+ def ensure_select(%{select: nil} = query, false) do
1285
+ query
1286
+ end
1287
+
1288
+ @doc """
1289
+ Normalizes and validates the query.
1290
+
1291
+ After the query was planned and there is no cache
1292
+ entry, we need to update its interpolations and check
1293
+ its fields and associations exist and are valid.
1294
+ """
1295
+ def normalize(query, operation, adapter, counter) do
1296
+ query
1297
+ |> normalize_query(operation, adapter, counter)
1298
+ |> elem(0)
1299
+ |> normalize_select(keep_literals?(operation, query))
1300
+ rescue
1301
+ e ->
1302
+ # Reraise errors so we ignore the planner inner stacktrace
1303
+ filter_and_reraise(e, __STACKTRACE__)
1304
+ end
1305
+
1306
+ defp keep_literals?(:insert_all, _), do: true
1307
+ defp keep_literals?(_, %{combinations: combinations}), do: combinations != []
1308
+
1309
+ defp normalize_query(query, operation, adapter, counter) do
1310
+ case operation do
1311
+ :all ->
1312
+ assert_no_update!(query, operation)
1313
+
1314
+ :insert_all ->
1315
+ assert_no_update!(query, operation)
1316
+
1317
+ :update_all ->
1318
+ assert_update!(query, operation)
1319
+ assert_only_filter_expressions!(query, operation)
1320
+
1321
+ :delete_all ->
1322
+ assert_no_update!(query, operation)
1323
+ assert_only_filter_expressions!(query, operation)
1324
+ end
1325
+
1326
+ traverse_exprs(
1327
+ query,
1328
+ operation,
1329
+ counter,
1330
+ &validate_and_increment(&1, &2, &3, &4, operation, adapter)
1331
+ )
1332
+ end
1333
+
1334
+ defp validate_and_increment(:from, query, %{source: %Ecto.SubQuery{}}, _counter, kind, _adapter)
1335
+ when kind not in ~w(all insert_all)a do
1336
+ error!(query, "`#{kind}` does not allow subqueries in `from`")
1337
+ end
1338
+
1339
+ defp validate_and_increment(:from, query, %{source: source} = expr, counter, _kind, adapter) do
1340
+ {source, acc} = prewalk_source(source, :from, query, expr, counter, adapter)
1341
+ {%{expr | source: source}, acc}
1342
+ end
1343
+
1344
+ defp validate_and_increment(kind, query, expr, counter, _operation, adapter)
1345
+ when kind in ~w(select distinct limit offset)a do
1346
+ if expr do
1347
+ prewalk(kind, query, expr, counter, adapter)
1348
+ else
1349
+ {nil, counter}
1350
+ end
1351
+ end
1352
+
1353
+ defp validate_and_increment(kind, query, exprs, counter, _operation, adapter)
1354
+ when kind in ~w(where group_by having order_by update)a do
1355
+ {exprs, counter} =
1356
+ Enum.reduce(exprs, {[], counter}, fn
1357
+ %{expr: []}, {list, acc} ->
1358
+ {list, acc}
1359
+
1360
+ expr, {list, acc} ->
1361
+ {expr, acc} = prewalk(kind, query, expr, acc, adapter)
1362
+ {[expr | list], acc}
1363
+ end)
1364
+
1365
+ {Enum.reverse(exprs), counter}
1366
+ end
1367
+
1368
+ defp validate_and_increment(:with_cte, _query, nil, counter, _operation, _adapter) do
1369
+ {nil, counter}
1370
+ end
1371
+
1372
+ defp validate_and_increment(:with_cte, query, with_expr, counter, _operation, adapter) do
1373
+ fun = &validate_and_increment(&1, &2, &3, &4, :all, adapter)
1374
+
1375
+ {queries, counter} =
1376
+ Enum.reduce(with_expr.queries, {[], counter}, fn
1377
+ {name, opts, %Ecto.Query{} = inner_query}, {queries, counter} ->
1378
+ inner_query = put_in(inner_query.aliases[@parent_as], query)
1379
+
1380
+ # We don't want to use normalize_subquery_select because we are
1381
+ # going to prepare the whole query ourselves next.
1382
+ {_, _, inner_query} = rewrite_subquery_select_expr(inner_query, true)
1383
+ {inner_query, counter} = traverse_exprs(inner_query, opts.operation, counter, fun)
1384
+
1385
+ # Now compute the fields as keyword lists so we emit AS in Ecto query.
1386
+ %{select: %{expr: expr, take: take, aliases: aliases}} = inner_query
1387
+
1388
+ {{:map, types}, fields, _from} =
1389
+ collect_fields(expr, [], :none, inner_query, take, true, %{})
1390
+
1391
+ fields = cte_fields(Keyword.keys(types), Enum.reverse(fields), aliases)
1392
+ inner_query = put_in(inner_query.select.fields, fields)
1393
+ {_, inner_query} = pop_in(inner_query.aliases[@parent_as])
1394
+
1395
+ {[{name, opts, inner_query} | queries], counter}
1396
+
1397
+ {name, opts, %QueryExpr{expr: {:fragment, _, _} = fragment} = query_expr},
1398
+ {queries, counter} ->
1399
+ {fragment, counter} =
1400
+ prewalk_source(fragment, :with_cte, query, with_expr, counter, adapter)
1401
+
1402
+ query_expr = %{query_expr | expr: fragment}
1403
+ {[{name, opts, query_expr} | queries], counter}
1404
+ end)
1405
+
1406
+ {%{with_expr | queries: Enum.reverse(queries)}, counter}
1407
+ end
1408
+
1409
+ defp validate_and_increment(:join, query, exprs, counter, _operation, adapter) do
1410
+ Enum.map_reduce(exprs, counter, fn join, acc ->
1411
+ {source, acc} = prewalk_source(join.source, :join, query, join, acc, adapter)
1412
+ {on, acc} = prewalk(:join, query, join.on, acc, adapter)
1413
+ {%{join | on: on, source: source, params: nil}, acc}
1414
+ end)
1415
+ end
1416
+
1417
+ defp validate_and_increment(:windows, query, exprs, counter, _operation, adapter) do
1418
+ {exprs, counter} =
1419
+ Enum.reduce(exprs, {[], counter}, fn {name, expr}, {list, acc} ->
1420
+ {expr, acc} = prewalk(:windows, query, expr, acc, adapter)
1421
+ {[{name, expr} | list], acc}
1422
+ end)
1423
+
1424
+ {Enum.reverse(exprs), counter}
1425
+ end
1426
+
1427
+ defp validate_and_increment(:combination, query, combinations, counter, operation, adapter) do
1428
+ fun = &validate_and_increment(&1, &2, &3, &4, operation, adapter)
1429
+ parent_aliases = query.aliases[@parent_as]
1430
+
1431
+ {combinations, counter} =
1432
+ Enum.reduce(combinations, {[], counter}, fn {type, combination_query},
1433
+ {combinations, counter} ->
1434
+ combination_query = put_in(combination_query.aliases[@parent_as], parent_aliases)
1435
+ {combination_query, counter} = traverse_exprs(combination_query, operation, counter, fun)
1436
+ {combination_query, _} = combination_query |> normalize_select(true)
1437
+ {_, combination_query} = pop_in(combination_query.aliases[@parent_as])
1438
+ {[{type, combination_query} | combinations], counter}
1439
+ end)
1440
+
1441
+ {Enum.reverse(combinations), counter}
1442
+ end
1443
+
1444
+ defp validate_json_path!([path_field | rest], field, {:parameterized, {Ecto.Embedded, embed}}) do
1445
+ case embed do
1446
+ %{related: related, cardinality: :one} ->
1447
+ unless Enum.any?(related.__schema__(:fields), &(Atom.to_string(&1) == path_field)) do
1448
+ raise "field `#{path_field}` does not exist in #{inspect(related)}"
1449
+ end
1450
+
1451
+ type = related.__schema__(:type, String.to_atom(path_field))
1452
+ validate_json_path!(rest, path_field, type)
1453
+
1454
+ %{related: _, cardinality: :many} ->
1455
+ unless is_integer(path_field) do
1456
+ raise "cannot use `#{path_field}` to refer to an item in `embeds_many`"
1457
+ end
1458
+
1459
+ updated_embed = %{embed | cardinality: :one}
1460
+ validate_json_path!(rest, path_field, {:parameterized, {Ecto.Embedded, updated_embed}})
1461
+
1462
+ other ->
1463
+ raise "expected field `#{field}` to be of type embed, got: `#{inspect(other)}`"
1464
+ end
1465
+ end
1466
+
1467
+ defp validate_json_path!([_path_field | _rest] = path, field, other_type) do
1468
+ case Ecto.Type.type(other_type) do
1469
+ :any ->
1470
+ :ok
1471
+
1472
+ :map ->
1473
+ :ok
1474
+
1475
+ {:map, _} ->
1476
+ :ok
1477
+
1478
+ {:parameterized, {type, _}} ->
1479
+ validate_json_path!(path, field, type)
1480
+
1481
+ type ->
1482
+ raise "expected field `#{field}` to be an embed or a map, got: `#{inspect(type)}`"
1483
+ end
1484
+ end
1485
+
1486
+ defp validate_json_path!([], _field, _type) do
1487
+ :ok
1488
+ end
1489
+
1490
+ defp prewalk_source({:fragment, meta, fragments}, kind, query, expr, acc, adapter) do
1491
+ {fragments, acc} = prewalk(fragments, kind, query, expr, acc, adapter)
1492
+ {{:fragment, meta, fragments}, acc}
1493
+ end
1494
+
1495
+ defp prewalk_source({:values, meta, [types, num_rows]}, _kind, _query, _expr, acc, _adapter) do
1496
+ length = num_rows * length(types)
1497
+ # Adapters will use the schema types to cast the values
1498
+ schema_types = Enum.map(types, fn {field, type} -> {field, Ecto.Type.type(type)} end)
1499
+ {{:values, meta, [schema_types, acc, num_rows]}, acc + length}
1500
+ end
1501
+
1502
+ defp prewalk_source(
1503
+ %Ecto.SubQuery{query: inner_query} = subquery,
1504
+ kind,
1505
+ query,
1506
+ _expr,
1507
+ counter,
1508
+ adapter
1509
+ ) do
1510
+ try do
1511
+ inner_query = put_in(inner_query.aliases[@parent_as], query)
1512
+ {inner_query, counter} = normalize_query(inner_query, :all, adapter, counter)
1513
+ {inner_query, _} = normalize_select(inner_query, true)
1514
+ {_, inner_query} = pop_in(inner_query.aliases[@parent_as])
1515
+
1516
+ # If the subquery comes from a select, we are not really interested on the fields
1517
+ inner_query =
1518
+ if kind == :where do
1519
+ inner_query
1520
+ else
1521
+ update_in(inner_query.select.fields, fn fields ->
1522
+ # fields are aliased by the subquery source, unless
1523
+ # already aliased by selected_as/2
1524
+ subquery.select
1525
+ |> subquery_source_fields()
1526
+ |> Enum.zip(fields)
1527
+ |> Enum.map(fn
1528
+ {_source_alias, {select_alias, field}} -> {select_alias, field}
1529
+ {source_alias, field} -> {source_alias, field}
1530
+ end)
1531
+ end)
1532
+ end
1533
+
1534
+ {%{subquery | query: inner_query}, counter}
1535
+ rescue
1536
+ e -> raise Ecto.SubQueryError, query: query, exception: e
1537
+ end
1538
+ end
1539
+
1540
+ defp prewalk_source(source, _kind, _query, _expr, acc, _adapter) do
1541
+ {source, acc}
1542
+ end
1543
+
1544
+ defp prewalk(:update, query, expr, counter, adapter) do
1545
+ source = get_source!(:update, query, 0)
1546
+
1547
+ {inner, acc} =
1548
+ Enum.map_reduce(expr.expr, counter, fn {op, kw}, counter ->
1549
+ {kw, acc} =
1550
+ Enum.map_reduce(kw, counter, fn {field, value}, counter ->
1551
+ {value, acc} = prewalk(value, :update, query, expr, counter, adapter)
1552
+ {{field_source(source, field), value}, acc}
1553
+ end)
1554
+
1555
+ {{op, kw}, acc}
1556
+ end)
1557
+
1558
+ {%{expr | expr: inner, params: nil}, acc}
1559
+ end
1560
+
1561
+ defp prewalk(kind, query, expr, counter, adapter) do
1562
+ {inner, acc} = prewalk(expr.expr, kind, query, expr, counter, adapter)
1563
+ {%{expr | expr: inner, params: nil}, acc}
1564
+ end
1565
+
1566
+ defp prewalk({:subquery, i}, kind, query, expr, acc, adapter) do
1567
+ prewalk_source(Enum.fetch!(expr.subqueries, i), kind, query, expr, acc, adapter)
1568
+ end
1569
+
1570
+ defp prewalk({:in, in_meta, [left, {:^, meta, [param]}]}, kind, query, expr, acc, adapter) do
1571
+ {left, acc} = prewalk(left, kind, query, expr, acc, adapter)
1572
+ {right, acc} = validate_in(meta, expr, param, acc, adapter)
1573
+ {{:in, in_meta, [left, right]}, acc}
1574
+ end
1575
+
1576
+ defp prewalk({:in, in_meta, [left, {:subquery, _} = right]}, kind, query, expr, acc, adapter) do
1577
+ {left, acc} = prewalk(left, kind, query, expr, acc, adapter)
1578
+ {right, acc} = prewalk(right, kind, query, expr, acc, adapter)
1579
+
1580
+ case right.query.select.fields do
1581
+ [_] ->
1582
+ :ok
1583
+
1584
+ _ ->
1585
+ error!(
1586
+ query,
1587
+ "subquery must return a single field in order to be used on the right-side of `in`"
1588
+ )
1589
+ end
1590
+
1591
+ {{:in, in_meta, [left, right]}, acc}
1592
+ end
1593
+
1594
+ defp prewalk({quantifier, meta, [{:subquery, _} = subquery]}, kind, query, expr, acc, adapter)
1595
+ when quantifier in [:exists, :any, :all] do
1596
+ {subquery, acc} = prewalk(subquery, kind, query, expr, acc, adapter)
1597
+
1598
+ case {quantifier, subquery.query.select.fields} do
1599
+ {:exists, _} ->
1600
+ :ok
1601
+
1602
+ {_, [_]} ->
1603
+ :ok
1604
+
1605
+ _ ->
1606
+ error!(
1607
+ query,
1608
+ "subquery must return a single field in order to be used with #{quantifier}"
1609
+ )
1610
+ end
1611
+
1612
+ {{quantifier, meta, [subquery]}, acc}
1613
+ end
1614
+
1615
+ defp prewalk(
1616
+ {:splice, splice_meta, [{:^, meta, [_]}, length]},
1617
+ _kind,
1618
+ _query,
1619
+ _expr,
1620
+ acc,
1621
+ _adapter
1622
+ ) do
1623
+ param = {:^, meta, [acc, length]}
1624
+ {{:splice, splice_meta, [param]}, acc + length}
1625
+ end
1626
+
1627
+ defp prewalk({{:., dot_meta, [left, field]}, meta, []}, kind, query, expr, acc, _adapter) do
1628
+ {ix, ix_expr, ix_query} = get_ix!(left, kind, query)
1629
+ extra = if kind == :select, do: [type: type!(kind, ix_query, expr, ix, field)], else: []
1630
+ field = field_source(get_source!(kind, ix_query, ix), field)
1631
+ {{{:., extra ++ dot_meta, [ix_expr, field]}, meta, []}, acc}
1632
+ end
1633
+
1634
+ defp prewalk({:^, meta, [ix]}, _kind, _query, _expr, acc, _adapter) when is_integer(ix) do
1635
+ {{:^, meta, [acc]}, acc + 1}
1636
+ end
1637
+
1638
+ defp prewalk({:type, _, [arg, type]}, kind, query, expr, acc, adapter) do
1639
+ {arg, acc} = prewalk(arg, kind, query, expr, acc, adapter)
1640
+ type = field_type!(kind, query, expr, type, true)
1641
+ {%Ecto.Query.Tagged{value: arg, tag: type, type: Ecto.Type.type(type)}, acc}
1642
+ end
1643
+
1644
+ defp prewalk({:json_extract_path, meta, [json_field, path]}, kind, query, expr, acc, _adapter) do
1645
+ {{:., dot_meta, [left, field]}, expr_meta, []} = json_field
1646
+ {ix, ix_expr, ix_query} = get_ix!(left, kind, query)
1647
+
1648
+ type = type!(kind, ix_query, expr, ix, field)
1649
+ validate_json_path!(path, field, type)
1650
+
1651
+ field_source = kind |> get_source!(ix_query, ix) |> field_source(field)
1652
+
1653
+ json_field = {{:., dot_meta, [ix_expr, field_source]}, expr_meta, []}
1654
+ {{:json_extract_path, meta, [json_field, path]}, acc}
1655
+ end
1656
+
1657
+ defp prewalk({:selected_as, [], [name]}, _kind, query, _expr, acc, _adapter) do
1658
+ name = selected_as!(query.select.aliases, name)
1659
+ {{:selected_as, [], [name]}, acc}
1660
+ end
1661
+
1662
+ defp prewalk(%Ecto.Query.Tagged{value: v, type: type} = tagged, kind, query, expr, acc, adapter) do
1663
+ if Ecto.Type.base?(type) do
1664
+ {tagged, acc}
1665
+ else
1666
+ type = field_type!(kind, query, expr, type)
1667
+
1668
+ with {:ok, type} <- normalize_param(kind, type, v),
1669
+ {:ok, value} <- dump_param(adapter, type, v) do
1670
+ # We cannot encode binary/uuid in queries because they would emit
1671
+ # invalid queries with binary parts in them. In theory, we could
1672
+ # wrap them in Ecto.Query.Tagged, but a tagged UUID would most
1673
+ # likely wrap its string representation, not its binary one.
1674
+ # So it is best to be consistent and not support query-dumping of
1675
+ # non-base types.
1676
+ if is_binary(value) and Ecto.Type.type(type) in [:binary_id, :binary, :uuid] do
1677
+ error =
1678
+ "cannot encode value `#{inspect(v)}` of type `#{inspect(type)}` within a query, please interpolate (using ^) instead"
1679
+
1680
+ error!(query, expr, error)
1681
+ else
1682
+ {value, acc}
1683
+ end
1684
+ else
1685
+ {:error, error} ->
1686
+ error =
1687
+ error <>
1688
+ ". Or the value is incompatible or it must be " <>
1689
+ "interpolated (using ^) so it may be cast accordingly"
1690
+
1691
+ error!(query, expr, error)
1692
+ end
1693
+ end
1694
+ end
1695
+
1696
+ defp prewalk({left, right}, kind, query, expr, acc, adapter) do
1697
+ {left, acc} = prewalk(left, kind, query, expr, acc, adapter)
1698
+ {right, acc} = prewalk(right, kind, query, expr, acc, adapter)
1699
+ {{left, right}, acc}
1700
+ end
1701
+
1702
+ defp prewalk({left, meta, args}, kind, query, expr, acc, adapter) do
1703
+ {left, acc} = prewalk(left, kind, query, expr, acc, adapter)
1704
+ {args, acc} = prewalk(args, kind, query, expr, acc, adapter)
1705
+ {{left, meta, args}, acc}
1706
+ end
1707
+
1708
+ defp prewalk(list, kind, query, expr, acc, adapter) when is_list(list) do
1709
+ Enum.map_reduce(list, acc, &prewalk(&1, kind, query, expr, &2, adapter))
1710
+ end
1711
+
1712
+ defp prewalk(other, _kind, _query, _expr, acc, _adapter) do
1713
+ {other, acc}
1714
+ end
1715
+
1716
+ defp selected_as!(select_aliases, name) do
1717
+ case select_aliases do
1718
+ %{^name => _} ->
1719
+ name
1720
+
1721
+ _ ->
1722
+ raise ArgumentError,
1723
+ "invalid alias: `#{inspect(name)}`. Use `selected_as/2` to define aliases in the outer most `select` expression."
1724
+ end
1725
+ end
1726
+
1727
+ defp validate_in(meta, expr, param, acc, adapter) do
1728
+ {v, t} = Enum.fetch!(expr.params, param)
1729
+ length = length(v)
1730
+
1731
+ case adapter.dumpers(t, t) do
1732
+ [{:in, _} | _] -> {{:^, meta, [acc, length]}, acc + length}
1733
+ _ -> {{:^, meta, [acc, length]}, acc + 1}
1734
+ end
1735
+ end
1736
+
1737
+ defp normalize_select(%{select: nil} = query, _keep_literals?) do
1738
+ {query, nil}
1739
+ end
1740
+
1741
+ defp normalize_select(query, keep_literals?) do
1742
+ %{assocs: assocs, preloads: preloads, select: select} = query
1743
+ %{take: take, expr: expr} = select
1744
+ {tag, from_take} = Map.get(take, 0, {:any, []})
1745
+ source = get_source!(:select, query, 0)
1746
+ assocs = merge_assocs(assocs, query)
1747
+
1748
+ # In from, if there is a schema and we have a map tag with preloads,
1749
+ # it needs to be converted to a map in a later pass.
1750
+ {take, from_tag} =
1751
+ case source do
1752
+ {source, schema, _}
1753
+ when tag == :map and preloads != [] and is_binary(source) and schema != nil ->
1754
+ {Map.put(take, 0, {:struct, from_take}), :map}
1755
+
1756
+ _ ->
1757
+ {take, :any}
1758
+ end
1759
+
1760
+ {postprocess, fields, from} =
1761
+ collect_fields(expr, [], :none, query, take, keep_literals?, %{})
1762
+
1763
+ {fields, preprocess, from} =
1764
+ case from do
1765
+ {from_expr, from_source, from_fields} ->
1766
+ {assoc_exprs, assoc_fields} = collect_assocs([], [], query, tag, from_take, assocs)
1767
+ fields = from_fields ++ Enum.reverse(assoc_fields, Enum.reverse(fields))
1768
+ preprocess = [from_expr | Enum.reverse(assoc_exprs)]
1769
+ {fields, preprocess, {from_tag, from_source}}
1770
+
1771
+ :none when preloads != [] or assocs != [] ->
1772
+ error!(
1773
+ query,
1774
+ "the binding used in `from` must be selected in `select` when using `preload`"
1775
+ )
1776
+
1777
+ :none ->
1778
+ {Enum.reverse(fields), [], :none}
1779
+ end
1780
+
1781
+ select = %{
1782
+ preprocess: preprocess,
1783
+ postprocess: postprocess,
1784
+ take: from_take,
1785
+ assocs: assocs,
1786
+ from: from
1787
+ }
1788
+
1789
+ {put_in(query.select.fields, fields), select}
1790
+ end
1791
+
1792
+ # Handling of source
1793
+
1794
+ # The idea of collect_fields is to collect all fields used in select.
1795
+ # However, special care is taken in for `from`. Because `from` is used
1796
+ # earlier in assoc/preloads, any operation done on `from` is separately
1797
+ # collected in the `from` information. Then, everything else refers to
1798
+ # the preprocessed `from` as `{:source, :from}`.
1799
+
1800
+ defp collect_fields(
1801
+ {:merge, _, [left, right]},
1802
+ fields,
1803
+ from,
1804
+ query,
1805
+ take,
1806
+ keep_literals?,
1807
+ _drop
1808
+ ) do
1809
+ case collect_fields(left, fields, from, query, take, keep_literals?, %{}) do
1810
+ {{:source, :from}, fields, left_from} ->
1811
+ {right, right_fields, _} =
1812
+ collect_fields(right, [], left_from, query, take, keep_literals?, %{})
1813
+
1814
+ {from_expr, from_source, from_fields} = left_from
1815
+
1816
+ from =
1817
+ {{:merge, from_expr, right}, from_source, from_fields ++ Enum.reverse(right_fields)}
1818
+
1819
+ {{:source, :from}, fields, from}
1820
+
1821
+ {left, left_fields, left_from} ->
1822
+ {right, right_fields, right_from} =
1823
+ collect_fields(right, left_fields, left_from, query, take, keep_literals?, %{})
1824
+
1825
+ {{:merge, left, right}, right_fields, right_from}
1826
+ end
1827
+ end
1828
+
1829
+ defp collect_fields({:&, _, [0]}, fields, :none, query, take, _keep_literals?, drop) do
1830
+ {expr, taken} = source_take!(:select, query, take, 0, 0, drop)
1831
+ {{:source, :from}, fields, {{:source, :from}, expr, taken}}
1832
+ end
1833
+
1834
+ defp collect_fields({:&, _, [0]}, fields, from, _query, _take, _keep_literals?, _drop) do
1835
+ {{:source, :from}, fields, from}
1836
+ end
1837
+
1838
+ defp collect_fields({:&, _, [ix]}, fields, from, query, take, _keep_literals?, drop) do
1839
+ {expr, taken} = source_take!(:select, query, take, ix, ix, drop)
1840
+ {expr, Enum.reverse(taken, fields), from}
1841
+ end
1842
+
1843
+ # Expression handling
1844
+
1845
+ defp collect_fields(
1846
+ {agg, _, [{{:., dot_meta, [{:&, _, [_]}, _]}, _, []} | _]} = expr,
1847
+ fields,
1848
+ from,
1849
+ _query,
1850
+ _take,
1851
+ _keep_literals?,
1852
+ _drop
1853
+ )
1854
+ when agg in @aggs do
1855
+ type =
1856
+ case agg do
1857
+ :count -> :integer
1858
+ :row_number -> :integer
1859
+ :rank -> :integer
1860
+ :dense_rank -> :integer
1861
+ :ntile -> :integer
1862
+ # If it is possible to upcast, we do it, otherwise keep the DB value.
1863
+ # For example, an average of integers will return a decimal, which can't be cast
1864
+ # as an integer. But an average of "moneys" should be upcast.
1865
+ _ -> {:try, Keyword.fetch!(dot_meta, :type)}
1866
+ end
1867
+
1868
+ {{:value, type}, [expr | fields], from}
1869
+ end
1870
+
1871
+ defp collect_fields(
1872
+ {:filter, _, [call, _]} = expr,
1873
+ fields,
1874
+ from,
1875
+ query,
1876
+ take,
1877
+ keep_literals?,
1878
+ _drop
1879
+ ) do
1880
+ case call do
1881
+ {agg, _, _} when agg in @aggs ->
1882
+ :ok
1883
+
1884
+ {:fragment, _, [_ | _]} ->
1885
+ :ok
1886
+
1887
+ _ ->
1888
+ error!(
1889
+ query,
1890
+ "filter(...) expects the first argument to be an aggregate expression, got: `#{Macro.to_string(expr)}`"
1891
+ )
1892
+ end
1893
+
1894
+ {type, _, _} = collect_fields(call, fields, from, query, take, keep_literals?, %{})
1895
+ {type, [expr | fields], from}
1896
+ end
1897
+
1898
+ defp collect_fields(
1899
+ {:coalesce, _, [left, right]} = expr,
1900
+ fields,
1901
+ from,
1902
+ query,
1903
+ take,
1904
+ _keep_literals?,
1905
+ _drop
1906
+ ) do
1907
+ {left_type, _, _} = collect_fields(left, fields, from, query, take, true, %{})
1908
+ {right_type, _, _} = collect_fields(right, fields, from, query, take, true, %{})
1909
+
1910
+ type = if left_type == right_type, do: left_type, else: {:value, :any}
1911
+ {type, [expr | fields], from}
1912
+ end
1913
+
1914
+ defp collect_fields(
1915
+ {:over, _, [call, window]} = expr,
1916
+ fields,
1917
+ from,
1918
+ query,
1919
+ take,
1920
+ keep_literals?,
1921
+ _drop
1922
+ ) do
1923
+ if is_atom(window) and not Keyword.has_key?(query.windows, window) do
1924
+ error!(query, "unknown window #{inspect(window)} given to over/2")
1925
+ end
1926
+
1927
+ {type, _, _} = collect_fields(call, fields, from, query, take, keep_literals?, %{})
1928
+ {type, [expr | fields], from}
1929
+ end
1930
+
1931
+ defp collect_fields(
1932
+ {{:., dot_meta, [{:&, _, [_]}, _]}, _, []} = expr,
1933
+ fields,
1934
+ from,
1935
+ _query,
1936
+ _take,
1937
+ _keep_literals?,
1938
+ _drop
1939
+ ) do
1940
+ {{:value, Keyword.fetch!(dot_meta, :type)}, [expr | fields], from}
1941
+ end
1942
+
1943
+ defp collect_fields({left, right}, fields, from, query, take, keep_literals?, _drop) do
1944
+ {args, fields, from} =
1945
+ collect_args([left, right], fields, from, query, take, keep_literals?, [])
1946
+
1947
+ {{:tuple, args}, fields, from}
1948
+ end
1949
+
1950
+ defp collect_fields({:{}, _, args}, fields, from, query, take, keep_literals?, _drop) do
1951
+ {args, fields, from} = collect_args(args, fields, from, query, take, keep_literals?, [])
1952
+ {{:tuple, args}, fields, from}
1953
+ end
1954
+
1955
+ defp collect_fields(
1956
+ {:%{}, _, [{:|, _, [data, args]}]},
1957
+ fields,
1958
+ from,
1959
+ query,
1960
+ take,
1961
+ keep_literals?,
1962
+ _drop
1963
+ ) do
1964
+ drop = Map.new(args, fn {key, _} -> {key, nil} end)
1965
+ {data, fields, from} = collect_fields(data, fields, from, query, take, keep_literals?, drop)
1966
+ {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, [])
1967
+ {{:map, data, args}, fields, from}
1968
+ end
1969
+
1970
+ defp collect_fields({:%{}, _, args}, fields, from, query, take, keep_literals?, _drop) do
1971
+ {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, [])
1972
+ {{:map, args}, fields, from}
1973
+ end
1974
+
1975
+ defp collect_fields(
1976
+ {:%, _, [name, {:%{}, _, [{:|, _, [data, args]}]}]},
1977
+ fields,
1978
+ from,
1979
+ query,
1980
+ take,
1981
+ keep_literals?,
1982
+ _drop
1983
+ ) do
1984
+ drop = Map.new(args, fn {key, _} -> {key, nil} end)
1985
+ {data, fields, from} = collect_fields(data, fields, from, query, take, keep_literals?, drop)
1986
+ {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, [])
1987
+ struct!(name, args)
1988
+ {{:struct, name, data, args}, fields, from}
1989
+ end
1990
+
1991
+ defp collect_fields(
1992
+ {:%, _, [name, {:%{}, _, args}]},
1993
+ fields,
1994
+ from,
1995
+ query,
1996
+ take,
1997
+ keep_literals?,
1998
+ _drop
1999
+ ) do
2000
+ {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, [])
2001
+ struct!(name, args)
2002
+ {{:struct, name, args}, fields, from}
2003
+ end
2004
+
2005
+ defp collect_fields(
2006
+ {:date_add, _, [arg | _]} = expr,
2007
+ fields,
2008
+ from,
2009
+ query,
2010
+ take,
2011
+ keep_literals?,
2012
+ _drop
2013
+ ) do
2014
+ case collect_fields(arg, fields, from, query, take, keep_literals?, %{}) do
2015
+ {{:value, :any}, _, _} -> {{:value, :date}, [expr | fields], from}
2016
+ {type, _, _} -> {type, [expr | fields], from}
2017
+ end
2018
+ end
2019
+
2020
+ defp collect_fields(
2021
+ {:datetime_add, _, [arg | _]} = expr,
2022
+ fields,
2023
+ from,
2024
+ query,
2025
+ take,
2026
+ keep_literals?,
2027
+ _drop
2028
+ ) do
2029
+ case collect_fields(arg, fields, from, query, take, keep_literals?, %{}) do
2030
+ {{:value, :any}, _, _} -> {{:value, :naive_datetime}, [expr | fields], from}
2031
+ {type, _, _} -> {type, [expr | fields], from}
2032
+ end
2033
+ end
2034
+
2035
+ defp collect_fields(args, fields, from, query, take, keep_literals?, _drop)
2036
+ when is_list(args) do
2037
+ {args, fields, from} = collect_args(args, fields, from, query, take, keep_literals?, [])
2038
+ {{:list, args}, fields, from}
2039
+ end
2040
+
2041
+ defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_binary(expr) do
2042
+ {{:value, :binary}, [expr | fields], from}
2043
+ end
2044
+
2045
+ defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_integer(expr) do
2046
+ {{:value, :integer}, [expr | fields], from}
2047
+ end
2048
+
2049
+ defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_float(expr) do
2050
+ {{:value, :float}, [expr | fields], from}
2051
+ end
2052
+
2053
+ defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_boolean(expr) do
2054
+ {{:value, :boolean}, [expr | fields], from}
2055
+ end
2056
+
2057
+ defp collect_fields(nil, fields, from, _query, _take, true, _drop) do
2058
+ {{:value, :any}, [nil | fields], from}
2059
+ end
2060
+
2061
+ defp collect_fields(expr, fields, from, _query, _take, _keep_literals?, _drop)
2062
+ when is_atom(expr) do
2063
+ {expr, fields, from}
2064
+ end
2065
+
2066
+ defp collect_fields(expr, fields, from, _query, _take, false, _drop)
2067
+ when is_binary(expr) or is_number(expr) do
2068
+ {expr, fields, from}
2069
+ end
2070
+
2071
+ defp collect_fields(
2072
+ %Ecto.Query.Tagged{tag: tag} = expr,
2073
+ fields,
2074
+ from,
2075
+ _query,
2076
+ _take,
2077
+ _keep_literals?,
2078
+ _drop
2079
+ ) do
2080
+ {{:value, tag}, [expr | fields], from}
2081
+ end
2082
+
2083
+ defp collect_fields({op, _, [_]} = expr, fields, from, _query, _take, _keep_literals?, _drop)
2084
+ when op in ~w(not is_nil)a do
2085
+ {{:value, :boolean}, [expr | fields], from}
2086
+ end
2087
+
2088
+ defp collect_fields({op, _, [_, _]} = expr, fields, from, _query, _take, _keep_literals?, _drop)
2089
+ when op in ~w(< > <= >= == != and or like ilike)a do
2090
+ {{:value, :boolean}, [expr | fields], from}
2091
+ end
2092
+
2093
+ defp collect_fields(
2094
+ {:selected_as, _, [select_expr, name]},
2095
+ fields,
2096
+ from,
2097
+ query,
2098
+ take,
2099
+ keep_literals?,
2100
+ _drop
2101
+ ) do
2102
+ {type, _, _} = collect_fields(select_expr, fields, from, query, take, keep_literals?, %{})
2103
+ {type, [{name, select_expr} | fields], from}
2104
+ end
2105
+
2106
+ defp collect_fields(expr, fields, from, _query, _take, _keep_literals?, _drop) do
2107
+ {{:value, :any}, [expr | fields], from}
2108
+ end
2109
+
2110
+ defp collect_kv([{key, value} | elems], fields, from, query, take, keep_literals?, acc) do
2111
+ {key, fields, from} = collect_fields(key, fields, from, query, take, keep_literals?, %{})
2112
+ {value, fields, from} = collect_fields(value, fields, from, query, take, keep_literals?, %{})
2113
+ collect_kv(elems, fields, from, query, take, keep_literals?, [{key, value} | acc])
2114
+ end
2115
+
2116
+ defp collect_kv([], fields, from, _query, _take, _keep_literals?, acc) do
2117
+ {Enum.reverse(acc), fields, from}
2118
+ end
2119
+
2120
+ defp collect_args([elem | elems], fields, from, query, take, keep_literals?, acc) do
2121
+ {elem, fields, from} = collect_fields(elem, fields, from, query, take, keep_literals?, %{})
2122
+ collect_args(elems, fields, from, query, take, keep_literals?, [elem | acc])
2123
+ end
2124
+
2125
+ defp collect_args([], fields, from, _query, _take, _keep_literals?, acc) do
2126
+ {Enum.reverse(acc), fields, from}
2127
+ end
2128
+
2129
+ defp merge_assocs(assocs, query) do
2130
+ assocs
2131
+ |> Enum.reduce(%{}, fn {field, {index, children}}, acc ->
2132
+ children = merge_assocs(children, query)
2133
+
2134
+ Map.update(acc, field, {index, children}, fn
2135
+ {^index, current_children} ->
2136
+ {index, merge_assocs(children ++ current_children, query)}
2137
+
2138
+ {other_index, _} ->
2139
+ error!(
2140
+ query,
2141
+ "association `#{field}` is being set to binding at position #{index} " <>
2142
+ "and at position #{other_index} at the same time"
2143
+ )
2144
+ end)
2145
+ end)
2146
+ |> Map.to_list()
2147
+ end
2148
+
2149
+ defp collect_assocs(exprs, fields, query, tag, take, [{assoc, {ix, children}} | tail]) do
2150
+ to_take = get_preload_source!(query, ix)
2151
+ {fetch, take_children} = fetch_assoc(tag, take, assoc)
2152
+ {expr, taken} = take!(to_take, query, fetch, assoc, ix, %{})
2153
+ exprs = [expr | exprs]
2154
+ fields = Enum.reverse(taken, fields)
2155
+ {exprs, fields} = collect_assocs(exprs, fields, query, tag, take_children, children)
2156
+ {exprs, fields} = collect_assocs(exprs, fields, query, tag, take, tail)
2157
+ {exprs, fields}
2158
+ end
2159
+
2160
+ defp collect_assocs(exprs, fields, _query, _tag, _take, []) do
2161
+ {exprs, fields}
2162
+ end
2163
+
2164
+ defp fetch_assoc(tag, take, assoc) do
2165
+ case Access.fetch(take, assoc) do
2166
+ {:ok, value} -> {{:ok, {tag, value}}, value}
2167
+ :error -> {:error, []}
2168
+ end
2169
+ end
2170
+
2171
+ defp source_take!(kind, query, take, field, ix, drop) do
2172
+ source = get_source!(kind, query, ix)
2173
+ take!(source, query, Access.fetch(take, field), field, ix, drop)
2174
+ end
2175
+
2176
+ defp take!(source, query, fetched, field, ix, drop) do
2177
+ case {fetched, source} do
2178
+ {{:ok, {:struct, _}}, {:fragment, _, _}} ->
2179
+ error!(query, "it is not possible to return a struct subset of a fragment")
2180
+
2181
+ {{:ok, {:struct, _}}, %Ecto.SubQuery{}} ->
2182
+ error!(query, "it is not possible to return a struct subset of a subquery")
2183
+
2184
+ {{:ok, {_, []}}, {_, _, _}} ->
2185
+ error!(
2186
+ query,
2187
+ "at least one field must be selected for binding `#{field}`, got an empty list"
2188
+ )
2189
+
2190
+ {{:ok, {:struct, _}}, {_, nil, _}} ->
2191
+ error!(query, "struct/2 in select expects a source with a schema")
2192
+
2193
+ {{:ok, {kind, fields}}, {source, schema, prefix}} when is_binary(source) ->
2194
+ dumper = if schema, do: schema.__schema__(:dump), else: %{}
2195
+ schema = if kind == :map, do: nil, else: schema
2196
+ {types, fields} = select_dump(List.wrap(fields), dumper, ix, drop)
2197
+ {{:source, {source, schema}, prefix || query.prefix, types}, fields}
2198
+
2199
+ {{:ok, {_, fields}}, _} ->
2200
+ {{:map, Enum.map(fields, &{&1, {:value, :any}})},
2201
+ Enum.map(fields, &select_field(&1, ix, :always))}
2202
+
2203
+ {:error, {:fragment, _, _}} ->
2204
+ {{:value, :map}, [{:&, [], [ix]}]}
2205
+
2206
+ {:error, {:values, _, [types, _]}} ->
2207
+ fields = Keyword.keys(types)
2208
+
2209
+ dumper =
2210
+ types
2211
+ |> Enum.map(fn {field, type} -> {field, {field, type, :always}} end)
2212
+ |> Enum.into(%{})
2213
+
2214
+ {types, fields} = select_dump(fields, dumper, ix, drop)
2215
+ {{:source, :values, nil, types}, fields}
2216
+
2217
+ {:error, {_, nil, _}} ->
2218
+ {{:value, :map}, [{:&, [], [ix]}]}
2219
+
2220
+ {:error, {source, schema, prefix}} ->
2221
+ {types, fields} =
2222
+ select_dump(schema.__schema__(:query_fields), schema.__schema__(:dump), ix, drop)
2223
+
2224
+ {{:source, {source, schema}, prefix || query.prefix, types}, fields}
2225
+
2226
+ {:error, %Ecto.SubQuery{select: select}} ->
2227
+ fields = subquery_source_fields(select)
2228
+ {select, Enum.map(fields, &select_field(&1, ix, :always))}
2229
+ end
2230
+ end
2231
+
2232
+ defp select_dump(fields, dumper, ix, drop) do
2233
+ fields
2234
+ |> Enum.reverse()
2235
+ |> Enum.reduce({[], []}, fn
2236
+ field, {types, exprs} when is_atom(field) and not is_map_key(drop, field) ->
2237
+ {source, type, writable} = Map.get(dumper, field, {field, :any, :always})
2238
+ {[{field, type} | types], [select_field(source, ix, writable) | exprs]}
2239
+
2240
+ _field, acc ->
2241
+ acc
2242
+ end)
2243
+ end
2244
+
2245
+ defp select_field(field, ix, writable) do
2246
+ {{:., [writable: writable], [{:&, [], [ix]}, field]}, [], []}
2247
+ end
2248
+
2249
+ defp get_ix!({:&, _, [ix]} = expr, _kind, query) do
2250
+ {ix, expr, query}
2251
+ end
2252
+
2253
+ defp get_ix!({:as, meta, [as]}, _kind, query) do
2254
+ case query.aliases do
2255
+ %{^as => ix} -> {ix, {:&, meta, [ix]}, query}
2256
+ %{} -> error!(query, "could not find named binding `as(#{inspect(as)})`")
2257
+ end
2258
+ end
2259
+
2260
+ defp get_ix!({:parent_as, meta, [as]}, kind, query) do
2261
+ case query.aliases[@parent_as] do
2262
+ %{aliases: %{^as => ix}, sources: sources} = query ->
2263
+ if kind == :select and not (ix < tuple_size(sources)) do
2264
+ error!(
2265
+ query,
2266
+ "the parent_as in a subquery select used as a join can only access the `from` binding"
2267
+ )
2268
+ else
2269
+ {ix, {:parent_as, [], [as]}, query}
2270
+ end
2271
+
2272
+ %{} = parent ->
2273
+ get_ix!({:parent_as, meta, [as]}, kind, parent)
2274
+
2275
+ nil ->
2276
+ error!(query, "could not find named binding `parent_as(#{inspect(as)})`")
2277
+ end
2278
+ end
2279
+
2280
+ defp get_source!(where, %{sources: sources} = query, ix) do
2281
+ elem(sources, ix)
2282
+ rescue
2283
+ ArgumentError ->
2284
+ error!(
2285
+ query,
2286
+ "invalid query has specified more bindings than bindings available " <>
2287
+ "in `#{where}` (look for `unknown_binding!` in the printed query below)"
2288
+ )
2289
+ end
2290
+
2291
+ defp get_preload_source!(query, ix) do
2292
+ case get_source!(:preload, query, ix) do
2293
+ {source, schema, _} = all when is_binary(source) and schema != nil ->
2294
+ all
2295
+
2296
+ %Ecto.SubQuery{select: {:source, {source, schema}, _, _}} = subquery
2297
+ when is_binary(source) and schema != nil ->
2298
+ subquery
2299
+
2300
+ _ ->
2301
+ error!(
2302
+ query,
2303
+ "can only preload sources with a schema " <>
2304
+ "(fragments, binaries, and subqueries that do not select a from/join schema are not supported)"
2305
+ )
2306
+ end
2307
+ end
2308
+
2309
+ @doc """
2310
+ Puts the prefix given via `opts` into the given query, if available.
2311
+ """
2312
+ def attach_prefix(%{prefix: nil} = query, opts) when is_list(opts) do
2313
+ case Keyword.fetch(opts, :prefix) do
2314
+ {:ok, prefix} ->
2315
+ %{query | prefix: prefix}
2316
+
2317
+ :error ->
2318
+ query
2319
+ end
2320
+ end
2321
+
2322
+ def attach_prefix(%{prefix: nil} = query, %{prefix: prefix}) do
2323
+ %{query | prefix: prefix}
2324
+ end
2325
+
2326
+ def attach_prefix(query, _), do: query
2327
+
2328
+ ## Helpers
2329
+
2330
+ @all_exprs [
2331
+ with_cte: :with_ctes,
2332
+ distinct: :distinct,
2333
+ select: :select,
2334
+ from: :from,
2335
+ join: :joins,
2336
+ where: :wheres,
2337
+ group_by: :group_bys,
2338
+ having: :havings,
2339
+ windows: :windows,
2340
+ combination: :combinations,
2341
+ order_by: :order_bys,
2342
+ limit: :limit,
2343
+ offset: :offset
2344
+ ]
2345
+
2346
+ # Although joins come before updates in the actual query,
2347
+ # the on fields are moved to where, so they effectively
2348
+ # need to come later for MySQL. This means subqueries
2349
+ # with parameters are not supported as a join on MySQL.
2350
+ # The only way to address it is by splitting how join
2351
+ # and their on expressions are processed.
2352
+ @update_all_exprs [
2353
+ with_cte: :with_ctes,
2354
+ from: :from,
2355
+ update: :updates,
2356
+ join: :joins,
2357
+ where: :wheres,
2358
+ select: :select
2359
+ ]
2360
+
2361
+ @delete_all_exprs [
2362
+ with_cte: :with_ctes,
2363
+ from: :from,
2364
+ join: :joins,
2365
+ where: :wheres,
2366
+ select: :select
2367
+ ]
2368
+
2369
+ # Traverse all query components with expressions.
2370
+ # Therefore from, preload, assocs and lock are not traversed.
2371
+ defp traverse_exprs(query, operation, acc, fun) do
2372
+ exprs =
2373
+ case operation do
2374
+ :all -> @all_exprs
2375
+ :insert_all -> @all_exprs
2376
+ :update_all -> @update_all_exprs
2377
+ :delete_all -> @delete_all_exprs
2378
+ end
2379
+
2380
+ Enum.reduce(exprs, {query, acc}, fn {kind, key}, {query, acc} ->
2381
+ {traversed, acc} = fun.(kind, query, Map.fetch!(query, key), acc)
2382
+ {%{query | key => traversed}, acc}
2383
+ end)
2384
+ end
2385
+
2386
+ defp field_type!(kind, query, expr, type, allow_virtuals? \\ false)
2387
+
2388
+ defp field_type!(kind, query, expr, {composite, {ix, field}}, allow_virtuals?)
2389
+ when is_integer(ix) do
2390
+ {composite, type!(kind, query, expr, ix, field, allow_virtuals?)}
2391
+ end
2392
+
2393
+ defp field_type!(
2394
+ kind,
2395
+ query,
2396
+ expr,
2397
+ {composite, {{bind_kind, _, [_]} = bind_expr, field}},
2398
+ allow_virtuals?
2399
+ )
2400
+ when bind_kind in [:as, :parent_as] do
2401
+ {ix, _, ix_query} = get_ix!(bind_expr, kind, query)
2402
+ {composite, type!(kind, ix_query, expr, ix, field, allow_virtuals?)}
2403
+ end
2404
+
2405
+ defp field_type!(kind, query, expr, {{bind_kind, _, [_]} = bind_expr, field}, allow_virtuals?)
2406
+ when bind_kind in [:as, :parent_as] do
2407
+ {ix, _, ix_query} = get_ix!(bind_expr, kind, query)
2408
+ type!(kind, ix_query, expr, ix, field, allow_virtuals?)
2409
+ end
2410
+
2411
+ defp field_type!(kind, query, expr, {ix, field}, allow_virtuals?) when is_integer(ix) do
2412
+ type!(kind, query, expr, ix, field, allow_virtuals?)
2413
+ end
2414
+
2415
+ defp field_type!(_kind, _query, _expr, type, _) do
2416
+ type
2417
+ end
2418
+
2419
+ defp type!(kind, query, expr, schema, field, allow_virtuals? \\ false)
2420
+
2421
+ defp type!(_kind, _query, _expr, nil, _field, _allow_virtuals?), do: :any
2422
+
2423
+ defp type!(kind, query, expr, ix, field, allow_virtuals?) when is_integer(ix) do
2424
+ case get_source!(kind, query, ix) do
2425
+ {:fragment, _, _} ->
2426
+ :any
2427
+
2428
+ {:values, _, [types, _]} ->
2429
+ case Keyword.fetch(types, field) do
2430
+ {:ok, type} ->
2431
+ type
2432
+
2433
+ :error ->
2434
+ error!(query, expr, "field `#{field}` in `#{kind}` does not exist in values list")
2435
+ end
2436
+
2437
+ {_, schema, _} ->
2438
+ type!(kind, query, expr, schema, field, allow_virtuals?)
2439
+
2440
+ %Ecto.SubQuery{select: select} ->
2441
+ case subquery_type_for(select, field) do
2442
+ {:ok, type} -> type
2443
+ :error -> error!(query, expr, "field `#{field}` does not exist in subquery")
2444
+ end
2445
+ end
2446
+ end
2447
+
2448
+ defp type!(kind, query, expr, schema, field, allow_virtuals?) when is_atom(schema) do
2449
+ cond do
2450
+ type = schema.__schema__(:type, field) ->
2451
+ type
2452
+
2453
+ type = allow_virtuals? && schema.__schema__(:virtual_type, field) ->
2454
+ type
2455
+
2456
+ Map.has_key?(schema.__struct__(), field) ->
2457
+ case schema.__schema__(:association, field) do
2458
+ %Ecto.Association.BelongsTo{owner_key: owner_key} ->
2459
+ error!(
2460
+ query,
2461
+ expr,
2462
+ "field `#{field}` in `#{kind}` is an association in schema #{inspect(schema)}. " <>
2463
+ "Did you mean to use `#{owner_key}`?"
2464
+ )
2465
+
2466
+ %_{} ->
2467
+ error!(
2468
+ query,
2469
+ expr,
2470
+ "field `#{field}` in `#{kind}` is an association in schema #{inspect(schema)}"
2471
+ )
2472
+
2473
+ _ ->
2474
+ error!(
2475
+ query,
2476
+ expr,
2477
+ "field `#{field}` in `#{kind}` is a virtual field in schema #{inspect(schema)}"
2478
+ )
2479
+ end
2480
+
2481
+ true ->
2482
+ hint = closest_fields_hint(field, schema)
2483
+
2484
+ error!(
2485
+ query,
2486
+ expr,
2487
+ "field `#{field}` in `#{kind}` does not exist in schema #{inspect(schema)}",
2488
+ hint
2489
+ )
2490
+ end
2491
+ end
2492
+
2493
+ defp closest_fields_hint(input, schema) do
2494
+ input_string = Atom.to_string(input)
2495
+
2496
+ schema.__schema__(:fields)
2497
+ |> Enum.map(fn field -> {field, String.jaro_distance(input_string, Atom.to_string(field))} end)
2498
+ |> Enum.filter(fn {_field, score} -> score >= 0.77 end)
2499
+ |> Enum.sort(&(elem(&1, 0) >= elem(&2, 0)))
2500
+ |> Enum.take(5)
2501
+ |> Enum.map(&elem(&1, 0))
2502
+ |> case do
2503
+ [] ->
2504
+ nil
2505
+
2506
+ [suggestion] ->
2507
+ "Did you mean `#{suggestion}`?"
2508
+
2509
+ suggestions ->
2510
+ Enum.reduce(suggestions, "Did you mean one of: \n", fn suggestion, acc ->
2511
+ acc <> "\n * `#{suggestion}`"
2512
+ end)
2513
+ end
2514
+ end
2515
+
2516
+ defp normalize_param(_kind, {:out, {:array, type}}, _value) do
2517
+ {:ok, type}
2518
+ end
2519
+
2520
+ defp normalize_param(_kind, {:out, :any}, _value) do
2521
+ {:ok, :any}
2522
+ end
2523
+
2524
+ defp normalize_param(kind, {:out, other}, value) do
2525
+ {:error,
2526
+ "value `#{inspect(value)}` in `#{kind}` expected to be part of an array " <>
2527
+ "but matched type is #{inspect(other)}"}
2528
+ end
2529
+
2530
+ defp normalize_param(_kind, type, _value) do
2531
+ {:ok, type}
2532
+ end
2533
+
2534
+ defp cast_param(kind, type, v) do
2535
+ case Ecto.Type.cast(type, v) do
2536
+ {:ok, v} ->
2537
+ {:ok, v}
2538
+
2539
+ :error ->
2540
+ {:error,
2541
+ "value `#{inspect(v)}` in `#{kind}` cannot be cast to type #{Ecto.Type.format(type)}"}
2542
+
2543
+ {:error, _meta} ->
2544
+ {:error,
2545
+ "value `#{inspect(v)}` in `#{kind}` cannot be cast to type #{Ecto.Type.format(type)}"}
2546
+
2547
+ other ->
2548
+ raise "expected #{inspect(type)}.cast/1 to return {:ok, v}, :error, or {:error, meta}" <>
2549
+ ", got: #{inspect(other)}"
2550
+ end
2551
+ end
2552
+
2553
+ defp dump_param(adapter, type, v) do
2554
+ case Ecto.Type.adapter_dump(adapter, type, v) do
2555
+ {:ok, v} ->
2556
+ {:ok, v}
2557
+
2558
+ :error ->
2559
+ {:error, "value `#{inspect(v)}` cannot be dumped to type #{Ecto.Type.format(type)}"}
2560
+ end
2561
+ end
2562
+
2563
+ defp field_source({source, schema, _}, field) when is_binary(source) and schema != nil do
2564
+ # If the field is not found we return the field itself
2565
+ # which will be checked and raise later.
2566
+ schema.__schema__(:field_source, field) || field
2567
+ end
2568
+
2569
+ defp field_source(_, field) do
2570
+ field
2571
+ end
2572
+
2573
+ defp cte_fields([key | rest_keys], [{key, select_expr} | rest_fields], aliases) do
2574
+ [{key, select_expr} | cte_fields(rest_keys, rest_fields, aliases)]
2575
+ end
2576
+
2577
+ defp cte_fields([key | rest_keys], [field | rest_fields], aliases) do
2578
+ if Map.has_key?(aliases, key) do
2579
+ raise ArgumentError,
2580
+ "the alias, #{inspect(key)}, provided to `selected_as/2` conflicts" <>
2581
+ "with the CTE's automatic aliasing. When using `selected_as/2`" <>
2582
+ "inside of a CTE, you must ensure it does not conflict with any of the other" <>
2583
+ "field names"
2584
+ end
2585
+
2586
+ {key, field} =
2587
+ case field do
2588
+ {alias, select_expr} -> {alias, select_expr}
2589
+ field -> {key, field}
2590
+ end
2591
+
2592
+ [{key, field} | cte_fields(rest_keys, rest_fields, aliases)]
2593
+ end
2594
+
2595
+ defp cte_fields([], [], _aliases), do: []
2596
+
2597
+ defp assert_update!(%Ecto.Query{updates: updates} = query, operation) do
2598
+ dumper = dumper_for_update(query)
2599
+
2600
+ changes =
2601
+ Enum.reduce(updates, %{}, fn update, acc ->
2602
+ Enum.reduce(update.expr, acc, fn {_op, kw}, acc ->
2603
+ Enum.reduce(kw, acc, fn {k, v}, acc ->
2604
+ if Map.has_key?(acc, k) do
2605
+ error!(query, "duplicate field `#{k}` for `#{operation}`")
2606
+ end
2607
+
2608
+ case dumper do
2609
+ %{^k => {_, _, :always}} -> :ok
2610
+ %{} -> error!(query, "cannot update non-updatable field `#{inspect(k)}`")
2611
+ nil -> :ok
2612
+ end
2613
+
2614
+ Map.put(acc, k, v)
2615
+ end)
2616
+ end)
2617
+ end)
2618
+
2619
+ if changes == %{} do
2620
+ error!(query, "`#{operation}` requires at least one field to be updated")
2621
+ end
2622
+ end
2623
+
2624
+ defp assert_no_update!(query, operation) do
2625
+ case query do
2626
+ %Ecto.Query{updates: []} ->
2627
+ query
2628
+
2629
+ _ ->
2630
+ error!(query, "`#{operation}` does not allow `update` expressions")
2631
+ end
2632
+ end
2633
+
2634
+ defp assert_only_filter_expressions!(query, operation) do
2635
+ case query do
2636
+ %Ecto.Query{
2637
+ order_bys: [],
2638
+ limit: nil,
2639
+ offset: nil,
2640
+ group_bys: [],
2641
+ havings: [],
2642
+ preloads: [],
2643
+ assocs: [],
2644
+ distinct: nil,
2645
+ lock: nil,
2646
+ windows: [],
2647
+ combinations: []
2648
+ } ->
2649
+ query
2650
+
2651
+ _ when operation == :delete_all ->
2652
+ error!(
2653
+ query,
2654
+ "`#{operation}` allows only `with_cte`, `where`, `select`, and `join` expressions. " <>
2655
+ "You can exclude unwanted expressions from a query by using " <>
2656
+ "Ecto.Query.exclude/2. Error found"
2657
+ )
2658
+
2659
+ _ ->
2660
+ error!(
2661
+ query,
2662
+ "`#{operation}` allows only `with_cte`, `where` and `join` expressions. " <>
2663
+ "You can exclude unwanted expressions from a query by using " <>
2664
+ "Ecto.Query.exclude/2. Error found"
2665
+ )
2666
+ end
2667
+ end
2668
+
2669
+ defp dumper_for_update(query) do
2670
+ case get_source!(:updates, query, 0) do
2671
+ {source, schema, _} when is_binary(source) and schema != nil ->
2672
+ schema.__schema__(:dump)
2673
+
2674
+ _ ->
2675
+ nil
2676
+ end
2677
+ end
2678
+
2679
+ defp filter_and_reraise(exception, stacktrace) do
2680
+ reraise exception, Enum.reject(stacktrace, &match?({__MODULE__, _, _, _}, &1))
2681
+ end
2682
+
2683
+ defp error!(query, message) do
2684
+ raise Ecto.QueryError, message: message, query: query
2685
+ end
2686
+
2687
+ defp error!(query, expr, message) do
2688
+ raise Ecto.QueryError, message: message, query: query, file: expr.file, line: expr.line
2689
+ end
2690
+
2691
+ defp error!(query, expr, message, hint) do
2692
+ raise Ecto.QueryError,
2693
+ message: message,
2694
+ query: query,
2695
+ file: expr.file,
2696
+ line: expr.line,
2697
+ hint: hint
2698
+ end
2699
+ end
deps/ecto/lib/ecto/query/window_api.ex ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Query.WindowAPI do
2
+ @moduledoc """
3
+ Lists all windows functions.
4
+
5
+ Windows functions must always be used as the first argument
6
+ of `over/2` where the second argument is the name of a window:
7
+
8
+ from e in Employee,
9
+ select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)},
10
+ windows: [department: [partition_by: e.depname]]
11
+
12
+ In the example above, we get the average salary per department.
13
+ `:department` is the window name, partitioned by `e.depname`
14
+ and `avg/1` is the window function.
15
+
16
+ However, note that defining a window is not necessary, as the
17
+ window definition can be given as the second argument to `over`:
18
+
19
+ from e in Employee,
20
+ select: {e.depname, e.empno, e.salary, over(avg(e.salary), partition_by: e.depname)}
21
+
22
+ Both queries are equivalent. However, if you are using the same
23
+ partitioning over and over again, defining a window will reduce
24
+ the query size. See `Ecto.Query.windows/3` for all possible window
25
+ expressions, such as `:partition_by` and `:order_by`.
26
+ """
27
+
28
+ @dialyzer :no_return
29
+
30
+ @doc """
31
+ Counts the entries in the table.
32
+
33
+ from p in Post, select: count()
34
+ """
35
+ def count, do: doc! []
36
+
37
+ @doc """
38
+ Counts the given entry.
39
+
40
+ from p in Post, select: count(p.id)
41
+ """
42
+ def count(value), do: doc! [value]
43
+
44
+ @doc """
45
+ Calculates the average for the given entry.
46
+
47
+ from p in Payment, select: avg(p.value)
48
+ """
49
+ def avg(value), do: doc! [value]
50
+
51
+ @doc """
52
+ Calculates the sum for the given entry.
53
+
54
+ from p in Payment, select: sum(p.value)
55
+ """
56
+ def sum(value), do: doc! [value]
57
+
58
+ @doc """
59
+ Calculates the minimum for the given entry.
60
+
61
+ from p in Payment, select: min(p.value)
62
+ """
63
+ def min(value), do: doc! [value]
64
+
65
+ @doc """
66
+ Calculates the maximum for the given entry.
67
+
68
+ from p in Payment, select: max(p.value)
69
+ """
70
+ def max(value), do: doc! [value]
71
+
72
+ @doc """
73
+ Defines a value based on the function and the window. See moduledoc for more information.
74
+
75
+ from e in Employee, select: over(avg(e.salary), partition_by: e.depname)
76
+ """
77
+ def over(window_function, window_name), do: doc! [window_function, window_name]
78
+
79
+ @doc """
80
+ Returns number of the current row within its partition, counting from 1.
81
+
82
+ from p in Post,
83
+ select: row_number() |> over(partition_by: p.category_id, order_by: p.date)
84
+
85
+ Note that this function must be invoked using window function syntax.
86
+ """
87
+ def row_number(), do: doc! []
88
+
89
+ @doc """
90
+ Returns rank of the current row with gaps; same as `row_number/0` of its first peer.
91
+
92
+ from p in Post,
93
+ select: rank() |> over(partition_by: p.category_id, order_by: p.date)
94
+
95
+ Note that this function must be invoked using window function syntax.
96
+ """
97
+ def rank(), do: doc! []
98
+
99
+ @doc """
100
+ Returns rank of the current row without gaps; this function counts peer groups.
101
+
102
+ from p in Post,
103
+ select: dense_rank() |> over(partition_by: p.category_id, order_by: p.date)
104
+
105
+ Note that this function must be invoked using window function syntax.
106
+ """
107
+ def dense_rank(), do: doc! []
108
+
109
+ @doc """
110
+ Returns relative rank of the current row: (rank - 1) / (total rows - 1).
111
+
112
+ from p in Post,
113
+ select: percent_rank() |> over(partition_by: p.category_id, order_by: p.date)
114
+
115
+ Note that this function must be invoked using window function syntax.
116
+ """
117
+ def percent_rank(), do: doc! []
118
+
119
+ @doc """
120
+ Returns relative rank of the current row:
121
+ (number of rows preceding or peer with current row) / (total rows).
122
+
123
+ from p in Post,
124
+ select: cume_dist() |> over(partition_by: p.category_id, order_by: p.date)
125
+
126
+ Note that this function must be invoked using window function syntax.
127
+ """
128
+ def cume_dist(), do: doc! []
129
+
130
+ @doc """
131
+ Returns integer ranging from 1 to the argument value, dividing the partition as equally as possible.
132
+
133
+ from p in Post,
134
+ select: ntile(10) |> over(partition_by: p.category_id, order_by: p.date)
135
+
136
+ Note that this function must be invoked using window function syntax.
137
+ """
138
+ def ntile(num_buckets), do: doc! [num_buckets]
139
+
140
+ @doc """
141
+ Returns value evaluated at the row that is the first row of the window frame.
142
+
143
+ from p in Post,
144
+ select: first_value(p.id) |> over(partition_by: p.category_id, order_by: p.date)
145
+
146
+ Note that this function must be invoked using window function syntax.
147
+ """
148
+ def first_value(value), do: doc! [value]
149
+
150
+ @doc """
151
+ Returns value evaluated at the row that is the last row of the window frame.
152
+
153
+ from p in Post,
154
+ select: last_value(p.id) |> over(partition_by: p.category_id, order_by: p.date)
155
+
156
+ Note that this function must be invoked using window function syntax.
157
+ """
158
+ def last_value(value), do: doc! [value]
159
+
160
+
161
+ @doc """
162
+ Applies the given expression as a FILTER clause against an
163
+ aggregate. This is currently only supported by Postgres.
164
+
165
+ from p in Post,
166
+ select: avg(p.value)
167
+ |> filter(p.value > 0 and p.value < 100)
168
+ |> over(partition_by: p.category_id, order_by: p.date)
169
+ """
170
+
171
+ def filter(value, filter), do: doc! [value, filter]
172
+
173
+ @doc """
174
+ Returns value evaluated at the row that is the nth row of the window
175
+ frame (counting from 1); `nil` if no such row.
176
+
177
+ from p in Post,
178
+ select: nth_value(p.id, 4) |> over(partition_by: p.category_id, order_by: p.date)
179
+
180
+ Note that this function must be invoked using window function syntax.
181
+ """
182
+ def nth_value(value, nth), do: doc! [value, nth]
183
+
184
+ @doc """
185
+ Returns value evaluated at the row that is offset rows before
186
+ the current row within the partition.
187
+
188
+ If there is no such row, instead return default (which must be of the
189
+ same type as value). Both offset and default are evaluated with respect
190
+ to the current row. If omitted, offset defaults to 1 and default to `nil`.
191
+
192
+ from e in Events,
193
+ windows: [w: [partition_by: e.name, order_by: e.tick]],
194
+ select: {
195
+ e.tick,
196
+ e.action,
197
+ e.name,
198
+ lag(e.action) |> over(:w), # previous_action
199
+ lead(e.action) |> over(:w) # next_action
200
+ }
201
+
202
+ Note that this function must be invoked using window function syntax.
203
+ """
204
+ def lag(value, offset \\ 1, default \\ nil), do: doc! [value, offset, default]
205
+
206
+ @doc """
207
+ Returns value evaluated at the row that is offset rows after
208
+ the current row within the partition.
209
+
210
+ If there is no such row, instead return default (which must be of the
211
+ same type as value). Both offset and default are evaluated with respect
212
+ to the current row. If omitted, offset defaults to 1 and default to `nil`.
213
+
214
+ from e in Events,
215
+ windows: [w: [partition_by: e.name, order_by: e.tick]],
216
+ select: {
217
+ e.tick,
218
+ e.action,
219
+ e.name,
220
+ lag(e.action) |> over(:w), # previous_action
221
+ lead(e.action) |> over(:w) # next_action
222
+ }
223
+
224
+ Note that this function must be invoked using window function syntax.
225
+ """
226
+ def lead(value, offset \\ 1, default \\ nil), do: doc! [value, offset, default]
227
+
228
+ defp doc!(_) do
229
+ raise "the functions in Ecto.Query.WindowAPI should not be invoked directly, " <>
230
+ "they serve for documentation purposes only"
231
+ end
232
+ end
deps/ecto/lib/ecto/queryable.ex ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defprotocol Ecto.Queryable do
2
+ @moduledoc """
3
+ Converts a data structure into an `Ecto.Query`.
4
+
5
+ This is used by `Ecto.Repo` and also `from` macro. For example, `Repo.all`
6
+ expects any queryable as argument, which is why you can do `Repo.all(MySchema)`
7
+ or `Repo.all(query)`. Furthermore, when you write `from ALIAS in QUERYABLE`,
8
+ `QUERYABLE` accepts any data structure that implements `Ecto.Queryable`.
9
+
10
+ This module defines a few default implementations so let us go over each and
11
+ how to use them.
12
+
13
+ ## Atom
14
+
15
+ The most common use case for this protocol is to convert atoms representing
16
+ an `Ecto.Schema` module into a query. This is what happens when you write:
17
+
18
+ query = from(p in Person)
19
+
20
+ Or when you directly pass a schema to a repository:
21
+
22
+ Repo.all(Person)
23
+
24
+ In case you did not know, Elixir modules are just atoms. This implementation
25
+ takes the provided module name and then tries to load the associated schema.
26
+ If no schema exists, it will raise `Protocol.UndefinedError`.
27
+
28
+ ## BitString
29
+
30
+ This implementation allows you to directly specify a table that you would like
31
+ to query from:
32
+
33
+ from(
34
+ p in "people",
35
+ select: {p.first_name, p.last_name}
36
+ )
37
+
38
+ Or:
39
+
40
+ Repo.delete_all("people")
41
+
42
+ While this is quite simple to use, some repository operations, such as
43
+ `Repo.all`, require a `select` clause. When you query a schema, the
44
+ select is automatically defined for you based on the schema fields,
45
+ but when you pass a table directly, you need to explicitly list them.
46
+ This limitation now brings us to our next implementation!
47
+
48
+ ## Tuple
49
+
50
+ Similar to the `BitString` implementation, this allows you to specify the
51
+ underlying table that you would like to query; however, this additionally
52
+ allows you to specify the schema you would like to use:
53
+
54
+ from(p in {"filtered_people", Person})
55
+
56
+ This can be particularly useful if you have database views that filter or
57
+ aggregate the underlying data of a table but share the same schema. This means
58
+ that you can reuse the same schema while specifying a separate "source" for
59
+ the data.
60
+
61
+ ## Ecto.Query
62
+
63
+ This is a simple pass through. After all, all `Ecto.Query` instances
64
+ can be converted into `Ecto.Query`:
65
+
66
+ Repo.all(from u in User, where: u.active)
67
+
68
+ This also enables Ecto queries to compose, since we can pass one query
69
+ as the source of another:
70
+
71
+ active_users = from u in User, where: u.active
72
+ ordered_active_users = from u in active_users, order_by: u.created_at
73
+
74
+ ## Ecto.SubQuery
75
+
76
+ Ecto also allows you to compose queries using subqueries. Imagine you
77
+ have a table of "people". Now imagine that you want to do something with
78
+ people with the most common last names. To get that list, you could write
79
+ something like:
80
+
81
+ sub = from(
82
+ p in Person,
83
+ group_by: p.last_name,
84
+ having: count(p.last_name) > 1,
85
+ select: %{last_name: p.last_name, count: count(p.last_name)}
86
+ )
87
+
88
+ Now if you want to do something else with this data, perhaps join on
89
+ additional tables and perform some calculations, you can do that as so:
90
+
91
+ from(
92
+ p in subquery(sub),
93
+ # other filtering etc here
94
+ )
95
+
96
+ Please note that the `Ecto.Query.subquery/2` is needed here to convert the
97
+ `Ecto.Query` into an instance of `Ecto.SubQuery`. This protocol then wraps
98
+ it into an `Ecto.Query`, but using the provided subquery in the FROM clause.
99
+ Please see `Ecto.Query.subquery/2` for more information.
100
+ """
101
+
102
+ @doc """
103
+ Converts the given `data` into an `Ecto.Query`.
104
+ """
105
+ def to_query(data)
106
+ end
107
+
108
+ defimpl Ecto.Queryable, for: Ecto.Query do
109
+ def to_query(query), do: query
110
+ end
111
+
112
+ defimpl Ecto.Queryable, for: Ecto.SubQuery do
113
+ def to_query(subquery) do
114
+ %Ecto.Query{from: %Ecto.Query.FromExpr{source: subquery}}
115
+ end
116
+ end
117
+
118
+ defimpl Ecto.Queryable, for: BitString do
119
+ def to_query(source) when is_binary(source) do
120
+ %Ecto.Query{from: %Ecto.Query.FromExpr{source: {source, nil}}}
121
+ end
122
+ end
123
+
124
+ defimpl Ecto.Queryable, for: Atom do
125
+ def to_query(module) do
126
+ try do
127
+ module.__schema__(:query)
128
+ rescue
129
+ UndefinedFunctionError ->
130
+ message =
131
+ if :code.is_loaded(module) do
132
+ "the given module does not provide a schema"
133
+ else
134
+ "the given module does not exist"
135
+ end
136
+
137
+ raise Protocol.UndefinedError, protocol: @protocol, value: module, description: message
138
+
139
+ FunctionClauseError ->
140
+ raise Protocol.UndefinedError, protocol: @protocol, value: module, description: "the given module is an embedded schema"
141
+ end
142
+ end
143
+ end
144
+
145
+ defimpl Ecto.Queryable, for: Tuple do
146
+ def to_query({source, schema} = from)
147
+ when is_binary(source) and is_atom(schema) and not is_nil(schema) do
148
+ %Ecto.Query{from: %Ecto.Query.FromExpr{source: from, prefix: schema.__schema__(:prefix)}}
149
+ end
150
+ end
deps/ecto/lib/ecto/repo.ex ADDED
@@ -0,0 +1,2227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Repo do
2
+ @moduledoc """
3
+ Defines a repository.
4
+
5
+ A repository maps to an underlying data store, controlled by the
6
+ adapter. For example, Ecto ships with a Postgres adapter that
7
+ stores data into a PostgreSQL database.
8
+
9
+ When used, the repository expects the `:otp_app` and `:adapter` as
10
+ option. The `:otp_app` should point to an OTP application that has
11
+ the repository configuration. For example, the repository:
12
+
13
+ defmodule Repo do
14
+ use Ecto.Repo,
15
+ otp_app: :my_app,
16
+ adapter: Ecto.Adapters.Postgres
17
+ end
18
+
19
+ Could be configured with:
20
+
21
+ config :my_app, Repo,
22
+ database: "ecto_simple",
23
+ username: "postgres",
24
+ password: "postgres",
25
+ hostname: "localhost"
26
+
27
+ Most of the configuration that goes into the `config` is specific
28
+ to the adapter. For this particular example, you can check
29
+ [`Ecto.Adapters.Postgres`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.Postgres.html)
30
+ for more information. In spite of this, the following configuration values
31
+ are common across all adapters:
32
+
33
+ * `:name`- The name of the Repo supervisor process
34
+
35
+ * `:priv` - the directory where to keep repository data, like
36
+ migrations, schema and more. Defaults to "priv/YOUR_REPO".
37
+ It must always point to a subdirectory inside the priv directory
38
+
39
+ * `:url` - an URL that specifies storage information. Read below
40
+ for more information
41
+
42
+ * `:log` - the log level used when logging the query with Elixir's
43
+ Logger. Can be any of `Logger.level/0` values or `false`. If false,
44
+ disables logging for that repository. Defaults to `:debug`
45
+
46
+ * `:pool_size` - the size of the pool used by the connection module.
47
+ Defaults to `10`
48
+
49
+ * `:pool_count` - the number of pools to run concurrently,
50
+ increase this option when the pool itself may be under contention.
51
+ When running multiple pools, queries are randomly routed to different
52
+ pools, without taking into account how many connections are available
53
+ in each. So in some circumstances, you may be routed to a fully busy
54
+ pool while others have connections available. The overall number of
55
+ connections used will be `pool_size * pool_count`. Defaults to `1`
56
+
57
+ * `:telemetry_prefix` - we recommend adapters to publish events
58
+ using the [Telemetry](`:telemetry`) library. By default, the telemetry prefix
59
+ is based on the module name, so if your module is called
60
+ `MyApp.Repo`, the prefix will be `[:my_app, :repo]`. See the
61
+ ["Telemetry Events"](#module-telemetry-events) section to see which events we recommend
62
+ adapters to publish. Note that if you have multiple databases, you
63
+ should keep the `:telemetry_prefix` consistent for each repo and
64
+ use the `:repo` property in the event metadata for distinguishing
65
+ between repos.
66
+
67
+ * `:stacktrace`- when true, publishes the stacktrace in telemetry events
68
+ and allows more advanced logging.
69
+
70
+ ## URLs
71
+
72
+ Repositories by default support URLs. For example, the configuration
73
+ above could be rewritten to:
74
+
75
+ config :my_app, Repo,
76
+ url: "ecto://postgres:postgres@localhost/ecto_simple"
77
+
78
+ The schema can be of any value and the path represents the database name.
79
+ The URL will be used generate the relevant Repo configuration values, such
80
+ as `:database`, `:username`, `:password`, `:hostname` and `:port`. These
81
+ values take precedence over those already specified in the Repo's configuration.
82
+
83
+ URL can include query parameters to override shared and adapter-specific
84
+ options, like `ssl`, `timeout` and `pool_size`. The following example
85
+ shows how to pass these configuration values:
86
+
87
+ config :my_app, Repo,
88
+ url: "ecto://postgres:postgres@localhost/ecto_simple?ssl=true&pool_size=10"
89
+
90
+ ## Shared options
91
+
92
+ Almost all of the repository functions outlined in this module accept the following
93
+ options:
94
+
95
+ * `:timeout` - The time in milliseconds (as an integer) to wait for the query call to
96
+ finish. `:infinity` will wait indefinitely (default: `15_000`)
97
+ * `:log` - Can be any of the `Logger.level/0` values or `false`. If `false`,
98
+ logging is disabled. Defaults to the configured Repo logger level
99
+ * `:telemetry_event` - The telemetry event name to dispatch the event under.
100
+ See the next section for more information
101
+ * `:telemetry_options` - Extra options to attach to telemetry event name.
102
+ See the next section for more information
103
+
104
+ ## Adapter-Specific Errors
105
+
106
+ Many of the functions in this module may raise adapter-specific errors, such as `PostgrexError`.
107
+ This can happen, for example, when the underlying database cannot execute the specified query.
108
+
109
+ ## Telemetry events
110
+
111
+ There are two types of telemetry events. The ones emitted by Ecto and the
112
+ ones that are adapter specific.
113
+
114
+ ### Ecto telemetry events
115
+
116
+ The following events are emitted by all Ecto repositories:
117
+
118
+ * `[:ecto, :repo, :init]` - it is invoked whenever a repository starts.
119
+ The measurement is a single `system_time` entry in native unit. The
120
+ metadata is the `:repo` and all initialization options under `:opts`.
121
+
122
+ ### Adapter-specific events
123
+
124
+ We recommend adapters to publish certain `Telemetry` events listed below.
125
+ Those events will use the `:telemetry_prefix` outlined above which defaults
126
+ to `[:my_app, :repo]`.
127
+
128
+ For instance, to receive all query events published by a repository called
129
+ `MyApp.Repo`, one would define a module:
130
+
131
+ defmodule MyApp.Telemetry do
132
+ def handle_event([:my_app, :repo, :query], measurements, metadata, config) do
133
+ IO.inspect binding()
134
+ end
135
+ end
136
+
137
+ Then, in the `Application.start/2` callback, attach the handler to this event using
138
+ a unique handler id:
139
+
140
+ :ok = :telemetry.attach("my-app-handler-id", [:my_app, :repo, :query], &MyApp.Telemetry.handle_event/4, %{})
141
+
142
+ For details, see [the telemetry documentation](https://hexdocs.pm/telemetry/).
143
+
144
+ Below we list all events developers should expect from Ecto. All examples
145
+ below consider a repository named `MyApp.Repo`:
146
+
147
+ #### `[:my_app, :repo, :query]`
148
+
149
+ This event should be invoked on every query sent to the adapter, including
150
+ queries that are related to the transaction management.
151
+
152
+ The `:measurements` map may include the following, all given in the
153
+ `:native` time unit:
154
+
155
+ * `:idle_time` - the time the connection spent waiting before being checked out for the query
156
+ * `:queue_time` - the time spent waiting to check out a database connection
157
+ * `:query_time` - the time spent executing the query
158
+ * `:decode_time` - the time spent decoding the data received from the database
159
+ * `:total_time` - the sum of (`queue_time`, `query_time`, and `decode_time`)️
160
+
161
+ All measurements are given in the `:native` time unit. You can read more
162
+ about it in the docs for `System.convert_time_unit/3`.
163
+
164
+ A telemetry `:metadata` map including the following fields. Each database
165
+ adapter may emit different information here. For Ecto.SQL databases, it
166
+ will look like this:
167
+
168
+ * `:type` - the type of the Ecto query. For example, for Ecto.SQL
169
+ databases, it would be `:ecto_sql_query`
170
+ * `:repo` - the Ecto repository
171
+ * `:result` - the query result
172
+ * `:params` - the dumped query parameters (formatted for database drivers like Postgrex)
173
+ * `:cast_params` - the casted query parameters (normalized before dumping)
174
+ * `:query` - the query sent to the database as a string
175
+ * `:source` - the source the query was made on (may be `nil`)
176
+ * `:stacktrace` - the stacktrace information, if enabled, or `nil`
177
+ * `:options` - extra options given to the repo operation under
178
+ `:telemetry_options`
179
+
180
+ ## Read-only repositories
181
+
182
+ You can mark a repository as read-only by passing the `:read_only`
183
+ flag on `use`:
184
+
185
+ use Ecto.Repo, otp_app: ..., adapter: ..., read_only: true
186
+
187
+ By passing the `:read_only` option, none of the functions that perform
188
+ write operations, such as `c:insert/2`, `c:insert_all/3`, `c:update_all/3`,
189
+ and friends will be defined.
190
+ """
191
+
192
+ @type t :: module
193
+
194
+ @doc """
195
+ Returns all running Ecto repositories.
196
+
197
+ The list is returned in no particular order. The list
198
+ contains either atoms, for named Ecto repositories, or
199
+ PIDs.
200
+ """
201
+ @spec all_running() :: [atom() | pid()]
202
+ defdelegate all_running(), to: Ecto.Repo.Registry
203
+
204
+ @doc false
205
+ defmacro __using__(opts) do
206
+ quote bind_quoted: [opts: opts] do
207
+ @behaviour Ecto.Repo
208
+
209
+ {otp_app, adapter, behaviours} =
210
+ Ecto.Repo.Supervisor.compile_config(__MODULE__, opts)
211
+
212
+ @otp_app otp_app
213
+ @adapter adapter
214
+ @default_dynamic_repo opts[:default_dynamic_repo] || __MODULE__
215
+ @read_only opts[:read_only] || false
216
+ @before_compile adapter
217
+ @aggregates [:count, :avg, :max, :min, :sum]
218
+
219
+ def config do
220
+ {:ok, config} = Ecto.Repo.Supervisor.init_config(:runtime, __MODULE__, @otp_app, [])
221
+ config
222
+ end
223
+
224
+ def __adapter__ do
225
+ @adapter
226
+ end
227
+
228
+ def child_spec(opts) do
229
+ %{
230
+ id: __MODULE__,
231
+ start: {__MODULE__, :start_link, [opts]},
232
+ type: :supervisor
233
+ }
234
+ end
235
+
236
+ def start_link(opts \\ []) do
237
+ Ecto.Repo.Supervisor.start_link(__MODULE__, @otp_app, @adapter, opts)
238
+ end
239
+
240
+ def stop(timeout \\ 5000) do
241
+ Supervisor.stop(get_dynamic_repo(), :normal, timeout)
242
+ end
243
+
244
+ def load(schema_or_types, data) do
245
+ Ecto.Repo.Schema.load(@adapter, schema_or_types, data)
246
+ end
247
+
248
+ def checkout(fun, opts \\ []) when is_function(fun) do
249
+ %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(get_dynamic_repo())
250
+ adapter.checkout(meta, opts, fun)
251
+ end
252
+
253
+ def checked_out? do
254
+ %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(get_dynamic_repo())
255
+ adapter.checked_out?(meta)
256
+ end
257
+
258
+ @compile {:inline, get_dynamic_repo: 0}
259
+
260
+ def get_dynamic_repo() do
261
+ Process.get({__MODULE__, :dynamic_repo}, @default_dynamic_repo)
262
+ end
263
+
264
+ def put_dynamic_repo(dynamic) when is_atom(dynamic) or is_pid(dynamic) do
265
+ Process.put({__MODULE__, :dynamic_repo}, dynamic) || @default_dynamic_repo
266
+ end
267
+
268
+ def default_options(_operation), do: []
269
+ defoverridable default_options: 1
270
+
271
+ defp prepare_opts(operation_name, []), do: default_options(operation_name)
272
+
273
+ defp prepare_opts(operation_name, [{key, _} | _rest] = opts) when is_atom(key) do
274
+ operation_name
275
+ |> default_options()
276
+ |> Keyword.merge(opts)
277
+ end
278
+
279
+ ## Transactions
280
+
281
+ if Ecto.Adapter.Transaction in behaviours do
282
+ def transaction(fun_or_multi, opts \\ []) do
283
+ repo = get_dynamic_repo()
284
+
285
+ Ecto.Repo.Transaction.transaction(
286
+ __MODULE__,
287
+ repo,
288
+ fun_or_multi,
289
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:transaction, opts))
290
+ )
291
+ end
292
+
293
+ def in_transaction? do
294
+ Ecto.Repo.Transaction.in_transaction?(get_dynamic_repo())
295
+ end
296
+
297
+ @spec rollback(term) :: no_return
298
+ def rollback(value) do
299
+ Ecto.Repo.Transaction.rollback(get_dynamic_repo(), value)
300
+ end
301
+ end
302
+
303
+ ## Schemas
304
+
305
+ if Ecto.Adapter.Schema in behaviours and not @read_only do
306
+ def insert(struct, opts \\ []) do
307
+ repo = get_dynamic_repo()
308
+
309
+ Ecto.Repo.Schema.insert(
310
+ __MODULE__,
311
+ repo,
312
+ struct,
313
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert, opts))
314
+ )
315
+ end
316
+
317
+ def update(struct, opts \\ []) do
318
+ repo = get_dynamic_repo()
319
+
320
+ Ecto.Repo.Schema.update(
321
+ __MODULE__,
322
+ repo,
323
+ struct,
324
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update, opts))
325
+ )
326
+ end
327
+
328
+ def insert_or_update(changeset, opts \\ []) do
329
+ repo = get_dynamic_repo()
330
+
331
+ Ecto.Repo.Schema.insert_or_update(
332
+ __MODULE__,
333
+ repo,
334
+ changeset,
335
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_or_update, opts))
336
+ )
337
+ end
338
+
339
+ def delete(struct, opts \\ []) do
340
+ repo = get_dynamic_repo()
341
+
342
+ Ecto.Repo.Schema.delete(
343
+ __MODULE__,
344
+ repo,
345
+ struct,
346
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete, opts))
347
+ )
348
+ end
349
+
350
+ def insert!(struct, opts \\ []) do
351
+ repo = get_dynamic_repo()
352
+
353
+ Ecto.Repo.Schema.insert!(
354
+ __MODULE__,
355
+ repo,
356
+ struct,
357
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert, opts))
358
+ )
359
+ end
360
+
361
+ def update!(struct, opts \\ []) do
362
+ repo = get_dynamic_repo()
363
+
364
+ Ecto.Repo.Schema.update!(
365
+ __MODULE__,
366
+ repo,
367
+ struct,
368
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update, opts))
369
+ )
370
+ end
371
+
372
+ def insert_or_update!(changeset, opts \\ []) do
373
+ repo = get_dynamic_repo()
374
+
375
+ Ecto.Repo.Schema.insert_or_update!(
376
+ __MODULE__,
377
+ repo,
378
+ changeset,
379
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_or_update, opts))
380
+ )
381
+ end
382
+
383
+ def delete!(struct, opts \\ []) do
384
+ repo = get_dynamic_repo()
385
+
386
+ Ecto.Repo.Schema.delete!(
387
+ __MODULE__,
388
+ repo,
389
+ struct,
390
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete, opts))
391
+ )
392
+ end
393
+
394
+ def insert_all(schema_or_source, entries, opts \\ []) do
395
+ repo = get_dynamic_repo()
396
+
397
+ Ecto.Repo.Schema.insert_all(
398
+ __MODULE__,
399
+ repo,
400
+ schema_or_source,
401
+ entries,
402
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_all, opts))
403
+ )
404
+ end
405
+ end
406
+
407
+ ## Queryable
408
+
409
+ if Ecto.Adapter.Queryable in behaviours do
410
+ if not @read_only do
411
+ def update_all(queryable, updates, opts \\ []) do
412
+ repo = get_dynamic_repo()
413
+
414
+ Ecto.Repo.Queryable.update_all(
415
+ repo,
416
+ queryable,
417
+ updates,
418
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update_all, opts))
419
+ )
420
+ end
421
+
422
+ def delete_all(queryable, opts \\ []) do
423
+ repo = get_dynamic_repo()
424
+
425
+ Ecto.Repo.Queryable.delete_all(
426
+ repo,
427
+ queryable,
428
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete_all, opts))
429
+ )
430
+ end
431
+ end
432
+
433
+ def all(queryable, opts \\ []) do
434
+ repo = get_dynamic_repo()
435
+
436
+ Ecto.Repo.Queryable.all(
437
+ repo,
438
+ queryable,
439
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
440
+ )
441
+ end
442
+
443
+ def stream(queryable, opts \\ []) do
444
+ repo = get_dynamic_repo()
445
+
446
+ Ecto.Repo.Queryable.stream(
447
+ repo,
448
+ queryable,
449
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:stream, opts))
450
+ )
451
+ end
452
+
453
+ def get(queryable, id, opts \\ []) do
454
+ repo = get_dynamic_repo()
455
+
456
+ Ecto.Repo.Queryable.get(
457
+ repo,
458
+ queryable,
459
+ id,
460
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
461
+ )
462
+ end
463
+
464
+ def get!(queryable, id, opts \\ []) do
465
+ repo = get_dynamic_repo()
466
+
467
+ Ecto.Repo.Queryable.get!(
468
+ repo,
469
+ queryable,
470
+ id,
471
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
472
+ )
473
+ end
474
+
475
+ def get_by(queryable, clauses, opts \\ []) do
476
+ repo = get_dynamic_repo()
477
+
478
+ Ecto.Repo.Queryable.get_by(
479
+ repo,
480
+ queryable,
481
+ clauses,
482
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
483
+ )
484
+ end
485
+
486
+ def get_by!(queryable, clauses, opts \\ []) do
487
+ repo = get_dynamic_repo()
488
+
489
+ Ecto.Repo.Queryable.get_by!(
490
+ repo,
491
+ queryable,
492
+ clauses,
493
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
494
+ )
495
+ end
496
+
497
+ def reload(queryable, opts \\ []) do
498
+ repo = get_dynamic_repo()
499
+
500
+ Ecto.Repo.Queryable.reload(
501
+ repo,
502
+ queryable,
503
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:reload, opts))
504
+ )
505
+ end
506
+
507
+ def reload!(queryable, opts \\ []) do
508
+ repo = get_dynamic_repo()
509
+
510
+ Ecto.Repo.Queryable.reload!(
511
+ repo,
512
+ queryable,
513
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:reload, opts))
514
+ )
515
+ end
516
+
517
+ def one(queryable, opts \\ []) do
518
+ repo = get_dynamic_repo()
519
+
520
+ Ecto.Repo.Queryable.one(
521
+ repo,
522
+ queryable,
523
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
524
+ )
525
+ end
526
+
527
+ def one!(queryable, opts \\ []) do
528
+ repo = get_dynamic_repo()
529
+
530
+ Ecto.Repo.Queryable.one!(
531
+ repo,
532
+ queryable,
533
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
534
+ )
535
+ end
536
+
537
+ def aggregate(queryable, aggregate, opts \\ [])
538
+
539
+ def aggregate(queryable, aggregate, opts)
540
+ when aggregate in [:count] and is_list(opts) do
541
+ repo = get_dynamic_repo()
542
+
543
+ Ecto.Repo.Queryable.aggregate(
544
+ repo,
545
+ queryable,
546
+ aggregate,
547
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
548
+ )
549
+ end
550
+
551
+ def aggregate(queryable, aggregate, field)
552
+ when aggregate in @aggregates and is_atom(field) do
553
+ repo = get_dynamic_repo()
554
+
555
+ Ecto.Repo.Queryable.aggregate(
556
+ repo,
557
+ queryable,
558
+ aggregate,
559
+ field,
560
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, []))
561
+ )
562
+ end
563
+
564
+ def aggregate(queryable, aggregate, field, opts)
565
+ when aggregate in @aggregates and is_atom(field) and is_list(opts) do
566
+ repo = get_dynamic_repo()
567
+
568
+ Ecto.Repo.Queryable.aggregate(
569
+ repo,
570
+ queryable,
571
+ aggregate,
572
+ field,
573
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
574
+ )
575
+ end
576
+
577
+ def exists?(queryable, opts \\ []) do
578
+ repo = get_dynamic_repo()
579
+
580
+ Ecto.Repo.Queryable.exists?(
581
+ repo,
582
+ queryable,
583
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))
584
+ )
585
+ end
586
+
587
+ def preload(struct_or_structs_or_nil, preloads, opts \\ []) do
588
+ repo = get_dynamic_repo()
589
+
590
+ Ecto.Repo.Preloader.preload(
591
+ struct_or_structs_or_nil,
592
+ repo,
593
+ preloads,
594
+ Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:preload, opts))
595
+ )
596
+ end
597
+
598
+ def prepare_query(operation, query, opts), do: {query, opts}
599
+ defoverridable prepare_query: 3
600
+ end
601
+ end
602
+ end
603
+
604
+ ## User callbacks
605
+
606
+ @optional_callbacks init: 2
607
+
608
+ @doc """
609
+ A callback executed when the repo starts or when configuration is read.
610
+
611
+ This callback is available for backwards compatibility purposes. Most
612
+ runtime configuration in Elixir today can be done via config/runtime.exs.
613
+
614
+ The first argument is the context the callback is being invoked. If it
615
+ is called because the Repo supervisor is starting, it will be `:supervisor`.
616
+ It will be `:runtime` if it is called for reading configuration without
617
+ actually starting a process.
618
+
619
+ The second argument is the repository configuration as stored in the
620
+ application environment. It must return `{:ok, keyword}` with the updated
621
+ list of configuration or `:ignore` (only in the `:supervisor` case).
622
+ """
623
+ @doc group: "User callbacks"
624
+ @callback init(context :: :supervisor | :runtime, config :: Keyword.t()) ::
625
+ {:ok, Keyword.t()} | :ignore
626
+
627
+ ## Ecto.Adapter
628
+
629
+ @doc """
630
+ Returns the adapter tied to the repository.
631
+ """
632
+ @doc group: "Config API"
633
+ @callback __adapter__ :: Ecto.Adapter.t()
634
+
635
+ @doc """
636
+ Returns the adapter configuration stored in the `:otp_app` environment.
637
+
638
+ If the `c:init/2` callback is implemented in the repository,
639
+ it will be invoked with the first argument set to `:runtime`.
640
+ It does not consider the options given on `c:start_link/1`.
641
+ """
642
+ @doc group: "Config API"
643
+ @callback config() :: Keyword.t()
644
+
645
+ @doc """
646
+ Starts the Repo supervision tree.
647
+
648
+ Returns `{:error, {:already_started, pid}}` if the repo is already
649
+ started or `{:error, term}` in case anything else goes wrong.
650
+
651
+ ## Options
652
+
653
+ See the configuration in the moduledoc for options shared between adapters,
654
+ for adapter-specific configuration see the adapter's documentation.
655
+ """
656
+ @doc group: "Process API"
657
+ @callback start_link(opts :: Keyword.t()) ::
658
+ {:ok, pid}
659
+ | {:error, {:already_started, pid}}
660
+ | {:error, term}
661
+
662
+ @doc """
663
+ Shuts down the repository.
664
+ """
665
+ @doc group: "Process API"
666
+ @callback stop(timeout) :: :ok
667
+
668
+ @doc """
669
+ Checks out a connection for the duration of the function.
670
+
671
+ It returns the result of the function. This is useful when
672
+ you need to perform multiple operations against the repository
673
+ in a row and you want to avoid checking out the connection
674
+ multiple times.
675
+
676
+ `checkout/2` and `transaction/2` can be combined and nested
677
+ multiple times. If `checkout/2` is called inside the function
678
+ of another `checkout/2` call, the function is simply executed,
679
+ without checking out a new connection.
680
+
681
+ ## Options
682
+
683
+ See the ["Shared options"](#module-shared-options) section at the module
684
+ documentation for more options.
685
+ """
686
+ @doc group: "Transaction API"
687
+ @callback checkout((-> result), opts :: Keyword.t()) :: result when result: var
688
+
689
+ @doc """
690
+ Returns true if a connection has been checked out.
691
+
692
+ This is true if inside a `c:Ecto.Repo.checkout/2` or
693
+ `c:Ecto.Repo.transaction/2`.
694
+
695
+ ## Examples
696
+
697
+ MyRepo.checked_out?
698
+ #=> false
699
+
700
+ MyRepo.transaction(fn ->
701
+ MyRepo.checked_out? #=> true
702
+ end)
703
+
704
+ MyRepo.checkout(fn ->
705
+ MyRepo.checked_out? #=> true
706
+ end)
707
+
708
+ """
709
+ @doc group: "Transaction API"
710
+ @callback checked_out?() :: boolean
711
+
712
+ @doc """
713
+ Loads `data` into a schema or a map.
714
+
715
+ The first argument can be a schema module or a map (of types).
716
+ The first argument determines the return value: a struct or a map,
717
+ respectively.
718
+
719
+ The second argument `data` specifies fields and values that are to be loaded.
720
+ It can be a map, a keyword list, or a `{fields, values}` tuple.
721
+ Fields can be atoms or strings.
722
+
723
+ Fields that are not present in the schema (or `types` map) are ignored.
724
+ If any of the values has invalid type, an error is raised.
725
+
726
+ To load data from non-database sources, use `Ecto.embedded_load/3`.
727
+
728
+ ## Examples
729
+
730
+ iex> MyRepo.load(User, %{name: "Alice", age: 25})
731
+ %User{name: "Alice", age: 25}
732
+
733
+ iex> MyRepo.load(User, [name: "Alice", age: 25])
734
+ %User{name: "Alice", age: 25}
735
+
736
+ `data` can also take form of `{fields, values}`:
737
+
738
+ iex> MyRepo.load(User, {[:name, :age], ["Alice", 25]})
739
+ %User{name: "Alice", age: 25, ...}
740
+
741
+ The first argument can also be a `types` map:
742
+
743
+ iex> types = %{name: :string, age: :integer}
744
+ iex> MyRepo.load(types, %{name: "Alice", age: 25})
745
+ %{name: "Alice", age: 25}
746
+
747
+ This function is especially useful when parsing raw query results:
748
+
749
+ iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT * FROM users", [])
750
+ iex> Enum.map(result.rows, &MyRepo.load(User, {result.columns, &1}))
751
+ [%User{...}, ...]
752
+
753
+ """
754
+ @doc group: "Schema API"
755
+ @callback load(
756
+ schema_or_map :: module | map(),
757
+ data :: map() | Keyword.t() | {list, list}
758
+ ) :: Ecto.Schema.t() | map()
759
+
760
+ @doc """
761
+ Returns the atom name or pid of the current repository.
762
+
763
+ See `c:put_dynamic_repo/1` for more information.
764
+ """
765
+ @doc group: "Process API"
766
+ @callback get_dynamic_repo() :: atom() | pid()
767
+
768
+ @doc """
769
+ Sets the dynamic repository to be used in further interactions.
770
+
771
+ Sometimes you may want a single Ecto repository to talk to
772
+ many different database instances. By default, when you call
773
+ `MyApp.Repo.start_link/1`, it will start a repository with
774
+ name `MyApp.Repo`. But if you want to start multiple repositories,
775
+ you can give each of them a different name:
776
+
777
+ MyApp.Repo.start_link(name: :tenant_foo, hostname: "foo.example.com")
778
+ MyApp.Repo.start_link(name: :tenant_bar, hostname: "bar.example.com")
779
+
780
+ You can also start repositories without names by explicitly
781
+ setting the name to nil:
782
+
783
+ MyApp.Repo.start_link(name: nil, hostname: "temp.example.com")
784
+
785
+ However, once the repository is started, you can't directly interact with
786
+ it, since all operations in `MyApp.Repo` are sent by default to the repository
787
+ named `MyApp.Repo`. You can change the default repo at compile time with:
788
+
789
+ use Ecto.Repo, default_dynamic_repo: :name_of_repo
790
+
791
+ Or you can change it anytime at runtime by calling `put_dynamic_repo/1`:
792
+
793
+ MyApp.Repo.put_dynamic_repo(:tenant_foo)
794
+
795
+ From this moment on, all future queries done by the current process will
796
+ run on `:tenant_foo`.
797
+ """
798
+ @doc group: "Process API"
799
+ @callback put_dynamic_repo(name_or_pid :: atom() | pid()) :: atom() | pid()
800
+
801
+ ## Ecto.Adapter.Queryable
802
+
803
+ @optional_callbacks get: 3,
804
+ get!: 3,
805
+ get_by: 3,
806
+ get_by!: 3,
807
+ reload: 2,
808
+ reload!: 2,
809
+ aggregate: 3,
810
+ aggregate: 4,
811
+ exists?: 2,
812
+ one: 2,
813
+ one!: 2,
814
+ preload: 3,
815
+ all: 2,
816
+ stream: 2,
817
+ update_all: 3,
818
+ delete_all: 2
819
+
820
+ @doc """
821
+ Fetches a single struct from the data store where the primary key matches the
822
+ given id.
823
+
824
+ Returns `nil` if no result was found. If the struct in the queryable
825
+ has no or more than one primary key, it will raise an argument error.
826
+
827
+ ## Options
828
+
829
+ * `:prefix` - The prefix to run the query on (such as the schema path
830
+ in Postgres or the database in MySQL). This will be applied to all `from`
831
+ and `join`s in the query that did not have a prefix previously given
832
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
833
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
834
+ `Ecto.Query` documentation.
835
+
836
+ See the ["Shared options"](#module-shared-options) section at the module
837
+ documentation for more options.
838
+
839
+ ## Example
840
+
841
+ MyRepo.get(Post, 42)
842
+
843
+ MyRepo.get(Post, 42, prefix: "public")
844
+
845
+ """
846
+ @doc group: "Query API"
847
+ @callback get(queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t()) ::
848
+ Ecto.Schema.t() | term | nil
849
+
850
+ @doc """
851
+ Similar to `c:get/3` but raises `Ecto.NoResultsError` if no record was found.
852
+
853
+ ## Options
854
+
855
+ * `:prefix` - The prefix to run the query on (such as the schema path
856
+ in Postgres or the database in MySQL). This will be applied to all `from`
857
+ and `join`s in the query that did not have a prefix previously given
858
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
859
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
860
+ `Ecto.Query` documentation.
861
+
862
+ See the ["Shared options"](#module-shared-options) section at the module
863
+ documentation for more options.
864
+
865
+ ## Example
866
+
867
+ MyRepo.get!(Post, 42)
868
+
869
+ MyRepo.get!(Post, 42, prefix: "public")
870
+
871
+ """
872
+ @doc group: "Query API"
873
+ @callback get!(queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t()) ::
874
+ Ecto.Schema.t() | term
875
+
876
+ @doc """
877
+ Fetches a single result from the query.
878
+
879
+ Returns `nil` if no result was found. Raises if more than one entry.
880
+
881
+ ## Options
882
+
883
+ * `:prefix` - The prefix to run the query on (such as the schema path
884
+ in Postgres or the database in MySQL). This will be applied to all `from`
885
+ and `join`s in the query that did not have a prefix previously given
886
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
887
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
888
+ `Ecto.Query` documentation.
889
+
890
+ See the ["Shared options"](#module-shared-options) section at the module
891
+ documentation for more options.
892
+
893
+ ## Example
894
+
895
+ MyRepo.get_by(Post, title: "My post")
896
+
897
+ MyRepo.get_by(Post, [title: "My post"], prefix: "public")
898
+
899
+ """
900
+ @doc group: "Query API"
901
+ @callback get_by(
902
+ queryable :: Ecto.Queryable.t(),
903
+ clauses :: Keyword.t() | map,
904
+ opts :: Keyword.t()
905
+ ) :: Ecto.Schema.t() | term | nil
906
+
907
+ @doc """
908
+ Similar to `c:get_by/3` but raises `Ecto.NoResultsError` if no record was found.
909
+
910
+ Raises if more than one entry.
911
+
912
+ ## Options
913
+
914
+ * `:prefix` - The prefix to run the query on (such as the schema path
915
+ in Postgres or the database in MySQL). This will be applied to all `from`
916
+ and `join`s in the query that did not have a prefix previously given
917
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
918
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
919
+ `Ecto.Query` documentation.
920
+
921
+ See the ["Shared options"](#module-shared-options) section at the module
922
+ documentation for more options.
923
+
924
+ ## Example
925
+
926
+ MyRepo.get_by!(Post, title: "My post")
927
+
928
+ MyRepo.get_by!(Post, [title: "My post"], prefix: "public")
929
+
930
+ """
931
+ @doc group: "Query API"
932
+ @callback get_by!(
933
+ queryable :: Ecto.Queryable.t(),
934
+ clauses :: Keyword.t() | map,
935
+ opts :: Keyword.t()
936
+ ) :: Ecto.Schema.t() | term
937
+
938
+ @doc """
939
+ Reloads a given schema or schema list from the database.
940
+
941
+ When using with lists, it is expected that all of the structs in the list belong
942
+ to the same schema. Ordering is guaranteed to be kept. Results not found in
943
+ the database will be returned as `nil`.
944
+
945
+ ## Example
946
+
947
+ MyRepo.reload(post)
948
+ %Post{}
949
+
950
+ MyRepo.reload([post1, post2])
951
+ [%Post{}, %Post{}]
952
+
953
+ MyRepo.reload([deleted_post, post1])
954
+ [nil, %Post{}]
955
+ """
956
+ @doc group: "Schema API"
957
+ @callback reload(
958
+ struct_or_structs :: Ecto.Schema.t() | [Ecto.Schema.t()],
959
+ opts :: Keyword.t()
960
+ ) :: Ecto.Schema.t() | [Ecto.Schema.t() | nil] | nil
961
+
962
+ @doc """
963
+ Similar to `c:reload/2`, but raises when something is not found.
964
+
965
+ When using with lists, ordering is guaranteed to be kept.
966
+
967
+ ## Example
968
+
969
+ MyRepo.reload!(post)
970
+ %Post{}
971
+
972
+ MyRepo.reload!([post1, post2])
973
+ [%Post{}, %Post{}]
974
+ """
975
+ @doc group: "Schema API"
976
+ @callback reload!(struct_or_structs, opts :: Keyword.t()) :: struct_or_structs
977
+ when struct_or_structs: Ecto.Schema.t() | [Ecto.Schema.t()]
978
+
979
+ @doc """
980
+ Calculate the given `aggregate`.
981
+
982
+ If the query has a limit, offset, distinct or combination set, it will be
983
+ automatically wrapped in a subquery in order to return the
984
+ proper result.
985
+
986
+ Any preload or select in the query will be ignored in favor of
987
+ the column being aggregated.
988
+
989
+ The aggregation will fail if any `group_by` field is set.
990
+
991
+ ## Options
992
+
993
+ * `:prefix` - The prefix to run the query on (such as the schema path
994
+ in Postgres or the database in MySQL). This will be applied to all `from`
995
+ and `join`s in the query that did not have a prefix previously given
996
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
997
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
998
+ `Ecto.Query` documentation.
999
+
1000
+ See the ["Shared options"](#module-shared-options) section at the module
1001
+ documentation for more options.
1002
+
1003
+ ## Examples
1004
+
1005
+ # Returns the number of blog posts
1006
+ Repo.aggregate(Post, :count)
1007
+
1008
+ # Returns the number of blog posts in the "private" schema path
1009
+ # (in Postgres) or database (in MySQL)
1010
+ Repo.aggregate(Post, :count, prefix: "private")
1011
+
1012
+ """
1013
+ @doc group: "Query API"
1014
+ @callback aggregate(
1015
+ queryable :: Ecto.Queryable.t(),
1016
+ aggregate :: :count,
1017
+ opts :: Keyword.t()
1018
+ ) :: term | nil
1019
+
1020
+ @doc """
1021
+ Calculate the given `aggregate` over the given `field`.
1022
+
1023
+ See `c:aggregate/3` for general considerations and options.
1024
+
1025
+ ## Examples
1026
+
1027
+ # Returns the sum of the number of visits for every blog post
1028
+ Repo.aggregate(Post, :sum, :visits)
1029
+
1030
+ # Returns the sum of the number of visits for every blog post in the
1031
+ # "private" schema path (in Postgres) or database (in MySQL)
1032
+ Repo.aggregate(Post, :sum, :visits, prefix: "private")
1033
+
1034
+ # Returns the average number of visits for the first 10 blog posts
1035
+ query = from Post, limit: 10
1036
+ Repo.aggregate(query, :avg, :visits)
1037
+ """
1038
+ @doc group: "Query API"
1039
+ @callback aggregate(
1040
+ queryable :: Ecto.Queryable.t(),
1041
+ aggregate :: :avg | :count | :max | :min | :sum,
1042
+ field :: atom,
1043
+ opts :: Keyword.t()
1044
+ ) :: term | nil
1045
+
1046
+ @doc """
1047
+ Checks if there exists an entry that matches the given queryable.
1048
+
1049
+ Returns a boolean.
1050
+
1051
+ ## Options
1052
+
1053
+ * `:prefix` - The prefix to run the query on (such as the schema path
1054
+ in Postgres or the database in MySQL). This will be applied to all `from`
1055
+ and `join`s in the query that did not have a prefix previously given
1056
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1057
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1058
+ `Ecto.Query` documentation.
1059
+
1060
+ See the ["Shared options"](#module-shared-options) section at the module
1061
+ documentation for more options.
1062
+
1063
+ > #### Generated Query {: .info}
1064
+ >
1065
+ > Ecto will take the provided queryable and modify it to reduce its footprint
1066
+ > as much as possible. For example, by forcing `SELECT 1` and `LIMIT 1`. Any
1067
+ > additional filtering must be provided directly on the queryable using expressions
1068
+ > such as `where` and `having`.
1069
+
1070
+ ## Examples
1071
+
1072
+ # checks if any posts exist
1073
+ Repo.exists?(Post)
1074
+
1075
+ # checks if any posts exist in the "private" schema path (in Postgres) or
1076
+ # database (in MySQL)
1077
+ Repo.exists?(Post, prefix: "private")
1078
+
1079
+ # checks if any post with a like count greater than 10 exists
1080
+ query = from p in Post, where: p.like_count > 10
1081
+ Repo.exists?(query)
1082
+ """
1083
+ @doc group: "Query API"
1084
+ @callback exists?(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: boolean()
1085
+
1086
+ @doc """
1087
+ Fetches a single result from the query.
1088
+
1089
+ Returns `nil` if no result was found. Raises if more than one entry.
1090
+
1091
+ ## Options
1092
+
1093
+ * `:prefix` - The prefix to run the query on (such as the schema path
1094
+ in Postgres or the database in MySQL). This will be applied to all `from`
1095
+ and `join`s in the query that did not have a prefix previously given
1096
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1097
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1098
+ `Ecto.Query` documentation.
1099
+
1100
+ See the ["Shared options"](#module-shared-options) section at the module
1101
+ documentation for more options.
1102
+
1103
+ ## Examples
1104
+
1105
+ Repo.one(from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id)
1106
+
1107
+ query = from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id
1108
+ Repo.one(query, prefix: "private")
1109
+ """
1110
+ @doc group: "Query API"
1111
+ @callback one(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) ::
1112
+ Ecto.Schema.t() | term | nil
1113
+
1114
+ @doc """
1115
+ Similar to `c:one/2` but raises `Ecto.NoResultsError` if no record was found.
1116
+
1117
+ Raises if more than one entry.
1118
+
1119
+ ## Options
1120
+
1121
+ * `:prefix` - The prefix to run the query on (such as the schema path
1122
+ in Postgres or the database in MySQL). This will be applied to all `from`
1123
+ and `join`s in the query that did not have a prefix previously given
1124
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1125
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1126
+ `Ecto.Query` documentation.
1127
+
1128
+ See the ["Shared options"](#module-shared-options) section at the module
1129
+ documentation for more options.
1130
+ """
1131
+ @doc group: "Query API"
1132
+ @callback one!(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) ::
1133
+ Ecto.Schema.t() | term
1134
+
1135
+ @doc """
1136
+ Preloads all associations on the given struct or structs.
1137
+
1138
+ This is similar to `Ecto.Query.preload/3` except it allows
1139
+ you to preload structs after they have been fetched from the
1140
+ database.
1141
+
1142
+ In case the association was already loaded, preload won't attempt
1143
+ to reload it. Preload assumes each association has the same nested
1144
+ associations already loaded. If this is not the case, it is
1145
+ possible to lose information. For example:
1146
+
1147
+ comment1 = TestRepo.preload(comment1, [author: [:permalink]])
1148
+ TestRepo.preload([comment1, comment2], :author)
1149
+
1150
+ If both comments are associated to the same author, the first comment
1151
+ will lose its nested `:permalink` association because the second comment
1152
+ does not have it preloaded. To avoid this, you must preload the nested
1153
+ associations as well.
1154
+
1155
+ If you want to reset the loaded fields, see `Ecto.reset_fields/2`.
1156
+
1157
+ ## Options
1158
+
1159
+ * `:force` - By default, Ecto won't preload associations that
1160
+ are already loaded. By setting this option to true, any existing
1161
+ association will be discarded and reloaded.
1162
+ * `:in_parallel` - If the preloads must be done in parallel. It can
1163
+ only be performed when we have more than one preload and the
1164
+ repository is not in a transaction. Defaults to `true`.
1165
+ * `:prefix` - the prefix to fetch preloads from. By default, queries
1166
+ will use the same prefix as the first struct in the given collection.
1167
+ This option allows the prefix to be changed.
1168
+ * `:on_preloader_spawn` - when preloads are done in parallel, this function
1169
+ will be called in the processes that perform the preloads. This can be useful
1170
+ for context propagation for traces.
1171
+
1172
+ See the ["Shared options"](#module-shared-options) section at the module
1173
+ documentation for more options.
1174
+
1175
+ ## Examples
1176
+
1177
+ # Use a single atom to preload an association
1178
+ posts = Repo.preload posts, :comments
1179
+
1180
+ # Use a list of atoms to preload multiple associations
1181
+ posts = Repo.preload posts, [:comments, :authors]
1182
+
1183
+ # Use a keyword list to preload nested associations as well
1184
+ posts = Repo.preload posts, [comments: [:replies, :likes], authors: []]
1185
+
1186
+ # You can mix atoms and keywords, but the atoms must come first
1187
+ posts = Repo.preload posts, [:authors, comments: [:likes, replies: [:reactions]]]
1188
+
1189
+ # Use a keyword list to customize how associations are queried
1190
+ posts = Repo.preload posts, [comments: from(c in Comment, order_by: c.published_at)]
1191
+
1192
+ # Use a two-element tuple for a custom query and nested association definition
1193
+ query = from c in Comment, order_by: c.published_at
1194
+ posts = Repo.preload posts, [comments: {query, [:replies, :likes]}]
1195
+
1196
+ The query given to preload may also preload its own associations.
1197
+ """
1198
+ @doc group: "Schema API"
1199
+ @callback preload(structs_or_struct_or_nil, preloads :: term, opts :: Keyword.t()) ::
1200
+ structs_or_struct_or_nil
1201
+ when structs_or_struct_or_nil: [Ecto.Schema.t()] | Ecto.Schema.t() | nil
1202
+
1203
+ @doc """
1204
+ A user customizable callback invoked for query-based operations.
1205
+
1206
+ This callback can be used to further modify the query and options
1207
+ before it is transformed and sent to the database.
1208
+
1209
+ This callback is invoked for all query APIs, including the `stream`
1210
+ functions. It is also invoked for `insert_all` if a source query is
1211
+ given. It is not invoked for any of the other schema functions.
1212
+
1213
+ ## Examples
1214
+
1215
+ Let's say you want to filter out records that were "soft-deleted"
1216
+ (have `deleted_at` column set) from all operations unless an admin
1217
+ is running the query; you can define the callback like this:
1218
+
1219
+ @impl true
1220
+ def prepare_query(_operation, query, opts) do
1221
+ if opts[:admin] do
1222
+ {query, opts}
1223
+ else
1224
+ query = from(x in query, where: is_nil(x.deleted_at))
1225
+ {query, opts}
1226
+ end
1227
+ end
1228
+
1229
+ And then execute the query:
1230
+
1231
+ Repo.all(query) # only non-deleted records are returned
1232
+ Repo.all(query, admin: true) # all records are returned
1233
+
1234
+ The callback will be invoked for all queries, including queries
1235
+ made from associations and preloads. It is not invoked for each
1236
+ individual join inside a query.
1237
+ """
1238
+ @doc group: "User callbacks"
1239
+ @callback prepare_query(operation, query :: Ecto.Query.t(), opts :: Keyword.t()) ::
1240
+ {Ecto.Query.t(), Keyword.t()}
1241
+ when operation: :all | :update_all | :delete_all | :stream | :insert_all
1242
+
1243
+ @doc """
1244
+ A user customizable callback invoked to retrieve default options
1245
+ for operations.
1246
+
1247
+ This can be used to provide default values per operation that
1248
+ have higher precedence than the values given on configuration
1249
+ or when starting the repository. It can also be used to set
1250
+ query specific options, such as `:prefix`.
1251
+
1252
+ This callback is invoked as the entry point for all repository
1253
+ operations. For example, if you are executing a query with preloads,
1254
+ this callback will be invoked once at the beginning, but the
1255
+ options returned here will be passed to all following operations.
1256
+ """
1257
+ @doc group: "User callbacks"
1258
+ @callback default_options(operation) :: Keyword.t()
1259
+ when operation:
1260
+ :all
1261
+ | :delete
1262
+ | :delete_all
1263
+ | :insert
1264
+ | :insert_all
1265
+ | :insert_or_update
1266
+ | :preload
1267
+ | :reload
1268
+ | :stream
1269
+ | :transaction
1270
+ | :update
1271
+ | :update_all
1272
+ @doc """
1273
+ Fetches all entries from the data store matching the given query.
1274
+
1275
+ May raise `Ecto.QueryError` if query validation fails.
1276
+
1277
+ ## Options
1278
+
1279
+ * `:prefix` - The prefix to run the query on (such as the schema path
1280
+ in Postgres or the database in MySQL). This will be applied to all `from`
1281
+ and `join`s in the query that did not have a prefix previously given
1282
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1283
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1284
+ `Ecto.Query` documentation.
1285
+
1286
+ See the ["Shared options"](#module-shared-options) section at the module
1287
+ documentation for more options.
1288
+
1289
+ ## Example
1290
+
1291
+ # Fetch all post titles
1292
+ query = from p in Post,
1293
+ select: p.title
1294
+ MyRepo.all(query)
1295
+ """
1296
+ @doc group: "Query API"
1297
+ @callback all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: [Ecto.Schema.t() | term]
1298
+
1299
+ @doc """
1300
+ Returns a lazy enumerable that emits all entries from the data store
1301
+ matching the given query.
1302
+
1303
+ SQL adapters, such as Postgres and MySQL, can only enumerate a stream
1304
+ inside a transaction.
1305
+
1306
+ May raise `Ecto.QueryError` if query validation fails.
1307
+
1308
+ ## Options
1309
+
1310
+ * `:prefix` - The prefix to run the query on (such as the schema path
1311
+ in Postgres or the database in MySQL). This will be applied to all `from`
1312
+ and `join`s in the query that did not have a prefix previously given
1313
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1314
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1315
+ `Ecto.Query` documentation.
1316
+
1317
+ * `:max_rows` - The number of rows to load from the database as we stream.
1318
+ It is supported at least by Postgres and MySQL and defaults to 500.
1319
+
1320
+ See the ["Shared options"](#module-shared-options) section at the module
1321
+ documentation for more options.
1322
+
1323
+ ## Example
1324
+
1325
+ # Fetch all post titles
1326
+ query = from p in Post,
1327
+ select: p.title
1328
+ stream = MyRepo.stream(query)
1329
+ MyRepo.transaction(fn ->
1330
+ Enum.to_list(stream)
1331
+ end)
1332
+ """
1333
+ @doc group: "Query API"
1334
+ @callback stream(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: Enum.t()
1335
+
1336
+ @doc """
1337
+ Updates all entries matching the given query with the given values.
1338
+
1339
+ It returns a tuple containing the number of entries and any returned
1340
+ result as second element. The second element is `nil` by default
1341
+ unless a `select` is supplied in the update query. Note, however,
1342
+ not all databases support returning data from UPDATEs.
1343
+
1344
+ Keep in mind this `update_all` will not update autogenerated
1345
+ fields like the `updated_at` columns.
1346
+
1347
+ See `Ecto.Query.update/3` for update operations that can be
1348
+ performed on fields.
1349
+
1350
+ ## Options
1351
+
1352
+ * `:prefix` - The prefix to run the query on (such as the schema path
1353
+ in Postgres or the database in MySQL). This will be applied to all `from`
1354
+ and `join`s in the query that did not have a prefix previously given
1355
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1356
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1357
+ `Ecto.Query` documentation.
1358
+
1359
+ See the ["Shared options"](#module-shared-options) section at the module
1360
+ documentation for remaining options.
1361
+
1362
+ ## Examples
1363
+
1364
+ MyRepo.update_all(Post, set: [title: "New title"])
1365
+
1366
+ MyRepo.update_all(Post, inc: [visits: 1])
1367
+
1368
+ from(p in Post, where: p.id < 10, select: p.visits)
1369
+ |> MyRepo.update_all(set: [title: "New title"])
1370
+
1371
+ from(p in Post, where: p.id < 10, update: [set: [title: "New title"]])
1372
+ |> MyRepo.update_all([])
1373
+
1374
+ from(p in Post, where: p.id < 10, update: [set: [title: ^new_title]])
1375
+ |> MyRepo.update_all([])
1376
+
1377
+ from(p in Post, where: p.id < 10, update: [set: [title: fragment("upper(?)", ^new_title)]])
1378
+ |> MyRepo.update_all([])
1379
+
1380
+ from(p in Post, where: p.id < 10, update: [set: [visits: p.visits * 1000]])
1381
+ |> MyRepo.update_all([])
1382
+
1383
+ """
1384
+ @doc group: "Query API"
1385
+ @callback update_all(
1386
+ queryable :: Ecto.Queryable.t(),
1387
+ updates :: Keyword.t(),
1388
+ opts :: Keyword.t()
1389
+ ) :: {non_neg_integer, nil | [term]}
1390
+
1391
+ @doc """
1392
+ Deletes all entries matching the given query.
1393
+
1394
+ It returns a tuple containing the number of entries and any returned
1395
+ result as second element. The second element is `nil` by default
1396
+ unless a `select` is supplied in the delete query. Note, however,
1397
+ not all databases support returning data from DELETEs.
1398
+
1399
+ ## Options
1400
+
1401
+ * `:prefix` - The prefix to run the query on (such as the schema path
1402
+ in Postgres or the database in MySQL). This will be applied to all `from`
1403
+ and `join`s in the query that did not have a prefix previously given
1404
+ either via the `:prefix` option on `join`/`from` or via `@schema_prefix`
1405
+ in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the
1406
+ `Ecto.Query` documentation.
1407
+
1408
+ See the ["Shared options"](#module-shared-options) section at the module
1409
+ documentation for remaining options.
1410
+
1411
+ ## Examples
1412
+
1413
+ MyRepo.delete_all(Post)
1414
+
1415
+ from(p in Post, where: p.id < 10) |> MyRepo.delete_all()
1416
+
1417
+ # With returning results, if supported by the database.
1418
+ {_count, posts} = from(p in Post, where: p.id < 10, select: p) |> MyRepo.delete_all()
1419
+
1420
+ """
1421
+ @doc group: "Query API"
1422
+ @callback delete_all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) ::
1423
+ {non_neg_integer, nil | [term]}
1424
+
1425
+ ## Ecto.Adapter.Schema
1426
+
1427
+ @optional_callbacks insert_all: 3,
1428
+ insert: 2,
1429
+ insert!: 2,
1430
+ update: 2,
1431
+ update!: 2,
1432
+ delete: 2,
1433
+ delete!: 2,
1434
+ insert_or_update: 2,
1435
+ insert_or_update!: 2,
1436
+ prepare_query: 3
1437
+
1438
+ @doc """
1439
+ Inserts all entries into the repository.
1440
+
1441
+ It expects a schema module (`MyApp.User`) or a source (`"users"`) or
1442
+ both (`{"users", MyApp.User}`) as the first argument. The second
1443
+ argument is a list of entries to be inserted, either as keyword
1444
+ lists or as maps. The keys of the entries are the field names as
1445
+ atoms, when a schema module is specified in the first argument.
1446
+ Otherwise, the keys can be either atoms or strings representing
1447
+ the names of the columns in the underlying datastore. The value
1448
+ should be the respective value for the field type or, optionally,
1449
+ an `Ecto.Query` that returns a single entry with a single value.
1450
+
1451
+ It returns a tuple containing the number of entries
1452
+ and any returned result as second element. If the database
1453
+ does not support RETURNING in INSERT statements or no
1454
+ return result was selected, the second element will be `nil`.
1455
+
1456
+ When a schema module is given, the entries given will be properly dumped
1457
+ before being sent to the database. If the schema primary key has type
1458
+ `:id` or `:binary_id`, it will be handled either at the adapter
1459
+ or the storage layer. However any other primary key type or autogenerated
1460
+ value, like `Ecto.UUID` and timestamps, won't be autogenerated when
1461
+ using `c:insert_all/3`. You must set those fields explicitly. This is by
1462
+ design as this function aims to be a more direct way to insert data into
1463
+ the database without the conveniences of `c:insert/2`. This is also
1464
+ consistent with `c:update_all/3` that does not handle auto generated
1465
+ values as well.
1466
+
1467
+ It is also not possible to use `insert_all` to insert across multiple
1468
+ tables, therefore associations are not supported.
1469
+
1470
+ If a source is given, without a schema module, the given fields are passed
1471
+ as is to the adapter.
1472
+
1473
+ ## Options
1474
+
1475
+ * `:returning` - selects which fields to return. When `true`,
1476
+ returns all fields in the given schema. May be a list of
1477
+ fields, where a struct is still returned but only with the
1478
+ given fields. Or `false`, where nothing is returned (the default).
1479
+ This option is not supported by all databases.
1480
+
1481
+ * `:prefix` - The prefix to run the query on (such as the schema path
1482
+ in Postgres or the database in MySQL). This overrides the prefix set
1483
+ in the query and any `@schema_prefix` set in the schema.
1484
+
1485
+ * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`,
1486
+ `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`,
1487
+ a keyword list of update instructions or an `Ecto.Query`
1488
+ query for updates. See the "[Upserts](#c:insert_all/3-upserts)" section for more information.
1489
+
1490
+ * `:conflict_target` - A list of column names to verify for conflicts.
1491
+ It is expected those columns to have unique indexes on them that may conflict.
1492
+ If none is specified, the conflict target is left up to the database.
1493
+ It may also be `{:unsafe_fragment, binary_fragment}` to pass any
1494
+ expression to the database without any sanitization, this is useful
1495
+ for partial index or index with expressions, such as
1496
+ `{:unsafe_fragment, "(coalesce(firstname, ''), coalesce(lastname, '')) WHERE middlename IS NULL"}` for
1497
+ `ON CONFLICT (coalesce(firstname, ''), coalesce(lastname, '')) WHERE middlename IS NULL` SQL query.
1498
+
1499
+ * `:placeholders` - A map with placeholders. This feature is not supported
1500
+ by all databases. See the ["Placeholders" section](#c:insert_all/3-placeholders) for more information.
1501
+
1502
+ See the ["Shared options"](#module-shared-options) section at the module
1503
+ documentation for remaining options.
1504
+
1505
+ ## Source query
1506
+
1507
+ A query can be given instead of a list with entries. This query needs to select
1508
+ into a map containing only keys that are available as writeable columns in the
1509
+ schema. This will query and insert the values all inside one query, without
1510
+ another round trip to the application.
1511
+
1512
+ ## Examples
1513
+
1514
+ MyRepo.insert_all(Post, [[title: "My first post"], [title: "My second post"]])
1515
+
1516
+ MyRepo.insert_all(Post, [%{title: "My first post"}, %{title: "My second post"}])
1517
+
1518
+ query = from p in Post,
1519
+ join: c in assoc(p, :comments),
1520
+ select: %{
1521
+ author_id: p.author_id,
1522
+ posts: count(p.id, :distinct),
1523
+ interactions: sum(p.likes) + count(c.id)
1524
+ },
1525
+ group_by: p.author_id
1526
+ MyRepo.insert_all(AuthorStats, query)
1527
+
1528
+ ## Upserts
1529
+
1530
+ `c:insert_all/3` provides upserts (update or inserts) via the `:on_conflict`
1531
+ option. The `:on_conflict` option supports the following values:
1532
+
1533
+ * `:raise` - raises if there is a conflicting primary key or unique index
1534
+
1535
+ * `:nothing` - ignores the error in case of conflicts
1536
+
1537
+ * `:replace_all` - replace **all** values on the existing row with the values
1538
+ in the schema/changeset, including fields not explicitly set in the changeset,
1539
+ such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`).
1540
+ Do not use this option if you have auto-incrementing primary keys, as they
1541
+ will also be replaced. You most likely want to use `{:replace_all_except, [:id]}`
1542
+ or `{:replace, fields}` explicitly instead. This option requires a schema
1543
+
1544
+ * `{:replace_all_except, fields}` - same as above except the given fields
1545
+ are not replaced. This option requires a schema
1546
+
1547
+ * `{:replace, fields}` - replace only specific columns. This option requires
1548
+ `:conflict_target`
1549
+
1550
+ * a keyword list of update instructions - such as the one given to
1551
+ `c:update_all/3`, for example: `[set: [title: "new title"]]`
1552
+
1553
+ * an `Ecto.Query` that will act as an `UPDATE` statement, such as the
1554
+ one given to `c:update_all/3`
1555
+
1556
+ Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY"
1557
+ on databases such as MySQL.
1558
+
1559
+ ## Return values
1560
+
1561
+ By default, both Postgres and MySQL will return the number of entries
1562
+ inserted on `c:insert_all/3`. However, when the `:on_conflict` option
1563
+ is specified, Postgres and MySQL will return different results.
1564
+
1565
+ Postgres will only count a row if it was affected and will
1566
+ return 0 if no new entry was added.
1567
+
1568
+ MySQL will return, at a minimum, the number of entries attempted. For example,
1569
+ if `:on_conflict` is set to `:nothing`, MySQL will return
1570
+ the number of entries attempted to be inserted, even when no entry
1571
+ was added.
1572
+
1573
+ Also note that if `:on_conflict` is a query, MySQL will return
1574
+ the number of attempted entries plus the number of entries modified
1575
+ by the UPDATE query.
1576
+
1577
+ ## Placeholders
1578
+
1579
+ Passing in a map for the `:placeholders` allows you to send less
1580
+ data over the wire when you have many entries with the same value
1581
+ for a field. To use a placeholder, replace its value in each of your
1582
+ entries with `{:placeholder, key}`, where `key` is the key you
1583
+ are using in the `:placeholders` option map. For example:
1584
+
1585
+ placeholders = %{blob: large_blob_of_text(...)}
1586
+
1587
+ entries = [
1588
+ %{title: "v1", body: {:placeholder, :blob}},
1589
+ %{title: "v2", body: {:placeholder, :blob}}
1590
+ ]
1591
+
1592
+ Repo.insert_all(Post, entries, placeholders: placeholders)
1593
+
1594
+ Keep in mind that:
1595
+
1596
+ * placeholders cannot be nested in other values. For example, you
1597
+ cannot put a placeholder inside an array. Instead, the whole
1598
+ array has to be the placeholder
1599
+
1600
+ * a placeholder key can only be used with columns of the same type
1601
+
1602
+ * placeholders require a database that supports index parameters,
1603
+ so they are not currently compatible with MySQL
1604
+
1605
+ """
1606
+ @doc group: "Schema API"
1607
+ @callback insert_all(
1608
+ schema_or_source :: binary() | {binary(), module()} | module(),
1609
+ entries_or_query ::
1610
+ [%{(atom() | String.t()) => value} | Keyword.t(value)] | Ecto.Query.t(),
1611
+ opts :: Keyword.t()
1612
+ ) :: {non_neg_integer(), nil | [term()]}
1613
+ when value: term() | Ecto.Query.t()
1614
+
1615
+ @doc """
1616
+ Inserts a struct defined via `Ecto.Schema` or a changeset.
1617
+
1618
+ In case a struct is given, the struct is converted into a changeset
1619
+ with all non-nil fields as part of the changeset.
1620
+
1621
+ In case a changeset is given, the changes in the changeset are
1622
+ merged with the struct fields, and all of them are sent to the
1623
+ database. If more than one database operation is required, they're
1624
+ automatically wrapped in a transaction.
1625
+
1626
+ It returns `{:ok, struct}` if the struct has been successfully
1627
+ inserted or `{:error, changeset}` if there was a validation
1628
+ or a known constraint error.
1629
+
1630
+ ## Options
1631
+
1632
+ * `:returning` - selects which fields to return. It accepts a list
1633
+ of fields to be returned from the database. When `true`, returns
1634
+ all fields, including those marked as `load_in_query: false`. When
1635
+ `false`, no extra fields are returned. It will always include all
1636
+ fields in `read_after_writes` as well as any autogenerated id. Be
1637
+ aware that the fields returned from the database overwrite what was
1638
+ supplied by the user. Any field not returned by the database will be
1639
+ present with the original value supplied by the user. Not all databases
1640
+ support this option and it may not be available during upserts.
1641
+ See the ["Upserts"](`c:insert/2#upserts`) section for more information.
1642
+
1643
+ * `:prefix` - The prefix to run the query on (such as the schema path
1644
+ in Postgres or the database in MySQL). This overrides the prefix set
1645
+ in the query and any `@schema_prefix` set on any schemas. Also, the
1646
+ `@schema_prefix` for the parent record will override all default
1647
+ `@schema_prefix`s set in any child schemas for associations.
1648
+
1649
+ * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`,
1650
+ `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`,
1651
+ a keyword list of update instructions or an `Ecto.Query` query for updates.
1652
+ See the ["Upserts"](`c:insert/2#upserts`) section for more information.
1653
+
1654
+ * `:conflict_target` - A list of column names to verify for conflicts.
1655
+ It is expected those columns to have unique indexes on them that may conflict.
1656
+ If none is specified, the conflict target is left up to the database.
1657
+ It may also be `{:unsafe_fragment, binary_fragment}` to pass any
1658
+ expression to the database without any sanitization, this is useful
1659
+ for partial index or index with expressions, such as
1660
+ `{:unsafe_fragment, "(coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL"}` for
1661
+ `ON CONFLICT (coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL` SQL query.
1662
+
1663
+ * `:stale_error_field` - The field where stale errors will be added in
1664
+ the returning changeset. This option can be used to avoid raising
1665
+ `Ecto.StaleEntryError`.
1666
+
1667
+ * `:stale_error_message` - The message to add to the configured
1668
+ `:stale_error_field` when stale errors happen, defaults to "is stale".
1669
+
1670
+ * `:allow_stale` - Doesn't error when structs are stale. Defaults to `false`.
1671
+ This may happen if there are rules or triggers in the database that
1672
+ rejects the insert operation. This option cascades to associations.
1673
+
1674
+ See the ["Shared options"](#module-shared-options) section at the module
1675
+ documentation for more options.
1676
+
1677
+ ## Examples
1678
+
1679
+ A typical example is calling `MyRepo.insert/1` with a struct
1680
+ and acting on the return value:
1681
+
1682
+ case MyRepo.insert %Post{title: "Ecto is great"} do
1683
+ {:ok, struct} -> # Inserted with success
1684
+ {:error, changeset} -> # Something went wrong
1685
+ end
1686
+
1687
+ ## Upserts
1688
+
1689
+ `c:insert/2` provides upserts (update or inserts) via the `:on_conflict`
1690
+ option. The `:on_conflict` option supports the following values:
1691
+
1692
+ * `:raise` - raises if there is a conflicting primary key or unique index
1693
+
1694
+ * `:nothing` - ignores the error in case of conflicts
1695
+
1696
+ * `:replace_all` - replace **all** values on the existing row with the values
1697
+ in the schema/changeset, including fields not explicitly set in the changeset,
1698
+ such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`).
1699
+ Do not use this option if you have auto-incrementing primary keys, as they
1700
+ will also be replaced. You most likely want to use `{:replace_all_except, [:id]}`
1701
+ or `{:replace, fields}` explicitly instead. This option requires a schema
1702
+
1703
+ * `{:replace_all_except, fields}` - same as above except the given fields are
1704
+ not replaced. This option requires a schema
1705
+
1706
+ * `{:replace, fields}` - replace only specific columns. This option requires
1707
+ `:conflict_target`
1708
+
1709
+ * a keyword list of update instructions - such as the one given to
1710
+ `c:update_all/3`, for example: `[set: [title: "new title"]]`
1711
+
1712
+ * an `Ecto.Query` that will act as an `UPDATE` statement, such as the
1713
+ one given to `c:update_all/3`. Similarly to `c:update_all/3`, auto
1714
+ generated values, such as timestamps are not automatically updated.
1715
+ If the struct cannot be found, `Ecto.StaleEntryError` will be raised.
1716
+
1717
+ Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY"
1718
+ on databases such as MySQL.
1719
+
1720
+ As an example, imagine `:title` is marked as a unique column in
1721
+ the database:
1722
+
1723
+ {:ok, inserted} = MyRepo.insert(%Post{title: "this is unique"})
1724
+
1725
+ Now we can insert with the same title but do nothing on conflicts:
1726
+
1727
+ {:ok, ignored} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: :nothing)
1728
+
1729
+ Because we used `on_conflict: :nothing`, instead of getting an error,
1730
+ we got `{:ok, struct}`. However the returned struct does not reflect
1731
+ the data in the database. If the primary key is auto-generated by the
1732
+ database, the primary key in the `ignored` record will be nil if there
1733
+ was no insertion. For example, if you use the default primary key
1734
+ (which has name `:id` and a type of `:id`), then `ignored.id` above
1735
+ will be nil if there was no insertion.
1736
+
1737
+ If your id is generated by your application (typically the case for
1738
+ `:binary_id`) or if you pass another value for `:on_conflict`, detecting
1739
+ if an insert or update happened is slightly more complex, as the database
1740
+ does not actually inform us what happened. Let's insert a post with the
1741
+ same title but use a query to update the body column in case of conflicts:
1742
+
1743
+ # In Postgres (it requires the conflict target for updates):
1744
+ on_conflict = [set: [body: "updated"]]
1745
+ {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"},
1746
+ on_conflict: on_conflict, conflict_target: :title)
1747
+
1748
+ # In MySQL (conflict target is not supported):
1749
+ on_conflict = [set: [title: "updated"]]
1750
+ {:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"},
1751
+ on_conflict: on_conflict)
1752
+
1753
+ In the examples above, even though it returned `:ok`, we do not know
1754
+ if we inserted new data or if we updated only the `:on_conflict` fields.
1755
+ In case an update happened, the data in the struct most likely does
1756
+ not match the data in the database. For example, autogenerated fields
1757
+ such as `inserted_at` will point to now rather than the time the
1758
+ struct was actually inserted.
1759
+
1760
+ If you need to guarantee the data in the returned struct mirrors the
1761
+ database, you have three options:
1762
+
1763
+ * Use `on_conflict: :replace_all`, although that will replace all
1764
+ fields in the database with the ones in the struct/changeset,
1765
+ including autogenerated fields such as `inserted_at` and `updated_at`:
1766
+
1767
+ MyRepo.insert(%Post{title: "this is unique"},
1768
+ on_conflict: :replace_all, conflict_target: :title)
1769
+
1770
+ * Specify `read_after_writes: true` in your schema for choosing
1771
+ fields that are read from the database after every operation.
1772
+ Or pass `returning: true` to `insert` to read all fields back.
1773
+ (Note that it will only read from the database if at least one
1774
+ field is updated).
1775
+
1776
+ MyRepo.insert(%Post{title: "this is unique"}, returning: true,
1777
+ on_conflict: on_conflict, conflict_target: :title)
1778
+
1779
+ * Alternatively, read the data again from the database in a separate
1780
+ query. This option requires the primary key to be generated by the
1781
+ database:
1782
+
1783
+ {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: on_conflict)
1784
+ Repo.get(Post, updated.id)
1785
+
1786
+ Because of the inability to know if the struct is up to date or not,
1787
+ inserting a struct with associations and using the `:on_conflict` option
1788
+ at the same time is not recommended, as Ecto will be unable to actually
1789
+ track the proper status of the association.
1790
+
1791
+ ## Advanced Upserts
1792
+
1793
+ Using an `Ecto.Query` for `:on_conflict` can allow us to use more advanced
1794
+ database features. For example, PostgreSQL supports conditional upserts like
1795
+ `DO UPDATE SET title = EXCLUDED.title, version = EXCLUDED.version
1796
+ WHERE EXCLUDED.version > post.version`.
1797
+ This means that the title and version will be updated only if the proposed
1798
+ row has a greater version value than the existing row.
1799
+
1800
+ Ecto can support this as follows:
1801
+
1802
+ conflict_query =
1803
+ from(p in Post,
1804
+ update: [set: [
1805
+ title: fragment("EXCLUDED.title"),
1806
+ version: fragment("EXCLUDED.version")
1807
+ ]],
1808
+ where: fragment("EXCLUDED.version > ?", p.version)
1809
+ )
1810
+
1811
+ MyRepo.insert(
1812
+ %Post{id: 1, title: "Ecto Upserts (Dance Remix)", version: 2},
1813
+ conflict_target: [:id],
1814
+ on_conflict: conflict_query
1815
+ )
1816
+ """
1817
+ @doc group: "Schema API"
1818
+ @callback insert(
1819
+ struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
1820
+ opts :: Keyword.t()
1821
+ ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
1822
+
1823
+ @doc """
1824
+ Updates a changeset using its primary key.
1825
+
1826
+ A changeset is required as it is the only mechanism for
1827
+ tracking dirty changes. Only the fields present in the `changes` part
1828
+ of the changeset are sent to the database. Any other, in-memory
1829
+ changes done to the schema are ignored. If more than one database
1830
+ operation is required, they're automatically wrapped in a transaction.
1831
+
1832
+ If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError`
1833
+ will be raised.
1834
+
1835
+ If the struct cannot be found, `Ecto.StaleEntryError` will be raised.
1836
+
1837
+ It returns `{:ok, struct}` if the struct has been successfully
1838
+ updated or `{:error, changeset}` if there was a validation
1839
+ or a known constraint error.
1840
+
1841
+ ## Options
1842
+
1843
+ * `:returning` - selects which fields to return. It accepts a list
1844
+ of fields to be returned from the database. When `true`, returns
1845
+ all fields, including those marked as `load_in_query: false`. When
1846
+ `false`, no extra fields are returned. It will always include all
1847
+ fields in `read_after_writes`. Be aware that the fields returned
1848
+ from the database overwrite what was supplied by the user. Any field
1849
+ not returned by the database will be present with the original value
1850
+ supplied by the user. Not all databases support this option.
1851
+
1852
+ * `:force` - By default, if there are no changes in the changeset,
1853
+ `c:update/2` is a no-op. By setting this option to true, update
1854
+ callbacks will always be executed, even if there are no changes
1855
+ (including timestamps).
1856
+
1857
+ * `:prefix` - The prefix to run the query on (such as the schema path
1858
+ in Postgres or the database in MySQL). This overrides the prefix set
1859
+ in the query and any `@schema_prefix` set on any schemas. Also, the
1860
+ `@schema_prefix` for the parent record will override all default
1861
+ `@schema_prefix`s set in any child schemas for associations.
1862
+
1863
+ * `:stale_error_field` - The field where stale errors will be added in
1864
+ the returning changeset. This option can be used to avoid raising
1865
+ `Ecto.StaleEntryError`.
1866
+
1867
+ * `:stale_error_message` - The message to add to the configured
1868
+ `:stale_error_field` when stale errors happen, defaults to "is stale".
1869
+
1870
+ * `:allow_stale` - Doesn't error if update is stale. Defaults to `false`.
1871
+ This may happen if the struct has been deleted from the database before
1872
+ the update or if there is a rule or a trigger on the database that rejects
1873
+ the update operation. This option cascades to associations.
1874
+
1875
+ See the ["Shared options"](#module-shared-options) section at the module
1876
+ documentation for more options.
1877
+
1878
+ ## Example
1879
+
1880
+ post = MyRepo.get!(Post, 42)
1881
+ post = Ecto.Changeset.change post, title: "New title"
1882
+ case MyRepo.update post do
1883
+ {:ok, struct} -> # Updated with success
1884
+ {:error, changeset} -> # Something went wrong
1885
+ end
1886
+ """
1887
+ @doc group: "Schema API"
1888
+ @callback update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
1889
+ {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
1890
+
1891
+ @doc """
1892
+ Inserts or updates a changeset depending on whether the struct is persisted
1893
+ or not.
1894
+
1895
+ The distinction whether to insert or update will be made on the
1896
+ `Ecto.Schema.Metadata` field `:state`. The `:state` is automatically set by
1897
+ Ecto when loading or building a schema.
1898
+
1899
+ Please note that for this to work, you will have to load existing structs from
1900
+ the database. So even if the struct exists, this won't work:
1901
+
1902
+ struct = %Post{id: "existing_id", ...}
1903
+ MyRepo.insert_or_update changeset
1904
+ # => {:error, changeset} # id already exists
1905
+
1906
+ ## Options
1907
+
1908
+ * `:prefix` - The prefix to run the query on (such as the schema path
1909
+ in Postgres or the database in MySQL). This overrides the prefix set
1910
+ in the query and any `@schema_prefix` set any schemas. Also, the
1911
+ `@schema_prefix` for the parent record will override all default
1912
+ `@schema_prefix`s set in any child schemas for associations.
1913
+ * `:stale_error_field` - The field where stale errors will be added in
1914
+ the returning changeset. This option can be used to avoid raising
1915
+ `Ecto.StaleEntryError`. Only applies to updates.
1916
+ * `:stale_error_message` - The message to add to the configured
1917
+ `:stale_error_field` when stale errors happen, defaults to "is stale".
1918
+ Only applies to updates.
1919
+ * `:allow_stale` - Doesn't error when structs are stale. Defaults to `false`.
1920
+ This option cascades to associations.
1921
+
1922
+ See the ["Shared options"](#module-shared-options) section at the module
1923
+ documentation for more options.
1924
+
1925
+ ## Example
1926
+
1927
+ result =
1928
+ case MyRepo.get(Post, id) do
1929
+ nil -> %Post{id: id} # Post not found, we build one
1930
+ post -> post # Post exists, let's use it
1931
+ end
1932
+ |> Post.changeset(changes)
1933
+ |> MyRepo.insert_or_update
1934
+
1935
+ case result do
1936
+ {:ok, struct} -> # Inserted or updated with success
1937
+ {:error, changeset} -> # Something went wrong
1938
+ end
1939
+ """
1940
+ @doc group: "Schema API"
1941
+ @callback insert_or_update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
1942
+ {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
1943
+
1944
+ @doc """
1945
+ Deletes a struct using its primary key.
1946
+
1947
+ If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError`
1948
+ will be raised. If the struct has been removed prior to the call,
1949
+ `Ecto.StaleEntryError` will be raised. If more than one database
1950
+ operation is required, they're automatically wrapped in a transaction.
1951
+
1952
+ It returns `{:ok, struct}` if the struct has been successfully
1953
+ deleted or `{:error, changeset}` if there was a validation
1954
+ or a known constraint error. By default, constraint errors will
1955
+ raise the `Ecto.ConstraintError` exception, unless a changeset is
1956
+ given as the first argument with the relevant constraints declared
1957
+ in it (see `Ecto.Changeset`).
1958
+
1959
+ ## Options
1960
+
1961
+ * `:returning` - selects which fields to return. It accepts a list
1962
+ of fields to be returned from the database. When `true`, returns
1963
+ all fields, including those marked as `load_in_query: false`. When
1964
+ `false`, no extra fields are returned. It will always include all
1965
+ fields in `read_after_writes`. Be aware that the fields returned
1966
+ from the database overwrite what was supplied by the user. Any field
1967
+ not returned by the database will be present with the original value
1968
+ supplied by the user. Not all databases support this option.
1969
+
1970
+ * `:prefix` - The prefix to run the query on (such as the schema path
1971
+ in Postgres or the database in MySQL). This overrides the prefix set
1972
+ in the query and any `@schema_prefix` set in the schema.
1973
+
1974
+ * `:stale_error_field` - The field where stale errors will be added in
1975
+ the returning changeset. This option can be used to avoid raising
1976
+ `Ecto.StaleEntryError`.
1977
+
1978
+ * `:stale_error_message` - The message to add to the configured
1979
+ `:stale_error_field` when stale errors happen, defaults to "is stale".
1980
+
1981
+ * `:allow_stale` - Doesn't error if delete is stale. Defaults to `false`.
1982
+ This may happen if the struct has been deleted from the database before
1983
+ this deletion or if there is a rule or a trigger on the database that rejects
1984
+ the delete operation.
1985
+
1986
+ See the ["Shared options"](#module-shared-options) section at the module
1987
+ documentation for more options.
1988
+
1989
+ ## Example
1990
+
1991
+ post = MyRepo.get!(Post, 42)
1992
+ case MyRepo.delete post do
1993
+ {:ok, struct} -> # Deleted with success
1994
+ {:error, changeset} -> # Something went wrong
1995
+ end
1996
+
1997
+ """
1998
+ @doc group: "Schema API"
1999
+ @callback delete(
2000
+ struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
2001
+ opts :: Keyword.t()
2002
+ ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
2003
+
2004
+ @doc """
2005
+ Same as `c:insert/2` but returns the struct or raises if the changeset is invalid.
2006
+ """
2007
+ @doc group: "Schema API"
2008
+ @callback insert!(
2009
+ struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
2010
+ opts :: Keyword.t()
2011
+ ) :: Ecto.Schema.t()
2012
+
2013
+ @doc """
2014
+ Same as `c:update/2` but returns the struct or raises if the changeset is invalid.
2015
+ """
2016
+ @doc group: "Schema API"
2017
+ @callback update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
2018
+ Ecto.Schema.t()
2019
+
2020
+ @doc """
2021
+ Same as `c:insert_or_update/2` but returns the struct or raises if the changeset
2022
+ is invalid.
2023
+ """
2024
+ @doc group: "Schema API"
2025
+ @callback insert_or_update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) ::
2026
+ Ecto.Schema.t()
2027
+
2028
+ @doc """
2029
+ Same as `c:delete/2` but returns the struct or raises if the changeset is invalid.
2030
+ """
2031
+ @doc group: "Schema API"
2032
+ @callback delete!(
2033
+ struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
2034
+ opts :: Keyword.t()
2035
+ ) :: Ecto.Schema.t()
2036
+
2037
+ ## Ecto.Adapter.Transaction
2038
+
2039
+ @optional_callbacks transaction: 2, in_transaction?: 0, rollback: 1
2040
+
2041
+ @doc """
2042
+ Runs the given function or `Ecto.Multi` inside a transaction.
2043
+
2044
+ ## Use with function
2045
+
2046
+ `c:transaction/2` can be called with both a function of arity
2047
+ zero or one. The arity zero function will just be executed as is:
2048
+
2049
+ import Ecto.Changeset, only: [change: 2]
2050
+
2051
+ MyRepo.transaction(fn ->
2052
+ MyRepo.update!(change(alice, balance: alice.balance - 10))
2053
+ MyRepo.update!(change(bob, balance: bob.balance + 10))
2054
+ end)
2055
+
2056
+ While the arity one function will receive the repo of the transaction
2057
+ as its first argument:
2058
+
2059
+ MyRepo.transaction(fn repo ->
2060
+ repo.insert!(%Post{})
2061
+ end)
2062
+
2063
+ If an Elixir exception occurs the transaction will be rolled back
2064
+ and the exception will bubble up from the transaction function.
2065
+ If no exception occurs, the transaction is committed when the
2066
+ function returns. A transaction can be explicitly rolled back
2067
+ by calling `c:rollback/1`, this will immediately leave the function
2068
+ and return the value given to `rollback` as `{:error, value}`.
2069
+
2070
+ A successful transaction returns the value returned by the function
2071
+ wrapped in a tuple as `{:ok, value}`.
2072
+
2073
+ ### Nested transactions
2074
+
2075
+ If `c:transaction/2` is called inside another transaction, the function
2076
+ is simply executed, without wrapping the new transaction call in any
2077
+ way. If there is an error in the inner transaction and the error is
2078
+ rescued, or the inner transaction is rolled back, the whole outer
2079
+ transaction is aborted, guaranteeing nothing will be committed.
2080
+
2081
+ Below is an example of how rollbacks work with nested transactions:
2082
+
2083
+ {:error, :rollback} =
2084
+ MyRepo.transaction(fn ->
2085
+ {:error, :posting_not_allowed} =
2086
+ MyRepo.transaction(fn ->
2087
+ # This function call causes the following to happen:
2088
+ #
2089
+ # * the transaction is rolled back in the database,
2090
+ # * code execution is stopped within the current function,
2091
+ # * and the value, passed to `rollback/1` is returned from
2092
+ # `MyRepo.transaction/1` as the second element in the error
2093
+ # tuple.
2094
+ #
2095
+ MyRepo.rollback(:posting_not_allowed)
2096
+
2097
+ # `rollback/1` stops execution, so code here won't be run
2098
+ end)
2099
+
2100
+ # The transaction here is now aborted and any further
2101
+ # operation will raise an exception.
2102
+ end)
2103
+
2104
+ See the ["Aborted transactions"](`c:transaction/2#aborted-transactions`) section for more examples of aborted
2105
+ transactions and how to handle them.
2106
+
2107
+ In practice, managing nested transactions can become complex quickly.
2108
+ For this reason, Ecto provides `Ecto.Multi` for composing transactions.
2109
+
2110
+ ## Use with Ecto.Multi
2111
+
2112
+ `c:transaction/2` also accepts the `Ecto.Multi` struct as first argument.
2113
+ `Ecto.Multi` allows you to compose transactions operations, step by step,
2114
+ and manage what happens in case of success or failure.
2115
+
2116
+ When an `Ecto.Multi` is given to this function, a transaction will be started,
2117
+ all operations applied and in case of success committed returning `{:ok, changes}`:
2118
+
2119
+ # With Ecto.Multi
2120
+ Ecto.Multi.new()
2121
+ |> Ecto.Multi.insert(:post, %Post{})
2122
+ |> MyRepo.transaction
2123
+
2124
+ In case of any errors the transaction will be rolled back and
2125
+ `{:error, failed_operation, failed_value, changes_so_far}` will be returned.
2126
+
2127
+ Explore the `Ecto.Multi` documentation to learn more and find detailed examples.
2128
+
2129
+ ## Aborted transactions
2130
+
2131
+ When an operation inside a transaction fails, the transaction is aborted in the database.
2132
+ For instance, if you attempt an insert that violates a unique constraint, the insert fails
2133
+ and the transaction is aborted. In such cases, any further operation inside the transaction
2134
+ will raise exceptions.
2135
+
2136
+ Take the following transaction as an example:
2137
+
2138
+ Repo.transaction(fn repo ->
2139
+ case repo.insert(changeset) do
2140
+ {:ok, post} ->
2141
+ repo.insert(%Status{value: "success"})
2142
+
2143
+ {:error, changeset} ->
2144
+ repo.insert(%Status{value: "failure"})
2145
+ end
2146
+ end)
2147
+
2148
+ If the changeset is valid, but the insert operation fails due to a database constraint,
2149
+ the subsequent `repo.insert(%Status{value: "failure"})` operation will raise an exception
2150
+ because the database has already aborted the transaction and thus making the operation invalid.
2151
+ In Postgres, the exception would look like this:
2152
+
2153
+ ** (Postgrex.Error) ERROR 25P02 (in_failed_sql_transaction) current transaction is aborted, commands ignored until end of transaction block
2154
+
2155
+ If the changeset is invalid before it reaches the database due to a validation error,
2156
+ no statement is sent to the database, an `:error` tuple is returned, and `repo.insert(%Status{value: "failure"})`
2157
+ operation will execute as usual.
2158
+
2159
+ We have two options to deal with such scenarios:
2160
+
2161
+ If you don't want to change the semantics of your code, you can also use the savepoints
2162
+ feature by passing the `:mode` option like this: `repo.insert(changeset, mode: :savepoint)`.
2163
+ In case of an exception, the transaction will rollback to the savepoint and prevent
2164
+ the transaction from failing.
2165
+
2166
+ Another alternative is to handle this operation outside of the transaction.
2167
+ For example, you can choose to perform an explicit `repo.rollback` call in the
2168
+ `{:error, changeset}` clause and then perform the `repo.insert(%Status{value: "failure"})` outside
2169
+ of the transaction. You might also consider using `Ecto.Multi`, as they automatically
2170
+ rollback whenever an operation fails.
2171
+
2172
+ ## Working with processes
2173
+
2174
+ The transaction is per process. A separate process started inside a
2175
+ transaction won't be part of the same transaction and will use a separate
2176
+ connection altogether.
2177
+
2178
+ When using the `Ecto.Adapters.SQL.Sandbox` in tests, while it may be
2179
+ possible to share the connection between processes, the parent process
2180
+ will typically hold the connection until the transaction completes. This
2181
+ may lead to a deadlock if the child process attempts to use the same connection.
2182
+ See the docs for
2183
+ [`Ecto.Adapters.SQL.Sandbox`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html)
2184
+ for more information.
2185
+
2186
+ ## Options
2187
+
2188
+ See the ["Shared options"](#module-shared-options) section at the module
2189
+ documentation for more options.
2190
+ """
2191
+ @doc group: "Transaction API"
2192
+ @callback transaction(fun_or_multi :: fun | Ecto.Multi.t(), opts :: Keyword.t()) ::
2193
+ {:ok, any}
2194
+ | {:error, any}
2195
+ | Ecto.Multi.failure()
2196
+
2197
+ @doc """
2198
+ Returns true if the current process is inside a transaction.
2199
+
2200
+ If you are using the `Ecto.Adapters.SQL.Sandbox` in tests, note that even
2201
+ though each test is inside a transaction, `in_transaction?/0` will only
2202
+ return true inside transactions explicitly created with `transaction/2`. This
2203
+ is done so the test environment mimics dev and prod.
2204
+
2205
+ ## Examples
2206
+
2207
+ MyRepo.in_transaction?
2208
+ #=> false
2209
+
2210
+ MyRepo.transaction(fn ->
2211
+ MyRepo.in_transaction? #=> true
2212
+ end)
2213
+
2214
+ """
2215
+ @doc group: "Transaction API"
2216
+ @callback in_transaction?() :: boolean
2217
+
2218
+ @doc """
2219
+ Rolls back the current transaction.
2220
+
2221
+ The transaction will return the value given as `{:error, value}`.
2222
+
2223
+ Note that calling `rollback` causes the code in the transaction to stop executing.
2224
+ """
2225
+ @doc group: "Transaction API"
2226
+ @callback rollback(value :: any) :: no_return
2227
+ end
deps/ecto/lib/ecto/repo/assoc.ex ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Ecto.Repo.Assoc do
2
+ # The module invoked by repo modules
3
+ # for association related functionality.
4
+ @moduledoc false
5
+
6
+ @doc """
7
+ Transforms a result set based on query assocs, loading
8
+ the associations onto their parent schema.
9
+ """
10
+ @spec query([list], list, tuple, (list -> list)) :: [Ecto.Schema.t]
11
+ def query(rows, assocs, sources, fun)
12
+
13
+ def query([], _assocs, _sources, _fun), do: []
14
+ def query(rows, [], _sources, fun), do: Enum.map(rows, fun)
15
+
16
+ def query(rows, assocs, sources, fun) do
17
+ # Create rose tree of accumulator dicts in the same
18
+ # structure as the fields tree
19
+ accs = create_accs(0, assocs, sources, [])
20
+
21
+ # Populate tree of dicts of associated entities from the result set
22
+ {_keys, _cache, rows, sub_dicts} = Enum.reduce(rows, accs, fn row, acc ->
23
+ merge(fun.(row), acc, 0) |> elem(0)
24
+ end)
25
+
26
+ # Create the reflections that will be loaded into memory.
27
+ refls = create_refls(0, assocs, sub_dicts, sources)
28
+
29
+ # Retrieve and load the assocs from cached dictionaries recursively
30
+ for {item, sub_structs} <- Enum.reverse(rows) do
31
+ [load_assocs(item, refls)|sub_structs]
32
+ end
33
+ end
34
+
35
+ defp merge([struct|sub_structs], {primary_keys, cache, dict, sub_dicts}, parent_key) do
36
+ child_key =
37
+ if struct do
38
+ for primary_key <- primary_keys do
39
+ case Map.get(struct, primary_key) do
40
+ nil -> raise Ecto.NoPrimaryKeyValueError, struct: struct
41
+ value -> value
42
+ end
43
+ end
44
+ end
45
+
46
+ # Traverse sub_structs adding one by one to the tree.
47
+ # Note we need to traverse even if we don't have a child_key
48
+ # due to nested associations.
49
+ {sub_dicts, sub_structs} = Enum.map_reduce(sub_dicts, sub_structs, &merge(&2, &1, child_key))
50
+
51
+ cache_key = cache_key(parent_key, child_key, sub_structs, dict)
52
+
53
+ if struct && parent_key && not Map.get(cache, cache_key, false) do
54
+ cache = Map.put(cache, cache_key, true)
55
+ item = {child_key, struct}
56
+
57
+ # If we have a list, we are at the root, so we also store the sub structs
58
+ dict = update_dict(dict, parent_key, item, sub_structs)
59
+
60
+ {{primary_keys, cache, dict, sub_dicts}, sub_structs}
61
+ else
62
+ {{primary_keys, cache, dict, sub_dicts}, sub_structs}
63
+ end
64
+ end
65
+
66
+ defp cache_key(parent_key, child_key, sub_structs, dict) when is_list(dict) do
67
+ {parent_key, child_key, sub_structs}
68
+ end
69
+
70
+ defp cache_key(parent_key, child_key, _sub_structs, dict) when is_map(dict) do
71
+ {parent_key, child_key}
72
+ end
73
+
74
+ defp update_dict(dict, _parent_key, item, sub_structs) when is_list(dict) do
75
+ [{item, sub_structs} | dict]
76
+ end
77
+
78
+ defp update_dict(dict, parent_key, item, _sub_structs) when is_map(dict) do
79
+ Map.update(dict, parent_key, [item], &[item | &1])
80
+ end
81
+
82
+ defp load_assocs({child_key, struct}, refls) do
83
+ Enum.reduce refls, struct, fn {dict, refl, sub_refls}, acc ->
84
+ %{field: field, cardinality: cardinality} = refl
85
+ loaded =
86
+ dict
87
+ |> Map.get(child_key, [])
88
+ |> Enum.reverse()
89
+ |> Enum.map(&load_assocs(&1, sub_refls))
90
+ |> maybe_first(cardinality)
91
+ Map.put(acc, field, loaded)
92
+ end
93
+ end
94
+
95
+ defp maybe_first(list, :one), do: List.first(list)
96
+ defp maybe_first(list, _), do: list
97
+
98
+ defp create_refls(idx, fields, dicts, sources) do
99
+ schema = get_assoc_schema(sources, idx)
100
+
101
+ Enum.map(:lists.zip(dicts, fields), fn
102
+ {{_primary_keys, _cache, dict, sub_dicts}, {field, {child_idx, child_fields}}} ->
103
+ refl = schema.__schema__(:association, field)
104
+ sub_refls = create_refls(child_idx, child_fields, sub_dicts, sources)
105
+ {dict, refl, sub_refls}
106
+ end)
107
+ end
108
+
109
+ defp create_accs(idx, fields, sources, initial_dict) do
110
+ acc = Enum.map(fields, fn {_field, {child_idx, child_fields}} ->
111
+ create_accs(child_idx, child_fields, sources, %{})
112
+ end)
113
+
114
+ schema = get_assoc_schema(sources, idx)
115
+
116
+ case schema.__schema__(:primary_key) do
117
+ [] -> raise Ecto.NoPrimaryKeyFieldError, schema: schema
118
+ pk -> {pk, %{}, initial_dict, acc}
119
+ end
120
+ end
121
+
122
+ defp get_assoc_schema(sources, idx) do
123
+ case elem(sources, idx) do
124
+ {_, schema, _} ->
125
+ schema
126
+
127
+ %Ecto.SubQuery{select: {:source, {_, schema}, _, _}} ->
128
+ schema
129
+ end
130
+ end
131
+ end