-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathrepo_test.exs
More file actions
2633 lines (2067 loc) · 87.9 KB
/
Copy pathrepo_test.exs
File metadata and controls
2633 lines (2067 loc) · 87.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Ecto.RepoTest do
use ExUnit.Case, async: true
import Ecto.Query
import Ecto, only: [put_meta: 2]
import ExUnit.CaptureLog
alias Ecto.TestRepo
defmodule MyParent do
use Ecto.Schema
schema "my_parent" do
field :n, :integer
end
def changeset(struct, params) do
Ecto.Changeset.cast(struct, params, [:n])
end
end
defmodule MyParentWithPrefix do
use Ecto.Schema
@schema_prefix "private"
schema "my_parent" do
field :n, :integer
end
def changeset(struct, params) do
Ecto.Changeset.cast(struct, params, [:n])
end
end
defmodule MyEmbed do
use Ecto.Schema
embedded_schema do
field :x, :string
field :y, :string
end
def changeset(struct, params) do
Ecto.Changeset.cast(struct, params, [:x])
end
end
defmodule MySchemaChild do
use Ecto.Schema
schema "my_schema_child" do
field :a, :string
belongs_to :my_schema, MySchema
belongs_to :my_schema_no_pk, MySchemaNoPK, references: :n, foreign_key: :n
end
def changeset(struct, params) do
Ecto.Changeset.cast(struct, params, [:a])
end
end
defmodule MySchema do
use Ecto.Schema
schema "my_schema" do
field :x, :string
field :y, :binary, source: :yyy
field :z, :string, default: "z"
field :w, :string, virtual: true
field :array, {:array, :string}
field :map, {:map, :string}
has_many :children, MySchemaChild
end
end
defmodule MySchemaWithPrefix do
use Ecto.Schema
@schema_prefix "private"
schema "my_schema" do
field :x, :string
end
end
defmodule MySchemaWithNonStringPrefix do
use Ecto.Schema
@schema_prefix %{key: :private}
schema "my_schema" do
field :x, :string
end
end
defmodule MySchemaWithAssoc do
use Ecto.Schema
schema "my_schema" do
field :n, :integer
belongs_to :parent, MyParent
end
end
defmodule MySchemaWithMultiAssoc do
use Ecto.Schema
schema "my_schema" do
field :n, :integer
belongs_to :parent, MyParent
belongs_to :mother, MyParent
end
end
defmodule MySchemaWithPrefixedAssoc do
use Ecto.Schema
schema "my_schema" do
field :n, :integer
belongs_to :parent, MyParentWithPrefix
end
end
defmodule MyPrefixedSchemaWithAssoc do
use Ecto.Schema
@schema_prefix "other"
schema "my_schema" do
field :n, :integer
belongs_to :parent, MyParent
end
end
defmodule MyPrefixedSchemaWithPrefixedAssoc do
use Ecto.Schema
@schema_prefix "other"
schema "my_schema" do
field :n, :integer
belongs_to :parent, MyParentWithPrefix
end
end
defmodule MySchemaEmbedsMany do
use Ecto.Schema
schema "my_schema" do
field :x, :string
embeds_many :embeds, MyEmbed, on_replace: :delete
end
end
defmodule MySchemaEmbedsOne do
use Ecto.Schema
schema "my_schema" do
field :x, :string
embeds_one :embed, MyEmbed
end
end
defmodule MySchemaNoPK do
use Ecto.Schema
@primary_key false
schema "my_schema" do
field :x, :string
field :n, :integer
has_one :child, MySchemaChild, references: :n, foreign_key: :n
end
end
defmodule MySchemaWritable do
use Ecto.Schema
schema "my_schema" do
field :never, :integer, writable: :never
field :always, :integer, writable: :always
field :insert, :integer, writable: :insert
end
end
defmodule MySchemaWritableWarn do
use Ecto.Schema
schema "my_schema" do
field :never, :integer, writable: :never, on_writable_violation: :warn
field :always, :integer, writable: :always
field :insert, :integer, writable: :insert, on_writable_violation: :warn
end
end
defmodule MySchemaWritableRaise do
use Ecto.Schema
schema "my_schema" do
field :never, :integer, writable: :never, on_writable_violation: :raise
field :always, :integer, writable: :always
field :insert, :integer, writable: :insert, on_writable_violation: :raise
end
end
defmodule MySchemaOneField do
use Ecto.Schema
@primary_key false
schema "my_schema" do
field :n, :integer
end
end
test "defines child_spec/1" do
assert TestRepo.child_spec([]) == %{
id: TestRepo,
start: {TestRepo, :start_link, [[]]},
type: :supervisor
}
end
test "load/2" do
# string fields
assert %MySchema{x: "abc"} =
TestRepo.load(MySchema, %{"x" => "abc"})
# atom fields
assert %MySchema{x: "abc"} =
TestRepo.load(MySchema, %{x: "abc"})
# keyword list
assert %MySchema{x: "abc"} =
TestRepo.load(MySchema, x: "abc")
# atom fields and values
assert %MySchema{x: "abc"} =
TestRepo.load(MySchema, {[:x], ["abc"]})
# string fields and values
assert %MySchema{x: "abc"} =
TestRepo.load(MySchema, {["x"], ["abc"]})
# default value
assert %MySchema{x: "abc", z: "z"} =
TestRepo.load(MySchema, %{x: "abc"})
# source field
assert %MySchema{y: "abc"} =
TestRepo.load(MySchema, %{yyy: "abc"})
# array field
assert %MySchema{array: ["one", "two"]} =
TestRepo.load(MySchema, %{array: ["one", "two"]})
# map field with atoms
assert %MySchema{map: %{color: "red"}} =
TestRepo.load(MySchema, %{map: %{color: "red"}})
# map field with strings
assert %MySchema{map: %{"color" => "red"}} =
TestRepo.load(MySchema, %{map: %{"color" => "red"}})
# nil
assert %MySchema{x: nil} =
TestRepo.load(MySchema, %{x: nil})
# invalid field is ignored
assert %MySchema{} =
TestRepo.load(MySchema, %{bad: "bad"})
# invalid value
assert_raise ArgumentError,
"cannot load `0` as type :string for field `x` in schema Ecto.RepoTest.MySchema",
fn ->
TestRepo.load(MySchema, %{x: 0})
end
# schemaless
assert TestRepo.load(%{x: :string}, %{x: "abc", bad: "bad"}) ==
%{x: "abc"}
end
describe "get" do
test "raises on bad inputs" do
TestRepo.get(MySchema, 123)
message = "cannot perform Ecto.Repo.get/2 because the given value is nil"
assert_raise ArgumentError, message, fn ->
TestRepo.get(MySchema, nil)
end
message = ~r"value `:atom` in `where` cannot be cast to type :id in query"
assert_raise Ecto.Query.CastError, message, fn ->
TestRepo.get(MySchema, :atom)
end
message = ~r"expected a from expression with a schema in query"
assert_raise Ecto.QueryError, message, fn ->
TestRepo.get(%Ecto.Query{}, :atom)
end
end
end
describe "get_by" do
test "raises on bad inputs" do
TestRepo.get_by(MySchema, id: 123)
TestRepo.get_by(MySchema, %{id: 123})
message = ~r"value `:atom` in `where` cannot be cast to type :id in query"
assert_raise Ecto.Query.CastError, message, fn ->
TestRepo.get_by(MySchema, id: :atom)
end
end
end
describe "reload" do
test "raises when input structs do not have valid primary keys" do
message = "Ecto.Repo.reload/2 expects existent structs, found a `nil` primary key"
assert_raise ArgumentError, message, fn ->
TestRepo.reload(%MySchema{})
end
end
test "raises when input is not a struct or a list of structs" do
message = ~r"expected a struct or a list of structs,"
assert_raise ArgumentError, message, fn ->
TestRepo.reload(%{my_key: 1})
end
assert_raise ArgumentError, message, fn ->
TestRepo.reload([%{my_key: 1}, %{my_key: 2}])
end
end
test "raises when schema doesn't have a primary key" do
message = ~r"to have exactly one primary key"
assert_raise ArgumentError, message, fn ->
TestRepo.reload(%MySchemaNoPK{})
end
end
test "raises when receives multiple struct types" do
message = ~r"expected an homogeneous list"
assert_raise ArgumentError, message, fn ->
TestRepo.reload([%MySchemaWithAssoc{id: 1}, %MySchema{id: 2}])
end
end
test "supports prefix" do
struct_with_prefix = put_meta(%MySchema{id: 2}, prefix: "another")
TestRepo.reload(struct_with_prefix)
assert_received {:all, %{prefix: "another"}}
end
test "supports non-string prefix" do
struct_with_prefix = put_meta(%MySchema{id: 2}, prefix: %{key: :another})
TestRepo.reload(struct_with_prefix)
assert_received {:all, %{prefix: %{key: :another}}}
end
test "respects source" do
struct_with_custom_source = put_meta(%MySchema{id: 2}, source: "custom_schema")
TestRepo.reload(struct_with_custom_source)
assert_received {:all, %{from: %{source: {"custom_schema", MySchema}}}}
end
test "returns empty list when given empty list" do
assert TestRepo.reload([]) == []
end
test "reload! returns empty list when given empty list" do
assert TestRepo.reload!([]) == []
end
end
defmodule DefaultOptionRepo do
use Ecto.Repo, otp_app: :ecto, adapter: Ecto.TestAdapter
def default_options(:all), do: [prefix: "all_schema"]
def default_options(:update_all), do: [prefix: "update_all_schema"]
def default_options(_), do: [prefix: "fallback_schema"]
end
describe "default_options" do
test "passes a default option for operation" do
{:ok, _pid} = DefaultOptionRepo.start_link(url: "ecto://user:pass@local/hello")
DefaultOptionRepo.all(MySchema)
assert_received {:all, query}
assert query.prefix == "all_schema"
DefaultOptionRepo.all(MySchema, prefix: "overridden_schema")
assert_received {:all, query}
assert query.prefix == "overridden_schema"
DefaultOptionRepo.update_all(MySchema, set: [x: "foo"])
assert_received {:update_all, query}
assert query.prefix == "update_all_schema"
DefaultOptionRepo.delete_all(MySchema)
assert_received {:delete_all, query}
assert query.prefix == "fallback_schema"
DefaultOptionRepo.preload(%MySchemaWithAssoc{parent_id: 1}, :parent)
assert_received {:all, query}
assert query.from.source == {"my_parent", Ecto.RepoTest.MyParent}
assert query.prefix == "fallback_schema"
end
end
describe "aggregate" do
test "aggregates on the given field" do
TestRepo.aggregate(MySchema, :min, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: min(m0.id)>"
TestRepo.aggregate(MySchema, :max, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: max(m0.id)>"
TestRepo.aggregate(MySchema, :sum, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: sum(m0.id)>"
TestRepo.aggregate(MySchema, :avg, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: avg(m0.id)>"
TestRepo.aggregate(MySchema, :count, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: count(m0.id)>"
TestRepo.aggregate(MySchema, :count)
assert_received {:all, query}
assert inspect(query) == "#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: count()>"
end
test "aggregates handle a prefix option" do
TestRepo.aggregate(MySchema, :min, :id, prefix: "public")
assert_received {:all, query}
assert query.prefix == "public"
end
test "aggregate/3 respects parent query prefix" do
query = from(m in MySchema, limit: 1) |> put_query_prefix("public")
TestRepo.aggregate(query, :count)
assert_received {:all, query}
assert query.prefix == "public"
end
test "aggregate/4 respects parent query prefix" do
query = from(m in MySchema, limit: 1) |> put_query_prefix("public")
TestRepo.aggregate(query, :count, :id)
assert_received {:all, query}
assert query.prefix == "public"
end
test "removes any preload from query" do
from(MySchemaWithAssoc, preload: :parent) |> TestRepo.aggregate(:count, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchemaWithAssoc, select: count(m0.id)>"
end
test "removes order by from query without distinct/limit/offset/combinations" do
from(MySchema, order_by: :id) |> TestRepo.aggregate(:count, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: count(m0.id)>"
end
test "overrides any select" do
from(MySchema, select: true) |> TestRepo.aggregate(:count, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: count(m0.id)>"
end
test "uses subqueries with distinct/limit/offset" do
from(MySchema, limit: 5) |> TestRepo.aggregate(:count, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in subquery(from m0 in Ecto.RepoTest.MySchema,\n" <>
" limit: 5,\n" <>
" select: %{id: m0.id}), select: count(m0.id)>"
end
test "uses subqueries with combinations" do
from(MySchema, union: ^from(MySchema)) |> TestRepo.aggregate(:count, :id)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in subquery(from m0 in Ecto.RepoTest.MySchema,\n" <>
" union: (from m0 in Ecto.RepoTest.MySchema,\n" <>
" select: m0),\n" <>
" select: %{id: m0.id}), select: count(m0.id)>"
end
test "raises when aggregating with group_by" do
assert_raise Ecto.QueryError, ~r"cannot aggregate on query with group_by", fn ->
from(MySchema, group_by: [:id]) |> TestRepo.aggregate(:count, :id)
end
end
end
describe "exists?" do
test "selects 1 and sets limit to 1" do
TestRepo.exists?(MySchema)
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, limit: 1, select: 1>"
from(MySchema, select: [:id], limit: 10) |> TestRepo.exists?()
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, limit: 1, select: 1>"
end
test "removes any preload from query" do
from(MySchemaWithAssoc, preload: :parent) |> TestRepo.exists?()
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchemaWithAssoc, limit: 1, select: 1>"
end
test "removes distinct from query" do
from(MySchema, select: [:id], distinct: true) |> TestRepo.exists?()
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, limit: 1, select: 1>"
end
test "keeps order by from query" do
from(MySchema, order_by: :id) |> TestRepo.exists?()
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, order_by: [asc: m0.id], limit: 1, select: 1>"
end
test "overrides any select" do
from(MySchema, select: true) |> TestRepo.exists?()
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, limit: 1, select: 1>"
from(MySchema, union: ^from(MySchema, select: true)) |> TestRepo.exists?()
assert_received {:all, query}
assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, union: (from m0 in Ecto.RepoTest.MySchema,\n select: 1), limit: 1, select: 1>"
end
end
describe "stream" do
test "emits row values lazily" do
stream = TestRepo.stream(MySchema)
refute_received {:stream, _}
assert [%MySchema{id: 1}] = Enum.to_list(stream)
assert_received {:stream, _}
assert Enum.take(stream, 0) == []
refute_received {:stream, _}
end
test "does not work with preloads" do
query = from m in MySchemaWithAssoc, preload: [:parent]
assert_raise Ecto.QueryError, ~r"preloads are not supported on streams", fn ->
TestRepo.stream(query)
end
query =
MySchemaWithAssoc
|> join(:inner, [m], p in assoc(m, :parent))
|> preload([_m, p], parent: p)
assert_raise Ecto.QueryError, ~r"preloads are not supported on streams", fn ->
TestRepo.stream(query)
end
end
end
describe "returning" do
test "on insert" do
TestRepo.insert(%MySchemaWithAssoc{}, returning: [:id])
assert_received {:insert, %{source: "my_schema", returning: [:id]}}
TestRepo.insert(%MySchemaWithAssoc{}, returning: [:parent_id])
assert_received {:insert, %{source: "my_schema", returning: [:id, :parent_id]}}
TestRepo.insert(%MySchemaWithAssoc{}, returning: true)
assert_received {:insert, %{source: "my_schema", returning: [:id, :parent_id, :n]}}
TestRepo.insert(%MySchemaWithAssoc{}, returning: false)
assert_received {:insert, %{source: "my_schema", returning: [:id]}}
end
test "on update" do
changeset = Ecto.Changeset.change(%MySchemaWithAssoc{id: 1}, %{n: 2})
TestRepo.update(changeset, returning: [:id])
assert_received {:update, %{source: "my_schema", returning: [:id]}}
TestRepo.update(changeset, returning: [:parent_id])
assert_received {:update, %{source: "my_schema", returning: [:parent_id]}}
TestRepo.update(changeset, returning: true)
assert_received {:update, %{source: "my_schema", returning: [:parent_id, :n, :id]}}
TestRepo.update(changeset, returning: false)
assert_received {:update, %{source: "my_schema", returning: []}}
end
test "on delete" do
changeset = Ecto.Changeset.change(%MySchemaWithAssoc{id: 1}, %{n: 2})
TestRepo.delete(changeset, returning: [:id])
assert_received {:delete, %{source: "my_schema", returning: [:id]}}
TestRepo.delete(changeset, returning: [:parent_id])
assert_received {:delete, %{source: "my_schema", returning: [:parent_id]}}
TestRepo.delete(changeset, returning: true)
assert_received {:delete, %{source: "my_schema", returning: [:parent_id, :n, :id]}}
TestRepo.delete(changeset, returning: false)
assert_received {:delete, %{source: "my_schema", returning: []}}
end
end
describe "insert_all" do
test "takes queries as values in rows" do
import Ecto.Query
value = "foo"
query = from(s in MySchema, select: s.x, where: s.y == ^value)
TestRepo.insert_all(MySchema, [
[y: "y1", x: "x1"],
[x: query, z: "z2"],
[z: "z3", x: query],
[y: query, z: query]
])
assert_received {:insert_all, %{source: "my_schema", header: header}, planned_rows}
assert [
[x: "x1", yyy: "y1"],
[x: {%Ecto.Query{}, [^value]}, z: "z2"],
[x: {%Ecto.Query{}, [^value]}, z: "z3"],
[yyy: {%Ecto.Query{}, [^value]}, z: {%Ecto.Query{}, [^value]}]
] = planned_rows
{queries_with_index, _} =
for row <- planned_rows, field <- header, reduce: {[], 0} do
{queries, ix} ->
case row[field] do
{%Ecto.Query{} = query, _} -> {[{ix, query} | queries], ix + 1}
nil -> {queries, ix}
_ -> {queries, ix + 1}
end
end
assert length(queries_with_index) == 4
Enum.each(queries_with_index, fn {ix, query} ->
assert [%{expr: {:==, _, [_, {:^, [], [^ix]}]}}] = query.wheres
end)
end
test "takes query selecting on map" do
import Ecto.Query
threshold = "ten"
query =
from s in MySchema,
where: s.x > ^threshold,
select: %{
x: s.x,
y: fragment("concat(?, ?, ?)", ^"one", ^"two", s.z)
}
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema"}, {%Ecto.Query{}, params}}
assert ["one", "two", "ten"] = params
end
test "takes query selecting on map with literals" do
threshold = "ten"
query =
from s in MySchema,
where: s.x > ^threshold,
select: %{
x: s.x,
y: "bar",
z: nil
}
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema"}, {%Ecto.Query{} = query, params}}
assert [{{:., _, [{:&, [], [0]}, :x]}, _, []}, "bar", nil] = query.select.fields
assert ["ten"] = params
end
test "takes query selecting on struct/2" do
query =
from s in MySchema,
select: struct(s, [:x, :y])
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema"}, {%Ecto.Query{}, _params}}
end
test "takes query selecting on map/2" do
query =
from s in MySchema,
select: map(s, [:x, :y])
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema"}, {%Ecto.Query{}, _params}}
end
test "takes query selecting on source" do
query = from s in MySchema, select: s
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{}, _params}}
assert header == [:id, :x, :yyy, :z, :array, :map]
end
test "takes query selecting on source with join" do
query = from p in MyParent, join: a in MySchemaWithAssoc, on: true, select: a
TestRepo.insert_all(MySchemaWithAssoc, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{}, _params}}
assert header == [:id, :n, :parent_id]
end
test "takes query selecting on source with literal update" do
query = from s in MySchema, select: %{s | x: "x"}
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{} = query, _params}}
unchanged_fields = [:id, :yyy, :z, :array, :map]
updated_fields = [:x]
updated_values = ["x"]
assert header == unchanged_fields ++ updated_fields
assert query.select.fields == select_fields(unchanged_fields, 0) ++ updated_values
end
test "takes query selecting on source with dynamic update" do
query = from s in MySchema, select: %{s | x: ^"x"}
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{} = query, _params}}
unchanged_fields = [:id, :yyy, :z, :array, :map]
updated_fields = [:x]
updated_values = [%Ecto.Query.Tagged{tag: :string, type: :string, value: {:^, [], [0]}}]
assert header == unchanged_fields ++ updated_fields
assert query.select.fields == select_fields(unchanged_fields, 0) ++ updated_values
end
test "takes query selecting on source with join column update" do
query =
from p in MyParent, join: a in MySchemaWithAssoc, on: true, select: %{p | id: a.parent_id}
TestRepo.insert_all(MySchemaWithAssoc, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{} = query, _params}}
unchanged_fields = [:n]
updated_fields = [:id]
updated_values = [{{:., [type: :id], [{:&, [], [1]}, :parent_id]}, [], []}]
assert header == unchanged_fields ++ updated_fields
assert query.select.fields == select_fields(unchanged_fields, 0) ++ updated_values
end
test "takes query selecting on source with update from same source" do
# no join
query = from s in MySchema, select: %{s | x: s.y, y: s.x}
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{} = query, _params}}
unchanged_fields = [:id, :z, :array, :map]
updated_fields = [:x, :yyy]
updated_values = [
{{:., [type: :binary], [{:&, [], [0]}, :yyy]}, [], []},
{{:., [type: :string], [{:&, [], [0]}, :x]}, [], []}
]
assert header == unchanged_fields ++ updated_fields
assert query.select.fields == select_fields(unchanged_fields, 0) ++ updated_values
# join
query =
from s in MySchema,
join: a in MySchemaWithAssoc,
on: true,
select: %{a | n: a.parent_id, parent_id: a.n}
TestRepo.insert_all(MySchemaWithAssoc, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{} = query, _params}}
unchanged_fields = [:id]
updated_fields = [:n, :parent_id]
updated_values = [
{{:., [type: :id], [{:&, [], [1]}, :parent_id]}, [], []},
{{:., [type: :integer], [{:&, [], [1]}, :n]}, [], []}
]
assert header == unchanged_fields ++ updated_fields
assert query.select.fields == select_fields(unchanged_fields, 1) ++ updated_values
end
test "takes query selecting on map/2 with update" do
query = from s in MySchema, select: %{map(s, [:id, :x, :z]) | x: "x"}
TestRepo.insert_all(MySchema, query)
assert_received {:insert_all, %{source: "my_schema", header: header},
{%Ecto.Query{} = query, _params}}
unchanged_fields = [:id, :z]
updated_fields = [:x]
updated_values = ["x"]
assert header == unchanged_fields ++ updated_fields
assert query.select.fields == select_fields(unchanged_fields, 0) ++ updated_values
end
test "raises with query selecting read only fields" do
msg = ~r"cannot select unwritable field"
assert_raise ArgumentError, msg, fn ->
TestRepo.insert_all(MySchemaWritable, from(w in MySchemaWritable, select: w))
end
end
test "raises when a bad query is given as source" do
assert_raise ArgumentError, fn ->
TestRepo.insert_all(MySchema, from(s in MySchema))
end
assert_raise ArgumentError, fn ->
source =
from s in MySchema,
select: s.x
TestRepo.insert_all(MySchema, source)
end
assert_raise Ecto.QueryError, fn ->
source = from s in MySchema, select: map(s, [])
TestRepo.insert_all(MySchema, source)
end
end
test "raises when on associations" do
assert_raise ArgumentError, fn ->
TestRepo.insert_all(MySchema, [%{another: nil}])
end
end
test "with an embeds_one field" do
TestRepo.insert_all(MySchemaEmbedsOne, [%{embed: %MyEmbed{x: "x"}}])
assert_received {:insert_all, %{source: "my_schema"}, [row]}
assert [embed: %{id: nil, x: "x"}] = row
end
test "with an embeds_many field" do
TestRepo.insert_all(MySchemaEmbedsMany, [%{embeds: [%MyEmbed{x: "x"}]}])
assert_received {:insert_all, %{source: "my_schema"}, [row]}
assert [embeds: [%{id: nil, x: "x"}]] = row
end
test "raises when an embedded struct is needed" do
assert_raise ArgumentError, ~r"expected a struct #{inspect(MyEmbed)} value", fn ->
TestRepo.insert_all(MySchemaEmbedsOne, [%{embed: %{x: "x"}}])
end
assert_raise ArgumentError, ~r"expected a list of #{inspect(MyEmbed)} struct values", fn ->
TestRepo.insert_all(MySchemaEmbedsMany, [%{embeds: [%{x: "x"}]}])
end
end
end
defmodule MySchemaWithBinaryId do
use Ecto.Schema
schema "my_schema_with_binary_id" do
field :bid, :binary_id
field :str, :string
end
end
describe "placeholders" do
@describetag :placeholders
test "Repo.insert_all supports placeholder keys with schema" do
TestRepo.insert_all(MySchema, [%{x: {:placeholder, :foo}}], placeholders: %{foo: "bar"})
assert_receive {:insert_all, meta, query}
assert meta.placeholders == ["bar"]
assert query == [[x: {:placeholder, 1}]]
end
test "Repo.insert_all supports placeholder keys without schema" do
TestRepo.insert_all("my_schema", [%{x: {:placeholder, :foo}}], placeholders: %{foo: "bar"})
assert_receive {:insert_all, meta, query}
assert meta.placeholders == ["bar"]
assert query == [[x: {:placeholder, 1}]]
end
test "Repo.insert_all raises when placeholder key is not found" do
assert_raise KeyError, fn ->
TestRepo.insert_all(MySchema, [%{x: {:placeholder, :bad_key}}], placeholders: %{foo: 100})
end
end
test "Repo.insert_all raises when placeholder key is used for different types" do
placeholders = %{uuid_key: Ecto.UUID.generate()}
ph_key = {:placeholder, :uuid_key}
entries = [%{bid: ph_key, string: ph_key}]
assert_raise ArgumentError, fn ->
TestRepo.insert_all(MySchemaWithBinaryId, entries, placeholders: placeholders)
end
end
test "Repo.insert_all raises when placeholder key is used with invalid types" do
placeholders = %{string_key: "foo"}
entries = [%{n: {:placeholder, :string_key}}]
assert_raise Ecto.ChangeError, fn ->
TestRepo.insert_all(MyParent, entries, placeholders: placeholders)
end
end
end
describe "update_all" do
test "raises on bad input" do
# Success
TestRepo.update_all(MySchema, set: [x: "321"])
query = from(e in MySchema, where: e.x == "123", update: [set: [x: "321"]])
TestRepo.update_all(query, [])
assert_raise Ecto.QueryError, fn ->
TestRepo.update_all(from(e in MySchema, order_by: e.x), set: [x: "321"])
end
end
end
describe "delete_all" do
test "raises on bad inputs" do
# Success
TestRepo.delete_all(MySchema)
query = from(e in MySchema, where: e.x == "123")
TestRepo.delete_all(query)