diff --git a/deps/ecto/hex_metadata.config b/deps/ecto/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..7c8d3fcd3dd17d95a4a5d761382428640cd948d0 --- /dev/null +++ b/deps/ecto/hex_metadata.config @@ -0,0 +1,71 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-ecto/ecto">>}]}. +{<<"name">>,<<"ecto">>}. +{<<"version">>,<<"3.12.5">>}. +{<<"description">>, + <<"A toolkit for data mapping and language integrated query for Elixir">>}. +{<<"elixir">>,<<"~> 1.11">>}. +{<<"app">>,<<"ecto">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"files">>, + [<<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"CHANGELOG.md">>, + <<"lib">>,<<"lib/ecto">>,<<"lib/ecto/adapter.ex">>,<<"lib/ecto/multi.ex">>, + <<"lib/ecto/queryable.ex">>,<<"lib/ecto/type.ex">>, + <<"lib/ecto/changeset.ex">>,<<"lib/ecto/parameterized_type.ex">>, + <<"lib/ecto/changeset">>,<<"lib/ecto/changeset/relation.ex">>, + <<"lib/ecto/adapter">>,<<"lib/ecto/adapter/transaction.ex">>, + <<"lib/ecto/adapter/queryable.ex">>,<<"lib/ecto/adapter/schema.ex">>, + <<"lib/ecto/adapter/storage.ex">>,<<"lib/ecto/query.ex">>, + <<"lib/ecto/enum.ex">>,<<"lib/ecto/schema">>, + <<"lib/ecto/schema/metadata.ex">>,<<"lib/ecto/schema/loader.ex">>, + <<"lib/ecto/uuid.ex">>,<<"lib/ecto/json.ex">>,<<"lib/ecto/embedded.ex">>, + <<"lib/ecto/schema.ex">>,<<"lib/ecto/association.ex">>, + <<"lib/ecto/application.ex">>,<<"lib/ecto/query">>, + <<"lib/ecto/query/planner.ex">>,<<"lib/ecto/query/window_api.ex">>, + <<"lib/ecto/query/api.ex">>,<<"lib/ecto/query/inspect.ex">>, + <<"lib/ecto/query/builder.ex">>,<<"lib/ecto/query/builder">>, + <<"lib/ecto/query/builder/preload.ex">>, + <<"lib/ecto/query/builder/group_by.ex">>, + <<"lib/ecto/query/builder/join.ex">>,<<"lib/ecto/query/builder/update.ex">>, + <<"lib/ecto/query/builder/distinct.ex">>, + <<"lib/ecto/query/builder/limit_offset.ex">>, + <<"lib/ecto/query/builder/select.ex">>, + <<"lib/ecto/query/builder/windows.ex">>, + <<"lib/ecto/query/builder/from.ex">>,<<"lib/ecto/query/builder/cte.ex">>, + <<"lib/ecto/query/builder/combination.ex">>, + <<"lib/ecto/query/builder/dynamic.ex">>, + <<"lib/ecto/query/builder/order_by.ex">>, + <<"lib/ecto/query/builder/lock.ex">>,<<"lib/ecto/query/builder/filter.ex">>, + <<"lib/ecto/repo.ex">>,<<"lib/ecto/repo">>, + <<"lib/ecto/repo/transaction.ex">>,<<"lib/ecto/repo/supervisor.ex">>, + <<"lib/ecto/repo/registry.ex">>,<<"lib/ecto/repo/queryable.ex">>, + <<"lib/ecto/repo/preloader.ex">>,<<"lib/ecto/repo/schema.ex">>, + <<"lib/ecto/repo/assoc.ex">>,<<"lib/ecto/exceptions.ex">>,<<"lib/mix">>, + <<"lib/mix/tasks">>,<<"lib/mix/tasks/ecto.create.ex">>, + <<"lib/mix/tasks/ecto.ex">>,<<"lib/mix/tasks/ecto.gen.repo.ex">>, + <<"lib/mix/tasks/ecto.drop.ex">>,<<"lib/mix/ecto.ex">>,<<"lib/ecto.ex">>, + <<"integration_test/cases">>,<<"integration_test/cases/type.exs">>, + <<"integration_test/cases/interval.exs">>, + <<"integration_test/cases/preload.exs">>, + <<"integration_test/cases/assoc.exs">>, + <<"integration_test/cases/joins.exs">>, + <<"integration_test/cases/windows.exs">>, + <<"integration_test/cases/repo.exs">>,<<"integration_test/support">>, + <<"integration_test/support/schemas.exs">>, + <<"integration_test/support/types.exs">>]}. +{<<"requirements">>, + [[{<<"name">>,<<"telemetry">>}, + {<<"app">>,<<"telemetry">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.4 or ~> 1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"decimal">>}, + {<<"app">>,<<"decimal">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 2.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"jason">>}, + {<<"app">>,<<"jason">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 1.0">>}, + {<<"repository">>,<<"hexpm">>}]]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/ecto/integration_test/cases/assoc.exs b/deps/ecto/integration_test/cases/assoc.exs new file mode 100644 index 0000000000000000000000000000000000000000..fe2eeb192719b1a5cc9dd2d4d9e2d35552940026 --- /dev/null +++ b/deps/ecto/integration_test/cases/assoc.exs @@ -0,0 +1,865 @@ +defmodule Ecto.Integration.AssocTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.TestRepo + import Ecto.Query + + alias Ecto.Integration.Custom + alias Ecto.Integration.Post + alias Ecto.Integration.User + alias Ecto.Integration.PostUser + alias Ecto.Integration.Comment + alias Ecto.Integration.Permalink + + test "has_many assoc" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + [c1, c2] = TestRepo.all Ecto.assoc(p1, :comments) + assert c1.id == cid1 + assert c2.id == cid2 + + [c1, c2, c3] = TestRepo.all Ecto.assoc([p1, p2], :comments) + assert c1.id == cid1 + assert c2.id == cid2 + assert c3.id == cid3 + end + + test "has_one assoc" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + %Permalink{id: lid1} = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id}) + %Permalink{} = TestRepo.insert!(%Permalink{url: "2"}) + %Permalink{id: lid3} = TestRepo.insert!(%Permalink{url: "3", post_id: p2.id}) + + [l1, l3] = TestRepo.all Ecto.assoc([p1, p2], :permalink) + assert l1.id == lid1 + assert l3.id == lid3 + end + + test "belongs_to assoc" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + + l1 = TestRepo.insert!(%Permalink{url: "1", post_id: pid1}) + l2 = TestRepo.insert!(%Permalink{url: "2"}) + l3 = TestRepo.insert!(%Permalink{url: "3", post_id: pid2}) + + assert [p1, p2] = TestRepo.all Ecto.assoc([l1, l2, l3], :post) + assert p1.id == pid1 + assert p2.id == pid2 + end + + test "has_many through assoc" do + p1 = TestRepo.insert!(%Post{}) + p2 = TestRepo.insert!(%Post{}) + + u1 = TestRepo.insert!(%User{name: "zzz"}) + u2 = TestRepo.insert!(%User{name: "aaa"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id}) + + query = Ecto.assoc([p1, p2], :comments_authors) |> order_by([a], a.name) + assert [^u2, ^u1] = TestRepo.all(query) + + # Dynamic through + query = Ecto.assoc([p1, p2], [:comments, :author]) |> order_by([a], a.name) + assert [^u2, ^u1] = TestRepo.all(query) + end + + @tag :on_replace_nilify + test "has_many through-through assoc leading" do + p1 = TestRepo.insert!(%Post{}) + p2 = TestRepo.insert!(%Post{}) + + u1 = TestRepo.insert!(%User{}) + u2 = TestRepo.insert!(%User{}) + + pl1 = TestRepo.insert!(%Permalink{user_id: u1.id, url: "zzz"}) + pl2 = TestRepo.insert!(%Permalink{user_id: u2.id, url: "aaa"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id}) + + query = Ecto.assoc([p1, p2], :comments_authors_permalinks) |> order_by([p], p.url) + assert [^pl2, ^pl1] = TestRepo.all(query) + + # Dynamic through + query = Ecto.assoc([p1, p2], [:comments, :author, :permalink]) |> order_by([p], p.url) + assert [^pl2, ^pl1] = TestRepo.all(query) + end + + test "has_many through-through assoc trailing" do + p1 = TestRepo.insert!(%Post{}) + u1 = TestRepo.insert!(%User{}) + pl1 = TestRepo.insert!(%Permalink{user_id: u1.id, post_id: p1.id}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + + query = Ecto.assoc([pl1], :post_comments_authors) + assert [^u1] = TestRepo.all(query) + + # Dynamic through + query = Ecto.assoc([pl1], [:post, :comments, :author]) + assert [^u1] = TestRepo.all(query) + end + + test "has_many through has_many, many_to_many and has_many" do + user1 = %User{id: uid1} = TestRepo.insert!(%User{name: "Gabriel"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "Isadora"}) + %User{id: uid3} = TestRepo.insert!(%User{name: "Joey Mush"}) + + p1 = TestRepo.insert!(%Post{title: "p1", author_id: uid1}) + p2 = TestRepo.insert!(%Post{title: "p2", author_id: uid2}) + p3 = TestRepo.insert!(%Post{title: "p3", author_id: uid2}) + TestRepo.insert!(%Post{title: "p4", author_id: uid3}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1], + [post_id: p1.id, user_id: uid2], + [post_id: p2.id, user_id: uid3]] + + [pid1, pid2, pid3] = + Ecto.assoc(user1, :related_2nd_order_posts) + |> TestRepo.all() + |> Enum.map(fn %Post{id: id} -> id end) + |> Enum.sort() + + assert p1.id == pid1 + assert p2.id == pid2 + assert p3.id == pid3 + end + + test "has_many through has_many, belongs_to and a nested has through" do + user1 = TestRepo.insert!(%User{name: "Gabriel"}) + user2 = TestRepo.insert!(%User{name: "Isadora"}) + user3 = TestRepo.insert!(%User{name: "Joey"}) + + post1 = TestRepo.insert!(%Post{title: "p1"}) + post2 = TestRepo.insert!(%Post{title: "p2"}) + + TestRepo.insert!(%Comment{author_id: user1.id, text: "c1", post_id: post1.id}) + TestRepo.insert!(%Comment{author_id: user2.id, text: "c2", post_id: post1.id}) + TestRepo.insert!(%Comment{author_id: user3.id, text: "c3", post_id: post2.id}) + + [u1_id, u2_id] = + Ecto.assoc(user1, :co_commenters) + |> TestRepo.all() + |> Enum.map(fn %User{id: id} -> id end) + |> Enum.sort() + + assert u1_id == user1.id + assert u2_id == user2.id + end + + test "has_many through two many_to_many associations" do + user1 = %User{id: uid1} = TestRepo.insert!(%User{name: "Gabriel"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "Isadora"}) + %User{id: uid3} = TestRepo.insert!(%User{name: "Joey Mush"}) + + p1 = TestRepo.insert!(%Post{title: "p1", author_id: uid1}) + TestRepo.insert!(%Post{title: "p2", author_id: uid2}) + p3 = TestRepo.insert!(%Post{title: "p3", author_id: uid2}) + p4 = TestRepo.insert!(%Post{title: "p4", author_id: uid3}) + + TestRepo.insert_all "posts_users", [[post_id: p3.id, user_id: uid1], + [post_id: p3.id, user_id: uid2], + [post_id: p1.id, user_id: uid3]] + + TestRepo.insert!(%PostUser{post_id: p1.id, user_id: uid2}) + TestRepo.insert!(%PostUser{post_id: p3.id, user_id: uid1}) + TestRepo.insert!(%PostUser{post_id: p3.id, user_id: uid2}) + TestRepo.insert!(%PostUser{post_id: p4.id, user_id: uid3}) + + [u1, u2] = + Ecto.assoc(user1, :users_through_schema_posts) + |> TestRepo.all() + |> Enum.map(fn %User{id: id} -> id end) + |> Enum.sort() + + assert uid1 == u1 + assert uid2 == u2 + end + + test "has_many through with where" do + post1 = TestRepo.insert!(%Post{title: "p1"}) + post2 = TestRepo.insert!(%Post{title: "p2"}) + post3 = TestRepo.insert!(%Post{title: "p3"}) + + author = TestRepo.insert!(%User{name: "john"}) + + TestRepo.insert!(%Comment{text: "1", lock_version: 1, post_id: post1.id, author_id: author.id}) + TestRepo.insert!(%Comment{text: "2", lock_version: 2, post_id: post2.id, author_id: author.id}) + TestRepo.insert!(%Comment{text: "3", lock_version: 2, post_id: post3.id, author_id: author.id}) + + [p2, p3] = Ecto.assoc(author, :v2_comments_posts) |> TestRepo.all() |> Enum.sort_by(&(&1.id)) + assert p2.id == post2.id + assert p3.id == post3.id + end + + test "many_to_many assoc" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "john"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "mary"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1], + [post_id: p1.id, user_id: uid2], + [post_id: p2.id, user_id: uid2]] + + [u1, u2] = TestRepo.all Ecto.assoc([p1], :users) + assert u1.id == uid1 + assert u2.id == uid2 + + [u2] = TestRepo.all Ecto.assoc([p2], :users) + assert u2.id == uid2 + [] = TestRepo.all Ecto.assoc([p3], :users) + + [u1, u2, u2] = TestRepo.all Ecto.assoc([p1, p2, p3], :users) + assert u1.id == uid1 + assert u2.id == uid2 + end + + ## Changesets + + test "has_one changeset assoc (on_replace: :delete)" do + # Insert new + changeset = + %Post{title: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "1"}) + post = TestRepo.insert!(changeset) + assert post.permalink.id + assert post.permalink.post_id == post.id + assert post.permalink.url == "1" + post = TestRepo.get!(from(Post, preload: [:permalink]), post.id) + assert post.permalink.url == "1" + + # Replace with new + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "2"}) + post = TestRepo.update!(changeset) + assert post.permalink.id + assert post.permalink.post_id == post.id + assert post.permalink.url == "2" + post = TestRepo.get!(from(Post, preload: [:permalink]), post.id) + assert post.permalink.url == "2" + + # Replacing with existing + existing = TestRepo.insert!(%Permalink{url: "3"}) + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, existing) + post = TestRepo.update!(changeset) + assert post.permalink.id + assert post.permalink.post_id == post.id + assert post.permalink.url == "3" + post = TestRepo.get!(from(Post, preload: [:permalink]), post.id) + assert post.permalink.url == "3" + + # Replacing with nil (on_replace: :delete) + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, nil) + post = TestRepo.update!(changeset) + refute post.permalink + post = TestRepo.get!(from(Post, preload: [:permalink]), post.id) + refute post.permalink + + assert [0] == TestRepo.all(from(p in Permalink, select: count(p.id))) + end + + test "has_one changeset assoc (on_replace: :delete_if_exists)" do + permalink = TestRepo.insert!(%Permalink{url: "1"}) + post = TestRepo.insert!(%Post{title: "1", permalink: permalink, force_permalink: permalink}) + TestRepo.delete!(permalink) + + assert_raise Ecto.StaleEntryError, fn -> + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:permalink, nil) + |> TestRepo.update!() + end + + post = + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:force_permalink, nil) + |> TestRepo.update!() + + assert post.force_permalink == nil + end + + @tag :on_replace_nilify + test "has_one changeset assoc (on_replace: :nilify)" do + # Insert new + changeset = + %User{name: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "1"}) + user = TestRepo.insert!(changeset) + assert user.permalink.id + assert user.permalink.user_id == user.id + assert user.permalink.url == "1" + user = TestRepo.get!(from(User, preload: [:permalink]), user.id) + assert user.permalink.url == "1" + + # Replace with new + changeset = + user + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, %Permalink{url: "2"}) + user = TestRepo.update!(changeset) + assert user.permalink.id + assert user.permalink.user_id == user.id + assert user.permalink.url == "2" + user = TestRepo.get!(from(User, preload: [:permalink]), user.id) + assert user.permalink.url == "2" + + # Replacing with nil (on_replace: :nilify) + changeset = + user + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:permalink, nil) + user = TestRepo.update!(changeset) + refute user.permalink + user = TestRepo.get!(from(User, preload: [:permalink]), user.id) + refute user.permalink + + assert [2] == TestRepo.all(from(p in Permalink, select: count(p.id))) + end + + @tag :on_replace_update + test "has_one changeset assoc (on_replace: :update)" do + # Insert new + changeset = + %Post{title: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:update_permalink, %Permalink{url: "1"}) + post = TestRepo.insert!(changeset) + assert post.update_permalink.id + assert post.update_permalink.post_id == post.id + assert post.update_permalink.url == "1" + post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id) + assert post.update_permalink.url == "1" + + perma = post.update_permalink + + # Put on update + changeset = + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:update_permalink, %{url: "2"}) + post = TestRepo.update!(changeset) + assert post.update_permalink.id == perma.id + assert post.update_permalink.post_id == post.id + assert post.update_permalink.url == "2" + post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id) + assert post.update_permalink.url == "2" + + # Cast on update + changeset = + post + |> Ecto.Changeset.cast(%{update_permalink: %{url: "3"}}, []) + |> Ecto.Changeset.cast_assoc(:update_permalink) + post = TestRepo.update!(changeset) + assert post.update_permalink.id == perma.id + assert post.update_permalink.post_id == post.id + assert post.update_permalink.url == "3" + post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id) + assert post.update_permalink.url == "3" + + # Replace with new struct + assert_raise RuntimeError, ~r"you are only allowed\sto update the existing entry", fn -> + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:update_permalink, %Permalink{url: "4"}) + end + + # Replace with existing struct + assert_raise RuntimeError, ~r"you are only allowed\sto update the existing entry", fn -> + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:update_permalink, TestRepo.insert!(%Permalink{url: "5"})) + end + + # Replacing with nil (on_replace: :update) + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:update_permalink, nil) + post = TestRepo.update!(changeset) + refute post.update_permalink + post = TestRepo.get!(from(Post, preload: [:update_permalink]), post.id) + refute post.update_permalink + + assert [2] == TestRepo.all(from(p in Permalink, select: count(p.id))) + end + + test "has_many changeset assoc (on_replace: :delete)" do + c1 = TestRepo.insert! %Comment{text: "1"} + c2 = %Comment{text: "2"} + + # Inserting + changeset = + %Post{title: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:comments, [c2]) + post = TestRepo.insert!(changeset) + [c2] = post.comments + assert c2.id + assert c2.post_id == post.id + post = TestRepo.get!(from(Post, preload: [:comments]), post.id) + [c2] = post.comments + assert c2.text == "2" + + # Updating + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:comments, [Ecto.Changeset.change(c1, text: "11"), + Ecto.Changeset.change(c2, text: "22")]) + post = TestRepo.update!(changeset) + [c1, _c2] = post.comments |> Enum.sort_by(&(&1.id)) + assert c1.id + assert c1.post_id == post.id + post = TestRepo.get!(from(Post, preload: [:comments]), post.id) + [c1, c2] = post.comments |> Enum.sort_by(&(&1.id)) + assert c1.text == "11" + assert c2.text == "22" + + # Replacing (on_replace: :delete) + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:comments, []) + post = TestRepo.update!(changeset) + assert post.comments == [] + post = TestRepo.get!(from(Post, preload: [:comments]), post.id) + assert post.comments == [] + + assert [0] == TestRepo.all(from(c in Comment, select: count(c.id))) + end + + test "has_many changeset assoc (on_replace: :delete_if_exists)" do + comment = TestRepo.insert!(%Comment{text: "1"}) + post = TestRepo.insert!(%Post{title: "1", comments: [comment], force_comments: [comment]}) + + TestRepo.delete!(comment) + + assert_raise Ecto.StaleEntryError, fn -> + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:comments, []) + |> TestRepo.update!() + end + + post = + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:force_comments, []) + |> TestRepo.update!() + + assert post.force_comments == [] + end + + test "has_many changeset assoc (on_replace: :nilify)" do + c1 = TestRepo.insert! %Comment{text: "1"} + c2 = %Comment{text: "2"} + + # Inserting + changeset = + %User{name: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:comments, [c1, c2]) + user = TestRepo.insert!(changeset) + [c1, c2] = user.comments + assert c1.id + assert c1.author_id == user.id + assert c2.id + assert c2.author_id == user.id + user = TestRepo.get!(from(User, preload: [:comments]), user.id) + [c1, c2] = user.comments + assert c1.text == "1" + assert c2.text == "2" + + # Replacing (on_replace: :nilify) + changeset = + user + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:comments, []) + user = TestRepo.update!(changeset) + assert user.comments == [] + user = TestRepo.get!(from(User, preload: [:comments]), user.id) + assert user.comments == [] + + assert [2] == TestRepo.all(from(c in Comment, select: count(c.id))) + end + + test "many_to_many changeset assoc" do + u1 = TestRepo.insert! %User{name: "1"} + u2 = %User{name: "2"} + + # Inserting + changeset = + %Post{title: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:users, [u2]) + post = TestRepo.insert!(changeset) + [u2] = post.users + assert u2.id + post = TestRepo.get!(from(Post, preload: [:users]), post.id) + [u2] = post.users + assert u2.name == "2" + + assert [1] == TestRepo.all(from(j in "posts_users", select: count(j.post_id))) + + # Updating + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:users, [Ecto.Changeset.change(u1, name: "11"), + Ecto.Changeset.change(u2, name: "22")]) + post = TestRepo.update!(changeset) + [u1, _u2] = post.users |> Enum.sort_by(&(&1.id)) + assert u1.id + post = TestRepo.get!(from(Post, preload: [:users]), post.id) + [u1, u2] = post.users |> Enum.sort_by(&(&1.id)) + assert u1.name == "11" + assert u2.name == "22" + + assert [2] == TestRepo.all(from(j in "posts_users", select: count(j.post_id))) + + # Replacing (on_replace: :delete) + changeset = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:users, []) + post = TestRepo.update!(changeset) + assert post.users == [] + post = TestRepo.get!(from(Post, preload: [:users]), post.id) + assert post.users == [] + + assert [0] == TestRepo.all(from(j in "posts_users", select: count(j.post_id))) + assert [2] == TestRepo.all(from(c in User, select: count(c.id))) + end + + test "many_to_many changeset assoc with schema" do + p1 = TestRepo.insert! %Post{title: "1"} + p2 = %Post{title: "2"} + + # Inserting + changeset = + %User{name: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:schema_posts, [p2]) + user = TestRepo.insert!(changeset) + [p2] = user.schema_posts + assert p2.id + user = TestRepo.get!(from(User, preload: [:schema_posts]), user.id) + [p2] = user.schema_posts + assert p2.title == "2" + + [up2] = TestRepo.all(PostUser) |> Enum.sort_by(&(&1.id)) + assert up2.post_id == p2.id + assert up2.user_id == user.id + assert up2.inserted_at + assert up2.updated_at + + # Updating + changeset = + user + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:schema_posts, [Ecto.Changeset.change(p1, title: "11"), + Ecto.Changeset.change(p2, title: "22")]) + user = TestRepo.update!(changeset) + [p1, _p2] = user.schema_posts |> Enum.sort_by(&(&1.id)) + assert p1.id + user = TestRepo.get!(from(User, preload: [:schema_posts]), user.id) + [p1, p2] = user.schema_posts |> Enum.sort_by(&(&1.id)) + assert p1.title == "11" + assert p2.title == "22" + + [_up2, up1] = TestRepo.all(PostUser) |> Enum.sort_by(&(&1.id)) + assert up1.post_id == p1.id + assert up1.user_id == user.id + assert up1.inserted_at + assert up1.updated_at + end + + test "many_to_many changeset assoc with self-referential binary_id" do + assoc_custom = TestRepo.insert!(%Custom{uuid: Ecto.UUID.generate()}) + custom = TestRepo.insert!(%Custom{customs: [assoc_custom]}) + + custom = Custom |> TestRepo.get!(custom.bid) |> TestRepo.preload(:customs) + assert [_] = custom.customs + + custom = + custom + |> Ecto.Changeset.change(%{}) + |> Ecto.Changeset.put_assoc(:customs, []) + |> TestRepo.update! + assert [] = custom.customs + + custom = Custom |> TestRepo.get!(custom.bid) |> TestRepo.preload(:customs) + assert [] = custom.customs + end + + @tag :unique_constraint + test "has_many changeset assoc with constraints" do + author = TestRepo.insert!(%User{name: "john doe"}) + p1 = TestRepo.insert!(%Post{title: "hello", author_id: author.id}) + TestRepo.insert!(%Post{title: "world", author_id: author.id}) + + # Asserts that `unique_constraint` for `uuid` exists + assert_raise Ecto.ConstraintError, fn -> + TestRepo.insert!(%Post{title: "another", author_id: author.id, uuid: p1.uuid}) + end + + author = TestRepo.preload author, [:posts] + posts_params = Enum.map author.posts, fn %Post{uuid: u} -> + %{uuid: u, title: "fresh"} + end + + # This will only work if we delete before performing inserts + changeset = + author + |> Ecto.Changeset.cast(%{"posts" => posts_params}, ~w()) + |> Ecto.Changeset.cast_assoc(:posts) + author = TestRepo.update! changeset + assert Enum.map(author.posts, &(&1.title)) == ["fresh", "fresh"] + end + + test "belongs_to changeset assoc" do + # Insert new + changeset = + %Permalink{url: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:post, %Post{title: "1"}) + perma = TestRepo.insert!(changeset) + post = perma.post + assert perma.post_id + assert perma.post_id == post.id + assert perma.post.title == "1" + + # Replace with new + changeset = + perma + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:post, %Post{title: "2"}) + perma = TestRepo.update!(changeset) + assert perma.post.id != post.id + post = perma.post + assert perma.post_id + assert perma.post_id == post.id + assert perma.post.title == "2" + + # Replace with existing + existing = TestRepo.insert!(%Post{title: "3"}) + changeset = + perma + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:post, existing) + perma = TestRepo.update!(changeset) + post = perma.post + assert perma.post_id == post.id + assert perma.post_id == existing.id + assert perma.post.title == "3" + + # Replace with nil + changeset = + perma + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:post, nil) + perma = TestRepo.update!(changeset) + assert perma.post == nil + assert perma.post_id == nil + end + + test "belongs_to changeset assoc (on_replace: :update)" do + # Insert new + changeset = + %Permalink{url: "1"} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:update_post, %Post{title: "1"}) + perma = TestRepo.insert!(changeset) + post = perma.update_post + assert perma.post_id + assert perma.post_id == post.id + assert perma.update_post.title == "1" + + # Casting on update + changeset = + perma + |> Ecto.Changeset.cast(%{update_post: %{title: "2"}}, []) + |> Ecto.Changeset.cast_assoc(:update_post) + perma = TestRepo.update!(changeset) + assert perma.update_post.id == post.id + post = perma.update_post + assert perma.post_id + assert perma.post_id == post.id + assert perma.update_post.title == "2" + + # Replace with nil + changeset = + perma + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:update_post, nil) + perma = TestRepo.update!(changeset) + assert perma.update_post == nil + assert perma.post_id == nil + end + + test "inserting struct with associations" do + tree = %Permalink{ + url: "root", + post: %Post{ + title: "belongs_to", + comments: [ + %Comment{text: "child 1"}, + %Comment{text: "child 2"}, + ] + } + } + + tree = TestRepo.insert!(tree) + assert tree.id + assert tree.post.id + assert length(tree.post.comments) == 2 + assert Enum.all?(tree.post.comments, & &1.id) + + tree = TestRepo.get!(from(Permalink, preload: [post: :comments]), tree.id) + assert tree.id + assert tree.post.id + assert length(tree.post.comments) == 2 + assert Enum.all?(tree.post.comments, & &1.id) + end + + test "inserting struct with empty associations" do + permalink = TestRepo.insert!(%Permalink{url: "root", post: nil}) + assert permalink.post == nil + + post = TestRepo.insert!(%Post{title: "empty", comments: []}) + assert post.comments == [] + end + + test "inserting changeset with empty cast associations" do + changeset = + %Permalink{} + |> Ecto.Changeset.cast(%{url: "root", post: nil}, [:url]) + |> Ecto.Changeset.cast_assoc(:post) + permalink = TestRepo.insert!(changeset) + assert permalink.post == nil + + changeset = + %Post{} + |> Ecto.Changeset.cast(%{title: "root", comments: []}, [:title]) + |> Ecto.Changeset.cast_assoc(:comments) + post = TestRepo.insert!(changeset) + assert post.comments == [] + end + + test "inserting changeset with empty put associations" do + changeset = + %Permalink{} + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:post, nil) + permalink = TestRepo.insert!(changeset) + assert permalink.post == nil + + changeset = + %Post{} + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:comments, []) + post = TestRepo.insert!(changeset) + assert post.comments == [] + end + + test "updating changeset with empty cast associations" do + post = TestRepo.insert!(%Post{}) + c1 = TestRepo.insert!(%Comment{post_id: post.id}) + c2 = TestRepo.insert!(%Comment{post_id: post.id}) + + assert TestRepo.all(Comment) == [c1, c2] + + post = TestRepo.get!(from(Post, preload: [:comments]), post.id) + + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:comments, []) + |> TestRepo.update!() + + assert TestRepo.all(Comment) == [] + end + + ## Dependent + + test "has_many assoc on delete deletes all" do + post = TestRepo.insert!(%Post{}) + TestRepo.insert!(%Comment{post_id: post.id}) + TestRepo.insert!(%Comment{post_id: post.id}) + TestRepo.delete!(post) + + assert TestRepo.all(Comment) == [] + refute Process.get(Comment) + end + + test "has_many assoc on delete nilifies all" do + user = TestRepo.insert!(%User{}) + TestRepo.insert!(%Comment{author_id: user.id}) + TestRepo.insert!(%Comment{author_id: user.id}) + TestRepo.delete!(user) + + author_ids = Comment |> TestRepo.all() |> Enum.map(fn(comment) -> comment.author_id end) + + assert author_ids == [nil, nil] + refute Process.get(Comment) + end + + test "has_many assoc on delete does nothing" do + user = TestRepo.insert!(%User{}) + TestRepo.insert!(%Post{author_id: user.id}) + + TestRepo.delete!(user) + assert Enum.count(TestRepo.all(Post)) == 1 + end + + test "many_to_many assoc on delete deletes all" do + p1 = TestRepo.insert!(%Post{title: "1", visits: 1}) + p2 = TestRepo.insert!(%Post{title: "2", visits: 2}) + + u1 = TestRepo.insert!(%User{name: "john"}) + u2 = TestRepo.insert!(%User{name: "mary"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: u1.id], + [post_id: p1.id, user_id: u1.id], + [post_id: p2.id, user_id: u2.id]] + TestRepo.delete!(p1) + + [pid2] = TestRepo.all from(p in Post, select: p.id) + assert pid2 == p2.id + + [[pid2, uid2]] = TestRepo.all from(j in "posts_users", select: [j.post_id, j.user_id]) + assert pid2 == p2.id + assert uid2 == u2.id + + [uid1, uid2] = TestRepo.all from(u in User, select: u.id) + assert uid1 == u1.id + assert uid2 == u2.id + end +end diff --git a/deps/ecto/integration_test/cases/interval.exs b/deps/ecto/integration_test/cases/interval.exs new file mode 100644 index 0000000000000000000000000000000000000000..0954bc9c1f69c2b46dddf6bc37c8540ffbff1199 --- /dev/null +++ b/deps/ecto/integration_test/cases/interval.exs @@ -0,0 +1,419 @@ +defmodule Ecto.Integration.IntervalTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.{Post, User, Usec} + alias Ecto.Integration.TestRepo + import Ecto.Query + + @posted ~D[2014-01-01] + @inserted_at ~N[2014-01-01 02:00:00] + + setup do + TestRepo.insert!(%Post{posted: @posted, inserted_at: @inserted_at}) + :ok + end + + test "date_add with year" do + dec = Decimal.new(1) + assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 1, "year")) + assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 1.0, "year")) + assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^1, "year")) + assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^1.0, "year")) + assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "year")) + end + + test "date_add with month" do + dec = Decimal.new(3) + assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3, "month")) + assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3.0, "month")) + assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3, "month")) + assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3.0, "month")) + assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "month")) + end + + test "date_add with week" do + dec = Decimal.new(3) + assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3, "week")) + assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, 3.0, "week")) + assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3, "week")) + assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^3.0, "week")) + assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "week")) + end + + test "date_add with day" do + dec = Decimal.new(5) + assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, 5, "day")) + assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, 5.0, "day")) + assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^5, "day")) + assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^5.0, "day")) + assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "day")) + end + + test "date_add with hour" do + dec = Decimal.new(48) + assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, 48, "hour")) + assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, 48.0, "hour")) + assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^48, "hour")) + assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^48.0, "hour")) + assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "hour")) + end + + test "date_add with dynamic" do + posted = @posted + assert [~D[2015-01-01]] = TestRepo.all(from p in Post, select: date_add(^posted, ^1, ^"year")) + assert [~D[2014-04-01]] = TestRepo.all(from p in Post, select: date_add(^posted, ^3, ^"month")) + assert [~D[2014-01-22]] = TestRepo.all(from p in Post, select: date_add(^posted, ^3, ^"week")) + assert [~D[2014-01-06]] = TestRepo.all(from p in Post, select: date_add(^posted, ^5, ^"day")) + assert [~D[2014-01-03]] = TestRepo.all(from p in Post, select: date_add(^posted, ^48, ^"hour")) + end + + test "date_add with negative interval" do + dec = Decimal.new(-1) + assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, -1, "year")) + assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, -1.0, "year")) + assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^-1, "year")) + assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^-1.0, "year")) + assert [~D[2013-01-01]] = TestRepo.all(from p in Post, select: date_add(p.posted, ^dec, "year")) + end + + test "datetime_add with year" do + dec = Decimal.new(1) + assert [~N[2015-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1, "year")) + assert [~N[2015-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1.0, "year")) + assert [~N[2015-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1, "year")) + assert [~N[2015-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1.0, "year")) + assert [~N[2015-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "year")) + end + + test "datetime_add with month" do + dec = Decimal.new(3) + assert [~N[2014-04-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3, "month")) + assert [~N[2014-04-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3.0, "month")) + assert [~N[2014-04-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3, "month")) + assert [~N[2014-04-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3.0, "month")) + assert [~N[2014-04-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "month")) + end + + test "datetime_add with week" do + dec = Decimal.new(3) + assert [~N[2014-01-22 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3, "week")) + assert [~N[2014-01-22 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 3.0, "week")) + assert [~N[2014-01-22 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3, "week")) + assert [~N[2014-01-22 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^3.0, "week")) + assert [~N[2014-01-22 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "week")) + end + + test "datetime_add with day" do + dec = Decimal.new(5) + assert [~N[2014-01-06 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 5, "day")) + assert [~N[2014-01-06 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 5.0, "day")) + assert [~N[2014-01-06 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^5, "day")) + assert [~N[2014-01-06 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^5.0, "day")) + assert [~N[2014-01-06 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "day")) + end + + test "datetime_add with hour" do + dec = Decimal.new(60) + assert [~N[2014-01-03 14:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 60, "hour")) + assert [~N[2014-01-03 14:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 60.0, "hour")) + assert [~N[2014-01-03 14:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^60, "hour")) + assert [~N[2014-01-03 14:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^60.0, "hour")) + assert [~N[2014-01-03 14:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "hour")) + end + + test "datetime_add with minute" do + dec = Decimal.new(90) + assert [~N[2014-01-01 03:30:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90, "minute")) + assert [~N[2014-01-01 03:30:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90.0, "minute")) + assert [~N[2014-01-01 03:30:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90, "minute")) + assert [~N[2014-01-01 03:30:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90.0, "minute")) + assert [~N[2014-01-01 03:30:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "minute")) + end + + test "datetime_add with second" do + dec = Decimal.new(90) + assert [~N[2014-01-01 02:01:30]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90, "second")) + assert [~N[2014-01-01 02:01:30]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 90.0, "second")) + assert [~N[2014-01-01 02:01:30]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90, "second")) + assert [~N[2014-01-01 02:01:30]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^90.0, "second")) + assert [~N[2014-01-01 02:01:30]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "second")) + end + + @tag :uses_msec + test "datetime_add with millisecond" do + dec = Decimal.new(1500) + assert [~N[2014-01-01 02:00:01]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500, "millisecond")) + assert [~N[2014-01-01 02:00:01]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500.0, "millisecond")) + assert [~N[2014-01-01 02:00:01]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500, "millisecond")) + assert [~N[2014-01-01 02:00:01]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500.0, "millisecond")) + assert [~N[2014-01-01 02:00:01]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "millisecond")) + end + + @tag :microsecond_precision + @tag :uses_usec + test "datetime_add with microsecond" do + dec = Decimal.new(1500) + assert [~N[2014-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500, "microsecond")) + assert [~N[2014-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, 1500.0, "microsecond")) + assert [~N[2014-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500, "microsecond")) + assert [~N[2014-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^1500.0, "microsecond")) + assert [~N[2014-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "microsecond")) + end + + test "datetime_add with dynamic" do + inserted_at = @inserted_at + assert [~N[2015-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^1, ^"year")) + assert [~N[2014-04-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^3, ^"month")) + assert [~N[2014-01-22 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^3, ^"week")) + assert [~N[2014-01-06 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^5, ^"day")) + assert [~N[2014-01-03 14:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^60, ^"hour")) + assert [~N[2014-01-01 03:30:00]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^90, ^"minute")) + assert [~N[2014-01-01 02:01:30]] = + TestRepo.all(from p in Post, select: datetime_add(^inserted_at, ^90, ^"second")) + end + + test "datetime_add with dynamic in filters" do + inserted_at = @inserted_at + field = :inserted_at + assert [_] = + TestRepo.all(from p in Post, where: p.inserted_at > datetime_add(^inserted_at, ^-1, "year")) + assert [_] = + TestRepo.all(from p in Post, where: p.inserted_at > datetime_add(^inserted_at, -3, "month")) + assert [_] = + TestRepo.all(from p in Post, where: field(p, ^field) > datetime_add(^inserted_at, ^-3, ^"week")) + assert [_] = + TestRepo.all(from p in Post, where: field(p, ^field) > datetime_add(^inserted_at, -5, ^"day")) + end + + test "datetime_add with negative interval" do + dec = Decimal.new(-1) + assert [~N[2013-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, -1, "year")) + assert [~N[2013-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, -1.0, "year")) + assert [~N[2013-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^-1, "year")) + assert [~N[2013-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^-1.0, "year")) + assert [~N[2013-01-01 02:00:00]] = + TestRepo.all(from p in Post, select: datetime_add(p.inserted_at, ^dec, "year")) + end + + test "from_now" do + current = DateTime.utc_now().year + dec = Decimal.new(5) + assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(5, "year")) + assert year > current + assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(5.0, "year")) + assert year > current + assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(^5, "year")) + assert year > current + assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(^5.0, "year")) + assert year > current + assert [%{year: year}] = TestRepo.all(from p in Post, select: from_now(^dec, "year")) + assert year > current + end + + test "ago" do + current = DateTime.utc_now().year + dec = Decimal.new(5) + assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(5, "year")) + assert year < current + assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(5.0, "year")) + assert year < current + assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(^5, "year")) + assert year < current + assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(^5.0, "year")) + assert year < current + assert [%{year: year}] = TestRepo.all(from p in Post, select: ago(^dec, "year")) + assert year < current + end + + test "datetime_add with utc_datetime" do + {:ok, datetime} = DateTime.from_naive(@inserted_at, "Etc/UTC") + TestRepo.insert!(%User{inserted_at: datetime}) + + {:ok, datetime} = DateTime.from_naive(~N[2015-01-01 02:00:00], "Etc/UTC") + dec = Decimal.new(1) + + assert [^datetime] = + TestRepo.all(from p in User, select: datetime_add(type(^datetime, :utc_datetime), 0, "year")) + assert [^datetime] = + TestRepo.all(from p in User, select: datetime_add(p.inserted_at, 1, "year")) + assert [^datetime] = + TestRepo.all(from p in User, select: datetime_add(p.inserted_at, 1.0, "year")) + assert [^datetime] = + TestRepo.all(from p in User, select: datetime_add(p.inserted_at, ^1, "year")) + assert [^datetime] = + TestRepo.all(from p in User, select: datetime_add(p.inserted_at, ^1.0, "year")) + assert [^datetime] = + TestRepo.all(from p in User, select: datetime_add(p.inserted_at, ^dec, "year")) + end + + @tag :microsecond_precision + test "datetime_add with naive_datetime_usec" do + TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.000001]}) + datetime = ~N[2014-01-01 02:00:00.001501] + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :naive_datetime_usec), 0, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 1500, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 1500.0, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^1500, "microsecond")) + end + + @tag :microsecond_precision + @tag :decimal_precision + test "datetime_add with naive_datetime_usec and decimal increment" do + TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.000001]}) + dec = Decimal.new(1500) + datetime = ~N[2014-01-01 02:00:00.001501] + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^1500.0, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^dec, "microsecond")) + end + + @tag :microsecond_precision + test "datetime_add with utc_datetime_usec" do + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.000001], "Etc/UTC") + TestRepo.insert!(%Usec{utc_datetime_usec: datetime}) + + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001501], "Etc/UTC") + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :utc_datetime_usec), 0, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 1500, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 1500.0, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^1500, "microsecond")) + end + + @tag :microsecond_precision + @tag :decimal_precision + test "datetime_add uses utc_datetime_usec with decimal increment" do + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.000001], "Etc/UTC") + TestRepo.insert!(%Usec{utc_datetime_usec: datetime}) + + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001501], "Etc/UTC") + dec = Decimal.new(1500) + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^1500.0, "microsecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^dec, "microsecond")) + end + + test "datetime_add with utc_datetime_usec in milliseconds" do + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001000], "Etc/UTC") + TestRepo.insert!(%Usec{utc_datetime_usec: datetime}) + + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.151000], "Etc/UTC") + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :utc_datetime_usec), 0, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 150, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, 150, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^150, "millisecond")) + end + + @tag :decimal_precision + test "datetime_add uses utc_datetime_usec with decimal increment in milliseconds" do + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.001000], "Etc/UTC") + TestRepo.insert!(%Usec{utc_datetime_usec: datetime}) + + {:ok, datetime} = DateTime.from_naive(~N[2014-01-01 02:00:00.151000], "Etc/UTC") + dec = Decimal.new(150) + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^150.0, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.utc_datetime_usec, ^dec, "millisecond")) + end + + test "datetime_add with naive_datetime_usec in milliseconds" do + TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.001000]}) + datetime = ~N[2014-01-01 02:00:00.151000] + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(type(^datetime, :naive_datetime_usec), 0, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 150, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, 150.0, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^150, "millisecond")) + end + + @tag :decimal_precision + test "datetime_add with naive_datetime_usec and decimal increment in milliseconds" do + TestRepo.insert!(%Usec{naive_datetime_usec: ~N[2014-01-01 02:00:00.001000]}) + dec = Decimal.new(150) + datetime = ~N[2014-01-01 02:00:00.151000] + + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^150.0, "millisecond")) + assert [^datetime] = + TestRepo.all(from u in Usec, select: datetime_add(u.naive_datetime_usec, ^dec, "millisecond")) + end +end diff --git a/deps/ecto/integration_test/cases/joins.exs b/deps/ecto/integration_test/cases/joins.exs new file mode 100644 index 0000000000000000000000000000000000000000..50ee4d7a75ae98dc60eda3ce3ef85aecb0d9d2ed --- /dev/null +++ b/deps/ecto/integration_test/cases/joins.exs @@ -0,0 +1,672 @@ +defmodule Ecto.Integration.JoinsTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.TestRepo + import Ecto.Query + + alias Ecto.Integration.Post + alias Ecto.Integration.Comment + alias Ecto.Integration.Permalink + alias Ecto.Integration.User + alias Ecto.Integration.PostUserCompositePk + + @tag :update_with_join + test "update all with joins" do + user = TestRepo.insert!(%User{name: "Tester"}) + post = TestRepo.insert!(%Post{title: "foo"}) + comment = TestRepo.insert!(%Comment{text: "hey", author_id: user.id, post_id: post.id}) + + another_post = TestRepo.insert!(%Post{title: "bar"}) + another_comment = TestRepo.insert!(%Comment{text: "another", author_id: user.id, post_id: another_post.id}) + + query = from(c in Comment, join: u in User, on: u.id == c.author_id, + where: c.post_id in ^[post.id]) + + assert {1, nil} = TestRepo.update_all(query, set: [text: "hoo"]) + assert %Comment{text: "hoo"} = TestRepo.get(Comment, comment.id) + assert %Comment{text: "another"} = TestRepo.get(Comment, another_comment.id) + end + + @tag :delete_with_join + test "delete all with joins" do + user = TestRepo.insert!(%User{name: "Tester"}) + post = TestRepo.insert!(%Post{title: "foo"}) + TestRepo.insert!(%Comment{text: "hey", author_id: user.id, post_id: post.id}) + TestRepo.insert!(%Comment{text: "foo", author_id: user.id, post_id: post.id}) + TestRepo.insert!(%Comment{text: "bar", author_id: user.id}) + + query = from(c in Comment, join: u in User, on: u.id == c.author_id, + where: is_nil(c.post_id)) + assert {1, nil} = TestRepo.delete_all(query) + assert [%Comment{}, %Comment{}] = TestRepo.all(Comment) + + query = from(c in Comment, join: u in assoc(c, :author), + join: p in assoc(c, :post), + where: p.id in ^[post.id]) + assert {2, nil} = TestRepo.delete_all(query) + assert [] = TestRepo.all(Comment) + end + + test "joins" do + _p = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id}) + + query = from(p in Post, join: c in assoc(p, :permalink), order_by: p.id, select: {p, c}) + assert [{^p2, ^c1}] = TestRepo.all(query) + + query = from(p in Post, join: c in assoc(p, :permalink), on: c.id == ^c1.id, select: {p, c}) + assert [{^p2, ^c1}] = TestRepo.all(query) + end + + test "joins with queries" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id}) + + # Joined query without parameter + permalink = from c in Permalink, where: c.url == "1" + + query = from(p in Post, join: c in ^permalink, on: c.post_id == p.id, select: {p, c}) + assert [{^p2, ^c1}] = TestRepo.all(query) + + # Joined query with parameter + permalink = from c in Permalink, where: c.url == "1" + + query = from(p in Post, join: c in ^permalink, on: c.id == ^c1.id, order_by: p.title, select: {p, c}) + assert [{^p1, ^c1}, {^p2, ^c1}] = TestRepo.all(query) + end + + test "named joins" do + _p = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id}) + + query = + from(p in Post, join: c in assoc(p, :permalink), as: :permalink, order_by: p.id) + |> select([p, permalink: c], {p, c}) + + assert [{^p2, ^c1}] = TestRepo.all(query) + end + + test "joins with dynamic in :on" do + p = TestRepo.insert!(%Post{title: "1"}) + c = TestRepo.insert!(%Permalink{url: "1", post_id: p.id}) + + join_on = dynamic([p, ..., c], c.id == ^c.id) + + query = + from(p in Post, join: c in Permalink, on: ^join_on) + |> select([p, c], {p, c}) + + assert [{^p, ^c}] = TestRepo.all(query) + + join_on = dynamic([p, permalink: c], c.id == ^c.id) + + query = + from(p in Post, join: c in Permalink, as: :permalink, on: ^join_on) + |> select([p, c], {p, c}) + + assert [{^p, ^c}] = TestRepo.all(query) + end + + @tag :cross_join + test "cross joins with missing entries" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id}) + + query = from(p in Post, cross_join: c in Permalink, order_by: p.id, select: {p, c}) + assert [{^p1, ^c1}, {^p2, ^c1}] = TestRepo.all(query) + end + + @tag :left_join + test "left joins with missing entries" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id}) + + query = from(p in Post, left_join: c in assoc(p, :permalink), order_by: p.id, select: {p, c}) + assert [{^p1, nil}, {^p2, ^c1}] = TestRepo.all(query) + end + + @tag :left_join + test "left join with missing entries from subquery" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + c1 = TestRepo.insert!(%Permalink{url: "1", post_id: p2.id}) + + query = from(p in Post, left_join: c in subquery(Permalink), on: p.id == c.post_id, order_by: p.id, select: {p, c}) + assert [{^p1, nil}, {^p2, ^c1}] = TestRepo.all(query) + end + + @tag :right_join + test "right joins with missing entries" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + + %Permalink{id: plid1} = TestRepo.insert!(%Permalink{url: "1", post_id: pid2}) + + TestRepo.insert!(%Comment{text: "1", post_id: pid1}) + TestRepo.insert!(%Comment{text: "2", post_id: pid2}) + TestRepo.insert!(%Comment{text: "3", post_id: nil}) + + query = from(p in Post, right_join: c in assoc(p, :comments), + preload: :permalink, order_by: c.id) + assert [p1, p2, p3] = TestRepo.all(query) + assert p1.id == pid1 + assert p2.id == pid2 + assert is_nil(p3.id) + + assert p1.permalink == nil + assert p2.permalink.id == plid1 + end + + ## Associations joins + + test "has_many association join" do + post = TestRepo.insert!(%Post{title: "1"}) + c1 = TestRepo.insert!(%Comment{text: "hey", post_id: post.id}) + c2 = TestRepo.insert!(%Comment{text: "heya", post_id: post.id}) + + query = from(p in Post, join: c in assoc(p, :comments), select: {p, c}, order_by: p.id) + [{^post, ^c1}, {^post, ^c2}] = TestRepo.all(query) + end + + test "has_one association join" do + post1 = TestRepo.insert!(%Post{title: "1"}) + post2 = TestRepo.insert!(%Post{title: "1"}) + user = TestRepo.insert!(%User{}) + p1 = TestRepo.insert!(%Permalink{url: "hey", user_id: user.id, post_id: post1.id}) + p2 = TestRepo.insert!(%Permalink{url: "heya", user_id: user.id, post_id: post2.id}) + + query = from(p in User, join: c in assoc(p, :permalink), select: {p, c}, order_by: c.id) + [{^user, ^p1}, {^user, ^p2}] = TestRepo.all(query) + end + + test "belongs_to association join" do + post1 = TestRepo.insert!(%Post{title: "1"}) + post2 = TestRepo.insert!(%Post{title: "1"}) + user = TestRepo.insert!(%User{}) + p1 = TestRepo.insert!(%Permalink{url: "hey", user_id: user.id, post_id: post1.id}) + p2 = TestRepo.insert!(%Permalink{url: "heya", user_id: user.id, post_id: post2.id}) + + query = from(p in Permalink, join: c in assoc(p, :user), select: {p, c}, order_by: p.id) + [{^p1, ^user}, {^p2, ^user}] = TestRepo.all(query) + end + + test "has_many through association join" do + p1 = TestRepo.insert!(%Post{}) + p2 = TestRepo.insert!(%Post{}) + + u1 = TestRepo.insert!(%User{name: "zzz"}) + u2 = TestRepo.insert!(%User{name: "aaa"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id}) + + query = from p in Post, join: a in assoc(p, :comments_authors), select: {p, a}, order_by: [p.id, a.name] + assert [{^p1, ^u2}, {^p1, ^u1}, {^p1, ^u1}, {^p2, ^u2}] = TestRepo.all(query) + end + + test "has_many through nested association joins" do + u1 = TestRepo.insert!(%User{name: "Alice"}) + u2 = TestRepo.insert!(%User{name: "John"}) + + p1 = TestRepo.insert!(%Post{title: "p1", author_id: u1.id}) + p2 = TestRepo.insert!(%Post{title: "p2", author_id: u1.id}) + + TestRepo.insert!(%Comment{text: "c1", author_id: u1.id, post_id: p1.id}) + TestRepo.insert!(%Comment{text: "c2", author_id: u2.id, post_id: p1.id}) + TestRepo.insert!(%Comment{text: "c3", author_id: u2.id, post_id: p2.id}) + TestRepo.insert!(%Comment{text: "c4", post_id: p2.id}) + TestRepo.insert!(%Comment{text: "c5", author_id: u1.id, post_id: p2.id}) + + assert %{ + comments: [ + %{text: "c1"}, + %{text: "c5"} + ], + posts: [ + %{title: "p1"} = p1, + %{title: "p2"} = p2 + ] + } = + from(u in User) + |> join(:left, [u], p in assoc(u, :posts)) + |> join(:left, [u], c in assoc(u, :comments)) + |> join(:left, [_, p], c in assoc(p, :comments)) + |> preload( + [user, posts, comments, post_comments], + comments: comments, + posts: {posts, comments: {post_comments, :author}} + ) + |> TestRepo.get(u1.id) + + assert [ + %{text: "c1", author: %{name: "Alice"}}, + %{text: "c2", author: %{name: "John"}} + ] = Enum.sort_by(p1.comments, & &1.text) + + assert [ + %{text: "c3", author: %{name: "John"}}, + %{text: "c4", author: nil}, + %{text: "c5", author: %{name: "Alice"}} + ] = Enum.sort_by(p2.comments, & &1.text) + end + + test "many_to_many association join" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + _p = TestRepo.insert!(%Post{title: "3"}) + u1 = TestRepo.insert!(%User{name: "john"}) + u2 = TestRepo.insert!(%User{name: "mary"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: u1.id], + [post_id: p1.id, user_id: u2.id], + [post_id: p2.id, user_id: u2.id]] + + query = from(p in Post, join: u in assoc(p, :users), select: {p, u}, order_by: p.id) + [{^p1, ^u1}, {^p1, ^u2}, {^p2, ^u2}] = TestRepo.all(query) + end + + ## Association preload + + test "has_many assoc selector" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + c1 = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + c2 = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + c3 = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + # Without on + query = from(p in Post, join: c in assoc(p, :comments), preload: [comments: c]) + [p1, p2] = TestRepo.all(query) + assert p1.comments == [c1, c2] + assert p2.comments == [c3] + + # With on + query = from(p in Post, left_join: c in assoc(p, :comments), + on: p.title == c.text, preload: [comments: c]) + [p1, p2] = TestRepo.all(query) + assert p1.comments == [c1] + assert p2.comments == [] + end + + test "has_one assoc selector" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id}) + _pl = TestRepo.insert!(%Permalink{url: "2"}) + pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: p2.id}) + + query = from(p in Post, join: pl in assoc(p, :permalink), preload: [permalink: pl]) + assert [post1, post3] = TestRepo.all(query) + + assert post1.permalink == pl1 + assert post3.permalink == pl3 + end + + test "belongs_to assoc selector" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + TestRepo.insert!(%Permalink{url: "1", post_id: p1.id}) + TestRepo.insert!(%Permalink{url: "2"}) + TestRepo.insert!(%Permalink{url: "3", post_id: p2.id}) + + query = from(pl in Permalink, left_join: p in assoc(pl, :post), preload: [post: p], order_by: pl.id) + assert [pl1, pl2, pl3] = TestRepo.all(query) + + assert pl1.post == p1 + refute pl2.post + assert pl3.post == p2 + end + + test "many_to_many assoc selector" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + _p = TestRepo.insert!(%Post{title: "3"}) + u1 = TestRepo.insert!(%User{name: "1"}) + u2 = TestRepo.insert!(%User{name: "2"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: u1.id], + [post_id: p1.id, user_id: u2.id], + [post_id: p2.id, user_id: u2.id]] + + # Without on + query = from(p in Post, left_join: u in assoc(p, :users), preload: [users: u], order_by: p.id) + [p1, p2, p3] = TestRepo.all(query) + assert Enum.sort_by(p1.users, & &1.name) == [u1, u2] + assert p2.users == [u2] + assert p3.users == [] + + # With on + query = from(p in Post, left_join: u in assoc(p, :users), on: p.title == u.name, + preload: [users: u], order_by: p.id) + [p1, p2, p3] = TestRepo.all(query) + assert p1.users == [u1] + assert p2.users == [u2] + assert p3.users == [] + end + + test "has_many through assoc selector" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + u1 = TestRepo.insert!(%User{name: "1"}) + u2 = TestRepo.insert!(%User{name: "2"}) + + TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + TestRepo.insert!(%Comment{post_id: p1.id, author_id: u1.id}) + TestRepo.insert!(%Comment{post_id: p1.id, author_id: u2.id}) + TestRepo.insert!(%Comment{post_id: p2.id, author_id: u2.id}) + + # Without on + query = from(p in Post, left_join: ca in assoc(p, :comments_authors), + preload: [comments_authors: ca]) + [p1, p2] = TestRepo.all(query) + assert Enum.sort_by(p1.comments_authors, & &1.id) == [u1, u2] + assert p2.comments_authors == [u2] + + # With on + query = from(p in Post, left_join: ca in assoc(p, :comments_authors), + on: ca.name == p.title, preload: [comments_authors: ca]) + [p1, p2] = TestRepo.all(query) + assert p1.comments_authors == [u1] + assert p2.comments_authors == [u2] + end + + test "has_many through-through assoc selector" do + %Post{id: pid1} = TestRepo.insert!(%Post{}) + %Post{id: pid2} = TestRepo.insert!(%Post{}) + + %Permalink{} = TestRepo.insert!(%Permalink{post_id: pid1, url: "1"}) + %Permalink{} = TestRepo.insert!(%Permalink{post_id: pid2, url: "2"}) + + %User{id: uid1} = TestRepo.insert!(%User{}) + %User{id: uid2} = TestRepo.insert!(%User{}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2}) + + query = from(p in Permalink, left_join: ca in assoc(p, :post_comments_authors), + preload: [post_comments_authors: ca], order_by: ca.id) + + [l1, l2] = TestRepo.all(query) + [u1, u2] = l1.post_comments_authors + assert u1.id == uid1 + assert u2.id == uid2 + + [u2] = l2.post_comments_authors + assert u2.id == uid2 + + # Insert some intermediary joins to check indexes won't be shuffled + query = from(p in Permalink, + left_join: assoc(p, :post), + left_join: ca in assoc(p, :post_comments_authors), + left_join: assoc(p, :post), + left_join: assoc(p, :post), + preload: [post_comments_authors: ca], order_by: ca.id) + + [l1, l2] = TestRepo.all(query) + [u1, u2] = l1.post_comments_authors + assert u1.id == uid1 + assert u2.id == uid2 + + [u2] = l2.post_comments_authors + assert u2.id == uid2 + end + + ## Nested + + test "nested assoc" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "2"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1, author_id: uid1}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid1, author_id: uid2}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: pid2, author_id: uid2}) + + # use multiple associations to force parallel preloader + query = from p in Post, + left_join: c in assoc(p, :comments), + left_join: u in assoc(c, :author), + order_by: [p.id, c.id, u.id], + preload: [:permalink, comments: {c, author: {u, [:comments, :custom]}}], + select: {0, [p], 1, 2} + + posts = TestRepo.all(query) + assert [p1, p2] = Enum.map(posts, fn {0, [p], 1, 2} -> p end) + assert p1.id == pid1 + assert p2.id == pid2 + + assert [c1, c2] = p1.comments + assert [c3] = p2.comments + assert c1.id == cid1 + assert c2.id == cid2 + assert c3.id == cid3 + + assert c1.author.id == uid1 + assert c2.author.id == uid2 + assert c3.author.id == uid2 + end + + test "nested assoc with missing entries" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + %Post{id: pid3} = TestRepo.insert!(%Post{title: "2"}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "2"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1, author_id: uid1}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid1, author_id: nil}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: pid3, author_id: uid2}) + + query = from p in Post, + left_join: c in assoc(p, :comments), + left_join: u in assoc(c, :author), + order_by: [p.id, c.id, u.id], + preload: [comments: {c, author: u}] + + assert [p1, p2, p3] = TestRepo.all(query) + assert p1.id == pid1 + assert p2.id == pid2 + assert p3.id == pid3 + + assert [c1, c2] = p1.comments + assert [] = p2.comments + assert [c3] = p3.comments + assert c1.id == cid1 + assert c2.id == cid2 + assert c3.id == cid3 + + assert c1.author.id == uid1 + assert c2.author == nil + assert c3.author.id == uid2 + end + + test "nested assoc with child preload" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "2"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1, author_id: uid1}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid1, author_id: uid2}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: pid2, author_id: uid2}) + + query = from p in Post, + left_join: c in assoc(p, :comments), + order_by: [p.id, c.id], + preload: [comments: {c, :author}], + select: p + + assert [p1, p2] = TestRepo.all(query) + assert p1.id == pid1 + assert p2.id == pid2 + + assert [c1, c2] = p1.comments + assert [c3] = p2.comments + assert c1.id == cid1 + assert c2.id == cid2 + assert c3.id == cid3 + + assert c1.author.id == uid1 + assert c2.author.id == uid2 + assert c3.author.id == uid2 + end + + test "nested assoc with sibling preload" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + + %Permalink{id: plid1} = TestRepo.insert!(%Permalink{url: "1", post_id: pid2}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid1}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: pid2}) + %Comment{id: _} = TestRepo.insert!(%Comment{text: "3", post_id: pid2}) + + query = from p in Post, + left_join: c in assoc(p, :comments), + where: c.text in ~w(1 2), + preload: [:permalink, comments: c], + select: {0, [p], 1, 2} + + posts = TestRepo.all(query) + assert [p1, p2] = Enum.map(posts, fn {0, [p], 1, 2} -> p end) + assert p1.id == pid1 + assert p2.id == pid2 + + assert p2.permalink.id == plid1 + + assert [c1] = p1.comments + assert [c2] = p2.comments + assert c1.id == cid1 + assert c2.id == cid2 + end + + test "mixing regular join and assoc selector" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + c1 = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + c2 = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + c3 = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id}) + _pl = TestRepo.insert!(%Permalink{url: "2"}) + pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: p2.id}) + + # Without on + query = from(p in Post, join: pl in assoc(p, :permalink), + join: c in assoc(p, :comments), + preload: [permalink: pl], + select: {p, c}) + [{p1, ^c1}, {p1, ^c2}, {p2, ^c3}] = TestRepo.all(query) + assert p1.permalink == pl1 + assert p2.permalink == pl3 + end + + test "association with composite pk join" do + post = TestRepo.insert!(%Post{title: "1"}) + user = TestRepo.insert!(%User{name: "1"}) + TestRepo.insert!(%PostUserCompositePk{post_id: post.id, user_id: user.id}) + + query = from(p in Post, join: a in assoc(p, :post_user_composite_pk), + preload: [post_user_composite_pk: a], select: p) + assert [post] = TestRepo.all(query) + assert post.post_user_composite_pk + end + + test "joining a through association with a nested preloads" do + post = TestRepo.insert!(%Post{title: "1"}) + user = TestRepo.insert!(%User{name: "1"}) + TestRepo.insert!(%Comment{text: "1", post_id: post.id}) + TestRepo.insert!(%Permalink{post_id: post.id, user_id: user.id}) + + query = + from c in Comment, + join: pp in assoc(c, :post_permalink), + join: u in assoc(pp, :user), + preload: [post_permalink: {pp, [:post, user: u]}] + + [comment] = TestRepo.all(query) + + assert not Ecto.assoc_loaded?(comment.post) + assert %Permalink{user: %User{}, post: %Post{}} = comment.post_permalink + end + + test "joining multiple through associations with a nested preloads" do + post = TestRepo.insert!(%Post{title: "1"}) + user = TestRepo.insert!(%User{name: "1"}) + TestRepo.insert!(%Comment{text: "1", post_id: post.id, author_id: user.id}) + TestRepo.insert!(%Permalink{post_id: post.id, user_id: user.id}) + + query = + from c in Comment, + join: pp in assoc(c, :post_permalink), + join: ap in assoc(c, :author_permalink), + join: u1 in assoc(pp, :user), + join: u2 in assoc(ap, :user), + preload: [post_permalink: {pp, [:post, user: u1]}, author_permalink: {ap, [:post, user: u2]}] + + [comment] = TestRepo.all(query) + + assert not Ecto.assoc_loaded?(comment.post) + assert not Ecto.assoc_loaded?(comment.author) + assert %Permalink{user: %User{}, post: %Post{}} = comment.post_permalink + assert %Permalink{user: %User{}, post: %Post{}} = comment.author_permalink + end + + test "joining nested through associations with a nested preloads" do + user = TestRepo.insert!(%User{name: "1"}) + post = TestRepo.insert!(%Post{title: "1", author_id: user.id}) + TestRepo.insert!(%Comment{text: "1", post_id: post.id}) + TestRepo.insert!(%Permalink{post_id: post.id, user_id: user.id}) + + query = + from c in Comment, + join: pp in assoc(c, :post_permalink), + join: up in assoc(pp, :user_posts), + preload: [post_permalink: {pp, [:post, user_posts: {up, :comments}]}] + + [comment] = TestRepo.all(query) + + assert not Ecto.assoc_loaded?(comment.post) + assert %Permalink{post: %Post{}, user_posts: [%Post{}]} = comment.post_permalink + assert not Ecto.assoc_loaded?(comment.post_permalink.user) + end + + test "joining and preloading through a subquery" do + %{id: p_id} = TestRepo.insert!(%Post{}) + %{id: c1_id} = TestRepo.insert!(%Comment{post_id: p_id}) + %{id: c2_id} = TestRepo.insert!(%Comment{post_id: p_id}) + + q = + from p1 in Post, + left_join: u in User, + on: p1.author_id == u.id, + inner_join: c in subquery(from c in Comment), + on: p1.id == c.post_id, + join: p2 in Post, + on: c.post_id == p2.id, + preload: [author: u, force_comments: {c, post: p2}] + + assert [%Post{id: ^p_id, force_comments: comments}] = TestRepo.all(q) + [comment1, comment2] = Enum.sort_by(comments, & &1.id) + assert %Comment{id: ^c1_id, post: %Post{id: ^p_id}} = comment1 + assert %Comment{id: ^c2_id, post: %Post{id: ^p_id}} = comment2 + end +end diff --git a/deps/ecto/integration_test/cases/preload.exs b/deps/ecto/integration_test/cases/preload.exs new file mode 100644 index 0000000000000000000000000000000000000000..c849a88227fd4b4aab0ed19334bcd9ed2f4309a9 --- /dev/null +++ b/deps/ecto/integration_test/cases/preload.exs @@ -0,0 +1,821 @@ +defmodule Ecto.Integration.PreloadTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.TestRepo + import Ecto.Query + + alias Ecto.Integration.Post + alias Ecto.Integration.Comment + alias Ecto.Integration.Item + alias Ecto.Integration.Permalink + alias Ecto.Integration.User + alias Ecto.Integration.Custom + alias Ecto.Integration.Order + + test "preload with parameter from select_merge" do + p1 = TestRepo.insert!(%Post{title: "p1"}) + TestRepo.insert!(%Comment{text: "c1", post: p1}) + + comments = + from(c in Comment, select: struct(c, [:text])) + |> select_merge([c], %{post_id: c.post_id}) + |> preload(:post) + |> TestRepo.all() + + assert [%{text: "c1", post: %{title: "p1"}}] = comments + end + + test "preload has_many" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + # We use the same text to expose bugs in preload sorting + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + assert %Ecto.Association.NotLoaded{} = p1.comments + + [p3, p1, p2] = TestRepo.preload([p3, p1, p2], :comments) + assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id() + assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id() + assert [] = p3.comments + end + + test "preload has_many multiple times" do + p1 = TestRepo.insert!(%Post{title: "1"}) + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + + [p1, p1] = TestRepo.preload([p1, p1], :comments) + assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id() + + [p1, p1] = TestRepo.preload([p1, p1], :comments) + assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id() + end + + test "preload has_one" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + %Permalink{id: pid1} = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id}) + %Permalink{} = TestRepo.insert!(%Permalink{url: "2", post_id: nil}) + %Permalink{id: pid3} = TestRepo.insert!(%Permalink{url: "3", post_id: p3.id}) + + assert %Ecto.Association.NotLoaded{} = p1.permalink + assert %Ecto.Association.NotLoaded{} = p2.permalink + + [p3, p1, p2] = TestRepo.preload([p3, p1, p2], :permalink) + assert %Permalink{id: ^pid1} = p1.permalink + refute p2.permalink + assert %Permalink{id: ^pid3} = p3.permalink + end + + test "preload belongs_to" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + TestRepo.insert!(%Post{title: "2"}) + %Post{id: pid3} = TestRepo.insert!(%Post{title: "3"}) + + pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: pid1}) + pl2 = TestRepo.insert!(%Permalink{url: "2", post_id: nil}) + pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: pid3}) + assert %Ecto.Association.NotLoaded{} = pl1.post + + [pl3, pl1, pl2] = TestRepo.preload([pl3, pl1, pl2], :post) + assert %Post{id: ^pid1} = pl1.post + refute pl2.post + assert %Post{id: ^pid3} = pl3.post + end + + test "preload multiple belongs_to" do + %User{id: uid} = TestRepo.insert!(%User{name: "foo"}) + %Post{id: pid} = TestRepo.insert!(%Post{title: "1"}) + %Comment{id: cid} = TestRepo.insert!(%Comment{post_id: pid, author_id: uid}) + + comment = TestRepo.get!(Comment, cid) + comment = TestRepo.preload(comment, [:author, :post]) + assert comment.author.id == uid + assert comment.post.id == pid + end + + test "preload belongs_to with shared parent" do + %Post{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %Post{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + + c1 = TestRepo.insert!(%Comment{text: "1", post_id: pid1}) + c2 = TestRepo.insert!(%Comment{text: "2", post_id: pid1}) + c3 = TestRepo.insert!(%Comment{text: "3", post_id: pid2}) + + [c3, c1, c2] = TestRepo.preload([c3, c1, c2], :post) + assert %Post{id: ^pid1} = c1.post + assert %Post{id: ^pid1} = c2.post + assert %Post{id: ^pid2} = c3.post + end + + test "preload many_to_many" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + # We use the same name to expose bugs in preload sorting + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + %User{id: uid3} = TestRepo.insert!(%User{name: "2"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "2"}) + %User{id: uid4} = TestRepo.insert!(%User{name: "3"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1], + [post_id: p1.id, user_id: uid2], + [post_id: p2.id, user_id: uid3], + [post_id: p2.id, user_id: uid4], + [post_id: p3.id, user_id: uid1], + [post_id: p3.id, user_id: uid4]] + + assert %Ecto.Association.NotLoaded{} = p1.users + + [p1, p2, p3] = TestRepo.preload([p1, p2, p3], :users) + assert [%User{id: ^uid1}, %User{id: ^uid2}] = p1.users |> sort_by_id + assert [%User{id: ^uid3}, %User{id: ^uid4}] = p2.users |> sort_by_id + assert [%User{id: ^uid1}, %User{id: ^uid4}] = p3.users |> sort_by_id + end + + test "preload has_many through" do + %Post{id: pid1} = p1 = TestRepo.insert!(%Post{}) + %Post{id: pid2} = p2 = TestRepo.insert!(%Post{}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "foo"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "bar"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2}) + + [p1, p2] = TestRepo.preload([p1, p2], :comments_authors) + + # Through was preloaded + [u1, u2] = p1.comments_authors |> sort_by_id + assert u1.id == uid1 + assert u2.id == uid2 + + [u2] = p2.comments_authors + assert u2.id == uid2 + + # But we also preloaded everything along the way + assert [c1, c2, c3] = p1.comments |> sort_by_id + assert c1.author.id == uid1 + assert c2.author.id == uid1 + assert c3.author.id == uid2 + + assert [c4] = p2.comments + assert c4.author.id == uid2 + end + + test "preload has_one through" do + %Post{id: pid1} = TestRepo.insert!(%Post{}) + %Post{id: pid2} = TestRepo.insert!(%Post{}) + + %Permalink{id: lid1} = TestRepo.insert!(%Permalink{post_id: pid1, url: "1"}) + %Permalink{id: lid2} = TestRepo.insert!(%Permalink{post_id: pid2, url: "2"}) + + %Comment{} = c1 = TestRepo.insert!(%Comment{post_id: pid1}) + %Comment{} = c2 = TestRepo.insert!(%Comment{post_id: pid1}) + %Comment{} = c3 = TestRepo.insert!(%Comment{post_id: pid2}) + + [c1, c2, c3] = TestRepo.preload([c1, c2, c3], :post_permalink) + + # Through was preloaded + assert c1.post.id == pid1 + assert c1.post.permalink.id == lid1 + assert c1.post_permalink.id == lid1 + + assert c2.post.id == pid1 + assert c2.post.permalink.id == lid1 + assert c2.post_permalink.id == lid1 + + assert c3.post.id == pid2 + assert c3.post.permalink.id == lid2 + assert c3.post_permalink.id == lid2 + end + + test "preload through with nil association" do + %Comment{} = c = TestRepo.insert!(%Comment{post_id: nil}) + + c = TestRepo.preload(c, [:post, :post_permalink]) + assert c.post == nil + assert c.post_permalink == nil + + c = TestRepo.preload(c, [:post, :post_permalink]) + assert c.post == nil + assert c.post_permalink == nil + end + + test "preload through with nil struct" do + %Comment{} = c = TestRepo.insert!(%Comment{}) + [%Comment{}, nil] = TestRepo.preload([c, nil], [:post, :post_permalink]) + end + + test "preload has_many through-through" do + %Post{id: pid1} = TestRepo.insert!(%Post{}) + %Post{id: pid2} = TestRepo.insert!(%Post{}) + + %Permalink{} = l1 = TestRepo.insert!(%Permalink{post_id: pid1, url: "1"}) + %Permalink{} = l2 = TestRepo.insert!(%Permalink{post_id: pid2, url: "2"}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "foo"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "bar"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2}) + + # With assoc query + [l1, l2] = TestRepo.preload([l1, l2], :post_comments_authors) + + # Through was preloaded + [u1, u2] = l1.post_comments_authors |> sort_by_id + assert u1.id == uid1 + assert u2.id == uid2 + + [u2] = l2.post_comments_authors + assert u2.id == uid2 + + # But we also preloaded everything along the way + assert l1.post.id == pid1 + assert l1.post.comments != [] + + assert l2.post.id == pid2 + assert l2.post.comments != [] + end + + test "preload has_many through many_to_many" do + %Post{} = p1 = TestRepo.insert!(%Post{}) + %Post{} = p2 = TestRepo.insert!(%Post{}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "foo"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "bar"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1], + [post_id: p1.id, user_id: uid2], + [post_id: p2.id, user_id: uid2]] + + %Comment{id: cid1} = TestRepo.insert!(%Comment{author_id: uid1}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{author_id: uid1}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{author_id: uid2}) + %Comment{id: cid4} = TestRepo.insert!(%Comment{author_id: uid2}) + + [p1, p2] = TestRepo.preload([p1, p2], :users_comments) + + # Through was preloaded + [c1, c2, c3, c4] = p1.users_comments |> sort_by_id + assert c1.id == cid1 + assert c2.id == cid2 + assert c3.id == cid3 + assert c4.id == cid4 + + [c3, c4] = p2.users_comments |> sort_by_id + assert c3.id == cid3 + assert c4.id == cid4 + + # But we also preloaded everything along the way + assert [u1, u2] = p1.users |> sort_by_id + assert u1.id == uid1 + assert u2.id == uid2 + + assert [u2] = p2.users + assert u2.id == uid2 + end + + ## Empties + + test "preload empty" do + assert TestRepo.preload([], :anything_goes) == [] + end + + test "preload has_many with no associated entries" do + p = TestRepo.insert!(%Post{title: "1"}) + p = TestRepo.preload(p, :comments) + + assert p.title == "1" + assert p.comments == [] + end + + test "preload has_one with no associated entries" do + p = TestRepo.insert!(%Post{title: "1"}) + p = TestRepo.preload(p, :permalink) + + assert p.title == "1" + assert p.permalink == nil + end + + test "preload belongs_to with no associated entry" do + c = TestRepo.insert!(%Comment{text: "1"}) + c = TestRepo.preload(c, :post) + + assert c.text == "1" + assert c.post == nil + end + + test "preload many_to_many with no associated entries" do + p = TestRepo.insert!(%Post{title: "1"}) + p = TestRepo.preload(p, :users) + + assert p.title == "1" + assert p.users == [] + end + + ## With queries + + test "preload with 1-arity function" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + # We use the same text to expose bugs in preload sorting + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2], + comments: fn _ -> TestRepo.all(Comment) end) + assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = pe1.comments + assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = pe2.comments + assert [] = pe3.comments + end + + test "preload with 2-arity function" do + p = TestRepo.insert!(%Post{title: "1"}) + c1 = TestRepo.insert!(%Comment{post_id: p.id}) + c2 = TestRepo.insert!(%Comment{post_id: p.id}) + + # making a simple preloader so that it works across all adapters + preloader = fn parent_ids, assoc -> + %{related_key: related_key, queryable: queryable} = assoc + + from(q in queryable, where: field(q, ^related_key) in ^parent_ids, order_by: q.id) + |> TestRepo.all() + end + + assert p = TestRepo.preload(p, comments: preloader) + assert [^c1, ^c2] = p.comments + end + + test "preload many_to_many with function" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + # We use the same name to expose bugs in preload sorting + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + %User{id: uid3} = TestRepo.insert!(%User{name: "2"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "2"}) + %User{id: uid4} = TestRepo.insert!(%User{name: "3"}) + + TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1], + [post_id: p1.id, user_id: uid2], + [post_id: p2.id, user_id: uid3], + [post_id: p2.id, user_id: uid4], + [post_id: p3.id, user_id: uid1], + [post_id: p3.id, user_id: uid4]] + + wrong_preloader = fn post_ids -> + TestRepo.all( + from u in User, + join: pu in "posts_users", + on: true, + where: pu.post_id in ^post_ids and pu.user_id == u.id, + order_by: u.id, + select: map(u, [:id]) + ) + end + + assert_raise RuntimeError, ~r/invalid custom preload for `users` on `Ecto.Integration.Post`/, fn -> + TestRepo.preload([p1, p2, p3], users: wrong_preloader) + end + + right_preloader = fn post_ids -> + TestRepo.all( + from u in User, + join: pu in "posts_users", + on: true, + where: pu.post_id in ^post_ids and pu.user_id == u.id, + order_by: u.id, + select: {pu.post_id, map(u, [:id])} + ) + end + + [p1, p2, p3] = TestRepo.preload([p1, p2, p3], users: right_preloader) + assert p1.users == [%{id: uid1}, %{id: uid2}] + assert p2.users == [%{id: uid3}, %{id: uid4}] + assert p3.users == [%{id: uid1}, %{id: uid4}] + end + + test "preload with query" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + p3 = TestRepo.insert!(%Post{title: "3"}) + + # We use the same text to expose bugs in preload sorting + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + assert %Ecto.Association.NotLoaded{} = p1.comments + + # With empty query + assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2], + comments: from(c in Comment, where: false)) + assert [] = pe1.comments + assert [] = pe2.comments + assert [] = pe3.comments + + # With custom select + assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2], + comments: from(c in Comment, select: c.id, order_by: c.id)) + assert [^cid1, ^cid2] = pe1.comments + assert [^cid3, ^cid4] = pe2.comments + assert [] = pe3.comments + + # With custom ordered query + assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2], + comments: from(c in Comment, order_by: [desc: c.text])) + assert [%Comment{id: ^cid2}, %Comment{id: ^cid1}] = pe1.comments + assert [%Comment{id: ^cid4}, %Comment{id: ^cid3}] = pe2.comments + assert [] = pe3.comments + + # With custom ordered query with preload + assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2], + comments: {from(c in Comment, order_by: [desc: c.text]), :post}) + assert [%Comment{id: ^cid2} = c2, %Comment{id: ^cid1} = c1] = pe1.comments + assert [%Comment{id: ^cid4} = c4, %Comment{id: ^cid3} = c3] = pe2.comments + assert [] = pe3.comments + + assert c1.post.title == "1" + assert c2.post.title == "1" + assert c3.post.title == "2" + assert c4.post.title == "2" + end + + test "preload through with query" do + %Post{id: pid1} = p1 = TestRepo.insert!(%Post{}) + + u1 = TestRepo.insert!(%User{name: "foo"}) + u2 = TestRepo.insert!(%User{name: "bar"}) + u3 = TestRepo.insert!(%User{name: "baz"}) + u4 = TestRepo.insert!(%User{name: "norf"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u1.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u2.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u3.id}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u4.id}) + + np1 = TestRepo.preload(p1, comments_authors: from(u in User, where: u.name == "foo")) + assert np1.comments_authors == [u1] + + assert_raise ArgumentError, ~r/Ecto expected a map\/struct with the key `id` but got: \d+/, fn -> + TestRepo.preload(p1, comments_authors: from(u in User, order_by: u.name, select: u.id)) + end + + # The subpreload order does not matter because the result is dictated by comments + np1 = TestRepo.preload(p1, comments_authors: from(u in User, order_by: u.name, select: %{id: u.id})) + assert np1.comments_authors == + [%{id: u1.id}, %{id: u2.id}, %{id: u3.id}, %{id: u4.id}] + end + + test "preload into a subquery source" do + %{id: p_id} = TestRepo.insert!(%Post{}) + %{id: c_id} = TestRepo.insert!(%Comment{post_id: p_id}) + + q = + from c in subquery(from c in Comment), + join: p in Post, + on: c.post_id == p.id, + preload: [post: p] + + assert [%Comment{id: ^c_id, post: %Post{id: ^p_id}}] = TestRepo.all(q) + end + + ## With take + + test "preload with take" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + _p = TestRepo.insert!(%Post{title: "3"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + + assert %Ecto.Association.NotLoaded{} = p1.comments + + posts = TestRepo.all(from Post, preload: [:comments], select: [:id, comments: [:id, :post_id]]) + [p1, p2, p3] = sort_by_id(posts) + assert p1.title == nil + assert p2.title == nil + assert p3.title == nil + + assert [%{id: ^cid1, text: nil}, %{id: ^cid2, text: nil}] = sort_by_id(p1.comments) + assert [%{id: ^cid3, text: nil}, %{id: ^cid4, text: nil}] = sort_by_id(p2.comments) + assert [] = sort_by_id(p3.comments) + end + + test "preload through with take" do + %Post{id: pid1} = TestRepo.insert!(%Post{}) + + %User{id: uid1} = TestRepo.insert!(%User{name: "foo"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "bar"}) + + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1}) + %Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2}) + + [p1] = TestRepo.all from Post, preload: [:comments_authors], select: [:id, comments_authors: :id] + [%{id: ^uid1, name: nil}, %{id: ^uid2, name: nil}] = p1.comments_authors |> sort_by_id + end + + ## Nested + + test "preload many assocs" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + assert [p2, p1] = TestRepo.preload([p2, p1], [:comments, :users]) + assert p1.comments == [] + assert p2.comments == [] + assert p1.users == [] + assert p2.users == [] + end + + test "preload nested" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + TestRepo.insert!(%Comment{text: "4", post_id: p2.id}) + + assert [p2, p1] = TestRepo.preload([p2, p1], [comments: :post]) + assert [c1, c2] = p1.comments + assert [c3, c4] = p2.comments + assert p1.id == c1.post.id + assert p1.id == c2.post.id + assert p2.id == c3.post.id + assert p2.id == c4.post.id + end + + test "preload nested via custom query" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + TestRepo.insert!(%Comment{text: "4", post_id: p2.id}) + + query = from(c in Comment, preload: :post, order_by: [desc: c.text]) + assert [p2, p1] = TestRepo.preload([p2, p1], comments: query) + assert [c2, c1] = p1.comments + assert [c4, c3] = p2.comments + assert p1.id == c1.post.id + assert p1.id == c2.post.id + assert p2.id == c3.post.id + assert p2.id == c4.post.id + end + + test "custom preload_order" do + post = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"}) + + TestRepo.insert!(%Comment{text: "2", post_id: post.id}) + TestRepo.insert!(%Comment{text: "1", post_id: post.id}) + + post = TestRepo.preload(post, [:ordered_comments, :ordered_users]) + + # asc + assert [%{text: "1"}, %{text: "2"}] = post.ordered_comments + + # desc + assert [%{name: "foo"}, %{name: "bar"}] = post.ordered_users + end + + test "custom preload_order with mfa" do + post1 = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"}) + post2 = TestRepo.insert!(%Post{users: [%User{name: "baz"}, %User{name: "foz"}], title: "2"}) + + [post1, post2] = TestRepo.preload([post1, post2], [:ordered_users_by_join_table], log: :error) + + assert [%{name: "foo"}, %{name: "bar"}] = post1.ordered_users_by_join_table + assert [%{name: "foz"}, %{name: "baz"}] = post2.ordered_users_by_join_table + end + + ## Others + + @tag :invalid_prefix + test "preload custom prefix from schema" do + p = TestRepo.insert!(%Post{title: "1"}) + p = Ecto.put_meta(p, prefix: "this_surely_does_not_exist") + # This preload should fail because it points to a prefix that does not exist + assert catch_error(TestRepo.preload(p, [:comments])) + end + + @tag :invalid_prefix + test "preload custom prefix from options" do + p = TestRepo.insert!(%Post{title: "1"}) + # This preload should fail because it points to a prefix that does not exist + assert catch_error(TestRepo.preload(p, [:comments], prefix: "this_surely_does_not_exist")) + end + + test "preload with binary_id" do + c = TestRepo.insert!(%Custom{}) + u = TestRepo.insert!(%User{custom_id: c.bid}) + + u = TestRepo.preload(u, :custom) + assert u.custom.bid == c.bid + end + + test "preload raises with association set but without id" do + c1 = TestRepo.insert!(%Comment{text: "1"}) + u1 = TestRepo.insert!(%User{name: "name"}) + updated = %{c1 | author: u1, author_id: nil} + + assert ExUnit.CaptureLog.capture_log(fn -> + assert TestRepo.preload(updated, [:author]).author == u1 + end) =~ ~r/its association key `author_id` is nil/ + + assert TestRepo.preload(updated, [:author], force: true).author == nil + end + + test "preload skips already loaded for cardinality one" do + %Post{id: pid} = TestRepo.insert!(%Post{title: "1"}) + + c1 = %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid}) + c2 = %Comment{id: _cid} = TestRepo.insert!(%Comment{text: "2", post_id: nil}) + + [c1, c2] = TestRepo.preload([c1, c2], :post) + assert %Post{id: ^pid} = c1.post + assert c2.post == nil + + [c1, c2] = TestRepo.preload([c1, c2], post: :comments) + assert [%Comment{id: ^cid1}] = c1.post.comments + + TestRepo.update_all Post, set: [title: "0"] + TestRepo.update_all Comment, set: [post_id: pid] + + # Preloading once again shouldn't change the result + [c1, c2] = TestRepo.preload([c1, c2], :post) + assert %Post{id: ^pid, title: "1", comments: [_|_]} = c1.post + assert c2.post == nil + + [c1, c2] = TestRepo.preload([c1, %{c2 | post_id: pid}], :post, force: true) + assert %Post{id: ^pid, title: "0", comments: %Ecto.Association.NotLoaded{}} = c1.post + assert %Post{id: ^pid, title: "0", comments: %Ecto.Association.NotLoaded{}} = c2.post + end + + test "preload skips already loaded for cardinality many" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id}) + + [p1, p2] = TestRepo.preload([p1, p2], :comments) + assert [%Comment{id: ^cid1}] = p1.comments + assert [%Comment{id: ^cid2}] = p2.comments + + [p1, p2] = TestRepo.preload([p1, p2], comments: :post) + assert hd(p1.comments).post.id == p1.id + assert hd(p2.comments).post.id == p2.id + + TestRepo.update_all Comment, set: [text: "0"] + + # Preloading once again shouldn't change the result + [p1, p2] = TestRepo.preload([p1, p2], :comments) + assert [%Comment{id: ^cid1, text: "1", post: %Post{}}] = p1.comments + assert [%Comment{id: ^cid2, text: "2", post: %Post{}}] = p2.comments + + [p1, p2] = TestRepo.preload([p1, p2], :comments, force: true) + assert [%Comment{id: ^cid1, text: "0", post: %Ecto.Association.NotLoaded{}}] = p1.comments + assert [%Comment{id: ^cid2, text: "0", post: %Ecto.Association.NotLoaded{}}] = p2.comments + end + + test "preload keyword query" do + p1 = TestRepo.insert!(%Post{title: "1"}) + p2 = TestRepo.insert!(%Post{title: "2"}) + TestRepo.insert!(%Post{title: "3"}) + + %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id}) + %Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id}) + %Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id}) + %Comment{id: cid4} = TestRepo.insert!(%Comment{text: "4", post_id: p2.id}) + + # Regular query + query = from(p in Post, preload: [:comments], select: p) + + assert [p1, p2, p3] = TestRepo.all(query) |> sort_by_id + assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id + assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id + assert [] = p3.comments + + # Query with interpolated preload query + query = from(p in Post, preload: [comments: ^from(c in Comment, where: false)], select: p) + + assert [p1, p2, p3] = TestRepo.all(query) + assert [] = p1.comments + assert [] = p2.comments + assert [] = p3.comments + + # Now let's use an interpolated preload too + comments = [:comments] + query = from(p in Post, preload: ^comments, select: {0, [p], 1, 2}) + + posts = TestRepo.all(query) + [p1, p2, p3] = Enum.map(posts, fn {0, [p], 1, 2} -> p end) |> sort_by_id + + assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id + assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id + assert [] = p3.comments + end + + + test "preload belongs_to in embedded_schema" do + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + item = %Item{user_id: uid1} + + # Starts as not loaded + assert %Ecto.Association.NotLoaded{} = item.user + + # Now we preload it + item = TestRepo.preload(item, :user) + assert %User{id: ^uid1} = item.user + end + + describe "preload associations from nested embeds" do + setup do + %User{id: uid1} = TestRepo.insert!(%User{name: "1"}) + %User{id: uid2} = TestRepo.insert!(%User{name: "2"}) + %User{id: uid3} = TestRepo.insert!(%User{name: "3"}) + item1 = %Item{id: 1, user_id: uid1} + item2 = %Item{id: 2, user_id: uid2} + item3 = %Item{id: 3, user_id: uid3} + order1 = %Order{items: [item1, item3, item2], item: item1} + order2 = %Order{items: [], item: nil} + order3 = %Order{items: nil, item: nil} + order4 = %Order{items: [item1, item2], item: item2} + + [orders: [order1, order2, order3, order4]] + end + + test "cannot preload embed without its associations", context do + assert_raise ArgumentError, ~r/cannot preload embedded field/, fn -> + TestRepo.preload(context.orders, :item) + end + end + + test "embeds_one", context do + [nil | preloaded_orders] = [nil | context.orders] |> TestRepo.preload(item: :user) + + expected_item_user = + Enum.map(context.orders, fn + %{item: nil} -> {nil, nil} + %{item: item} -> {item.id, item.user_id} + end) + + actual_item_user = + Enum.map(preloaded_orders, fn + %{item: nil} -> {nil, nil} + %{item: item} -> {item.id, item.user.id} + end) + + assert expected_item_user == actual_item_user + end + + test "embeds_many", context do + [nil | preloaded_orders] = [nil | context.orders] |> TestRepo.preload(items: :user) + + expected_items_user = + Enum.map(context.orders, fn + %{items: nil} -> {nil, nil} + %{items: items} -> Enum.map(items, & {&1.id, &1.user_id}) + end) + + actual_items_user = + Enum.map(preloaded_orders, fn + %{items: nil} -> {nil, nil} + %{items: items} -> Enum.map(items, & {&1.id, &1.user.id}) + end) + + assert expected_items_user == actual_items_user + end + end + + defp sort_by_id(values) do + Enum.sort_by(values, &(&1.id)) + end +end diff --git a/deps/ecto/integration_test/cases/repo.exs b/deps/ecto/integration_test/cases/repo.exs new file mode 100644 index 0000000000000000000000000000000000000000..667db70a77c22d1156a0dcdf54abcec6cfe7ecfc --- /dev/null +++ b/deps/ecto/integration_test/cases/repo.exs @@ -0,0 +1,2267 @@ +defmodule Ecto.Integration.RepoTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.TestRepo + import Ecto.Query + + alias Ecto.Integration.Post + alias Ecto.Integration.Order + alias Ecto.Integration.User + alias Ecto.Integration.Comment + alias Ecto.Integration.Permalink + alias Ecto.Integration.Custom + alias Ecto.Integration.Barebone + alias Ecto.Integration.CompositePk + alias Ecto.Integration.PostUserCompositePk + + test "returns already started for started repos" do + assert {:error, {:already_started, _}} = TestRepo.start_link() + end + + test "supports unnamed repos" do + assert {:ok, pid} = TestRepo.start_link(name: nil) + assert Ecto.Repo.Queryable.all(pid, Post, Ecto.Repo.Supervisor.tuplet(pid, [])) == [] + end + + test "all empty" do + assert TestRepo.all(Post) == [] + assert TestRepo.all(from p in Post) == [] + end + + test "all with in" do + TestRepo.insert!(%Post{title: "hello"}) + + # Works without the query cache. + assert_raise Ecto.Query.CastError, fn -> + TestRepo.all(from p in Post, where: p.title in ^nil) + end + + assert [] = TestRepo.all from p in Post, where: p.title in [] + assert [] = TestRepo.all from p in Post, where: p.title in ["1", "2", "3"] + assert [] = TestRepo.all from p in Post, where: p.title in ^[] + + assert [_] = TestRepo.all from p in Post, where: p.title not in [] + assert [_] = TestRepo.all from p in Post, where: p.title in ["1", "hello", "3"] + assert [_] = TestRepo.all from p in Post, where: p.title in ["1", ^"hello", "3"] + assert [_] = TestRepo.all from p in Post, where: p.title in ^["1", "hello", "3"] + + # Still doesn't work after the query cache. + assert_raise Ecto.Query.CastError, fn -> + TestRepo.all(from p in Post, where: p.title in ^nil) + end + end + + test "all using named from" do + TestRepo.insert!(%Post{title: "hello"}) + + query = + from(p in Post, as: :post) + |> where([post: p], p.title == "hello") + + assert [_] = TestRepo.all query + end + + test "all without schema" do + %Post{} = TestRepo.insert!(%Post{title: "title1"}) + %Post{} = TestRepo.insert!(%Post{title: "title2"}) + + assert ["title1", "title2"] = + TestRepo.all(from(p in "posts", order_by: p.title, select: p.title)) + + assert [_] = + TestRepo.all(from(p in "posts", where: p.title == "title1", select: p.id)) + end + + test "all shares metadata" do + TestRepo.insert!(%Post{title: "title1"}) + TestRepo.insert!(%Post{title: "title2"}) + + [post1, post2] = TestRepo.all(Post) + assert :erts_debug.same(post1.__meta__, post2.__meta__) + + [new_post1, new_post2] = TestRepo.all(Post) + assert :erts_debug.same(post1.__meta__, new_post1.__meta__) + assert :erts_debug.same(post2.__meta__, new_post2.__meta__) + end + + @tag :invalid_prefix + test "all with invalid prefix" do + assert catch_error(TestRepo.all("posts", prefix: "oops")) + end + + test "insert, update and delete" do + post = %Post{title: "insert, update, delete", visits: 1} + meta = post.__meta__ + + assert %Post{} = inserted = TestRepo.insert!(post) + assert %Post{} = updated = TestRepo.update!(Ecto.Changeset.change(inserted, visits: 2)) + + deleted_meta = put_in meta.state, :deleted + assert %Post{__meta__: ^deleted_meta} = TestRepo.delete!(updated) + + loaded_meta = put_in meta.state, :loaded + assert %Post{__meta__: ^loaded_meta} = TestRepo.insert!(post) + + post = TestRepo.one(Post) + assert post.__meta__.state == :loaded + assert post.inserted_at + end + + test "insert, update and delete with field source" do + permalink = %Permalink{url: "url"} + assert %Permalink{url: "url"} = inserted = + TestRepo.insert!(permalink) + assert %Permalink{url: "new"} = updated = + TestRepo.update!(Ecto.Changeset.change(inserted, url: "new")) + assert %Permalink{url: "new"} = + TestRepo.delete!(updated) + end + + @tag :composite_pk + test "insert, update and delete with composite pk" do + c1 = TestRepo.insert!(%CompositePk{a: 1, b: 2, name: "first"}) + c2 = TestRepo.insert!(%CompositePk{a: 1, b: 3, name: "second"}) + + assert CompositePk |> first |> TestRepo.one == c1 + assert CompositePk |> last |> TestRepo.one == c2 + + changeset = Ecto.Changeset.cast(c1, %{name: "first change"}, ~w(name)a) + c1 = TestRepo.update!(changeset) + assert TestRepo.get_by!(CompositePk, %{a: 1, b: 2}) == c1 + + TestRepo.delete!(c2) + assert TestRepo.all(CompositePk) == [c1] + + assert_raise ArgumentError, ~r"to have exactly one primary key", fn -> + TestRepo.get(CompositePk, []) + end + + assert_raise ArgumentError, ~r"to have exactly one primary key", fn -> + TestRepo.get!(CompositePk, [1, 2]) + end + end + + @tag :composite_pk + test "insert, update and delete with associated composite pk" do + user = TestRepo.insert!(%User{}) + post = TestRepo.insert!(%Post{title: "post title"}) + + user_post = TestRepo.insert!(%PostUserCompositePk{user_id: user.id, post_id: post.id}) + assert TestRepo.get_by!(PostUserCompositePk, [user_id: user.id, post_id: post.id]) == user_post + TestRepo.delete!(user_post) + assert TestRepo.all(PostUserCompositePk) == [] + end + + @tag :invalid_prefix + test "insert, update and delete with invalid prefix" do + post = TestRepo.insert!(%Post{}) + changeset = Ecto.Changeset.change(post, title: "foo") + assert catch_error(TestRepo.insert(%Post{}, prefix: "oops")) + assert catch_error(TestRepo.update(changeset, prefix: "oops")) + assert catch_error(TestRepo.delete(changeset, prefix: "oops")) + + # Check we can still insert the post after the invalid prefix attempt + assert %Post{id: _} = TestRepo.insert!(%Post{}) + end + + test "insert and update with changeset" do + # On insert we merge the fields and changes + changeset = Ecto.Changeset.cast(%Post{visits: 13, title: "wrong"}, + %{"title" => "hello", "temp" => "unknown"}, ~w(title temp)a) + + post = TestRepo.insert!(changeset) + assert %Post{visits: 13, title: "hello", temp: "unknown"} = post + assert %Post{visits: 13, title: "hello", temp: "temp"} = TestRepo.get!(Post, post.id) + + # On update we merge only fields, direct schema changes are discarded + changeset = Ecto.Changeset.cast(%{post | visits: 17}, + %{"title" => "world", "temp" => "unknown"}, ~w(title temp)a) + + assert %Post{visits: 17, title: "world", temp: "unknown"} = TestRepo.update!(changeset) + assert %Post{visits: 13, title: "world", temp: "temp"} = TestRepo.get!(Post, post.id) + end + + test "insert and update with empty changeset" do + # On insert we merge the fields and changes + changeset = Ecto.Changeset.cast(%Permalink{}, %{}, ~w()) + assert %Permalink{} = permalink = TestRepo.insert!(changeset) + + # Assert we can update the same value twice, + # without changes, without triggering stale errors. + changeset = Ecto.Changeset.cast(permalink, %{}, ~w()) + assert TestRepo.update!(changeset) == permalink + assert TestRepo.update!(changeset) == permalink + end + + @tag :no_primary_key + test "insert with no primary key" do + assert %Barebone{num: nil} = TestRepo.insert!(%Barebone{}) + assert %Barebone{num: 13} = TestRepo.insert!(%Barebone{num: 13}) + end + + @tag :read_after_writes + test "insert and update with changeset read after writes" do + defmodule RAW do + use Ecto.Schema + + schema "comments" do + field :text, :string + field :lock_version, :integer, read_after_writes: true + end + end + + changeset = Ecto.Changeset.cast(struct(RAW, %{}), %{}, ~w()) + + # If the field is nil, we will not send it + # and read the value back from the database. + assert %{id: cid, lock_version: 1} = raw = TestRepo.insert!(changeset) + + # Set the counter to 11, so we can read it soon + TestRepo.update_all from(u in RAW, where: u.id == ^cid), set: [lock_version: 11] + + # We will read back on update too + changeset = Ecto.Changeset.cast(raw, %{"text" => "0"}, ~w(text)a) + assert %{id: ^cid, lock_version: 11, text: "0"} = TestRepo.update!(changeset) + end + + test "insert autogenerates for custom type" do + post = TestRepo.insert!(%Post{uuid: nil}) + assert byte_size(post.uuid) == 36 + assert TestRepo.get_by(Post, uuid: post.uuid) == post + end + + @tag :id_type + test "insert autogenerates for custom id type" do + defmodule ID do + use Ecto.Schema + + @primary_key {:id, CustomPermalink, autogenerate: true} + schema "posts" do + end + end + + id = TestRepo.insert!(struct(ID, id: nil)) + assert id.id + assert TestRepo.get_by(ID, id: "#{id.id}-hello") == id + end + + @tag :id_type + @tag :assigns_id_type + test "insert with user-assigned primary key" do + assert %Post{id: 1} = TestRepo.insert!(%Post{id: 1}) + end + + @tag :id_type + @tag :assigns_id_type + test "insert and update with user-assigned primary key in changeset" do + changeset = Ecto.Changeset.cast(%Post{id: 11}, %{"id" => "13"}, ~w(id)a) + assert %Post{id: 13} = post = TestRepo.insert!(changeset) + + changeset = Ecto.Changeset.cast(post, %{"id" => "15"}, ~w(id)a) + assert %Post{id: 15} = TestRepo.update!(changeset) + end + + test "insert and fetch a schema with utc timestamps" do + datetime = DateTime.from_unix!(System.os_time(:second), :second) + TestRepo.insert!(%User{inserted_at: datetime}) + assert [%{inserted_at: ^datetime}] = TestRepo.all(User) + end + + test "optimistic locking in update/delete operations" do + import Ecto.Changeset, only: [cast: 3, optimistic_lock: 2] + base_comment = TestRepo.insert!(%Comment{}) + + changeset_ok = + base_comment + |> cast(%{"text" => "foo.bar"}, ~w(text)a) + |> optimistic_lock(:lock_version) + TestRepo.update!(changeset_ok) + + changeset_stale = + base_comment + |> cast(%{"text" => "foo.bat"}, ~w(text)a) + |> optimistic_lock(:lock_version) + + assert_raise Ecto.StaleEntryError, fn -> TestRepo.update!(changeset_stale) end + assert_raise Ecto.StaleEntryError, fn -> TestRepo.delete!(changeset_stale) end + end + + test "optimistic locking in update operation with nil field" do + import Ecto.Changeset, only: [cast: 3, optimistic_lock: 3] + + base_comment = + %Comment{} + |> cast(%{lock_version: nil}, [:lock_version]) + |> TestRepo.insert!() + + incrementer = + fn + nil -> 1 + old_value -> old_value + 1 + end + + changeset_ok = + base_comment + |> cast(%{"text" => "foo.bar"}, ~w(text)a) + |> optimistic_lock(:lock_version, incrementer) + + updated = TestRepo.update!(changeset_ok) + assert updated.text == "foo.bar" + assert updated.lock_version == 1 + end + + test "optimistic locking in delete operation with nil field" do + import Ecto.Changeset, only: [cast: 3, optimistic_lock: 3] + + base_comment = + %Comment{} + |> cast(%{lock_version: nil}, [:lock_version]) + |> TestRepo.insert!() + + incrementer = + fn + nil -> 1 + old_value -> old_value + 1 + end + + changeset_ok = optimistic_lock(base_comment, :lock_version, incrementer) + TestRepo.delete!(changeset_ok) + + refute TestRepo.get(Comment, base_comment.id) + end + + @tag :unique_constraint + test "unique constraint" do + changeset = Ecto.Changeset.change(%Post{}, uuid: Ecto.UUID.generate()) + {:ok, _} = TestRepo.insert(changeset) + + exception = + assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn -> + changeset + |> TestRepo.insert() + end + + assert exception.message =~ "\"posts_uuid_index\" (unique_constraint)" + assert exception.message =~ "The changeset has not defined any constraint." + assert exception.message =~ "call `unique_constraint/3`" + + message = ~r/constraint error when attempting to insert struct/ + exception = + assert_raise Ecto.ConstraintError, message, fn -> + changeset + |> Ecto.Changeset.unique_constraint(:uuid, name: :posts_email_changeset) + |> TestRepo.insert() + end + + assert exception.message =~ "\"posts_email_changeset\" (unique_constraint)" + + {:error, changeset} = + changeset + |> Ecto.Changeset.unique_constraint(:uuid) + |> TestRepo.insert() + assert changeset.errors == [uuid: {"has already been taken", [constraint: :unique, constraint_name: "posts_uuid_index"]}] + assert changeset.data.__meta__.state == :built + end + + @tag :unique_constraint + test "unique constraint from association" do + uuid = Ecto.UUID.generate() + post = & %Post{} |> Ecto.Changeset.change(uuid: &1) |> Ecto.Changeset.unique_constraint(:uuid) + + {:error, changeset} = + TestRepo.insert %User{ + comments: [%Comment{}], + permalink: %Permalink{}, + posts: [post.(uuid), post.(uuid), post.(Ecto.UUID.generate())] + } + + [_, p2, _] = changeset.changes.posts + assert p2.errors == [uuid: {"has already been taken", [constraint: :unique, constraint_name: "posts_uuid_index"]}] + end + + @tag :id_type + @tag :unique_constraint + test "unique constraint with binary_id" do + changeset = Ecto.Changeset.change(%Custom{}, uuid: Ecto.UUID.generate()) + {:ok, _} = TestRepo.insert(changeset) + + {:error, changeset} = + changeset + |> Ecto.Changeset.unique_constraint(:uuid) + |> TestRepo.insert() + assert changeset.errors == [uuid: {"has already been taken", [constraint: :unique, constraint_name: "customs_uuid_index"]}] + assert changeset.data.__meta__.state == :built + end + + test "unique pseudo-constraint violation error message with join table at the repository" do + post = + TestRepo.insert!(%Post{title: "some post"}) + |> TestRepo.preload(:unique_users) + + user = + TestRepo.insert!(%User{name: "some user"}) + + # Violate the unique composite index + {:error, changeset} = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:unique_users, [user, user]) + |> TestRepo.update + + errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end) + assert errors == %{unique_users: [%{}, %{id: ["has already been taken"]}]} + refute changeset.valid? + end + + @tag :join + @tag :unique_constraint + test "unique constraint violation error message with join table in single changeset" do + post = + TestRepo.insert!(%Post{title: "some post"}) + |> TestRepo.preload(:constraint_users) + + user = + TestRepo.insert!(%User{name: "some user"}) + + # Violate the unique composite index + {:error, changeset} = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:constraint_users, [user, user]) + |> Ecto.Changeset.unique_constraint(:user, + name: :posts_users_composite_pk_post_id_user_id_index, + message: "has already been assigned") + |> TestRepo.update + + errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end) + assert errors == %{constraint_users: [%{}, %{user: ["has already been assigned"]}]} + + refute changeset.valid? + end + + @tag :join + @tag :unique_constraint + test "unique constraint violation error message with join table and separate changesets" do + post = + TestRepo.insert!(%Post{title: "some post"}) + |> TestRepo.preload(:constraint_users) + + user = TestRepo.insert!(%User{name: "some user"}) + + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:constraint_users, [user]) + |> TestRepo.update + + # Violate the unique composite index + {:error, changeset} = + post + |> Ecto.Changeset.change + |> Ecto.Changeset.put_assoc(:constraint_users, [user]) + |> Ecto.Changeset.unique_constraint(:user, + name: :posts_users_composite_pk_post_id_user_id_index, + message: "has already been assigned") + |> TestRepo.update + + errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end) + assert errors == %{constraint_users: [%{user: ["has already been assigned"]}]} + + refute changeset.valid? + end + + @tag :foreign_key_constraint + test "foreign key constraint" do + changeset = Ecto.Changeset.change(%Comment{post_id: 0}) + + exception = + assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn -> + changeset + |> TestRepo.insert() + end + + assert exception.message =~ "\"comments_post_id_fkey\" (foreign_key_constraint)" + assert exception.message =~ "The changeset has not defined any constraint." + assert exception.message =~ "call `foreign_key_constraint/3`" + + message = ~r/constraint error when attempting to insert struct/ + exception = + assert_raise Ecto.ConstraintError, message, fn -> + changeset + |> Ecto.Changeset.foreign_key_constraint(:post_id, name: :comments_post_id_other) + |> TestRepo.insert() + end + + assert exception.message =~ "\"comments_post_id_other\" (foreign_key_constraint)" + + {:error, changeset} = + changeset + |> Ecto.Changeset.foreign_key_constraint(:post_id) + |> TestRepo.insert() + assert changeset.errors == [post_id: {"does not exist", [constraint: :foreign, constraint_name: "comments_post_id_fkey"]}] + end + + @tag :foreign_key_constraint + test "assoc constraint" do + changeset = Ecto.Changeset.change(%Comment{post_id: 0}) + + exception = + assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn -> + changeset + |> TestRepo.insert() + end + + assert exception.message =~ "\"comments_post_id_fkey\" (foreign_key_constraint)" + assert exception.message =~ "The changeset has not defined any constraint." + + message = ~r/constraint error when attempting to insert struct/ + exception = + assert_raise Ecto.ConstraintError, message, fn -> + changeset + |> Ecto.Changeset.assoc_constraint(:post, name: :comments_post_id_other) + |> TestRepo.insert() + end + + assert exception.message =~ "\"comments_post_id_other\" (foreign_key_constraint)" + + {:error, changeset} = + changeset + |> Ecto.Changeset.assoc_constraint(:post) + |> TestRepo.insert() + assert changeset.errors == [post: {"does not exist", [constraint: :assoc, constraint_name: "comments_post_id_fkey"]}] + end + + @tag :foreign_key_constraint + test "no assoc constraint error" do + user = TestRepo.insert!(%User{}) + TestRepo.insert!(%Permalink{user_id: user.id}) + + exception = + assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to delete struct/, fn -> + TestRepo.delete!(user) + end + + assert exception.message =~ "\"permalinks_user_id_fkey\" (foreign_key_constraint)" + assert exception.message =~ "The changeset has not defined any constraint." + end + + @tag :foreign_key_constraint + test "no assoc constraint with changeset mismatch" do + user = TestRepo.insert!(%User{}) + TestRepo.insert!(%Permalink{user_id: user.id}) + + message = ~r/constraint error when attempting to delete struct/ + exception = + assert_raise Ecto.ConstraintError, message, fn -> + user + |> Ecto.Changeset.change + |> Ecto.Changeset.no_assoc_constraint(:permalink, name: :permalinks_user_id_pther) + |> TestRepo.delete() + end + + assert exception.message =~ "\"permalinks_user_id_pther\" (foreign_key_constraint)" + end + + @tag :foreign_key_constraint + test "no assoc constraint with changeset match" do + user = TestRepo.insert!(%User{}) + TestRepo.insert!(%Permalink{user_id: user.id}) + + {:error, changeset} = + user + |> Ecto.Changeset.change + |> Ecto.Changeset.no_assoc_constraint(:permalink) + |> TestRepo.delete() + assert changeset.errors == [permalink: {"is still associated with this entry", [constraint: :no_assoc, constraint_name: "permalinks_user_id_fkey"]}] + end + + @tag :foreign_key_constraint + test "insert and update with embeds during failing child foreign key" do + changeset = + Order + |> struct(%{}) + |> order_changeset(%{item: %{price: 10}, permalink: %{post_id: 0}}) + + {:error, changeset} = TestRepo.insert(changeset) + assert %Ecto.Changeset{} = changeset.changes.item + + order = + Order + |> struct(%{}) + |> order_changeset(%{}) + |> TestRepo.insert!() + |> TestRepo.preload([:permalink]) + + changeset = order_changeset(order, %{item: %{price: 10}, permalink: %{post_id: 0}}) + assert %Ecto.Changeset{} = changeset.changes.item + + {:error, changeset} = TestRepo.update(changeset) + assert %Ecto.Changeset{} = changeset.changes.item + end + + def order_changeset(order, params) do + order + |> Ecto.Changeset.cast(params, [:permalink_id]) + |> Ecto.Changeset.cast_embed(:item, with: &item_changeset/2) + |> Ecto.Changeset.cast_assoc(:permalink, with: &permalink_changeset/2) + end + + def item_changeset(item, params) do + item + |> Ecto.Changeset.cast(params, [:price]) + end + + def permalink_changeset(comment, params) do + comment + |> Ecto.Changeset.cast(params, [:post_id]) + |> Ecto.Changeset.assoc_constraint(:post) + end + + test "unsafe_validate_unique/4" do + {:ok, inserted_post} = TestRepo.insert(%Post{title: "Greetings", visits: 13}) + new_post_changeset = Post.changeset(%Post{}, %{title: "Greetings", visits: 17}) + + changeset = Ecto.Changeset.unsafe_validate_unique(new_post_changeset, [:title], TestRepo) + assert changeset.errors[:title] == + {"has already been taken", validation: :unsafe_unique, fields: [:title]} + + changeset = Ecto.Changeset.unsafe_validate_unique(new_post_changeset, [:title, :text], TestRepo) + assert changeset.errors[:title] == nil + + update_changeset = Post.changeset(inserted_post, %{visits: 17}) + changeset = Ecto.Changeset.unsafe_validate_unique(update_changeset, [:title], TestRepo) + assert changeset.errors[:title] == nil # cannot conflict with itself + end + + test "unsafe_validate_unique/4 with composite keys" do + {:ok, inserted_post} = TestRepo.insert(%CompositePk{a: 123, b: 456, name: "UniqueName"}) + + different_pk = CompositePk.changeset(%CompositePk{}, %{name: "UniqueName", a: 789, b: 321}) + changeset = Ecto.Changeset.unsafe_validate_unique(different_pk, [:name], TestRepo) + assert changeset.errors[:name] == + {"has already been taken", validation: :unsafe_unique, fields: [:name]} + + partial_pk = CompositePk.changeset(%CompositePk{}, %{name: "UniqueName", a: 789, b: 456}) + changeset = Ecto.Changeset.unsafe_validate_unique(partial_pk, [:name], TestRepo) + assert changeset.errors[:name] == + {"has already been taken", validation: :unsafe_unique, fields: [:name]} + + update_changeset = CompositePk.changeset(inserted_post, %{name: "NewName"}) + changeset = Ecto.Changeset.unsafe_validate_unique(update_changeset, [:name], TestRepo) + assert changeset.valid? + assert changeset.errors[:name] == nil # cannot conflict with itself + end + + test "get(!)" do + post1 = TestRepo.insert!(%Post{title: "1"}) + post2 = TestRepo.insert!(%Post{title: "2"}) + + assert post1 == TestRepo.get(Post, post1.id) + assert post2 == TestRepo.get(Post, to_string post2.id) # With casting + + assert post1 == TestRepo.get!(Post, post1.id) + assert post2 == TestRepo.get!(Post, to_string post2.id) # With casting + + TestRepo.delete!(post1) + + assert TestRepo.get(Post, post1.id) == nil + assert_raise Ecto.NoResultsError, fn -> + TestRepo.get!(Post, post1.id) + end + end + + test "get(!) with custom source" do + custom = Ecto.put_meta(%Custom{}, source: "posts") + custom = TestRepo.insert!(custom) + bid = custom.bid + assert %Custom{bid: ^bid, __meta__: %{source: "posts"}} = + TestRepo.get(from(c in {"posts", Custom}), bid) + end + + test "get(!) with binary_id" do + custom = TestRepo.insert!(%Custom{}) + bid = custom.bid + assert %Custom{bid: ^bid} = TestRepo.get(Custom, bid) + end + + test "get_by(!)" do + post1 = TestRepo.insert!(%Post{title: "1", visits: 1}) + post2 = TestRepo.insert!(%Post{title: "2", visits: 2}) + + assert post1 == TestRepo.get_by(Post, id: post1.id) + assert post1 == TestRepo.get_by(Post, title: post1.title) + assert post1 == TestRepo.get_by(Post, id: post1.id, title: post1.title) + assert post2 == TestRepo.get_by(Post, id: to_string(post2.id)) # With casting + assert nil == TestRepo.get_by(Post, title: "hey") + assert nil == TestRepo.get_by(Post, id: post2.id, visits: 3) + + assert post1 == TestRepo.get_by!(Post, id: post1.id) + assert post1 == TestRepo.get_by!(Post, title: post1.title) + assert post1 == TestRepo.get_by!(Post, id: post1.id, visits: 1) + assert post2 == TestRepo.get_by!(Post, id: to_string(post2.id)) # With casting + + assert post1 == TestRepo.get_by!(Post, %{id: post1.id}) + + assert_raise Ecto.NoResultsError, fn -> + TestRepo.get_by!(Post, id: post2.id, title: "hey") + end + end + + test "reload" do + post1 = TestRepo.insert!(%Post{title: "1", visits: 1}) + post2 = TestRepo.insert!(%Post{title: "2", visits: 2}) + + assert post1 == TestRepo.reload(post1) + assert [post1, post2] == TestRepo.reload([post1, post2]) + assert [post1, post2, nil] == TestRepo.reload([post1, post2, %Post{id: 0}]) + assert nil == TestRepo.reload(%Post{id: 0}) + + # keeps order as received in the params + assert [post2, post1] == TestRepo.reload([post2, post1]) + + TestRepo.update_all(Post, inc: [visits: 1]) + + assert [%{visits: 2}, %{visits: 3}] = TestRepo.reload([post1, post2]) + end + + test "reload ignores preloads" do + post = TestRepo.insert!(%Post{title: "1", visits: 1}) |> TestRepo.preload(:comments) + + assert %{comments: %Ecto.Association.NotLoaded{}} = TestRepo.reload(post) + end + + test "reload!" do + post1 = TestRepo.insert!(%Post{title: "1", visits: 1}) + post2 = TestRepo.insert!(%Post{title: "2", visits: 2}) + + assert post1 == TestRepo.reload!(post1) + assert [post1, post2] == TestRepo.reload!([post1, post2]) + + assert_raise RuntimeError, ~r"could not reload", fn -> + TestRepo.reload!([post1, post2, %Post{id: -1}]) + end + + assert_raise Ecto.NoResultsError, fn -> + TestRepo.reload!(%Post{id: -1}) + end + + assert [post2, post1] == TestRepo.reload([post2, post1]) + + TestRepo.update_all(Post, inc: [visits: 1]) + + assert [%{visits: 2}, %{visits: 3}] = TestRepo.reload!([post1, post2]) + end + + test "first, last and one(!)" do + post1 = TestRepo.insert!(%Post{title: "1"}) + post2 = TestRepo.insert!(%Post{title: "2"}) + + assert post1 == Post |> first |> TestRepo.one + assert post2 == Post |> last |> TestRepo.one + + query = from p in Post, order_by: p.title + assert post1 == query |> first |> TestRepo.one + assert post2 == query |> last |> TestRepo.one + + query = from p in Post, order_by: [desc: p.title], limit: 10 + assert post2 == query |> first |> TestRepo.one + assert post1 == query |> last |> TestRepo.one + + query = from p in Post, where: is_nil(p.id) + refute query |> first |> TestRepo.one + refute query |> last |> TestRepo.one + assert_raise Ecto.NoResultsError, fn -> query |> first |> TestRepo.one! end + assert_raise Ecto.NoResultsError, fn -> query |> last |> TestRepo.one! end + end + + test "exists?" do + TestRepo.insert!(%Post{title: "1", visits: 2}) + TestRepo.insert!(%Post{title: "2", visits: 1}) + + query = from p in Post, where: not is_nil(p.title), limit: 2 + assert query |> TestRepo.exists? == true + + query = from p in Post, where: p.title == "1", select: p.title + assert query |> TestRepo.exists? == true + + query = from p in Post, where: is_nil(p.id) + assert query |> TestRepo.exists? == false + + query = from p in Post, where: is_nil(p.id) + assert query |> TestRepo.exists? == false + + query = from(p in Post, select: {p.visits, avg(p.visits)}, group_by: p.visits, having: avg(p.visits) > 1) + assert query |> TestRepo.exists? == true + end + + test "aggregate" do + assert TestRepo.aggregate(Post, :max, :visits) == nil + + TestRepo.insert!(%Post{visits: 10}) + TestRepo.insert!(%Post{visits: 12}) + TestRepo.insert!(%Post{visits: 14}) + TestRepo.insert!(%Post{visits: 14}) + + # Barebones + assert TestRepo.aggregate(Post, :max, :visits) == 14 + assert TestRepo.aggregate(Post, :min, :visits) == 10 + assert TestRepo.aggregate(Post, :count, :visits) == 4 + assert "50" = to_string(TestRepo.aggregate(Post, :sum, :visits)) + + # With order_by + query = from Post, order_by: [asc: :visits] + assert TestRepo.aggregate(query, :max, :visits) == 14 + + # With order_by and limit + query = from Post, order_by: [asc: :visits], limit: 2 + assert TestRepo.aggregate(query, :max, :visits) == 12 + end + + @tag :decimal_precision + test "aggregate avg" do + TestRepo.insert!(%Post{visits: 10}) + TestRepo.insert!(%Post{visits: 12}) + TestRepo.insert!(%Post{visits: 14}) + TestRepo.insert!(%Post{visits: 14}) + + assert "12.5" <> _ = to_string(TestRepo.aggregate(Post, :avg, :visits)) + end + + @tag :inline_order_by + test "aggregate with distinct" do + TestRepo.insert!(%Post{visits: 10}) + TestRepo.insert!(%Post{visits: 12}) + TestRepo.insert!(%Post{visits: 14}) + TestRepo.insert!(%Post{visits: 14}) + + query = from Post, order_by: [asc: :visits], distinct: true + assert TestRepo.aggregate(query, :count, :visits) == 3 + end + + @tag :insert_cell_wise_defaults + test "insert all" do + assert {2, nil} = TestRepo.insert_all("comments", [[text: "1"], %{text: "2", lock_version: 2}]) + assert {2, nil} = TestRepo.insert_all({"comments", Comment}, [[text: "3"], %{text: "4", lock_version: 2}]) + assert [%Comment{text: "1", lock_version: 1}, + %Comment{text: "2", lock_version: 2}, + %Comment{text: "3", lock_version: 1}, + %Comment{text: "4", lock_version: 2}] = TestRepo.all(Comment) + + assert {2, nil} = TestRepo.insert_all(Post, [[], []]) + assert [%Post{}, %Post{}] = TestRepo.all(Post) + + assert {0, nil} = TestRepo.insert_all("posts", []) + assert {0, nil} = TestRepo.insert_all({"posts", Post}, []) + end + + @tag :insert_select + test "insert all with query for single fields" do + comment = TestRepo.insert!(%Comment{text: "1", lock_version: 1}) + + text_query = from(c in Comment, select: c.text, where: [id: ^comment.id, lock_version: 1]) + + lock_version_query = from(c in Comment, select: c.lock_version, where: [id: ^comment.id]) + + rows = [ + [text: "2", lock_version: lock_version_query], + [lock_version: lock_version_query, text: "3"], + [text: text_query], + [text: text_query, lock_version: lock_version_query], + [lock_version: 6, text: "6"] + ] + assert {5, nil} = TestRepo.insert_all(Comment, rows, []) + + inserted_rows = Comment + |> where([c], c.id != ^comment.id) + |> TestRepo.all() + + assert [%Comment{text: "2", lock_version: 1}, + %Comment{text: "3", lock_version: 1}, + %Comment{text: "1"}, + %Comment{text: "1", lock_version: 1}, + %Comment{text: "6", lock_version: 6}] = inserted_rows + end + + describe "insert_all with source query" do + @tag :upsert_all + @tag :with_conflict_target + @tag :concat + test "insert_all with query and conflict target" do + {:ok, %Post{id: id}} = TestRepo.insert(%Post{ + title: "A generic title" + }) + + source = from p in Post, + select: %{ + title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id) + } + + assert {1, _} = TestRepo.insert_all(Post, source, conflict_target: [:id], on_conflict: :replace_all) + + expected_id = id + 1 + expected_title = "A generic title suffix #{id}" + + assert %Post{title: ^expected_title} = TestRepo.get(Post, expected_id) + end + + @tag :returning + @tag :concat + test "insert_all with query and returning" do + {:ok, %Post{id: id}} = TestRepo.insert(%Post{ + title: "A generic title" + }) + + source = from p in Post, + select: %{ + title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id) + } + + assert {1, returns} = TestRepo.insert_all(Post, source, returning: [:id, :title]) + + expected_id = id + 1 + expected_title = "A generic title suffix #{id}" + assert [%Post{id: ^expected_id, title: ^expected_title}] = returns + end + + @tag :upsert_all + @tag :without_conflict_target + @tag :concat + test "insert_all with query and on_conflict" do + {:ok, %Post{id: id}} = TestRepo.insert(%Post{ + title: "A generic title" + }) + + source = from p in Post, + select: %{ + title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id) + } + + assert {1, _} = TestRepo.insert_all(Post, source, on_conflict: :replace_all) + + expected_id = id + 1 + expected_title = "A generic title suffix #{id}" + + assert %Post{title: ^expected_title} = TestRepo.get(Post, expected_id) + end + + @tag :concat + test "insert_all with query" do + {:ok, %Post{id: id}} = TestRepo.insert(%Post{ + title: "A generic title" + }) + + source = from p in Post, + select: %{ + title: fragment("concat(?, ?, ?)", p.title, type(^" suffix ", :string), p.id) + } + + assert {1, _} = TestRepo.insert_all(Post, source) + + expected_id = id + 1 + expected_title = "A generic title suffix #{id}" + + assert %Post{title: ^expected_title} = TestRepo.get(Post, expected_id) + end + + test "insert_all with query and source field" do + %{id: post_id} = TestRepo.insert!(%Post{}) + TestRepo.insert!(%Permalink{url: "url", title: "title"}) + + source = from p in Permalink, select: %{url: p.title, post_id: ^post_id} + assert {1, _} = TestRepo.insert_all(Permalink, source) + end + end + + @tag :invalid_prefix + @tag :insert_cell_wise_defaults + test "insert all with invalid prefix" do + assert catch_error(TestRepo.insert_all(Post, [[], []], prefix: "oops")) + end + + @tag :returning + @tag :insert_cell_wise_defaults + test "insert all with returning with schema" do + assert {0, []} = TestRepo.insert_all(Comment, [], returning: true) + assert {0, nil} = TestRepo.insert_all(Comment, [], returning: false) + + {2, [c1, c2]} = TestRepo.insert_all(Comment, [[text: "1"], [text: "2"]], returning: [:id, :text]) + assert %Comment{text: "1", __meta__: %{state: :loaded}} = c1 + assert %Comment{text: "2", __meta__: %{state: :loaded}} = c2 + + {2, [c1, c2]} = TestRepo.insert_all(Comment, [[text: "3"], [text: "4"]], returning: true) + assert %Comment{text: "3", __meta__: %{state: :loaded}} = c1 + assert %Comment{text: "4", __meta__: %{state: :loaded}} = c2 + end + + @tag :returning + @tag :insert_cell_wise_defaults + test "insert all with returning with schema with field source" do + assert {0, []} = TestRepo.insert_all(Permalink, [], returning: true) + assert {0, nil} = TestRepo.insert_all(Permalink, [], returning: false) + + {2, [c1, c2]} = TestRepo.insert_all(Permalink, [[url: "1"], [url: "2"]], returning: [:id, :url]) + assert %Permalink{url: "1", __meta__: %{state: :loaded}} = c1 + assert %Permalink{url: "2", __meta__: %{state: :loaded}} = c2 + + {2, [c1, c2]} = TestRepo.insert_all(Permalink, [[url: "3"], [url: "4"]], returning: true) + assert %Permalink{url: "3", __meta__: %{state: :loaded}} = c1 + assert %Permalink{url: "4", __meta__: %{state: :loaded}} = c2 + end + + @tag :returning + @tag :insert_cell_wise_defaults + test "insert all with returning without schema" do + {2, [c1, c2]} = TestRepo.insert_all("comments", [[text: "1"], [text: "2"]], returning: [:id, :text]) + assert %{id: _, text: "1"} = c1 + assert %{id: _, text: "2"} = c2 + + assert_raise ArgumentError, fn -> + TestRepo.insert_all("comments", [[text: "1"], [text: "2"]], returning: true) + end + end + + @tag :insert_cell_wise_defaults + test "insert all with dumping" do + uuid = Ecto.UUID.generate() + assert {1, nil} = TestRepo.insert_all(Post, [%{uuid: uuid}]) + assert [%Post{uuid: ^uuid, title: nil}] = TestRepo.all(Post) + end + + @tag :insert_cell_wise_defaults + test "insert all autogenerates for binary_id type" do + custom = TestRepo.insert!(%Custom{bid: nil}) + assert custom.bid + assert TestRepo.get(Custom, custom.bid) + assert TestRepo.delete!(custom) + refute TestRepo.get(Custom, custom.bid) + + uuid = Ecto.UUID.generate() + assert {2, nil} = TestRepo.insert_all(Custom, [%{uuid: uuid}, %{bid: custom.bid}]) + assert [%Custom{bid: bid2, uuid: nil}, + %Custom{bid: bid1, uuid: ^uuid}] = Enum.sort_by(TestRepo.all(Custom), & &1.uuid) + assert bid1 && bid2 + assert custom.bid != bid1 + assert custom.bid == bid2 + end + + describe "placeholders" do + @describetag :placeholders + + test "Repo.insert_all fills in placeholders" do + placeholders = %{foo: 100, bar: "test"} + bar_ph = {:placeholder, :bar} + foo_ph = {:placeholder, :foo} + + entries = [ + %{intensity: 1.0, title: bar_ph, posted: ~D[2020-12-21], visits: foo_ph}, + %{intensity: 2.0, title: bar_ph, posted: ~D[2000-12-21], visits: foo_ph} + ] |> Enum.map(&Map.put(&1, :uuid, Ecto.UUID.generate)) + + TestRepo.insert_all(Post, entries, placeholders: placeholders) + + query = from(p in Post, select: {p.intensity, p.title, p.visits}) + assert [{1.0, "test", 100}, {2.0, "test", 100}] == TestRepo.all(query) + end + + test "Repo.insert_all accepts non-atom placeholder keys" do + placeholders = %{10 => "integer key", {:foo, :bar} => "tuple key"} + entries = [%{text: {:placeholder, 10}}, %{text: {:placeholder, {:foo, :bar}}}] + TestRepo.insert_all(Comment, entries, placeholders: placeholders) + + query = from(c in Comment, select: c.text) + assert ["integer key", "tuple key"] == TestRepo.all(query) + end + + test "Repo.insert_all fills in placeholders with keyword list entries" do + TestRepo.insert_all(Barebone, [[num: {:placeholder, :foo}]], placeholders: %{foo: 100}) + + query = from(b in Barebone, select: b.num) + assert [100] == TestRepo.all(query) + end + + @tag :upsert_all + @tag :with_conflict_target + test "Repo.insert_all upserts and fills in placeholders with conditioned on_conflict query" do + do_not_update_title = "don't touch me" + + posted_value = + from p in Post, where: p.public == ^true and p.id > ^0, select: p.posted, limit: 1 + + on_conflict = + from p in Post, update: [set: [title: "updated"]], where: p.title != ^do_not_update_title + + placeholders = %{visits: 1, title: "title"} + + post1 = [ + visits: {:placeholder, :visits}, + title: {:placeholder, :title}, + uuid: Ecto.UUID.generate(), + posted: posted_value + ] + + post2 = [ + title: do_not_update_title, + uuid: Ecto.UUID.generate(), + posted: posted_value + ] + + assert TestRepo.insert_all(Post, [post1, post2], + placeholders: placeholders, + on_conflict: on_conflict, + conflict_target: [:uuid] + ) == + {2, nil} + + # only update first post + assert TestRepo.insert_all(Post, [post1, post2], + placeholders: placeholders, + on_conflict: on_conflict, + conflict_target: [:uuid] + ) == + {1, nil} + + assert TestRepo.aggregate(where(Post, title: "updated"), :count) == 1 + end + end + + test "update all" do + assert post1 = TestRepo.insert!(%Post{title: "1"}) + assert post2 = TestRepo.insert!(%Post{title: "2"}) + assert post3 = TestRepo.insert!(%Post{title: "3"}) + + assert {3, nil} = TestRepo.update_all(Post, set: [title: "x"]) + + assert %Post{title: "x"} = TestRepo.reload(post1) + assert %Post{title: "x"} = TestRepo.reload(post2) + assert %Post{title: "x"} = TestRepo.reload(post3) + + assert {3, nil} = TestRepo.update_all("posts", [set: [title: nil]]) + + assert %Post{title: nil} = TestRepo.reload(post1) + assert %Post{title: nil} = TestRepo.reload(post2) + assert %Post{title: nil} = TestRepo.reload(post3) + end + + @tag :invalid_prefix + test "update all with invalid prefix" do + assert catch_error(TestRepo.update_all(Post, [set: [title: "x"]], prefix: "oops")) + end + + @tag :returning + test "update all with returning with schema" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + assert {3, posts} = TestRepo.update_all(select(Post, [p], p), [set: [title: "x"]]) + + [p1, p2, p3] = Enum.sort_by(posts, & &1.id) + assert %Post{id: ^id1, title: "x"} = p1 + assert %Post{id: ^id2, title: "x"} = p2 + assert %Post{id: ^id3, title: "x"} = p3 + + assert {3, posts} = TestRepo.update_all(select(Post, [:id, :visits]), [set: [visits: 11]]) + + [p1, p2, p3] = Enum.sort_by(posts, & &1.id) + assert %Post{id: ^id1, title: nil, visits: 11} = p1 + assert %Post{id: ^id2, title: nil, visits: 11} = p2 + assert %Post{id: ^id3, title: nil, visits: 11} = p3 + end + + @tag :returning + test "update all with returning without schema" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + assert {3, posts} = TestRepo.update_all(select("posts", [:id, :title]), [set: [title: "x"]]) + + [p1, p2, p3] = Enum.sort_by(posts, & &1.id) + assert p1 == %{id: id1, title: "x"} + assert p2 == %{id: id2, title: "x"} + assert p3 == %{id: id3, title: "x"} + end + + test "update all with filter" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + query = from(p in Post, where: p.title == "1" or p.title == "2", + update: [set: [visits: ^17]]) + assert {2, nil} = TestRepo.update_all(query, set: [title: "x"]) + + assert %Post{title: "x", visits: 17} = TestRepo.get(Post, id1) + assert %Post{title: "x", visits: 17} = TestRepo.get(Post, id2) + assert %Post{title: "3", visits: nil} = TestRepo.get(Post, id3) + end + + test "update all no entries" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + query = from(p in Post, where: p.title == "4") + assert {0, nil} = TestRepo.update_all(query, set: [title: "x"]) + + assert %Post{title: "1"} = TestRepo.get(Post, id1) + assert %Post{title: "2"} = TestRepo.get(Post, id2) + assert %Post{title: "3"} = TestRepo.get(Post, id3) + end + + test "update all increment syntax" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1", visits: 0}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2", visits: 1}) + + # Positive + query = from p in Post, where: not is_nil(p.id), update: [inc: [visits: 2]] + assert {2, nil} = TestRepo.update_all(query, []) + + assert %Post{visits: 2} = TestRepo.get(Post, id1) + assert %Post{visits: 3} = TestRepo.get(Post, id2) + + # Negative + query = from p in Post, where: not is_nil(p.id), update: [inc: [visits: -1]] + assert {2, nil} = TestRepo.update_all(query, []) + + assert %Post{visits: 1} = TestRepo.get(Post, id1) + assert %Post{visits: 2} = TestRepo.get(Post, id2) + end + + @tag :id_type + test "update all with casting and dumping on id type field" do + assert %Post{id: id1} = TestRepo.insert!(%Post{}) + assert {1, nil} = TestRepo.update_all(Post, set: [counter: to_string(id1)]) + assert %Post{counter: ^id1} = TestRepo.get(Post, id1) + end + + test "update all with casting and dumping" do + visits = 13 + datetime = ~N[2014-01-16 20:26:51] + assert %Post{id: id} = TestRepo.insert!(%Post{}) + + assert {1, nil} = TestRepo.update_all(Post, set: [visits: visits, inserted_at: datetime]) + assert %Post{visits: 13, inserted_at: ^datetime} = TestRepo.get(Post, id) + end + + test "delete all" do + assert %Post{} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{} = TestRepo.insert!(%Post{title: "3"}) + + assert {3, nil} = TestRepo.delete_all(Post) + assert [] = TestRepo.all(Post) + end + + @tag :invalid_prefix + test "delete all with invalid prefix" do + assert catch_error(TestRepo.delete_all(Post, prefix: "oops")) + end + + @tag :returning + test "delete all with returning with schema" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + assert {3, posts} = TestRepo.delete_all(select(Post, [p], p)) + + [p1, p2, p3] = Enum.sort_by(posts, & &1.id) + assert %Post{id: ^id1, title: "1"} = p1 + assert %Post{id: ^id2, title: "2"} = p2 + assert %Post{id: ^id3, title: "3"} = p3 + end + + @tag :returning + test "delete all with returning without schema" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + assert {3, posts} = TestRepo.delete_all(select("posts", [:id, :title])) + + [p1, p2, p3] = Enum.sort_by(posts, & &1.id) + assert p1 == %{id: id1, title: "1"} + assert p2 == %{id: id2, title: "2"} + assert p3 == %{id: id3, title: "3"} + end + + test "delete all with filter" do + assert %Post{} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{} = TestRepo.insert!(%Post{title: "3"}) + + query = from(p in Post, where: p.title == "1" or p.title == "2") + assert {2, nil} = TestRepo.delete_all(query) + assert [%Post{}] = TestRepo.all(Post) + end + + test "delete all no entries" do + assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"}) + assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"}) + assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"}) + + query = from(p in Post, where: p.title == "4") + assert {0, nil} = TestRepo.delete_all(query) + assert %Post{title: "1"} = TestRepo.get(Post, id1) + assert %Post{title: "2"} = TestRepo.get(Post, id2) + assert %Post{title: "3"} = TestRepo.get(Post, id3) + end + + test "virtual field" do + assert %Post{id: id} = TestRepo.insert!(%Post{title: "1"}) + assert TestRepo.get(Post, id).temp == "temp" + end + + ## Query syntax + + defmodule Foo do + defstruct [:title] + end + + describe "query select" do + test "expressions" do + %Post{} = TestRepo.insert!(%Post{title: "1", visits: 13}) + + assert [{"1", 13}] == + TestRepo.all(from p in Post, select: {p.title, p.visits}) + + assert [["1", 13]] == + TestRepo.all(from p in Post, select: [p.title, p.visits]) + + assert [%{:title => "1", 3 => 13, "visits" => 13}] == + TestRepo.all(from p in Post, select: %{ + :title => p.title, + "visits" => p.visits, + 3 => p.visits + }) + + assert [%{:title => "1", "1" => 13, "visits" => 13}] == + TestRepo.all(from p in Post, select: %{ + :title => p.title, + p.title => p.visits, + "visits" => p.visits + }) + + assert [%Foo{title: "1"}] == + TestRepo.all(from p in Post, select: %Foo{title: p.title}) + end + + test "map update" do + %Post{} = TestRepo.insert!(%Post{title: "1", visits: 13}) + + assert [%Post{:title => "new title", visits: 13}] = + TestRepo.all(from p in Post, select: %{p | title: "new title"}) + + assert [%Post{title: "new title", visits: 13}] = + TestRepo.all(from p in Post, select: %Post{p | title: "new title"}) + + assert [%Post{:title => "1", visits: -1}] = + TestRepo.all(from p in Post, select: %{p | visits: ^"-1"}) + + assert [%Post{title: "1", visits: -1}] = + TestRepo.all(from p in Post, select: %Post{p | visits: ^"-1"}) + + assert_raise KeyError, fn -> + TestRepo.all(from p in Post, select: %{p | unknown: "new title"}) + end + + assert_raise BadMapError, fn -> + TestRepo.all(from p in Post, select: %{p.title | title: "new title"}) + end + + assert_raise BadStructError, fn -> + TestRepo.all(from p in Post, select: %Foo{p | title: p.title}) + end + end + + test "map update on association" do + p = TestRepo.insert!(%Post{}) + TestRepo.insert!(%Comment{post_id: p.id, text: "comment text"}) + TestRepo.insert!(%Comment{}) + + query = + from(c in Comment, left_join: p in Post, on: c.post_id == p.id, select: %{p | temp: c.text}) + + assert [%Post{:temp => "comment text"}, nil] = TestRepo.all(query) + end + + test "take with structs" do + %{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + %{id: pid3} = TestRepo.insert!(%Post{title: "3"}) + + [p1, p2, p3] = Post |> select([p], struct(p, [:title])) |> order_by([:title]) |> TestRepo.all + refute p1.id + assert p1.title == "1" + assert match?(%Post{}, p1) + refute p2.id + assert p2.title == "2" + assert match?(%Post{}, p2) + refute p3.id + assert p3.title == "3" + assert match?(%Post{}, p3) + + [p1, p2, p3] = Post |> select([:id]) |> order_by([:id]) |> TestRepo.all + assert %Post{id: ^pid1} = p1 + assert %Post{id: ^pid2} = p2 + assert %Post{id: ^pid3} = p3 + end + + test "take with maps" do + %{id: pid1} = TestRepo.insert!(%Post{title: "1"}) + %{id: pid2} = TestRepo.insert!(%Post{title: "2"}) + %{id: pid3} = TestRepo.insert!(%Post{title: "3"}) + + [p1, p2, p3] = "posts" |> select([p], map(p, [:title])) |> order_by([:title]) |> TestRepo.all + assert p1 == %{title: "1"} + assert p2 == %{title: "2"} + assert p3 == %{title: "3"} + + [p1, p2, p3] = "posts" |> select([:id]) |> order_by([:id]) |> TestRepo.all + assert p1 == %{id: pid1} + assert p2 == %{id: pid2} + assert p3 == %{id: pid3} + end + + test "take with preload assocs" do + %{id: pid} = TestRepo.insert!(%Post{title: "post"}) + TestRepo.insert!(%Comment{post_id: pid, text: "comment"}) + fields = [:id, :title, comments: [:text, :post_id]] + + [p] = Post |> preload(:comments) |> select([p], ^fields) |> TestRepo.all + assert %Post{title: "post"} = p + assert [%Comment{text: "comment"}] = p.comments + + [p] = Post |> preload(:comments) |> select([p], struct(p, ^fields)) |> TestRepo.all + assert %Post{title: "post"} = p + assert [%Comment{text: "comment"}] = p.comments + + [p] = Post |> preload(:comments) |> select([p], map(p, ^fields)) |> TestRepo.all + assert p == %{id: pid, title: "post", comments: [%{text: "comment", post_id: pid}]} + end + + test "take with nil preload assoc" do + %{id: cid} = TestRepo.insert!(%Comment{text: "comment"}) + fields = [:id, :text, post: [:title]] + + [c] = Comment |> preload(:post) |> select([c], ^fields) |> TestRepo.all + assert %Comment{id: ^cid, text: "comment", post: nil} = c + + [c] = Comment |> preload(:post) |> select([c], struct(c, ^fields)) |> TestRepo.all + assert %Comment{id: ^cid, text: "comment", post: nil} = c + + [c] = Comment |> preload(:post) |> select([c], map(c, ^fields)) |> TestRepo.all + assert c == %{id: cid, text: "comment", post: nil} + end + + test "take with join assocs" do + %{id: pid} = TestRepo.insert!(%Post{title: "post"}) + %{id: cid} = TestRepo.insert!(%Comment{post_id: pid, text: "comment"}) + fields = [:id, :title, comments: [:text, :post_id, :id]] + query = from p in Post, where: p.id == ^pid, join: c in assoc(p, :comments), preload: [comments: c] + + p = TestRepo.one(from q in query, select: ^fields) + assert %Post{title: "post"} = p + assert [%Comment{text: "comment"}] = p.comments + + p = TestRepo.one(from q in query, select: struct(q, ^fields)) + assert %Post{title: "post"} = p + assert [%Comment{text: "comment"}] = p.comments + + p = TestRepo.one(from q in query, select: map(q, ^fields)) + assert p == %{id: pid, title: "post", comments: [%{text: "comment", post_id: pid, id: cid}]} + end + + test "take with single nil column" do + %Post{} = TestRepo.insert!(%Post{title: "1", counter: nil}) + assert %{counter: nil} = + TestRepo.one(from p in Post, where: p.title == "1", select: [:counter]) + end + + test "take with join assocs and single nil column" do + %{id: post_id} = TestRepo.insert!(%Post{title: "1"}, counter: nil) + TestRepo.insert!(%Comment{post_id: post_id, text: "comment"}) + assert %{counter: nil} == + TestRepo.one(from p in Post, join: c in assoc(p, :comments), where: p.title == "1", select: map(p, [:counter])) + end + + test "field source" do + TestRepo.insert!(%Permalink{url: "url"}) + assert ["url"] = Permalink |> select([p], p.url) |> TestRepo.all() + assert [1] = Permalink |> select([p], count(p.url)) |> TestRepo.all() + end + + test "merge" do + date = Date.utc_today() + %Post{id: post_id} = TestRepo.insert!(%Post{title: "1", counter: nil, posted: date, public: false}) + + # Merge on source + assert [%Post{title: "2"}] = + Post |> select([p], merge(p, %{title: "2"})) |> TestRepo.all() + assert [%Post{title: "2"}] = + Post |> select([p], p) |> select_merge([p], %{title: "2"}) |> TestRepo.all() + + # Merge on struct + assert [%Post{title: "2"}] = + Post |> select([p], merge(%Post{title: p.title}, %{title: "2"})) |> TestRepo.all() + assert [%Post{title: "2"}] = + Post |> select([p], %Post{title: p.title}) |> select_merge([p], %{title: "2"}) |> TestRepo.all() + + # Merge on map + assert [%{title: "2"}] = + Post |> select([p], merge(%{title: p.title}, %{title: "2"})) |> TestRepo.all() + assert [%{title: "2"}] = + Post |> select([p], %{title: p.title}) |> select_merge([p], %{title: "2"}) |> TestRepo.all() + + # Merge on outer join with map + %Permalink{} = TestRepo.insert!(%Permalink{post_id: post_id, url: "Q", title: "Z"}) + + # left join record is present + assert [%{url: "Q", title: "1", posted: _date}] = + Permalink + |> join(:left, [l], p in Post, on: l.post_id == p.id) + |> select([l, p], merge(l, map(p, ^~w(title posted)a))) + |> TestRepo.all() + + assert [%{url: "Q", title: "1", posted: _date}] = + Permalink + |> join(:left, [l], p in Post, on: l.post_id == p.id) + |> select_merge([_l, p], map(p, ^~w(title posted)a)) + |> TestRepo.all() + + # left join record is not present + assert [%{url: "Q", title: "Z", posted: nil}] = + Permalink + |> join(:left, [l], p in Post, on: l.post_id == p.id and p.public == true) + |> select([l, p], merge(l, map(p, ^~w(title posted)a))) + |> TestRepo.all() + + assert [%{url: "Q", title: "Z", posted: nil}] = + Permalink + |> join(:left, [l], p in Post, on: l.post_id == p.id and p.public == true) + |> select_merge([_l, p], map(p, ^~w(title posted)a)) + |> TestRepo.all() + end + + test "merge with update on self" do + %Post{} = TestRepo.insert!(%Post{title: "1", counter: 1}) + + assert [%Post{title: "1", counter: 2}] = + Post |> select([p], merge(p, %{p | counter: 2})) |> TestRepo.all() + assert [%Post{title: "1", counter: 2}] = + Post |> select([p], p) |> select_merge([p], %{p | counter: 2}) |> TestRepo.all() + end + + test "merge within subquery" do + %Post{} = TestRepo.insert!(%Post{title: "1", counter: 1}) + + subquery = + Post + |> select_merge([p], %{p | counter: 2}) + |> subquery() + + assert [%Post{title: "1", counter: 2}] = TestRepo.all(subquery) + end + + @tag :selected_as_with_group_by + test "selected_as/2 with group_by" do + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3}) + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 2}) + TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil}) + + query = + from p in Post, + select: %{ + posted: selected_as(p.posted, :date), + min_visits: p.visits |> coalesce(0) |> min() + }, + group_by: selected_as(:date), + order_by: p.posted + + assert [%{posted: ~D[2020-12-20], min_visits: 0}, %{posted: ~D[2020-12-21], min_visits: 2}] = + TestRepo.all(query) + end + + @tag :selected_as_with_order_by + test "selected_as/2 with order_by" do + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3}) + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 2}) + TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil}) + + base_query = + from p in Post, + select: %{ + posted: p.posted, + min_visits: p.visits |> coalesce(0) |> min() |> selected_as(:min_visits) + }, + group_by: p.posted + + # ascending order + results = base_query |> order_by(selected_as(:min_visits)) |> TestRepo.all() + + assert [%{posted: ~D[2020-12-20], min_visits: 0}, %{posted: ~D[2020-12-21], min_visits: 2}] = + results + + # descending order + results = base_query |> order_by([desc: selected_as(:min_visits)]) |> TestRepo.all() + + assert [%{posted: ~D[2020-12-21], min_visits: 2}, %{posted: ~D[2020-12-20], min_visits: 0}] = + results + end + + @tag :selected_as_with_order_by + test "selected_as/2 respects custom types" do + TestRepo.insert!(%Post{title: "title1", visits: 1}) + TestRepo.insert!(%Post{title: "title2"}) + uuid = Ecto.UUID.generate() + + query = + from p in Post, + select: %{ + uuid: type(^uuid, Ecto.UUID) |> selected_as(:uuid), + visits: p.visits |> coalesce(0) |> selected_as(:visits) + }, + order_by: [selected_as(:uuid), selected_as(:visits)] + + assert [%{uuid: ^uuid, visits: 0}, %{uuid: ^uuid, visits: 1}] = TestRepo.all(query) + end + + @tag :selected_as_with_order_by_expression + test "selected_as/2 with order_by expression" do + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3, intensity: 2.0}) + TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil, intensity: 10.0}) + + results = + from(p in Post, + select: %{ + posted: p.posted, + visits: p.visits |> coalesce(0) |> selected_as(:num_visits), + intensity: selected_as(p.intensity, :strength) + }, + order_by: [desc: (selected_as(:num_visits) + selected_as(:strength))] + ) + |> TestRepo.all() + + assert [%{posted: ~D[2020-12-20], visits: 0}, %{posted: ~D[2020-12-21], visits: 3}] = + results + end + + @tag :selected_as_with_having + test "selected_as/2 with having" do + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 3}) + TestRepo.insert!(%Post{posted: ~D[2020-12-21], visits: 2}) + TestRepo.insert!(%Post{posted: ~D[2020-12-20], visits: nil}) + + results = + from(p in Post, + select: %{ + posted: p.posted, + min_visits: p.visits |> coalesce(0) |> min() |> selected_as(:min_visits) + }, + group_by: p.posted, + having: selected_as(:min_visits) > 0, + or_having: not(selected_as(:min_visits) > 0), + order_by: p.posted + ) + |> TestRepo.all() + + assert [%{posted: ~D[2020-12-20], min_visits: 0}, %{posted: ~D[2020-12-21], min_visits: 2}] = results + end + end + + @tag :distinct_count + test "query count distinct" do + TestRepo.insert!(%Post{title: "1"}) + TestRepo.insert!(%Post{title: "1"}) + TestRepo.insert!(%Post{title: "2"}) + + assert [3] == Post |> select([p], count(p.title)) |> TestRepo.all + assert [2] == Post |> select([p], count(p.title, :distinct)) |> TestRepo.all + end + + test "query where interpolation" do + post1 = TestRepo.insert!(%Post{title: "hello"}) + post2 = TestRepo.insert!(%Post{title: "goodbye"}) + + assert [post1, post2] == Post |> where([], []) |> TestRepo.all |> Enum.sort_by(& &1.id) + assert [post1] == Post |> where([], [title: "hello"]) |> TestRepo.all + assert [post1] == Post |> where([], [title: "hello", id: ^post1.id]) |> TestRepo.all + + params0 = [] + params1 = [title: "hello"] + params2 = [title: "hello", id: post1.id] + assert [post1, post2] == (from Post, where: ^params0) |> TestRepo.all |> Enum.sort_by(& &1.id) + assert [post1] == (from Post, where: ^params1) |> TestRepo.all + assert [post1] == (from Post, where: ^params2) |> TestRepo.all + + post3 = TestRepo.insert!(%Post{title: "goodbye", uuid: nil}) + params3 = [title: "goodbye", uuid: post3.uuid] + assert [post3] == (from Post, where: ^params3) |> TestRepo.all + end + + describe "upsert via insert" do + @describetag :upsert + + test "on conflict raise" do + {:ok, inserted} = TestRepo.insert(%Post{title: "first"}, on_conflict: :raise) + assert catch_error(TestRepo.insert(%Post{id: inserted.id, title: "second"}, on_conflict: :raise)) + end + + test "on conflict ignore" do + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing) + assert inserted.id + assert inserted.__meta__.state == :loaded + + {:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing) + assert not_inserted.id == nil + assert not_inserted.__meta__.state == :loaded + end + + @tag :with_conflict_target + test "on conflict and associations" do + on_conflict = [set: [title: "second"]] + post = %Post{uuid: Ecto.UUID.generate(), + title: "first", comments: [%Comment{}]} + {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid]) + assert inserted.id + end + + @tag :with_conflict_target + test "on conflict with inc" do + uuid = "6fa459ea-ee8a-3ca4-894e-db77e160355e" + post = %Post{title: "first", uuid: uuid} + {:ok, _} = TestRepo.insert(post) + post = %{title: "upsert", uuid: uuid} + TestRepo.insert_all(Post, [post], on_conflict: [inc: [visits: 1]], conflict_target: :uuid) + end + + @tag :with_conflict_target + test "on conflict ignore and conflict target" do + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid]) + assert inserted.id + + # Error on non-conflict target + assert catch_error(TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:id])) + + # Error on conflict target + {:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid]) + assert not_inserted.id == nil + end + + @tag :without_conflict_target + test "on conflict keyword list" do + on_conflict = [set: [title: "second"]] + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict) + assert inserted.id + + {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict) + assert updated.id == inserted.id + assert updated.title != "second" + assert TestRepo.get!(Post, inserted.id).title == "second" + end + + @tag :with_conflict_target + test "on conflict keyword list and conflict target" do + on_conflict = [set: [title: "second"]] + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid]) + assert inserted.id + + # Error on non-conflict target + assert catch_error(TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:id])) + + {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid]) + assert updated.id == inserted.id + assert updated.title != "second" + assert TestRepo.get!(Post, inserted.id).title == "second" + end + + @tag :returning + @tag :with_conflict_target + test "on conflict keyword list and conflict target and returning" do + {:ok, c1} = TestRepo.insert(%Post{}) + {:ok, c2} = TestRepo.insert(%Post{id: c1.id}, on_conflict: [set: [id: c1.id]], conflict_target: [:id], returning: [:id, :uuid]) + {:ok, c3} = TestRepo.insert(%Post{id: c1.id}, on_conflict: [set: [id: c1.id]], conflict_target: [:id], returning: true) + {:ok, c4} = TestRepo.insert(%Post{id: c1.id}, on_conflict: [set: [id: c1.id]], conflict_target: [:id], returning: false) + + assert c2.uuid == c1.uuid + assert c3.uuid == c1.uuid + assert c4.uuid != c1.uuid + end + + @tag :returning + @tag :with_conflict_target + test "on conflict keyword list and conflict target and returning and field source" do + TestRepo.insert!(%Permalink{url: "old"}) + {:ok, c1} = TestRepo.insert(%Permalink{url: "old"}, + on_conflict: [set: [url: "new1"]], + conflict_target: [:url], + returning: [:url]) + + TestRepo.insert!(%Permalink{url: "old"}) + {:ok, c2} = TestRepo.insert(%Permalink{url: "old"}, + on_conflict: [set: [url: "new2"]], + conflict_target: [:url], + returning: true) + + assert c1.url == "new1" + assert c2.url == "new2" + end + + @tag :returning + @tag :with_conflict_target + test "on conflict ignore and returning" do + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid]) + assert inserted.id + + {:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid], returning: true) + assert not_inserted.id == nil + end + + @tag :without_conflict_target + test "on conflict query" do + on_conflict = from Post, update: [set: [title: "second"]] + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict) + assert inserted.id + + {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict) + assert updated.id == inserted.id + assert updated.title != "second" + assert TestRepo.get!(Post, inserted.id).title == "second" + end + + @tag :with_conflict_target + test "on conflict query and conflict target" do + on_conflict = from Post, update: [set: [title: "second"]] + post = %Post{title: "first", uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid]) + assert inserted.id + + # Error on non-conflict target + assert catch_error(TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:id])) + + {:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid]) + assert updated.id == inserted.id + assert updated.title != "second" + assert TestRepo.get!(Post, inserted.id).title == "second" + end + + @tag :with_conflict_target + test "on conflict query having condition" do + post = %Post{title: "first", counter: 1, uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post) + + on_conflict = from Post, where: [counter: 2], update: [set: [title: "second"]] + + insert_options = [ + on_conflict: on_conflict, + conflict_target: [:uuid], + stale_error_field: :counter + ] + + assert {:error, changeset} = TestRepo.insert(post, insert_options) + assert changeset.errors == [counter: {"is stale", [stale: true]}] + + assert TestRepo.get!(Post, inserted.id).title == "first" + end + + @tag :without_conflict_target + test "on conflict replace_all" do + post = %Post{title: "first", visits: 13, uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: :replace_all) + assert inserted.id + + post = %Post{title: "updated", visits: 17, uuid: post.uuid} + post = TestRepo.insert!(post, on_conflict: :replace_all) + assert post.id != inserted.id + assert post.title == "updated" + assert post.visits == 17 + + assert TestRepo.all(from p in Post, select: {p.id, p.title, p.visits}) == + [{post.id, "updated", 17}] + assert TestRepo.all(from p in Post, select: count(p.id)) == [1] + end + + @tag :with_conflict_target + test "on conflict replace_all and conflict target" do + post = %Post{title: "first", visits: 13, uuid: Ecto.UUID.generate()} + {:ok, inserted} = TestRepo.insert(post, on_conflict: :replace_all, conflict_target: :uuid) + assert inserted.id + + post = %Post{title: "updated", visits: 17, uuid: post.uuid} + post = TestRepo.insert!(post, on_conflict: :replace_all, conflict_target: :uuid) + assert post.id != inserted.id + assert post.title == "updated" + assert post.visits == 17 + + assert TestRepo.all(from p in Post, select: {p.id, p.title, p.visits}) == + [{post.id, "updated", 17}] + assert TestRepo.all(from p in Post, select: count(p.id)) == [1] + end + end + + describe "upsert via insert_all" do + @describetag :upsert_all + + test "on conflict raise" do + post = [title: "first", uuid: Ecto.UUID.generate()] + {1, nil} = TestRepo.insert_all(Post, [post], on_conflict: :raise) + assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: :raise)) + end + + test "on conflict ignore" do + post = [title: "first", uuid: Ecto.UUID.generate()] + assert TestRepo.insert_all(Post, [post], on_conflict: :nothing) == {1, nil} + + # PG returns 0, MySQL returns 1 + {entries, nil} = TestRepo.insert_all(Post, [post], on_conflict: :nothing) + assert entries == 0 or entries == 1 + + assert length(TestRepo.all(Post)) == 1 + end + + @tag :with_conflict_target + test "on conflict ignore and conflict target" do + post = [title: "first", uuid: Ecto.UUID.generate()] + assert TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:uuid]) == + {1, nil} + + # Error on non-conflict target + assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:id])) + + # Error on conflict target + assert TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:uuid]) == + {0, nil} + end + + @tag :with_conflict_target + test "on conflict keyword list and conflict target" do + on_conflict = [set: [title: "second"]] + post = [title: "first", uuid: Ecto.UUID.generate()] + {1, nil} = TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) + + # Error on non-conflict target + assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id])) + + # Error on conflict target + assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + assert TestRepo.all(from p in Post, select: p.title) == ["second"] + end + + @tag :with_conflict_target + @tag :returning + test "on conflict keyword list and conflict target and returning and source field" do + on_conflict = [set: [url: "new"]] + permalink = [url: "old"] + + assert {1, [%Permalink{url: "old"}]} = + TestRepo.insert_all(Permalink, [permalink], + on_conflict: on_conflict, conflict_target: [:url], returning: [:url]) + + assert {1, [%Permalink{url: "new"}]} = + TestRepo.insert_all(Permalink, [permalink], + on_conflict: on_conflict, conflict_target: [:url], returning: [:url]) + end + + @tag :with_conflict_target + test "on conflict query and conflict target" do + on_conflict = from p in Post, where: p.id > ^0, update: [set: [title: "second"]] + post = [title: "first", uuid: Ecto.UUID.generate()] + assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + + # Error on non-conflict target + assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id])) + + # Error on conflict target + assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + assert TestRepo.all(from p in Post, select: p.title) == ["second"] + end + + @tag :insert_select + @tag :with_conflict_target + test "on conflict query and insert select and conflict target" do + on_conflict = from p in Post, where: p.id > ^0, update: [set: [title: "second"]] + visits_value = from p in Post, where: p.public == ^true and p.id > ^0, select: p.visits, limit: 1 + post = [title: "first", uuid: Ecto.UUID.generate(), visits: visits_value] + assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + + # Error on non-conflict target + assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id])) + + # Error on conflict target + assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + assert TestRepo.all(from p in Post, select: p.title) == ["second"] + end + + @tag :returning + @tag :with_conflict_target + test "on conflict query and conflict target and returning" do + on_conflict = from Post, update: [set: [title: "second"]] + post = [title: "first", uuid: Ecto.UUID.generate()] + {1, [%{id: id}]} = TestRepo.insert_all(Post, [post], on_conflict: on_conflict, + conflict_target: [:uuid], returning: [:id]) + + # Error on non-conflict target + assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, + conflict_target: [:id], returning: [:id])) + + # Error on conflict target + {1, [%Post{id: ^id, title: "second"}]} = + TestRepo.insert_all(Post, [post], on_conflict: on_conflict, + conflict_target: [:uuid], returning: [:id, :title]) + end + + @tag :with_conflict_target + test "source (without an Ecto schema) on conflict query and conflict target" do + on_conflict = [set: [title: "second"]] + {:ok, uuid} = Ecto.UUID.dump(Ecto.UUID.generate()) + post = [title: "first", uuid: uuid] + assert TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + + # Error on non-conflict target + assert catch_error(TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:id])) + + # Error on conflict target + assert TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:uuid]) == + {1, nil} + assert TestRepo.all(from p in Post, select: p.title) == ["second"] + end + + @tag :without_conflict_target + test "on conflict replace_all" do + post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()} + post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()} + + {:ok, post_first} = TestRepo.insert(post_first, on_conflict: :replace_all) + {:ok, post_second} = TestRepo.insert(post_second, on_conflict: :replace_all) + + assert post_first.id + assert post_second.id + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + # Multiple record change value: note IDS are also replaced + changes = [%{id: post_first.id + 2, title: "first_updated", + visits: 1, uuid: post_first.uuid}, + %{id: post_second.id + 2, title: "second_updated", + visits: 2, uuid: post_second.uuid}] + + TestRepo.insert_all(Post, changes, on_conflict: :replace_all) + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + updated_first = TestRepo.get(Post, post_first.id + 2) + assert updated_first.title == "first_updated" + assert updated_first.visits == 1 + + updated_second = TestRepo.get(Post, post_second.id + 2) + assert updated_second.title == "second_updated" + assert updated_second.visits == 2 + end + + @tag :with_conflict_target + test "on conflict replace_all and conflict_target" do + post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()} + post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()} + + {:ok, post_first} = TestRepo.insert(post_first, on_conflict: :replace_all, conflict_target: :uuid) + {:ok, post_second} = TestRepo.insert(post_second, on_conflict: :replace_all, conflict_target: :uuid) + + assert post_first.id + assert post_second.id + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + # Multiple record change value: note IDS are also replaced + changes = [%{id: post_second.id + 1, title: "first_updated", + visits: 1, uuid: post_first.uuid}, + %{id: post_second.id + 2, title: "second_updated", + visits: 2, uuid: post_second.uuid}] + + TestRepo.insert_all(Post, changes, on_conflict: :replace_all, conflict_target: :uuid) + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + updated_first = TestRepo.get(Post, post_second.id + 1) + assert updated_first.title == "first_updated" + assert updated_first.visits == 1 + + updated_second = TestRepo.get(Post, post_second.id + 2) + assert updated_second.title == "second_updated" + assert updated_second.visits == 2 + end + + @tag :without_conflict_target + test "on conflict replace_all_except" do + post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()} + post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()} + + {:ok, post_first} = TestRepo.insert(post_first, on_conflict: {:replace_all_except, [:id]}) + {:ok, post_second} = TestRepo.insert(post_second, on_conflict: {:replace_all_except, [:id]}) + + assert post_first.id + assert post_second.id + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + # Multiple record change value: note IDS are not replaced + changes = [%{id: post_first.id + 2, title: "first_updated", + visits: 1, uuid: post_first.uuid}, + %{id: post_second.id + 2, title: "second_updated", + visits: 2, uuid: post_second.uuid}] + + TestRepo.insert_all(Post, changes, on_conflict: {:replace_all_except, [:id]}) + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + updated_first = TestRepo.get(Post, post_first.id) + assert updated_first.title == "first_updated" + assert updated_first.visits == 1 + + updated_second = TestRepo.get(Post, post_second.id) + assert updated_second.title == "second_updated" + assert updated_second.visits == 2 + end + + @tag :with_conflict_target + test "on conflict replace_all_except and conflict_target" do + post_first = %Post{title: "first", public: true, uuid: Ecto.UUID.generate()} + post_second = %Post{title: "second", public: false, uuid: Ecto.UUID.generate()} + + {:ok, post_first} = TestRepo.insert(post_first, on_conflict: {:replace_all_except, [:id]}, conflict_target: :uuid) + {:ok, post_second} = TestRepo.insert(post_second, on_conflict: {:replace_all_except, [:id]}, conflict_target: :uuid) + + assert post_first.id + assert post_second.id + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + # Multiple record change value: note IDS are not replaced + changes = [%{id: post_first.id + 2, title: "first_updated", + visits: 1, uuid: post_first.uuid}, + %{id: post_second.id + 2, title: "second_updated", + visits: 2, uuid: post_second.uuid}] + + TestRepo.insert_all(Post, changes, on_conflict: {:replace_all_except, [:id]}, conflict_target: :uuid) + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + updated_first = TestRepo.get(Post, post_first.id) + assert updated_first.title == "first_updated" + assert updated_first.visits == 1 + + updated_second = TestRepo.get(Post, post_second.id) + assert updated_second.title == "second_updated" + assert updated_second.visits == 2 + end + + @tag :with_conflict_target + test "on conflict replace and conflict_target" do + post_first = %Post{title: "first", visits: 10, public: true, uuid: Ecto.UUID.generate()} + post_second = %Post{title: "second", visits: 20, public: false, uuid: Ecto.UUID.generate()} + + {:ok, post_first} = TestRepo.insert(post_first, on_conflict: {:replace, [:title, :visits]}, conflict_target: :uuid) + {:ok, post_second} = TestRepo.insert(post_second, on_conflict: {:replace, [:title, :visits]}, conflict_target: :uuid) + + assert post_first.id + assert post_second.id + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + # Multiple record change value: note `public` field is not changed + changes = [%{id: post_first.id, title: "first_updated", visits: 11, public: false, uuid: post_first.uuid}, + %{id: post_second.id, title: "second_updated", visits: 21, public: true, uuid: post_second.uuid}] + + TestRepo.insert_all(Post, changes, on_conflict: {:replace, [:title, :visits]}, conflict_target: :uuid) + assert TestRepo.all(from p in Post, select: count(p.id)) == [2] + + updated_first = TestRepo.get(Post, post_first.id) + assert updated_first.title == "first_updated" + assert updated_first.visits == 11 + assert updated_first.public == true + + updated_second = TestRepo.get(Post, post_second.id) + assert updated_second.title == "second_updated" + assert updated_second.visits == 21 + assert updated_second.public == false + end + end + + describe "values list" do + @describetag :values_list + + test "all" do + uuid_module = uuid_module(TestRepo.__adapter__()) + uuid = uuid_module.generate() + + # Without select + values = [%{bid: uuid, visits: 1}, %{bid: uuid, visits: 2}] + types = %{bid: uuid_module, visits: :integer} + query = from v in values(values, types) + assert TestRepo.all(query) == values + + # With select + query = select(query, [v], {v, v.bid}) + assert TestRepo.all(query) == Enum.map(values, &{&1, &1.bid}) + end + + test "all with join" do + uuid_module = uuid_module(TestRepo.__adapter__()) + uuid = uuid_module.generate() + + values1 = [%{bid: uuid, visits: 1}, %{bid: uuid, visits: 2}] + values2 = [%{bid: uuid, visits: 1}] + types = %{bid: uuid_module, visits: :integer} + + query = + from v1 in values(values1, types), + join: v2 in values(values2, types), + on: v1.visits == v2.visits + + assert TestRepo.all(query) == [%{bid: uuid, visits: 1}] + end + + test "delete_all" do + uuid_module = uuid_module(TestRepo.__adapter__()) + uuid = uuid_module.generate() + + _p1 = TestRepo.insert!(%Post{bid: uuid, visits: 1}) + p2 = TestRepo.insert!(%Post{bid: uuid, visits: 5}) + + values = [%{bid: uuid, visits: 1}, %{bid: nil, visits: 1}, %{bid: uuid, visits: 3}] + types = %{bid: uuid_module, visits: :integer} + + query = + from p in Post, + join: v in values(values, types), + on: p.visits == v.visits + + assert {1, _} = TestRepo.delete_all(query) + assert TestRepo.all(Post) == [p2] + end + + test "update_all" do + uuid_module = uuid_module(TestRepo.__adapter__()) + uuid = uuid_module.generate() + + TestRepo.insert!(%Post{bid: uuid, visits: 1}) + + values = [%{bid: uuid, visits: 10}, %{bid: nil, visits: 2}] + types = %{bid: uuid_module, visits: :integer} + + query = + from p in Post, + join: v in values(values, types), + on: p.bid == v.bid, + update: [set: [visits: v.visits]] + + assert {1, _} = TestRepo.update_all(query, []) + assert [%{visits: 10}] = TestRepo.all(Post) + end + + defp uuid_module(Ecto.Adapters.Tds), do: Tds.Ecto.UUID + defp uuid_module(_), do: Ecto.UUID + end +end diff --git a/deps/ecto/integration_test/cases/type.exs b/deps/ecto/integration_test/cases/type.exs new file mode 100644 index 0000000000000000000000000000000000000000..f0b52b513d4554be94048eda003f89c2e6ee0642 --- /dev/null +++ b/deps/ecto/integration_test/cases/type.exs @@ -0,0 +1,601 @@ +defmodule Ecto.Integration.TypeTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.{Bitstring, Comment, Custom, Item, ItemColor, Order, Post, User, Tag, Usec} + alias Ecto.Integration.TestRepo + import Ecto.Query + + @parameterized_type Ecto.ParameterizedType.init(Ecto.Enum, values: [:a, :b]) + + test "primitive types" do + integer = 1 + float = 0.1 + blob = <<0, 1>> + uuid = "00010203-0405-4607-8809-0a0b0c0d0e0f" + datetime = ~N[2014-01-16 20:26:51] + + TestRepo.insert!(%Post{blob: blob, public: true, visits: integer, uuid: uuid, + counter: integer, inserted_at: datetime, intensity: float}) + + # nil + assert [nil] = TestRepo.all(from Post, select: nil) + + # ID + assert [1] = TestRepo.all(from p in Post, where: p.counter == ^integer, select: p.counter) + + # Integers + assert [1] = TestRepo.all(from p in Post, where: p.visits == ^integer, select: p.visits) + assert [1] = TestRepo.all(from p in Post, where: p.visits == 1, select: p.visits) + assert [3] = TestRepo.all(from p in Post, select: p.visits + 2) + + # Floats + assert [0.1] = TestRepo.all(from p in Post, where: p.intensity == ^float, select: p.intensity) + assert [0.1] = TestRepo.all(from p in Post, where: p.intensity == 0.1, select: p.intensity) + assert [1500.0] = TestRepo.all(from p in Post, select: 1500.0) + assert [0.5] = TestRepo.all(from p in Post, select: p.intensity * 5) + + # Booleans + assert [true] = TestRepo.all(from p in Post, where: p.public == ^true, select: p.public) + assert [true] = TestRepo.all(from p in Post, where: p.public == true, select: p.public) + + # Binaries + assert [^blob] = TestRepo.all(from p in Post, where: p.blob == <<0, 1>>, select: p.blob) + assert [^blob] = TestRepo.all(from p in Post, where: p.blob == ^blob, select: p.blob) + + # UUID + assert [^uuid] = TestRepo.all(from p in Post, where: p.uuid == ^uuid, select: p.uuid) + + # NaiveDatetime + assert [^datetime] = TestRepo.all(from p in Post, where: p.inserted_at == ^datetime, select: p.inserted_at) + + # Datetime + datetime = DateTime.from_unix!(System.os_time(:second), :second) + TestRepo.insert!(%User{inserted_at: datetime}) + assert [^datetime] = TestRepo.all(from u in User, where: u.inserted_at == ^datetime, select: u.inserted_at) + + # usec + naive_datetime = ~N[2014-01-16 20:26:51.000000] + datetime = DateTime.from_naive!(~N[2014-01-16 20:26:51.000000], "Etc/UTC") + TestRepo.insert!(%Usec{naive_datetime_usec: naive_datetime, utc_datetime_usec: datetime}) + assert [^naive_datetime] = TestRepo.all(from u in Usec, where: u.naive_datetime_usec == ^naive_datetime, select: u.naive_datetime_usec) + assert [^datetime] = TestRepo.all(from u in Usec, where: u.utc_datetime_usec == ^datetime, select: u.utc_datetime_usec) + + naive_datetime = ~N[2014-01-16 20:26:51.123000] + datetime = DateTime.from_naive!(~N[2014-01-16 20:26:51.123000], "Etc/UTC") + TestRepo.insert!(%Usec{naive_datetime_usec: naive_datetime, utc_datetime_usec: datetime}) + assert [^naive_datetime] = TestRepo.all(from u in Usec, where: u.naive_datetime_usec == ^naive_datetime, select: u.naive_datetime_usec) + assert [^datetime] = TestRepo.all(from u in Usec, where: u.utc_datetime_usec == ^datetime, select: u.utc_datetime_usec) + end + + @tag :bitstring_type + test "bitstring type" do + bitstring = <<2::3>> + + TestRepo.insert!(%Bitstring{bs: bitstring, bs_with_size: <<5::10>>}) + + # Bitstrings + assert [^bitstring] = TestRepo.all(from p in Bitstring, where: p.bs == ^bitstring, select: p.bs) + assert [^bitstring] = TestRepo.all(from p in Bitstring, where: p.bs == <<2::3>>, select: p.bs) + + assert [<<42::6>>] = TestRepo.all(from p in Bitstring, limit: 1, select: p.bs_with_default) + end + + if Code.ensure_loaded?(Duration) do + @tag :duration_type + test "duration type" do + duration = %Duration{year: 1, month: 1, second: 1, microsecond: {100, 6}} + + struct = %Ecto.Integration.Duration{ + dur: duration, + dur_with_fields: duration, + dur_with_precision: duration, + dur_with_fields_and_precision: duration + } + + TestRepo.insert!(struct) + + persisted_duration = + from(d in Ecto.Integration.Duration, where: d.dur == ^duration) + |> TestRepo.one() + + assert persisted_duration.dur == duration + + # `:field` option set to MONTH so it ignores all units lower than `:month` + assert persisted_duration.dur_with_fields == %Duration{ + year: 1, + month: 1, + microsecond: {0, 6} + } + + assert persisted_duration.dur_with_precision == %Duration{ + year: 1, + month: 1, + second: 1, + microsecond: {100, 4} + } + + # `:field` option is set to HOUR TO SECOND so it ignores all units lower than `:second` + assert persisted_duration.dur_with_fields_and_precision == %Duration{ + year: 1, + month: 1, + second: 1, + microsecond: {0, 1} + } + + # `:default set in migration` + assert persisted_duration.dur_with_default == %Duration{month: 10, microsecond: {0, 6}} + end + end + + @tag :select_not + test "primitive types boolean negate" do + TestRepo.insert!(%Post{public: true}) + assert [false] = TestRepo.all(from p in Post, where: p.public == true, select: not p.public) + assert [true] = TestRepo.all(from p in Post, where: p.public == true, select: not not p.public) + end + + test "aggregate types" do + datetime = ~N[2014-01-16 20:26:51] + TestRepo.insert!(%Post{inserted_at: datetime}) + query = from p in Post, select: max(p.inserted_at) + assert [^datetime] = TestRepo.all(query) + end + + # We don't specifically assert on the tuple content because + # some databases would return integer, others decimal. + # The important is that the type has been invoked for wrapping. + test "aggregate custom types" do + TestRepo.insert!(%Post{wrapped_visits: {:int, 10}}) + query = from p in Post, select: sum(p.wrapped_visits) + assert [{:int, _}] = TestRepo.all(query) + end + + @tag :aggregate_filters + test "aggregate filter types" do + datetime = ~N[2014-01-16 20:26:51] + TestRepo.insert!(%Post{inserted_at: datetime}) + query = from p in Post, select: filter(max(p.inserted_at), p.public == ^true) + assert [^datetime] = TestRepo.all(query) + end + + test "coalesce text type when default" do + TestRepo.insert!(%Post{blob: nil}) + blob = <<0, 1>> + query = from p in Post, select: coalesce(p.blob, ^blob) + assert [^blob] = TestRepo.all(query) + end + + test "coalesce text type when value" do + blob = <<0, 2>> + default_blob = <<0, 1>> + TestRepo.insert!(%Post{blob: blob}) + query = from p in Post, select: coalesce(p.blob, ^default_blob) + assert [^blob] = TestRepo.all(query) + end + + test "tagged types" do + %{id: post_id} = TestRepo.insert!(%Post{visits: 12}) + TestRepo.insert!(%Comment{text: "#{post_id}", post_id: post_id}) + + # Numbers + assert [1] = TestRepo.all(from Post, select: type(^"1", :integer)) + assert [1.0] = TestRepo.all(from Post, select: type(^1.0, :float)) + assert [1] = TestRepo.all(from p in Post, select: type(^"1", p.visits)) + assert [1.0] = TestRepo.all(from p in Post, select: type(^"1", p.intensity)) + + # Custom wrappers + assert [1] = TestRepo.all(from Post, select: type(^"1", CustomPermalink)) + + # Custom types + uuid = Ecto.UUID.generate() + assert [^uuid] = TestRepo.all(from Post, select: type(^uuid, Ecto.UUID)) + + # Parameterized types + assert [:a] = TestRepo.all(from Post, select: type(^"a", ^@parameterized_type)) + + # Math operations + assert [4] = TestRepo.all(from Post, select: type(2 + ^"2", :integer)) + assert [4.0] = TestRepo.all(from Post, select: type(2.0 + ^"2", :float)) + assert [4] = TestRepo.all(from p in Post, select: type(2 + ^"2", p.visits)) + assert [4.0] = TestRepo.all(from p in Post, select: type(2.0 + ^"2", p.intensity)) + + # Comparison expression + assert [12] = TestRepo.all(from p in Post, select: type(coalesce(p.visits, 0), :integer)) + assert [1.0] = TestRepo.all(from p in Post, select: type(coalesce(p.intensity, 1.0), :float)) + + # parent_as/1 + child = from c in Comment, where: type(parent_as(:posts).id, :string) == c.text, select: c.post_id + query = from p in Post, as: :posts, where: p.id in subquery(child), select: p.id + assert [post_id] == TestRepo.all(query) + end + + test "binary id type" do + assert %Custom{} = custom = TestRepo.insert!(%Custom{}) + bid = custom.bid + assert [^bid] = TestRepo.all(from c in Custom, select: c.bid) + assert [^bid] = TestRepo.all(from c in Custom, select: type(^bid, :binary_id)) + end + + @tag :like_match_blob + test "text type as blob" do + assert %Post{} = post = TestRepo.insert!(%Post{blob: <<0, 1, 2>>}) + id = post.id + assert post.blob == <<0, 1, 2>> + assert [^id] = TestRepo.all(from p in Post, where: like(p.blob, ^<<0, 1, 2>>), select: p.id) + end + + @tag :like_match_blob + @tag :text_type_as_string + test "text type as string" do + assert %Post{} = post = TestRepo.insert!(%Post{blob: "hello"}) + id = post.id + assert post.blob == "hello" + assert [^id] = TestRepo.all(from p in Post, where: like(p.blob, ^"hello"), select: p.id) + end + + @tag :array_type + test "array type" do + ints = [1, 2, 3] + tag = TestRepo.insert!(%Tag{ints: ints}) + + assert TestRepo.all(from t in Tag, where: t.ints == ^[], select: t.ints) == [] + assert TestRepo.all(from t in Tag, where: t.ints == ^[1, 2, 3], select: t.ints) == [ints] + + # Both sides interpolation + assert TestRepo.all(from t in Tag, where: ^"b" in ^["a", "b", "c"], select: t.ints) == [ints] + assert TestRepo.all(from t in Tag, where: ^"b" in [^"a", ^"b", ^"c"], select: t.ints) == [ints] + + # Querying + assert TestRepo.all(from t in Tag, where: t.ints == [1, 2, 3], select: t.ints) == [ints] + assert TestRepo.all(from t in Tag, where: 0 in t.ints, select: t.ints) == [] + assert TestRepo.all(from t in Tag, where: 1 in t.ints, select: t.ints) == [ints] + + # Update + tag = TestRepo.update!(Ecto.Changeset.change tag, ints: nil) + assert TestRepo.get!(Tag, tag.id).ints == nil + + tag = TestRepo.update!(Ecto.Changeset.change tag, ints: [3, 2, 1]) + assert TestRepo.get!(Tag, tag.id).ints == [3, 2, 1] + + # Update all + {1, _} = TestRepo.update_all(Tag, push: [ints: 0]) + assert TestRepo.get!(Tag, tag.id).ints == [3, 2, 1, 0] + + {1, _} = TestRepo.update_all(Tag, pull: [ints: 2]) + assert TestRepo.get!(Tag, tag.id).ints == [3, 1, 0] + + {1, _} = TestRepo.update_all(Tag, set: [ints: nil]) + assert TestRepo.get!(Tag, tag.id).ints == nil + end + + @tag :array_type + test "array type with custom types" do + uuids = ["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"] + TestRepo.insert!(%Tag{uuids: ["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"]}) + + assert TestRepo.all(from t in Tag, where: t.uuids == ^[], select: t.uuids) == [] + assert TestRepo.all(from t in Tag, where: t.uuids == ^["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"], + select: t.uuids) == [uuids] + + {1, _} = TestRepo.update_all(Tag, set: [uuids: nil]) + assert TestRepo.all(from t in Tag, select: t.uuids) == [nil] + end + + @tag :array_type + test "array type with nil in array" do + tag = TestRepo.insert!(%Tag{ints: [1, nil, 3]}) + assert tag.ints == [1, nil, 3] + end + + @tag :map_type + test "untyped map" do + post1 = TestRepo.insert!(%Post{meta: %{"foo" => "bar", "baz" => "bat"}}) + post2 = TestRepo.insert!(%Post{meta: %{foo: "bar", baz: "bat"}}) + + assert TestRepo.all(from p in Post, where: p.id == ^post1.id, select: p.meta) == + [%{"foo" => "bar", "baz" => "bat"}] + assert TestRepo.all(from p in Post, where: p.id == ^post2.id, select: p.meta) == + [%{"foo" => "bar", "baz" => "bat"}] + end + + @tag :map_type + test "typed string map" do + post1 = TestRepo.insert!(%Post{links: %{"foo" => "http://foo.com", "bar" => "http://bar.com"}}) + post2 = TestRepo.insert!(%Post{links: %{foo: "http://foo.com", bar: "http://bar.com"}}) + + assert TestRepo.all(from p in Post, where: p.id == ^post1.id, select: p.links) == + [%{"foo" => "http://foo.com", "bar" => "http://bar.com"}] + assert TestRepo.all(from p in Post, where: p.id == ^post2.id, select: p.links) == + [%{"foo" => "http://foo.com", "bar" => "http://bar.com"}] + end + + @tag :map_type + test "typed float map" do + post = TestRepo.insert!(%Post{intensities: %{"foo" => 1.0, "bar" => 416500.0}}) + + # Note we are using === since we want to check integer vs float + assert TestRepo.all(from p in Post, where: p.id == ^post.id, select: p.intensities) === + [%{"foo" => 1.0, "bar" => 416500.0}] + end + + @tag :map_type + test "map type on update" do + post = TestRepo.insert!(%Post{meta: %{"world" => "hello"}}) + assert TestRepo.get!(Post, post.id).meta == %{"world" => "hello"} + + post = TestRepo.update!(Ecto.Changeset.change post, meta: %{hello: "world"}) + assert TestRepo.get!(Post, post.id).meta == %{"hello" => "world"} + + query = from(p in Post, where: p.id == ^post.id) + TestRepo.update_all(query, set: [meta: %{world: "hello"}]) + assert TestRepo.get!(Post, post.id).meta == %{"world" => "hello"} + end + + @tag :map_type + test "embeds one" do + item = %Item{price: 123, valid_at: ~D[2014-01-16]} + + order = + %Order{} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_embed(:item, item) + |> TestRepo.insert!() + + dbitem = TestRepo.get!(Order, order.id).item + assert item.reference == dbitem.reference + assert item.price == dbitem.price + assert item.valid_at == dbitem.valid_at + assert dbitem.id + + [dbitem] = TestRepo.all(from o in Order, select: o.item) + assert item.reference == dbitem.reference + assert item.price == dbitem.price + assert item.valid_at == dbitem.valid_at + assert dbitem.id + + {1, _} = TestRepo.update_all(Order, set: [item: %{dbitem | price: 456}]) + assert TestRepo.get!(Order, order.id).item.price == 456 + end + + @tag :map_type + @tag :json_extract_path + test "json_extract_path with primitive values" do + order = %Order{metadata: + %{ + :id => 123, + :time => ~T[09:00:00], + "code" => "good", + "'single quoted'" => "bar", + "\"double quoted\"" => "baz", + "enabled" => true, + "extra" => [%{"enabled" => false}] + } + } + + order = TestRepo.insert!(order) + + assert TestRepo.one(from o in Order, select: json_extract_path(o.metadata, ^["id"])) == 123 + assert TestRepo.one(from o in Order, select: o.metadata["bad"]) == nil + assert TestRepo.one(from o in Order, select: o.metadata["bad"]["bad"]) == nil + + field = "id" + assert TestRepo.one(from o in Order, select: o.metadata[^field]) == 123 + assert TestRepo.one(from o in Order, select: o.metadata["time"]) == "09:00:00" + assert TestRepo.one(from o in Order, select: o.metadata["'single quoted'"]) == "bar" + assert TestRepo.one(from o in Order, select: o.metadata["';"]) == nil + assert TestRepo.one(from o in Order, select: o.metadata["\"double quoted\""]) == "baz" + assert TestRepo.one(from o in Order, select: o.metadata["enabled"]) == true + assert TestRepo.one(from o in Order, select: o.metadata["extra"][0]["enabled"]) == false + + # where + assert TestRepo.one(from o in Order, where: o.metadata["id"] == 123, select: o.id) == order.id + assert TestRepo.one(from o in Order, where: o.metadata["id"] == 456, select: o.id) == nil + assert TestRepo.one(from o in Order, where: o.metadata["code"] == "good", select: o.id) == order.id + assert TestRepo.one(from o in Order, where: o.metadata["code"] == "bad", select: o.id) == nil + assert TestRepo.one(from o in Order, where: o.metadata["enabled"] == true, select: o.id) == order.id + assert TestRepo.one(from o in Order, where: o.metadata["extra"][0]["enabled"] == false, select: o.id) == order.id + end + + @tag :map_type + @tag :json_extract_path + test "json_extract_path with arrays and objects" do + order = %Order{metadata: %{tags: [%{name: "red"}, %{name: "green"}]}} + order = TestRepo.insert!(order) + + assert TestRepo.one(from o in Order, select: o.metadata["tags"][0]["name"]) == "red" + assert TestRepo.one(from o in Order, select: o.metadata["tags"][99]["name"]) == nil + + index = 1 + assert TestRepo.one(from o in Order, select: o.metadata["tags"][^index]["name"]) == "green" + + # where + assert TestRepo.one(from o in Order, where: o.metadata["tags"][0]["name"] == "red", select: o.id) == order.id + assert TestRepo.one(from o in Order, where: o.metadata["tags"][0]["name"] == "blue", select: o.id) == nil + assert TestRepo.one(from o in Order, where: o.metadata["tags"][99]["name"] == "red", select: o.id) == nil + end + + @tag :map_type + @tag :json_extract_path + test "json_extract_path with embeds" do + order = %Order{items: [%{valid_at: ~D[2020-01-01]}]} + TestRepo.insert!(order) + + assert TestRepo.one(from o in Order, select: o.items[0]["valid_at"]) == "2020-01-01" + end + + @tag :map_type + @tag :json_extract_path + test "json_extract_path with custom field source" do + order = TestRepo.insert!(%Order{metadata: %{tags: [%{name: "red"}, %{name: "green"}]}}) + + assert TestRepo.one(from o in Order, where: o.metadata["tags"][0]["name"] == "red", select: o.id) == order.id + end + + @tag :map_type + @tag :map_type_schemaless + test "embeds one with custom type" do + item = %Item{price: 123, reference: "PREFIX-EXAMPLE"} + + order = + %Order{} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_embed(:item, item) + |> TestRepo.insert!() + + dbitem = TestRepo.get!(Order, order.id).item + assert dbitem.reference == "PREFIX-EXAMPLE" + assert [%{"reference" => "EXAMPLE"}] = TestRepo.all(from o in "orders", select: o.item) + end + + @tag :map_type + test "empty embeds one" do + order = TestRepo.insert!(%Order{}) + assert order.item == nil + assert TestRepo.get!(Order, order.id).item == nil + end + + @tag :map_type + @tag :array_type + test "embeds many" do + item = %Item{price: 123, valid_at: ~D[2014-01-16]} + tag = + %Tag{} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_embed(:items, [item]) + tag = TestRepo.insert!(tag) + + [dbitem] = TestRepo.get!(Tag, tag.id).items + assert item.price == dbitem.price + assert item.valid_at == dbitem.valid_at + assert dbitem.id + + [[dbitem]] = TestRepo.all(from t in Tag, select: t.items) + assert item.price == dbitem.price + assert item.valid_at == dbitem.valid_at + assert dbitem.id + + {1, _} = TestRepo.update_all(Tag, set: [items: [%{dbitem | price: 456}]]) + assert (TestRepo.get!(Tag, tag.id).items |> hd).price == 456 + end + + @tag :map_type + @tag :array_type + test "empty embeds many" do + tag = TestRepo.insert!(%Tag{}) + assert tag.items == [] + assert TestRepo.get!(Tag, tag.id).items == [] + end + + @tag :map_type + @tag :array_type + test "nested embeds" do + red = %ItemColor{name: "red"} + blue = %ItemColor{name: "blue"} + item = %Item{ + primary_color: red, + secondary_colors: [blue] + } + + order = + %Order{} + |> Ecto.Changeset.change + |> Ecto.Changeset.put_embed(:item, item) + order = TestRepo.insert!(order) + + dbitem = TestRepo.get!(Order, order.id).item + assert dbitem.primary_color.name == "red" + assert Enum.map(dbitem.secondary_colors, & &1.name) == ["blue"] + assert dbitem.id + assert dbitem.primary_color.id + + [dbitem] = TestRepo.all(from o in Order, select: o.item) + assert dbitem.primary_color.name == "red" + assert Enum.map(dbitem.secondary_colors, & &1.name) == ["blue"] + assert dbitem.id + assert dbitem.primary_color.id + end + + @tag :decimal_type + test "decimal type" do + decimal = Decimal.new("1.0") + TestRepo.insert!(%Post{cost: decimal}) + + [cost] = TestRepo.all(from p in Post, where: p.cost == ^decimal, select: p.cost) + assert Decimal.equal?(decimal, cost) + [cost] = TestRepo.all(from p in Post, where: p.cost == ^1.0, select: p.cost) + assert Decimal.equal?(decimal, cost) + [cost] = TestRepo.all(from p in Post, where: p.cost == ^1, select: p.cost) + assert Decimal.equal?(decimal, cost) + [cost] = TestRepo.all(from p in Post, where: p.cost == 1.0, select: p.cost) + assert Decimal.equal?(decimal, cost) + [cost] = TestRepo.all(from p in Post, where: p.cost == 1, select: p.cost) + assert Decimal.equal?(decimal, cost) + [cost] = TestRepo.all(from p in Post, select: p.cost * 2) + assert Decimal.equal?(Decimal.new("2.0"), cost) + [cost] = TestRepo.all(from p in Post, select: p.cost - p.cost) + assert Decimal.equal?(Decimal.new("0.0"), cost) + end + + @tag :decimal_type + @tag :decimal_precision + test "decimal typed aggregations" do + decimal = Decimal.new("1.0") + TestRepo.insert!(%Post{cost: decimal}) + + assert [1] = TestRepo.all(from p in Post, select: type(sum(p.cost), :integer)) + assert [1.0] = TestRepo.all(from p in Post, select: type(sum(p.cost), :float)) + [cost] = TestRepo.all(from p in Post, select: type(sum(p.cost), :decimal)) + assert Decimal.equal?(decimal, cost) + end + + @tag :decimal_type + test "on coalesce with mixed types" do + decimal = Decimal.new("1.0") + TestRepo.insert!(%Post{cost: decimal}) + [cost] = TestRepo.all(from p in Post, select: coalesce(p.cost, 0)) + assert Decimal.equal?(decimal, cost) + end + + @tag :union_with_literals + test "unions with literals" do + TestRepo.insert!(%Post{}) + TestRepo.insert!(%Post{}) + + query1 = from(p in Post, select: %{n: 1}) + query2 = from(p in Post, select: %{n: 2}) + + assert TestRepo.all(union_all(query1, ^query2)) == + [%{n: 1}, %{n: 1}, %{n: 2}, %{n: 2}] + + query1 = from(p in Post, select: %{n: 1.0}) + query2 = from(p in Post, select: %{n: 2.0}) + + assert TestRepo.all(union_all(query1, ^query2)) == + [%{n: 1.0}, %{n: 1.0}, %{n: 2.0}, %{n: 2.0}] + + query1 = from(p in Post, select: %{n: "foo"}) + query2 = from(p in Post, select: %{n: "bar"}) + + assert TestRepo.all(union_all(query1, ^query2)) == + [%{n: "foo"}, %{n: "foo"}, %{n: "bar"}, %{n: "bar"}] + end + + test "schemaless types" do + TestRepo.insert!(%Post{visits: 123}) + assert [123] = TestRepo.all(from p in "posts", select: type(p.visits, :integer)) + end + + test "schemaless calendar types" do + datetime = ~N[2014-01-16 20:26:51] + assert {1, _} = + TestRepo.insert_all("posts", [[inserted_at: datetime]]) + assert {1, _} = + TestRepo.update_all("posts", set: [inserted_at: datetime]) + assert [_] = + TestRepo.all(from p in "posts", where: p.inserted_at >= ^datetime, select: p.inserted_at) + assert [_] = + TestRepo.all(from p in "posts", where: p.inserted_at in [^datetime], select: p.inserted_at) + assert [_] = + TestRepo.all(from p in "posts", where: p.inserted_at in ^[datetime], select: p.inserted_at) + end +end diff --git a/deps/ecto/integration_test/cases/windows.exs b/deps/ecto/integration_test/cases/windows.exs new file mode 100644 index 0000000000000000000000000000000000000000..a52eda296af1aa7c17e38d146eb76f69c74c7697 --- /dev/null +++ b/deps/ecto/integration_test/cases/windows.exs @@ -0,0 +1,53 @@ +defmodule Ecto.Integration.WindowsTest do + use Ecto.Integration.Case, async: Application.compile_env(:ecto, :async_integration_tests, true) + + alias Ecto.Integration.TestRepo + import Ecto.Query + + alias Ecto.Integration.{Comment, User, Post} + + test "over" do + u1 = TestRepo.insert!(%User{name: "Tester"}) + u2 = TestRepo.insert!(%User{name: "Developer"}) + c1 = TestRepo.insert!(%Comment{text: "1", author_id: u1.id}) + c2 = TestRepo.insert!(%Comment{text: "2", author_id: u1.id}) + c3 = TestRepo.insert!(%Comment{text: "3", author_id: u1.id}) + c4 = TestRepo.insert!(%Comment{text: "4", author_id: u2.id}) + + # Over nothing + query = from(c in Comment, select: [c, count(c.id) |> over()]) + assert [[^c1, 4], [^c2, 4], [^c3, 4], [^c4, 4]] = TestRepo.all(query) + + # Over partition + query = from(c in Comment, select: [c, count(c.id) |> over(partition_by: c.author_id)]) + assert [[^c1, 3], [^c2, 3], [^c3, 3], [^c4, 1]] = TestRepo.all(query) + + # Over window + query = from(c in Comment, windows: [w: [partition_by: c.author_id]], select: [c, count(c.id) |> over(:w)]) + assert [[^c1, 3], [^c2, 3], [^c3, 3], [^c4, 1]] = TestRepo.all(query) + end + + test "frame" do + posts = Enum.map(0..6, &%{counter: &1, visits: round(:math.pow(2, &1))}) + TestRepo.insert_all(Post, posts) + + n = 1 + query = from(p in Post, + windows: [w: [order_by: p.counter, frame: fragment("ROWS BETWEEN ? PRECEDING AND ? FOLLOWING", ^n, ^n)]], + select: [p.counter, sum(p.visits) |> over(:w)] + ) + assert [[0, 3], [1, 7], [2, 14], [3, 28], [4, 56], [5, 112], [6, 96]] = TestRepo.all(query) + + query = from(p in Post, + windows: [w: [order_by: p.counter, frame: fragment("ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING")]], + select: [p.counter, sum(p.visits) |> over(:w)] + ) + assert [[0, 126], [1, 124], [2, 120], [3, 112], [4, 96], [5, 64], [6, nil]] = TestRepo.all(query) + + query = from(p in Post, + windows: [w: [order_by: p.counter, frame: fragment("ROWS CURRENT ROW")]], + select: [p.counter, sum(p.visits) |> over(:w)] + ) + assert [[0, 1], [1, 2], [2, 4], [3, 8], [4, 16], [5, 32], [6, 64]] = TestRepo.all(query) + end +end diff --git a/deps/ecto/integration_test/support/schemas.exs b/deps/ecto/integration_test/support/schemas.exs new file mode 100644 index 0000000000000000000000000000000000000000..5dbb78f707a886be8cd5fbf0faa05fa5acaf7359 --- /dev/null +++ b/deps/ecto/integration_test/support/schemas.exs @@ -0,0 +1,423 @@ +Code.require_file("types.exs", __DIR__) + +defmodule Ecto.Integration.Schema do + defmacro __using__(_) do + quote do + use Ecto.Schema + + type = + Application.compile_env(:ecto, :primary_key_type) || + raise ":primary_key_type not set in :ecto application" + + @primary_key {:id, type, autogenerate: true} + @foreign_key_type type + end + end +end + +defmodule Ecto.Integration.Post do + @moduledoc """ + This module is used to test: + + * Overall functionality + * Overall types + * Non-null timestamps + * Relationships + * Dependent callbacks + + """ + use Ecto.Integration.Schema + import Ecto.Changeset + import Ecto.Query, only: [dynamic: 2] + + schema "posts" do + field :counter, :id # Same as integer + field :title, :string + field :blob, :binary + field :temp, :string, default: "temp", virtual: true + field :public, :boolean, default: true + field :cost, :decimal + field :visits, :integer + field :wrapped_visits, WrappedInteger + field :intensity, :float + field :bid, :binary_id + field :uuid, Ecto.Integration.TestRepo.uuid(), autogenerate: true + field :meta, :map + field :links, {:map, :string} + field :intensities, {:map, :float} + field :posted, :date + has_many :comments, Ecto.Integration.Comment, on_delete: :delete_all, on_replace: :delete + has_many :force_comments, Ecto.Integration.Comment, on_replace: :delete_if_exists + has_many :ordered_comments, Ecto.Integration.Comment, preload_order: [:text] + # The post<->permalink relationship should be marked as uniq + has_one :permalink, Ecto.Integration.Permalink, on_delete: :delete_all, on_replace: :delete + has_one :force_permalink, Ecto.Integration.Permalink, on_replace: :delete_if_exists + has_one :update_permalink, Ecto.Integration.Permalink, foreign_key: :post_id, on_delete: :delete_all, on_replace: :update + has_many :comments_authors, through: [:comments, :author] + belongs_to :author, Ecto.Integration.User + many_to_many :users, Ecto.Integration.User, + join_through: "posts_users", on_delete: :delete_all, on_replace: :delete + many_to_many :ordered_users, Ecto.Integration.User, join_through: "posts_users", preload_order: [desc: :name] + many_to_many :ordered_users_by_join_table, Ecto.Integration.User, + join_through: "posts_users", preload_order: {__MODULE__, :preload_order, []} + many_to_many :unique_users, Ecto.Integration.User, + join_through: "posts_users", unique: true + many_to_many :constraint_users, Ecto.Integration.User, + join_through: Ecto.Integration.PostUserCompositePk + has_many :users_comments, through: [:users, :comments] + has_many :comments_authors_permalinks, through: [:comments_authors, :permalink] + has_one :post_user_composite_pk, Ecto.Integration.PostUserCompositePk + timestamps() + end + + def preload_order() do + [desc: dynamic([assoc, join], join.user_id)] + end + + def changeset(schema, params) do + cast(schema, params, ~w(counter title blob temp public cost visits + intensity bid uuid meta posted)a) + end +end + +defmodule Ecto.Integration.Comment do + @moduledoc """ + This module is used to test: + + * Optimistic lock + * Relationships + * Dependent callbacks + + """ + use Ecto.Integration.Schema + + schema "comments" do + field :text, :string + field :lock_version, :integer, default: 1 + belongs_to :post, Ecto.Integration.Post + belongs_to :author, Ecto.Integration.User + has_one :post_permalink, through: [:post, :permalink] + has_one :author_permalink, through: [:author, :permalink] + end + + def changeset(schema, params) do + Ecto.Changeset.cast(schema, params, [:text]) + end +end + +defmodule Ecto.Integration.Permalink do + @moduledoc """ + This module is used to test: + + * Field sources + * Relationships + * Dependent callbacks + + """ + use Ecto.Integration.Schema + + schema "permalinks" do + field :url, :string, source: :uniform_resource_locator + field :title, :string + field :posted, :date, virtual: true + belongs_to :post, Ecto.Integration.Post, on_replace: :nilify + belongs_to :update_post, Ecto.Integration.Post, on_replace: :update, foreign_key: :post_id, define_field: false + belongs_to :user, Ecto.Integration.User + has_many :post_comments_authors, through: [:post, :comments_authors] + has_many :user_posts, through: [:user, :posts] + end + + def changeset(schema, params) do + Ecto.Changeset.cast(schema, params, [:url, :title]) + end +end + +defmodule Ecto.Integration.PostUser do + @moduledoc """ + This module is used to test: + + * Many to many associations join_through with schema + + """ + use Ecto.Integration.Schema + + schema "posts_users_pk" do + belongs_to :user, Ecto.Integration.User + belongs_to :post, Ecto.Integration.Post + timestamps() + end +end + +defmodule Ecto.Integration.User do + @moduledoc """ + This module is used to test: + + * UTC Timestamps + * Relationships + * Dependent callbacks + + """ + use Ecto.Integration.Schema + + schema "users" do + field :name, :string + has_many :comments, Ecto.Integration.Comment, foreign_key: :author_id, on_delete: :nilify_all, on_replace: :nilify + has_one :permalink, Ecto.Integration.Permalink, on_replace: :nilify + has_many :posts, Ecto.Integration.Post, foreign_key: :author_id, on_delete: :nothing, on_replace: :delete + belongs_to :custom, Ecto.Integration.Custom, references: :bid, type: :binary_id + many_to_many :schema_posts, Ecto.Integration.Post, join_through: Ecto.Integration.PostUser + many_to_many :unique_posts, Ecto.Integration.Post, join_through: Ecto.Integration.PostUserCompositePk + + has_many :related_2nd_order_posts, through: [:posts, :users, :posts] + has_many :users_through_schema_posts, through: [:schema_posts, :users] + + has_many :v2_comments, Ecto.Integration.Comment, foreign_key: :author_id, where: [lock_version: 2] + has_many :v2_comments_posts, through: [:v2_comments, :post] + has_many :co_commenters, through: [:comments, :post, :comments_authors] + + timestamps(type: :utc_datetime) + end +end + +defmodule Ecto.Integration.Custom do + @moduledoc """ + This module is used to test: + + * binary_id primary key + * Tying another schemas to an existing schema + + Due to the second item, it must be a subset of posts. + """ + use Ecto.Integration.Schema + + @primary_key {:bid, :binary_id, autogenerate: true} + schema "customs" do + field :uuid, Ecto.Integration.TestRepo.uuid() + many_to_many :customs, Ecto.Integration.Custom, + join_through: "customs_customs", join_keys: [custom_id1: :bid, custom_id2: :bid], + on_delete: :delete_all, on_replace: :delete + end +end + +defmodule Ecto.Integration.Barebone do + @moduledoc """ + This module is used to test: + + * A schema without primary keys + + """ + use Ecto.Integration.Schema + + @primary_key false + schema "barebones" do + field :num, :integer + end +end + +defmodule Ecto.Integration.Tag do + @moduledoc """ + This module is used to test: + + * The array type + * Embedding many schemas (uses array) + + """ + use Ecto.Integration.Schema + + schema "tags" do + field :ints, {:array, :integer} + field :uuids, {:array, Ecto.Integration.TestRepo.uuid()} + embeds_many :items, Ecto.Integration.Item + end +end + +defmodule Ecto.Integration.Item do + @moduledoc """ + This module is used to test: + + * Embedding + * Preloading associations in embedded schemas + + """ + use Ecto.Schema + + embedded_schema do + field :reference, PrefixedString + field :price, :integer + field :valid_at, :date + + embeds_one :primary_color, Ecto.Integration.ItemColor + embeds_many :secondary_colors, Ecto.Integration.ItemColor + + belongs_to :user, Ecto.Integration.User + end +end + +defmodule Ecto.Integration.ItemColor do + @moduledoc """ + This module is used to test: + + * Nested embeds + + """ + use Ecto.Schema + + embedded_schema do + field :name, :string + end +end + +defmodule Ecto.Integration.Order do + @moduledoc """ + This module is used to test: + + * Text columns + * Embedding one schema + * Preloading items inside embeds_many + * Preloading items inside embeds_one + * Field source with json_extract_path + + """ + use Ecto.Integration.Schema + + schema "orders" do + field :metadata, :map, source: :meta + embeds_one :item, Ecto.Integration.Item + embeds_many :items, Ecto.Integration.Item + belongs_to :permalink, Ecto.Integration.Permalink + end +end + +defmodule Ecto.Integration.CompositePk do + @moduledoc """ + This module is used to test: + + * Composite primary keys + + """ + use Ecto.Integration.Schema + import Ecto.Changeset + + @primary_key false + schema "composite_pk" do + field :a, :integer, primary_key: true + field :b, :integer, primary_key: true + field :name, :string + end + def changeset(schema, params) do + cast(schema, params, ~w(a b name)a) + end +end + +defmodule Ecto.Integration.CorruptedPk do + @moduledoc """ + This module is used to test: + + * Primary keys that is not unique on a DB side + + """ + use Ecto.Integration.Schema + + @primary_key false + schema "corrupted_pk" do + field :a, :string, primary_key: true + end +end + +defmodule Ecto.Integration.PostUserCompositePk do + @moduledoc """ + This module is used to test: + + * Composite primary keys for 2 belongs_to fields + + """ + use Ecto.Integration.Schema + + @primary_key false + schema "posts_users_composite_pk" do + belongs_to :user, Ecto.Integration.User, primary_key: true + belongs_to :post, Ecto.Integration.Post, primary_key: true + timestamps() + end +end + +defmodule Ecto.Integration.Usec do + @moduledoc """ + This module is used to test: + + * usec datetime types + + """ + use Ecto.Integration.Schema + + schema "usecs" do + field :naive_datetime_usec, :naive_datetime_usec + field :utc_datetime_usec, :utc_datetime_usec + end +end + +defmodule Ecto.Integration.Logging do + @moduledoc """ + This module is used to test: + + * Logging the casted version of parameters without array types + + """ + use Ecto.Integration.Schema + + @primary_key {:bid, :binary_id, autogenerate: true} + schema "loggings" do + field :int, :integer + field :uuid, Ecto.Integration.TestRepo.uuid() + timestamps() + end +end + +defmodule Ecto.Integration.ArrayLogging do + @moduledoc """ + This module is used to test: + + * Logging the casted version of parameters with array types + + """ + use Ecto.Integration.Schema + + schema "array_loggings" do + field :uuids, {:array, Ecto.Integration.TestRepo.uuid()} + timestamps() + end +end + +defmodule Ecto.Integration.Bitstring do + @moduledoc """ + This module is used to test: + + * Bitstring type + + """ + use Ecto.Integration.Schema + + schema "bitstrings" do + field :bs, :bitstring + field :bs_with_default, :bitstring + field :bs_with_size, :bitstring + end +end + +if Code.ensure_loaded?(Duration) do + defmodule Ecto.Integration.Duration do + @moduledoc """ + This module is used to test: + * Duration type + """ + use Ecto.Integration.Schema + + schema "durations" do + field :dur, :duration + field :dur_with_fields, :duration + field :dur_with_precision, :duration + field :dur_with_fields_and_precision, :duration + field :dur_with_default, :duration + end + end +end diff --git a/deps/ecto/integration_test/support/types.exs b/deps/ecto/integration_test/support/types.exs new file mode 100644 index 0000000000000000000000000000000000000000..196012f891fbaa34248ed2dfbc3da6e9a90b44f8 --- /dev/null +++ b/deps/ecto/integration_test/support/types.exs @@ -0,0 +1,53 @@ +defmodule CustomPermalink do + def type, do: :id + + def cast(string) when is_binary(string) do + case Integer.parse(string) do + {int, _} -> {:ok, int} + :error -> :error + end + end + + def cast(integer) when is_integer(integer), do: {:ok, integer} + def cast(_), do: :error + + def load(integer) when is_integer(integer), do: {:ok, integer} + def dump(integer) when is_integer(integer), do: {:ok, integer} +end + +defmodule PrefixedString do + use Ecto.Type + def type(), do: :string + def cast(string), do: {:ok, string} + def load(string), do: {:ok, "PREFIX-" <> string} + def dump("PREFIX-" <> string), do: {:ok, string} + def dump(_string), do: :error + def embed_as(_), do: :dump +end + +defmodule WrappedInteger do + use Ecto.Type + def type(), do: :integer + def cast(integer), do: {:ok, {:int, integer}} + def load(integer), do: {:ok, {:int, integer}} + def dump({:int, integer}), do: {:ok, integer} +end + +defmodule ParameterizedPrefixedString do + use Ecto.ParameterizedType + def init(opts), do: Enum.into(opts, %{}) + def type(_), do: :string + + def cast(data, %{prefix: prefix}) do + if String.starts_with?(data, [prefix <> "-"]) do + {:ok, data} + else + {:ok, prefix <> "-" <> data} + end + end + + def load(string, _, %{prefix: prefix}), do: {:ok, prefix <> "-" <> string} + def dump(nil, _, _), do: {:ok, nil} + def dump(data, _, %{prefix: _prefix}), do: {:ok, data |> String.split("-") |> List.last()} + def embed_as(_, _), do: :dump +end diff --git a/deps/ecto/lib/ecto.ex b/deps/ecto/lib/ecto.ex new file mode 100644 index 0000000000000000000000000000000000000000..87e046f37a7f654eb5e34cac33700181f3ed193c --- /dev/null +++ b/deps/ecto/lib/ecto.ex @@ -0,0 +1,747 @@ +defmodule Ecto do + @moduledoc ~S""" + Ecto is split into 4 main components: + + * `Ecto.Repo` - repositories are wrappers around the data store. + Via the repository, we can create, update, destroy and query + existing entries. A repository needs an adapter and credentials + to communicate to the database + + * `Ecto.Schema` - schemas are used to map external data into Elixir + structs. We often use them to map database tables to Elixir data but + they have many other use cases + + * `Ecto.Query` - written in Elixir syntax, queries are used to retrieve + information from a given repository. Ecto queries are secure and composable + + * `Ecto.Changeset` - changesets provide a way to track and validate changes + before they are applied to the data + + In summary: + + * `Ecto.Repo` - **where** the data is + * `Ecto.Schema` - **what** the data is + * `Ecto.Query` - **how to read** the data + * `Ecto.Changeset` - **how to change** the data + + Besides the four components above, most developers use Ecto to interact + with SQL databases, such as PostgreSQL and MySQL via the + [`ecto_sql`](https://hexdocs.pm/ecto_sql) project. `ecto_sql` provides many + conveniences for working with SQL databases as well as the ability to version + how your database changes through time via + [database migrations](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.html#module-migrations). + + If you want to quickly check a sample application using Ecto, please check + the [getting started guide](https://hexdocs.pm/ecto/getting-started.html) and + the accompanying sample application. [Ecto's README](https://github.com/elixir-ecto/ecto) + also links to other resources. + + In the following sections, we will provide an overview of those components and + how they interact with each other. Feel free to access their respective module + documentation for more specific examples, options and configuration. + + ## Repositories + + `Ecto.Repo` is a wrapper around the database. We can define a + repository as follows: + + defmodule Repo do + use Ecto.Repo, + otp_app: :my_app, + adapter: Ecto.Adapters.Postgres + end + + Where the configuration for the Repo must be in your application + environment, usually defined in your `config/config.exs`: + + config :my_app, Repo, + database: "ecto_simple", + username: "postgres", + password: "postgres", + hostname: "localhost", + # OR use a URL to connect instead + url: "postgres://postgres:postgres@localhost/ecto_simple" + + Each repository in Ecto defines a `start_link/0` function that needs to be invoked + before using the repository. In general, this function is not called directly, + but is used as part of your application supervision tree. + + If your application was generated with a supervisor (by passing `--sup` to `mix new`) + you will have a `lib/my_app/application.ex` file containing the application start + callback that defines and starts your supervisor. You just need to edit the `start/2` + function to start the repo as a supervisor on your application's supervisor: + + def start(_type, _args) do + children = [ + MyApp.Repo, + ] + + opts = [strategy: :one_for_one, name: MyApp.Supervisor] + Supervisor.start_link(children, opts) + end + + ## Schema + + Schemas allow developers to define the shape of their data. + Let's see an example: + + defmodule Weather do + use Ecto.Schema + + # weather is the DB table + schema "weather" do + field :city, :string + field :temp_lo, :integer + field :temp_hi, :integer + field :prcp, :float, default: 0.0 + end + end + + By defining a schema, Ecto automatically defines a struct with + the schema fields: + + iex> weather = %Weather{temp_lo: 30} + iex> weather.temp_lo + 30 + + The schema also allows us to interact with a repository: + + iex> weather = %Weather{temp_lo: 0, temp_hi: 23} + iex> Repo.insert!(weather) + %Weather{...} + + After persisting `weather` to the database, it will return a new copy of + `%Weather{}` with the primary key (the `id`) set. We can use this value + to read a struct back from the repository: + + # Get the struct back + iex> weather = Repo.get Weather, 1 + %Weather{id: 1, ...} + + # Delete it + iex> Repo.delete!(weather) + %Weather{...} + + > NOTE: by using `Ecto.Schema`, an `:id` field with type `:id` (:id means :integer) is + > generated by default, which is the primary key of the schema. If you want + > to use a different primary key, you can declare custom `@primary_key` + > before the `schema/2` call. Consult the `Ecto.Schema` documentation + > for more information. + + Notice how the storage (repository) and the data are decoupled. This provides + two main benefits: + + * By having structs as data, we guarantee they are light-weight, + serializable structures. In many languages, the data is often represented + by large, complex objects, with entwined state transactions, which makes + serialization, maintenance and understanding hard; + + * You do not need to define schemas in order to interact with repositories, + operations like `all`, `insert_all` and so on allow developers to directly + access and modify the data, keeping the database at your fingertips when + necessary; + + ## Changesets + + Although in the example above we have directly inserted and deleted the + struct in the repository, operations on top of schemas are done through + changesets so Ecto can efficiently track changes. + + Changesets allow developers to filter, cast, and validate changes before + we apply them to the data. Imagine the given schema: + + defmodule User do + use Ecto.Schema + + import Ecto.Changeset + + schema "users" do + field :name + field :email + field :age, :integer + end + + def changeset(user, params \\ %{}) do + user + |> cast(params, [:name, :email, :age]) + |> validate_required([:name, :email]) + |> validate_format(:email, ~r/@/) + |> validate_inclusion(:age, 18..100) + end + end + + The `changeset/2` function first invokes `Ecto.Changeset.cast/4` with + the struct, the parameters and a list of allowed fields; this returns a changeset. + The parameters is a map with binary keys and values that will be cast based + on the type defined by the schema. + + Any parameter that was not explicitly listed in the fields list will be ignored. + + After casting, the changeset is given to many `Ecto.Changeset.validate_*` + functions that validate only the **changed fields**. In other words: + if a field was not given as a parameter, it won't be validated at all. + For example, if the params map contain only the "name" and "email" keys, + the "age" validation won't run. + + Once a changeset is built, it can be given to functions like `insert` and + `update` in the repository that will return an `:ok` or `:error` tuple: + + case Repo.update(changeset) do + {:ok, user} -> + # user updated + {:error, changeset} -> + # an error occurred + end + + The benefit of having explicit changesets is that we can easily provide + different changesets for different use cases. For example, one + could easily provide specific changesets for registering and updating + users: + + def registration_changeset(user, params) do + # Changeset on create + end + + def update_changeset(user, params) do + # Changeset on update + end + + Changesets are also capable of transforming database constraints, + like unique indexes and foreign key checks, into errors. Allowing + developers to keep their database consistent while still providing + proper feedback to end users. Check `Ecto.Changeset.unique_constraint/3` + for some examples as well as the other `_constraint` functions. + + ## Query + + Last but not least, Ecto allows you to write queries in Elixir and send + them to the repository, which translates them to the underlying database. + Let's see an example: + + import Ecto.Query, only: [from: 2] + + query = from u in User, + where: u.age > 18 or is_nil(u.email), + select: u + + # Returns %User{} structs matching the query + Repo.all(query) + + In the example above we relied on our schema but queries can also be + made directly against a table by giving the table name as a string. In + such cases, the data to be fetched must be explicitly outlined: + + query = from u in "users", + where: u.age > 18 or is_nil(u.email), + select: %{name: u.name, age: u.age} + + # Returns maps as defined in select + Repo.all(query) + + Queries are defined and extended with the `from` macro. The supported + keywords are: + + * `:distinct` + * `:where` + * `:order_by` + * `:offset` + * `:limit` + * `:lock` + * `:group_by` + * `:having` + * `:join` + * `:select` + * `:preload` + + Examples and detailed documentation for each of those are available + in the `Ecto.Query` module. Functions supported in queries are listed + in `Ecto.Query.API`. + + When writing a query, you are inside Ecto's query syntax. In order to + access params values or invoke Elixir functions, you need to use the `^` + operator, which is overloaded by Ecto: + + def min_age(min) do + from u in User, where: u.age > ^min + end + + Besides `Repo.all/1` which returns all entries, repositories also + provide `Repo.one/1` which returns one entry or nil, `Repo.one!/1` + which returns one entry or raises, `Repo.get/2` which fetches + entries for a particular ID and more. + + Finally, if you need an escape hatch, Ecto provides fragments + (see `Ecto.Query.API.fragment/1`) to inject SQL (and non-SQL) + fragments into queries. Also, most adapters provide direct + APIs for queries, like `Ecto.Adapters.SQL.query/4`, allowing + developers to completely bypass Ecto queries. + + ## Other topics + + ### Associations + + Ecto supports defining associations on schemas: + + defmodule Post do + use Ecto.Schema + + schema "posts" do + has_many :comments, Comment + end + end + + defmodule Comment do + use Ecto.Schema + + schema "comments" do + field :title, :string + belongs_to :post, Post + end + end + + When an association is defined, Ecto also defines a field in the schema + with the association name. By default, associations are not loaded into + this field: + + iex> post = Repo.get(Post, 42) + iex> post.comments + #Ecto.Association.NotLoaded<...> + + However, developers can use the preload functionality in queries to + automatically pre-populate the field: + + Repo.all from p in Post, preload: [:comments] + + Preloading can also be done with a pre-defined join value: + + Repo.all from p in Post, + join: c in assoc(p, :comments), + where: c.votes > p.votes, + preload: [comments: c] + + Finally, for the simple cases, preloading can also be done after + a collection was fetched: + + posts = Repo.all(Post) |> Repo.preload(:comments) + + The `Ecto` module also provides conveniences for working + with associations. For example, `Ecto.assoc/3` returns a query + with all associated data to a given struct: + + import Ecto + + # Get all comments for the given post + Repo.all assoc(post, :comments) + + # Or build a query on top of the associated comments + query = from c in assoc(post, :comments), where: not is_nil(c.title) + Repo.all(query) + + Another function in `Ecto` is `build_assoc/3`, which allows + someone to build an associated struct with the proper fields: + + Repo.transaction fn -> + post = Repo.insert!(%Post{title: "Hello", body: "world"}) + + # Build a comment from post + comment = Ecto.build_assoc(post, :comments, body: "Excellent!") + + Repo.insert!(comment) + end + + In the example above, `Ecto.build_assoc/3` is equivalent to: + + %Comment{post_id: post.id, body: "Excellent!"} + + You can find more information about defining associations and each + respective association module in `Ecto.Schema` docs. + + > NOTE: Ecto does not lazy load associations. While lazily loading + > associations may sound convenient at first, in the long run it + > becomes a source of confusion and performance issues. + + ### Embeds + + Ecto also supports embeds. While associations keep parent and child + entries in different tables, embeds stores the child along side the + parent. + + Databases like MongoDB have native support for embeds. Databases + like PostgreSQL uses a mixture of JSONB (`embeds_one/3`) and ARRAY + columns to provide this functionality. + + Check `Ecto.Schema.embeds_one/3` and `Ecto.Schema.embeds_many/3` + for more information. + + ### Mix tasks and generators + + Ecto provides many tasks to help your workflow as well as code generators. + You can find all available tasks by typing `mix help` inside a project + with Ecto listed as a dependency. + + Ecto generators will automatically open the generated files if you have + `ECTO_EDITOR` set in your environment variable. + + #### Repo resolution + + Ecto requires developers to specify the key `:ecto_repos` in their + application configuration before using tasks like `ecto.create` and + `ecto.migrate`. For example: + + config :my_app, :ecto_repos, [MyApp.Repo] + + config :my_app, MyApp.Repo, + database: "ecto_simple", + username: "postgres", + password: "postgres", + hostname: "localhost" + + """ + + @doc """ + Returns the schema primary keys as a keyword list. + """ + @spec primary_key(Ecto.Schema.t()) :: Keyword.t() + def primary_key(%{__struct__: schema} = struct) do + Enum.map(schema.__schema__(:primary_key), fn field -> + {field, Map.fetch!(struct, field)} + end) + end + + @doc """ + Returns the schema primary keys as a keyword list. + + Raises `Ecto.NoPrimaryKeyFieldError` if the schema has no + primary key field. + """ + @spec primary_key!(Ecto.Schema.t()) :: Keyword.t() + def primary_key!(%{__struct__: schema} = struct) do + case primary_key(struct) do + [] -> raise Ecto.NoPrimaryKeyFieldError, schema: schema + pk -> pk + end + end + + @doc """ + Builds a struct from the given `assoc` in `struct`. + + ## Examples + + If the relationship is a `has_one` or `has_many` and + the primary key is set in the parent struct, the key will + automatically be set in the built association: + + iex> post = Repo.get(Post, 13) + %Post{id: 13} + iex> build_assoc(post, :comments) + %Comment{id: nil, post_id: 13} + + Note though it doesn't happen with `belongs_to` cases, as the + key is often the primary key and such is usually generated + dynamically: + + iex> comment = Repo.get(Comment, 13) + %Comment{id: 13, post_id: 25} + iex> build_assoc(comment, :post) + %Post{id: nil} + + You can also pass the attributes, which can be a map or + a keyword list, to set the struct's fields except the + association key. + + iex> build_assoc(post, :comments, text: "cool") + %Comment{id: nil, post_id: 13, text: "cool"} + + iex> build_assoc(post, :comments, %{text: "cool"}) + %Comment{id: nil, post_id: 13, text: "cool"} + + iex> build_assoc(post, :comments, post_id: 1) + %Comment{id: nil, post_id: 13} + + The given attributes are expected to be structured data. + If you want to build an association with external data, + such as a request parameters, you can use `Ecto.Changeset.cast/3` + after `build_assoc/3`: + + parent + |> Ecto.build_assoc(:child) + |> Ecto.Changeset.cast(params, [:field1, :field2]) + + """ + def build_assoc(%{__struct__: schema} = struct, assoc, attributes \\ %{}) do + assoc = Ecto.Association.association_from_schema!(schema, assoc) + assoc.__struct__.build(assoc, struct, drop_meta(attributes)) + end + + defp drop_meta(%{} = attrs), do: Map.drop(attrs, [:__struct__, :__meta__]) + defp drop_meta([_ | _] = attrs), do: Keyword.drop(attrs, [:__struct__, :__meta__]) + + @doc """ + Builds a query for the association in the given struct or structs. + + ## Examples + + In the example below, we get all comments associated to the given + post: + + post = Repo.get Post, 1 + Repo.all Ecto.assoc(post, :comments) + + `assoc/3` can also receive a list of posts, as long as the posts are + not empty: + + posts = Repo.all from p in Post, where: is_nil(p.published_at) + Repo.all Ecto.assoc(posts, :comments) + + This function can also be used to dynamically load through associations + by giving it a list. For example, to get all authors for all comments for + the given posts, do: + + posts = Repo.all from p in Post, where: is_nil(p.published_at) + Repo.all Ecto.assoc(posts, [:comments, :author]) + + ## Options + + * `:prefix` - the prefix to fetch assocs from. By default, queries + will use the same prefix as the first struct in the given collection. + This option allows the prefix to be changed. + + """ + def assoc(struct_or_structs, assocs, opts \\ []) do + [assoc | assocs] = List.wrap(assocs) + + structs = + case struct_or_structs do + nil -> raise ArgumentError, "cannot retrieve association #{inspect(assoc)} for nil" + [] -> raise ArgumentError, "cannot retrieve association #{inspect(assoc)} for empty list" + struct_or_structs -> List.wrap(struct_or_structs) + end + + sample = hd(structs) + prefix = assoc_prefix(sample, opts) + schema = sample.__struct__ + refl = %{owner_key: owner_key} = Ecto.Association.association_from_schema!(schema, assoc) + + values = + Enum.uniq( + for( + struct <- structs, + assert_struct!(schema, struct), + key = Map.fetch!(struct, owner_key), + do: key + ) + ) + + case assocs do + [] -> + %module{} = refl + %{module.assoc_query(refl, nil, values) | prefix: prefix} + + assocs -> + %{ + Ecto.Association.filter_through_chain(schema, [assoc | assocs], values) + | prefix: prefix + } + end + end + + defp assoc_prefix(sample, opts) do + case Keyword.fetch(opts, :prefix) do + {:ok, prefix} -> + prefix + + :error -> + case sample do + %{__meta__: %{prefix: prefix}} -> prefix + # Must be an embedded schema + _ -> nil + end + end + end + + @doc """ + Checks if an association is loaded. + + ## Examples + + iex> post = Repo.get(Post, 1) + iex> Ecto.assoc_loaded?(post.comments) + false + iex> post = post |> Repo.preload(:comments) + iex> Ecto.assoc_loaded?(post.comments) + true + + """ + def assoc_loaded?(%Ecto.Association.NotLoaded{}), do: false + def assoc_loaded?(list) when is_list(list), do: true + def assoc_loaded?(%_{}), do: true + def assoc_loaded?(nil), do: true + + @doc """ + Resets fields in a struct to their default values. + + ## Examples + + iex> post = post |> Repo.preload(:author) + %Post{title: "hello world", author: %Author{}} + iex> Ecto.reset_fields(post, [:title, :author]) + %Post{ + title: "default title", + author: #Ecto.Association.NotLoaded + } + + """ + @spec reset_fields(Ecto.Schema.t(), list()) :: Ecto.Schema.t() + def reset_fields(struct, []), do: struct + + def reset_fields(%{__struct__: schema} = struct, fields) do + default_struct = schema.__struct__() + default_fields = Map.take(default_struct, fields) + Map.merge(struct, default_fields) + end + + @doc """ + Gets the metadata from the given struct. + """ + def get_meta(struct, :context), + do: struct.__meta__.context + + def get_meta(struct, :state), + do: struct.__meta__.state + + def get_meta(struct, :source), + do: struct.__meta__.source + + def get_meta(struct, :prefix), + do: struct.__meta__.prefix + + @doc """ + Returns a new struct with updated metadata. + + It is possible to set: + + * `:source` - changes the struct query source + * `:prefix` - changes the struct query prefix + * `:context` - changes the struct meta context + * `:state` - changes the struct state + + Please refer to the `Ecto.Schema.Metadata` module for more information. + """ + @spec put_meta(Ecto.Schema.schema(), meta) :: Ecto.Schema.schema() + when meta: [ + source: Ecto.Schema.source(), + prefix: Ecto.Schema.prefix(), + context: Ecto.Schema.Metadata.context(), + state: Ecto.Schema.Metadata.state() + ] + def put_meta(%{__meta__: meta} = struct, opts) do + case put_or_noop_meta(opts, meta, false) do + :noop -> struct + meta -> %{struct | __meta__: meta} + end + end + + defp put_or_noop_meta([{key, value} | t], meta, updated?) do + case meta do + %{^key => ^value} -> put_or_noop_meta(t, meta, updated?) + _ -> put_or_noop_meta(t, put_meta(meta, key, value), true) + end + end + + defp put_or_noop_meta([], meta, true), do: meta + defp put_or_noop_meta([], _meta, false), do: :noop + + defp put_meta(meta, :state, state) do + if state in [:built, :loaded, :deleted] do + %{meta | state: state} + else + raise ArgumentError, "invalid state #{inspect(state)}" + end + end + + defp put_meta(meta, :source, source) do + %{meta | source: source} + end + + defp put_meta(meta, :prefix, prefix) do + %{meta | prefix: prefix} + end + + defp put_meta(meta, :context, context) do + %{meta | context: context} + end + + defp put_meta(_meta, key, _value) do + raise ArgumentError, "unknown meta key #{inspect(key)}" + end + + defp assert_struct!(module, %{__struct__: struct}) do + if struct != module do + raise ArgumentError, + "expected a homogeneous list containing the same struct, " <> + "got: #{inspect(module)} and #{inspect(struct)}" + else + true + end + end + + @doc """ + Loads previously dumped `data` in the given `format` into a schema. + + The first argument can be an embedded schema module, or a map (of types) and + determines the return value: a struct or a map, respectively. + + The second argument `data` specifies fields and values that are to be loaded. + It can be a map, a keyword list, or a `{fields, values}` tuple. Fields can be + atoms or strings. + + The third argument `format` is the format the data has been dumped as. For + example, databases may dump embedded to `:json`, this function allows such + dumped data to be put back into the schemas. If custom types are used, + Ecto will invoke the `c:Ecto.Type.embed_as/1` callback to decide if the data + should be loaded using `cast` or `load`. + + Fields that are not present in the schema (or `types` map) are ignored. + If any of the values has invalid type, an error is raised. + + Note that if you want to load data into a non-embedded schema that was + directly persisted into a given repository, then use `c:Ecto.Repo.load/2`. + + ## Examples + + iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT users.settings FROM users", []) + iex> Enum.map(result.rows, fn [settings] -> Ecto.embedded_load(Setting, Jason.decode!(settings), :json) end) + [%Setting{...}, ...] + """ + @spec embedded_load( + module_or_map :: module | map(), + data :: map(), + format :: atom() + ) :: Ecto.Schema.t() | map() + def embedded_load(schema_or_types, data, format) do + Ecto.Schema.Loader.unsafe_load( + schema_or_types, + data, + &Ecto.Type.embedded_load(&1, &2, format) + ) + end + + @doc """ + Dumps the given struct defined by an embedded schema. + + This converts the given embedded schema to a map to be serialized + with the given format. For example: + + iex> Ecto.embedded_dump(%Post{}, :json) + %{title: "hello"} + + """ + @spec embedded_dump(Ecto.Schema.t(), format :: atom()) :: map() + def embedded_dump(%schema{} = data, format) do + Ecto.Schema.Loader.safe_dump( + data, + schema.__schema__(:dump), + &Ecto.Type.embedded_dump(&1, &2, format) + ) + end +end diff --git a/deps/ecto/lib/ecto/adapter.ex b/deps/ecto/lib/ecto/adapter.ex new file mode 100644 index 0000000000000000000000000000000000000000..a84649596d94132469e8d92189c6bbbedb0c813f --- /dev/null +++ b/deps/ecto/lib/ecto/adapter.ex @@ -0,0 +1,142 @@ +defmodule Ecto.Adapter do + @moduledoc """ + Specifies the minimal API required from adapters. + """ + + @type t :: module + + @typedoc """ + The metadata returned by the adapter `c:init/1`. + + It must be a map and Ecto itself will always inject + two keys into the meta: + + * the `:cache` key, which as ETS table that can be used as a cache (if available) + * the `:pid` key, which is the PID returned by the child spec returned in `c:init/1` + + """ + @type adapter_meta :: %{optional(:stacktrace) => boolean(), optional(any()) => any()} + + @doc """ + The callback invoked in case the adapter needs to inject code. + """ + @macrocallback __before_compile__(env :: Macro.Env.t()) :: Macro.t() + + @doc """ + Ensure all applications necessary to run the adapter are started. + """ + @callback ensure_all_started( + config :: Keyword.t(), + type :: :permanent | :transient | :temporary + ) :: + {:ok, [atom]} | {:error, atom} + + @doc """ + Initializes the adapter supervision tree by returning the children and adapter metadata. + """ + @callback init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec(), adapter_meta} + + @doc """ + Checks out a connection for the duration of the given function. + + In case the adapter provides a pool, this guarantees all of the code + inside the given `fun` runs against the same connection, which + might improve performance by for instance allowing multiple related + calls to the datastore to share cache information: + + Repo.checkout(fn -> + for _ <- 1..100 do + Repo.insert!(%Post{}) + end + end) + + If the adapter does not provide a pool, just calling the passed function + and returning its result are enough. + + If the adapter provides a pool, it is supposed to "check out" one of the + pool connections for the duration of the function call. Which connection + is checked out is not passed to the calling function, so it should be done + using a stateful method like using the current process' dictionary, process + tracking, or some kind of other lookup method. Make sure that this stored + connection is then used in the other callbacks implementations, such as + `Ecto.Adapter.Queryable` and `Ecto.Adapter.Schema`. + """ + @callback checkout(adapter_meta, config :: Keyword.t(), (-> result)) :: result when result: var + + @doc """ + Returns true if a connection has been checked out. + """ + @callback checked_out?(adapter_meta) :: boolean + + @doc """ + Returns the loaders for a given type. + + It receives the primitive type and the Ecto type (which may be + primitive as well). It returns a list of loaders with the given + type usually at the end. + + This allows developers to properly translate values coming from + the adapters into Ecto ones. For example, if the database does not + support booleans but instead returns 0 and 1 for them, you could + add: + + def loaders(:boolean, type), do: [&bool_decode/1, type] + def loaders(_primitive, type), do: [type] + + defp bool_decode(0), do: {:ok, false} + defp bool_decode(1), do: {:ok, true} + + All adapters are required to implement a clause for `:binary_id` types, + since they are adapter specific. If your adapter does not provide binary + ids, you may simply use `Ecto.UUID`: + + def loaders(:binary_id, type), do: [Ecto.UUID, type] + def loaders(_primitive, type), do: [type] + + """ + @callback loaders(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) :: + [(term -> {:ok, term} | :error) | Ecto.Type.t()] + + @doc """ + Returns the dumpers for a given type. + + It receives the primitive type and the Ecto type (which may be + primitive as well). It returns a list of dumpers with the given + type usually at the beginning. + + This allows developers to properly translate values coming from + the Ecto into adapter ones. For example, if the database does not + support booleans but instead returns 0 and 1 for them, you could + add: + + def dumpers(:boolean, type), do: [type, &bool_encode/1] + def dumpers(_primitive, type), do: [type] + + defp bool_encode(false), do: {:ok, 0} + defp bool_encode(true), do: {:ok, 1} + + All adapters are required to implement a clause for :binary_id types, + since they are adapter specific. If your adapter does not provide + binary ids, you may simply use `Ecto.UUID`: + + def dumpers(:binary_id, type), do: [type, Ecto.UUID] + def dumpers(_primitive, type), do: [type] + + """ + @callback dumpers(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) :: + [(term -> {:ok, term} | :error) | Ecto.Type.t()] + + @doc """ + Returns the adapter metadata from its `c:init/1` callback. + + It expects a process name of a repository. The name is either + an atom or a PID. For a given repository, you often want to + call this function based on the repository dynamic repo: + + Ecto.Adapter.lookup_meta(repo.get_dynamic_repo()) + + """ + def lookup_meta(repo_name_or_pid) do + Ecto.Repo.Registry.lookup(repo_name_or_pid) + end +end diff --git a/deps/ecto/lib/ecto/adapter/queryable.ex b/deps/ecto/lib/ecto/adapter/queryable.ex new file mode 100644 index 0000000000000000000000000000000000000000..9d0a62d5c891a1ca35808e2231987bdf5d9a6585 --- /dev/null +++ b/deps/ecto/lib/ecto/adapter/queryable.ex @@ -0,0 +1,127 @@ +defmodule Ecto.Adapter.Queryable do + @moduledoc """ + Specifies the query API required from adapters. + + If your adapter is only able to respond to one or a couple of the query functions, + add custom implementations of those functions directly to the Repo + by using `c:Ecto.Adapter.__before_compile__/1` instead. + """ + + @typedoc "Proxy type to the adapter meta" + @type adapter_meta :: Ecto.Adapter.adapter_meta() + + @typedoc "Ecto.Query metadata fields (stored in cache)" + @type query_meta :: %{sources: tuple, preloads: term, select: map} + + @typedoc """ + Cache query metadata that is passed to `c:execute/5`. + + The cache can be in 3 states, documented below. + + If `{:nocache, prepared}` is given, it means the query was + not and cannot be cached. The `prepared` value is the value + returned by `c:prepare/2`. + + If `{:cache, cache_function, prepared}` is given, it means + the query can be cached and it must be cached by calling + the `cache_function` function with the cache entry of your + choice. Once `cache_function` is called, the next time the + same query is given to `c:execute/5`, it will receive the + `:cached` tuple. + + If `{:cached, update_function, reset_function, cached}` is + given, it means the query has been cached. You may call + `update_function/1` if you want to update the cached result. + Or you may call `reset_function/1`, with a new prepared query, + to force the query to be cached again. If `reset_function/1` + is called, the next time the same query is given to + `c:execute/5`, it will receive the `:cache` tuple. + """ + @type query_cache :: {:nocache, prepared} + | {:cache, cache_function :: (cached -> :ok), prepared} + | {:cached, update_function :: (cached -> :ok), reset_function :: (prepared -> :ok), cached} + + @type prepared :: term + @type cached :: term + @type options :: Keyword.t() + @type selected :: term + + @doc """ + Commands invoked to prepare a query. + + It is used on `c:Ecto.Repo.all/2`, `c:Ecto.Repo.update_all/3`, + and `c:Ecto.Repo.delete_all/2`. It returns a tuple, indicating if + this query can be cached or not, and the `prepared` query. + The `prepared` query is any term that will be passed to the + adapter's `c:execute/5`. + """ + @callback prepare(atom :: :all | :update_all | :delete_all, query :: Ecto.Query.t()) :: + {:cache, prepared} | {:nocache, prepared} + + @doc """ + Executes a previously prepared query. + + The `query_meta` field is a map containing some of the fields + found in the `Ecto.Query` struct, after they have been normalized. + For example, the values `selected` by the query, which then have + to be returned, can be found in `query_meta`. + + The `query_cache` and its state is documented in `t:query_cache/0`. + + The `params` is the list of query parameters. For example, for + a query such as `from Post, where: [id: ^123]`, `params` will be + `[123]`. + + Finally, `options` is a keyword list of options given to the + `Repo` operation that triggered the adapter call. Any option is + allowed, as this is a mechanism to allow users of Ecto to customize + how the adapter behaves per operation. + + It must return a tuple containing the number of entries and + the result set as a list of lists. The entries in the actual + list will depend on what has been selected by the query. The + result set may also be `nil`, if no value is being selected. + """ + @callback execute(adapter_meta, query_meta, query_cache, params :: list(), options) :: + {non_neg_integer, [[selected]] | nil} + + @doc """ + Streams a previously prepared query. + + See `c:execute/5` for a description of arguments. + + It returns a stream of values. + """ + @callback stream(adapter_meta, query_meta, query_cache, params :: list(), options) :: + Enumerable.t + + @doc """ + Plans and prepares a query for the given repo, leveraging its query cache. + + This operation uses the query cache if one is available. + """ + def prepare_query(operation, repo_name_or_pid, queryable) do + %{adapter: adapter, cache: cache} = Ecto.Repo.Registry.lookup(repo_name_or_pid) + + {_meta, prepared, _cast_params, dump_params} = + queryable + |> Ecto.Queryable.to_query() + |> Ecto.Query.Planner.ensure_select(operation == :all) + |> Ecto.Query.Planner.query(operation, cache, adapter, 0) + + {prepared, dump_params} + end + + @doc """ + Plans a query using the given adapter. + + This does not expect the repository and therefore does not leverage the cache. + """ + def plan_query(operation, adapter, queryable) do + query = Ecto.Queryable.to_query(queryable) + {query, params, _key} = Ecto.Query.Planner.plan(query, operation, adapter) + {cast_params, dump_params} = Enum.unzip(params) + {query, _} = Ecto.Query.Planner.normalize(query, operation, adapter, 0) + {query, cast_params, dump_params} + end +end diff --git a/deps/ecto/lib/ecto/adapter/schema.ex b/deps/ecto/lib/ecto/adapter/schema.ex new file mode 100644 index 0000000000000000000000000000000000000000..57c7bca28c05a835732579b6dc377b0a52c6a37f --- /dev/null +++ b/deps/ecto/lib/ecto/adapter/schema.ex @@ -0,0 +1,92 @@ +defmodule Ecto.Adapter.Schema do + @moduledoc """ + Specifies the schema API required from adapters. + """ + + @typedoc "Proxy type to the adapter meta" + @type adapter_meta :: Ecto.Adapter.adapter_meta() + + @typedoc "Ecto.Schema metadata fields" + @type schema_meta :: %{ + autogenerate_id: {schema_field :: atom, source_field :: atom, Ecto.Type.t()}, + context: term, + prefix: binary | nil, + schema: atom, + source: binary + } + + @type fields :: Keyword.t() + @type filters :: Keyword.t() + @type constraints :: Keyword.t() + @type returning :: [atom] + @type placeholders :: [term] + @type options :: Keyword.t() + + @type on_conflict :: + {:raise, list(), []} + | {:nothing, list(), [atom]} + | {[atom], list(), [atom]} + | {Ecto.Query.t(), list(), [atom]} + + @doc """ + Called to autogenerate a value for id/embed_id/binary_id. + + Returns the autogenerated value, or nil if it must be + autogenerated inside the storage or raise if not supported. + """ + @callback autogenerate(field_type :: :id | :binary_id | :embed_id) :: term | nil + + @doc """ + Inserts multiple entries into the data store. + + In case an `Ecto.Query` given as any of the field values by the user, + it will be sent to the adapter as a tuple with in the shape of + `{query, params}`. + """ + @callback insert_all( + adapter_meta, + schema_meta, + header :: [atom], + [[{atom, term | {Ecto.Query.t(), list()}}]], + on_conflict, + returning, + placeholders, + options + ) :: {non_neg_integer, [[term]] | nil} + + @doc """ + Inserts a single new struct in the data store. + + ## Autogenerate + + The primary key will be automatically included in `returning` if the + field has type `:id` or `:binary_id` and no value was set by the + developer or none was autogenerated by the adapter. + """ + @callback insert(adapter_meta, schema_meta, fields, on_conflict, returning, options) :: + {:ok, fields} | {:invalid, constraints} + + @doc """ + Updates a single struct with the given filters. + + While `filters` can be any record column, it is expected that + at least the primary key (or any other key that uniquely + identifies an existing record) be given as a filter. Therefore, + in case there is no record matching the given filters, + `{:error, :stale}` is returned. + """ + @callback update(adapter_meta, schema_meta, fields, filters, returning, options) :: + {:ok, fields} | {:invalid, constraints} | {:error, :stale} + + @doc """ + Deletes a single struct with the given filters. + + While `filters` can be any record column, it is expected that + at least the primary key (or any other key that uniquely + identifies an existing record) be given as a filter. Therefore, + in case there is no record matching the given filters, + `{:error, :stale}` is returned. + """ + @callback delete(adapter_meta, schema_meta, filters, returning, options) :: + {:ok, fields} | {:invalid, constraints} | {:error, :stale} +end diff --git a/deps/ecto/lib/ecto/adapter/storage.ex b/deps/ecto/lib/ecto/adapter/storage.ex new file mode 100644 index 0000000000000000000000000000000000000000..7590da26689a6269ef5a6dbe75dbecf6531c7d8f --- /dev/null +++ b/deps/ecto/lib/ecto/adapter/storage.ex @@ -0,0 +1,53 @@ +defmodule Ecto.Adapter.Storage do + @moduledoc """ + Specifies the adapter storage API. + """ + + @doc """ + Creates the storage given by options. + + Returns `:ok` if it was created successfully. + + Returns `{:error, :already_up}` if the storage has already been created or + `{:error, term}` in case anything else goes wrong. + + ## Examples + + storage_up(username: "postgres", + database: "ecto_test", + hostname: "localhost") + + """ + @callback storage_up(options :: Keyword.t) :: :ok | {:error, :already_up} | {:error, term} + + @doc """ + Drops the storage given by options. + + Returns `:ok` if it was dropped successfully. + + Returns `{:error, :already_down}` if the storage has already been dropped or + `{:error, term}` in case anything else goes wrong. + + ## Examples + + storage_down(username: "postgres", + database: "ecto_test", + hostname: "localhost") + + """ + @callback storage_down(options :: Keyword.t) :: :ok | {:error, :already_down} | {:error, term} + + @doc """ + Returns the status of a storage given by options. + + Can return `:up`, `:down` or `{:error, term}` in case anything goes wrong. + + ## Examples + + storage_status(username: "postgres", + database: "ecto_test", + hostname: "localhost") + + """ + @callback storage_status(options :: Keyword.t()) :: :up | :down | {:error, term()} +end diff --git a/deps/ecto/lib/ecto/adapter/transaction.ex b/deps/ecto/lib/ecto/adapter/transaction.ex new file mode 100644 index 0000000000000000000000000000000000000000..8624b55a176571b71010b1b72f0c56a4ec7251ef --- /dev/null +++ b/deps/ecto/lib/ecto/adapter/transaction.ex @@ -0,0 +1,31 @@ +defmodule Ecto.Adapter.Transaction do + @moduledoc """ + Specifies the adapter transactions API. + """ + + @type adapter_meta :: Ecto.Adapter.adapter_meta() + + @doc """ + Runs the given function inside a transaction. + + Returns `{:ok, value}` if the transaction was successful where `value` + is the value returned by the function or `{:error, value}` if the transaction + was rolled back where `value` is the value given to `rollback/1`. + """ + @callback transaction(adapter_meta, options :: Keyword.t(), function :: fun) :: + {:ok, any} | {:error, any} + + @doc """ + Returns true if the given process is inside a transaction. + """ + @callback in_transaction?(adapter_meta) :: boolean + + @doc """ + Rolls back the current transaction. + + The transaction will return the value given as `{:error, value}`. + + See `c:Ecto.Repo.rollback/1`. + """ + @callback rollback(adapter_meta, value :: any) :: no_return +end diff --git a/deps/ecto/lib/ecto/application.ex b/deps/ecto/lib/ecto/application.ex new file mode 100644 index 0000000000000000000000000000000000000000..8da32e7a58b52d105860162bc231e410a06634f8 --- /dev/null +++ b/deps/ecto/lib/ecto/application.ex @@ -0,0 +1,13 @@ +defmodule Ecto.Application do + @moduledoc false + use Application + + def start(_type, _args) do + children = [ + Ecto.Repo.Registry + ] + + opts = [strategy: :one_for_one, name: Ecto.Supervisor] + Supervisor.start_link(children, opts) + end +end diff --git a/deps/ecto/lib/ecto/association.ex b/deps/ecto/lib/ecto/association.ex new file mode 100644 index 0000000000000000000000000000000000000000..88fa398b13282fe4aba392e25773c78ed3270fd8 --- /dev/null +++ b/deps/ecto/lib/ecto/association.ex @@ -0,0 +1,1711 @@ +import Ecto.Query, only: [from: 1, from: 2, join: 4, join: 5, distinct: 3, where: 3] + +defmodule Ecto.Association.NotLoaded do + @moduledoc """ + Struct returned by associations when they are not loaded. + + The fields are: + + * `__field__` - the association field in `owner` + * `__owner__` - the schema that owns the association + * `__cardinality__` - the cardinality of the association + """ + + @type t :: %__MODULE__{ + __field__: atom(), + __owner__: any(), + __cardinality__: atom() + } + + defstruct [:__field__, :__owner__, :__cardinality__] + + defimpl Inspect do + def inspect(not_loaded, _opts) do + msg = "association #{inspect(not_loaded.__field__)} is not loaded" + ~s(#Ecto.Association.NotLoaded<#{msg}>) + end + end +end + +defmodule Ecto.Association do + @moduledoc false + + @type t :: %{ + required(:__struct__) => atom, + required(:on_cast) => nil | fun, + required(:cardinality) => :one | :many, + required(:relationship) => :parent | :child, + required(:owner) => atom, + required(:owner_key) => atom, + required(:field) => atom, + required(:unique) => boolean, + optional(atom) => any + } + + alias Ecto.Query.Builder.OrderBy + + @doc """ + Helper to check if a queryable is compiled. + """ + def ensure_compiled(queryable, env) do + if not is_atom(queryable) or queryable in env.context_modules do + :skip + else + case Code.ensure_compiled(queryable) do + {:module, _} -> :compiled + {:error, :unavailable} -> :skip + {:error, _} -> :not_found + end + end + end + + @doc """ + Builds the association struct. + + The struct must be defined in the module that implements the + callback and it must contain at least the following keys: + + * `:cardinality` - tells if the association is one to one + or one/many to many + + * `:field` - tells the field in the owner struct where the + association should be stored + + * `:owner` - the owner module of the association + + * `:owner_key` - the key in the owner with the association value + + * `:relationship` - if the relationship to the specified schema is + of a `:child` or a `:parent` + + """ + @callback struct(module, field :: atom, opts :: Keyword.t()) :: t + + @doc """ + Invoked after the schema is compiled to validate associations. + + Useful for checking if associated modules exist without running + into deadlocks. + """ + @callback after_compile_validation(t, Macro.Env.t()) :: :ok | {:error, String.t()} + + @doc """ + Builds a struct for the given association. + + The struct to build from is given as argument in case default values + should be set in the struct. + + Invoked by `Ecto.build_assoc/3`. + """ + @callback build(t, owner :: Ecto.Schema.t(), %{atom => term} | [Keyword.t()]) :: Ecto.Schema.t() + + @doc """ + Returns an association join query. + + This callback receives the association struct and it must return + a query that retrieves all associated entries using joins up to + the owner association. + + For example, a `has_many :comments` inside a `Post` module would + return: + + from c in Comment, join: p in Post, on: c.post_id == p.id + + Note all the logic must be expressed inside joins, as fields like + `where` and `order_by` won't be used by the caller. + + This callback is invoked when `join: assoc(p, :comments)` is used + inside queries. + """ + @callback joins_query(t) :: Ecto.Query.t() + + @doc """ + Returns the association query on top of the given query. + + If the query is `nil`, the association target must be used. + + This callback receives the association struct and it must return + a query that retrieves all associated entries with the given + values for the owner key. + + This callback is used by `Ecto.assoc/2` and when preloading. + """ + @callback assoc_query(t, Ecto.Query.t() | nil, values :: [term]) :: Ecto.Query.t() + + @doc """ + Returns information used by the preloader. + """ + @callback preload_info(t) :: + {:assoc, t, {integer, atom} | {integer, atom, Ecto.Type.t()}} + | {:through, t, [atom]} + + @doc """ + Performs the repository change on the association. + + Receives the parent changeset, the current changesets + and the repository action options. Must return the + persisted struct (or nil) or the changeset error. + """ + @callback on_repo_change( + t, + parent :: Ecto.Changeset.t(), + changeset :: Ecto.Changeset.t(), + Ecto.Adapter.t(), + Keyword.t() + ) :: + {:ok, Ecto.Schema.t() | nil} | {:error, Ecto.Changeset.t()} + + @doc """ + Retrieves the association from the given schema. + """ + def association_from_schema!(schema, assoc) do + schema.__schema__(:association, assoc) || + raise ArgumentError, "schema #{inspect(schema)} does not have association #{inspect(assoc)}" + end + + @doc """ + Returns the association key for the given module with the given suffix. + + ## Examples + + iex> Ecto.Association.association_key(Hello.World, :id) + :world_id + + iex> Ecto.Association.association_key(Hello.HTTP, :id) + :http_id + + iex> Ecto.Association.association_key(Hello.HTTPServer, :id) + :http_server_id + + """ + def association_key(module, suffix) do + prefix = module |> Module.split() |> List.last() |> Macro.underscore() + :"#{prefix}_#{suffix}" + end + + @doc """ + Build an association query through the given associations from the specified owner table + and through the given associations. Finally filter by the provided values of the owner_key of + the first relationship in the chain. Used in Ecto.assoc/2. + """ + def filter_through_chain(owner, through, values) do + chain_through(owner, through, nil, values) + |> distinct([x], true) + end + + @doc """ + Join the target table given a list of associations to go through starting from the owner table. + """ + def join_through_chain(owner, through, query) do + chain_through(owner, through, query, nil) + end + + # This function is used by both join_through_chain/3 and filter_through_chain/3 since the algorithm for both + # is nearly identical barring a few differences. + defp chain_through(owner, through, join_to, values) do + # Flatten the chain of throughs. If any of the associations is a HasThrough this allows us to expand it so we have + # a list of atomic associations to join through. + {_, through} = flatten_through_chain(owner, through, []) + + # If we're joining then we're going forward from the owner table to the destination table. + # Otherwise we're going backward from the destination table then filtering by values. + chain_direction = if(join_to != nil, do: :forward, else: :backward) + + # This stage produces a list of joins represented as a keyword list with the following structure: + # [ + # [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)] + # ] + relation_list = resolve_through_tables(owner, through, chain_direction) + + # Filter out the joins which are redundant + filtered_list = + Enum.with_index(relation_list) + |> Enum.filter(fn + # We always keep the first table in the chain since it's our source table for the query + {_, 0} -> + true + + {rel, _} -> + # If the condition is not empty we need to join to the table. Otherwise if the in_key and out_key is the same + # then this join is redundant since we can just join to the next table in the chain. + rel.in_key != rel.out_key or rel.where != [] + end) + |> Enum.map(&elem(&1, 0)) + + # If we're preloading we don't need the last table since it is the owner table. + filtered_list = if(join_to == nil, do: Enum.drop(filtered_list, -1), else: filtered_list) + + [source | joins] = filtered_list + + source_schema = source.schema + query = join_to || from(s in source_schema) + + counter = Ecto.Query.Builder.count_binds(query) - 1 + + # We need to create the query by joining all the tables, and also we need the out_key of the final table to use + # for the final WHERE clause with values. + {_, query, _, dest_out_key} = + Enum.reduce(joins, {source, query, counter, source.out_key}, fn + curr_rel, {prev_rel, query, counter, _} -> + related_queryable = curr_rel.schema + + next = + join(query, :inner, [{src, counter}], dest in ^related_queryable, + on: field(src, ^prev_rel.out_key) == field(dest, ^curr_rel.in_key) + ) + |> combine_joins_query(curr_rel.where, counter + 1) + + {curr_rel, next, counter + 1, curr_rel.out_key} + end) + + final_bind = Ecto.Query.Builder.count_binds(query) - 1 + + values = List.wrap(values) + + query = + case {join_to, values} do + {nil, [single_value]} -> + where(query, [{dest, final_bind}], field(dest, ^dest_out_key) == ^single_value) + + {nil, values} -> + where(query, [{dest, final_bind}], field(dest, ^dest_out_key) in ^values) + + {_, _} -> + query + end + + combine_assoc_query(query, source.where || []) + end + + defp flatten_through_chain(owner, [], acc), do: {owner, acc} + + defp flatten_through_chain(owner, [assoc | tl], acc) do + refl = association_from_schema!(owner, assoc) + + case refl do + %{through: nested_throughs} -> + {owner, acc} = flatten_through_chain(owner, nested_throughs, acc) + flatten_through_chain(owner, tl, acc) + + _ -> + flatten_through_chain(refl.related, tl, acc ++ [assoc]) + end + end + + defp resolve_through_tables(owner, through, :backward) do + # This step generates a list of maps with the following keys: + # [ + # %{schema: ..., out_key: ..., in_key: ..., where: ...} + # ] + # This is a list of all tables that we will need to join to follow the chain of throughs and which key is used + # to join in and out of the table, along with the where condition for that table. The final table of the chain will + # be "owner", and the first table of the chain will be the final destination table of all the throughs. + initial_owner_map = %{schema: owner, out_key: nil, in_key: nil, where: nil} + + Enum.reduce(through, {owner, [initial_owner_map]}, fn assoc, {owner, table_list} -> + refl = association_from_schema!(owner, assoc) + [owner_map | table_list] = table_list + + table_list = + case refl do + %{ + join_through: join_through, + join_keys: join_keys, + join_where: join_where, + where: where + } -> + [{owner_join_key, owner_key}, {related_join_key, related_key}] = join_keys + + owner_map = %{owner_map | in_key: owner_key} + + join_map = %{ + schema: join_through, + out_key: owner_join_key, + in_key: related_join_key, + where: join_where + } + + related_map = %{schema: refl.related, out_key: related_key, in_key: nil, where: where} + + [related_map, join_map, owner_map | table_list] + + _ -> + owner_map = %{owner_map | in_key: refl.owner_key} + + related_map = %{ + schema: refl.related, + out_key: refl.related_key, + in_key: nil, + where: refl.where + } + + [related_map, owner_map | table_list] + end + + {refl.related, table_list} + end) + |> elem(1) + end + + defp resolve_through_tables(owner, through, :forward) do + # In the forward case (joining) we need to reverse the list and swap the in_key for the out_key + # since we've changed directions. + resolve_through_tables(owner, through, :backward) + |> Enum.reverse() + |> Enum.map(fn %{out_key: out_key, in_key: in_key} = join -> + %{join | out_key: in_key, in_key: out_key} + end) + end + + @doc """ + Add the default assoc query where clauses to a join. + + This handles only `where` and converts it to a `join`, + as that is the only information propagate in join queries. + """ + def combine_joins_query(query, [], _binding), do: query + + def combine_joins_query(%{joins: joins} = query, [_ | _] = conditions, binding) do + {joins, [join_expr]} = Enum.split(joins, -1) + %{on: %{params: params, expr: expr} = join_on} = join_expr + {expr, params} = expand_where(conditions, expr, Enum.reverse(params), length(params), binding) + %{query | joins: joins ++ [%{join_expr | on: %{join_on | expr: expr, params: params}}]} + end + + @doc """ + Add the default assoc query where clauses a provided query. + """ + def combine_assoc_query(query, []), do: query + + def combine_assoc_query(%{wheres: []} = query, conditions) do + {expr, params} = expand_where(conditions, true, [], 0, 0) + + bool_expr = %Ecto.Query.BooleanExpr{ + op: :and, + expr: expr, + params: params, + line: __ENV__.line, + file: __ENV__.file + } + + %{query | wheres: [bool_expr]} + end + + def combine_assoc_query(%{wheres: wheres} = query, conditions) do + {wheres, [where_expr]} = Enum.split(wheres, -1) + %{params: params, expr: expr} = where_expr + {expr, params} = expand_where(conditions, expr, Enum.reverse(params), length(params), 0) + %{query | wheres: wheres ++ [%{where_expr | expr: expr, params: params}]} + end + + defp expand_where(conditions, expr, params, counter, binding) do + conjoin_exprs = fn + true, r -> r + l, r -> {:and, [], [l, r]} + end + + {expr, params, _counter} = + Enum.reduce(conditions, {expr, params, counter}, fn + {key, nil}, {expr, params, counter} -> + expr = conjoin_exprs.(expr, {:is_nil, [], [to_field(binding, key)]}) + {expr, params, counter} + + {key, {:not, nil}}, {expr, params, counter} -> + expr = conjoin_exprs.(expr, {:not, [], [{:is_nil, [], [to_field(binding, key)]}]}) + {expr, params, counter} + + {key, {:fragment, frag}}, {expr, params, counter} when is_binary(frag) -> + pieces = Ecto.Query.Builder.fragment_pieces(frag, [to_field(binding, key)]) + expr = conjoin_exprs.(expr, {:fragment, [], pieces}) + {expr, params, counter} + + {key, {:in, value}}, {expr, params, counter} when is_list(value) -> + expr = conjoin_exprs.(expr, {:in, [], [to_field(binding, key), {:^, [], [counter]}]}) + {expr, [{value, {:in, {binding, key}}} | params], counter + 1} + + {key, value}, {expr, params, counter} -> + expr = conjoin_exprs.(expr, {:==, [], [to_field(binding, key), {:^, [], [counter]}]}) + {expr, [{value, {binding, key}} | params], counter + 1} + end) + + {expr, Enum.reverse(params)} + end + + defp to_field(binding, field), + do: {{:., [], [{:&, [], [binding]}, field]}, [], []} + + @doc """ + Build a join query with the given `through` associations starting at `counter`. + """ + def joins_query(query, through, counter) do + Enum.reduce(through, {query, counter}, fn current, {acc, counter} -> + query = join(acc, :inner, [{x, counter}], assoc(x, ^current)) + {query, counter + 1} + end) + |> elem(0) + end + + @doc """ + Retrieves related module from queryable. + + ## Examples + + iex> Ecto.Association.related_from_query({"custom_source", Schema}, :comments_v1) + Schema + + iex> Ecto.Association.related_from_query(Schema, :comments_v1) + Schema + + iex> Ecto.Association.related_from_query("wrong", :comments_v1) + ** (ArgumentError) association :comments_v1 queryable must be a schema or a {source, schema}. got: "wrong" + """ + def related_from_query(atom, _name) when is_atom(atom), do: atom + + def related_from_query({source, schema}, _name) when is_binary(source) and is_atom(schema), + do: schema + + def related_from_query(queryable, name) do + raise ArgumentError, + "association #{inspect(name)} queryable must be a schema or " <> + "a {source, schema}. got: #{inspect(queryable)}" + end + + @doc """ + Applies default values into the struct. + """ + def apply_defaults(struct, defaults, _owner) when is_list(defaults) do + struct(struct, defaults) + end + + def apply_defaults(struct, {mod, fun, args}, owner) do + apply(mod, fun, [struct.__struct__(), owner | args]) + end + + @doc """ + Validates `defaults` for association named `name`. + """ + def validate_defaults!(_module, _name, {mod, fun, args} = defaults) + when is_atom(mod) and is_atom(fun) and is_list(args), + do: defaults + + def validate_defaults!(module, _name, fun) when is_atom(fun), + do: {module, fun, []} + + def validate_defaults!(_module, _name, defaults) when is_list(defaults), + do: defaults + + def validate_defaults!(_module, name, defaults) do + raise ArgumentError, + "expected defaults for #{inspect(name)} to be a keyword list " <> + "or a {module, fun, args} tuple, got: `#{inspect(defaults)}`" + end + + @doc """ + Validates `preload_order` for association named `name`. + """ + def validate_preload_order!(_name, {mod, fun, args} = preload_order) + when is_atom(mod) and is_atom(fun) and is_list(args), + do: preload_order + + def validate_preload_order!(name, preload_order) when is_list(preload_order) do + Enum.map(preload_order, fn + field when is_atom(field) -> + field + + {direction, field} when is_atom(direction) and is_atom(field) -> + unless OrderBy.valid_direction?(direction) do + raise ArgumentError, + "expected `:preload_order` for #{inspect(name)} to be a keyword list or a list of atoms/fields, " <> + "got: `#{inspect(preload_order)}`, " <> + "`#{inspect(direction)}` is not a valid direction" + end + + {direction, field} + + item -> + raise ArgumentError, + "expected `:preload_order` for #{inspect(name)} to be a keyword list or a list of atoms/fields, " <> + "got: `#{inspect(preload_order)}`, " <> + "`#{inspect(item)}` is not valid" + end) + end + + def validate_preload_order!(name, preload_order) do + raise ArgumentError, + "expected `:preload_order` for #{inspect(name)} to be a keyword list, a list of atoms/fields " <> + "or a {Mod, fun, args} tuple, got: `#{inspect(preload_order)}`" + end + + @doc """ + Merges source from query into to the given schema. + + In case the query does not have a source, returns + the schema unchanged. + """ + def merge_source(schema, query) + + def merge_source(%{__meta__: %{source: source}} = struct, {source, _}) do + struct + end + + def merge_source(struct, {source, _}) do + Ecto.put_meta(struct, source: source) + end + + def merge_source(struct, _query) do + struct + end + + @doc """ + Updates the prefix of a changeset based on the metadata. + """ + def update_parent_prefix( + %{data: %{__meta__: %{prefix: prefix}}} = changeset, + %{__meta__: %{prefix: prefix}} + ), + do: changeset + + def update_parent_prefix( + %{data: %{__meta__: %{prefix: nil}}} = changeset, + %{__meta__: %{prefix: prefix}} + ), + do: update_in(changeset.data, &Ecto.put_meta(&1, prefix: prefix)) + + def update_parent_prefix(changeset, _), + do: changeset + + @doc """ + Performs the repository action in the related changeset, + returning `{:ok, data}` or `{:error, changes}`. + """ + def on_repo_change(%{data: struct}, [], _adapter, _opts) do + {:ok, struct} + end + + def on_repo_change(changeset, assocs, adapter, opts) do + %{data: struct, changes: changes, action: action} = changeset + + {struct, changes, _halt, valid?} = + Enum.reduce(assocs, {struct, changes, false, true}, fn {refl, value}, acc -> + on_repo_change(refl, value, changeset, action, adapter, opts, acc) + end) + + case valid? do + true -> {:ok, struct} + false -> {:error, changes} + end + end + + defp on_repo_change( + %{cardinality: :one, field: field} = meta, + nil, + parent_changeset, + _repo_action, + adapter, + opts, + {parent, changes, halt, valid?} + ) do + if not halt, do: maybe_replace_one!(meta, nil, parent, parent_changeset, adapter, opts) + {Map.put(parent, field, nil), Map.put(changes, field, nil), halt, valid?} + end + + defp on_repo_change( + %{cardinality: :one, field: field, __struct__: mod} = meta, + %{action: action, data: current} = changeset, + parent_changeset, + repo_action, + adapter, + opts, + {parent, changes, halt, valid?} + ) do + check_action!(meta, action, repo_action) + if not halt, do: maybe_replace_one!(meta, current, parent, parent_changeset, adapter, opts) + + case on_repo_change_unless_halted(halt, mod, meta, parent_changeset, changeset, adapter, opts) do + {:ok, struct} -> + {Map.put(parent, field, struct), Map.put(changes, field, changeset), halt, valid?} + + {:error, error_changeset} -> + {parent, Map.put(changes, field, error_changeset), + halted?(halt, changeset, error_changeset), false} + end + end + + defp on_repo_change( + %{cardinality: :many, field: field, __struct__: mod} = meta, + changesets, + parent_changeset, + repo_action, + adapter, + opts, + {parent, changes, halt, all_valid?} + ) do + {changesets, structs, halt, valid?} = + Enum.reduce(changesets, {[], [], halt, true}, fn + %{action: action} = changeset, {changesets, structs, halt, valid?} -> + check_action!(meta, action, repo_action) + + case on_repo_change_unless_halted( + halt, + mod, + meta, + parent_changeset, + changeset, + adapter, + opts + ) do + {:ok, nil} -> + {[changeset | changesets], structs, halt, valid?} + + {:ok, struct} -> + {[changeset | changesets], [struct | structs], halt, valid?} + + {:error, error_changeset} -> + {[error_changeset | changesets], structs, halted?(halt, changeset, error_changeset), + false} + end + end) + + if valid? do + {Map.put(parent, field, Enum.reverse(structs)), + Map.put(changes, field, Enum.reverse(changesets)), halt, all_valid?} + else + {parent, Map.put(changes, field, Enum.reverse(changesets)), halt, false} + end + end + + defp check_action!(%{related: schema}, :delete, :insert) do + raise ArgumentError, + "got action :delete in changeset for associated #{inspect(schema)} while inserting" + end + + defp check_action!(_, _, _), do: :ok + + defp halted?(true, _, _), do: true + defp halted?(_, %{valid?: true}, %{valid?: false}), do: true + defp halted?(_, _, _), do: false + + defp on_repo_change_unless_halted(true, _mod, _meta, _parent, changeset, _adapter, _opts) do + {:error, changeset} + end + + defp on_repo_change_unless_halted(false, mod, meta, parent, changeset, adapter, opts) do + mod.on_repo_change(meta, parent, changeset, adapter, opts) + end + + defp maybe_replace_one!( + %{field: field, __struct__: mod} = meta, + current, + parent, + parent_changeset, + adapter, + opts + ) do + previous = Map.get(parent, field) + + if replaceable?(previous) and primary_key!(previous) != primary_key!(current) do + changeset = %{Ecto.Changeset.change(previous) | action: :replace} + + case mod.on_repo_change(meta, parent_changeset, changeset, adapter, opts) do + {:ok, _} -> + :ok + + {:error, changeset} -> + raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset + end + end + end + + defp maybe_replace_one!(_, _, _, _, _, _), do: :ok + + defp replaceable?(nil), do: false + defp replaceable?(%Ecto.Association.NotLoaded{}), do: false + defp replaceable?(%{__meta__: %{state: :built}}), do: false + defp replaceable?(_), do: true + + defp primary_key!(nil), do: [] + defp primary_key!(struct), do: Ecto.primary_key!(struct) +end + +defmodule Ecto.Association.Has do + @moduledoc """ + The association struct for `has_one` and `has_many` associations. + + Its fields are: + + * `cardinality` - The association cardinality + * `field` - The name of the association field on the schema + * `owner` - The schema where the association was defined + * `related` - The schema that is associated + * `owner_key` - The key on the `owner` schema used for the association + * `related_key` - The key on the `related` schema used for the association + * `queryable` - The real query to use for querying association + * `on_delete` - The action taken on associations when schema is deleted + * `on_replace` - The action taken on associations when schema is replaced + * `defaults` - Default fields used when building the association + * `relationship` - The relationship to the specified schema, default is `:child` + * `preload_order` - Default `order_by` of the association, used only by preload + """ + + @behaviour Ecto.Association + @on_delete_opts [:nothing, :nilify_all, :delete_all] + @on_replace_opts [:raise, :mark_as_invalid, :delete, :delete_if_exists, :nilify] + @has_one_on_replace_opts @on_replace_opts ++ [:update] + defstruct [ + :cardinality, + :field, + :owner, + :related, + :owner_key, + :related_key, + :on_cast, + :queryable, + :on_delete, + :on_replace, + where: [], + unique: true, + defaults: [], + relationship: :child, + ordered: false, + preload_order: [] + ] + + @impl true + def after_compile_validation(%{queryable: queryable, related_key: related_key}, env) do + compiled = Ecto.Association.ensure_compiled(queryable, env) + + cond do + compiled == :skip -> + :ok + + compiled == :not_found -> + {:error, "associated schema #{inspect(queryable)} does not exist"} + + not function_exported?(queryable, :__schema__, 2) -> + {:error, "associated module #{inspect(queryable)} is not an Ecto schema"} + + is_nil(queryable.__schema__(:type, related_key)) -> + {:error, "associated schema #{inspect(queryable)} does not have field `#{related_key}`"} + + true -> + :ok + end + end + + @impl true + def struct(module, name, opts) do + queryable = Keyword.fetch!(opts, :queryable) + cardinality = Keyword.fetch!(opts, :cardinality) + related = Ecto.Association.related_from_query(queryable, name) + + ref = + module + |> Module.get_attribute(:primary_key) + |> get_ref(opts[:references], name) + + unless Module.get_attribute(module, :ecto_fields)[ref] do + raise ArgumentError, + "schema does not have the field #{inspect(ref)} used by " <> + "association #{inspect(name)}, please set the :references option accordingly" + end + + if opts[:through] do + raise ArgumentError, + "invalid association #{inspect(name)}. When using the :through " <> + "option, the schema should not be passed as second argument" + end + + on_delete = Keyword.get(opts, :on_delete, :nothing) + + unless on_delete in @on_delete_opts do + raise ArgumentError, + "invalid :on_delete option for #{inspect(name)}. " <> + "The only valid options are: " <> + Enum.map_join(@on_delete_opts, ", ", &"`#{inspect(&1)}`") + end + + on_replace = Keyword.get(opts, :on_replace, :raise) + on_replace_opts = if cardinality == :one, do: @has_one_on_replace_opts, else: @on_replace_opts + + unless on_replace in on_replace_opts do + raise ArgumentError, + "invalid `:on_replace` option for #{inspect(name)}. " <> + "The only valid options are: " <> + Enum.map_join(@on_replace_opts, ", ", &"`#{inspect(&1)}`") + end + + defaults = Ecto.Association.validate_defaults!(module, name, opts[:defaults] || []) + preload_order = Ecto.Association.validate_preload_order!(name, opts[:preload_order] || []) + where = opts[:where] || [] + + unless is_list(where) do + raise ArgumentError, + "expected `:where` for #{inspect(name)} to be a keyword list, got: `#{inspect(where)}`" + end + + %__MODULE__{ + field: name, + cardinality: cardinality, + owner: module, + related: related, + owner_key: ref, + related_key: opts[:foreign_key] || Ecto.Association.association_key(module, ref), + queryable: queryable, + on_delete: on_delete, + on_replace: on_replace, + defaults: defaults, + where: where, + preload_order: preload_order + } + end + + defp get_ref(primary_key, nil, name) when primary_key in [nil, false] do + raise ArgumentError, + "need to set :references option for " <> + "association #{inspect(name)} when schema has no primary key" + end + + defp get_ref(primary_key, nil, _name), do: elem(primary_key, 0) + defp get_ref(_primary_key, references, _name), do: references + + @impl true + def build(%{owner_key: owner_key, related_key: related_key} = refl, owner, attributes) do + data = refl |> build(owner) |> struct(attributes) + %{data | related_key => Map.get(owner, owner_key)} + end + + @impl true + def joins_query( + %{related_key: related_key, owner: owner, owner_key: owner_key, queryable: queryable} = + assoc + ) do + from(o in owner, join: q in ^queryable, on: field(q, ^related_key) == field(o, ^owner_key)) + |> Ecto.Association.combine_joins_query(assoc.where, 1) + end + + @impl true + def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, [value]) do + from(x in (query || queryable), where: field(x, ^related_key) == ^value) + |> Ecto.Association.combine_assoc_query(assoc.where) + end + + @impl true + def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, values) do + from(x in (query || queryable), where: field(x, ^related_key) in ^values) + |> Ecto.Association.combine_assoc_query(assoc.where) + end + + @impl true + def preload_info(%{related_key: related_key} = refl) do + {:assoc, refl, {0, related_key}} + end + + @impl true + def on_repo_change( + %{on_replace: :delete_if_exists} = refl, + parent_changeset, + %{action: :replace} = changeset, + adapter, + opts + ) do + try do + on_repo_change(%{refl | on_replace: :delete}, parent_changeset, changeset, adapter, opts) + rescue + Ecto.StaleEntryError -> {:ok, nil} + end + end + + def on_repo_change( + %{on_replace: on_replace} = refl, + %{data: parent} = parent_changeset, + %{action: :replace} = changeset, + adapter, + opts + ) do + changeset = + case on_replace do + :nilify -> %{changeset | action: :update} + :update -> %{changeset | action: :update} + :delete -> %{changeset | action: :delete} + end + + changeset = Ecto.Association.update_parent_prefix(changeset, parent) + + case on_repo_change(refl, %{parent_changeset | data: nil}, changeset, adapter, opts) do + {:ok, _} -> {:ok, nil} + {:error, changeset} -> {:error, changeset} + end + end + + def on_repo_change(assoc, parent_changeset, changeset, _adapter, opts) do + %{data: parent, repo: repo} = parent_changeset + %{action: action, changes: changes} = changeset + + {key, value} = parent_key(assoc, parent) + changeset = update_parent_key(changeset, action, key, value) + changeset = Ecto.Association.update_parent_prefix(changeset, parent) + + case apply(repo, action, [changeset, opts]) do + {:ok, _} = ok -> + if action == :delete, do: {:ok, nil}, else: ok + + {:error, changeset} -> + original = Map.get(changes, key) + {:error, put_in(changeset.changes[key], original)} + end + end + + defp update_parent_key(changeset, :delete, _key, _value), + do: changeset + + defp update_parent_key(changeset, _action, key, value), + do: Ecto.Changeset.put_change(changeset, key, value) + + defp parent_key(%{related_key: related_key}, nil) do + {related_key, nil} + end + + defp parent_key(%{owner_key: owner_key, related_key: related_key}, owner) do + {related_key, Map.get(owner, owner_key)} + end + + ## Relation callbacks + @behaviour Ecto.Changeset.Relation + + @impl true + def build(%{related: related, queryable: queryable, defaults: defaults}, owner) do + related + |> Ecto.Association.apply_defaults(defaults, owner) + |> Ecto.Association.merge_source(queryable) + end + + ## On delete callbacks + + @doc false + def delete_all(refl, parent, repo_name, opts) do + if query = on_delete_query(refl, parent) do + Ecto.Repo.Queryable.delete_all(repo_name, query, opts) + end + end + + @doc false + def nilify_all(%{related_key: related_key} = refl, parent, repo_name, opts) do + if query = on_delete_query(refl, parent) do + Ecto.Repo.Queryable.update_all(repo_name, query, [set: [{related_key, nil}]], opts) + end + end + + defp on_delete_query( + %{owner_key: owner_key, related_key: related_key, queryable: queryable}, + parent + ) do + if value = Map.get(parent, owner_key) do + query = from x in queryable, where: field(x, ^related_key) == ^value + + parent + |> Ecto.get_meta(:prefix) + |> case do + nil -> query + prefix -> Ecto.Query.put_query_prefix(query, prefix) + end + end + end +end + +defmodule Ecto.Association.HasThrough do + @moduledoc """ + The association struct for `has_one` and `has_many` through associations. + + Its fields are: + + * `cardinality` - The association cardinality + * `field` - The name of the association field on the schema + * `owner` - The schema where the association was defined + * `owner_key` - The key on the `owner` schema used for the association + * `through` - The through associations + * `relationship` - The relationship to the specified schema, default `:child` + """ + + @behaviour Ecto.Association + defstruct [ + :cardinality, + :field, + :owner, + :owner_key, + :through, + :on_cast, + relationship: :child, + unique: true, + ordered: false + ] + + @impl true + def after_compile_validation(_, _) do + :ok + end + + @impl true + def struct(module, name, opts) do + through = Keyword.fetch!(opts, :through) + + refl = + case through do + [h, _ | _] -> + Module.get_attribute(module, :ecto_assocs)[h] + + _ -> + raise ArgumentError, + ":through expects a list with at least two entries: " <> + "the association in the current module and one step through, got: #{inspect(through)}" + end + + unless refl do + raise ArgumentError, + "schema does not have the association #{inspect(hd(through))} " <> + "used by association #{inspect(name)}, please ensure the association exists and " <> + "is defined before the :through one" + end + + %__MODULE__{ + field: name, + cardinality: Keyword.fetch!(opts, :cardinality), + through: through, + owner: module, + owner_key: refl.owner_key + } + end + + @impl true + def build(%{field: name}, %{__struct__: owner}, _attributes) do + raise ArgumentError, + "cannot build through association `#{inspect(name)}` for #{inspect(owner)}. " <> + "Instead build the intermediate steps explicitly." + end + + @impl true + def preload_info(%{through: through} = refl) do + {:through, refl, through} + end + + @impl true + def on_repo_change(%{field: name}, _, _, _, _) do + raise ArgumentError, + "cannot insert/update/delete through associations `#{inspect(name)}` via the repository. " <> + "Instead build the intermediate steps explicitly." + end + + @impl true + def joins_query(%{owner: owner, through: through}) do + Ecto.Association.join_through_chain(owner, through, from(x in owner)) + end + + @impl true + def assoc_query(%{owner: owner, through: through}, _, values) do + Ecto.Association.filter_through_chain(owner, through, values) + end +end + +defmodule Ecto.Association.BelongsTo do + @moduledoc """ + The association struct for a `belongs_to` association. + + Its fields are: + + * `cardinality` - The association cardinality + * `field` - The name of the association field on the schema + * `owner` - The schema where the association was defined + * `owner_key` - The key on the `owner` schema used for the association + * `related` - The schema that is associated + * `related_key` - The key on the `related` schema used for the association + * `queryable` - The real query to use for querying association + * `defaults` - Default fields used when building the association + * `relationship` - The relationship to the specified schema, default `:parent` + * `on_replace` - The action taken on associations when schema is replaced + """ + + @behaviour Ecto.Association + @on_replace_opts [:raise, :mark_as_invalid, :delete, :delete_if_exists, :nilify, :update] + defstruct [ + :field, + :owner, + :related, + :owner_key, + :related_key, + :queryable, + :on_cast, + :on_replace, + where: [], + defaults: [], + cardinality: :one, + relationship: :parent, + unique: true, + ordered: false + ] + + @impl true + def after_compile_validation(%{queryable: queryable, related_key: related_key}, env) do + compiled = Ecto.Association.ensure_compiled(queryable, env) + + cond do + compiled == :skip -> + :ok + + compiled == :not_found -> + {:error, "associated schema #{inspect(queryable)} does not exist"} + + not function_exported?(queryable, :__schema__, 2) -> + {:error, "associated module #{inspect(queryable)} is not an Ecto schema"} + + is_nil(queryable.__schema__(:type, related_key)) -> + {:error, "associated schema #{inspect(queryable)} does not have field `#{related_key}`"} + + true -> + :ok + end + end + + @impl true + def struct(module, name, opts) do + ref = if ref = opts[:references], do: ref, else: :id + queryable = Keyword.fetch!(opts, :queryable) + related = Ecto.Association.related_from_query(queryable, name) + on_replace = Keyword.get(opts, :on_replace, :raise) + + unless on_replace in @on_replace_opts do + raise ArgumentError, + "invalid `:on_replace` option for #{inspect(name)}. " <> + "The only valid options are: " <> + Enum.map_join(@on_replace_opts, ", ", &"`#{inspect(&1)}`") + end + + defaults = Ecto.Association.validate_defaults!(module, name, opts[:defaults] || []) + where = opts[:where] || [] + + unless is_list(where) do + raise ArgumentError, + "expected `:where` for #{inspect(name)} to be a keyword list, got: `#{inspect(where)}`" + end + + %__MODULE__{ + field: name, + owner: module, + related: related, + owner_key: Keyword.fetch!(opts, :foreign_key), + related_key: ref, + queryable: queryable, + on_replace: on_replace, + defaults: defaults, + where: where + } + end + + @impl true + def build(refl, owner, attributes) do + refl + |> build(owner) + |> struct(attributes) + end + + @impl true + def joins_query( + %{related_key: related_key, owner: owner, owner_key: owner_key, queryable: queryable} = + assoc + ) do + from(o in owner, join: q in ^queryable, on: field(q, ^related_key) == field(o, ^owner_key)) + |> Ecto.Association.combine_joins_query(assoc.where, 1) + end + + @impl true + def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, [value]) do + from(x in (query || queryable), where: field(x, ^related_key) == ^value) + |> Ecto.Association.combine_assoc_query(assoc.where) + end + + @impl true + def assoc_query(%{related_key: related_key, queryable: queryable} = assoc, query, values) do + from(x in (query || queryable), where: field(x, ^related_key) in ^values) + |> Ecto.Association.combine_assoc_query(assoc.where) + end + + @impl true + def preload_info(%{related_key: related_key} = refl) do + {:assoc, refl, {0, related_key}} + end + + @impl true + def on_repo_change(%{on_replace: :nilify}, _, %{action: :replace}, _adapter, _opts) do + {:ok, nil} + end + + def on_repo_change( + %{on_replace: :delete_if_exists} = refl, + parent_changeset, + %{action: :replace} = changeset, + adapter, + opts + ) do + try do + on_repo_change(%{refl | on_replace: :delete}, parent_changeset, changeset, adapter, opts) + rescue + Ecto.StaleEntryError -> {:ok, nil} + end + end + + def on_repo_change( + %{on_replace: on_replace} = refl, + parent_changeset, + %{action: :replace} = changeset, + adapter, + opts + ) do + changeset = + case on_replace do + :delete -> %{changeset | action: :delete} + :update -> %{changeset | action: :update} + end + + on_repo_change(refl, parent_changeset, changeset, adapter, opts) + end + + def on_repo_change( + _refl, + %{data: parent, repo: repo}, + %{action: action} = changeset, + _adapter, + opts + ) do + changeset = Ecto.Association.update_parent_prefix(changeset, parent) + + case apply(repo, action, [changeset, opts]) do + {:ok, _} = ok -> + if action == :delete, do: {:ok, nil}, else: ok + + {:error, changeset} -> + {:error, changeset} + end + end + + ## Relation callbacks + @behaviour Ecto.Changeset.Relation + + @impl true + def build(%{related: related, queryable: queryable, defaults: defaults}, owner) do + related + |> Ecto.Association.apply_defaults(defaults, owner) + |> Ecto.Association.merge_source(queryable) + end +end + +defmodule Ecto.Association.ManyToMany do + @moduledoc """ + The association struct for `many_to_many` associations. + + Its fields are: + + * `cardinality` - The association cardinality + * `field` - The name of the association field on the schema + * `owner` - The schema where the association was defined + * `related` - The schema that is associated + * `owner_key` - The key on the `owner` schema used for the association + * `queryable` - The real query to use for querying association + * `on_delete` - The action taken on associations when schema is deleted + * `on_replace` - The action taken on associations when schema is replaced + * `defaults` - Default fields used when building the association + * `relationship` - The relationship to the specified schema, default `:child` + * `join_keys` - The keyword list with many to many join keys + * `join_through` - Atom (representing a schema) or a string (representing a table) + for many to many associations + * `join_defaults` - A list of defaults for join associations + * `preload_order` - Default `order_by` of the association, used only by preload + """ + + @behaviour Ecto.Association + @on_delete_opts [:nothing, :delete_all] + @on_replace_opts [:raise, :mark_as_invalid, :delete] + + defstruct [ + :field, + :owner, + :related, + :owner_key, + :queryable, + :on_delete, + :on_replace, + :join_keys, + :join_through, + :on_cast, + where: [], + join_where: [], + defaults: [], + join_defaults: [], + relationship: :child, + cardinality: :many, + unique: false, + ordered: false, + preload_order: [] + ] + + @impl true + def after_compile_validation(%{queryable: queryable, join_through: join_through}, env) do + compiled = Ecto.Association.ensure_compiled(queryable, env) + join_compiled = Ecto.Association.ensure_compiled(join_through, env) + + cond do + compiled == :skip -> + :ok + + compiled == :not_found -> + {:error, "associated schema #{inspect(queryable)} does not exist"} + + not function_exported?(queryable, :__schema__, 2) -> + {:error, "associated module #{inspect(queryable)} is not an Ecto schema"} + + join_compiled == :skip -> + :ok + + join_compiled == :not_found -> + {:error, ":join_through schema #{inspect(join_through)} does not exist"} + + not function_exported?(join_through, :__schema__, 2) -> + {:error, ":join_through module #{inspect(join_through)} is not an Ecto schema"} + + true -> + :ok + end + end + + @impl true + def struct(module, name, opts) do + queryable = Keyword.fetch!(opts, :queryable) + related = Ecto.Association.related_from_query(queryable, name) + + join_keys = opts[:join_keys] + join_through = opts[:join_through] + validate_join_through(name, join_through) + + {owner_key, join_keys} = + case join_keys do + [{join_owner_key, owner_key}, {join_related_key, related_key}] + when is_atom(join_owner_key) and is_atom(owner_key) and + is_atom(join_related_key) and is_atom(related_key) -> + {owner_key, join_keys} + + nil -> + {:id, default_join_keys(module, related)} + + _ -> + raise ArgumentError, + "many_to_many #{inspect(name)} expect :join_keys to be a keyword list " <> + "with two entries, the first being how the join table should reach " <> + "the current schema and the second how the join table should reach " <> + "the associated schema. For example: #{inspect(default_join_keys(module, related))}" + end + + unless Module.get_attribute(module, :ecto_fields)[owner_key] do + raise ArgumentError, + "schema does not have the field #{inspect(owner_key)} used by " <> + "association #{inspect(name)}, please set the :join_keys option accordingly" + end + + on_delete = Keyword.get(opts, :on_delete, :nothing) + on_replace = Keyword.get(opts, :on_replace, :raise) + + unless on_delete in @on_delete_opts do + raise ArgumentError, + "invalid :on_delete option for #{inspect(name)}. " <> + "The only valid options are: " <> + Enum.map_join(@on_delete_opts, ", ", &"`#{inspect(&1)}`") + end + + unless on_replace in @on_replace_opts do + raise ArgumentError, + "invalid `:on_replace` option for #{inspect(name)}. " <> + "The only valid options are: " <> + Enum.map_join(@on_replace_opts, ", ", &"`#{inspect(&1)}`") + end + + where = opts[:where] || [] + join_where = opts[:join_where] || [] + defaults = Ecto.Association.validate_defaults!(module, name, opts[:defaults] || []) + join_defaults = Ecto.Association.validate_defaults!(module, name, opts[:join_defaults] || []) + preload_order = Ecto.Association.validate_preload_order!(name, opts[:preload_order] || []) + + unless is_list(where) do + raise ArgumentError, + "expected `:where` for #{inspect(name)} to be a keyword list, got: `#{inspect(where)}`" + end + + unless is_list(join_where) do + raise ArgumentError, + "expected `:join_where` for #{inspect(name)} to be a keyword list, got: `#{inspect(join_where)}`" + end + + if opts[:join_defaults] && is_binary(join_through) do + raise ArgumentError, ":join_defaults has no effect for a :join_through without a schema" + end + + %__MODULE__{ + field: name, + cardinality: Keyword.fetch!(opts, :cardinality), + owner: module, + related: related, + owner_key: owner_key, + join_keys: join_keys, + join_where: join_where, + join_through: join_through, + join_defaults: join_defaults, + queryable: queryable, + on_delete: on_delete, + on_replace: on_replace, + unique: Keyword.get(opts, :unique, false), + defaults: defaults, + where: where, + preload_order: preload_order + } + end + + defp default_join_keys(module, related) do + [ + {Ecto.Association.association_key(module, :id), :id}, + {Ecto.Association.association_key(related, :id), :id} + ] + end + + @impl true + def joins_query( + %{owner: owner, queryable: queryable, join_through: join_through, join_keys: join_keys} = + assoc + ) do + [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys + + from(o in owner, + join: j in ^join_through, + on: field(j, ^join_owner_key) == field(o, ^owner_key), + join: q in ^queryable, + on: field(j, ^join_related_key) == field(q, ^related_key) + ) + |> Ecto.Association.combine_joins_query(assoc.where, 2) + |> Ecto.Association.combine_joins_query(assoc.join_where, 1) + end + + def assoc_query(%{queryable: queryable} = refl, values) do + assoc_query(refl, queryable, values) + end + + @impl true + def assoc_query(assoc, query, values) do + %{queryable: queryable, join_through: join_through, join_keys: join_keys, owner: owner} = + assoc + + [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys + + owner_key_type = owner.__schema__(:type, owner_key) + + # We only need to join in the "join table". Preload and Ecto.assoc expressions can then filter + # by &1.join_owner_key in ^... to filter down to the associated entries in the related table. + query = + from(q in (query || queryable), + join: j in ^join_through, + on: field(q, ^related_key) == field(j, ^join_related_key), + where: field(j, ^join_owner_key) in type(^values, {:in, ^owner_key_type}) + ) + |> Ecto.Association.combine_assoc_query(assoc.where) + + Ecto.Association.combine_joins_query(query, assoc.join_where, length(query.joins)) + end + + @impl true + def build(refl, owner, attributes) do + refl + |> build(owner) + |> struct(attributes) + end + + @impl true + def preload_info(%{join_keys: [{join_owner_key, owner_key}, {_, _}], owner: owner} = refl) do + owner_key_type = owner.__schema__(:type, owner_key) + + # When preloading use the last bound table (which is the join table) and the join_owner_key + # to filter out related entities to the owner structs we're preloading with. + {:assoc, refl, {-1, join_owner_key, owner_key_type}} + end + + @impl true + def on_repo_change( + %{on_replace: :delete} = refl, + parent_changeset, + %{action: :replace} = changeset, + adapter, + opts + ) do + on_repo_change(refl, parent_changeset, %{changeset | action: :delete}, adapter, opts) + end + + def on_repo_change( + %{join_keys: join_keys, join_through: join_through, join_where: join_where}, + %{repo: repo, data: owner}, + %{action: :delete, data: related}, + adapter, + opts + ) do + [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys + owner_value = dump!(:delete, join_through, owner, owner_key, adapter) + related_value = dump!(:delete, join_through, related, related_key, adapter) + + query = + join_through + |> where([j], field(j, ^join_owner_key) == ^owner_value) + |> where([j], field(j, ^join_related_key) == ^related_value) + |> Ecto.Association.combine_assoc_query(join_where) + + query = %{query | prefix: owner.__meta__.prefix} + repo.delete_all(query, opts) + {:ok, nil} + end + + def on_repo_change( + %{field: field, join_through: join_through, join_keys: join_keys} = refl, + %{repo: repo, data: owner} = parent_changeset, + %{action: action} = changeset, + adapter, + opts + ) do + changeset = Ecto.Association.update_parent_prefix(changeset, owner) + + case apply(repo, action, [changeset, opts]) do + {:ok, related} -> + [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys + + if insert_join?(parent_changeset, changeset, field, related_key) do + owner_value = dump!(:insert, join_through, owner, owner_key, adapter) + related_value = dump!(:insert, join_through, related, related_key, adapter) + data = %{join_owner_key => owner_value, join_related_key => related_value} + + case insert_join(join_through, refl, parent_changeset, data, opts) do + {:error, join_changeset} -> + {:error, + %{ + changeset + | errors: join_changeset.errors ++ changeset.errors, + valid?: join_changeset.valid? and changeset.valid? + }} + + _ -> + {:ok, related} + end + else + {:ok, related} + end + + {:error, changeset} -> + {:error, changeset} + end + end + + defp validate_join_through(name, nil) do + raise ArgumentError, + "many_to_many #{inspect(name)} associations require the :join_through option to be given" + end + + defp validate_join_through(_, join_through) + when is_atom(join_through) or is_binary(join_through) do + :ok + end + + defp validate_join_through(name, _join_through) do + raise ArgumentError, + "many_to_many #{inspect(name)} associations require the :join_through option to be " <> + "an atom (representing a schema) or a string (representing a table)" + end + + defp insert_join?(%{action: :insert}, _, _field, _related_key), do: true + defp insert_join?(_, %{action: :insert}, _field, _related_key), do: true + + defp insert_join?(%{data: owner}, %{data: related}, field, related_key) do + current_key = Map.fetch!(related, related_key) + + not Enum.any?(Map.fetch!(owner, field), fn child -> + Map.get(child, related_key) == current_key + end) + end + + defp insert_join(join_through, _refl, %{repo: repo, data: owner}, data, opts) + when is_binary(join_through) do + opts = Keyword.put_new(opts, :prefix, owner.__meta__.prefix) + repo.insert_all(join_through, [data], opts) + end + + defp insert_join(join_through, refl, parent_changeset, data, opts) when is_atom(join_through) do + %{repo: repo, constraints: constraints, data: owner} = parent_changeset + + changeset = + join_through + |> Ecto.Association.apply_defaults(refl.join_defaults, owner) + |> Map.merge(data) + |> Ecto.Changeset.change() + |> Map.put(:constraints, constraints) + |> put_new_prefix(owner.__meta__.prefix) + + repo.insert(changeset, opts) + end + + defp put_new_prefix(%{data: %{__meta__: %{prefix: prefix}}} = changeset, prefix), + do: changeset + + defp put_new_prefix(%{data: %{__meta__: %{prefix: nil}}} = changeset, prefix), + do: update_in(changeset.data, &Ecto.put_meta(&1, prefix: prefix)) + + defp put_new_prefix(changeset, _), + do: changeset + + defp field!(op, struct, field) do + Map.get(struct, field) || + raise "could not #{op} join entry because `#{field}` is nil in #{inspect(struct)}" + end + + defp dump!(action, join_through, struct, field, adapter) when is_binary(join_through) do + value = field!(action, struct, field) + type = struct.__struct__.__schema__(:type, field) + + case Ecto.Type.adapter_dump(adapter, type, value) do + {:ok, value} -> + value + + :error -> + raise Ecto.ChangeError, + "value `#{inspect(value)}` for `#{inspect(struct.__struct__)}.#{field}` " <> + "in `#{action}` does not match type #{Ecto.Type.format(type)}" + end + end + + defp dump!(action, join_through, struct, field, _) when is_atom(join_through) do + field!(action, struct, field) + end + + ## Relation callbacks + @behaviour Ecto.Changeset.Relation + + @impl true + def build(%{related: related, queryable: queryable, defaults: defaults}, owner) do + related + |> Ecto.Association.apply_defaults(defaults, owner) + |> Ecto.Association.merge_source(queryable) + end + + ## On delete callbacks + + @doc false + def delete_all(refl, parent, repo_name, opts) do + %{join_through: join_through, join_keys: join_keys, owner: owner} = refl + [{join_owner_key, owner_key}, {_, _}] = join_keys + + if value = Map.get(parent, owner_key) do + owner_type = owner.__schema__(:type, owner_key) + + query = + from j in join_through, where: field(j, ^join_owner_key) == type(^value, ^owner_type) + + Ecto.Repo.Queryable.delete_all(repo_name, query, opts) + end + end +end diff --git a/deps/ecto/lib/ecto/changeset.ex b/deps/ecto/lib/ecto/changeset.ex new file mode 100644 index 0000000000000000000000000000000000000000..48e412baf580bd0845e61972b41132083cb5d6d6 --- /dev/null +++ b/deps/ecto/lib/ecto/changeset.ex @@ -0,0 +1,4294 @@ +defmodule Ecto.Changeset do + @moduledoc ~S""" + Changesets allow filtering, casting, validation and + definition of constraints when manipulating structs. + + There is an example of working with changesets in the introductory + documentation in the `Ecto` module. The functions `cast/4` and + `change/2` are the usual entry points for creating changesets. + The first one is used to cast and validate external parameters, + such as parameters sent through a form, API, command line, etc. + The second one is used to change data directly from your application. + + The remaining functions in this module, such as validations, + constraints, association handling, are about manipulating + changesets. + + ## External vs internal data + + Changesets allow working with two kinds of data: + + * internal to the application - for example programmatically generated, + or coming from other subsystems. This use case is primarily covered + by the `change/2` and `put_change/3` functions. + + * external to the application - for example data provided by the user in + a form that needs to be type-converted and properly validated. This + use case is primarily covered by the `cast/4` function. + + When working with external data, the data is typically provided + as maps with string keys (also known as parameters). On the other hand, + when working with internal data, you typically have maps of atom keys + or structs. This duality allows you to track the nature of your data: + if you have structs or maps with atom keys, it means the data has been + parsed/validated. + + If you have external data or you have maps that may have either + string or atom keys, consider using `cast/4` to create a changeset. + The changeset will parse and validate these parameters and provide APIs + to safely manipulate and change the data accordingly. + + ## Validations and constraints + + Ecto changesets provide both validations and constraints which + are ultimately turned into errors in case something goes wrong. + + The difference between them is that most validations can be + executed without a need to interact with the database and, therefore, + are always executed before attempting to insert or update the entry + in the database. Validations run immediately when a validation function + is called on the data that is contained in the changeset at that time. + + Some validations may happen against the database but + they are inherently unsafe. Those validations start with a `unsafe_` + prefix, such as `unsafe_validate_unique/4`. + + On the other hand, constraints rely on the database and are always safe. + As a consequence, validations are always checked before constraints. + Constraints won't even be checked in case validations failed. + + Let's see an example: + + defmodule User do + use Ecto.Schema + import Ecto.Changeset + + schema "users" do + field :name + field :email + field :age, :integer + end + + def changeset(user, params \\ %{}) do + user + |> cast(params, [:name, :email, :age]) + |> validate_required([:name, :email]) + |> validate_format(:email, ~r/@/) + |> validate_inclusion(:age, 18..100) + |> unique_constraint(:email) + end + end + + In the `changeset/2` function above, we define three validations. + They check that `name` and `email` fields are present in the + changeset, the e-mail is of the specified format, and the age is + between 18 and 100 - as well as a unique constraint in the email + field. + + Let's suppose the e-mail is given but the age is invalid. The + changeset would have the following errors: + + changeset = User.changeset(%User{}, %{age: 0, email: "mary@example.com"}) + {:error, changeset} = Repo.insert(changeset) + changeset.errors #=> [age: {"is invalid", []}, name: {"can't be blank", []}] + + In this case, we haven't checked the unique constraint in the + e-mail field because the data did not validate. Let's fix the + age and the name, and assume that the e-mail already exists in the + database: + + changeset = User.changeset(%User{}, %{age: 42, name: "Mary", email: "mary@example.com"}) + {:error, changeset} = Repo.insert(changeset) + changeset.errors #=> [email: {"has already been taken", []}] + + Validations and constraints define an explicit boundary when the check + happens. By moving constraints to the database, we also provide a safe, + correct and data-race free means of checking the user input. + + ### Deferred constraints + + Some databases support deferred constraints, i.e., constraints which are + checked at the end of the transaction rather than at the end of each statement. + + Changesets do not support this type of constraints. When working with deferred + constraints, a violation while invoking `c:Ecto.Repo.insert/2` or `c:Ecto.Repo.update/2` won't + return `{:error, changeset}`, but rather raise an error at the end of the + transaction. + + ## Empty values + + Many times, the data given on cast needs to be further pruned, specially + regarding empty values. For example, if you are gathering data to be + cast from the command line or through an HTML form or any other text-based + format, it is likely those means cannot express nil values. For + those reasons, changesets include the concept of empty values. + + When applying changes using `cast/4`, an empty value will be automatically + converted to the field's default value. If the field is an array type, any + empty value inside the array will be removed. When a plain map is used in + the data portion of a schemaless changeset, every field's default value is + considered to be `nil`. For example: + + iex> data = %{name: "Bob"} + iex> types = %{name: :string} + iex> params = %{name: ""} + iex> changeset = Ecto.Changeset.cast({data, types}, params, Map.keys(types)) + iex> changeset.changes + %{name: nil} + + Empty values are stored as a list in the changeset's `:empty_values` field. + The list contains elements of type `t:empty_value/0`. Those are either values, + which will be considered empty if they + match, or a function that must return a boolean if the value is empty or + not. By default, Ecto uses `Ecto.Changeset.empty_values/0` which will mark + a field as empty if it is a string made only of whitespace characters. + You can also pass the `:empty_values` option to `cast/4` in case you want + to change how a particular `cast/4` work. + + ## Associations, embeds, and on replace + + Using changesets you can work with associations as well as with embedded + structs. There are two primary APIs: + + * `cast_assoc/3` and `cast_embed/3` - those functions are used when + working with external data. In particular, they allow you to change + associations and embeds alongside the parent struct, all at once. + + * `put_assoc/4` and `put_embed/4` - it allows you to replace the + association or embed as a whole. This can be used to move associated + data from one entry to another, to completely remove or replace + existing entries. + + These functions are opinionated on how it works with associations. + If you need different behaviour or explicit control over the associated + data, you can skip this functionality and use `Ecto.Multi` to encode how + several database operations will happen on several schemas and changesets + at once. + + You can learn more about working with associations in our documentation, + including cheatsheets and practical examples. Check out: + + * The docs for `cast_assoc/3` and `put_assoc/3` + * The [associations cheatsheet](associations.html) + * The [Constraints and Upserts guide](constraints-and-upserts.html) + * The [Polymorphic associations with many to many guide](polymorphic-associations-with-many-to-many.html) + + ### The `:on_replace` option + + When using any of those APIs, you may run into situations where Ecto sees + data is being replaced. For example, imagine a Post has many Comments where + the comments have IDs 1, 2 and 3. If you call `cast_assoc/3` passing only + the IDs 1 and 2, Ecto will consider 3 is being "replaced" and it will raise + by default. Such behaviour can be changed when defining the relation by + setting `:on_replace` option when defining your association/embed according + to the values below: + + * `:raise` (default) - do not allow removing association or embedded + data via parent changesets + * `:mark_as_invalid` - if attempting to remove the association or + embedded data via parent changeset - an error will be added to the parent + changeset, and it will be marked as invalid + * `:nilify` - sets owner reference column to `nil` (available only for + associations). Use this on a `belongs_to` column to allow the association + to be cleared out so that it can be set to a new value. Will set `action` + on associated changesets to `:replace` + * `:update` - updates the association, available only for `has_one`, `belongs_to` + and `embeds_one`. This option will update all the fields given to the changeset + including the id for the association + * `:delete` - removes the association or related data from the database. + This option has to be used carefully (see below). Will set `action` on associated + changesets to `:replace` + * `:delete_if_exists` - like `:delete` except that it ignores any stale entry + error. For instance, if you set `on_replace: :delete` but the replaced + resource was already deleted by a separate request, it will raise a + `Ecto.StaleEntryError`. `:delete_if_exists` makes it so it will only delete + if the entry still exists + + The `:delete` and `:delete_if_exists` options must be used carefully as they allow + users to delete any associated data by simply setting it to `nil` or an empty list. + If you need deletion, it is often preferred to add a separate boolean virtual field + in the schema and manually mark the changeset for deletion if the `:delete` field is + set in the params, as in the example below. Note that we don't call `cast/4` in this + case because we don't want to prevent deletion if a change is invalid (changes are + irrelevant if the entity needs to be deleted). + + defmodule Comment do + use Ecto.Schema + import Ecto.Changeset + + schema "comments" do + field :body, :string + field :delete, :boolean, virtual: true + end + + def changeset(comment, %{"delete" => "true"}) do + %{Ecto.Changeset.change(comment, delete: true) | action: :delete} + end + + def changeset(comment, params) do + cast(comment, params, [:body]) + end + end + + ## Schemaless changesets + + In the changeset examples so far, we have always used changesets to validate + and cast data contained in a struct defined by an Ecto schema, such as the `%User{}` + struct defined by the `User` module. + + However, changesets can also be used with "regular" structs too by passing a tuple + with the data and its types: + + user = %User{} + types = %{name: :string, email: :string, age: :integer} + params = %{name: "Callum", email: "callum@example.com", age: 27} + changeset = + {user, types} + |> Ecto.Changeset.cast(params, Map.keys(types)) + |> Ecto.Changeset.validate_required(...) + |> Ecto.Changeset.validate_length(...) + + where the user struct refers to the definition in the following module: + + defmodule User do + defstruct [:name, :email, :age] + end + + Changesets can also be used with data in a plain map, by following the same API: + + data = %{} + types = %{name: :string, email: :string, age: :integer} + params = %{name: "Callum", email: "callum@example.com", age: 27} + changeset = + {data, types} + |> Ecto.Changeset.cast(params, Map.keys(types)) + |> Ecto.Changeset.validate_required(...) + |> Ecto.Changeset.validate_length(...) + + Besides the basic types which are mentioned above, such as `:boolean` and `:string`, + parameterized types can also be used in schemaless changesets. They implement + the `Ecto.ParameterizedType` behaviour and we can create the necessary type info by + calling the `init/2` function. + + For example, to use `Ecto.Enum` in a schemaless changeset: + + types = %{ + name: :string, + role: Ecto.ParameterizedType.init(Ecto.Enum, values: [:reader, :editor, :admin]) + } + + data = %{} + params = %{name: "Callum", role: "reader"} + + changeset = + {data, types} + |> Ecto.Changeset.cast(params, Map.keys(types)) + |> Ecto.Changeset.validate_required(...) + |> Ecto.Changeset.validate_length(...) + + Schemaless changesets make Ecto extremely useful to cast, validate and prune data even + if it is not meant to be persisted to the database. + + ### Changeset actions + + Changesets have an action field which is usually set by `Ecto.Repo` + whenever one of the operations such as `insert` or `update` is called: + + changeset = User.changeset(%User{}, %{age: 42, email: "mary@example.com"}) + {:error, changeset} = Repo.insert(changeset) + changeset.action + #=> :insert + + This means that when working with changesets that are not meant to be + persisted to the database, such as schemaless changesets, you may need + to explicitly set the action to one specific value. Frameworks such as + Phoenix [use the action value to define how HTML forms should + act](https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html#form/1-a-note-on-errors). + + Instead of setting the action manually, you may use `apply_action/2` that + emulates operations such as `c:Ecto.Repo.insert`. `apply_action/2` will return + `{:ok, changes}` if the changeset is valid or `{:error, changeset}`, with + the given `action` set in the changeset in case of errors. + + ## The Ecto.Changeset struct + + The public fields are: + + * `valid?` - Stores if the changeset is valid + * `data` - The changeset source data, for example, a struct + * `params` - The parameters as given on changeset creation + * `changes` - The `changes` from parameters that were approved in casting + * `errors` - All errors from validations + * `required` - All required fields as a list of atoms + * `action` - The action to be performed with the changeset + * `types` - Cache of the data's field types + * `empty_values` - A list of values to be considered empty + * `repo` - The repository applying the changeset (only set after a Repo function is called) + * `repo_opts` - A keyword list of options given to the underlying repository operation + + The following fields are private and must not be accessed directly. + + * `validations` + * `constraints` + * `filters` + * `prepare` + + ### Redacting fields in inspect + + To hide a field's value from the inspect protocol of `Ecto.Changeset`, mark + the field as `redact: true` in the schema, and it will display with the + value `**redacted**`. + """ + + require Logger + require Ecto.Query + alias __MODULE__ + alias Ecto.Changeset.Relation + alias Ecto.Schema.Metadata + + @empty_values [&Ecto.Type.empty_trimmed_string?/1] + + # If a new field is added here, def merge must be adapted + defstruct valid?: false, + data: nil, + params: nil, + changes: %{}, + errors: [], + validations: [], + required: [], + prepare: [], + constraints: [], + filters: %{}, + action: nil, + types: %{}, + empty_values: @empty_values, + repo: nil, + repo_opts: [] + + @type t(data_type) :: %Changeset{ + valid?: boolean(), + repo: atom | nil, + repo_opts: Keyword.t(), + data: data_type, + params: %{optional(String.t()) => term} | nil, + changes: %{optional(atom) => term}, + required: [atom], + prepare: [(t -> t)], + errors: [{atom, error}], + constraints: [constraint], + validations: [validation], + filters: %{optional(atom) => term}, + action: action, + types: types + } + + @type t :: t(Ecto.Schema.t() | map | nil) + @type error :: {String.t(), Keyword.t()} + @type action :: nil | :insert | :update | :delete | :replace | :ignore | atom + @type constraint :: %{ + type: :check | :exclusion | :foreign_key | :unique, + constraint: String.t() | Regex.t(), + match: :exact | :suffix | :prefix, + field: atom, + error_message: String.t(), + error_type: atom + } + @type data :: map() + @type types :: %{atom => Ecto.Type.t() | {:assoc, term()} | {:embed, term()}} + @type traverse_result :: %{atom => [term] | traverse_result} + @type validation :: {atom, term} + + @typedoc """ + A possible value that you can pass to the `:empty_values` option. + + See `empty_values/0` and the [*Empty values* section](#module-empty-values) in + the module documentation for more information. + """ + @typedoc since: "3.11.0" + @type empty_value :: (term() -> boolean()) | binary() | list() | map() | tuple() + + @number_validators %{ + less_than: {&/2, "must be greater than %{number}"}, + less_than_or_equal_to: {&<=/2, "must be less than or equal to %{number}"}, + greater_than_or_equal_to: {&>=/2, "must be greater than or equal to %{number}"}, + equal_to: {&==/2, "must be equal to %{number}"}, + not_equal_to: {&!=/2, "must be not equal to %{number}"} + } + + @relations [:embed, :assoc] + @match_types [:exact, :suffix, :prefix] + + @doc """ + Wraps the given data in a changeset or adds changes to a changeset. + + `changes` is a map or keyword where the key is an atom representing a + field, association or embed and the value is a term. Note the `value` is + directly stored in the changeset with no validation whatsoever. For this + reason, this function is meant for working with data internal to the + application. + + When changing embeds and associations, see `put_assoc/4` for a complete + reference on the accepted values. + + This function is useful for: + + * wrapping a struct inside a changeset + * directly changing a struct without performing castings nor validations + * directly bulk-adding changes to a changeset + + Changed attributes will only be added if the change does not have the + same value as the field in the data. + + When a changeset is passed as the first argument, the changes passed as the + second argument are merged over the changes already in the changeset if they + differ from the values in the struct. + + When a `{data, types}` is passed as the first argument, a changeset is + created with the given data and types and marked as valid. + + See `cast/4` if you'd prefer to cast and validate external parameters. + + ## Examples + + iex> changeset = change(%Post{}) + %Ecto.Changeset{...} + iex> changeset.valid? + true + iex> changeset.changes + %{} + + iex> changeset = change(%Post{author: "bar"}, title: "title") + iex> changeset.changes + %{title: "title"} + + iex> changeset = change(%Post{title: "title"}, title: "title") + iex> changeset.changes + %{} + + iex> changeset = change(changeset, %{title: "new title", body: "body"}) + iex> changeset.changes.title + "new title" + iex> changeset.changes.body + "body" + + """ + @spec change(Ecto.Schema.t() | t | {data, types}, %{atom => term} | Keyword.t()) :: t + def change(data, changes \\ %{}) + + def change({data, types}, changes) when is_map(data) do + change(%Changeset{data: data, types: Enum.into(types, %{}), valid?: true}, changes) + end + + def change(%Changeset{changes: changes, types: types} = changeset, new_changes) + when is_map(new_changes) or is_list(new_changes) do + {changes, errors, valid?} = + get_changed(changeset.data, types, changes, new_changes, changeset.errors, changeset.valid?) + + %{changeset | changes: changes, errors: errors, valid?: valid?} + end + + def change(%{__struct__: struct} = data, changes) when is_map(changes) or is_list(changes) do + types = struct.__changeset__() + {changes, errors, valid?} = get_changed(data, types, %{}, changes, [], true) + %Changeset{valid?: valid?, data: data, changes: changes, errors: errors, types: types} + end + + defp get_changed(data, types, old_changes, new_changes, errors, valid?) do + Enum.reduce(new_changes, {old_changes, errors, valid?}, fn + {key, value}, {changes, errors, valid?} -> + put_change(data, changes, errors, valid?, key, value, Map.get(types, key)) + + _, _ -> + raise ArgumentError, + "invalid changes being applied to changeset. " <> + "Expected a keyword list or a map, got: #{inspect(new_changes)}" + end) + end + + @doc """ + Returns true if a field was changed in a changeset. + + This function can check associations and embeds, but doesn't support the `:to` + and `:from` options for such fields. + + ## Options + + * `:to` - Check if the field was changed to a specific value + * `:from` - Check if the field was changed from a specific value + + ## Examples + + iex> post = %Post{title: "Foo", body: "Old"} + iex> changeset = change(post, %{title: "New title", body: "Old"}) + + iex> changed?(changeset, :body) + false + + iex> changed?(changeset, :title) + true + + iex> changed?(changeset, :title, to: "NEW TITLE") + false + """ + @spec changed?(t, atom, Keyword.t()) :: boolean + def changed?(%Changeset{} = changeset, field, opts \\ []) when is_atom(field) do + case Map.fetch(changeset.types, field) do + {:ok, type} -> + case fetch_change(changeset, field) do + {:ok, new_value} -> + case type do + {tag, relation} when tag in @relations -> + if opts != [] do + raise ArgumentError, "invalid options for #{tag} field" + end + + relation_changed?(relation.cardinality, new_value) + + _ -> + Enum.all?(opts, fn + {:from, from} -> + Ecto.Type.equal?(type, Map.get(changeset.data, field), from) + + {:to, to} -> + Ecto.Type.equal?(type, new_value, to) + + other -> + raise ArgumentError, "unknown option #{inspect(other)}" + end) + end + + :error -> + false + end + + :error -> + raise ArgumentError, "field #{inspect(field)} doesn't exist" + end + end + + defp relation_changed?(:one, changeset) do + changeset.action != :update or changeset.changes != %{} + end + + defp relation_changed?(:many, changesets) do + Enum.any?(changesets, &relation_changed?(:one, &1)) + end + + @doc """ + Returns the default empty values used by `Ecto.Changeset`. + + By default, Ecto marks a field as empty if it is a string made + only of whitespace characters. If you want to provide your + additional empty values on top of the default, such as an empty + list, you can write: + + @empty_values [[]] ++ Ecto.Changeset.empty_values() + + Then, you can pass `empty_values: @empty_values` on `cast/3`. + + See also the [*Empty values* section](#module-empty-values) for more + information. + """ + @doc since: "3.10.0" + @spec empty_values() :: [empty_value()] + def empty_values do + @empty_values + end + + @doc """ + Applies the given `params` as changes on the `data` according to + the set of `permitted` keys. Returns a changeset. + + `data` may be either a changeset, a schema struct or a `{data, types}` + tuple. The second argument is a map of `params` that are cast according + to the type information from `data`. `params` is a map with string keys + or a map with atom keys, containing potentially invalid data. Mixed keys + are not allowed. + + During casting, all `permitted` parameters whose values match the specified + type information will have their key name converted to an atom and stored + together with the value as a change in the `:changes` field of the changeset. + If the cast value matches the current value for the field, it will not be + included in `:changes` unless the `force_changes: true` option is + provided. All parameters that are not explicitly permitted are ignored. + + If casting of all fields is successful, the changeset is returned as valid. + + Note that `cast/4` validates the types in the `params`, but not in the given + `data`. + + ## Options + + * `:empty_values` - a list of values to be considered as empty when casting. + Empty values are always replaced by the default value of the respective field. + If the field is an array type, any empty value inside of the array will be removed. + To set this option while keeping the current default, use `empty_values/0` and add + your additional empty values + + * `:force_changes` - a boolean indicating whether to include values that don't alter + the current data in `:changes`. See `force_change/3` for more information, Defaults + to `false` + + * `:message` - a function of arity 2 that is used to create the error message when + casting fails. It is called for every field that cannot be casted and receives the + field name as the first argument and the error metadata as the second argument. It + must return a string or `nil`. If a string is returned it will be used as the error + message. If `nil` is returned the default error message will be used. The field type + is given under the `:type` key in the metadata + + ## Examples + + iex> changeset = cast(post, params, [:title]) + iex> if changeset.valid? do + ...> Repo.update!(changeset) + ...> end + + Passing a changeset as the first argument: + + iex> changeset = cast(post, %{title: "Hello"}, [:title]) + iex> new_changeset = cast(changeset, %{title: "Foo", body: "World"}, [:body]) + iex> new_changeset.params + %{"title" => "Hello", "body" => "World"} + + Or creating a changeset from a simple map with types: + + iex> data = %{title: "hello"} + iex> types = %{title: :string} + iex> changeset = cast({data, types}, %{title: "world"}, [:title]) + iex> apply_changes(changeset) + %{title: "world"} + + You can use empty values (and even cast multiple times) to change + what is considered an empty value: + + # Using default + iex> params = %{title: "", topics: []} + iex> changeset = cast(%Post{}, params, [:title, :topics]) + iex> changeset.changes + %{topics: []} + + # Changing default + iex> params = %{title: "", topics: []} + iex> changeset = cast(%Post{}, params, [:title, :topics], empty_values: [[], nil]) + iex> changeset.changes + %{title: ""} + + # Augmenting default + iex> params = %{title: "", topics: []} + iex> changeset = + ...> cast(%Post{}, params, [:title, :topics], empty_values: [[], nil] ++ Ecto.Changeset.empty_values()) + iex> changeset.changes + %{} + + You can define a custom error message function. + + # Using field name + iex> params = %{title: 1, body: 2} + iex> custom_errors = [title: "must be a string"] + iex> msg_func = fn field, _meta -> custom_errors[field] end + iex> changeset = cast(post, params, [:title, :body], message: msg_func) + iex> changeset.errors + [ + title: {"must be a string", [type: :string, validation: :cast]}, + body: {"is_invalid", [type: :string, validation: :cast]} + ] + + # Using field type + iex> params = %{title: 1, body: 2} + iex> custom_errors = [string: "must be a string"] + iex> msg_func = fn _field, meta -> + ... type = meta[:type] + ... custom_errors[type] + ... end + iex> changeset = cast(post, params, [:title, :body], message: msg_func) + iex> changeset.errors + [ + title: {"must be a string", [type: :string, validation: :cast]}, + body: {"must be a string", [type: :string, validation: :cast]} + ] + + ## Composing casts + + `cast/4` also accepts a changeset as its first argument. In such cases, all + the effects caused by the call to `cast/4` (additional errors and changes) + are simply added to the ones already present in the argument changeset. + Parameters are merged (**not deep-merged**) and the ones passed to `cast/4` + take precedence over the ones already in the changeset. + """ + @spec cast( + Ecto.Schema.t() | t | {data, types}, + %{binary => term} | %{atom => term} | :invalid, + [atom], + Keyword.t() + ) :: t + def cast(data, params, permitted, opts \\ []) + + def cast(_data, %{__struct__: _} = params, _permitted, _opts) do + raise Ecto.CastError, + type: :map, + value: params, + message: "expected params to be a :map, got: `#{inspect(params)}`" + end + + def cast({data, types}, params, permitted, opts) when is_map(data) do + cast(data, types, %{}, params, permitted, opts) + end + + def cast(%Changeset{} = changeset, params, permitted, opts) do + %{changes: changes, data: data, types: types, empty_values: empty_values} = changeset + + opts = + cond do + opts[:empty_values] -> + opts + + empty_values != empty_values() -> + # TODO: Remove changeset.empty_values field in Ecto v3.14 + IO.warn( + "Changing the empty_values field of Ecto.Changeset is deprecated, " <> + "please pass the :empty_values option on cast instead" + ) + + [empty_values: empty_values] ++ opts + + true -> + [empty_values: empty_values] ++ opts + end + + new_changeset = cast(data, types, changes, params, permitted, opts) + cast_merge(changeset, new_changeset) + end + + def cast(%{__struct__: module} = data, params, permitted, opts) do + cast(data, module.__changeset__(), %{}, params, permitted, opts) + end + + defp cast(%{} = data, %{} = types, %{} = changes, :invalid, permitted, _opts) + when is_list(permitted) do + _ = Enum.each(permitted, &cast_key/1) + %Changeset{params: nil, data: data, valid?: false, errors: [], changes: changes, types: types} + end + + defp cast(%{} = data, %{} = types, %{} = changes, %{} = params, permitted, opts) + when is_list(permitted) do + empty_values = Keyword.get(opts, :empty_values, @empty_values) + force? = Keyword.get(opts, :force_changes, false) + params = convert_params(params) + msg_func = Keyword.get(opts, :message, fn _, _ -> nil end) + + unless is_function(msg_func, 2) do + raise ArgumentError, + "expected `:message` to be a function of arity 2, received: #{inspect(msg_func)}" + end + + defaults = + case data do + %{__struct__: struct} -> struct.__struct__() + %{} -> %{} + end + + {changes, errors, valid?} = + Enum.reduce( + permitted, + {changes, [], true}, + &process_param(&1, params, types, data, empty_values, defaults, force?, msg_func, &2) + ) + + %Changeset{ + params: params, + data: data, + valid?: valid?, + errors: Enum.reverse(errors), + changes: changes, + types: types + } + end + + defp cast(%{}, %{}, %{}, params, permitted, _opts) when is_list(permitted) do + raise Ecto.CastError, + type: :map, + value: params, + message: "expected params to be a :map, got: `#{inspect(params)}`" + end + + defp process_param( + key, + params, + types, + data, + empty_values, + defaults, + force?, + msg_func, + {changes, errors, valid?} + ) do + {key, param_key} = cast_key(key) + type = cast_type!(types, key) + + current = + case changes do + %{^key => value} -> value + _ -> Map.get(data, key) + end + + case cast_field(key, param_key, type, params, current, empty_values, defaults, force?, valid?) do + {:ok, value, valid?} -> + {Map.put(changes, key, value), errors, valid?} + + :missing -> + {changes, errors, valid?} + + {:invalid, custom_errors} -> + {default_message, metadata} = + custom_errors + |> Keyword.put_new(:validation, :cast) + |> Keyword.put(:type, type) + |> Keyword.pop(:message, "is invalid") + + message = + case msg_func.(key, metadata) do + nil -> default_message + user_message -> user_message + end + + {changes, [{key, {message, metadata}} | errors], false} + end + end + + defp cast_type!(types, key) do + case types do + %{^key => {tag, _}} when tag in @relations -> + raise "casting #{tag}s with cast/4 for #{inspect(key)} field is not supported, use cast_#{tag}/3 instead" + + %{^key => type} -> + type + + _ -> + known_fields = types |> Map.keys() |> Enum.map_join(", ", &inspect/1) + + raise ArgumentError, + "unknown field `#{inspect(key)}` given to cast. Either the field does not exist or it is a " <> + ":through association (which are read-only). The known fields are: #{known_fields}" + end + end + + defp cast_key(key) when is_atom(key), + do: {key, Atom.to_string(key)} + + defp cast_key(key) do + raise ArgumentError, "cast/3 expects a list of atom keys, got key: `#{inspect(key)}`" + end + + defp cast_field(key, param_key, type, params, current, empty_values, defaults, force?, valid?) do + case params do + %{^param_key => value} -> + value = filter_empty_values(type, value, empty_values, defaults, key) + + case Ecto.Type.cast(type, value) do + {:ok, value} -> + if not force? and Ecto.Type.equal?(type, current, value) do + :missing + else + {:ok, value, valid?} + end + + :error -> + {:invalid, []} + + {:error, custom_errors} when is_list(custom_errors) -> + {:invalid, custom_errors} + end + + _ -> + :missing + end + end + + defp filter_empty_values(type, value, empty_values, defaults, key) do + case filter_empty_values(type, value, empty_values) do + :empty -> Map.get(defaults, key) + {:ok, value} -> value + end + end + + defp filter_empty_values({:array, type}, value, empty_values) when is_list(value) do + value = + for elem <- value, + {:ok, elem} <- [filter_empty_values(type, elem, empty_values)], + do: elem + + if value in empty_values do + :empty + else + {:ok, value} + end + end + + defp filter_empty_values(_type, value, empty_values) do + filter_empty_value(empty_values, value) + end + + defp filter_empty_value([head | tail], value) when is_function(head) do + case head.(value) do + true -> :empty + false -> filter_empty_value(tail, value) + end + end + + defp filter_empty_value([value | _tail], value), + do: :empty + + defp filter_empty_value([_head | tail], value), + do: filter_empty_value(tail, value) + + defp filter_empty_value([], value), + do: {:ok, value} + + # We only look at the first element because traversing the whole map + # can be expensive and it was showing up during profiling. This means + # we won't always raise, but the check only exists for user convenience + # anyway, and it is not a guarantee. + defp convert_params(params) do + case :maps.next(:maps.iterator(params)) do + {key, _, _} when is_atom(key) -> + for {key, value} <- params, into: %{} do + if is_atom(key) do + {Atom.to_string(key), value} + else + raise Ecto.CastError, + type: :map, + value: params, + message: + "expected params to be a map with atoms or string keys, " <> + "got a map with mixed keys: #{inspect(params)}" + end + end + + _ -> + params + end + end + + ## Casting related + + @doc """ + Casts the given association with the changeset parameters. + + This function should be used when working with the entire association at + once (and not a single element of a many-style association) and receiving + data external to the application. + + `cast_assoc/3` matches the records extracted from the database + and compares it with the parameters received from an external source. + Therefore, it is expected that the data in the changeset has explicitly + preloaded the association being cast and that all of the IDs exist and + are unique. + + For example, imagine a user has many addresses relationship where + post data is sent as follows + + %{"name" => "john doe", "addresses" => [ + %{"street" => "somewhere", "country" => "brazil", "id" => 1}, + %{"street" => "elsewhere", "country" => "poland"}, + ]} + + and then + + User + |> Repo.get!(id) + |> Repo.preload(:addresses) # Only required when updating data + |> Ecto.Changeset.cast(params, []) + |> Ecto.Changeset.cast_assoc(:addresses, with: &MyApp.Address.changeset/2) + + The parameters for the given association will be retrieved + from `changeset.params`. Those parameters are expected to be + a map with attributes, similar to the ones passed to `cast/4`. + Once parameters are retrieved, `cast_assoc/3` will match those + parameters with the associations already in the changeset data. + + Once `cast_assoc/3` is called, Ecto will compare each parameter + with the user's already preloaded addresses and act as follows: + + * If the parameter does not contain an ID, the parameter data + will be passed to `MyApp.Address.changeset/2` with a new struct + and become an insert operation. We only consider the ID as not + given if there is no "id" key or if its value is strictly `nil` + + * If the parameter contains an ID and there is no associated child + with such ID, the parameter data will be passed to + `MyApp.Address.changeset/2` with a new struct and become an insert + operation + + * If the parameter contains an ID and there is an associated child + with such ID, the parameter data will be passed to + `MyApp.Address.changeset/2` with the existing struct and become an + update operation + + * If there is an associated child with an ID and its ID is not given + as parameter, the `:on_replace` callback for that association will + be invoked (see the ["On replace" section](#module-the-on_replace-option) + on the module documentation) + + If two or more addresses have the same IDs, Ecto will consider that an + error and add an error to the changeset saying that there are duplicate + entries. + + Every time the `MyApp.Address.changeset/2` function is invoked, it must + return a changeset. This changeset will always be included under `changes` + of the parent changeset, even if there are no changes. This is done for + reflection purposes, allowing developers to introspect validations and + other metadata from the association. Once the parent changeset is given + to an `Ecto.Repo` function, all entries will be inserted/updated/deleted + within the same transaction. + + As you see above, this function is opinionated on how it works. If you + need different behaviour or if you need explicit control over the associated + data, you can either use `put_assoc/4` or use `Ecto.Multi` to encode how + several database operations will happen on several schemas and changesets + at once. + + ## Custom actions + + Developers are allowed to explicitly set the `:action` field of a + changeset to instruct Ecto how to act in certain situations. Let's suppose + that, if one of the associations has only empty fields, you want to ignore + the entry altogether instead of showing an error. The changeset function could + be written like this: + + def changeset(struct, params) do + struct + |> cast(params, [:title, :body]) + |> validate_required([:title, :body]) + |> case do + %{valid?: false, changes: changes} = changeset when changes == %{} -> + # If the changeset is invalid and has no changes, it is + # because all required fields are missing, so we ignore it. + %{changeset | action: :ignore} + changeset -> + changeset + end + end + + You can also set it to delete if you want data to be deleted based on the + received parameters (such as a checkbox or any other indicator). + + ## Partial changes for many-style associations + + By preloading an association using a custom query you can confine the behavior + of `cast_assoc/3`. This opens up the possibility to work on a subset of the data, + instead of all associations in the database. + + Taking the initial example of users having addresses, imagine those addresses + are set up to belong to a country. If you want to allow users to bulk edit all + addresses that belong to a single country, you can do so by changing the preload + query: + + query = from MyApp.Address, where: [country: ^edit_country] + + User + |> Repo.get!(id) + |> Repo.preload(addresses: query) + |> Ecto.Changeset.cast(params, []) + |> Ecto.Changeset.cast_assoc(:addresses) + + This will allow you to cast and update only the association for the given country. + The important point for partial changes is that any addresses, which were not + preloaded won't be changed. + + ## Sorting and deleting from -many collections + + In earlier examples, we passed a -many style association as a list: + + %{"name" => "john doe", "addresses" => [ + %{"street" => "somewhere", "country" => "brazil", "id" => 1}, + %{"street" => "elsewhere", "country" => "poland"}, + ]} + + However, it is also common to pass the addresses as a map, where each + key is an integer representing its position: + + %{"name" => "john doe", "addresses" => %{ + 0 => %{"street" => "somewhere", "country" => "brazil", "id" => 1}, + 1 => %{"street" => "elsewhere", "country" => "poland"} + }} + + Using indexes becomes specially useful with two supporting options: + `:sort_param` and `:drop_param`. These options tell the indexes should + be reordered or deleted from the data. For example, if you did: + + cast_embed(changeset, :addresses, + sort_param: :addresses_sort, + drop_param: :addresses_drop) + + You can now submit this: + + %{"name" => "john doe", "addresses" => %{...}, "addresses_drop" => [0]} + + And now the entry with index 0 will be dropped from the params before casting. + Note this requires setting the relevant `:on_replace` option on your + associations/embeds definition. + + Similar, for sorting, you could do: + + %{"name" => "john doe", "addresses" => %{...}, "addresses_sort" => [1, 0]} + + And that will internally sort the elements so 1 comes before 0. Note that + any index not present in `"addresses_sort"` will come _before_ any of the + sorted indexes. If an index is not found, an empty entry is added in its + place. + + For embeds, this guarantees the embeds will be rewritten in the given order. + However, for associations, this is not enough. You will have to add a + `field :position, :integer` to the schema and add a with function of arity 3 + to add the position to your children changeset. For example, you could implement: + + defp child_changeset(child, _changes, position) do + child + |> change(position: position) + end + + And by passing it to `:with`, it will be called with the final position of the + item: + + changeset + |> cast_assoc(:children, sort_param: ..., with: &child_changeset/3) + + These parameters can be powerful in certain UIs as it allows you to decouple + the sorting and replacement of the data from its representation. + + ## More resources + + You can learn more about working with associations in our documentation, + including cheatsheets and practical examples. Check out: + + * The docs for `put_assoc/3` + * The [associations cheatsheet](associations.html) + * The [Constraints and Upserts guide](constraints-and-upserts.html) + * The [Polymorphic associations with many to many guide](polymorphic-associations-with-many-to-many.html) + + ## Options + + * `:required` - if the association is a required field. For associations of cardinality + one, a non-nil value satisfies this validation. For associations with many entries, + a non-empty list is satisfactory. + + * `:required_message` - the message on failure, defaults to "can't be blank" + + * `:invalid_message` - the message on failure, defaults to "is invalid" + + * `:force_update_on_change` - force the parent record to be updated in the + repository if there is a change, defaults to `true` + + * `:with` - the function to build the changeset from params. Defaults to the + `changeset/2` function of the associated module. It can be an anonymous + function that expects two arguments: the associated struct to be cast and its + parameters. It must return a changeset. For associations with cardinality `:many`, + functions with arity 3 are accepted, and the third argument will be the position + of the associated element in the list, or `nil`, if the association is being replaced. + + * `:drop_param` - the parameter name which keeps a list of indexes to drop + from the relation parameters + + * `:sort_param` - the parameter name which keeps a list of indexes to sort + from the relation parameters. Unknown indexes are considered to be new + entries. Non-listed indexes will come before any sorted ones. See + `cast_assoc/3` for more information + + """ + @spec cast_assoc(t, atom, Keyword.t()) :: t + def cast_assoc(changeset, name, opts \\ []) when is_atom(name) do + cast_relation(:assoc, changeset, name, opts) + end + + @doc """ + Casts the given embed with the changeset parameters. + + The parameters for the given embed will be retrieved + from `changeset.params`. Those parameters are expected to be + a map with attributes, similar to the ones passed to `cast/4`. + Once parameters are retrieved, `cast_embed/3` will match those + parameters with the embeds already in the changeset record. + See `cast_assoc/3` for an example of working with casts and + associations which would also apply for embeds. + + The changeset must have been previously `cast` using + `cast/4` before this function is invoked. + + ## Options + + * `:required` - if the embed is a required field. For embeds of cardinality + one, a non-nil value satisfies this validation. For embeds with many entries, + a non-empty list is satisfactory. + + * `:required_message` - the message on failure, defaults to "can't be blank" + + * `:invalid_message` - the message on failure, defaults to "is invalid" + + * `:force_update_on_change` - force the parent record to be updated in the + repository if there is a change, defaults to `true` + + * `:with` - the function to build the changeset from params. Defaults to the + `changeset/2` function of the associated module. It must be an anonymous + function that expects two arguments: the embedded struct to be cast and its + parameters. It must return a changeset. For embeds with cardinality `:many`, + functions with arity 3 are accepted, and the third argument will be the position + of the associated element in the list, or `nil`, if the embed is being replaced. + + * `:drop_param` - the parameter name which keeps a list of indexes to drop + from the relation parameters + + * `:sort_param` - the parameter name which keeps a list of indexes to sort + from the relation parameters. Unknown indexes are considered to be new + entries. Non-listed indexes will come before any sorted ones. See + `cast_assoc/3` for more information + + """ + @spec cast_embed(t, atom, Keyword.t()) :: t + def cast_embed(changeset, name, opts \\ []) when is_atom(name) do + cast_relation(:embed, changeset, name, opts) + end + + defp cast_relation(type, %Changeset{data: data, types: types}, _name, _opts) + when data == nil or types == nil do + raise ArgumentError, + "cast_#{type}/3 expects the changeset to be cast. " <> + "Please call cast/4 before calling cast_#{type}/3" + end + + defp cast_relation(type, %Changeset{} = changeset, key, opts) do + {key, param_key} = cast_key(key) + %{data: data, types: types, params: params, changes: changes} = changeset + %{related: related} = relation = relation!(:cast, type, key, Map.get(types, key)) + params = params || %{} + + {changeset, required?} = + if opts[:required] do + {update_in(changeset.required, &[key | &1]), true} + else + {changeset, false} + end + + on_cast = Keyword.get_lazy(opts, :with, fn -> on_cast_default(type, related) end) + sort = opts_key_from_params(:sort_param, opts, params) + drop = opts_key_from_params(:drop_param, opts, params) + + changeset = + if is_map_key(params, param_key) or is_list(sort) or is_list(drop) do + value = Map.get(params, param_key) + original = Map.get(data, key) + current = Relation.load!(data, original) + value = cast_params(relation, value, sort, drop) + + case Relation.cast(relation, data, value, current, on_cast) do + {:ok, change, relation_valid?} when change != original -> + valid? = changeset.valid? and relation_valid? + changes = Map.put(changes, key, change) + changeset = %{force_update(changeset, opts) | changes: changes, valid?: valid?} + missing_relation(changeset, key, current, required?, relation, opts) + + {:error, {message, meta}} -> + meta = [validation: type] ++ meta + error = {key, message(opts, :invalid_message, message, meta)} + %{changeset | errors: [error | changeset.errors], valid?: false} + + # ignore or ok with change == original + _ -> + missing_relation(changeset, key, current, required?, relation, opts) + end + else + missing_relation(changeset, key, Map.get(data, key), required?, relation, opts) + end + + update_in(changeset.types[key], fn {type, relation} -> + {type, %{relation | on_cast: on_cast}} + end) + end + + defp cast_params(%{cardinality: :many} = relation, nil, sort, drop) + when is_list(sort) or is_list(drop) do + cast_params(relation, %{}, sort, drop) + end + + defp cast_params(%{cardinality: :many}, value, sort, drop) when is_map(value) do + drop = if is_list(drop), do: drop, else: [] + + {sorted, pending} = + if is_list(sort) do + Enum.map_reduce(sort -- drop, value, &Map.pop(&2, &1, %{})) + else + {[], value} + end + + sorted ++ + (pending + |> Map.drop(drop) + |> Enum.map(&key_as_int/1) + |> Enum.sort() + |> Enum.map(&elem(&1, 1))) + end + + defp cast_params(%{cardinality: :one}, value, sort, drop) do + if sort do + raise ArgumentError, ":sort_param not supported for belongs_to/has_one" + end + + if drop do + raise ArgumentError, ":drop_param not supported for belongs_to/has_one" + end + + value + end + + defp cast_params(_relation, value, _sort, _drop) do + value + end + + defp opts_key_from_params(opt, opts, params) do + if key = opts[opt] do + Map.get(params, Atom.to_string(key), nil) + end + end + + # We check for the byte size to avoid creating unnecessary large integers + # which would never map to a database key (u64 is 20 digits only). + defp key_as_int({key, val}) when is_binary(key) and byte_size(key) < 32 do + case Integer.parse(key) do + {key, ""} -> {key, val} + _ -> {key, val} + end + end + + defp key_as_int(key_val), do: key_val + + defp on_cast_default(type, module) do + fn struct, params -> + try do + module.changeset(struct, params) + rescue + e in UndefinedFunctionError -> + case __STACKTRACE__ do + [{^module, :changeset, args_or_arity, _}] + when args_or_arity == 2 + when length(args_or_arity) == 2 -> + raise ArgumentError, """ + the module #{inspect(module)} does not define a changeset/2 function, + which is used by cast_#{type}/3. You need to either: + + 1. implement the #{type}.changeset/2 function + 2. pass the :with option to cast_#{type}/3 with an anonymous + function of arity 2 (or possibly arity 3, if using has_many or + embeds_many) + + When using an inline embed, the :with option must be given + """ + + stacktrace -> + reraise e, stacktrace + end + end + end + end + + defp missing_relation(changeset, name, current, required?, relation, opts) do + %{changes: changes, errors: errors} = changeset + current_changes = Map.get(changes, name, current) + + if required? and Relation.empty?(relation, current_changes) do + errors = [ + {name, message(opts, :required_message, "can't be blank", validation: :required)} + | errors + ] + + %{changeset | errors: errors, valid?: false} + else + changeset + end + end + + defp relation!(_op, type, _name, {type, relation}), + do: relation + + defp relation!(op, :assoc, name, nil) do + raise ArgumentError, + "cannot #{op} assoc `#{name}`, assoc `#{name}` not found. Make sure it is spelled correctly and that the association type is not read-only" + end + + defp relation!(op, type, name, nil) do + raise ArgumentError, + "cannot #{op} #{type} `#{name}`, #{type} `#{name}` not found. Make sure that it exists and is spelled correctly" + end + + defp relation!(op, type, name, {other, _}) when other in @relations do + raise ArgumentError, + "expected `#{name}` to be an #{type} in `#{op}_#{type}`, got: `#{other}`" + end + + defp relation!(op, type, name, schema_type) do + raise ArgumentError, + "expected `#{name}` to be an #{type} in `#{op}_#{type}`, got: `#{inspect(schema_type)}`" + end + + defp force_update(changeset, opts) do + if Keyword.get(opts, :force_update_on_change, true) do + put_in(changeset.repo_opts[:force], true) + else + changeset + end + end + + ## Working with changesets + + @doc """ + Merges two changesets. + + This function merges two changesets provided they have been applied to the + same data (their `:data` field is equal); if the data differs, an + `ArgumentError` exception is raised. If one of the changesets has a `:repo` + field which is not `nil`, then the value of that field is used as the `:repo` + field of the resulting changeset; if both changesets have a non-`nil` and + different `:repo` field, an `ArgumentError` exception is raised. + + The other fields are merged with the following criteria: + + * `params` - params are merged (not deep-merged) giving precedence to the + params of `changeset2` in case of a conflict. If both changesets have their + `:params` fields set to `nil`, the resulting changeset will have its params + set to `nil` too. + * `changes` - changes are merged giving precedence to the `changeset2` + changes. + * `errors` and `validations` - they are simply concatenated. + * `required` - required fields are merged; all the fields that appear + in the required list of both changesets are moved to the required + list of the resulting changeset. + + ## Examples + + iex> changeset1 = cast(%Post{}, %{title: "Title"}, [:title]) + iex> changeset2 = cast(%Post{}, %{title: "New title", body: "Body"}, [:title, :body]) + iex> changeset = merge(changeset1, changeset2) + iex> changeset.changes + %{body: "Body", title: "New title"} + + iex> changeset1 = cast(%Post{body: "Body"}, %{title: "Title"}, [:title]) + iex> changeset2 = cast(%Post{}, %{title: "New title"}, [:title]) + iex> merge(changeset1, changeset2) + ** (ArgumentError) different :data when merging changesets + + """ + @spec merge(t, t) :: t + def merge(changeset1, changeset2) + + def merge(%Changeset{data: data} = cs1, %Changeset{data: data} = cs2) do + new_repo = merge_identical(cs1.repo, cs2.repo, "repos") + new_repo_opts = Keyword.merge(cs1.repo_opts, cs2.repo_opts) + new_action = merge_identical(cs1.action, cs2.action, "actions") + new_filters = Map.merge(cs1.filters, cs2.filters) + new_validations = cs1.validations ++ cs2.validations + new_constraints = cs1.constraints ++ cs2.constraints + + cast_merge( + %{ + cs1 + | repo: new_repo, + repo_opts: new_repo_opts, + filters: new_filters, + action: new_action, + validations: new_validations, + constraints: new_constraints + }, + cs2 + ) + end + + def merge(%Changeset{}, %Changeset{}) do + raise ArgumentError, message: "different :data when merging changesets" + end + + defp cast_merge(cs1, cs2) do + new_params = (cs1.params || cs2.params) && Map.merge(cs1.params || %{}, cs2.params || %{}) + new_types = Map.merge(cs1.types, cs2.types) + new_changes = Map.merge(cs1.changes, cs2.changes) + new_errors = Enum.uniq(cs1.errors ++ cs2.errors) + new_required = Enum.uniq(cs1.required ++ cs2.required) + new_valid? = cs1.valid? and cs2.valid? + + %{ + cs1 + | params: new_params, + valid?: new_valid?, + errors: new_errors, + types: new_types, + changes: new_changes, + required: new_required + } + end + + defp merge_identical(object, nil, _thing), do: object + defp merge_identical(nil, object, _thing), do: object + defp merge_identical(object, object, _thing), do: object + + defp merge_identical(lhs, rhs, thing) do + raise ArgumentError, + "different #{thing} (`#{inspect(lhs)}` and " <> + "`#{inspect(rhs)}`) when merging changesets" + end + + @doc """ + Fetches the given field from changes or from the data. + + While `fetch_change/2` only looks at the current `changes` + to retrieve a value, this function looks at the changes and + then falls back on the data, finally returning `:error` if + no value is available. + + For relations, these functions will return the changeset + original data with changes applied. To retrieve raw changesets, + please use `fetch_change/2`. + + ## Examples + + iex> post = %Post{title: "Foo", body: "Bar baz bong"} + iex> changeset = change(post, %{title: "New title"}) + iex> fetch_field(changeset, :title) + {:changes, "New title"} + iex> fetch_field(changeset, :body) + {:data, "Bar baz bong"} + iex> fetch_field(changeset, :not_a_field) + :error + + """ + @spec fetch_field(t, atom) :: {:changes, term} | {:data, term} | :error + def fetch_field(%Changeset{changes: changes, data: data, types: types}, key) + when is_atom(key) do + case Map.fetch(changes, key) do + {:ok, value} -> + {:changes, change_as_field(types, key, value)} + + :error -> + case Map.fetch(data, key) do + {:ok, value} -> {:data, data_as_field(data, types, key, value)} + :error -> :error + end + end + end + + @doc """ + Same as `fetch_field/2` but returns the value or raises if the given key was not found. + + ## Examples + + iex> post = %Post{title: "Foo", body: "Bar baz bong"} + iex> changeset = change(post, %{title: "New title"}) + iex> fetch_field!(changeset, :title) + "New title" + iex> fetch_field!(changeset, :other) + ** (KeyError) key :other not found in: %Post{...} + """ + @spec fetch_field!(t, atom) :: term + def fetch_field!(changeset, key) do + case fetch_field(changeset, key) do + {_, value} -> + value + + :error -> + raise KeyError, key: key, term: changeset.data + end + end + + @doc """ + Gets a field from changes or from the data. + + While `get_change/3` only looks at the current `changes` + to retrieve a value, this function looks at the changes and + then falls back on the data, finally returning `default` if + no value is available. + + For associations and embeds, this function always returns + nil, a struct, or a list of structs. In case of changes, + the changeset data will have all data applies. This guarantees + a consistent result regardless if changes have been applied + or not. Use `get_change/2` or `get_assoc/3`/`get_embed/3` + if you want to retrieve the relations as changesets or + if you want more fine-grained control. + + iex> post = %Post{title: "A title", body: "My body is a cage"} + iex> changeset = change(post, %{title: "A new title"}) + iex> get_field(changeset, :title) + "A new title" + iex> get_field(changeset, :not_a_field, "Told you, not a field!") + "Told you, not a field!" + + """ + @spec get_field(t, atom, term) :: term + def get_field(%Changeset{changes: changes, data: data, types: types}, key, default \\ nil) do + case changes do + %{^key => value} -> + change_as_field(types, key, value) + + %{} -> + case data do + %{^key => value} -> data_as_field(data, types, key, value) + %{} -> default + end + end + end + + defp change_as_field(types, key, value) do + case types do + %{^key => {tag, relation}} when tag in @relations -> + Relation.apply_changes(relation, value) + + %{} -> + value + end + end + + defp data_as_field(data, types, key, value) do + case types do + %{^key => {tag, _relation}} when tag in @relations -> + Relation.load!(data, value) + + %{} -> + value + end + end + + @doc """ + Gets the association entry or entries from changes or from the data. + + Returned data is normalized to changesets by default. Pass the `:struct` + flag to retrieve the data as structs with changes applied, similar to `get_field/2`. + + ## Examples + + iex> %Author{posts: [%Post{id: 1, title: "hello"}]} + ...> |> change() + ...> |> get_assoc(:posts) + [%Ecto.Changeset{data: %Post{id: 1, title: "hello"}, changes: %{}}] + + iex> %Author{posts: [%Post{id: 1, title: "hello"}]} + ...> |> cast(%{posts: [%{id: 1, title: "world"}]}, []) + ...> |> cast_assoc(:posts) + ...> |> get_assoc(:posts, :changeset) + [%Ecto.Changeset{data: %Post{id: 1, title: "hello"}, changes: %{title: "world"}}] + + iex> %Author{posts: [%Post{id: 1, title: "hello"}]} + ...> |> cast(%{posts: [%{id: 1, title: "world"}]}, []) + ...> |> cast_assoc(:posts) + ...> |> get_assoc(:posts, :struct) + [%Post{id: 1, title: "world"}] + + """ + @spec get_assoc(t, atom, :changeset | :struct) :: + [t | Ecto.Schema.t()] | t | Ecto.Schema.t() | nil + def get_assoc(changeset, name, as \\ :changeset) + + def get_assoc(%Changeset{} = changeset, name, :struct) do + get_field(changeset, name) + end + + def get_assoc(%Changeset{} = changeset, name, :changeset) do + get_relation(:assoc, changeset, name) + end + + @doc """ + Gets the embedded entry or entries from changes or from the data. + + Returned data is normalized to changesets by default. Pass the `:struct` + flag to retrieve the data as structs with changes applied, similar to `get_field/2`. + + ## Examples + + iex> %Post{comments: [%Comment{id: 1, body: "hello"}]} + ...> |> change() + ...> |> get_embed(:comments) + [%Ecto.Changeset{data: %Comment{id: 1, body: "hello"}, changes: %{}}] + + iex> %Post{comments: [%Comment{id: 1, body: "hello"}]} + ...> |> cast(%{comments: [%{id: 1, body: "world"}]}, []) + ...> |> cast_embed(:comments) + ...> |> get_embed(:comments, :changeset) + [%Ecto.Changeset{data: %Comment{id: 1, body: "hello"}, changes: %{body: "world"}}] + + iex> %Post{comments: [%Comment{id: 1, body: "hello"}]} + ...> |> cast(%{comments: [%{id: 1, body: "world"}]}, []) + ...> |> cast_embed(:comments) + ...> |> get_embed(:comments, :struct) + [%Comment{id: 1, body: "world"}] + + """ + def get_embed(changeset, name, as \\ :changeset) + + def get_embed(%Changeset{} = changeset, name, :struct) do + get_field(changeset, name) + end + + def get_embed(%Changeset{} = changeset, name, :changeset) do + get_relation(:embed, changeset, name) + end + + defp get_relation(tag, %{changes: changes, data: data, types: types}, name) do + _ = relation!(:get, tag, name, Map.get(types, name)) + + existing = + case changes do + %{^name => value} -> value + %{} -> Relation.load!(data, Map.fetch!(data, name)) + end + + case existing do + nil -> nil + list when is_list(list) -> Enum.map(list, &change/1) + item -> change(item) + end + end + + @doc """ + Fetches a change from the given changeset. + + This function only looks at the `:changes` field of the given `changeset` and + returns `{:ok, value}` if the change is present or `:error` if it's not. + + ## Examples + + iex> changeset = change(%Post{body: "foo"}, %{title: "bar"}) + iex> fetch_change(changeset, :title) + {:ok, "bar"} + iex> fetch_change(changeset, :body) + :error + + """ + @spec fetch_change(t, atom) :: {:ok, term} | :error + def fetch_change(%Changeset{changes: changes} = _changeset, key) when is_atom(key) do + Map.fetch(changes, key) + end + + @doc """ + Same as `fetch_change/2` but returns the value or raises if the given key was not found. + + ## Examples + + iex> changeset = change(%Post{body: "foo"}, %{title: "bar"}) + iex> fetch_change!(changeset, :title) + "bar" + iex> fetch_change!(changeset, :body) + ** (KeyError) key :body not found in: %{title: "bar"} + """ + @spec fetch_change!(t, atom) :: term + def fetch_change!(changeset, key) do + case fetch_change(changeset, key) do + {:ok, value} -> + value + + :error -> + raise KeyError, key: key, term: changeset.changes + end + end + + @doc """ + Gets a change or returns a default value. + + For associations and embeds, this function always returns + nil, a changeset, or a list of changesets. + + ## Examples + + iex> changeset = change(%Post{body: "foo"}, %{title: "bar"}) + iex> get_change(changeset, :title) + "bar" + iex> get_change(changeset, :body) + nil + + """ + @spec get_change(t, atom, term) :: term + def get_change(%Changeset{changes: changes} = _changeset, key, default \\ nil) + when is_atom(key) do + Map.get(changes, key, default) + end + + @doc """ + Updates a change. + + The given `function` is invoked with the change value only if there + is a change for `key`. Once the function is invoked, it behaves as + `put_change/3`. + + Note that the value of the change can still be `nil` (unless the field + was marked as required on `validate_required/3`). + + ## Examples + + iex> changeset = change(%Post{}, %{impressions: 1}) + iex> changeset = update_change(changeset, :impressions, &(&1 + 1)) + iex> changeset.changes.impressions + 2 + + """ + @spec update_change(t, atom, (term -> term)) :: t + def update_change(%Changeset{changes: changes} = changeset, key, function) when is_atom(key) do + case Map.fetch(changes, key) do + {:ok, value} -> + put_change(changeset, key, function.(value)) + + :error -> + changeset + end + end + + @doc """ + Puts a change on the given `key` with `value`. + + `key` is an atom that represents any field, embed or + association in the changeset. Note the `value` is directly + stored in the changeset with no validation whatsoever. + For this reason, this function is meant for working with + data internal to the application. + + If the change is already present, it is overridden with + the new value. If the change has the same value as in the + changeset data, no changes are added (and any existing + changes are removed). + + When changing embeds and associations, see `put_assoc/4` + for a complete reference on the accepted values. + + ## Examples + + iex> changeset = change(%Post{}, %{title: "foo"}) + iex> changeset = put_change(changeset, :title, "bar") + iex> changeset.changes + %{title: "bar"} + + iex> changeset = change(%Post{title: "foo"}) + iex> changeset = put_change(changeset, :title, "foo") + iex> changeset.changes + %{} + + """ + @spec put_change(t, atom, term) :: t + def put_change(%Changeset{data: data, types: types} = changeset, key, value) do + type = Map.get(types, key) + + {changes, errors, valid?} = + put_change(data, changeset.changes, changeset.errors, changeset.valid?, key, value, type) + + %{changeset | changes: changes, errors: errors, valid?: valid?} + end + + defp put_change(data, changes, errors, valid?, key, value, {tag, relation}) + when tag in @relations do + original = Map.get(data, key) + current = Relation.load!(data, original) + + case Relation.change(relation, value, current) do + {:ok, change, relation_valid?} when change != original -> + {Map.put(changes, key, change), errors, valid? and relation_valid?} + + {:error, error} -> + {changes, [{key, error} | errors], false} + + # ignore or ok with change == original + _ -> + {Map.delete(changes, key), errors, valid?} + end + end + + defp put_change(data, _changes, _errors, _valid?, key, _value, nil) when is_atom(key) do + raise ArgumentError, "unknown field `#{inspect(key)}` in #{inspect(data)}" + end + + defp put_change(_data, _changes, _errors, _valid?, key, _value, nil) when not is_atom(key) do + raise ArgumentError, + "field names given to change/put_change must be atoms, got: `#{inspect(key)}`" + end + + defp put_change(data, changes, errors, valid?, key, value, type) do + if not Ecto.Type.equal?(type, Map.get(data, key), value) do + {Map.put(changes, key, value), errors, valid?} + else + {Map.delete(changes, key), errors, valid?} + end + end + + @doc """ + Puts the given association entry or entries as a change in the changeset. + + This function is used to work with associations as a whole. For example, + if a Post has many Comments, it allows you to add, remove or change all + comments at once. If your goal is to simply add a new comment to a post, + then it is preferred to do so manually, as we will describe later in the + ["Example: Adding a comment to a post" section](#put_assoc/4-example-adding-a-comment-to-a-post). + + This function requires the associated data to have been preloaded, except + when the parent changeset has been newly built and not yet persisted. + Missing data will invoke the `:on_replace` behaviour defined on the + association. + + For associations with cardinality one, `nil` can be used to remove the existing + entry. For associations with many entries, an empty list may be given instead. + + If the association has no changes, it will be skipped. If the association is + invalid, the changeset will be marked as invalid. If the given value is not any + of values below, it will raise. + + The associated data may be given in different formats: + + * a map or a keyword list representing changes to be applied to the + associated data. A map or keyword list can be given to update the + associated data as long as they have matching primary keys. + For example, `put_assoc(changeset, :comments, [%{id: 1, title: "changed"}])` + will locate the comment with `:id` of 1 and update its title. + If no comment with such id exists, one is created on the fly. + Since only a single comment was given, any other associated comment + will be replaced. On all cases, it is expected the keys to be atoms. + Opposite to `cast_assoc` and `embed_assoc`, the given map (or struct) + is not validated in any way and will be inserted as is. + This API is mostly used in scripts and tests, to make it straight- + forward to create schemas with associations at once, such as: + + Ecto.Changeset.change( + %Post{}, + title: "foo", + comments: [ + %{body: "first"}, + %{body: "second"} + ] + ) + + * changesets - when changesets are given, they are treated as the canonical + data and the associated data currently stored in the association is either + updated or replaced. For example, if you call + `put_assoc(post_changeset, :comments, [list_of_comments_changesets])`, + all comments with matching IDs will be updated according to the changesets. + New comments or comments not associated to any post will be correctly + associated. Currently associated comments that do not have a matching ID + in the list of changesets will act according to the `:on_replace` association + configuration (you can chose to raise, ignore the operation, update or delete + them). If there are changes in any of the changesets, they will be + persisted too. + + * structs - when structs are given, they are treated as the canonical data + and the associated data currently stored in the association is replaced. + For example, if you call + `put_assoc(post_changeset, :comments, [list_of_comments_structs])`, + all comments with matching IDs will be replaced by the new structs. + New comments or comments not associated to any post will be correctly + associated. Currently associated comments that do not have a matching ID + in the list of changesets will act according to the `:on_replace` + association configuration (you can chose to raise, ignore the operation, + update or delete them). Different to passing changesets, structs are not + change tracked in any fashion. In other words, if you change a comment + struct and give it to `put_assoc/4`, the updates in the struct won't be + persisted. You must use changesets, keyword lists, or maps instead. `put_assoc/4` with structs + only takes care of guaranteeing that the comments and the parent data + are associated. This is extremely useful when associating existing data, + as we will see in the ["Example: Adding tags to a post" section](#put_assoc/4-example-adding-tags-to-a-post). + + Once the parent changeset is given to an `Ecto.Repo` function, all entries + will be inserted/updated/deleted within the same transaction. + + If you need different behaviour or explicit control over how this function + behaves, you can drop it altogether and use `Ecto.Multi` to encode how several + database operations will happen on several schemas and changesets at once. + + ## Example: Adding a comment to a post + + Imagine a relationship where Post has many comments and you want to add a + new comment to an existing post. While it is possible to use `put_assoc/4` + for this, it would be unnecessarily complex. Let's see an example. + + First, let's fetch the post with all existing comments: + + post = Post |> Repo.get!(1) |> Repo.preload(:comments) + + The following approach is **wrong**: + + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:comments, [%Comment{body: "bad example!"}]) + |> Repo.update!() + + The reason why the example above is wrong is because `put_assoc/4` always + works with the **full data**. So the example above will effectively **erase + all previous comments** and only keep the comment you are currently adding. + Instead, you could try: + + post + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:comments, [%Comment{body: "so-so example!"} | post.comments]) + |> Repo.update!() + + In this example, we prepend the new comment to the list of existing comments. + Ecto will diff the list of comments currently in `post` with the list of comments + given, and correctly insert the new comment to the database. Note, however, + Ecto is doing a lot of work just to figure out something we knew since the + beginning, which is that there is only one new comment. + + In cases like above, when you want to work only on a single entry, it is + much easier to simply work on the association directly. For example, we + could instead set the `post` association in the comment: + + %Comment{body: "better example"} + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_assoc(:post, post) + |> Repo.insert!() + + Alternatively, we can make sure that when we create a comment, it is already + associated to the post: + + Ecto.build_assoc(post, :comments) + |> Ecto.Changeset.change(body: "great example!") + |> Repo.insert!() + + Or we can simply set the post_id in the comment itself: + + %Comment{body: "better example", post_id: post.id} + |> Repo.insert!() + + In other words, when you find yourself wanting to work only with a subset + of the data, then using `put_assoc/4` is most likely unnecessary. Instead, + you want to work on the other side of the association. + + Let's see an example where using `put_assoc/4` is a good fit. + + ## Example: Adding tags to a post + + Imagine you are receiving a set of tags you want to associate to a post. + Let's imagine that those tags exist upfront and are all persisted to the + database. Imagine we get the data in this format: + + params = %{"title" => "new post", "tags" => ["learner"]} + + Now, since the tags already exist, we will bring all of them from the + database and put them directly in the post: + + tags = Repo.all(from t in Tag, where: t.name in ^params["tags"]) + + post + |> Repo.preload(:tags) + |> Ecto.Changeset.cast(params, [:title]) # No need to allow :tags as we put them directly + |> Ecto.Changeset.put_assoc(:tags, tags) # Explicitly set the tags + + Since in this case we always require the user to pass all tags + directly, using `put_assoc/4` is a great fit. It will automatically + remove any tag not given and properly associate all of the given + tags with the post. + + Furthermore, since the tag information is given as structs read directly + from the database, Ecto will treat the data as correct and only do the + minimum necessary to guarantee that posts and tags are associated, + without trying to update or diff any of the fields in the tag struct. + + Although it accepts an `opts` argument, there are no options currently + supported by `put_assoc/4`. + + ## More resources + + You can learn more about working with associations in our documentation, + including cheatsheets and practical examples. Check out: + + * The docs for `cast_assoc/3` + * The [associations cheatsheet](associations.html) + * The [Constraints and Upserts guide](constraints-and-upserts.html) + * The [Polymorphic associations with many to many guide](polymorphic-associations-with-many-to-many.html) + + """ + @spec put_assoc(t, atom, term, Keyword.t()) :: t + def put_assoc(%Changeset{} = changeset, name, value, opts \\ []) do + put_relation(:assoc, changeset, name, value, opts) + end + + @doc """ + Puts the given embed entry or entries as a change in the changeset. + + This function is used to work with embeds as a whole. For embeds with + cardinality one, `nil` can be used to remove the existing entry. For + embeds with many entries, an empty list may be given instead. + + If the embed has no changes, it will be skipped. If the embed is + invalid, the changeset will be marked as invalid. + + The list of supported values and their behaviour is described in + `put_assoc/4`. If the given value is not any of values listed there, + it will raise. + + Although this function accepts an `opts` argument, there are no options + currently supported by `put_embed/4`. + """ + @spec put_embed(t, atom, term, Keyword.t()) :: t + def put_embed(%Changeset{} = changeset, name, value, opts \\ []) do + put_relation(:embed, changeset, name, value, opts) + end + + defp put_relation(tag, changeset, name, value, _opts) do + %{data: data, types: types, changes: changes, errors: errors, valid?: valid?} = changeset + relation = relation!(:put, tag, name, Map.get(types, name)) + + {changes, errors, valid?} = + put_change(data, changes, errors, valid?, name, value, {tag, relation}) + + %{changeset | changes: changes, errors: errors, valid?: valid?} + end + + @doc """ + Forces a change on the given `key` with `value`. + + If the change is already present, it is overridden with + the new value. If the value is later modified via + `put_change/3` and `update_change/3`, reverting back to + its original value, the change will be reverted unless + `force_change/3` is called once again. + + ## Examples + + iex> changeset = change(%Post{author: "bar"}, %{title: "foo"}) + iex> changeset = force_change(changeset, :title, "bar") + iex> changeset.changes + %{title: "bar"} + + iex> changeset = force_change(changeset, :author, "bar") + iex> changeset.changes + %{title: "bar", author: "bar"} + + """ + @spec force_change(t, atom, term) :: t + def force_change(%Changeset{types: types} = changeset, key, value) do + case Map.get(types, key) do + {tag, _} when tag in @relations -> + raise "changing #{tag}s with force_change/3 is not supported, " <> + "please use put_#{tag}/4 instead" + + nil -> + raise ArgumentError, "unknown field `#{inspect(key)}` in #{inspect(changeset.data)}" + + _ -> + put_in(changeset.changes[key], value) + end + end + + @doc """ + Deletes a change with the given key. + + ## Examples + + iex> changeset = change(%Post{}, %{title: "foo"}) + iex> changeset = delete_change(changeset, :title) + iex> get_change(changeset, :title) + nil + + """ + @spec delete_change(t, atom) :: t + def delete_change(%Changeset{} = changeset, key) when is_atom(key) do + update_in(changeset.changes, &Map.delete(&1, key)) + end + + @doc """ + Applies the changeset changes to the changeset data. + + This operation will return the underlying data with changes + regardless if the changeset is valid or not. See `apply_action/2` + for a similar function that ensures the changeset is valid. + + ## Examples + + iex> changeset = change(%Post{author: "bar"}, %{title: "foo"}) + iex> apply_changes(changeset) + %Post{author: "bar", title: "foo"} + + """ + @spec apply_changes(t) :: Ecto.Schema.t() | data + def apply_changes(%Changeset{changes: changes, data: data}) when changes == %{} do + data + end + + def apply_changes(%Changeset{changes: changes, data: data, types: types}) do + Enum.reduce(changes, data, fn {key, value}, acc -> + case Map.fetch(types, key) do + {:ok, {tag, relation}} when tag in @relations -> + apply_relation_changes(acc, key, relation, value) + + {:ok, _} -> + Map.put(acc, key, value) + + :error -> + acc + end + end) + end + + @doc """ + Applies the changeset action only if the changes are valid. + + If the changes are valid, all changes are applied to the changeset data. + If the changes are invalid, no changes are applied, and an error tuple + is returned with the changeset containing the action that was attempted + to be applied. + + The action may be any atom. + + ## Examples + + iex> {:ok, data} = apply_action(changeset, :update) + + iex> {:ok, data} = apply_action(changeset, :my_action) + + iex> {:error, changeset} = apply_action(changeset, :update) + %Ecto.Changeset{action: :update} + """ + @spec apply_action(t, action) :: {:ok, Ecto.Schema.t() | data} | {:error, t} + def apply_action(%Changeset{} = changeset, action) when is_atom(action) do + if changeset.valid? do + {:ok, apply_changes(changeset)} + else + {:error, %Changeset{changeset | action: action}} + end + end + + def apply_action(%Changeset{}, action) do + raise ArgumentError, "expected action to be an atom, got: #{inspect(action)}" + end + + @doc """ + Applies the changeset action if the changes are valid or raises an error. + + ## Examples + + iex> changeset = change(%Post{author: "bar"}, %{title: "foo"}) + iex> apply_action!(changeset, :update) + %Post{author: "bar", title: "foo"} + + iex> changeset = change(%Post{author: "bar"}, %{title: :bad}) + iex> apply_action!(changeset, :update) + ** (Ecto.InvalidChangesetError) could not perform update because changeset is invalid. + + See `apply_action/2` for more information. + """ + @spec apply_action!(t, action) :: Ecto.Schema.t() | data + def apply_action!(%Changeset{} = changeset, action) do + case apply_action(changeset, action) do + {:ok, data} -> + data + + {:error, changeset} -> + raise Ecto.InvalidChangesetError, action: action, changeset: changeset + end + end + + ## Validations + + @doc ~S""" + Returns a keyword list of the validations for this changeset. + + The keys in the list are the names of fields, and the values are a + validation associated with the field. A field may occur multiple + times in the list. + + ## Example + + %Post{} + |> change() + |> validate_format(:title, ~r/^\w+:\s/, message: "must start with a topic") + |> validate_length(:title, max: 100) + |> validations() + #=> [ + title: {:length, [ max: 100 ]}, + title: {:format, ~r/^\w+:\s/} + ] + + The following validations may be included in the result. The list is + not necessarily exhaustive. For example, custom validations written + by the developer will also appear in our return value. + + This first group contains validations that hold a keyword list of validators. + This list may also include a `:message` key. + + * `{:length, [option]}` + + * `min: n` + * `max: n` + * `is: n` + * `count: :graphemes | :codepoints` + + * `{:number, [option]}` + + * `equal_to: n` + * `greater_than: n` + * `greater_than_or_equal_to: n` + * `less_than: n` + * `less_than_or_equal_to: n` + + The other validators simply take a value: + + * `{:exclusion, Enum.t}` + * `{:format, ~r/pattern/}` + * `{:inclusion, Enum.t}` + * `{:subset, Enum.t}` + + Note that calling `validate_required/3` does not store the validation under the + `changeset.validations` key (and so won't be included in the result of this + function). The required fields are stored under the `changeset.required` key. + """ + @spec validations(t) :: [{atom, term}] + def validations(%Changeset{validations: validations}) do + validations + end + + @doc """ + Adds an error to the changeset. + + An additional keyword list `keys` can be passed to provide additional + contextual information for the error. This is useful when using + `traverse_errors/2` and when translating errors with `Gettext` + + ## Examples + + iex> changeset = change(%Post{}, %{title: ""}) + iex> changeset = add_error(changeset, :title, "empty") + iex> changeset.errors + [title: {"empty", []}] + iex> changeset.valid? + false + + iex> changeset = change(%Post{}, %{title: ""}) + iex> changeset = add_error(changeset, :title, "empty", additional: "info") + iex> changeset.errors + [title: {"empty", [additional: "info"]}] + iex> changeset.valid? + false + + iex> changeset = change(%Post{}, %{tags: ["ecto", "elixir", "x"]}) + iex> changeset = add_error(changeset, :tags, "tag '%{val}' is too short", val: "x") + iex> changeset.errors + [tags: {"tag '%{val}' is too short", [val: "x"]}] + iex> changeset.valid? + false + """ + @spec add_error(t, atom, String.t(), Keyword.t()) :: t + def add_error(%Changeset{errors: errors} = changeset, key, message, keys \\ []) + when is_binary(message) do + %{changeset | errors: [{key, {message, keys}} | errors], valid?: false} + end + + @doc """ + Validates the given `field` change. + + It invokes the `validator` function to perform the validation + only if a change for the given `field` exists and the change + value is not `nil`. The function must return a list of errors + (with an empty list meaning no errors). + + In case there's at least one error, the list of errors will be appended to the + `:errors` field of the changeset and the `:valid?` flag will be set to + `false`. + + ## Examples + + iex> changeset = change(%Post{}, %{title: "foo"}) + iex> changeset = validate_change changeset, :title, fn :title, title -> + ...> # Value must not be "foo"! + ...> if title == "foo" do + ...> [title: "cannot be foo"] + ...> else + ...> [] + ...> end + ...> end + iex> changeset.errors + [title: {"cannot be foo", []}] + + iex> changeset = change(%Post{}, %{title: "foo"}) + iex> changeset = validate_change changeset, :title, fn :title, title -> + ...> if title == "foo" do + ...> [title: {"cannot be foo", additional: "info"}] + ...> else + ...> [] + ...> end + ...> end + iex> changeset.errors + [title: {"cannot be foo", [additional: "info"]}] + + """ + @spec validate_change( + t, + atom, + (atom, term -> [{atom, String.t()} | {atom, error}]) + ) :: t + def validate_change(%Changeset{} = changeset, field, validator) when is_atom(field) do + %{changes: changes, types: types, errors: errors} = changeset + ensure_field_exists!(changeset, types, field) + + value = Map.get(changes, field) + new = if is_nil(value), do: [], else: validator.(field, value) + + new = + Enum.map(new, fn + {key, val} when is_atom(key) and is_binary(val) -> + {key, {val, []}} + + {key, {val, opts}} when is_atom(key) and is_binary(val) and is_list(opts) -> + {key, {val, opts}} + end) + + case new do + [] -> changeset + [_ | _] -> %{changeset | errors: new ++ errors, valid?: false} + end + end + + @doc """ + Stores the validation `metadata` and validates the given `field` change. + + Similar to `validate_change/3` but stores the validation metadata + into the changeset validators. The validator metadata is often used + as a reflection mechanism, to automatically generate code based on + the available validations. + + ## Examples + + iex> changeset = change(%Post{}, %{title: "foo"}) + iex> changeset = validate_change changeset, :title, :useless_validator, fn + ...> _, _ -> [] + ...> end + iex> changeset.validations + [title: :useless_validator] + + """ + @spec validate_change( + t, + atom, + term, + (atom, term -> [{atom, String.t()} | {atom, error}]) + ) :: t + def validate_change( + %Changeset{validations: validations} = changeset, + field, + metadata, + validator + ) do + changeset = %{changeset | validations: [{field, metadata} | validations]} + validate_change(changeset, field, validator) + end + + @doc """ + Validates that one or more fields are present in the changeset. + + You can pass a single field name or a list of field names that + are required. + + If the value of a field is `nil` or a string made only of whitespace, + the changeset is marked as invalid, the field is removed from the + changeset's changes, and an error is added. An error won't be added if + the field already has an error. + + If a field is given to `validate_required/3` but it has not been passed + as parameter during `cast/3` (i.e. it has not been changed), then + `validate_required/3` will check for its current value in the data. + If the data contains a non-empty value for the field, then no error is + added. This allows developers to use `validate_required/3` to perform + partial updates. For example, on `insert` all fields would be required, + because their default values on the data are all `nil`, but on `update`, + if you don't want to change a field that has been previously set, + you are not required to pass it as a parameter, since `validate_required/3` + won't add an error for missing changes as long as the value in the + data given to the `changeset` is not empty. + + Do not use this function to validate associations that are required, + instead pass the `:required` option to `cast_assoc/3` or `cast_embed/3`. + + Opposite to other validations, calling this function does not store + the validation under the `changeset.validations` key. Instead, it + stores all required fields under `changeset.required`. + + ## Options + + * `:message` - the message on failure, defaults to "can't be blank". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_required(changeset, :title) + validate_required(changeset, [:title, :body]) + + """ + @spec validate_required(t, list | atom, Keyword.t()) :: t + def validate_required(%Changeset{} = changeset, fields, opts \\ []) when not is_nil(fields) do + %{required: required, errors: errors, changes: changes} = changeset + fields = List.wrap(fields) + + fields_with_errors = + for field <- fields, + field_missing?(changeset, field), + is_nil(errors[field]), + do: field + + case fields_with_errors do + [] -> + %{changeset | required: fields ++ required} + + _ -> + new_errors = + Enum.map( + fields_with_errors, + &{&1, message(opts, "can't be blank", validation: :required)} + ) + + changes = Map.drop(changes, fields_with_errors) + + %{ + changeset + | changes: changes, + required: fields ++ required, + errors: new_errors ++ errors, + valid?: false + } + end + end + + @doc """ + Determines whether a field is missing in a changeset. + + The field passed into this function will have its presence evaluated + according to the same rules as `validate_required/3`. + + This is useful when performing complex validations that are not possible with + `validate_required/3`. For example, evaluating whether at least one field + from a list is present or evaluating that exactly one field from a list is + present. + + ## Examples + + iex> changeset = cast(%Post{}, %{color: "Red"}, [:color]) + iex> missing_fields = Enum.filter([:title, :body], &field_missing?(changeset, &1)) + iex> changeset = + ...> case missing_fields do + ...> [_, _] -> add_error(changeset, :title, "at least one of `:title` or `:body` must be present") + ...> _ -> changeset + ...> end + ...> changeset.errors + [title: {"at least one of `:title` or `:body` must be present", []}] + + """ + @spec field_missing?(t(), atom()) :: boolean() + def field_missing?(%Changeset{} = changeset, field) when not is_nil(field) do + ensure_field_not_many!(changeset.types, field) && missing?(changeset, field) && + ensure_field_exists!(changeset, changeset.types, field) + end + + @doc """ + Validates that no existing record with a different primary key + has the same values for these fields. + + This function exists to provide quick feedback to users of your + application. It should not be relied on for any data guarantee as it + has race conditions and is inherently unsafe. For example, if this + check happens twice in the same time interval (because the user + submitted a form twice), both checks may pass and you may end-up with + duplicate entries in the database. Therefore, a `unique_constraint/3` + should also be used to ensure your data won't get corrupted. + + However, because constraints are only checked if all validations + succeed, this function can be used as an early check to provide + early feedback to users, since most conflicting data will have been + inserted prior to the current validation phase. + + When applying this validation to a schemas loaded from the database + this check will exclude rows having the same primary key as set on + the changeset, as those are supposed to be overwritten anyways. + + ## Options + + * `:message` - the message in case the constraint check fails, + defaults to "has already been taken". Can also be a `{msg, opts}` tuple, + to provide additional options when using `traverse_errors/2`. + + * `:error_key` - the key to which changeset error will be added when + check fails, defaults to the first field name of the given list of + fields. + + * `:prefix` - the prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). See `Ecto.Repo` documentation + for more information. + + * `:nulls_distinct` - a boolean controlling whether different null values + are considered distinct (not equal). If `false`, `nil` values will have + their uniqueness checked. Otherwise, the check will not be performed. This + is only meaningful when paired with a unique index that treats nulls as equal, + such as Postgres 15's `NULLS NOT DISTINCT` option. Defaults to `true` + + * `:repo_opts` - the options to pass to the `Ecto.Repo` call. + + * `:query` - the base query to use for the check. Defaults to the schema of + the changeset. If the primary key is set, a clause will be added to exclude + the changeset row itself from the check. + + ## Examples + + unsafe_validate_unique(changeset, :city_name, repo) + unsafe_validate_unique(changeset, [:city_name, :state_name], repo) + unsafe_validate_unique(changeset, [:city_name, :state_name], repo, message: "city must be unique within state") + unsafe_validate_unique(changeset, [:city_name, :state_name], repo, prefix: "public") + unsafe_validate_unique(changeset, [:city_name, :state_name], repo, query: from(c in City, where: is_nil(c.deleted_at))) + + """ + @spec unsafe_validate_unique(t, atom | [atom, ...], Ecto.Repo.t(), Keyword.t()) :: t + def unsafe_validate_unique(%Changeset{} = changeset, fields, repo, opts \\ []) + when is_list(opts) do + {repo_opts, opts} = Keyword.pop(opts, :repo_opts, []) + %{data: data, validations: validations} = changeset + + unless is_struct(data) and function_exported?(data.__struct__, :__schema__, 1) do + raise ArgumentError, + "unsafe_validate_unique/4 does not work with schemaless changesets, got #{inspect(data)}" + end + + schema = + case {changeset.data, opts[:query]} do + # regular schema + {%schema{__meta__: %Metadata{}}, _} -> + schema + + # embedded schema with base query + {%schema{}, base_query} when base_query != nil -> + schema + + # embedded schema without base query + {data, _} -> + raise ArgumentError, + "unsafe_validate_unique/4 does not work with embedded schemas unless " <> + "the `:query` option is specified, got: #{inspect(data)}" + end + + fields = List.wrap(fields) + + changeset = %{ + changeset + | validations: [{hd(fields), {:unsafe_unique, fields: fields}} | validations] + } + + nulls_distinct = Keyword.get(opts, :nulls_distinct, true) + where_clause = unsafe_unique_filter(fields, changeset, nulls_distinct) + + # No need to query if there is a prior error for the fields + any_prior_errors_for_fields? = Enum.any?(changeset.errors, &(elem(&1, 0) in fields)) + + # No need to query if we haven't changed any of the fields in question + unrelated_changes? = Enum.all?(fields, &(not Map.has_key?(changeset.changes, &1))) + + # If one or more fields are `nil` and `nulls_distinct` is not false, we can't query for uniqueness + distinct_nils? = + if nulls_distinct == false do + false + else + Enum.any?(where_clause, &(&1 |> elem(1) |> is_nil())) + end + + if unrelated_changes? or distinct_nils? or any_prior_errors_for_fields? do + changeset + else + query = + Keyword.get(opts, :query, schema) + |> maybe_exclude_itself(changeset) + |> Ecto.Query.where(^where_clause) + + query = + if prefix = opts[:prefix] do + Ecto.Query.put_query_prefix(query, prefix) + else + query + end + + if repo.exists?(query, repo_opts) do + error_key = Keyword.get(opts, :error_key, hd(fields)) + + {error_message, keys} = + message(opts, "has already been taken", validation: :unsafe_unique, fields: fields) + + add_error(changeset, error_key, error_message, keys) + else + changeset + end + end + end + + defp unsafe_unique_filter(fields, changeset, false) do + Enum.reduce(fields, Ecto.Query.dynamic(true), fn field, dynamic -> + case get_field(changeset, field) do + nil -> Ecto.Query.dynamic([q], ^dynamic and is_nil(field(q, ^field))) + value -> Ecto.Query.dynamic([q], ^dynamic and field(q, ^field) == ^value) + end + end) + end + + defp unsafe_unique_filter(fields, changeset, _nulls_distinct) do + for field <- fields do + {field, get_field(changeset, field)} + end + end + + defp maybe_exclude_itself(base_query, %{data: %schema{__meta__: %Metadata{}}} = changeset) do + primary_keys_to_exclude = + case Ecto.get_meta(changeset.data, :state) do + :loaded -> + :primary_key + |> schema.__schema__() + |> Enum.map(&{&1, get_field(changeset, &1)}) + + _ -> + [] + end + + case primary_keys_to_exclude do + [{_pk_field, nil} | _remaining_pks] -> + base_query + + [{pk_field, value} | remaining_pks] -> + # generate a clean query (one that does not start with 'TRUE OR ...') + first_expr = Ecto.Query.dynamic([q], field(q, ^pk_field) == ^value) + + Enum.reduce_while(remaining_pks, first_expr, fn + {_pk_field, nil}, _expr -> + {:halt, nil} + + {pk_field, value}, expr -> + {:cont, Ecto.Query.dynamic([q], ^expr and field(q, ^pk_field) == ^value)} + end) + |> case do + nil -> + base_query + + matches_pk -> + Ecto.Query.where(base_query, ^Ecto.Query.dynamic(not (^matches_pk))) + end + + [] -> + base_query + end + end + + defp maybe_exclude_itself(base_query, _changeset), do: base_query + + defp ensure_field_exists!(changeset = %Changeset{}, types, field) do + unless Map.has_key?(types, field) do + raise ArgumentError, "unknown field #{inspect(field)} in #{inspect(changeset.data)}" + end + + true + end + + defp ensure_field_not_many!(types, field) do + case types do + %{^field => {:assoc, %Ecto.Association.Has{cardinality: :many}}} -> + IO.warn( + "attempting to determine the presence of has_many association #{inspect(field)} " <> + "with validate_required/3 or field_missing?/2 which has no effect. You can pass the " <> + ":required option to Ecto.Changeset.cast_assoc/3 to achieve this." + ) + + %{^field => {:embed, %Ecto.Embedded{cardinality: :many}}} -> + IO.warn( + "attempting to determine the presence of embed_many field #{inspect(field)} " <> + "with validate_required/3 or field_missing?/2 which has no effect. You can pass the " <> + ":required option to Ecto.Changeset.cast_embed/3 to achieve this." + ) + + _ -> + true + end + end + + defp missing?(changeset, field) when is_atom(field) do + case get_field(changeset, field) do + %{__struct__: Ecto.Association.NotLoaded} -> + raise ArgumentError, + "attempting to determine the presence of association `#{field}` " <> + "that was not loaded. Please preload your associations " <> + "before calling validate_required/3 or field_missing?/2. " <> + "You may also consider passing the :required option to Ecto.Changeset.cast_assoc/3" + + value when is_binary(value) -> + value == "" + + nil -> + true + + _ -> + false + end + end + + defp missing?(_changeset, field) do + raise ArgumentError, + "validate_required/3 and field_missing?/2 expect field names to be atoms, got: `#{inspect(field)}`" + end + + @doc """ + Validates a change has the given format. + + The format has to be expressed as a regular expression. + + The validation only runs if a change for the given `field` exists and the + change value is not `nil`. + + ## Options + + * `:message` - the message on failure, defaults to "has invalid format". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_format(changeset, :email, ~r/@/) + + """ + @spec validate_format(t, atom, Regex.t(), Keyword.t()) :: t + def validate_format(changeset, field, format, opts \\ []) do + validate_change(changeset, field, {:format, format}, fn _, value -> + unless is_binary(value) do + raise ArgumentError, + "validate_format/4 expects changes to be strings, received: #{inspect(value)} for field `#{field}`" + end + + if value =~ format, + do: [], + else: [{field, message(opts, "has invalid format", validation: :format)}] + end) + end + + @doc """ + Validates a change is included in the given enumerable. + + The validation only runs if a change for the given `field` exists and the + change value is not `nil`. + + ## Options + + * `:message` - the message on failure, defaults to "is invalid". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_inclusion(changeset, :cardinal_direction, ["north", "east", "south", "west"]) + validate_inclusion(changeset, :age, 0..99) + + """ + @spec validate_inclusion(t, atom, Enum.t(), Keyword.t()) :: t + def validate_inclusion(changeset, field, data, opts \\ []) do + validate_change(changeset, field, {:inclusion, data}, fn _, value -> + type = Map.fetch!(changeset.types, field) + + if Ecto.Type.include?(type, value, data), + do: [], + else: [{field, message(opts, "is invalid", validation: :inclusion, enum: data)}] + end) + end + + @doc ~S""" + Validates a change, of type enum, is a subset of the given enumerable. + + This validates if a list of values belongs to the given enumerable. + If you need to validate if a single value is inside the given enumerable, + you should use `validate_inclusion/4` instead. + + Type of the field must be array. + + The validation only runs if a change for the given `field` exists and the + change value is not `nil`. + + ## Options + + * `:message` - the message on failure, defaults to "has an invalid entry". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_subset(changeset, :pets, ["cat", "dog", "parrot"]) + validate_subset(changeset, :lottery_numbers, 0..99) + + """ + @spec validate_subset(t, atom, Enum.t(), Keyword.t()) :: t + def validate_subset(changeset, field, data, opts \\ []) do + validate_change(changeset, field, {:subset, data}, fn _, value -> + element_type = + case Map.fetch!(changeset.types, field) do + {:array, element_type} -> + element_type + + type -> + # backwards compatibility: custom types use underlying type + {:array, element_type} = Ecto.Type.type(type) + element_type + end + + case Enum.any?(value, fn element -> not Ecto.Type.include?(element_type, element, data) end) do + true -> + [{field, message(opts, "has an invalid entry", validation: :subset, enum: data)}] + + false -> + [] + end + end) + end + + @doc """ + Validates a change is not included in the given enumerable. + + The validation only runs if a change for the given `field` exists and the + change value is not `nil`. + + ## Options + + * `:message` - the message on failure, defaults to "is reserved". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_exclusion(changeset, :name, ~w(admin superadmin)) + + """ + @spec validate_exclusion(t, atom, Enum.t(), Keyword.t()) :: t + def validate_exclusion(changeset, field, data, opts \\ []) do + validate_change(changeset, field, {:exclusion, data}, fn _, value -> + type = Map.fetch!(changeset.types, field) + + if Ecto.Type.include?(type, value, data), + do: [{field, message(opts, "is reserved", validation: :exclusion, enum: data)}], + else: [] + end) + end + + @doc """ + Validates a change is a string or list of the given length. + + Note that the length of a string is counted in graphemes by default. If using + this validation to match a character limit of a database backend, + it's likely that the limit ignores graphemes and limits the number + of unicode characters. Then consider using the `:count` option to + limit the number of codepoints (`:codepoints`), or limit the number of bytes (`:bytes`). + + The validation only runs if a change for the given `field` exists and the + change value is not `nil`. + + ## Options + + * `:is` - the length must be exactly this value + * `:min` - the length must be greater than or equal to this value + * `:max` - the length must be less than or equal to this value + * `:count` - what length to count for string, `:graphemes` (default), `:codepoints` or `:bytes` + * `:message` - the message on failure, depending on the validation, is one of: + * for strings: + * "should be %{count} character(s)" + * "should be at least %{count} character(s)" + * "should be at most %{count} character(s)" + * for binary: + * "should be %{count} byte(s)" + * "should be at least %{count} byte(s)" + * "should be at most %{count} byte(s)" + * for lists and maps: + * "should have %{count} item(s)" + * "should have at least %{count} item(s)" + * "should have at most %{count} item(s)" + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_length(changeset, :title, min: 3) + validate_length(changeset, :title, max: 100) + validate_length(changeset, :title, min: 3, max: 100) + validate_length(changeset, :code, is: 9) + validate_length(changeset, :topics, is: 2) + validate_length(changeset, :icon, count: :bytes, max: 1024 * 16) + + """ + @spec validate_length(t, atom, Keyword.t()) :: t + def validate_length(changeset, field, opts) when is_list(opts) do + validate_change(changeset, field, {:length, opts}, fn + _, value -> + count_type = opts[:count] || :graphemes + + {type, length} = + case {value, count_type} do + {value, :codepoints} when is_binary(value) -> + {:string, codepoints_length(value, 0)} + + {value, :graphemes} when is_binary(value) -> + {:string, String.length(value)} + + {value, :bytes} when is_binary(value) -> + {:binary, byte_size(value)} + + {value, _} when is_list(value) -> + {:list, list_length(changeset, field, value)} + + {value, _} when is_map(value) -> + {:map, map_size(value)} + end + + error = + ((is = opts[:is]) && wrong_length(type, length, is, opts)) || + ((min = opts[:min]) && too_short(type, length, min, opts)) || + ((max = opts[:max]) && too_long(type, length, max, opts)) + + if error, do: [{field, error}], else: [] + end) + end + + defp codepoints_length(<<_::utf8, rest::binary>>, acc), do: codepoints_length(rest, acc + 1) + defp codepoints_length(<<_, rest::binary>>, acc), do: codepoints_length(rest, acc + 1) + defp codepoints_length(<<>>, acc), do: acc + + defp list_length(%{types: types}, field, value) do + case Map.fetch(types, field) do + {:ok, {tag, _association}} when tag in [:embed, :assoc] -> + length(Relation.filter_empty(value)) + + _ -> + length(value) + end + end + + defp wrong_length(_type, value, value, _opts), do: nil + + defp wrong_length(:string, _length, value, opts), + do: + message(opts, "should be %{count} character(s)", + count: value, + validation: :length, + kind: :is, + type: :string + ) + + defp wrong_length(:binary, _length, value, opts), + do: + message(opts, "should be %{count} byte(s)", + count: value, + validation: :length, + kind: :is, + type: :binary + ) + + defp wrong_length(:list, _length, value, opts), + do: + message(opts, "should have %{count} item(s)", + count: value, + validation: :length, + kind: :is, + type: :list + ) + + defp wrong_length(:map, _length, value, opts), + do: + message(opts, "should have %{count} item(s)", + count: value, + validation: :length, + kind: :is, + type: :map + ) + + defp too_short(_type, length, value, _opts) when length >= value, do: nil + + defp too_short(:string, _length, value, opts) do + message(opts, "should be at least %{count} character(s)", + count: value, + validation: :length, + kind: :min, + type: :string + ) + end + + defp too_short(:binary, _length, value, opts) do + message(opts, "should be at least %{count} byte(s)", + count: value, + validation: :length, + kind: :min, + type: :binary + ) + end + + defp too_short(:list, _length, value, opts) do + message(opts, "should have at least %{count} item(s)", + count: value, + validation: :length, + kind: :min, + type: :list + ) + end + + defp too_short(:map, _length, value, opts) do + message(opts, "should have at least %{count} item(s)", + count: value, + validation: :length, + kind: :min, + type: :map + ) + end + + defp too_long(_type, length, value, _opts) when length <= value, do: nil + + defp too_long(:string, _length, value, opts) do + message(opts, "should be at most %{count} character(s)", + count: value, + validation: :length, + kind: :max, + type: :string + ) + end + + defp too_long(:binary, _length, value, opts) do + message(opts, "should be at most %{count} byte(s)", + count: value, + validation: :length, + kind: :max, + type: :binary + ) + end + + defp too_long(:list, _length, value, opts) do + message(opts, "should have at most %{count} item(s)", + count: value, + validation: :length, + kind: :max, + type: :list + ) + end + + defp too_long(:map, _length, value, opts) do + message(opts, "should have at most %{count} item(s)", + count: value, + validation: :length, + kind: :max, + type: :map + ) + end + + @doc """ + Validates the properties of a number. + + The validation only runs if a change for the given `field` exists and the + change value is not `nil`. + + ## Options + + * `:less_than` + * `:greater_than` + * `:less_than_or_equal_to` + * `:greater_than_or_equal_to` + * `:equal_to` + * `:not_equal_to` + * `:message` - the message on failure, defaults to one of: + * "must be less than %{number}" + * "must be greater than %{number}" + * "must be less than or equal to %{number}" + * "must be greater than or equal to %{number}" + * "must be equal to %{number}" + * "must be not equal to %{number}" + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_number(changeset, :count, less_than: 3) + validate_number(changeset, :pi, greater_than: 3, less_than: 4) + validate_number(changeset, :the_answer_to_life_the_universe_and_everything, equal_to: 42) + + """ + @spec validate_number(t, atom, Keyword.t()) :: t + def validate_number(changeset, field, opts) do + validate_change(changeset, field, {:number, opts}, fn + field, value -> + unless valid_number?(value) do + raise ArgumentError, + "expected field `#{field}` to be a decimal, integer, or float, got: #{inspect(value)}" + end + + opts + |> Keyword.drop([:message]) + |> Enum.find_value([], fn {spec_key, target_value} -> + case Map.fetch(@number_validators, spec_key) do + {:ok, {spec_function, default_message}} -> + unless valid_number?(target_value) do + raise ArgumentError, + "expected option `#{spec_key}` to be a decimal, integer, or float, got: #{inspect(target_value)}" + end + + compare_numbers( + field, + value, + default_message, + spec_key, + spec_function, + target_value, + opts + ) + + :error -> + supported_options = + @number_validators |> Map.keys() |> Enum.map_join("\n", &" * #{inspect(&1)}") + + raise ArgumentError, """ + unknown option #{inspect(spec_key)} given to validate_number/3 + + The supported options are: + + #{supported_options} + """ + end + end) + end) + end + + defp valid_number?(%Decimal{}), do: true + defp valid_number?(other), do: is_number(other) + + defp compare_numbers( + field, + %Decimal{} = value, + default_message, + spec_key, + _spec_function, + %Decimal{} = target_value, + opts + ) do + result = Decimal.compare(value, target_value) + + case decimal_compare(result, spec_key) do + true -> nil + false -> [{field, message(opts, default_message, validation: :number, kind: spec_key, number: target_value)}] + end + end + + defp compare_numbers(field, value, default_message, spec_key, spec_function, %Decimal{} = target_value, opts) do + compare_numbers(field, decimal_new(value), default_message, spec_key, spec_function, target_value, opts) + end + + defp compare_numbers(field, %Decimal{} = value, default_message, spec_key, spec_function, target_value, opts) do + compare_numbers(field, value, default_message, spec_key, spec_function, decimal_new(target_value), opts) + end + + defp compare_numbers(field, value, default_message, spec_key, spec_function, target_value, opts) do + case apply(spec_function, [value, target_value]) do + true -> nil + false -> [{field, message(opts, default_message, validation: :number, kind: spec_key, number: target_value)}] + end + end + + defp decimal_new(term) when is_float(term), do: Decimal.from_float(term) + defp decimal_new(term), do: Decimal.new(term) + + defp decimal_compare(:lt, spec), do: spec in [:less_than, :less_than_or_equal_to, :not_equal_to] + + defp decimal_compare(:gt, spec), + do: spec in [:greater_than, :greater_than_or_equal_to, :not_equal_to] + + defp decimal_compare(:eq, spec), + do: spec in [:equal_to, :less_than_or_equal_to, :greater_than_or_equal_to] + + @doc """ + Validates that the given parameter matches its confirmation. + + By calling `validate_confirmation(changeset, :email)`, this + validation will check if both "email" and "email_confirmation" + in the parameter map matches. Note this validation only looks + at the parameters themselves, never the fields in the schema. + As such as, the "email_confirmation" field does not need to be + added as a virtual field in your schema. + + Note that if the confirmation field is missing, this does not + add a validation error. This is done on purpose as you do not + trigger confirmation validation in places where a confirmation + is not required (for example, in APIs). You can force the + confirmation parameter to be required in the options (see below). + + ## Options + + * `:message` - the message on failure, defaults to "does not match confirmation". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + * `:required` - boolean, sets whether existence of confirmation parameter + is required for addition of error. Defaults to false + + ## Examples + + validate_confirmation(changeset, :email) + validate_confirmation(changeset, :password, message: "does not match password") + + cast(data, params, [:password]) + |> validate_confirmation(:password, message: "does not match password") + + """ + @spec validate_confirmation(t, atom, Keyword.t()) :: t + def validate_confirmation(changeset, field, opts \\ []) + + def validate_confirmation(%{params: params} = changeset, field, opts) when is_map(params) do + param = Atom.to_string(field) + error_param = "#{param}_confirmation" + error_field = String.to_atom(error_param) + value = Map.get(params, param) + + errors = + case params do + %{^error_param => ^value} -> + [] + + %{^error_param => _} -> + [ + {error_field, message(opts, "does not match confirmation", validation: :confirmation)} + ] + + %{} -> + confirmation_missing(opts, error_field) + end + + %{ + changeset + | validations: [{field, {:confirmation, opts}} | changeset.validations], + errors: errors ++ changeset.errors, + valid?: changeset.valid? and errors == [] + } + end + + def validate_confirmation(%{params: nil} = changeset, _, _) do + changeset + end + + defp confirmation_missing(opts, error_field) do + required = Keyword.get(opts, :required, false) + + if required, + do: [{error_field, message(opts, "can't be blank", validation: :required)}], + else: [] + end + + defp message(opts, key \\ :message, default, message_opts) do + case Keyword.get(opts, key, default) do + {message, extra_opts} when is_binary(message) and is_list(extra_opts) -> + {message, Keyword.merge(message_opts, extra_opts)} + + message when is_binary(message) -> + {message, message_opts} + end + end + + defp constraint_message(opts, key \\ :message, default) do + Keyword.get(opts, key, default) + end + + @doc """ + Validates the given parameter is true. + + Note this validation only checks the parameter itself is true, never + the field in the schema. That's because acceptance parameters do not need + to be persisted, as by definition they would always be stored as `true`. + + ## Options + + * `:message` - the message on failure, defaults to "must be accepted". + Can also be a `{msg, opts}` tuple, to provide additional options + when using `traverse_errors/2`. + + ## Examples + + validate_acceptance(changeset, :terms_of_service) + validate_acceptance(changeset, :rules, message: "please accept rules") + + """ + @spec validate_acceptance(t, atom, Keyword.t()) :: t + def validate_acceptance(changeset, field, opts \\ []) + + def validate_acceptance(%{params: params} = changeset, field, opts) do + errors = validate_acceptance_errors(params, field, opts) + + %{ + changeset + | validations: [{field, {:acceptance, opts}} | changeset.validations], + errors: errors ++ changeset.errors, + valid?: changeset.valid? and errors == [] + } + end + + defp validate_acceptance_errors(nil, _field, _opts), do: [] + + defp validate_acceptance_errors(params, field, opts) do + param = Atom.to_string(field) + value = Map.get(params, param) + + case Ecto.Type.cast(:boolean, value) do + {:ok, true} -> [] + _ -> [{field, message(opts, "must be accepted", validation: :acceptance)}] + end + end + + ## Optimistic lock + + @doc ~S""" + Applies optimistic locking to the changeset. + + [Optimistic + locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) (or + *optimistic concurrency control*) is a technique that allows concurrent edits + on a single record. While pessimistic locking works by locking a resource for + an entire transaction, optimistic locking only checks if the resource changed + before updating it. + + This is done by regularly fetching the record from the database, then checking + whether another user has made changes to the record *only when updating the + record*. This behaviour is ideal in situations where the chances of concurrent + updates to the same record are low; if they're not, pessimistic locking or + other concurrency patterns may be more suited. + + ## Usage + + Optimistic locking works by keeping a "version" counter for each record; this + counter gets incremented each time a modification is made to a record. Hence, + in order to use optimistic locking, a field must exist in your schema for + versioning purpose. Such field is usually an integer but other types are + supported. + + ## Examples + + Assuming we have a `Post` schema (stored in the `posts` table), the first step + is to add a version column to the `posts` table: + + alter table(:posts) do + add :lock_version, :integer, default: 1 + end + + The column name is arbitrary and doesn't need to be `:lock_version`. Now add + a field to the schema too: + + defmodule Post do + use Ecto.Schema + + schema "posts" do + field :title, :string + field :lock_version, :integer, default: 1 + end + + def changeset(:update, struct, params \\ %{}) do + struct + |> Ecto.Changeset.cast(params, [:title]) + |> Ecto.Changeset.optimistic_lock(:lock_version) + end + end + + Now let's take optimistic locking for a spin: + + iex> post = Repo.insert!(%Post{title: "foo"}) + %Post{id: 1, title: "foo", lock_version: 1} + iex> valid_change = Post.changeset(:update, post, %{title: "bar"}) + iex> stale_change = Post.changeset(:update, post, %{title: "baz"}) + iex> Repo.update!(valid_change) + %Post{id: 1, title: "bar", lock_version: 2} + iex> Repo.update!(stale_change) + ** (Ecto.StaleEntryError) attempted to update a stale entry: + + %Post{id: 1, title: "baz", lock_version: 1} + + When a conflict happens (a record which has been previously fetched is + being updated, but that same record has been modified since it was + fetched), an `Ecto.StaleEntryError` exception is raised. + + Optimistic locking also works with delete operations. Just call the + `optimistic_lock/3` function with the data before delete: + + iex> changeset = Ecto.Changeset.optimistic_lock(post, :lock_version) + iex> Repo.delete(changeset) + + `optimistic_lock/3` by default assumes the field + being used as a lock is an integer. If you want to use another type, + you need to pass the third argument customizing how the next value + is generated: + + iex> Ecto.Changeset.optimistic_lock(post, :lock_uuid, fn _ -> Ecto.UUID.generate end) + + """ + @spec optimistic_lock(Ecto.Schema.t() | t, atom, (term -> term)) :: t + def optimistic_lock(data_or_changeset, field, incrementer \\ &increment_with_rollover/1) do + changeset = change(data_or_changeset, %{}) + current = get_field(changeset, field) + + # Apply these changes only inside the repo because we + # don't want to permanently track the lock change. + changeset = + prepare_changes(changeset, fn changeset -> + put_in(changeset.changes[field], incrementer.(current)) + end) + + if is_nil(current) do + Logger.warning(""" + the current value of `#{field}` is `nil` and will not be used as a filter for optimistic locking. \ + To ensure `#{field}` is never `nil`, consider setting a default value. + """) + + changeset + else + put_in(changeset.filters[field], current) + end + end + + # increment_with_rollover expect to be used with lock_version set as :integer in db schema + # 2_147_483_647 is upper limit for signed integer for both PostgreSQL and MySQL + defp increment_with_rollover(val) when val >= 2_147_483_647 do + 1 + end + + defp increment_with_rollover(val) when is_integer(val) do + val + 1 + end + + @doc """ + Provides a function executed by the repository on insert/update/delete. + + If the changeset given to the repository is valid, the function given to + `prepare_changes/2` will be called with the changeset and must return a + changeset, allowing developers to do final adjustments to the changeset or + to issue data consistency commands. The repository itself can be accessed + inside the function under the `repo` field in the changeset. If the + changeset given to the repository is invalid, the function will not be + invoked. + + The given function is guaranteed to run inside the same transaction + as the changeset operation for databases that do support transactions. + + ## Example + + A common use case is updating a counter cache, in this case updating a post's + comment count when a comment is created: + + def create_comment(comment, params) do + comment + |> cast(params, [:body, :post_id]) + |> prepare_changes(fn changeset -> + if post_id = get_change(changeset, :post_id) do + query = from Post, where: [id: ^post_id] + changeset.repo.update_all(query, inc: [comment_count: 1]) + end + changeset + end) + end + + We retrieve the repo from the comment changeset itself and use + update_all to update the counter cache in one query. Finally, the original + changeset must be returned. + """ + @spec prepare_changes(t, (t -> t)) :: t + def prepare_changes(%Changeset{prepare: prepare} = changeset, function) + when is_function(function, 1) do + %{changeset | prepare: [function | prepare]} + end + + ## Constraints + + @doc """ + Returns all constraints in a changeset. + + A constraint is a map with the following fields: + + * `:type` - the type of the constraint that will be checked in the database, + such as `:check`, `:unique`, etc + * `:constraint` - the database constraint name as a string or `Regex`. The constraint at + the database level will be checked against this according to `:match` type + * `:match` - the type of match Ecto will perform on a violated constraint + against the `:constraint` value. It is `:exact`, `:suffix` or `:prefix` + * `:field` - the field a violated constraint will apply the error to + * `:error_message` - the error message in case of violated constraints + * `:error_type` - the type of error that identifies the error message + + """ + @spec constraints(t) :: [constraint] + def constraints(%Changeset{constraints: constraints}) do + constraints + end + + @doc """ + Checks for a check constraint in the given field. + + The check constraint works by relying on the database to check + if the check constraint has been violated or not and, if so, + Ecto converts it into a changeset error. + + In order to use the check constraint, the first step is + to define the check constraint in a migration: + + create constraint("users", :age_must_be_positive, check: "age > 0") + + Now that a constraint exists, when modifying users, we could + annotate the changeset with a check constraint so Ecto knows + how to convert it into an error message: + + cast(user, params, [:age]) + |> check_constraint(:age, name: :age_must_be_positive) + + Now, when invoking `c:Ecto.Repo.insert/2` or `c:Ecto.Repo.update/2`, + if the age is not positive, the underlying operation will fail + but Ecto will convert the database exception into a changeset error + and return an `{:error, changeset}` tuple. Note that the error will + occur only after hitting the database, so it will not be visible + until all other validations pass. If the constraint fails inside a + transaction, the transaction will be marked as aborted. + + ## Options + + * `:message` - the message in case the constraint check fails. + Defaults to "is invalid" + * `:name` - the constraint name. By default, the constraint + name is inferred from the table + field. If this option is given, + the `field` argument only indicates the field the error will be + added to. May be required explicitly for complex cases + * `:match` - how the changeset constraint name is matched against the + repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to + `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` + to this changeset constraint. `:prefix` matches any repo constraint which + `starts_with?` `:name` to this changeset constraint. + + """ + @spec check_constraint(t, atom, Keyword.t()) :: t + def check_constraint(changeset, field, opts \\ []) do + name = opts[:name] || raise ArgumentError, "must supply the name of the constraint" + message = constraint_message(opts, "is invalid") + match_type = Keyword.get(opts, :match, :exact) + + add_constraint(changeset, :check, name, match_type, field, message, :check) + end + + @doc """ + Checks for a unique constraint in the given field or list of fields. + + The unique constraint works by relying on the database to check + if the unique constraint has been violated or not and, if so, + Ecto converts it into a changeset error. + + In order to use the uniqueness constraint, the first step is + to define the unique index in a migration: + + create unique_index(:users, [:email]) + + Now that a constraint exists, when modifying users, we could + annotate the changeset with a unique constraint so Ecto knows + how to convert it into an error message: + + cast(user, params, [:email]) + |> unique_constraint(:email) + + Now, when invoking `c:Ecto.Repo.insert/2` or `c:Ecto.Repo.update/2`, + if the email already exists, the underlying operation will fail but + Ecto will convert the database exception into a changeset error and + return an `{:error, changeset}` tuple. Note that the error will occur + only after hitting the database, so it will not be visible until all + other validations pass. If the constraint fails inside a transaction, + the transaction will be marked as aborted. + + ## Options + + * `:message` - the message in case the constraint check fails, + defaults to "has already been taken" + + * `:name` - the constraint name. By default, the constraint + name is inferred from the table + field. If this option is given, + the `field` argument only indicates the field the error will be + added to. May be required explicitly for complex cases + + * `:match` - how the changeset constraint name is matched against the + repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to + `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` + to this changeset constraint. `:prefix` matches any repo constraint which + `starts_with?` `:name` to this changeset constraint. + + * `:error_key` - the key to which changeset error will be added when + check fails, defaults to the first field name of the given list of + fields. + + ## Complex constraints + + Because the constraint logic is in the database, we can leverage + all the database functionality when defining them. For example, + let's suppose the e-mails are scoped by company id: + + # In migration + create unique_index(:users, [:email, :company_id]) + + # In the changeset function + cast(user, params, [:email]) + |> unique_constraint([:email, :company_id]) + + The first field name, `:email` in this case, will be used as the error + key to the changeset errors keyword list. For example, the above + `unique_constraint/3` would generate something like: + + Repo.insert!(%User{email: "john@elixir.org", company_id: 1}) + changeset = User.changeset(%User{}, %{email: "john@elixir.org", company_id: 1}) + {:error, changeset} = Repo.insert(changeset) + changeset.errors #=> [email: {"has already been taken", []}] + + In complex cases, instead of relying on name inference, it may be best + to set the constraint name explicitly: + + # In the migration + create unique_index(:users, [:email, :company_id], name: :users_email_company_id_index) + + # In the changeset function + cast(user, params, [:email]) + |> unique_constraint(:email, name: :users_email_company_id_index) + + ### Partitioning + + If your table is partitioned, then your unique index might look different + per partition, e.g. Postgres adds p to the middle of your key, like: + + users_p0_email_key + users_p1_email_key + ... + users_p99_email_key + + In this case you can use the name and suffix options together to match on + these dynamic indexes, like: + + cast(user, params, [:email]) + |> unique_constraint(:email, name: :email_key, match: :suffix) + + There are cases where the index has a number added both for table name and + index name, generating an index name such as: + + user_p0_email_idx2 + user_p1_email_idx3 + ... + user_p99_email_idx101 + + In that case, a `Regex` can be used to match: + + cast(user, params, [:email]) + |> unique_constraint(:email, name: ~r/user_p\d+_email_idx\d+/) + + ## Case sensitivity + + Unfortunately, different databases provide different guarantees + when it comes to case-sensitiveness. For example, in MySQL, comparisons + are case-insensitive by default. In Postgres, users can define case + insensitive column by using the `:citext` type/extension. In your migration: + + execute "CREATE EXTENSION IF NOT EXISTS citext" + create table(:users) do + ... + add :email, :citext + ... + end + + If for some reason your database does not support case insensitive columns, + you can explicitly downcase values before inserting/updating them: + + cast(data, params, [:email]) + |> update_change(:email, &String.downcase/1) + |> unique_constraint(:email) + + """ + @spec unique_constraint(t, atom | [atom, ...], Keyword.t()) :: t + def unique_constraint(changeset, field_or_fields, opts \\ []) + + def unique_constraint(changeset, field, opts) when is_atom(field) do + unique_constraint(changeset, [field], opts) + end + + def unique_constraint(changeset, [first_field | _] = fields, opts) do + name = opts[:name] || unique_index_name(changeset, fields) + message = constraint_message(opts, "has already been taken") + match_type = Keyword.get(opts, :match, :exact) + error_key = Keyword.get(opts, :error_key, first_field) + + add_constraint(changeset, :unique, name, match_type, error_key, message, :unique) + end + + defp unique_index_name(changeset, fields) do + field_names = Enum.map(fields, &get_field_source(changeset, &1)) + Enum.join([get_source(changeset)] ++ field_names ++ ["index"], "_") + end + + @doc """ + Checks for foreign key constraint in the given field. + + The foreign key constraint works by relying on the database to + check if the associated data exists or not. This is useful to + guarantee that a child will only be created if the parent exists + in the database too. + + In order to use the foreign key constraint the first step is + to define the foreign key in a migration. This is often done + with references. For example, imagine you are creating a + comments table that belongs to posts. One would have: + + create table(:comments) do + add :post_id, references(:posts) + end + + By default, Ecto will generate a foreign key constraint with + name "comments_post_id_fkey" (the name is configurable). + + Now that a constraint exists, when creating comments, we could + annotate the changeset with foreign key constraint so Ecto knows + how to convert it into an error message: + + cast(comment, params, [:post_id]) + |> foreign_key_constraint(:post_id) + + Now, when invoking `c:Ecto.Repo.insert/2` or `c:Ecto.Repo.update/2`, + if the associated post does not exist, the underlying operation will + fail but Ecto will convert the database exception into a changeset + error and return an `{:error, changeset}` tuple. Note that the error + will occur only after hitting the database, so it will not be visible + until all other validations pass. If the constraint fails inside a + transaction, the transaction will be marked as aborted. + + ## Options + + * `:message` - the message in case the constraint check fails, + defaults to "does not exist" + * `:name` - the constraint name. By default, the constraint + name is inferred from the table + field. If this option is given, + the `field` argument only indicates the field the error will be + added to. May be required explicitly for complex cases + * `:match` - how the changeset constraint name is matched against the + repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to + `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` + to this changeset constraint. `:prefix` matches any repo constraint which + `starts_with?` `:name` to this changeset constraint. + + """ + @spec foreign_key_constraint(t, atom, Keyword.t()) :: t + def foreign_key_constraint(changeset, field, opts \\ []) do + name = opts[:name] || "#{get_source(changeset)}_#{get_field_source(changeset, field)}_fkey" + match_type = Keyword.get(opts, :match, :exact) + message = constraint_message(opts, "does not exist") + + add_constraint(changeset, :foreign_key, name, match_type, field, message, :foreign) + end + + @doc """ + Checks the associated field exists. + + This is similar to `foreign_key_constraint/3` except that the + field is inferred from the association definition. This is useful + to guarantee that a child will only be created if the parent exists + in the database too. Therefore, it only applies to `belongs_to` + associations. + + As the name says, a constraint is required in the database for + this function to work. Such constraint is often added as a + reference to the child table: + + create table(:comments) do + add :post_id, references(:posts) + end + + Now, when inserting a comment, it is possible to forbid any + comment to be added if the associated post does not exist: + + comment + |> Ecto.Changeset.cast(params, [:post_id]) + |> Ecto.Changeset.assoc_constraint(:post) + |> Repo.insert + + ## Options + + * `:message` - the message in case the constraint check fails, + defaults to "does not exist" + * `:name` - the constraint name. By default, the constraint + name is inferred from the table + field. If this option is given, + the `field` argument only indicates the field the error will be + added to. May be required explicitly for complex cases + * `:match` - how the changeset constraint name is matched against the + repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to + `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` + to this changeset constraint. `:prefix` matches any repo constraint which + `starts_with?` `:name` to this changeset constraint. + """ + @spec assoc_constraint(t, atom, Keyword.t()) :: t + def assoc_constraint(changeset, assoc, opts \\ []) do + name = + opts[:name] || + case get_assoc_type(changeset, assoc) do + %Ecto.Association.BelongsTo{owner_key: owner_key} -> + "#{get_source(changeset)}_#{owner_key}_fkey" + + other -> + raise ArgumentError, + "assoc_constraint can only be added to belongs to associations, got: #{inspect(other)}" + end + + match_type = Keyword.get(opts, :match, :exact) + message = constraint_message(opts, "does not exist") + + add_constraint(changeset, :foreign_key, name, match_type, assoc, message, :assoc) + end + + @doc """ + Checks the associated field does not exist. + + This is similar to `foreign_key_constraint/3` except that the + field is inferred from the association definition. This is useful + to guarantee that parent can only be deleted (or have its primary + key changed) if no child exists in the database. Therefore, it only + applies to `has_*` associations. + + As the name says, a constraint is required in the database for + this function to work. Such constraint is often added as a + reference to the child table: + + create table(:comments) do + add :post_id, references(:posts) + end + + Now, when deleting the post, it is possible to forbid any post to + be deleted if they still have comments attached to it: + + post + |> Ecto.Changeset.change + |> Ecto.Changeset.no_assoc_constraint(:comments) + |> Repo.delete + + ## Options + + * `:message` - the message in case the constraint check fails, + defaults to "is still associated with this entry" (for `has_one`) + and "are still associated with this entry" (for `has_many`) + * `:name` - the constraint name. By default, the constraint + name is inferred from the table + field. If this option is given, + the `field` argument only indicates the field the error will be + added to. May be required explicitly for complex cases + * `:match` - how the changeset constraint name is matched against the + repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to + `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` + to this changeset constraint. `:prefix` matches any repo constraint which + `starts_with?` `:name` to this changeset constraint. + + """ + @spec no_assoc_constraint(t, atom, Keyword.t()) :: t + def no_assoc_constraint(changeset, assoc, opts \\ []) do + {name, message} = + case get_assoc_type(changeset, assoc) do + %Ecto.Association.Has{ + cardinality: cardinality, + related_key: related_key, + related: related + } -> + {opts[:name] || "#{related.__schema__(:source)}_#{related_key}_fkey", + constraint_message(opts, no_assoc_message(cardinality))} + + other -> + raise ArgumentError, + "no_assoc_constraint can only be added to has one/many associations, got: #{inspect(other)}" + end + + match_type = Keyword.get(opts, :match, :exact) + + add_constraint(changeset, :foreign_key, name, match_type, assoc, message, :no_assoc) + end + + @doc """ + Checks for an exclusion constraint in the given field. + + The exclusion constraint works by relying on the database to check + if the exclusion constraint has been violated or not and, if so, + Ecto converts it into a changeset error. + + ## Options + + * `:message` - the message in case the constraint check fails, + defaults to "violates an exclusion constraint" + * `:name` - the constraint name. By default, the constraint + name is inferred from the table + field. If this option is given, + the `field` argument only indicates the field the error will be + added to. May be required explicitly for complex cases + * `:match` - how the changeset constraint name is matched against the + repo constraint, may be `:exact`, `:suffix` or `:prefix`. Defaults to + `:exact`. `:suffix` matches any repo constraint which `ends_with?` `:name` + to this changeset constraint. `:prefix` matches any repo constraint which + `starts_with?` `:name` to this changeset constraint. + + """ + def exclusion_constraint(changeset, field, opts \\ []) do + name = + opts[:name] || "#{get_source(changeset)}_#{get_field_source(changeset, field)}_exclusion" + + message = constraint_message(opts, "violates an exclusion constraint") + match_type = Keyword.get(opts, :match, :exact) + + add_constraint(changeset, :exclusion, name, match_type, field, message, :exclusion) + end + + defp no_assoc_message(:one), do: "is still associated with this entry" + defp no_assoc_message(:many), do: "are still associated with this entry" + + defp add_constraint( + %Changeset{constraints: constraints} = changeset, + type, + constraint, + match, + field, + error_message, + error_type + ) + when is_atom(field) and is_binary(error_message) do + constraint = %{ + constraint: normalize_constraint(constraint, match), + error_message: error_message, + error_type: error_type, + field: field, + match: match, + type: type + } + + %{changeset | constraints: [constraint | constraints]} + end + + defp normalize_constraint(constraint, match) when is_atom(constraint) do + normalize_constraint(Atom.to_string(constraint), match) + end + + defp normalize_constraint(constraint, match) when is_binary(constraint) do + unless match in @match_types do + raise ArgumentError, + "invalid match type: #{inspect(match)}. Allowed match types: #{inspect(@match_types)}" + end + + constraint + end + + defp normalize_constraint(%Regex{} = constraint, match) do + if match != :exact do + raise ArgumentError, + "a Regex constraint only allows match type of :exact, got: #{inspect(match)}" + end + + constraint + end + + defp get_source(%{data: %{__meta__: %{source: source}}}) when is_binary(source), + do: source + + defp get_source(%{data: data}) do + raise ArgumentError, + "cannot add constraint to changeset because it does not have a source, got: #{inspect(data)}" + end + + defp get_source(item) do + raise ArgumentError, + "cannot add constraint because a changeset was not supplied, got: #{inspect(item)}" + end + + defp get_assoc_type(%{types: types}, assoc) do + case Map.fetch(types, assoc) do + {:ok, {:assoc, association}} -> association + _ -> raise_invalid_assoc(types, assoc) + end + end + + defp raise_invalid_assoc(types, assoc) do + associations = for {_key, {:assoc, %{field: field}}} <- types, do: field + one_of = if match?([_], associations), do: "", else: "one of " + + raise ArgumentError, + "cannot add constraint to changeset because association `#{assoc}` does not exist. " <> + "Did you mean #{one_of}`#{Enum.join(associations, "`, `")}`?" + end + + defp get_field_source(%{data: %{__struct__: schema}}, field) when is_atom(schema), + do: schema.__schema__(:field_source, field) || field + + defp get_field_source(%{}, field), + do: field + + @doc ~S""" + Traverses changeset errors and applies the given function to error messages. + + This function is particularly useful when associations and embeds + are cast in the changeset as it will traverse all associations and + embeds and place all errors in a series of nested maps. + + A changeset is supplied along with a function to apply to each + error message as the changeset is traversed. The error message + function receives an error tuple `{msg, opts}`, for example: + + {"should be at least %{count} characters", [count: 3, validation: :length, min: 3]} + + ## Examples + + iex> traverse_errors(changeset, fn {msg, opts} -> + ...> Regex.replace(~r"%{(\w+)}", msg, fn _, key -> + ...> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() + ...> end) + ...> end) + %{title: ["should be at least 3 characters"]} + + Optionally function can accept three arguments: `changeset`, `field` + and error tuple `{msg, opts}`. It is useful whenever you want to extract + validations rules from `changeset.validations` to build detailed error + description. + """ + @spec traverse_errors(t, (error -> String.t()) | (Changeset.t(), atom, error -> String.t())) :: + traverse_result + def traverse_errors( + %Changeset{errors: errors, changes: changes, types: types} = changeset, + msg_func + ) + when is_function(msg_func, 1) or is_function(msg_func, 3) do + errors + |> Enum.reverse() + |> merge_keyword_keys(msg_func, changeset) + |> merge_related_keys(changes, types, msg_func, &traverse_errors/2) + end + + defp merge_keyword_keys(keyword_list, msg_func, _) when is_function(msg_func, 1) do + Enum.reduce(keyword_list, %{}, fn {key, val}, acc -> + val = msg_func.(val) + Map.update(acc, key, [val], &[val | &1]) + end) + end + + defp merge_keyword_keys(keyword_list, msg_func, changeset) when is_function(msg_func, 3) do + Enum.reduce(keyword_list, %{}, fn {key, val}, acc -> + val = msg_func.(changeset, key, val) + Map.update(acc, key, [val], &[val | &1]) + end) + end + + defp merge_related_keys(_, _, nil, _, _) do + raise ArgumentError, "changeset does not have types information" + end + + defp merge_related_keys(map, changes, types, msg_func, traverse_function) do + Enum.reduce(types, map, fn + {field, {tag, %{cardinality: :many}}}, acc when tag in @relations -> + if changesets = Map.get(changes, field) do + {child, all_empty?} = + Enum.map_reduce(changesets, true, fn changeset, all_empty? -> + child = traverse_function.(changeset, msg_func) + {child, all_empty? and child == %{}} + end) + + case all_empty? do + true -> acc + false -> Map.put(acc, field, child) + end + else + acc + end + + {field, {tag, %{cardinality: :one}}}, acc when tag in @relations -> + if changeset = Map.get(changes, field) do + case traverse_function.(changeset, msg_func) do + child when child == %{} -> acc + child -> Map.put(acc, field, child) + end + else + acc + end + + {_, _}, acc -> + acc + end) + end + + defp apply_relation_changes(acc, key, relation, value) do + relation_changed = Relation.apply_changes(relation, value) + + acc = Map.put(acc, key, relation_changed) + + with %Ecto.Association.BelongsTo{related_key: related_key} <- relation, + %{^related_key => id} <- relation_changed do + Map.put(acc, relation.owner_key, id) + else + _ -> acc + end + end + + @doc ~S""" + Traverses changeset validations and applies the given function to validations. + + This behaves the same as `traverse_errors/2`, but operates on changeset + validations instead of errors. + + ## Examples + + iex> traverse_validations(changeset, &(&1)) + %{title: [format: ~r/pattern/, length: [min: 1, max: 20]]} + + iex> traverse_validations(changeset, fn + ...> {:length, opts} -> {:length, "#{Keyword.get(opts, :min, 0)}-#{Keyword.get(opts, :max, 32)}"} + ...> {:format, %Regex{source: source}} -> {:format, "/#{source}/"} + ...> {other, opts} -> {other, inspect(opts)} + ...> end) + %{title: [format: "/pattern/", length: "1-20"]} + """ + @spec traverse_validations( + t, + (validation -> String.t()) | (Changeset.t(), atom, validation -> String.t()) + ) :: traverse_result + def traverse_validations( + %Changeset{validations: validations, changes: changes, types: types} = changeset, + msg_func + ) + when is_function(msg_func, 1) or is_function(msg_func, 3) do + validations + |> Enum.reverse() + |> merge_keyword_keys(msg_func, changeset) + |> merge_related_keys(changes, types, msg_func, &traverse_validations/2) + end +end + +defimpl Inspect, for: Ecto.Changeset do + import Inspect.Algebra + + def inspect(%Ecto.Changeset{data: data} = changeset, opts) do + # The trailing element is skipped later on + list = + for attr <- [:action, :changes, :errors, :data, :valid?, :action] do + {attr, Map.get(changeset, attr)} + end + + redacted_fields = + case data do + %type{} -> + if function_exported?(type, :__schema__, 1) do + type.__schema__(:redact_fields) + else + [] + end + + _ -> + [] + end + + container_doc("#Ecto.Changeset<", list, ">", %{limit: 5}, fn + {:action, action}, _opts -> + concat("action: ", to_doc(action, opts)) + + {:changes, changes}, _opts -> + concat("changes: ", changes |> filter(redacted_fields) |> to_doc(opts)) + + {:data, data}, _opts -> + concat("data: ", to_struct(data, opts)) + + {:errors, errors}, _opts -> + concat("errors: ", to_doc(errors, opts)) + + {:valid?, valid?}, _opts -> + concat("valid?: ", to_doc(valid?, opts)) + end) + end + + defp to_struct(%{__struct__: struct}, _opts), do: "#" <> Kernel.inspect(struct) <> "<>" + defp to_struct(other, opts), do: to_doc(other, opts) + + defp filter(changes, redacted_fields) do + Enum.reduce(redacted_fields, changes, fn redacted_field, changes -> + if Map.has_key?(changes, redacted_field) do + Map.put(changes, redacted_field, "**redacted**") + else + changes + end + end) + end +end diff --git a/deps/ecto/lib/ecto/changeset/relation.ex b/deps/ecto/lib/ecto/changeset/relation.ex new file mode 100644 index 0000000000000000000000000000000000000000..1cc76c98db2ad5568e5a53ddbab802a9775cfb72 --- /dev/null +++ b/deps/ecto/lib/ecto/changeset/relation.ex @@ -0,0 +1,584 @@ +defmodule Ecto.Changeset.Relation do + @moduledoc false + + require Logger + alias Ecto.Changeset + alias Ecto.Association.NotLoaded + + @type t :: %{required(:__struct__) => atom(), + required(:cardinality) => :one | :many, + required(:on_replace) => :raise | :mark_as_invalid | atom, + required(:relationship) => :parent | :child, + required(:ordered) => boolean, + required(:owner) => atom, + required(:related) => atom, + required(:field) => atom, + optional(atom()) => any()} + + @doc """ + Builds the related data. + """ + @callback build(t, owner :: Ecto.Schema.t) :: Ecto.Schema.t + + @doc """ + Returns empty container for relation. + """ + def empty(%{cardinality: cardinality}), do: cardinality_to_empty(cardinality) + + defp cardinality_to_empty(:one), do: nil + defp cardinality_to_empty(:many), do: [] + + @doc """ + Checks if the container can be considered empty. + """ + def empty?(%{cardinality: _}, %NotLoaded{}), do: true + def empty?(%{cardinality: :many}, []), do: true + def empty?(%{cardinality: :many}, changes), do: filter_empty(changes) == [] + def empty?(%{cardinality: :one}, nil), do: true + def empty?(%{}, _), do: false + + @doc """ + Filter empty changes + """ + def filter_empty(changes) do + Enum.filter(changes, fn + %Changeset{action: action} when action in [:replace, :delete] -> false + _ -> true + end) + end + + @doc """ + Applies related changeset changes + """ + def apply_changes(%{cardinality: :one}, nil) do + nil + end + + def apply_changes(%{cardinality: :one}, changeset) do + apply_changes(changeset) + end + + def apply_changes(%{cardinality: :many}, changesets) do + for changeset <- changesets, + struct = apply_changes(changeset), + do: struct + end + + defp apply_changes(%Changeset{action: :delete}), do: nil + defp apply_changes(%Changeset{action: :replace}), do: nil + defp apply_changes(changeset), do: Changeset.apply_changes(changeset) + + @doc """ + Loads the relation with the given struct. + + Loading will fail if the association is not loaded but the struct is. + """ + def load!(%{__meta__: %{state: :built}}, %NotLoaded{__cardinality__: cardinality}) do + cardinality_to_empty(cardinality) + end + + def load!(struct, %NotLoaded{__field__: field}) do + raise "attempting to cast or change association `#{field}` " <> + "from `#{inspect struct.__struct__}` that was not loaded. Please preload your " <> + "associations before manipulating them through changesets" + end + + def load!(_struct, loaded), do: loaded + + @doc """ + Casts related according to the `on_cast` function. + """ + def cast(%{cardinality: :one} = relation, _owner, nil, current, _on_cast) do + case current && on_replace(relation, current) do + :error -> {:error, {"is invalid", [type: expected_type(relation)]}} + _ -> {:ok, nil, true} + end + end + + def cast(%{cardinality: :one} = relation, owner, params, current, on_cast) when is_list(params) do + if Keyword.keyword?(params) do + cast(relation, owner, Map.new(params), current, on_cast) + else + {:error, {"is invalid", [type: expected_type(relation)]}} + end + end + + def cast(%{related: mod} = relation, owner, params, current, on_cast) do + pks = mod.__schema__(:primary_key) + fun = &do_cast(relation, owner, &1, &2, &3, &4, on_cast) + data_pk = data_pk(pks) + param_pk = param_pk(mod, pks) + + with :error <- cast_or_change(relation, params, current, data_pk, param_pk, fun) do + {:error, {"is invalid", [type: expected_type(relation)]}} + end + end + + defp do_cast(meta, owner, params, struct, allowed_actions, idx, {module, fun, args}) + when is_atom(module) and is_atom(fun) and is_list(args) do + IO.warn "passing a MFA to :with in cast_assoc/cast_embed is deprecated, please pass an anonymous function instead" + + on_cast = fn changeset, attrs -> + apply(module, fun, [changeset, attrs | args]) + end + + do_cast(meta, owner, params, struct, allowed_actions, idx, on_cast) + end + + defp do_cast(relation, owner, params, nil = _struct, allowed_actions, idx, on_cast) do + {:ok, + relation + |> apply_on_cast(on_cast, relation.__struct__.build(relation, owner), params, idx) + |> put_new_action(:insert) + |> check_action!(allowed_actions)} + end + + defp do_cast(relation, _owner, nil = _params, current, _allowed_actions, _idx, _on_cast) do + on_replace(relation, current) + end + + defp do_cast(relation, _owner, params, struct, allowed_actions, idx, on_cast) do + {:ok, + relation + |> apply_on_cast(on_cast, struct, params, idx) + |> put_new_action(:update) + |> check_action!(allowed_actions)} + end + + defp apply_on_cast(%{cardinality: :many}, on_cast, struct, params, idx) when is_function(on_cast, 3) do + on_cast.(struct, params, idx) + end + + defp apply_on_cast(%{cardinality: :one, field: field}, on_cast, _struct, _params, _idx) when is_function(on_cast, 3) do + raise ArgumentError, "invalid :with function for relation #{inspect(field)} " <> + "of cardinality one. Expected a function of arity 2" + end + + defp apply_on_cast(_relation, on_cast, struct, params, _idx) when is_function(on_cast, 2) do + on_cast.(struct, params) + end + + @doc """ + Wraps related structs in changesets. + """ + def change(%{cardinality: :one} = relation, nil, current) do + case current && on_replace(relation, current) do + :error -> {:error, {"is invalid", [type: expected_type(relation)]}} + _ -> {:ok, nil, true} + end + end + + def change(%{related: mod} = relation, value, current) do + get_pks = data_pk(mod.__schema__(:primary_key)) + with :error <- cast_or_change(relation, value, current, get_pks, get_pks, + &do_change(relation, &1, &2, &3, &4)) do + {:error, {"is invalid", [type: expected_type(relation)]}} + end + end + + # This may be an insert or an update, get all fields. + defp do_change(relation, %{__struct__: _} = changeset_or_struct, nil, _allowed_actions, _idx) do + changeset = Changeset.change(changeset_or_struct) + {:ok, + changeset + |> assert_changeset_struct!(relation) + |> put_new_action(action_from_changeset(changeset, nil))} + end + + defp do_change(relation, nil, current, _allowed_actions, _idx) do + on_replace(relation, current) + end + + defp do_change(relation, %Changeset{} = changeset, _current, allowed_actions, _idx) do + {:ok, + changeset + |> assert_changeset_struct!(relation) + |> put_new_action(:update) + |> check_action!(allowed_actions)} + end + + defp do_change(_relation, %{__struct__: _} = struct, _current, allowed_actions, _idx) do + {:ok, + struct + |> Ecto.Changeset.change + |> put_new_action(:update) + |> check_action!(allowed_actions)} + end + + defp do_change(relation, changes, current, allowed_actions, idx) + when is_list(changes) or is_map(changes) do + changeset = Ecto.Changeset.change(current || relation.__struct__.build(relation, nil), changes) + changeset = put_new_action(changeset, action_from_changeset(changeset, current)) + do_change(relation, changeset, current, allowed_actions, idx) + end + + defp action_from_changeset(%{data: %{__meta__: %{state: state}}}, _current) do + case state do + :built -> :insert + :loaded -> :update + :deleted -> :delete + end + end + + defp action_from_changeset(_, nil) do + :insert + end + + defp action_from_changeset(_, _current) do + :update + end + + defp assert_changeset_struct!(%{data: %{__struct__: mod}} = changeset, %{related: mod}) do + changeset + end + defp assert_changeset_struct!(%{data: data}, %{related: mod}) do + raise ArgumentError, "expected changeset data to be a #{mod} struct, got: #{inspect data}" + end + + @doc """ + Handles the changeset or struct when being replaced. + """ + def on_replace(%{on_replace: :mark_as_invalid}, _changeset_or_struct) do + :error + end + + def on_replace(%{on_replace: :raise, field: name, owner: owner}, _) do + raise """ + you are attempting to change relation #{inspect name} of + #{inspect owner} but the `:on_replace` option of this relation + is set to `:raise`. + + By default it is not possible to replace or delete embeds and + associations during `cast`. Therefore Ecto requires the parameters + given to `cast` to have IDs matching the data currently associated + to #{inspect owner}. Failing to do so results in this error message. + + If you want to replace data or automatically delete any data + not sent to `cast`, please set the appropriate `:on_replace` + option when defining the relation. The docs for `Ecto.Changeset` + covers the supported options in the "Associations, embeds and on + replace" section. + + However, if you don't want to allow data to be replaced or + deleted, only updated, make sure that: + + * If you are attempting to update an existing entry, you + are including the entry primary key (ID) in the data. + + * If you have a relationship with many children, all children + must be given on update. + + """ + end + + def on_replace(_relation, changeset_or_struct) do + {:ok, Changeset.change(changeset_or_struct) |> put_new_action(:replace)} + end + + defp raise_if_updating_with_struct!(%{field: name, owner: owner}, %{__struct__: _} = new) do + raise """ + you have set that the relation #{inspect name} of #{inspect owner} + has `:on_replace` set to `:update` but you are giving it a struct/ + changeset to put_assoc/put_change. + + Since you have set `:on_replace` to `:update`, you are only allowed + to update the existing entry by giving updated fields as a map or + keyword list or set it to nil. + + If you indeed want to replace the existing #{inspect name}, you have + to change the foreign key field directly. + + Got: #{inspect new} + """ + end + + defp raise_if_updating_with_struct!(_, _) do + true + end + + defp cast_or_change(%{cardinality: :one} = relation, value, current, current_pks_fun, new_pks_fun, fun) + when is_map(value) or is_list(value) or is_nil(value) do + single_change(relation, value, current_pks_fun, new_pks_fun, fun, current) + end + + defp cast_or_change(%{cardinality: :many}, [], [], _current_pks, _new_pks, _fun) do + {:ok, [], true} + end + + defp cast_or_change(%{cardinality: :many} = relation, value, current, current_pks_fun, new_pks_fun, fun) + when is_list(value) do + {current_pks, current_map} = process_current(current, current_pks_fun, relation) + %{unique: unique, ordered: ordered, related: mod} = relation + change_pks_fun = change_pk(mod.__schema__(:primary_key)) + ordered = if ordered, do: current_pks, else: [] + map_changes(value, new_pks_fun, change_pks_fun, fun, current_map, [], true, true, unique && %{}, 0, ordered) + end + + defp cast_or_change(_, _, _, _, _, _), do: :error + + # single change + + defp single_change(_relation, nil, _current_pks_fun, _new_pks_fun, fun, current) do + single_change(nil, current, fun, [:update, :delete], false) + end + + defp single_change(_relation, new, _current_pks_fun, _new_pks_fun, fun, nil) do + single_change(new, nil, fun, [:insert], false) + end + + defp single_change(%{on_replace: on_replace} = relation, new, current_pks_fun, new_pks_fun, fun, current) do + pk_values = new_pks_fun.(new) + + if (pk_values == current_pks_fun.(current) and pk_values != []) or + (on_replace == :update and raise_if_updating_with_struct!(relation, new)) do + single_change(new, current, fun, allowed_actions(pk_values), true) + else + case on_replace(relation, current) do + {:ok, _changeset} -> single_change(new, nil, fun, [:insert], false) + :error -> :error + end + end + end + + defp single_change(new, current, fun, allowed_actions, skippable?) do + case fun.(new, current, allowed_actions, nil) do + {:ok, %{action: :ignore}} -> + :ignore + {:ok, changeset} -> + if skippable? and skip?(changeset) do + :ignore + else + {:ok, changeset, changeset.valid?} + end + :error -> + :error + end + end + + # map changes + + defp map_changes([changes | rest], new_pks, change_pks, fun, current, acc, valid?, skip?, unique, idx, ordered) + when is_map(changes) or is_list(changes) do + pk_values = new_pks.(changes) + {struct, current, allowed_actions} = pop_current(current, pk_values) + + case fun.(changes, struct, allowed_actions, idx) do + {:ok, %{action: :ignore}} -> + ordered = pop_ordered(pk_values, ordered) + map_changes(rest, new_pks, change_pks, fun, current, acc, valid?, skip?, unique, idx + 1, ordered) + {:ok, changeset} -> + pk_values = change_pks.(changeset) + changeset = maybe_add_error_on_pk(changeset, pk_values, unique) + acc = [changeset | acc] + valid? = valid? and changeset.valid? + skip? = (struct != nil) and skip? and skip?(changeset) + unique = unique && Map.put(unique, pk_values, true) + ordered = pop_ordered(pk_values, ordered) + map_changes(rest, new_pks, change_pks, fun, current, acc, valid?, skip?, unique, idx + 1, ordered) + :error -> + :error + end + end + + defp map_changes([], _new_pks, _change_pks, fun, current, acc, valid?, skip?, _unique, _idx, ordered) do + current_structs = Enum.map(current, &elem(&1, 1)) + skip? = skip? and ordered == [] + reduce_delete_changesets(current_structs, fun, Enum.reverse(acc), valid?, skip?) + end + + defp map_changes(_params, _new_pks, _change_pks, _fun, _current, _acc, _valid?, _skip?, _unique, _idx, _ordered) do + :error + end + + defp pop_ordered(pk_values, [pk_values | tail]), do: tail + defp pop_ordered(_pk_values, tail), do: tail + + defp maybe_add_error_on_pk(%{data: %{__struct__: schema}} = changeset, pk_values, unique) do + if is_map(unique) and not missing_pks?(pk_values) and Map.has_key?(unique, pk_values) do + Enum.reduce(schema.__schema__(:primary_key), changeset, fn pk, acc -> + Changeset.add_error(acc, pk, "has already been taken") + end) + else + changeset + end + end + + defp missing_pks?(pk_values) do + pk_values == [] or Enum.any?(pk_values, &is_nil/1) + end + + defp allowed_actions(pk_values) do + if Enum.all?(pk_values, &is_nil/1) do + [:insert, :update, :delete] + else + [:update, :delete] + end + end + + defp reduce_delete_changesets([struct | rest], fun, acc, valid?, _skip?) do + case fun.(nil, struct, [:update, :delete], nil) do + {:ok, changeset} -> + valid? = valid? and changeset.valid? + reduce_delete_changesets(rest, fun, [changeset | acc], valid?, false) + + :error -> + :error + end + end + + defp reduce_delete_changesets([], _fun, _acc, _valid?, true), do: :ignore + defp reduce_delete_changesets([], _fun, acc, valid?, false), do: {:ok, acc, valid?} + + # helpers + + defp check_action!(changeset, allowed_actions) do + action = changeset.action + + cond do + action in allowed_actions -> + changeset + + action == :ignore -> + changeset + + action == :insert -> + raise "cannot insert related #{inspect changeset.data} " <> + "because it is already associated with the given struct" + + action == :replace -> + raise "cannot replace related #{inspect changeset.data}. " <> + "This typically happens when you are calling put_assoc/put_embed " <> + "with the results of a previous put_assoc/put_embed/cast_assoc/cast_embed " <> + "operation, which is not supported. You must call such operations only once " <> + "per embed/assoc, in order for Ecto to track changes efficiently" + + true -> + raise "cannot #{action} related #{inspect changeset.data} because " <> + "it already exists and it is not currently associated with the " <> + "given struct. Ecto forbids casting existing records through " <> + "the association field for security reasons. Instead, set " <> + "the foreign key value accordingly" + end + end + + defp process_current(nil, _get_pks, _relation), + do: {[], %{}} + + defp process_current(current, get_pks, relation) do + {pks, {map, counter}} = + Enum.map_reduce(current, {%{}, 0}, fn struct, {acc, counter} -> + pks = get_pks.(struct) + key = if pks == [], do: map_size(acc), else: pks + {pks, {Map.put(acc, key, struct), counter + 1}} + end) + + if map_size(map) != counter do + Logger.warning """ + found duplicate primary keys for association/embed `#{inspect(relation.field)}` \ + in `#{inspect(relation.owner)}`. In case of duplicate IDs, only the last entry \ + with the same ID will be kept. Make sure that all entries in `#{inspect(relation.field)}` \ + have an ID and the IDs are unique between them + """ + end + + {pks, map} + end + + defp pop_current(current, pk_values) do + case Map.pop(current, pk_values) do + {nil, current} -> {nil, current, [:insert]} + {struct, current} -> {struct, current, allowed_actions(pk_values)} + end + end + + defp data_pk(pks) do + fn + %Changeset{data: data} -> Enum.map(pks, &Map.get(data, &1)) + map when is_map(map) -> Enum.map(pks, &Map.get(map, &1)) + list when is_list(list) -> Enum.map(pks, &Keyword.get(list, &1)) + end + end + + defp param_pk(mod, pks) do + pks = Enum.map(pks, &{&1, Atom.to_string(&1), mod.__schema__(:type, &1)}) + fn params -> + Enum.map pks, fn {atom_key, string_key, type} -> + original = Map.get(params, string_key) || Map.get(params, atom_key) + case Ecto.Type.cast(type, original) do + {:ok, value} -> value + _ -> original + end + end + end + end + + defp change_pk(pks) do + fn %Changeset{} = cs -> + Enum.map(pks, fn pk -> + case cs.changes do + %{^pk => pk_value} -> pk_value + _ -> Map.get(cs.data, pk) + end + end) + end + end + + defp put_new_action(%{action: action} = changeset, new_action) when is_nil(action), + do: Map.put(changeset, :action, new_action) + defp put_new_action(changeset, _new_action), + do: changeset + + defp skip?(%{valid?: true, changes: empty, action: :update}) when empty == %{}, + do: true + defp skip?(_changeset), + do: false + + defp expected_type(%{cardinality: :one}), do: :map + defp expected_type(%{cardinality: :many}), do: {:array, :map} + + ## Surface changes on insert + + def surface_changes(%{changes: changes, types: types} = changeset, struct, fields) do + {changes, errors} = + Enum.reduce fields, {changes, []}, fn field, {changes, errors} -> + case {struct, changes, types} do + # User has explicitly changed it + {_, %{^field => _}, _} -> + {changes, errors} + + # Handle associations specially + {_, _, %{^field => {tag, embed_or_assoc}}} when tag in [:assoc, :embed] -> + # This is partly reimplementing the logic behind put_relation + # in Ecto.Changeset but we need to do it in a way where we have + # control over the current value. + value = not_loaded_to_empty(Map.get(struct, field)) + empty = empty(embed_or_assoc) + case change(embed_or_assoc, value, empty) do + {:ok, change, _} when change != empty -> + {Map.put(changes, field, change), errors} + {:error, error} -> + {changes, [{field, error}]} + _ -> # :ignore or ok with change == empty + {changes, errors} + end + + # Struct has a non nil value + {%{^field => value}, _, %{^field => _}} when value != nil -> + {Map.put(changes, field, value), errors} + + {_, _, _} -> + {changes, errors} + end + end + + case errors do + [] -> %{changeset | changes: changes} + _ -> %{changeset | errors: errors ++ changeset.errors, valid?: false, changes: changes} + end + end + + defp not_loaded_to_empty(%NotLoaded{__cardinality__: cardinality}), + do: cardinality_to_empty(cardinality) + + defp not_loaded_to_empty(loaded), do: loaded +end diff --git a/deps/ecto/lib/ecto/embedded.ex b/deps/ecto/lib/ecto/embedded.ex new file mode 100644 index 0000000000000000000000000000000000000000..e8c5fb28fb2f378da28a104333df15668ed68a22 --- /dev/null +++ b/deps/ecto/lib/ecto/embedded.ex @@ -0,0 +1,301 @@ +defmodule Ecto.Embedded do + @moduledoc """ + The embedding struct for `embeds_one` and `embeds_many`. + + Its fields are: + + * `cardinality` - The association cardinality + * `field` - The name of the association field on the schema + * `owner` - The schema where the association was defined + * `related` - The schema that is embedded + * `on_cast` - Function name to call by default when casting embeds + * `on_replace` - The action taken on associations when schema is replaced + + """ + alias __MODULE__ + alias Ecto.Changeset + alias Ecto.Changeset.Relation + + use Ecto.ParameterizedType + + @behaviour Relation + @on_replace_opts [:raise, :mark_as_invalid, :delete] + @embeds_one_on_replace_opts @on_replace_opts ++ [:update] + + defstruct [ + :cardinality, + :field, + :owner, + :related, + :on_cast, + on_replace: :raise, + unique: true, + ordered: true + ] + + ## Parameterized API + + # We treat even embed_many as maps, as that's often the + # most efficient format to encode them in the database. + @impl Ecto.ParameterizedType + def type(_), do: {:map, :any} + + @impl Ecto.ParameterizedType + def init(opts) do + opts = Keyword.put_new(opts, :on_replace, :raise) + cardinality = Keyword.fetch!(opts, :cardinality) + + on_replace_opts = + if cardinality == :one, do: @embeds_one_on_replace_opts, else: @on_replace_opts + + unless opts[:on_replace] in on_replace_opts do + raise ArgumentError, + "invalid `:on_replace` option for #{inspect(Keyword.fetch!(opts, :field))}. " <> + "The only valid options are: " <> + Enum.map_join(on_replace_opts, ", ", &"`#{inspect(&1)}`") + end + + struct(%Embedded{}, opts) + end + + @impl Ecto.ParameterizedType + def load(nil, _fun, %{cardinality: :one}), do: {:ok, nil} + + def load(value, fun, %{cardinality: :one, related: schema, field: field}) when is_map(value) do + {:ok, load_field(field, schema, value, fun)} + end + + def load(nil, _fun, %{cardinality: :many}), do: {:ok, []} + + def load(value, fun, %{cardinality: :many, related: schema, field: field}) + when is_list(value) do + {:ok, Enum.map(value, &load_field(field, schema, &1, fun))} + end + + def load(_value, _fun, _embed) do + :error + end + + defp load_field(_field, schema, value, loader) when is_map(value) do + Ecto.Schema.Loader.unsafe_load(schema, value, loader) + end + + defp load_field(field, _schema, value, _fun) do + raise ArgumentError, "cannot load embed `#{field}`, expected a map but got: #{inspect(value)}" + end + + @impl Ecto.ParameterizedType + def dump(nil, _, _), do: {:ok, nil} + + def dump(value, fun, %{cardinality: :one, related: schema, field: field}) when is_map(value) do + {:ok, dump_field(field, schema, value, schema.__schema__(:dump), fun, _one_embed? = true)} + end + + def dump(value, fun, %{cardinality: :many, related: schema, field: field}) + when is_list(value) do + types = schema.__schema__(:dump) + {:ok, Enum.map(value, &dump_field(field, schema, &1, types, fun, _one_embed? = false))} + end + + def dump(_value, _fun, _embed) do + :error + end + + defp dump_field(_field, schema, %{__struct__: schema} = struct, types, dumper, _one_embed?) do + Ecto.Schema.Loader.safe_dump(struct, types, dumper) + end + + defp dump_field(field, schema, value, _types, _dumper, one_embed?) do + one_or_many = + if one_embed?, + do: "a struct #{inspect(schema)} value", + else: "a list of #{inspect(schema)} struct values" + + raise ArgumentError, + "cannot dump embed `#{field}`, expected #{one_or_many} but got: #{inspect(value)}" + end + + @impl Ecto.ParameterizedType + def cast(nil, %{cardinality: :one}), do: {:ok, nil} + + def cast(%{__struct__: schema} = struct, %{cardinality: :one, related: schema}) do + {:ok, struct} + end + + def cast(nil, %{cardinality: :many}), do: {:ok, []} + + def cast(value, %{cardinality: :many, related: schema}) when is_list(value) do + if Enum.all?(value, &Kernel.match?(%{__struct__: ^schema}, &1)) do + {:ok, value} + else + :error + end + end + + def cast(_value, _embed) do + :error + end + + @impl Ecto.ParameterizedType + def embed_as(_, _), do: :dump + + ## End of parameterized API + + # Callback invoked by repository to prepare embeds. + # + # It replaces the changesets for embeds inside changes + # by actual structs so it can be dumped by adapters and + # loaded into the schema struct afterwards. + @doc false + def prepare(changeset, embeds, adapter, repo_action) do + %{changes: changes, types: types, repo: repo} = changeset + prepare(Map.take(changes, embeds), types, adapter, repo, repo_action) + end + + defp prepare(embeds, _types, _adapter, _repo, _repo_action) when embeds == %{} do + embeds + end + + defp prepare(embeds, types, adapter, repo, repo_action) do + Enum.reduce(embeds, embeds, fn {name, changeset_or_changesets}, acc -> + {:embed, embed} = Map.get(types, name) + Map.put(acc, name, prepare_each(embed, changeset_or_changesets, adapter, repo, repo_action)) + end) + end + + defp prepare_each(%{cardinality: :one}, nil, _adapter, _repo, _repo_action) do + nil + end + + defp prepare_each(%{cardinality: :one} = embed, changeset, adapter, repo, repo_action) do + action = normalize_action(changeset.action, repo_action, embed) + changeset = run_prepare(changeset, repo) + to_struct(changeset, action, embed, adapter) + end + + defp prepare_each(%{cardinality: :many} = embed, changesets, adapter, repo, repo_action) do + for changeset <- changesets, + action = normalize_action(changeset.action, repo_action, embed), + changeset = run_prepare(changeset, repo), + prepared = to_struct(changeset, action, embed, adapter), + do: prepared + end + + defp to_struct(%Changeset{valid?: false}, _action, %{related: schema}, _adapter) do + raise ArgumentError, + "changeset for embedded #{inspect(schema)} is invalid, " <> + "but the parent changeset was not marked as invalid" + end + + defp to_struct(%Changeset{data: %{__struct__: actual}}, _action, %{related: expected}, _adapter) + when actual != expected do + raise ArgumentError, + "expected changeset for embedded schema `#{inspect(expected)}`, " <> + "got: #{inspect(actual)}" + end + + defp to_struct(%Changeset{changes: changes, data: schema}, :update, _embed, _adapter) + when changes == %{} do + schema + end + + defp to_struct(%Changeset{}, :delete, _embed, _adapter) do + nil + end + + defp to_struct(%Changeset{data: data} = changeset, action, %{related: schema}, adapter) do + %{data: struct, changes: changes} = + changeset = + maybe_surface_changes(changeset, data, schema, action) + + embeds = prepare(changeset, schema.__schema__(:embeds), adapter, action) + + changes + |> Map.merge(embeds) + |> autogenerate_id(struct, action, schema, adapter) + |> autogenerate(action, schema) + |> apply_embeds(struct) + end + + defp maybe_surface_changes(changeset, data, schema, :insert) do + Relation.surface_changes(changeset, data, schema.__schema__(:fields)) + end + + defp maybe_surface_changes(changeset, _data, _schema, _action) do + changeset + end + + defp run_prepare(changeset, repo) do + changeset = %{changeset | repo: repo} + + Enum.reduce(Enum.reverse(changeset.prepare), changeset, fn fun, acc -> + case fun.(acc) do + %Ecto.Changeset{} = acc -> + acc + + other -> + raise "expected function #{inspect(fun)} given to Ecto.Changeset.prepare_changes/2 " <> + "to return an Ecto.Changeset, got: `#{inspect(other)}`" + end + end) + end + + defp apply_embeds(changes, struct) do + struct(struct, changes) + end + + defp normalize_action(:replace, _, %{on_replace: :delete}), do: :delete + defp normalize_action(:update, :insert, _), do: :insert + defp normalize_action(action, _, _), do: action + + defp autogenerate_id(changes, _struct, :insert, schema, adapter) do + case schema.__schema__(:autogenerate_id) do + {key, _source, :binary_id} -> + Map.put_new_lazy(changes, key, fn -> adapter.autogenerate(:embed_id) end) + + {_key, _source, :id} -> + raise ArgumentError, + "embedded schema `#{inspect(schema)}` cannot autogenerate `:id` primary keys, " <> + "those are typically used for auto-incrementing constraints. " <> + "Maybe you meant to use `:binary_id` instead?" + + nil -> + changes + end + end + + defp autogenerate_id(changes, struct, :update, _schema, _adapter) do + for {_, nil} <- Ecto.primary_key(struct) do + raise Ecto.NoPrimaryKeyValueError, struct: struct + end + + changes + end + + defp autogenerate(changes, action, schema) do + autogen_fields = action |> action_to_auto() |> schema.__schema__() + + Enum.reduce(autogen_fields, changes, fn {fields, {mod, fun, args}}, acc -> + case Enum.reject(fields, &Map.has_key?(changes, &1)) do + [] -> + acc + + fields -> + generated = apply(mod, fun, args) + Enum.reduce(fields, acc, &Map.put(&2, &1, generated)) + end + end) + end + + defp action_to_auto(:insert), do: :autogenerate + defp action_to_auto(:update), do: :autoupdate + + @impl Relation + def build(%Embedded{related: related}, _owner) do + related.__struct__() + end + + def preload_info(_embed) do + :embed + end +end diff --git a/deps/ecto/lib/ecto/enum.ex b/deps/ecto/lib/ecto/enum.ex new file mode 100644 index 0000000000000000000000000000000000000000..3a550a8085f828314cdfef445aa0d60713e7f51a --- /dev/null +++ b/deps/ecto/lib/ecto/enum.ex @@ -0,0 +1,341 @@ +defmodule Ecto.Enum do + @moduledoc """ + A custom type that maps atoms to strings or integers. + + `Ecto.Enum` must be used whenever you want to keep atom values in a field. + Since atoms cannot be persisted to the database, `Ecto.Enum` converts them + to strings or integers when writing to the database and converts them back + to atoms when loading data. It can be used in your schemas as follows: + + # Stored as strings + field :status, Ecto.Enum, values: [:foo, :bar, :baz] + + or + + # Stored as integers + field :status, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5] + + Therefore, the type to be used in your migrations for enum fields depends + on the choice above. For the cases above, one would do, respectively: + + add :status, :string + + or + + add :status, :integer + + Some databases also support enum types, which you could use in combination + with the above. + + Composite types, such as `:array`, are also supported which allow selecting + multiple values per record: + + field :roles, {:array, Ecto.Enum}, values: [:author, :editor, :admin] + + Overall, `:values` must be a list of atoms or a keyword list. Values will be + cast to atoms safely and only if the atom exists in the list (otherwise an + error will be raised). Attempting to load any string/integer not represented + by an atom in the list will be invalid. + + The helper function `mappings/2` returns the mappings for a given schema and + field, which can be used in places like form drop-downs. See `mappings/2` for + examples. + + If you want the values only, you can use `values/2`, and if you want + the "dump-able" values only, you can use `dump_values/2`. + + ## Embeds + + `Ecto.Enum` allows to customize how fields are dumped within embeds through the + `:embed_as` option. Two alternatives are supported: `:values`, which will save + the enum keys (and not their respective mapping), and `:dumped`, which will save + the dumped value. The default is `:values`. For example, assuming the following + schema: + + defmodule EnumSchema do + use Ecto.Schema + + schema "my_schema" do + embeds_one :embed, Embed do + field :embed_as_values, Ecto.Enum, values: [foo: 1, bar: 2], embed_as: :values + field :embed_as_dump, Ecto.Enum, values: [foo: 1, bar: 2], embed_as: :dumped + end + end + end + + The `:embed_as_values` field value will save `:foo` or `:bar`, while the + `:embed_as_dump` field value will save `1` or `2`. + """ + + use Ecto.ParameterizedType + + @impl true + def type(params), do: params.type + + @impl true + def init(opts) do + values = opts[:values] + + {type, mappings} = + cond do + is_list(values) and Enum.all?(values, &is_atom/1) -> + validate_unique!(values) + {:string, Enum.map(values, fn atom -> {atom, to_string(atom)} end)} + + type = Keyword.keyword?(values) and infer_type(Keyword.values(values)) -> + validate_unique!(Keyword.keys(values)) + validate_unique!(Keyword.values(values)) + {type, values} + + true -> + raise ArgumentError, """ + Ecto.Enum types must have a values option specified as a list of atoms or a + keyword list with a mapping from atoms to either integer or string values. + + For example: + + field :my_field, Ecto.Enum, values: [:foo, :bar] + + or + + field :my_field, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5] + """ + end + + on_load = Map.new(mappings, fn {key, val} -> {val, key} end) + on_dump = Map.new(mappings) + on_cast = Map.new(mappings, fn {key, _} -> {Atom.to_string(key), key} end) + + embed_as = + case Keyword.get(opts, :embed_as, :values) do + :values -> + :self + + :dumped -> + :dump + + other -> + raise ArgumentError, """ + the `:embed_as` option for `Ecto.Enum` accepts either `:values` or `:dumped`, + received: `#{inspect(other)}` + """ + end + + %{ + on_load: on_load, + on_dump: on_dump, + on_cast: on_cast, + mappings: mappings, + embed_as: embed_as, + type: type + } + end + + defp validate_unique!(values) do + if length(Enum.uniq(values)) != length(values) do + raise ArgumentError, """ + Ecto.Enum type values must be unique. + + For example: + + field :my_field, Ecto.Enum, values: [:foo, :bar, :foo] + + is invalid, while + + field :my_field, Ecto.Enum, values: [:foo, :bar, :baz] + + is valid + """ + end + end + + defp infer_type(values) do + cond do + Enum.all?(values, &is_integer/1) -> :integer + Enum.all?(values, &is_binary/1) -> :string + true -> nil + end + end + + @impl true + def cast(nil, _params), do: {:ok, nil} + + def cast(data, params) do + case params do + %{on_load: %{^data => as_atom}} -> + {:ok, as_atom} + + %{on_dump: %{^data => _}} -> + {:ok, data} + + %{on_cast: %{^data => as_atom}} -> + {:ok, as_atom} + + params -> + {:error, validation: :inclusion, enum: Map.keys(params.on_cast)} + end + end + + @impl true + def load(nil, _, _), do: {:ok, nil} + + def load(data, _loader, %{on_load: on_load}) do + case on_load do + %{^data => as_atom} -> {:ok, as_atom} + _ -> :error + end + end + + @impl true + def dump(nil, _, _), do: {:ok, nil} + + def dump(data, _dumper, %{on_dump: on_dump}) do + case on_dump do + %{^data => as_string} -> {:ok, as_string} + _ -> :error + end + end + + @impl true + def equal?(a, b, _params), do: a == b + + @impl true + def embed_as(_, %{embed_as: embed_as}), do: embed_as + + @impl true + def format(%{mappings: mappings}) do + "#Ecto.Enum" + end + + @doc """ + Returns the possible values for a given schema or types map and field. + + These values are the atoms that represent the different possible values + of the field. + + ## Examples + + Assuming this schema: + + defmodule MySchema do + use Ecto.Schema + + schema "my_schema" do + field :my_string_enum, Ecto.Enum, values: [:foo, :bar, :baz] + field :my_integer_enum, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5] + end + end + + Then: + + Ecto.Enum.values(MySchema, :my_string_enum) + #=> [:foo, :bar, :baz] + + Ecto.Enum.values(MySchema, :my_integer_enum) + #=> [:foo, :bar, :baz] + + """ + @spec values(module | map, atom) :: [atom()] + def values(schema_or_types, field) do + schema_or_types + |> mappings(field) + |> Keyword.keys() + end + + @doc """ + Returns the possible dump values for a given schema or types map and field + + "Dump values" are the values that can be dumped in the database. For enums stored + as strings, these are the strings that will be dumped in the database. For enums + stored as integers, these are the integers that will be dumped in the database. + + ## Examples + + Assuming this schema: + + defmodule MySchema do + use Ecto.Schema + + schema "my_schema" do + field :my_string_enum, Ecto.Enum, values: [:foo, :bar, :baz] + field :my_integer_enum, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5] + end + end + + Then: + + Ecto.Enum.dump_values(MySchema, :my_string_enum) + #=> ["foo", "bar", "baz"] + + Ecto.Enum.dump_values(MySchema, :my_integer_enum) + #=> [1, 2, 5] + + `schema_or_types` can also be a types map. See `mappings/2` for more information. + """ + @spec dump_values(module | map, atom) :: [String.t()] | [integer()] + def dump_values(schema_or_types, field) do + schema_or_types + |> mappings(field) + |> Keyword.values() + end + + @doc """ + Returns the mappings between values and dumped values. + + ## Examples + + Assuming this schema: + + defmodule MySchema do + use Ecto.Schema + + schema "my_schema" do + field :my_string_enum, Ecto.Enum, values: [:foo, :bar, :baz] + field :my_integer_enum, Ecto.Enum, values: [foo: 1, bar: 2, baz: 5] + end + end + + Here are some examples of using `mappings/2` with it: + + Ecto.Enum.mappings(MySchema, :my_string_enum) + #=> [foo: "foo", bar: "bar", baz: "baz"] + + Ecto.Enum.mappings(MySchema, :my_integer_enum) + #=> [foo: 1, bar: 2, baz: 5] + + Examples of calling `mappings/2` with a types map: + + schemaless_types = %{ + my_enum: Ecto.ParameterizedType.init(Ecto.Enum, values: [:foo, :bar, :baz]), + my_integer_enum: Ecto.ParameterizedType.init(Ecto.Enum, values: [foo: 1, bar: 2, baz: 5]) + } + + Ecto.Enum.mappings(schemaless_types, :my_enum) + #=> [foo: "foo", bar: "bar", baz: "baz"] + Ecto.Enum.mappings(schemaless_types, :my_integer_enum) + #=> [foo: 1, bar: 2, baz: 5] + + """ + @spec mappings(module | map, atom) :: keyword(String.t() | integer()) + def mappings(schema_or_types, field) + + def mappings(types, field) when is_map(types) do + case types do + %{^field => {:parameterized, {Ecto.Enum, %{mappings: mappings}}}} -> mappings + %{^field => {_, {:parameterized, {Ecto.Enum, %{mappings: mappings}}}}} -> mappings + %{^field => _} -> raise ArgumentError, "#{field} is not an Ecto.Enum field" + %{} -> raise ArgumentError, "#{field} does not exist" + end + end + + def mappings(schema, field) when is_atom(schema) do + try do + schema.__changeset__() + rescue + _ in UndefinedFunctionError -> + raise ArgumentError, "#{inspect(schema)} is not an Ecto schema or types map" + else + %{} = types -> mappings(types, field) + end + end +end diff --git a/deps/ecto/lib/ecto/exceptions.ex b/deps/ecto/lib/ecto/exceptions.ex new file mode 100644 index 0000000000000000000000000000000000000000..22b096375f4f1feeaaa00045641a11e237d12e2b --- /dev/null +++ b/deps/ecto/lib/ecto/exceptions.ex @@ -0,0 +1,321 @@ +defmodule Ecto.Query.CompileError do + @moduledoc """ + Raised at compilation time when the query cannot be compiled. + """ + defexception [:message] +end + +defmodule Ecto.Query.CastError do + @moduledoc """ + Raised at runtime when a value cannot be cast. + """ + defexception [:type, :value, :message] + + def exception(opts) do + value = Keyword.fetch!(opts, :value) + type = Keyword.fetch!(opts, :type) + msg = Keyword.fetch!(opts, :message) + %__MODULE__{value: value, type: type, message: msg} + end +end + +defmodule Ecto.QueryError do + @moduledoc """ + Raised at runtime when the query is invalid. + """ + defexception [:message] + + def exception(opts) do + message = Keyword.fetch!(opts, :message) + query = Keyword.fetch!(opts, :query) + hint = Keyword.get(opts, :hint) + + message = """ + #{message} in query: + + #{Inspect.Ecto.Query.to_string(query)} + """ + + file = opts[:file] + line = opts[:line] + + message = + if file && line do + relative = Path.relative_to_cwd(file) + Exception.format_file_line(relative, line) <> " " <> message + else + message + end + + message = + if hint do + message <> "\n" <> hint <> "\n" + else + message + end + + %__MODULE__{message: message} + end +end + +defmodule Ecto.SubQueryError do + @moduledoc """ + Raised at runtime when a subquery is invalid. + """ + defexception [:message, :exception] + + def exception(opts) do + exception = Keyword.fetch!(opts, :exception) + query = Keyword.fetch!(opts, :query) + + message = """ + the following exception happened when compiling a subquery. + + #{Exception.format(:error, exception, []) |> String.replace("\n", "\n ")} + + The subquery originated from the following query: + + #{Inspect.Ecto.Query.to_string(query)} + """ + + %__MODULE__{message: message, exception: exception} + end +end + +defmodule Ecto.InvalidChangesetError do + @moduledoc """ + Raised when we cannot perform an action because the + changeset is invalid. + """ + defexception [:action, :changeset] + + def message(%{action: action, changeset: changeset}) do + changes = extract_changes(changeset) + errors = Ecto.Changeset.traverse_errors(changeset, & &1) + + """ + could not perform #{action} because changeset is invalid. + + Errors + + #{pretty(errors)} + + Applied changes + + #{pretty(changes)} + + Params + + #{pretty(changeset.params)} + + Changeset + + #{pretty(changeset)} + """ + end + + defp pretty(term) do + inspect(term, pretty: true) + |> String.split("\n") + |> Enum.map_join("\n", &(" " <> &1)) + end + + defp extract_changes(%Ecto.Changeset{changes: changes}) do + Enum.reduce(changes, %{}, fn {key, value}, acc -> + case value do + %Ecto.Changeset{action: :delete} -> acc + _ -> Map.put(acc, key, extract_changes(value)) + end + end) + end + + defp extract_changes([%Ecto.Changeset{action: :delete} | tail]), + do: extract_changes(tail) + + defp extract_changes([%Ecto.Changeset{} = changeset | tail]), + do: [extract_changes(changeset) | extract_changes(tail)] + + defp extract_changes(other), + do: other +end + +defmodule Ecto.CastError do + @moduledoc """ + Raised when a changeset can't cast a value. + """ + defexception [:message, :type, :value] + + def exception(opts) do + type = Keyword.fetch!(opts, :type) + value = Keyword.fetch!(opts, :value) + msg = opts[:message] || "cannot cast #{inspect(value)} to #{Ecto.Type.format(type)}" + %__MODULE__{message: msg, type: type, value: value} + end +end + +defmodule Ecto.InvalidURLError do + defexception [:message, :url] + + def exception(opts) do + url = Keyword.fetch!(opts, :url) + msg = Keyword.fetch!(opts, :message) + msg = "invalid URL #{url}, #{msg}. The parsed URL is: #{inspect(URI.parse(url))}" + %__MODULE__{message: msg, url: url} + end +end + +defmodule Ecto.NoPrimaryKeyFieldError do + @moduledoc """ + Raised at runtime when an operation that requires a primary key is invoked + with a schema that does not define a primary key by using `@primary_key false` + """ + defexception [:message, :schema] + + def exception(opts) do + schema = Keyword.fetch!(opts, :schema) + message = "schema `#{inspect(schema)}` has no primary key" + %__MODULE__{message: message, schema: schema} + end +end + +defmodule Ecto.NoPrimaryKeyValueError do + @moduledoc """ + Raised at runtime when an operation that requires a primary key is invoked + with a schema missing value for its primary key + """ + defexception [:message, :struct] + + def exception(opts) do + struct = Keyword.fetch!(opts, :struct) + message = "struct `#{inspect(struct)}` is missing primary key value" + %__MODULE__{message: message, struct: struct} + end +end + +defmodule Ecto.ChangeError do + defexception [:message] +end + +defmodule Ecto.NoResultsError do + defexception [:message] + + def exception(opts) do + query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query() + + msg = """ + expected at least one result but got none in query: + + #{Inspect.Ecto.Query.to_string(query)} + """ + + %__MODULE__{message: msg} + end +end + +defmodule Ecto.MultipleResultsError do + defexception [:message] + + def exception(opts) do + query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query() + count = Keyword.fetch!(opts, :count) + + msg = """ + expected at most one result but got #{count} in query: + + #{Inspect.Ecto.Query.to_string(query)} + """ + + %__MODULE__{message: msg} + end +end + +defmodule Ecto.MultiplePrimaryKeyError do + defexception [:message] + + def exception(opts) do + operation = Keyword.fetch!(opts, :operation) + source = Keyword.fetch!(opts, :source) + params = Keyword.fetch!(opts, :params) + count = Keyword.fetch!(opts, :count) + + msg = """ + expected #{operation} on #{source} to return at most one entry but got #{count} entries. + + This typically means the field(s) set as primary_key in your schema/source + are not enough to uniquely identify entries in the repository. + + Those are the parameters sent to the repository: + + #{inspect(params)} + """ + + %__MODULE__{message: msg} + end +end + +defmodule Ecto.MigrationError do + defexception [:message] +end + +defmodule Ecto.StaleEntryError do + defexception [:message, :changeset] + + def exception(opts) do + action = Keyword.fetch!(opts, :action) + changeset = Keyword.fetch!(opts, :changeset) + + msg = """ + attempted to #{action} a stale struct: + + #{inspect(changeset.data)} + + This typically happens when the struct no longer exists in the database \ + or a database trigger/rule has forbidden the action. If stale entries are \ + expected, you may use `:stale_error_field` to convert this into a changeset \ + error, or set `:allow_stale` to true if you would like stale operations to \ + be considered a success (such as a stale deletion) + """ + + %__MODULE__{message: msg, changeset: changeset} + end +end + +defmodule Ecto.ConstraintError do + defexception [:type, :constraint, :message] + + def exception(opts) do + type = Keyword.fetch!(opts, :type) + constraint = Keyword.fetch!(opts, :constraint) + changeset = Keyword.fetch!(opts, :changeset) + action = Keyword.fetch!(opts, :action) + + constraints = + case changeset.constraints do + [] -> + "The changeset has not defined any constraint." + + constraints -> + "The changeset defined the following constraints:\n\n" <> + Enum.map_join( + constraints, + "\n", + &" * #{inspect(&1.constraint)} (#{&1.type}_constraint)" + ) + end + + msg = """ + constraint error when attempting to #{action} struct: + + * #{inspect(constraint)} (#{type}_constraint) + + If you would like to stop this constraint violation from raising an + exception and instead add it as an error to your changeset, please + call `#{type}_constraint/3` on your changeset with the constraint + `:name` as an option. + + #{constraints} + """ + + %__MODULE__{message: msg, type: type, constraint: constraint} + end +end diff --git a/deps/ecto/lib/ecto/json.ex b/deps/ecto/lib/ecto/json.ex new file mode 100644 index 0000000000000000000000000000000000000000..b28c5d462e5a757bbe14031665fb2ec620c0bf6a --- /dev/null +++ b/deps/ecto/lib/ecto/json.ex @@ -0,0 +1,48 @@ +if Code.ensure_loaded?(Jason.Encoder) do + defimpl Jason.Encoder, for: Ecto.Association.NotLoaded do + def encode(%{__owner__: owner, __field__: field}, _) do + raise """ + cannot encode association #{inspect(field)} from #{inspect(owner)} to \ + JSON because the association was not loaded. + + You can either preload the association: + + Repo.preload(#{inspect(owner)}, #{inspect(field)}) + + Or choose to not encode the association when converting the struct \ + to JSON by explicitly listing the JSON fields in your schema: + + defmodule #{inspect(owner)} do + # ... + + @derive {Jason.Encoder, only: [:name, :title, ...]} + schema ... do + + You can also use the :except option instead of :only if you would \ + prefer to skip some fields. + """ + end + end + + defimpl Jason.Encoder, for: Ecto.Schema.Metadata do + def encode(%{schema: schema}, _) do + raise """ + cannot encode metadata from the :__meta__ field for #{inspect(schema)} \ + to JSON. This metadata is used internally by Ecto and should never be \ + exposed externally. + + You can either map the schemas to remove the :__meta__ field before \ + encoding or explicitly list the JSON fields in your schema: + + defmodule #{inspect(schema)} do + # ... + + @derive {Jason.Encoder, only: [:name, :title, ...]} + schema ... do + + You can also use the :except option instead of :only if you would \ + prefer to skip some fields. + """ + end + end +end diff --git a/deps/ecto/lib/ecto/multi.ex b/deps/ecto/lib/ecto/multi.ex new file mode 100644 index 0000000000000000000000000000000000000000..218e8d9d6cf318b2592424e9c4ab48e5a186d3e5 --- /dev/null +++ b/deps/ecto/lib/ecto/multi.ex @@ -0,0 +1,990 @@ +defmodule Ecto.Multi do + @moduledoc """ + `Ecto.Multi` is a data structure for grouping multiple Repo operations. + + `Ecto.Multi` makes it possible to pack operations that should be + performed in a single database transaction and gives a way to introspect + the queued operations without actually performing them. Each operation + is given a name that is unique and will identify its result in case of + success or failure. + + If a multi is valid (i.e. all the changesets in it are valid), + all operations will be executed in the order they were added. + + The `Ecto.Multi` structure should be considered opaque. You can use + `%Ecto.Multi{}` to pattern match the type, but accessing fields or + directly modifying them is not advised. + + `Ecto.Multi.to_list/1` returns a canonical representation of the + structure that can be used for introspection. + + ## Changesets + + If multi contains operations that accept changesets (like `insert/4`, + `update/4` or `delete/4`) they will be checked before starting the + transaction. If any changeset has errors, the transaction won't even + be started and the error will be immediately returned. + + Note: `insert/4`, `update/4`, `insert_or_update/4`, and `delete/4` + variants that accept a function do not perform these checks since + the functions are executed after the transaction has started. + + ## Run + + Multi allows you to run arbitrary functions as part of your transaction + via `run/3` and `run/5`. This is especially useful when an operation + depends on the value of a previous operation. For this reason, the + function given as a callback to `run/3` and `run/5` will receive the repo + as the first argument, and all changes performed by the multi so far as a + map for the second argument. + + The function given to `run` must return `{:ok, value}` or `{:error, value}` + as its result. Returning an error will abort any further operations + and make the whole multi fail. + + ## Example + + Let's look at an example definition and usage. The use case we'll be + looking into is resetting a password. We need to update the account + with proper information, log the request and remove all current sessions: + + defmodule PasswordManager do + alias Ecto.Multi + + def reset(account, params) do + Multi.new() + |> Multi.update(:account, Account.password_reset_changeset(account, params)) + |> Multi.insert(:log, Log.password_reset_changeset(account, params)) + |> Multi.delete_all(:sessions, Ecto.assoc(account, :sessions)) + end + end + + We can later execute it in the integration layer using Repo: + + Repo.transaction(PasswordManager.reset(account, params)) + + By pattern matching on the result we can differentiate different conditions: + + case result do + {:ok, %{account: account, log: log, sessions: sessions}} -> + # Operation was successful, we can access results (exactly the same + # we would get from running corresponding Repo functions) under keys + # we used for naming the operations. + {:error, failed_operation, failed_value, changes_so_far} -> + # One of the operations failed. We can access the operation's failure + # value (like changeset for operations on changesets) to prepare a + # proper response. We also get access to the results of any operations + # that succeeded before the indicated operation failed. However, any + # successful operations would have been rolled back. + end + + We can also easily unit test our transaction without actually running it. + Since changesets can use in-memory-data, we can use an account that is + constructed in memory as well (without persisting it to the database): + + test "dry run password reset" do + account = %Account{password: "letmein"} + multi = PasswordManager.reset(account, params) + + assert [ + {:account, {:update, account_changeset, []}}, + {:log, {:insert, log_changeset, []}}, + {:sessions, {:delete_all, query, []}} + ] = Ecto.Multi.to_list(multi) + + # We can introspect changesets and query to see if everything + # is as expected, for example: + assert account_changeset.valid? + assert log_changeset.valid? + assert inspect(query) == "#Ecto.Query" + end + + The name of each operation does not have to be an atom. This can be particularly + useful when you wish to update a collection of changesets at once, and track their + errors individually: + + accounts = [%Account{id: 1}, %Account{id: 2}] + + Enum.reduce(accounts, Multi.new(), fn account, multi -> + Multi.update( + multi, + {:account, account.id}, + Account.password_reset_changeset(account, params) + ) + end) + """ + + alias __MODULE__ + alias Ecto.Changeset + + defstruct operations: [], names: MapSet.new() + + @typedoc """ + Map of changes made so far during the current transaction. For any Multi + which returns `{:ok, result}`, its `t:name/0` is added as a key and its + result as the value. + """ + @type changes :: map + @type run :: (Ecto.Repo.t(), changes -> {:ok | :error, any}) + @type fun(result) :: (changes -> result) + @type merge :: (changes -> t) | {module, atom, [any]} + @typep schema_or_source :: binary | {binary, module} | module + @typep operation :: + {:changeset, Changeset.t(), Keyword.t()} + | {:run, run} + | {:put, any} + | {:inspect, Keyword.t()} + | {:merge, merge} + | {:update_all, Ecto.Query.t(), Keyword.t()} + | {:delete_all, Ecto.Query.t(), Keyword.t()} + | {:insert_all, schema_or_source, [map | Keyword.t()], Keyword.t()} + @typep operations :: [{name, operation}] + + @typep names :: MapSet.t() + + @typedoc """ + Name of an operation in the Multi. Can be any term, as long as it is unique + within the list of operations; for example, `:insert_post` or `{:delete_post, + 5}`. + """ + @type name :: any + + @typedoc """ + Result of a failed transaction using a Multi. + """ + @type failure :: + {:error, failed_operation :: Ecto.Multi.name(), failed_value :: any(), + changes_so_far :: %{Ecto.Multi.name() => any}} + + @type t :: %__MODULE__{operations: operations, names: names} + + @doc """ + Returns an empty `Ecto.Multi` struct. + + ## Example + + iex> Ecto.Multi.new() |> Ecto.Multi.to_list() + [] + + """ + @spec new :: t + def new do + %Multi{} + end + + @doc """ + Appends the second multi to the first one. + + All names must be unique between both structures. + + ## Example + + iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end) + iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end) + iex> Ecto.Multi.append(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys + [:left, :right] + + """ + @spec append(t, t) :: t + def append(lhs, rhs) do + merge_structs(lhs, rhs, &(&2 ++ &1)) + end + + @doc """ + Prepends the second multi to the first one. + + All names must be unique between both structures. + + ## Example + + iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end) + iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end) + iex> Ecto.Multi.prepend(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys + [:right, :left] + + """ + @spec prepend(t, t) :: t + def prepend(lhs, rhs) do + merge_structs(lhs, rhs, &(&1 ++ &2)) + end + + defp merge_structs(%Multi{} = lhs, %Multi{} = rhs, joiner) do + %{names: lhs_names, operations: lhs_ops} = lhs + %{names: rhs_names, operations: rhs_ops} = rhs + + case MapSet.intersection(lhs_names, rhs_names) |> MapSet.to_list() do + [] -> + %Multi{names: MapSet.union(lhs_names, rhs_names), operations: joiner.(lhs_ops, rhs_ops)} + + common -> + raise ArgumentError, """ + error when merging the following Ecto.Multi structs: + + #{Kernel.inspect(lhs)} + + #{Kernel.inspect(rhs)} + + both declared operations: #{Kernel.inspect(common)} + """ + end + end + + @doc """ + Merges a multi returned dynamically by an anonymous function. + + This function is useful when the multi to be merged requires information + from the original multi. Hence the second argument is an anonymous function + that receives the multi changes so far. The anonymous function must return + another multi. + + If you would prefer to simply merge two multis together, see `append/2` or + `prepend/2`. + + Duplicated operations are not allowed. + + ## Example + + multi = + Ecto.Multi.new() + |> Ecto.Multi.insert(:post, %Post{title: "first"}) + + multi + |> Ecto.Multi.merge(fn %{post: post} -> + Ecto.Multi.new() + |> Ecto.Multi.insert(:comment, Ecto.build_assoc(post, :comments)) + end) + |> MyApp.Repo.transaction() + """ + @spec merge(t, (changes -> t)) :: t + def merge(%Multi{} = multi, merge) when is_function(merge, 1) do + Map.update!(multi, :operations, &[{:merge, {:merge, merge}} | &1]) + end + + @doc """ + Merges a multi returned dynamically by calling `module` and `function` with `args`. + + Similar to `merge/2`, but allows to pass module name, function and arguments. + The function should return an `Ecto.Multi`, and receives changes so far + as the first argument (prepended to those passed in the call to the function). + + Duplicated operations are not allowed. + """ + @spec merge(t, module, function, args) :: t when function: atom, args: [any] + def merge(%Multi{} = multi, mod, fun, args) + when is_atom(mod) and is_atom(fun) and is_list(args) do + Map.update!(multi, :operations, &[{:merge, {:merge, {mod, fun, args}}} | &1]) + end + + @doc """ + Adds an insert operation to the multi. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.insert/2`. + + ## Example + + Ecto.Multi.new() + |> Ecto.Multi.insert(:insert, %Post{title: "first"}) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.insert(:post, %Post{title: "first"}) + |> Ecto.Multi.insert(:comment, fn %{post: post} -> + Ecto.build_assoc(post, :comments) + end) + |> MyApp.Repo.transaction() + + """ + @spec insert( + t, + name, + Changeset.t() | Ecto.Schema.t() | fun(Changeset.t() | Ecto.Schema.t()), + Keyword.t() + ) :: t + def insert(multi, name, changeset_or_struct_or_fun, opts \\ []) + + def insert(multi, name, %Changeset{} = changeset, opts) do + add_changeset(multi, :insert, name, changeset, opts) + end + + def insert(multi, name, %_{} = struct, opts) do + insert(multi, name, Changeset.change(struct), opts) + end + + def insert(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:insert, fun}, opts)) + end + + @doc """ + Adds an update operation to the multi. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.update/2`. + + ## Example + + post = MyApp.Repo.get!(Post, 1) + changeset = Ecto.Changeset.change(post, title: "New title") + Ecto.Multi.new() + |> Ecto.Multi.update(:update, changeset) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.insert(:post, %Post{title: "first"}) + |> Ecto.Multi.update(:fun, fn %{post: post} -> + Ecto.Changeset.change(post, title: "New title") + end) + |> MyApp.Repo.transaction() + + """ + @spec update(t, name, Changeset.t() | fun(Changeset.t()), Keyword.t()) :: t + def update(multi, name, changeset_or_fun, opts \\ []) + + def update(multi, name, %Changeset{} = changeset, opts) do + add_changeset(multi, :update, name, changeset, opts) + end + + def update(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:update, fun}, opts)) + end + + @doc """ + Inserts or updates a changeset depending on whether the changeset was persisted or not. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.insert_or_update/2`. + + ## Example + + changeset = Post.changeset(%Post{}, %{title: "New title"}) + Ecto.Multi.new() + |> Ecto.Multi.insert_or_update(:insert_or_update, changeset) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.run(:post, fn repo, _changes -> + {:ok, repo.get(Post, 1) || %Post{}} + end) + |> Ecto.Multi.insert_or_update(:update, fn %{post: post} -> + Ecto.Changeset.change(post, title: "New title") + end) + |> MyApp.Repo.transaction() + + """ + @spec insert_or_update(t, name, Changeset.t() | fun(Changeset.t()), Keyword.t()) :: t + def insert_or_update(multi, name, changeset_or_fun, opts \\ []) + + def insert_or_update( + multi, + name, + %Changeset{data: %{__meta__: %{state: :loaded}}} = changeset, + opts + ) do + add_changeset(multi, :update, name, changeset, opts) + end + + def insert_or_update(multi, name, %Changeset{} = changeset, opts) do + add_changeset(multi, :insert, name, changeset, opts) + end + + def insert_or_update(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:insert_or_update, fun}, opts)) + end + + @doc """ + Adds a delete operation to the multi. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.delete/2`. + + ## Example + + post = MyApp.Repo.get!(Post, 1) + Ecto.Multi.new() + |> Ecto.Multi.delete(:delete, post) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.run(:post, fn repo, _changes -> + case repo.get(Post, 1) do + nil -> {:error, :not_found} + post -> {:ok, post} + end + end) + |> Ecto.Multi.delete(:delete, fn %{post: post} -> + # Others validations + post + end) + |> MyApp.Repo.transaction() + + """ + @spec delete( + t, + name, + Changeset.t() | Ecto.Schema.t() | fun(Changeset.t() | Ecto.Schema.t()), + Keyword.t() + ) :: t + def delete(multi, name, changeset_or_struct_fun, opts \\ []) + + def delete(multi, name, %Changeset{} = changeset, opts) do + add_changeset(multi, :delete, name, changeset, opts) + end + + def delete(multi, name, %_{} = struct, opts) do + delete(multi, name, Changeset.change(struct), opts) + end + + def delete(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:delete, fun}, opts)) + end + + @doc """ + Runs a query expecting one result and stores it in the multi. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.one/2`. + + ## Example + + Ecto.Multi.new() + |> Ecto.Multi.one(:post, Post) + |> Ecto.Multi.one(:author, fn %{post: post} -> + from(a in Author, where: a.id == ^post.author_id) + end) + |> MyApp.Repo.transaction() + """ + @spec one( + t, + name, + queryable :: Ecto.Queryable.t() | fun(Ecto.Queryable.t()), + opts :: Keyword.t() + ) :: t + def one(multi, name, queryable_or_fun, opts \\ []) + + def one(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:one, fun}, opts)) + end + + def one(multi, name, queryable, opts) do + run(multi, name, operation_fun({:one, fn _ -> queryable end}, opts)) + end + + @doc """ + Runs a query and stores all entries in the multi. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.all/2` does. + + ## Example + + Ecto.Multi.new() + |> Ecto.Multi.all(:all, Post) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.all(:all, fn _changes -> Post end) + |> MyApp.Repo.transaction() + """ + @spec all( + t, + name, + queryable :: Ecto.Queryable.t() | fun(Ecto.Queryable.t()), + opts :: Keyword.t() + ) :: t + def all(multi, name, queryable_or_fun, opts \\ []) + + def all(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:all, fun}, opts)) + end + + def all(multi, name, queryable, opts) do + run(multi, name, operation_fun({:all, fn _ -> queryable end}, opts)) + end + + @doc """ + Checks if there exists an entry matching the given query and stores a boolean in the multi. + + The `name` must be unique from other statements in the multi. + + The remaining arguments and options are the same as in `c:Ecto.Repo.exists?/2`. + + ## Example + + Ecto.Multi.new() + |> Ecto.Multi.exists?(:post, Post) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.exists?(:post, fn _changes -> Post end) + |> MyApp.Repo.transaction() + """ + @spec exists?( + t, + name, + queryable :: Ecto.Queryable.t() | fun(Ecto.Queryable.t()), + opts :: Keyword.t() + ) :: t + def exists?(multi, name, queryable_or_fun, opts \\ []) + + def exists?(multi, name, fun, opts) when is_function(fun, 1) do + run(multi, name, operation_fun({:exists?, fun}, opts)) + end + + def exists?(multi, name, queryable, opts) do + run(multi, name, operation_fun({:exists?, fn _ -> queryable end}, opts)) + end + + defp add_changeset(multi, action, name, changeset, opts) when is_list(opts) do + add_operation(multi, name, {:changeset, put_action(changeset, action), opts}) + end + + defp put_action(%{action: nil} = changeset, action) do + %{changeset | action: action} + end + + defp put_action(%{action: action} = changeset, action) do + changeset + end + + defp put_action(%{action: original}, action) do + raise ArgumentError, + "you provided a changeset with an action already set " <> + "to #{Kernel.inspect(original)} when trying to #{action} it" + end + + @doc """ + Causes the multi to fail with the given value. + + Running the multi in a transaction will execute + no previous steps and returns the value of the first + error added. + """ + @spec error(t, name, error :: term) :: t + def error(multi, name, value) do + add_operation(multi, name, {:error, value}) + end + + @doc """ + Adds a function to run as part of the multi. + + The function should return either `{:ok, value}` or `{:error, value}`, + and receives the repo as the first argument, and the changes so far + as the second argument. + + ## Example + + Ecto.Multi.run(multi, :write, fn _repo, %{image: image} -> + with :ok <- File.write(image.name, image.contents) do + {:ok, nil} + end + end) + """ + @spec run(t, name, run) :: t + def run(multi, name, run) when is_function(run, 2) do + add_operation(multi, name, {:run, run}) + end + + @doc """ + Adds a function to run as part of the multi. + + Similar to `run/3`, but allows to pass module name, function and arguments. + The function should return either `{:ok, value}` or `{:error, value}`, and + receives the repo as the first argument, and the changes so far as the + second argument (prepended to those passed in the call to the function). + """ + @spec run(t, name, module, function, args) :: t when function: atom, args: [any] + def run(multi, name, mod, fun, args) + when is_atom(mod) and is_atom(fun) and is_list(args) do + add_operation(multi, name, {:run, {mod, fun, args}}) + end + + @doc """ + Adds an insert_all operation to the multi. + + Accepts the same arguments and options as `c:Ecto.Repo.insert_all/3` does. + + ## Example + + posts = [%{title: "My first post"}, %{title: "My second post"}] + Ecto.Multi.new() + |> Ecto.Multi.insert_all(:insert_all, Post, posts) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.run(:post, fn repo, _changes -> + case repo.get(Post, 1) do + nil -> {:error, :not_found} + post -> {:ok, post} + end + end) + |> Ecto.Multi.insert_all(:insert_all, Comment, fn %{post: post} -> + # Others validations + + entries + |> Enum.map(fn comment -> + Map.put(comment, :post_id, post.id) + end) + end) + |> MyApp.Repo.transaction() + + """ + @spec insert_all( + t, + name, + schema_or_source, + entries_or_query_or_fun :: + [map | Keyword.t()] | fun([map | Keyword.t()]) | Ecto.Query.t(), + Keyword.t() + ) :: t + def insert_all(multi, name, schema_or_source, entries_or_query_or_fun, opts \\ []) + + def insert_all(multi, name, schema_or_source, entries_fun, opts) + when is_function(entries_fun, 1) and is_list(opts) do + run(multi, name, operation_fun({:insert_all, schema_or_source, entries_fun}, opts)) + end + + def insert_all(multi, name, schema_or_source, entries_or_query, opts) when is_list(opts) do + add_operation(multi, name, {:insert_all, schema_or_source, entries_or_query, opts}) + end + + @doc """ + Adds an update_all operation to the multi. + + Accepts the same arguments and options as `c:Ecto.Repo.update_all/3` does. + + ## Example + + Ecto.Multi.new() + |> Ecto.Multi.update_all(:update_all, Post, set: [title: "New title"]) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.run(:post, fn repo, _changes -> + case repo.get(Post, 1) do + nil -> {:error, :not_found} + post -> {:ok, post} + end + end) + |> Ecto.Multi.update_all(:update_all, fn %{post: post} -> + # Others validations + from(c in Comment, where: c.post_id == ^post.id, update: [set: [title: "New title"]]) + end, []) + |> MyApp.Repo.transaction() + + """ + @spec update_all( + t, + name, + Ecto.Queryable.t() | fun(Ecto.Queryable.t()), + Keyword.t(), + Keyword.t() + ) :: t + def update_all(multi, name, queryable_or_fun, updates, opts \\ []) + + def update_all(multi, name, queryable_fun, updates, opts) + when is_function(queryable_fun, 1) and is_list(opts) do + run(multi, name, operation_fun({:update_all, queryable_fun, updates}, opts)) + end + + def update_all(multi, name, queryable, updates, opts) when is_list(opts) do + query = Ecto.Queryable.to_query(queryable) + add_operation(multi, name, {:update_all, query, updates, opts}) + end + + @doc """ + Adds a delete_all operation to the multi. + + Accepts the same arguments and options as `c:Ecto.Repo.delete_all/2` does. + + ## Example + + queryable = from(p in Post, where: p.id < 5) + Ecto.Multi.new() + |> Ecto.Multi.delete_all(:delete_all, queryable) + |> MyApp.Repo.transaction() + + Ecto.Multi.new() + |> Ecto.Multi.run(:post, fn repo, _changes -> + case repo.get(Post, 1) do + nil -> {:error, :not_found} + post -> {:ok, post} + end + end) + |> Ecto.Multi.delete_all(:delete_all, fn %{post: post} -> + # Others validations + from(c in Comment, where: c.post_id == ^post.id) + end) + |> MyApp.Repo.transaction() + + """ + @spec delete_all(t, name, Ecto.Queryable.t() | fun(Ecto.Queryable.t()), Keyword.t()) :: t + def delete_all(multi, name, queryable_or_fun, opts \\ []) + + def delete_all(multi, name, fun, opts) when is_function(fun, 1) and is_list(opts) do + run(multi, name, operation_fun({:delete_all, fun}, opts)) + end + + def delete_all(multi, name, queryable, opts) when is_list(opts) do + query = Ecto.Queryable.to_query(queryable) + add_operation(multi, name, {:delete_all, query, opts}) + end + + defp add_operation(%Multi{} = multi, name, operation) do + %{operations: operations, names: names} = multi + + if MapSet.member?(names, name) do + raise "#{Kernel.inspect(name)} is already a member of the Ecto.Multi: \n#{Kernel.inspect(multi)}" + else + %{multi | operations: [{name, operation} | operations], names: MapSet.put(names, name)} + end + end + + @doc """ + Returns the list of operations stored in `multi`. + + Always use this function when you need to access the operations you + have defined in `Ecto.Multi`. Inspecting the `Ecto.Multi` struct internals + directly is discouraged. + """ + @spec to_list(t) :: [{name, term}] + def to_list(%Multi{operations: operations}) do + operations + |> Enum.reverse() + |> Enum.map(&format_operation/1) + end + + defp format_operation({name, {:changeset, changeset, opts}}), + do: {name, {changeset.action, changeset, opts}} + + defp format_operation(other), + do: other + + @doc """ + Adds a value to the changes so far under the given name. + + The given `value` is added to the multi before the transaction starts. + If you would like to run arbitrary functions as part of your transaction, + see `run/3` or `run/5`. + + ## Example + + Imagine there is an existing company schema that you retrieved from + the database. You can insert it as a change in the multi using `put/3`: + + Ecto.Multi.new() + |> Ecto.Multi.put(:company, company) + |> Ecto.Multi.insert(:user, fn changes -> User.changeset(changes.company) end) + |> Ecto.Multi.insert(:person, fn changes -> Person.changeset(changes.user, changes.company) end) + |> MyApp.Repo.transaction() + + In the example above there isn't a large benefit in putting the + `company` in the multi, because you could also access the + `company` variable directly inside the anonymous function. + + However, the benefit of `put/3` is when composing `Ecto.Multi`s. + If the insert operations above were defined in another module, + you could use `put(:company, company)` to inject changes that + will be accessed by other functions down the chain, removing + the need to pass both `multi` and `company` values around. + """ + @spec put(t, name, any) :: t + def put(multi, name, value) do + add_operation(multi, name, {:put, value}) + end + + @doc """ + Inspects results from a Multi + + By default, the name is shown as a label to the inspect, custom labels are + supported through the `IO.inspect/2` `label` option. + + ## Options + + All options for IO.inspect/2 are supported, it also support the following ones: + + * `:only` - A field or a list of fields to inspect, will print the entire + map by default. + + ## Examples + + Ecto.Multi.new() + |> Ecto.Multi.insert(:person_a, changeset) + |> Ecto.Multi.insert(:person_b, changeset) + |> Ecto.Multi.inspect() + |> MyApp.Repo.transaction() + + Prints: + %{person_a: %Person{...}, person_b: %Person{...}} + + We can use the `:only` option to limit which fields will be printed: + + Ecto.Multi.new() + |> Ecto.Multi.insert(:person_a, changeset) + |> Ecto.Multi.insert(:person_b, changeset) + |> Ecto.Multi.inspect(only: :person_a) + |> MyApp.Repo.transaction() + + Prints: + %{person_a: %Person{...}} + + """ + @spec inspect(t, Keyword.t()) :: t + def inspect(multi, opts \\ []) do + Map.update!(multi, :operations, &[{:inspect, {:inspect, opts}} | &1]) + end + + @doc false + @spec __apply__(t, Ecto.Repo.t(), fun, (term -> no_return)) :: {:ok, term} | {:error, term} + def __apply__(%Multi{} = multi, repo, wrap, return) do + operations = Enum.reverse(multi.operations) + + with {:ok, operations} <- check_operations_valid(operations) do + apply_operations(operations, multi.names, repo, wrap, return) + end + end + + defp check_operations_valid(operations) do + Enum.find_value(operations, &invalid_operation/1) || {:ok, operations} + end + + defp invalid_operation({name, {:changeset, %{valid?: false} = changeset, _}}), + do: {:error, {name, changeset, %{}}} + + defp invalid_operation({name, {:error, value}}), + do: {:error, {name, value, %{}}} + + defp invalid_operation(_operation), + do: nil + + defp apply_operations([], _names, _repo, _wrap, _return), do: {:ok, %{}} + + defp apply_operations(operations, names, repo, wrap, return) do + wrap.(fn -> + operations + |> Enum.reduce({%{}, names}, &apply_operation(&1, repo, wrap, return, &2)) + |> elem(0) + end) + end + + defp apply_operation({_, {:merge, merge}}, repo, wrap, return, {acc, names}) do + case __apply__(apply_merge_fun(merge, acc), repo, wrap, return) do + {:ok, value} -> + merge_results(acc, value, names) + + {:error, {name, value, nested_acc}} -> + {acc, _names} = merge_results(acc, nested_acc, names) + return.({name, value, acc}) + end + end + + defp apply_operation({_name, {:inspect, opts}}, _repo, _wrap_, _return, {acc, names}) do + if opts[:only] do + acc |> Map.take(List.wrap(opts[:only])) |> IO.inspect(opts) + else + IO.inspect(acc, opts) + end + + {acc, names} + end + + defp apply_operation({name, operation}, repo, wrap, return, {acc, names}) do + case apply_operation(operation, acc, {wrap, return}, repo) do + {:ok, value} -> + {Map.put(acc, name, value), names} + + {:error, value} -> + return.({name, value, acc}) + + other -> + raise "expected Ecto.Multi callback named `#{Kernel.inspect(name)}` to return either {:ok, value} or {:error, value}, got: #{Kernel.inspect(other)}" + end + end + + defp apply_operation({:changeset, changeset, opts}, _acc, _apply_args, repo), + do: apply(repo, changeset.action, [changeset, opts]) + + defp apply_operation({:run, run}, acc, _apply_args, repo), + do: apply_run_fun(run, repo, acc) + + defp apply_operation({:error, value}, _acc, _apply_args, _repo), + do: {:error, value} + + defp apply_operation({:insert_all, source, entries, opts}, _acc, _apply_args, repo), + do: {:ok, repo.insert_all(source, entries, opts)} + + defp apply_operation({:update_all, query, updates, opts}, _acc, _apply_args, repo), + do: {:ok, repo.update_all(query, updates, opts)} + + defp apply_operation({:delete_all, query, opts}, _acc, _apply_args, repo), + do: {:ok, repo.delete_all(query, opts)} + + defp apply_operation({:put, value}, _acc, _apply_args, _repo), + do: {:ok, value} + + defp apply_merge_fun({mod, fun, args}, acc), do: apply(mod, fun, [acc | args]) + defp apply_merge_fun(fun, acc), do: apply(fun, [acc]) + + defp apply_run_fun({mod, fun, args}, repo, acc), do: apply(mod, fun, [repo, acc | args]) + defp apply_run_fun(fun, repo, acc), do: apply(fun, [repo, acc]) + + defp merge_results(changes, new_changes, names) do + new_names = new_changes |> Map.keys() |> MapSet.new() + + case MapSet.intersection(names, new_names) |> MapSet.to_list() do + [] -> + {Map.merge(changes, new_changes), MapSet.union(names, new_names)} + + common -> + raise "cannot merge multi, the following operations were found in " <> + "both Ecto.Multi: #{Kernel.inspect(common)}" + end + end + + defp operation_fun({:update_all, queryable_fun, updates}, opts) do + fn repo, changes -> + {:ok, repo.update_all(queryable_fun.(changes), updates, opts)} + end + end + + defp operation_fun({:insert_all, schema_or_source, entries_fun}, opts) do + fn repo, changes -> + {:ok, repo.insert_all(schema_or_source, entries_fun.(changes), opts)} + end + end + + defp operation_fun({:delete_all, fun}, opts) do + fn repo, changes -> + {:ok, repo.delete_all(fun.(changes), opts)} + end + end + + defp operation_fun({:one, fun}, opts) do + fn repo, changes -> + {:ok, repo.one(fun.(changes), opts)} + end + end + + defp operation_fun({:all, fun}, opts) do + fn repo, changes -> + {:ok, repo.all(fun.(changes), opts)} + end + end + + defp operation_fun({:exists?, fun}, opts) do + fn repo, changes -> + {:ok, repo.exists?(fun.(changes), opts)} + end + end + + defp operation_fun({operation, fun}, opts) do + fn repo, changes -> + apply(repo, operation, [fun.(changes), opts]) + end + end +end diff --git a/deps/ecto/lib/ecto/parameterized_type.ex b/deps/ecto/lib/ecto/parameterized_type.ex new file mode 100644 index 0000000000000000000000000000000000000000..0fab2f08e85b04b5cfedca13ff1ac916d293cbb6 --- /dev/null +++ b/deps/ecto/lib/ecto/parameterized_type.ex @@ -0,0 +1,213 @@ +defmodule Ecto.ParameterizedType do + @moduledoc """ + Parameterized types are Ecto types that can be customized per field. + + Parameterized types allow a set of options to be specified in the schema + which are initialized on compilation and passed to the callback functions + as the last argument. + + For example, `field :foo, :string` behaves the same for every field. + On the other hand, `field :foo, Ecto.Enum, values: [:foo, :bar, :baz]` + will likely have a different set of values per field. + + Note that options are specified as a keyword, but it is idiomatic to + convert them to maps inside `c:init/1` for easier pattern matching in + other callbacks. + + Parameterized types are a superset of regular types. In other words, + with parameterized types you can do everything a regular type does, + and more. For example, parameterized types can handle `nil` values + in both `load` and `dump` callbacks, they can customize `cast` behavior + per query and per changeset, and also control how values are embedded. + + However, parameterized types are also more complex. Therefore, if + everything you need to achieve can be done with basic types, they + should be preferred to parameterized ones. + + ## Examples + + To create a parameterized type, create a module as shown below: + + defmodule MyApp.MyType do + use Ecto.ParameterizedType + + def type(_params), do: :string + + def init(opts) do + validate_opts(opts) + Enum.into(opts, %{}) + end + + def cast(data, params) do + ... + {:ok, cast_data} + end + + def load(data, _loader, params) do + ... + {:ok, loaded_data} + end + + def dump(data, dumper, params) do + ... + {:ok, dumped_data} + end + + def equal?(a, b, _params) do + a == b + end + end + + To use this type in a schema field, specify the type and parameters like this: + + schema "foo" do + field :bar, MyApp.MyType, opt1: :baz, opt2: :boo + end + + To use this type in places where you need it to be initialized (for example, + schemaless changesets), you can use `init/2`. + + > #### `use Ecto.ParameterizedType` {: .info} + > + > When you `use Ecto.ParameterizedType`, it will set + > `@behaviour Ecto.ParameterizedType` and define default, overridable + > implementations for `c:embed_as/2` and `c:equal?/3`. + """ + + @typedoc """ + The keyword options passed from the Schema's field macro into `c:init/1` + """ + @type opts :: keyword() + + @typedoc """ + The parameters for the ParameterizedType + + This is the value passed back from `c:init/1` and subsequently passed + as the last argument to all callbacks. Idiomatically it is a map. + """ + @type params :: term() + + @doc """ + Callback to convert the options specified in the field macro into parameters + to be used in other callbacks. + + This function is called at compile time, and should raise if invalid values are + specified. It is idiomatic that the parameters returned from this are a map. + `field` and `schema` will be injected into the options automatically. + + For example, this schema specification + + schema "my_table" do + field :my_field, MyParameterizedType, opt1: :foo, opt2: nil + end + + will result in the call: + + MyParameterizedType.init([schema: "my_table", field: :my_field, opt1: :foo, opt2: nil]) + + """ + @callback init(opts :: opts()) :: params() + + @doc """ + Casts the given input to the ParameterizedType with the given parameters. + + If the parameterized type is also a composite type, + the inner type can be cast by calling `Ecto.Type.cast/2` + directly. + + For more information on casting, see `c:Ecto.Type.cast/1`. + """ + @callback cast(data :: term, params()) :: + {:ok, term} | :error | {:error, keyword()} + + @doc """ + Loads the given term into a ParameterizedType. + + It receives a `loader` function in case the parameterized + type is also a composite type. In order to load the inner + type, the `loader` must be called with the inner type and + the inner value as argument. + + For more information on loading, see `c:Ecto.Type.load/1`. + Note that this callback *will* be called when loading a `nil` + value, unlike `c:Ecto.Type.load/1`. + """ + @callback load(value :: any(), loader :: function(), params()) :: {:ok, value :: any()} | :error + + @doc """ + Dumps the given term into an Ecto native type. + + It receives a `dumper` function in case the parameterized + type is also a composite type. In order to dump the inner + type, the `dumper` must be called with the inner type and + the inner value as argument. + + For more information on dumping, see `c:Ecto.Type.dump/1`. + Note that this callback *will* be called when dumping a `nil` + value, unlike `c:Ecto.Type.dump/1`. + """ + @callback dump(value :: any(), dumper :: function(), params()) :: {:ok, value :: any()} | :error + + @doc """ + Returns the underlying schema type for the ParameterizedType. + + For more information on schema types, see `c:Ecto.Type.type/0` + """ + @callback type(params()) :: Ecto.Type.t() + + @doc """ + Checks if two terms are semantically equal. + """ + @callback equal?(value1 :: any(), value2 :: any(), params()) :: boolean() + + @doc """ + Dictates how the type should be treated inside embeds. + + For more information on embedding, see `c:Ecto.Type.embed_as/1` + """ + @callback embed_as(format :: atom(), params()) :: :self | :dump + + @doc """ + Generates a loaded version of the data. + + This callback is invoked when a parameterized type is given + to `field` with the `:autogenerate` flag. + """ + @callback autogenerate(params()) :: term() + + @doc """ + Formats output when a ParameterizedType is printed in exceptions and + other logs. + + Note this callback is not used when constructing `Ecto.Changeset` validation + errors. See the `:message` option of most `Ecto.Changeset` validation + functions for how to customize error messaging on a per `Ecto.Changeset` basis. + """ + @callback format(params()) :: String.t() + + @optional_callbacks autogenerate: 1, format: 1 + + @doc """ + Inits a parameterized type given by `type` with `opts`. + + Useful when manually initializing a type for schemaless changesets. + """ + def init(type, opts) do + {:parameterized, {type, type.init(opts)}} + end + + @doc false + defmacro __using__(_) do + quote location: :keep do + @behaviour Ecto.ParameterizedType + + @doc false + def embed_as(_, _), do: :self + + @doc false + def equal?(term1, term2, _params), do: term1 == term2 + + defoverridable embed_as: 2, equal?: 3 + end + end +end diff --git a/deps/ecto/lib/ecto/query.ex b/deps/ecto/lib/ecto/query.ex new file mode 100644 index 0000000000000000000000000000000000000000..279448eb9502ca2f7428c1cf3063bf6f998d7c46 --- /dev/null +++ b/deps/ecto/lib/ecto/query.ex @@ -0,0 +1,3052 @@ +defmodule Ecto.SubQuery do + @moduledoc """ + A struct representing subqueries. + + Users of Ecto must consider this struct as opaque + and not access its field. Authors of adapters may + read its contents, but never modify them. + + See `Ecto.Query.subquery/2` for more information. + """ + defstruct [:query, :params, :select, :cache] + + @type t :: %__MODULE__{} +end + +defmodule Ecto.Query do + @moduledoc ~S""" + Provides the Query DSL. + + Queries are used to retrieve and manipulate data from a repository + (see `Ecto.Repo`). Ecto queries come in two flavors: keyword-based + and macro-based. Most examples will use the keyword-based syntax, + the macro one will be explored in later sections. + + Let's see a sample query: + + # Imports only from/2 of Ecto.Query + import Ecto.Query, only: [from: 2] + + # Create a query + query = from u in "users", + where: u.age > 18, + select: u.name + + # Send the query to the repository + Repo.all(query) + + In the example above, we are directly querying the "users" table + from the database. Queries do not reach out to the data store until + they are passed as arguments to a function from `Ecto.Repo`. + + ## Query expressions + + Ecto allows a limited set of expressions inside queries. In the + query below, for example, we use `u.age` to access a field, the + `>` comparison operator and the literal `0`: + + query = from u in "users", where: u.age > 0, select: u.name + + You can find the full list of operations in `Ecto.Query.API`. + Besides the operations listed there, the following literals are + supported in queries: + + * Integers: `1`, `2`, `3` + * Floats: `1.0`, `2.0`, `3.0` + * Booleans: `true`, `false` + * Binaries: `<<1, 2, 3>>` + * Strings: `"foo bar"`, `~s(this is a string)` + * Atoms (other than booleans and `nil`): `:foo`, `:bar` + * Arrays: `[1, 2, 3]`, `~w(interpolate words)` + + All other types and dynamic values must be passed as a parameter using + interpolation as explained below. + + ## Interpolation and casting + + External values and Elixir expressions can be injected into a query + expression with `^`: + + def with_minimum(age, height_ft) do + from u in "users", + where: u.age > ^age and u.height > ^(height_ft * 3.28), + select: u.name + end + + with_minimum(18, 5.0) + + When interpolating values, you may want to explicitly tell Ecto + what is the expected type of the value being interpolated: + + age = "18" + Repo.all(from u in "users", + where: u.age > type(^age, :integer), + select: u.name) + + In the example above, Ecto will cast the age to type integer. When + a value cannot be cast, `Ecto.Query.CastError` is raised. + + To avoid the repetition of always specifying the types, you may define + an `Ecto.Schema`. In such cases, Ecto will analyze your queries and + automatically cast the interpolated "age" when compared to the `u.age` + field, as long as the age field is defined with type `:integer` in + your schema: + + age = "18" + Repo.all(from u in User, where: u.age > ^age, select: u.name) + + Another advantage of using schemas is that we no longer need to specify + the select option in queries, as by default Ecto will retrieve all + fields specified in the schema: + + age = "18" + Repo.all(from u in User, where: u.age > ^age) + + For this reason, we will use schemas on the remaining examples but + remember Ecto does not require them in order to write queries. + + ## `nil` comparison + + `nil` comparison in filters, such as where and having, is forbidden + and it will raise an error: + + # Raises if age is nil + from u in User, where: u.age == ^age + + This is done as a security measure to avoid attacks that attempt + to traverse entries with nil columns. To check that value is `nil`, + use `is_nil/1` instead: + + from u in User, where: is_nil(u.age) + + ## Composition + + Ecto queries are composable. For example, the query above can + actually be defined in two parts: + + # Create a query + query = from u in User, where: u.age > 18 + + # Extend the query + query = from u in query, select: u.name + + Composing queries uses the same syntax as creating a query. + The difference is that, instead of passing a schema like `User` + on the right-hand side of `in`, we passed the query itself. + + Any value can be used on the right-hand side of `in` as long as it implements + the `Ecto.Queryable` protocol. For now, we know the protocol is + implemented for both atoms (like `User`) and strings (like "users"). + + In any case, regardless if a schema has been given or not, Ecto + queries are always composable thanks to its binding system. + + ### Positional bindings + + On the left-hand side of `in` we specify the query bindings. This is + done inside `from` and `join` clauses. In the query below `u` is a + binding and `u.age` is a field access using this binding. + + query = from u in User, where: u.age > 18 + + Bindings are not exposed from the query. When composing queries, you + must specify bindings again for each refinement query. For example, + to further narrow down the above query, we again need to tell Ecto what + bindings to expect: + + query = from u in query, select: u.city + + Bindings in Ecto are positional, and the names do not have to be + consistent between input and refinement queries. For example, the + query above could also be written as: + + query = from q in query, select: q.city + + It would make no difference to Ecto. This is important because + it allows developers to compose queries without caring about + the bindings used in the initial query. + + When using joins, the bindings should be matched in the order they + are specified: + + # Create a query + query = from p in Post, + join: c in Comment, on: c.post_id == p.id + + # Extend the query + query = from [p, c] in query, + select: {p.title, c.body} + + You are not required to specify all bindings when composing. + For example, if we would like to order the results above by + post insertion date, we could further extend it as: + + query = from q in query, order_by: q.inserted_at + + The example above will work if the input query has 1 or 10 + bindings. As long as the number of bindings is less than the + number of `from`s + `join`s, Ecto will match only what you have + specified. The first binding always matches the source given + in `from`. + + Similarly, if you are interested only in the last binding + (or the last bindings) in a query, you can use `...` to + specify "all bindings before" and match on the last one. + + For instance, imagine you wrote: + + posts_with_comments = + from p in query, join: c in Comment, on: c.post_id == p.id + + And now we want to make sure to return both the post title + and the comment body. Although we may not know how many + bindings there are in the query, we are sure posts is the + first binding and comments are the last one, so we can write: + + from [p, ..., c] in posts_with_comments, select: {p.title, c.body} + + In other words, `...` will include all the bindings between the + first and the last, which may be one, many or no bindings at all. + + ### Named bindings + + Another option for flexibly building queries with joins are named + bindings. Coming back to the previous example, we can use the + `as: :comment` option to bind the comments join to a concrete name: + + posts_with_comments = + from p in Post, + join: c in Comment, as: :comment, on: c.post_id == p.id + + Now we can refer to it using the following form of a bindings list: + + from [p, comment: c] in posts_with_comments, select: {p.title, c.body} + + This approach lets us not worry about keeping track of the position + of the bindings when composing the query. The `:as` option can be + given both on joins and on `from`: + + from p in Post, as: :post + + Only atoms are accepted for binding names. Named binding references + must always be placed at the end of the bindings list: + + [positional_binding_1, positional_binding_2, named_1: binding, named_2: binding] + + Named bindings can also be used for late binding with the `as/1` + construct, allowing you to refer to a binding that has not been + defined yet: + + from c in Comment, where: as(:posts).id == c.post_id + + This is especially useful when working with subqueries, where you + may need to refer to a parent binding with `parent_as`, which is + not known when writing the subquery: + + child_query = from c in Comment, where: parent_as(:posts).id == c.post_id + from p in Post, as: :posts, inner_lateral_join: c in subquery(child_query) + + You can also match on a specific binding when building queries. For + example, let's suppose you want to create a generic sort function + that will order by a given `field` with a given `as` in `query`: + + # Knowing the name of the binding + def sort(query, as, field) do + from [{^as, x}] in query, order_by: field(x, ^field) + end + + ### Bindingless operations + + Although bindings are extremely useful when working with joins, + they are not necessary when the query has only the `from` clause. + For such cases, Ecto supports a way for building queries + without specifying the binding: + + from Post, + where: [category: "fresh and new"], + order_by: [desc: :published_at], + select: [:id, :title, :body] + + The query above will select all posts with category "fresh and new", + order by the most recently published, and return Post structs with + only the id, title and body fields set. It is equivalent to: + + from p in Post, + where: p.category == "fresh and new", + order_by: [desc: p.published_at], + select: struct(p, [:id, :title, :body]) + + One advantage of bindingless queries is that they are data-driven + and therefore useful for dynamically building queries. For example, + the query above could also be written as: + + where = [category: "fresh and new"] + order_by = [desc: :published_at] + select = [:id, :title, :body] + from Post, where: ^where, order_by: ^order_by, select: ^select + + This feature is very useful when queries need to be built based + on some user input, like web search forms, CLIs and so on. + + ## Fragments + + If you need an escape hatch, Ecto provides fragments + (see `Ecto.Query.API.fragment/1`) to inject SQL (and non-SQL) + fragments into queries. + + For example, to get all posts while running the "lower(?)" + function in the database where `p.title` is interpolated + in place of `?`, one can write: + + from p in Post, + where: is_nil(p.published_at) and + fragment("lower(?)", p.title) == ^title + + Also, most adapters provide direct APIs for queries, like + `Ecto.Adapters.SQL.query/4`, allowing developers to + completely bypass Ecto queries. + + ## Macro API + + In all examples so far we have used the **keywords query syntax** to + create a query: + + import Ecto.Query + from u in "users", where: u.age > 18, select: u.name + + Due to the prevalence of the pipe operator in Elixir, Ecto also supports + a pipe-based syntax: + + "users" + |> where([u], u.age > 18) + |> select([u], u.name) + + The keyword-based and pipe-based examples are equivalent. The downside + of using macros is that the binding must be specified for every operation. + However, since keyword-based and pipe-based examples are equivalent, the + bindingless syntax also works for macros. Please note that the following + example is not completely equivalent to the previous example, + as it does not return the name but rather the `User` struct: + + "users" + |> where([u], u.age > 18) + |> select([:name]) + + Such a syntax allows developers to write queries using bindings only in more + complex query expressions. + + This module documents each of those macros, providing examples in + both the keywords query and pipe expression formats. + + ## Query prefix + + It is possible to set a prefix for the queries. For Postgres users, + this will specify the schema where the table is located, while for + MySQL users this will specify the database where the table is + located. When no prefix is set, Postgres queries are assumed to be + in the public schema, while MySQL queries are assumed to be in the + database set in the config for the repo. + + The query prefix may be set either for the whole query or on each + individual `from` and `join` expression. If a `prefix` is not given + to a `from` or a `join`, the prefix of the schema given to the `from` + or `join` is used. The query prefix is used only if none of the above + are declared. + + Let's see some examples. To set the query prefix globally, the simplest + mechanism is to pass an option to the repository operation: + + results = Repo.all(query, prefix: "accounts") + + You may also set the prefix for the whole query by setting the prefix field: + + results = + query # May be User or an Ecto.Query itself + |> Ecto.Query.put_query_prefix("accounts") + |> Repo.all() + + Setting the prefix in the query changes the default prefix of all `from` + and `join` expressions. You can override the query prefix by either setting + the `@schema_prefix` in your schema definitions or by passing the prefix + option: + + from u in User, + prefix: "accounts", + join: p in assoc(u, :posts), + prefix: "public" + + Overall, here is the prefix lookup precedence: + + 1. The `:prefix` option given to `from`/`join` has the highest precedence + 2. Then it falls back to the `@schema_prefix` attribute declared in the schema + given to `from`/`join` + 3. Then it falls back to the query prefix. The query prefix may be + set either on the query with `put_query_prefix/2` or by passing + the `:prefix` option when calling the `Repo` module (where the + former wins if both methods are used) + + The prefixes set in the query will be preserved when loading data. + """ + + @doc """ + The `Ecto.Query` struct. + + Users of Ecto must consider this struct as opaque + and not access its field directly. Authors of adapters + may read its contents, but never modify them. + """ + defstruct prefix: nil, + sources: nil, + from: nil, + joins: [], + aliases: %{}, + wheres: [], + select: nil, + order_bys: [], + limit: nil, + offset: nil, + group_bys: [], + combinations: [], + updates: [], + havings: [], + preloads: [], + assocs: [], + distinct: nil, + lock: nil, + windows: [], + with_ctes: nil + + defmodule FromExpr do + @moduledoc false + defstruct [:source, :file, :line, :as, :prefix, params: [], hints: []] + end + + defmodule DynamicExpr do + @moduledoc false + defstruct [:fun, :binding, :file, :line] + end + + defmodule QueryExpr do + @moduledoc false + defstruct [:expr, :file, :line, params: []] + end + + defmodule ByExpr do + @moduledoc false + defstruct [:expr, :file, :line, params: [], subqueries: []] + end + + defmodule BooleanExpr do + @moduledoc false + defstruct [:op, :expr, :file, :line, params: [], subqueries: []] + end + + defmodule SelectExpr do + @moduledoc false + defstruct [:expr, :file, :line, :fields, params: [], take: %{}, subqueries: [], aliases: %{}] + end + + defmodule JoinExpr do + @moduledoc false + defstruct [ + :qual, + :source, + :on, + :file, + :line, + :assoc, + :as, + :ix, + :prefix, + params: [], + hints: [] + ] + end + + defmodule WithExpr do + @moduledoc false + defstruct recursive: false, queries: [] + end + + defmodule LimitExpr do + @moduledoc false + defstruct [:expr, :file, :line, with_ties: false, params: []] + end + + defmodule Tagged do + @moduledoc false + # * value is the tagged value + # * tag is the directly tagged value, like Ecto.UUID + # * type is the underlying tag type, like :string + defstruct [:tag, :type, :value] + end + + defmodule Values do + @moduledoc false + defstruct [:types, :num_rows, :params] + + def new([], _types) do + raise ArgumentError, "must provide a non-empty list to values/2" + end + + def new(values_list, types) do + fields = fields(values_list) + types = types!(fields, types) + params = params!(values_list, types) + %__MODULE__{types: types, params: params, num_rows: length(values_list)} + end + + defp fields(values_list) do + fields = + Enum.reduce(values_list, MapSet.new(), fn values, fields -> + Enum.reduce(values, fields, fn {field, _}, fields -> + MapSet.put(fields, field) + end) + end) + + MapSet.to_list(fields) + end + + defp types!(fields, types) do + Enum.map(fields, fn field -> + case types do + %{^field => type} -> + {field, type} + + _ -> + raise ArgumentError, + "values/2 must declare the type for every field. " <> + "The type was not given for field `#{field}`" + end + end) + end + + defp params!(values_list, types) do + Enum.reduce(values_list, [], fn values, params -> + Enum.reduce(types, params, fn {field, type}, params -> + case values do + %{^field => value} -> + [{value, type} | params] + + _ -> + raise ArgumentError, + "each member of a values list must have the same fields. " <> + "Missing field `#{field}` in #{inspect(values)}" + end + end) + end) + end + end + + @type t :: %__MODULE__{} + @type dynamic_expr :: %DynamicExpr{} + + alias Ecto.Query.Builder + + @doc """ + Builds a dynamic query expression. + + Dynamic query expressions allow developers to compose query + expressions bit by bit, so that they can be interpolated into + parts of a query or another dynamic expression later on. + + ## Examples + + Imagine you have a set of conditions you want to build your query on: + + conditions = false + + conditions = + if params["is_public"] do + dynamic([p], p.is_public or ^conditions) + else + conditions + end + + conditions = + if params["allow_reviewers"] do + dynamic([p, a], a.reviewer == true or ^conditions) + else + conditions + end + + from query, where: ^conditions + + In the example above, we were able to build the query expressions + bit by bit, using different bindings, and later interpolate it all + at once into the actual query. + + A dynamic expression can always be interpolated inside another dynamic + expression and into the constructs described below. + + ## `where`, `having` and a `join`'s `on` + + The `dynamic` macro can be interpolated at the root of a `where`, + `having` or a `join`'s `on`. + + For example, assuming the `conditions` variable defined in the + previous section, the following is forbidden because it is not + at the root of a `where`: + + from q in query, where: q.some_condition and ^conditions + + Fortunately that's easily solved by simply rewriting it to: + + conditions = dynamic([q], q.some_condition and ^conditions) + from query, where: ^conditions + + > #### Dynamic boundaries {: .warning} + > + > Type casting does not cross dynamic boundaries. When you write + > a dynamic expression, such as `dynamic([p], p.visits > ^param)`, + > Ecto will automatically cast `^param` to the type of `p.visits`. + > + > However, if `p.visits` is in itself dynamic, as in the example + > below, then Ecto won't be able to propagate its type to `^param`: + > + > field = dynamic([p], p.visits) + > dynamic(^field > ^param) + > + + ## `order_by` + + Dynamics can be interpolated inside keyword lists at the root of + `order_by`. For example, you can write: + + order_by = [ + asc: :some_field, + desc: dynamic([p], fragment("?->>?", p.another_field, "json_key")) + ] + + from query, order_by: ^order_by + + Dynamics are also supported in `order_by/2` clauses inside `windows/2`. + + As with `where` and friends, it is not possible to pass dynamics + outside of a root. For example, this won't work: + + from query, order_by: [asc: ^dynamic(...)] + + But this will: + + from query, order_by: ^[asc: dynamic(...)] + + ## `group_by` + + Dynamics can be interpolated inside keyword lists at the root of + `group_by`. For example, you can write: + + group_by = [ + :some_field, + dynamic([p], fragment("?->>?", p.another_field, "json_key")) + ] + + from query, group_by: ^group_by + + Dynamics are also supported in `partition_by/2` clauses inside `windows/2`. + + As with `where` and friends, it is not possible to pass dynamics + outside of a root. For example, this won't work: + + from query, group_by: [:some_field, ^dynamic(...)] + + But this will: + + from query, group_by: ^[:some_field, dynamic(...)] + + ## `select` and `select_merge` + + Dynamics can be inside maps interpolated at the root of a + `select` or `select_merge`. For example, you can write: + + fields = %{ + period: dynamic([p], p.month), + metric: dynamic([p], p.distance) + } + + from query, select: ^fields + + As with `where` and friends, it is not possible to pass dynamics + outside of a root. For example, this won't work: + + from query, select: %{field: ^dynamic(...)} + + But this will: + + from query, select: ^%{field: dynamic(...)} + + Maps with dynamics can also be merged into existing `select` structures, + enabling a variety of possibilities for partially dynamic selects: + + metric = dynamic([p], p.distance) + + from query, select: [:period, :metric], select_merge: ^%{metric: metric} + + Aliasing fields with `selected_as/2` and referencing them with `selected_as/1` + is also allowed: + + fields = %{ + period: dynamic([p], selected_as(p.month, :month)), + metric: dynamic([p], p.distance) + } + + order = dynamic(selected_as(:month)) + + from query, select: ^fields, order_by: ^order + + ## `update` + + A `dynamic` is also supported inside updates, for example: + + updates = [ + set: [average: dynamic([p], p.sum / p.count)] + ] + + from query, update: ^updates + + ## `preload` + + Dynamics can be used with `preload` in order to dynamically + specify the binding for a joined association. For example, you can + write: + + preloads = [ + :non_joined_assoc, + joined_assoc: dynamic([joined: j], j) + ] + + from x in query, + join: assoc(x, :joined_assoc), + as: :joined, + preload: ^preloads + + While the example above uses a named binding (`:joined`), + positional bindings may also be used: + + preloads = [ + :non_joined_assoc, + joined_assoc: dynamic([_, j], j) + ] + + from x in query, + join: assoc(x, :joined_assoc) + preload: ^preloads + + As with `where` and friends, it is not possible to pass dynamics + outside of an interpolated root. For example, this won't work: + + from query, preload: [comments: ^dynamic(...)] + + But this will: + + from query, preload: ^[comments: dynamic(...)] + + Dynamic expressions used in `preload` must evaluate to a single + binding. For instance, this won't work: + + preloads = dynamic([comments: c, likes: l], [comments: {c, likes: l}]) + + But this will: + + dynamic_comments = dynamic([comments: c], c) + dynamic_likes = dynamic([likes: l], l) + + preloads = [ + comments: {dynamic_comments, likes: dynamic_likes} + ] + """ + defmacro dynamic(binding \\ [], expr) do + Builder.Dynamic.build(binding, expr, __CALLER__) + end + + @doc """ + Defines windows which can be used with `Ecto.Query.WindowAPI`. + + Receives a keyword list where keys are names of the windows + and values are a keyword list with window expressions. + + ## Examples + + # Compare each employee's salary with the average salary in his or her department + from e in Employee, + select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)}, + windows: [department: [partition_by: e.depname]] + + In the example above, we get the average salary per department. + `:department` is the window name, partitioned by `e.depname` + and `avg/1` is the window function. For more information + on windows functions, see `Ecto.Query.WindowAPI`. + + ## Window expressions + + The following keys are allowed when specifying a window. + + ### :partition_by + + A list of fields to partition the window by, for example: + + windows: [department: [partition_by: e.depname]] + + A list of atoms can also be interpolated for dynamic partitioning: + + fields = [:depname, :year] + windows: [dynamic_window: [partition_by: ^fields]] + + ### :order_by + + A list of fields to order the window by, for example: + + windows: [ordered_names: [order_by: e.name]] + + It works exactly as the keyword query version of `order_by/3`. + + ### :frame + + A fragment which defines the frame for window functions. + + ## Examples + + # Compare each employee's salary for each month with his average salary for previous 3 months + from p in Payroll, + select: {p.empno, p.date, p.salary, over(avg(p.salary), :prev_months)}, + windows: [prev_months: [partition_by: p.empno, order_by: p.date, frame: fragment("ROWS 3 PRECEDING EXCLUDE CURRENT ROW")]] + + """ + defmacro windows(query, binding \\ [], expr) do + Builder.Windows.build(query, binding, expr, __CALLER__) + end + + @doc """ + Converts a query into a subquery. + + If a subquery is given, returns the subquery itself. + If any other value is given, it is converted to a query via + `Ecto.Queryable` and wrapped in the `Ecto.SubQuery` struct. + + `subquery` is supported in: + + * `from`, + * `join`, + * `where`, in the form `p.x in subquery(q)`, + * `select` and `select_merge`, in the form of `%{field: subquery(...)}`. + + ## Examples + + # Get the average salary of the top 10 highest salaries + query = from Employee, order_by: [desc: :salary], limit: 10 + from e in subquery(query), select: avg(e.salary) + + A prefix can be specified for a subquery, similar to standard repo operations: + + query = from Employee, order_by: [desc: :salary], limit: 10 + from e in subquery(query, prefix: "my_prefix"), select: avg(e.salary) + + + Subquery can also be used in a `join` expression. + + UPDATE posts + SET sync_started_at = $1 + WHERE id IN ( + SELECT id FROM posts + WHERE synced = false AND (sync_started_at IS NULL OR sync_started_at < $1) + LIMIT $2 + ) + + We can write it as a join expression: + + subset = from(p in Post, + where: p.synced == false and + (is_nil(p.sync_started_at) or p.sync_started_at < ^min_sync_started_at), + limit: ^batch_size + ) + + Repo.update_all( + from(p in Post, join: s in subquery(subset), on: s.id == p.id), + set: [sync_started_at: NaiveDateTime.utc_now()] + ) + + Or as a `where` condition: + + subset_ids = from(p in subset, select: p.id) + Repo.update_all( + from(p in Post, where: p.id in subquery(subset_ids)), + set: [sync_started_at: NaiveDateTime.utc_now()] + ) + + If you need to refer to a parent binding which is not known when writing the subquery, + you can use `parent_as` as shown in the examples under ["Named bindings"](#module-named-bindings) + in this module doc. + + You can also use subquery directly in `select` and `select_merge`: + + comments_count = from(c in Comment, where: c.post_id == parent_as(:post).id, select: count()) + from(p in Post, as: :post, select: %{id: p.id, comments: subquery(comments_count)}) + """ + def subquery(query, opts \\ []) do + subquery = wrap_in_subquery(query) + + case Keyword.fetch(opts, :prefix) do + {:ok, prefix} -> + put_in(subquery.query.prefix, prefix) + + :error -> + subquery + end + end + + defp wrap_in_subquery(%Ecto.SubQuery{} = subquery), do: subquery + defp wrap_in_subquery(%Ecto.Query{} = query), do: %Ecto.SubQuery{query: query} + defp wrap_in_subquery(queryable), do: %Ecto.SubQuery{query: Ecto.Queryable.to_query(queryable)} + + @joins [ + :join, + :inner_join, + :cross_join, + :cross_lateral_join, + :left_join, + :right_join, + :full_join, + :inner_lateral_join, + :left_lateral_join + ] + + @doc """ + Puts the given prefix in a query. + """ + def put_query_prefix(%Ecto.Query{} = query, prefix) do + %{query | prefix: prefix} + end + + def put_query_prefix(other, prefix) do + query = %Ecto.Query{} = Ecto.Queryable.to_query(other) + put_query_prefix(query, prefix) + end + + @doc """ + Resets a previously set field on a query. + + It can reset many fields except the query source (`from`). When excluding + a `:join`, it will remove *all* types of joins. If you prefer to remove a + single type of join, please see paragraph below. + + ## Examples + + Ecto.Query.exclude(query, :join) + Ecto.Query.exclude(query, :where) + Ecto.Query.exclude(query, :order_by) + Ecto.Query.exclude(query, :group_by) + Ecto.Query.exclude(query, :having) + Ecto.Query.exclude(query, :distinct) + Ecto.Query.exclude(query, :select) + Ecto.Query.exclude(query, :combinations) + Ecto.Query.exclude(query, :with_ctes) + Ecto.Query.exclude(query, :limit) + Ecto.Query.exclude(query, :offset) + Ecto.Query.exclude(query, :lock) + Ecto.Query.exclude(query, :preload) + Ecto.Query.exclude(query, :update) + + You can also remove specific joins as well such as `left_join` and + `inner_join`: + + Ecto.Query.exclude(query, :inner_join) + Ecto.Query.exclude(query, :cross_join) + Ecto.Query.exclude(query, :cross_lateral_join) + Ecto.Query.exclude(query, :left_join) + Ecto.Query.exclude(query, :right_join) + Ecto.Query.exclude(query, :full_join) + Ecto.Query.exclude(query, :inner_lateral_join) + Ecto.Query.exclude(query, :left_lateral_join) + + However, keep in mind that if a join is removed and its bindings + were referenced elsewhere, the bindings won't be removed, leading + to a query that won't compile. + """ + def exclude(%Ecto.Query{} = query, field), do: do_exclude(query, field) + def exclude(query, field), do: do_exclude(Ecto.Queryable.to_query(query), field) + + defp do_exclude(%Ecto.Query{} = query, :join) do + %{query | joins: [], aliases: Map.take(query.aliases, [query.from.as])} + end + + defp do_exclude(%Ecto.Query{} = query, join_keyword) when join_keyword in @joins do + qual = join_qual(join_keyword) + {excluded, remaining} = Enum.split_with(query.joins, &(&1.qual == qual)) + aliases = Map.drop(query.aliases, Enum.map(excluded, & &1.as)) + %{query | joins: remaining, aliases: aliases} + end + + defp do_exclude(%Ecto.Query{} = query, :where), do: %{query | wheres: []} + defp do_exclude(%Ecto.Query{} = query, :order_by), do: %{query | order_bys: []} + defp do_exclude(%Ecto.Query{} = query, :group_by), do: %{query | group_bys: []} + defp do_exclude(%Ecto.Query{} = query, :combinations), do: %{query | combinations: []} + defp do_exclude(%Ecto.Query{} = query, :with_ctes), do: %{query | with_ctes: nil} + defp do_exclude(%Ecto.Query{} = query, :having), do: %{query | havings: []} + defp do_exclude(%Ecto.Query{} = query, :distinct), do: %{query | distinct: nil} + defp do_exclude(%Ecto.Query{} = query, :select), do: %{query | select: nil} + defp do_exclude(%Ecto.Query{} = query, :limit), do: %{query | limit: nil} + defp do_exclude(%Ecto.Query{} = query, :offset), do: %{query | offset: nil} + defp do_exclude(%Ecto.Query{} = query, :lock), do: %{query | lock: nil} + defp do_exclude(%Ecto.Query{} = query, :preload), do: %{query | preloads: [], assocs: []} + defp do_exclude(%Ecto.Query{} = query, :update), do: %{query | updates: []} + + @doc """ + Creates a query. + + It can either be a keyword query or a query expression. + + If it is a keyword query the first argument must be + either an `in` expression, a value that implements + the `Ecto.Queryable` protocol, or an `Ecto.Query.API.fragment/1`. If the query needs a + reference to the data source in any other part of the + expression, then an `in` must be used to create a reference + variable. The second argument should be a keyword query + where the keys are expression types and the values are + expressions. + + If it is a query expression the first argument must be + a value that implements the `Ecto.Queryable` protocol + and the second argument the expression. + + ## Hints + + The `hints` keyword can be used to specify query hints: + + from p in Post, + hints: ["USE INDEX FOO"], + where: p.title == "title" + + It can also be used as a general mechanism for adding statements that + come after the `from` clause. For example, it can be used to enable + table sampling: + + from p in Post, + hints: "TABLESAMPLE SYSTEM(1)" + + `from` hints must be a (list of) compile-time strings or unsafe fragments. An unsafe + fragment can be used to specify dynamic hints: + + sample = "SYSTEM_ROWS(1)" + + from p in Post, + hints: ["TABLESAMPLE", unsafe_fragment(^sample)] + + > #### Unsafe Fragments {: .warning} + > + > The output of `unsafe_fragment/1` will be injected directly into the + > resulting SQL statement without being escaped. For this reason, input + > from uncontrolled sources, such as user input, should **never** be used. + > Otherwise, it could lead to harmful SQL injection attacks. + + ## Keywords examples + + # `in` expression + from(c in City, select: c) + + # Ecto.Queryable + from(City, limit: 1) + + # Fragment with user-defined function and predefined columns + from(f in fragment("my_table_valued_function(arg)"), select: f.x) + + # Fragment with built-in function and undefined columns + from(f in fragment("select generate_series(?::integer, ?::integer) as x", ^0, ^10), select: f.x) + + ## Expressions examples + + # Schema + City |> select([c], c) + + # Source + "cities" |> select([c], c) + + # Source with schema + {"cities", Source} |> select([c], c) + + # Ecto.Query + from(c in Cities) |> select([c], c) + + ## Examples + + def paginate(query, page, size) do + from query, + limit: ^size, + offset: ^((page-1) * size) + end + + The example above does not use `in` because `limit` and `offset` + do not require a reference to the data source. However, extending + the query with a where expression would require the use of `in`: + + def published(query) do + from p in query, where: not(is_nil(p.published_at)) + end + + Notice we have created a `p` variable to reference the query's + original data source. This assumes that the original query + only had one source. When the given query has more than one source, + positional or named bindings may be used to access the additional sources. + + def published_multi(query) do + from [p,o] in query, + where: not(is_nil(p.published_at)) and not(is_nil(o.published_at)) + end + + Note that the variables `p` and `o` can be named whatever you like + as they have no importance in the query sent to the database. + """ + defmacro from(expr, kw \\ []) do + unless Keyword.keyword?(kw) do + raise ArgumentError, "second argument to `from` must be a compile time keyword list" + end + + {kw, as, prefix, hints} = collect_as_and_prefix_and_hints(kw, nil, nil, nil) + + {quoted, binds, count_bind} = + Builder.From.build(expr, __CALLER__, as, prefix, List.wrap(hints)) + + from(kw, __CALLER__, count_bind, quoted, to_query_binds(binds)) + end + + @from_join_opts [:as, :prefix, :hints] + @no_binds [:union, :union_all, :except, :except_all, :intersect, :intersect_all] + @binds [:lock, :where, :or_where, :select, :distinct, :order_by, :group_by, :windows] ++ + [:having, :or_having, :limit, :offset, :preload, :update, :select_merge, :with_ctes] + + defp from([{type, expr} | t], env, count_bind, quoted, binds) when type in @binds do + # If all bindings are integer indexes keep AST Macro expandable to %Query{}, + # otherwise ensure that quoted code is evaluated before macro call + quoted = + if Enum.all?(binds, fn {_, value} -> is_integer(value) end) do + quote do + Ecto.Query.unquote(type)(unquote(quoted), unquote(binds), unquote(expr)) + end + else + quote do + query = unquote(quoted) + Ecto.Query.unquote(type)(query, unquote(binds), unquote(expr)) + end + end + + {t, quoted} = maybe_with_ties(type, t, quoted, binds) + + from(t, env, count_bind, quoted, binds) + end + + defp from([{type, expr} | t], env, count_bind, quoted, binds) when type in @no_binds do + quoted = + quote do + Ecto.Query.unquote(type)(unquote(quoted), unquote(expr)) + end + + from(t, env, count_bind, quoted, binds) + end + + defp from([{join, expr} | t], env, count_bind, quoted, binds) when join in @joins do + qual = join_qual(join) + {t, on, as, prefix, hints} = collect_on(t, nil, nil, nil, nil) + + {quoted, binds, count_bind} = + Builder.Join.build(quoted, qual, binds, expr, count_bind, on, as, prefix, hints, env) + + from(t, env, count_bind, quoted, to_query_binds(binds)) + end + + defp from([{:with_ties, _value} | _], _env, _count_bind, _quoted, _binds) do + Builder.error!("`with_ties` keyword must immediately follow a limit") + end + + defp from([{:on, _value} | _], _env, _count_bind, _quoted, _binds) do + Builder.error!("`on` keyword must immediately follow a join") + end + + defp from([{key, _value} | _], _env, _count_bind, _quoted, _binds) + when key in @from_join_opts do + Builder.error!("`#{key}` keyword must immediately follow a from/join") + end + + defp from([{key, _value} | _], _env, _count_bind, _quoted, _binds) do + Builder.error!("unsupported #{inspect(key)} in keyword query expression") + end + + defp from([], _env, _count_bind, quoted, _binds) do + quoted + end + + defp maybe_with_ties(:limit, t, quoted, binds) do + {t, with_ties} = collect_with_ties(t, nil) + + quoted = + if with_ties != nil do + quote do + Ecto.Query.with_ties(unquote(quoted), unquote(binds), unquote(with_ties)) + end + else + quoted + end + + {t, quoted} + end + + defp maybe_with_ties(_type, t, quoted, _binds), do: {t, quoted} + + defp to_query_binds(binds) do + for {k, v} <- binds, do: {{k, [], nil}, v} + end + + defp join_qual(:join), do: :inner + defp join_qual(:full_join), do: :full + defp join_qual(:left_join), do: :left + defp join_qual(:right_join), do: :right + defp join_qual(:inner_join), do: :inner + defp join_qual(:cross_join), do: :cross + defp join_qual(:cross_lateral_join), do: :cross_lateral + defp join_qual(:left_lateral_join), do: :left_lateral + defp join_qual(:inner_lateral_join), do: :inner_lateral + + defp collect_with_ties([{:with_ties, with_ties} | t], nil), + do: collect_with_ties(t, with_ties) + + defp collect_with_ties([{:with_ties, _} | _], _), + do: Builder.error!("`with_ties` keyword was given more than once to the same limit") + + defp collect_with_ties(t, with_ties), + do: {t, with_ties} + + defp collect_on([{key, _} | _] = t, on, as, prefix, hints) when key in @from_join_opts do + {t, as, prefix, hints} = collect_as_and_prefix_and_hints(t, as, prefix, hints) + collect_on(t, on, as, prefix, hints) + end + + defp collect_on([{:on, on} | t], nil, as, prefix, hints), + do: collect_on(t, on, as, prefix, hints) + + defp collect_on([{:on, expr} | t], on, as, prefix, hints), + do: collect_on(t, {:and, [], [on, expr]}, as, prefix, hints) + + defp collect_on(t, on, as, prefix, hints), + do: {t, on, as, prefix, hints} + + defp collect_as_and_prefix_and_hints([{:as, as} | t], nil, prefix, hints), + do: collect_as_and_prefix_and_hints(t, as, prefix, hints) + + defp collect_as_and_prefix_and_hints([{:as, _} | _], _, _, _), + do: Builder.error!("`as` keyword was given more than once to the same from/join") + + defp collect_as_and_prefix_and_hints([{:prefix, prefix} | t], as, nil, hints), + do: collect_as_and_prefix_and_hints(t, as, {:ok, prefix}, hints) + + defp collect_as_and_prefix_and_hints([{:prefix, _} | _], _, _, _), + do: Builder.error!("`prefix` keyword was given more than once to the same from/join") + + defp collect_as_and_prefix_and_hints([{:hints, hints} | t], as, prefix, nil), + do: collect_as_and_prefix_and_hints(t, as, prefix, hints) + + defp collect_as_and_prefix_and_hints([{:hints, _} | _], _, _, _), + do: Builder.error!("`hints` keyword was given more than once to the same from/join") + + defp collect_as_and_prefix_and_hints(t, as, prefix, hints), + do: {t, as, prefix, hints} + + @doc """ + A join query expression. + + Receives a source that is to be joined to the query and a condition for + the join. The join condition can be any expression that evaluates + to a boolean value. The qualifier must be one of `:inner`, `:left`, + `:right`, `:cross`, `:cross_lateral`, `:full`, `:inner_lateral` or `:left_lateral`. + + For a keyword query the `:join` keyword can be changed to `:inner_join`, + `:left_join`, `:right_join`, `:cross_join`, `:cross_lateral_join`, `:full_join`, `:inner_lateral_join` + or `:left_lateral_join`. `:join` is equivalent to `:inner_join`. + + Currently it is possible to join on: + + * an `Ecto.Schema`, such as `p in Post` + * an interpolated Ecto query with zero or more `where` clauses, + such as `c in ^(from "posts", where: [public: true])` + * an association, such as `c in assoc(post, :comments)` + * a subquery, such as `c in subquery(another_query)` + * a query fragment, such as `c in fragment("SOME COMPLEX QUERY")`, + see "Joining with fragments" below. + + ## Options + + Each join accepts the following options: + + * `:on` - a query expression or keyword list to filter the join, defaults to `true` + * `:as` - a named binding for the join + * `:prefix` - the prefix to be used for the join when issuing a database query + * `:hints` - a string or a list of strings to be used as database hints + + In the keyword query syntax, those options must be given immediately + after the join. In the expression syntax, the options are given as + the fifth argument. + + > #### Unspecified join condition {: .warning} + > + > Leaving the `:on` option unspecified while performing a join + > that is not a cross join will trigger a warning. This is to + > help users avoid performing expensive cross joins when they don't + > mean to. If the behaviour is desired, you may remove the warning by + > changing to a cross join or explicitly setting `on: true`. If + > the behaviour is not desired, you should specify the appropriate + > join condition. + + ## Keywords examples + + from c in Comment, + join: p in Post, + on: p.id == c.post_id, + select: {p.title, c.text} + + from p in Post, + left_join: c in assoc(p, :comments), + select: {p, c} + + Keywords can also be given or interpolated as part of `on`: + + from c in Comment, + join: p in Post, + on: [id: c.post_id], + select: {p.title, c.text} + + Any key in `on` will apply to the currently joined expression. + + It is also possible to interpolate an Ecto query on the right-hand side + of `in`. For example, the query above can also be written as: + + posts = Post + from c in Comment, + join: p in ^posts, + on: [id: c.post_id], + select: {p.title, c.text} + + The above is specially useful to dynamically join on existing + queries, for example, to dynamically choose a source, or by + choosing between public posts or posts that have been recently + published: + + posts = + if params["drafts"] do + from p in Post, where: [drafts: true] + else + from p in Post, where: [public: true] + end + + from c in Comment, + join: p in ^posts, on: [id: c.post_id], + select: {p.title, c.text} + + Only simple queries with `where` expressions can be interpolated + in a join. + + ## Expressions examples + + Comment + |> join(:inner, [c], p in Post, on: c.post_id == p.id) + |> select([c, p], {p.title, c.text}) + + Post + |> join(:left, [p], c in assoc(p, :comments)) + |> select([p, c], {p, c}) + + Post + |> join(:left, [p], c in Comment, on: c.post_id == p.id and c.is_visible == true) + |> select([p, c], {p, c}) + + ## Joining with fragments + + When you need to join on a complex query, Ecto supports fragments in joins: + + Comment + |> join(:inner, [c], p in fragment("SOME COMPLEX QUERY", c.id, ^some_param)) + + Note that the `join` does not automatically wrap the fragment in + parentheses, since some expressions require parens and others + require no parens. Therefore, in cases such as common table + expressions, you will have to explicitly wrap the fragment content + in parens. + + ## Lateral Joins + + Lateral joins require a subquery that refer to previous bindings. This can be achieved using + `parent_as` within the `subquery` function: + + Game + |> from(as: :game) + |> join( + :inner_lateral, + [], + subquery( + GamesSold + |> where([gs], gs.game_id == parent_as(:game).id) + |> order_by([gs], gs.sold_on) + |> limit(2) + ), + on: true + ) + |> select([g, gs], {g.name, gs.sold_on}) + + ## Hints + + `join` also supports table hints, as found in databases such as + [MySQL](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html), + [MSSQL](https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-2017) and + [Clickhouse](https://clickhouse.tech/docs/en/sql-reference/statements/select/sample/). + + For example, a developer using MySQL may write: + + from p in Post, + join: c in Comment, + hints: ["USE INDEX FOO", "USE INDEX BAR"], + where: p.id == c.post_id, + select: c + + Keep in mind you want to use hints rarely, so don't forget to read the database + disclaimers about such functionality. + + Join hints must be static compile-time strings when they are specified as (list of) strings. + """ + @join_opts [:on | @from_join_opts] + + defmacro join(query, qual, binding \\ [], expr, opts \\ []) + + defmacro join(query, qual, binding, expr, opts) + when is_list(binding) and is_list(opts) do + {t, on, as, prefix, hints} = collect_on(opts, nil, nil, nil, nil) + + with [{key, _} | _] <- t do + raise ArgumentError, + "invalid option `#{key}` passed to Ecto.Query.join/5, " <> + "valid options are: #{inspect(@join_opts)}" + end + + query + |> Builder.Join.build(qual, binding, expr, nil, on, as, prefix, hints, __CALLER__) + |> elem(0) + end + + defmacro join(_query, _qual, binding, _expr, opts) when is_list(opts) do + raise ArgumentError, + "invalid binding passed to Ecto.Query.join/5, should be " <> + "list of variables, got: #{Macro.to_string(binding)}" + end + + defmacro join(_query, _qual, _binding, _expr, opts) do + raise ArgumentError, + "invalid opts passed to Ecto.Query.join/5, should be " <> + "list, got: #{Macro.to_string(opts)}" + end + + @doc ~S''' + A common table expression (CTE) also known as WITH expression. + + `name` must be a compile-time literal string that is being used + as the table name to join the CTE in the main query or in the + recursive CTE. + + **IMPORTANT!** Beware of using CTEs. In raw SQL, CTEs can be + used as a mechanism to organize queries, but said mechanism + has no purpose in Ecto since Ecto queries are composable by + definition. In other words, if you need to break a large query + into parts, use all of the functionality in Elixir and in this + module to structure your code. Furthermore, breaking a query + into CTEs can negatively impact performance, as the database + may not optimize efficiently across CTEs. The main use case + for CTEs in Ecto is to provide recursive definitions, which + we outline in the following section. Non-recursive CTEs can + often be written as joins or subqueries, which provide better + performance. + + ## Options + + * `:as` - the CTE query itself or a fragment + * `:materialized` - a boolean indicating whether the CTE should + be materialized. If blank, the database's default behaviour + will be used (only supported by Postgrex, for the built-in adapters) + * `:operation` - one of `:all`, `:update_all`, or `:delete_all` + indicating the operation type of the CTE query. If blank, it defaults to `:all`, + making the CTE query a SELECT query. (only supported by Postgres built-in adapter) + + ## Recursive CTEs + + Use `recursive_ctes/2` to enable recursive mode for CTEs. + + In the CTE query itself use the same table name to leverage + recursion that has been passed to the `name` argument. Make sure + to write a stop condition to avoid an infinite recursion loop. + Generally speaking, you should only use CTEs in Ecto for + writing recursive queries. + + ## Expression examples + + Products and their category names for breadcrumbs: + + category_tree_initial_query = + Category + |> where([c], is_nil(c.parent_id)) + + category_tree_recursion_query = + Category + |> join(:inner, [c], ct in "category_tree", on: c.parent_id == ct.id) + + category_tree_query = + category_tree_initial_query + |> union_all(^category_tree_recursion_query) + + Product + |> recursive_ctes(true) + |> with_cte("category_tree", as: ^category_tree_query) + |> join(:left, [p], c in "category_tree", on: c.id == p.category_id) + |> group_by([p], p.id) + |> select([p, c], %{p | category_names: fragment("ARRAY_AGG(?)", c.name)}) + + It's also possible to pass a raw SQL fragment: + + @raw_sql_category_tree """ + SELECT * FROM categories WHERE c.parent_id IS NULL + UNION ALL + SELECT * FROM categories AS c, category_tree AS ct WHERE ct.id = c.parent_id + """ + + Product + |> recursive_ctes(true) + |> with_cte("category_tree", as: fragment(@raw_sql_category_tree)) + |> join(:inner, [p], c in "category_tree", on: c.id == p.category_id) + + You can also query over the CTE table itself. In such cases, you can pass + tuple with the CTE table name as the first element and an Ecto schema as the second + element. This will cast the result rows to Ecto structs as long as the Ecto + schema maps over the same fields in the CTE table: + + {"category_tree", Category} + |> recursive_ctes(true) + |> with_cte("category_tree", as: ^category_tree_query) + |> join(:left, [c], p in assoc(c, :products)) + |> group_by([c], c.id) + |> select([c, p], %{c | products_count: count(p.id)}) + + Keep in mind that the query above will inherit all properties from the `Category` schema, + include a `@schema_prefix` if any is set. In such cases, you can disable those properties + by setting them as option: + + from(cte in {"category_tree", Category}, prefix: nil) + |> recursive_ctes(true) + |> with_cte("category_tree", as: ^category_tree_query) + + For Postgres built-in adapter, it is possible to define data-modifying CTE queries: + + update_categories_query = + Category + |> where([c], is_nil(c.parent_id)) + |> update([c], set: [name: "Root category"]) + |> select([c], c) + + {"update_categories", Category} + |> with_cte("update_categories", as: ^update_categories_query, operation: :update_all) + |> select([c], c) + + Note: In order to retrieve the updates rows from a CTE query, the parent query + must select rows from the CTE table instead of the table referenced by the CTE query. + For example, `"update_categories"` will return updates rows for `"category"` table, but + selecting from `"category"` table directly will return unaffected rows. + For more details see Postgres documentation on data-modifying CTEs and how these work + with snapshots. + + Keyword syntax is not supported for this feature. + + ## Limitation: CTEs on schemas with source fields + + Ecto allows developers to say that a table in their Ecto schema + maps to a different column in their database: + + field :group_id, :integer, source: :iGroupId + + At the moment, using a schema with source fields in CTE may emit + invalid queries. If you are running into such scenarios, your best + option is to use a fragment as your CTE. + ''' + defmacro with_cte(query, name, opts) do + with_query = opts[:as] + operation = opts[:operation] + + if !with_query do + Builder.error!("`as` option must be specified") + end + + Builder.CTE.build(query, name, with_query, opts[:materialized], operation, __CALLER__) + end + + @doc """ + Enables or disables recursive mode for CTEs. + + According to the SQL standard it affects all CTEs in the query, not individual ones. + + See `with_cte/3` on example of how to build a query with a recursive CTE. + """ + def recursive_ctes(%__MODULE__{with_ctes: with_expr} = query, value) when is_boolean(value) do + with_expr = with_expr || %WithExpr{} + with_expr = %{with_expr | recursive: value} + %{query | with_ctes: with_expr} + end + + def recursive_ctes(queryable, value) do + recursive_ctes(Ecto.Queryable.to_query(queryable), value) + end + + @doc """ + A select query expression. + + Selects which fields will be selected from the schema and any transformations + that should be performed on the fields. Any expression that is accepted in a + query can be a select field. + + Select also allows each expression to be wrapped in lists, tuples or maps as + shown in the examples below. A full schema can also be selected. + + There can only be one select expression in a query, if the select expression + is omitted, the query will by default select the full schema. If `select` is + given more than once, an error is raised. Use `exclude/2` if you would like + to remove a previous select for overriding or see `select_merge/3` for a + limited version of `select` that is composable and can be called multiple + times. + + `select` also accepts a list of atoms where each atom refers to a field in + the source to be selected. + + ## Keywords examples + + from(c in City, select: c) # returns the schema as a struct + from(c in City, select: {c.name, c.population}) + from(c in City, select: [c.name, c.county]) + from(c in City, select: %{n: c.name, answer: 42}) + from(c in City, select: %{c | alternative_name: c.name}) + from(c in City, select: %Data{name: c.name}) + + It is also possible to select a struct and limit the returned + fields at the same time: + + from(City, select: [:name]) + + The syntax above is equivalent to: + + from(city in City, select: struct(city, [:name])) + + You can also write: + + from(city in City, select: map(city, [:name])) + + If you want a map with only the selected fields to be returned. + + To select a struct but omit only given fields, you can + override them with `nil` or another default value: + + from(city in City, select: %{city | geojson: nil, text: ""}) + + For more information, read the docs for `Ecto.Query.API.struct/2` + and `Ecto.Query.API.map/2`. + + ## Expressions examples + + City |> select([c], c) + City |> select([c], {c.name, c.country}) + City |> select([c], %{"name" => c.name}) + City |> select([:name]) + City |> select([c], struct(c, [:name])) + City |> select([c], map(c, [:name])) + City |> select([c], %{c | geojson: nil, text: ""}) + + ## Dynamic parts + + Dynamics can be part of a `select` as values in a map that must be interpolated + at the root level: + + period = if monthly?, do: dynamic([p], p.month), else: dynamic([p], p.date) + metric = if distance?, do: dynamic([p], p.distance), else: dynamic([p], p.time) + + from(c in City, select: ^%{period: period, metric: metric}) + """ + defmacro select(query, binding \\ [], expr) do + Builder.Select.build(:select, query, binding, expr, __CALLER__) + end + + @doc """ + Mergeable select query expression. + + This macro is similar to `select/3` except it may be specified + multiple times as long as every entry is a map. This is useful + for merging and composing selects. For example: + + query = from p in Post, select: %{} + + query = + if include_title? do + from p in query, select_merge: %{title: p.title} + else + query + end + + query = + if include_visits? do + from p in query, select_merge: %{visits: p.visits} + else + query + end + + In the example above, the query is built little by little by merging + into a final map. If both conditions above are true, the final query + would be equivalent to: + + from p in Post, select: %{title: p.title, visits: p.visits} + + If `:select_merge` is called and there is no value selected previously, + it will default to the source, `p` in the example above. + + The argument given to `:select_merge` must always be a map. The value + being merged on must be a struct or a map. If it is a struct, the fields + merged later on must be part of the struct, otherwise an error is raised. + + If the argument to `:select_merge` is a constructed struct + (`Ecto.Query.API.struct/2`) or map (`Ecto.Query.API.map/2`) where the source + to struct or map may be a `nil` value (as in an outer join), the source will + be returned unmodified. + + query = + Post + |> join(:left, [p], t in Post.Translation, + on: t.post_id == p.id and t.locale == ^"en" + ) + |> select_merge([_p, t], map(t, ^~w(title summary)a)) + + If there is no English translation for the post, the untranslated post + `title` will be returned and `summary` will be `nil`. If there is, both + `title` and `summary` will be the value from `Post.Translation`. + + `select_merge` cannot be used to set fields in associations, as + associations are always loaded later, overriding any previous value. + + Dynamics can be part of a `select_merge` as values in a map that must be + interpolated at the root level. The rules for merging detailed above apply. + This allows merging dynamic values into previously selected maps and structs. + """ + defmacro select_merge(query, binding \\ [], expr) do + Builder.Select.build(:merge, query, binding, expr, __CALLER__) + end + + @doc """ + A distinct query expression. + + When true, only keeps distinct values from the resulting + select expression. + + If supported by your database, you can also pass query expressions + to distinct and it will generate a query with DISTINCT ON. In such + cases, `distinct` accepts exactly the same expressions as `order_by` + and any `distinct` expression will be automatically prepended to the + `order_by` expressions in case there is any `order_by` expression. + + ## Keywords examples + + # Returns the list of different categories in the Post schema + from(p in Post, distinct: true, select: p.category) + + # If your database supports DISTINCT ON(), + # you can pass expressions to distinct too + from(p in Post, + distinct: p.category, + order_by: [p.date]) + + # The DISTINCT ON() also supports ordering similar to ORDER BY. + from(p in Post, + distinct: [desc: p.category], + order_by: [p.date]) + + # Using atoms + from(p in Post, distinct: :category, order_by: :date) + + ## Expressions example + + Post + |> distinct(true) + |> order_by([p], [p.category, p.author]) + + """ + defmacro distinct(query, binding \\ [], expr) do + Builder.Distinct.build(query, binding, expr, __CALLER__) + end + + @doc """ + An AND where query expression. + + `where` expressions are used to filter the result set. If there is more + than one where expression, they are combined with an `and` operator. All + where expressions have to evaluate to a boolean value. + + `where` also accepts a keyword list where the field given as key is going to + be compared with the given value. The fields will always refer to the source + given in `from`. + + ## Keywords example + + from(c in City, where: c.country == "Sweden") + from(c in City, where: [country: "Sweden"]) + + It is also possible to interpolate the whole keyword list, allowing you to + dynamically filter the source: + + filters = [country: "Sweden"] + from(c in City, where: ^filters) + + ## Expressions examples + + City |> where([c], c.country == "Sweden") + City |> where(country: "Sweden") + + """ + defmacro where(query, binding \\ [], expr) do + Builder.Filter.build(:where, :and, query, binding, expr, __CALLER__) + end + + @doc """ + An OR where query expression. + + Behaves exactly the same as `where` except it combines with any previous + expression by using an `OR`. All expressions have to evaluate to a boolean + value. + + `or_where` also accepts a keyword list where each key is a field to be + compared with the given value. Each key-value pair will be combined + using `AND`, exactly as in `where`. + + ## Keywords example + + from(c in City, where: [country: "Sweden"], or_where: [country: "Brazil"]) + + If interpolating keyword lists, the keyword list entries are combined + using ANDs and joined to any existing expression with an OR: + + filters = [country: "USA", name: "New York"] + from(c in City, where: [country: "Sweden"], or_where: ^filters) + + is equivalent to: + + from c in City, where: (c.country == "Sweden") or + (c.country == "USA" and c.name == "New York") + + The behaviour above is by design to keep the changes between `where` + and `or_where` minimal. Plus, if you have a keyword list and you + would like each pair to be combined using `or`, it can be easily done + with `Enum.reduce/3`: + + filters = [country: "USA", is_tax_exempt: true] + Enum.reduce(filters, City, fn {key, value}, query -> + from q in query, or_where: field(q, ^key) == ^value + end) + + which will be equivalent to: + + from c in City, or_where: (c.country == "USA"), or_where: c.is_tax_exempt == true + + ## Expressions example + + City |> where([c], c.country == "Sweden") |> or_where([c], c.country == "Brazil") + + """ + defmacro or_where(query, binding \\ [], expr) do + Builder.Filter.build(:where, :or, query, binding, expr, __CALLER__) + end + + @doc """ + An order by query expression. + + Orders the fields based on one or more fields. It accepts a single field + or a list of fields. The default direction is ascending (`:asc`) and can be + customized in a keyword list as one of the following: + + * `:asc` + * `:asc_nulls_last` + * `:asc_nulls_first` + * `:desc` + * `:desc_nulls_last` + * `:desc_nulls_first` + + The `*_nulls_first` and `*_nulls_last` variants are not supported by all + databases. While all databases default to ascending order, the choice of + "nulls first" or "nulls last" is specific to each database implementation. + + `order_by` may be invoked or listed in a query many times. New expressions + are appended to the existing ones. + + `order_by` also accepts a list of atoms where each atom refers to a field in + source or a keyword list where the direction is given as key and the field + to order as value. + + ## Keywords examples + + from(c in City, order_by: c.name, order_by: c.population) + from(c in City, order_by: [c.name, c.population]) + from(c in City, order_by: [asc: c.name, desc: c.population]) + + from(c in City, order_by: [:name, :population]) + from(c in City, order_by: [asc: :name, desc_nulls_first: :population]) + + A keyword list can also be interpolated: + + values = [asc: :name, desc_nulls_first: :population] + from(c in City, order_by: ^values) + + A fragment can also be used: + + from c in City, order_by: [ + # A deterministic shuffled order + fragment("? % ? DESC", c.id, ^modulus), + desc: c.id, + ] + + It's also possible to order by an aliased or calculated column: + + from(c in City, + select: %{ + name: c.name, + total_population: + fragment( + "COALESCE(?, ?) + ? AS total_population", + c.animal_population, + 0, + c.human_population + ) + }, + order_by: [ + # based on `AS total_population` in the previous fragment + {:desc, fragment("total_population")} + ] + ) + + ## Expressions examples + + City |> order_by([c], asc: c.name, desc: c.population) + City |> order_by(asc: :name) # Sorts by the cities name + City |> order_by(^order_by_param) # Keyword list + + """ + defmacro order_by(query, binding \\ [], expr) do + Builder.OrderBy.build(query, binding, expr, :append, __CALLER__) + end + + @doc """ + An order by query expression that is prepended to existing ones. + + Accepts the same input as `order_by/3` except the expression will + come before any previously defined order by expression. This only + works with the macro-based query syntax and not the keyword-based + query syntax. + + For example, the following will generate a query that orders by `human_popluation` + and then `name`: + + City |> order_by([c], c.name) |> prepend_order_by([c], c.human_population) + + The corresponding keyword-based syntax will raise an error: + + from c in City, order_by: c.name, prepend_order_by: c.human_population + + """ + defmacro prepend_order_by(query, binding \\ [], expr) do + Builder.OrderBy.build(query, binding, expr, :prepend, __CALLER__) + end + + @doc """ + A union query expression. + + Combines result sets of multiple queries. The `select` of each query + must be exactly the same, with the same types in the same order. + + Union expression returns only unique rows as if each query returned + distinct results. This may cause a performance penalty. If you need + to combine multiple result sets without removing duplicate rows + consider using `union_all/2`. + + ## Combination behaviour + + There are several behaviours of combination queries that must be taken + into account, otherwise you may unexpectedly return the wrong query result. + + ### Order by, limit and offset + + The `order_by`, `limit` and `offset` expressions of the parent query apply + to the result of the entire combination. `order_by` must be specified in one + of the following ways, since the combination of two or more queries is not + automatically aliased: + + - Use `Ecto.Query.API.fragment/1` to pass an `order_by` statement + that directly access the combination fields. + - Wrap the combination in a subquery and refer to the binding of the subquery. + + ### Column selection ordering + + The columns of each of the queries in the combination must be specified in + the exact same order. Otherwise, you may see the values of one column appearing + in another. This holds for all types of select expressions, including maps. + + For example, the following query will interchange the values of the supplier's + name and city because that is the order the fields are specified in the customer + query. + + supplier_query = from s in Supplier, select: %{city: s.city, name: s.name} + customer_query = from c in Customer, select: %{name: c.name, city: c.city} + union(supplier_query, ^customer_query) + + ### Selecting literal atoms + + When selecting a literal atom, its value must be the same across all queries. + Otherwise, the value from the parent query will be applied to all other queries. + This also holds true for selecting maps with atom keys. + + ## Keywords examples + + # Unordered result + supplier_query = from s in Supplier, select: s.city + from c in Customer, select: c.city, union: ^supplier_query + + # Ordered result + supplier_query = from s in Supplier, select: s.city + union_query = from c in Customer, select: c.city, union: ^supplier_query + from s in subquery(union_query), order_by: s.city + + ## Expressions examples + + # Unordered result + supplier_query = Supplier |> select([s], s.city) + Customer |> select([c], c.city) |> union(^supplier_query) + + # Ordered result + customer_query = Customer |> select([c], c.city) |> order_by(fragment("city")) + supplier_query = Supplier |> select([s], s.city) + union(customer_query, ^supplier_query) + + """ + defmacro union(query, other_query) do + Builder.Combination.build(:union, query, other_query, __CALLER__) + end + + @doc """ + A union all query expression. + + Combines result sets of multiple queries. The `select` of each query + must be exactly the same, with the same types in the same order. + + ## Combination behaviour + + There are several behaviours of combination queries that must be taken + into account, otherwise you may unexpectedly return the wrong query result. + + ### Order by, limit and offset + + The `order_by`, `limit` and `offset` expressions of the parent query apply + to the result of the entire combination. `order_by` must be specified in one + of the following ways, since the combination of two or more queries is not + automatically aliased: + + - Use `Ecto.Query.API.fragment/1` to pass an `order_by` statement + that directly access the combination fields. + - Wrap the combination in a subquery and refer to the binding of the subquery. + + ### Column selection ordering + + The columns of each of the queries in the combination must be specified in + the exact same order. Otherwise, you may see the values of one column appearing + in another. This holds for all types of select expressions, including maps. + + For example, the following query will interchange the values of the supplier's + name and city because that is the order the fields are specified in the customer + query. + + supplier_query = from s in Supplier, select: %{city: s.city, name: s.name} + customer_query = from c in Customer, select: %{name: c.name, city: c.city} + union_all(supplier_query, ^customer_query) + + ### Selecting literal atoms + + When selecting a literal atom, its value must be the same across all queries. + Otherwise, the value from the parent query will be applied to all other queries. + This also holds true for selecting maps with atom keys. + + ## Keywords examples + + # Unordered result + supplier_query = from s in Supplier, select: s.city + from c in Customer, select: c.city, union_all: ^supplier_query + + # Ordered result + supplier_query = from s in Supplier, select: s.city + union_all_query = from c in Customer, select: c.city, union_all: ^supplier_query + from s in subquery(union_all_query), order_by: s.city + + ## Expressions examples + + # Unordered result + supplier_query = Supplier |> select([s], s.city) + Customer |> select([c], c.city) |> union_all(^supplier_query) + + # Ordered result + customer_query = Customer |> select([c], c.city) |> order_by(fragment("city")) + supplier_query = Supplier |> select([s], s.city) + union_all(customer_query, ^supplier_query) + """ + defmacro union_all(query, other_query) do + Builder.Combination.build(:union_all, query, other_query, __CALLER__) + end + + @doc """ + An except (set difference) query expression. + + Takes the difference of the result sets of multiple queries. The + `select` of each query must be exactly the same, with the same + types in the same order. + + Except expression returns only unique rows as if each query returned + distinct results. This may cause a performance penalty. If you need + to take the difference of multiple result sets without + removing duplicate rows consider using `except_all/2`. + + ## Combination behaviour + + There are several behaviours of combination queries that must be taken + into account, otherwise you may unexpectedly return the wrong query result. + + ### Order by, limit and offset + + The `order_by`, `limit` and `offset` expressions of the parent query apply + to the result of the entire combination. `order_by` must be specified in one + of the following ways, since the combination of two or more queries is not + automatically aliased: + + - Use `Ecto.Query.API.fragment/1` to pass an `order_by` statement + that directly access the combination fields. + - Wrap the combination in a subquery and refer to the binding of the subquery. + + ### Column selection ordering + + The columns of each of the queries in the combination must be specified in + the exact same order. Otherwise, you may see the values of one column appearing + in another. This holds for all types of select expressions, including maps. + + For example, the following query will interchange the values of the supplier's + name and city because that is the order the fields are specified in the customer + query. + + supplier_query = from s in Supplier, select: %{city: s.city, name: s.name} + customer_query = from c in Customer, select: %{name: c.name, city: c.city} + except(supplier_query, ^customer_query) + + ### Selecting literal atoms + + When selecting a literal atom, its value must be the same across all queries. + Otherwise, the value from the parent query will be applied to all other queries. + This also holds true for selecting maps with atom keys. + + ## Keywords examples + + # Unordered result + supplier_query = from s in Supplier, select: s.city + from c in Customer, select: c.city, except: ^supplier_query + + # Ordered result + supplier_query = from s in Supplier, select: s.city + except_query = from c in Customer, select: c.city, except: ^supplier_query + from s in subquery(except_query), order_by: s.city + + ## Expressions examples + + # Unordered result + supplier_query = Supplier |> select([s], s.city) + Customer |> select([c], c.city) |> except(^supplier_query) + + # Ordered result + customer_query = Customer |> select([c], c.city) |> order_by(fragment("city")) + supplier_query = Supplier |> select([s], s.city) + except(customer_query, ^supplier_query) + """ + defmacro except(query, other_query) do + Builder.Combination.build(:except, query, other_query, __CALLER__) + end + + @doc """ + An except (set difference) query expression. + + Takes the difference of the result sets of multiple queries. The + `select` of each query must be exactly the same, with the same + types in the same order. + + ## Combination behaviour + + There are several behaviours of combination queries that must be taken + into account, otherwise you may unexpectedly return the wrong query result. + + ### Order by, limit and offset + + The `order_by`, `limit` and `offset` expressions of the parent query apply + to the result of the entire combination. `order_by` must be specified in one + of the following ways, since the combination of two or more queries is not + automatically aliased: + + - Use `Ecto.Query.API.fragment/1` to pass an `order_by` statement + that directly access the combination fields. + - Wrap the combination in a subquery and refer to the binding of the subquery. + + ### Column selection ordering + + The columns of each of the queries in the combination must be specified in + the exact same order. Otherwise, you may see the values of one column appearing + in another. This holds for all types of select expressions, including maps. + + For example, the following query will interchange the values of the supplier's + name and city because that is the order the fields are specified in the customer + query. + + supplier_query = from s in Supplier, select: %{city: s.city, name: s.name} + customer_query = from c in Customer, select: %{name: c.name, city: c.city} + except_all(supplier_query, ^customer_query) + + ### Selecting literal atoms + + When selecting a literal atom, its value must be the same across all queries. + Otherwise, the value from the parent query will be applied to all other queries. + This also holds true for selecting maps with atom keys. + + ## Keywords examples + + # Unordered result + supplier_query = from s in Supplier, select: s.city + from c in Customer, select: c.city, except_all: ^supplier_query + + # Ordered result + supplier_query = from s in Supplier, select: s.city + except_all_query = from c in Customer, select: c.city, except_all: ^supplier_query + from s in subquery(except_all_query), order_by: s.city + + ## Expressions examples + + # Unordered result + supplier_query = Supplier |> select([s], s.city) + Customer |> select([c], c.city) |> except_all(^supplier_query) + + # Ordered result + customer_query = Customer |> select([c], c.city) |> order_by(fragment("city")) + supplier_query = Supplier |> select([s], s.city) + except_all(customer_query, ^supplier_query) + """ + defmacro except_all(query, other_query) do + Builder.Combination.build(:except_all, query, other_query, __CALLER__) + end + + @doc """ + An intersect query expression. + + Takes the overlap of the result sets of multiple queries. The + `select` of each query must be exactly the same, with the same + types in the same order. + + Intersect expression returns only unique rows as if each query returned + distinct results. This may cause a performance penalty. If you need + to take the intersection of multiple result sets without + removing duplicate rows consider using `intersect_all/2`. + + ## Combination behaviour + + There are several behaviours of combination queries that must be taken + into account, otherwise you may unexpectedly return the wrong query result. + + ### Order by, limit and offset + + The `order_by`, `limit` and `offset` expressions of the parent query apply + to the result of the entire combination. `order_by` must be specified in one + of the following ways, since the combination of two or more queries is not + automatically aliased: + + - Use `Ecto.Query.API.fragment/1` to pass an `order_by` statement + that directly access the combination fields. + - Wrap the combination in a subquery and refer to the binding of the subquery. + + ### Column selection ordering + + The columns of each of the queries in the combination must be specified in + the exact same order. Otherwise, you may see the values of one column appearing + in another. This holds for all types of select expressions, including maps. + + For example, the following query will interchange the values of the supplier's + name and city because that is the order the fields are specified in the customer + query. + + supplier_query = from s in Supplier, select: %{city: s.city, name: s.name} + customer_query = from c in Customer, select: %{name: c.name, city: c.city} + intersect(supplier_query, ^customer_query) + + ### Selecting literal atoms + + When selecting a literal atom, its value must be the same across all queries. + Otherwise, the value from the parent query will be applied to all other queries. + This also holds true for selecting maps with atom keys. + + ## Keywords examples + + # Unordered result + supplier_query = from s in Supplier, select: s.city + from c in Customer, select: c.city, intersect: ^supplier_query + + # Ordered result + supplier_query = from s in Supplier, select: s.city + intersect_query = from c in Customer, select: c.city, intersect: ^supplier_query + from s in subquery(intersect_query), order_by: s.city + + ## Expressions examples + + # Unordered result + supplier_query = Supplier |> select([s], s.city) + Customer |> select([c], c.city) |> intersect(^supplier_query) + + # Ordered result + customer_query = Customer |> select([c], c.city) |> order_by(fragment("city")) + supplier_query = Supplier |> select([s], s.city) + intersect(customer_query, ^supplier_query) + """ + defmacro intersect(query, other_query) do + Builder.Combination.build(:intersect, query, other_query, __CALLER__) + end + + @doc """ + An intersect query expression. + + Takes the overlap of the result sets of multiple queries. The + `select` of each query must be exactly the same, with the same + types in the same order. + + ## Combination behaviour + + There are several behaviours of combination queries that must be taken + into account, otherwise you may unexpectedly return the wrong query result. + + ### Order by, limit and offset + + The `order_by`, `limit` and `offset` expressions of the parent query apply + to the result of the entire combination. `order_by` must be specified in one + of the following ways, since the combination of two or more queries is not + automatically aliased: + + - Use `Ecto.Query.API.fragment/1` to pass an `order_by` statement + that directly access the combination fields. + - Wrap the combination in a subquery and refer to the binding of the subquery. + + ### Column selection ordering + + The columns of each of the queries in the combination must be specified in + the exact same order. Otherwise, you may see the values of one column appearing + in another. This holds for all types of select expressions, including maps. + + For example, the following query will interchange the values of the supplier's + name and city because that is the order the fields are specified in the customer + query. + + supplier_query = from s in Supplier, select: %{city: s.city, name: s.name} + customer_query = from c in Customer, select: %{name: c.name, city: c.city} + intersect_all(supplier_query, ^customer_query) + + ### Selecting literal atoms + + When selecting a literal atom, its value must be the same across all queries. + Otherwise, the value from the parent query will be applied to all other queries. + This also holds true for selecting maps with atom keys. + + ## Keywords examples + + # Unordered result + supplier_query = from s in Supplier, select: s.city + from c in Customer, select: c.city, intersect_all: ^supplier_query + + # Ordered result + supplier_query = from s in Supplier, select: s.city + intersect_all_query = from c in Customer, select: c.city, intersect_all: ^supplier_query + from s in subquery(intersect_all_query), order_by: s.city + + ## Expressions examples + + # Unordered result + supplier_query = Supplier |> select([s], s.city) + Customer |> select([c], c.city) |> intersect_all(^supplier_query) + + # Ordered result + customer_query = Customer |> select([c], c.city) |> order_by(fragment("city")) + supplier_query = Supplier |> select([s], s.city) + intersect_all(customer_query, ^supplier_query) + """ + defmacro intersect_all(query, other_query) do + Builder.Combination.build(:intersect_all, query, other_query, __CALLER__) + end + + @doc """ + A limit query expression. + + Limits the number of rows returned from the result. Can be any expression but + has to evaluate to an integer value and it can't include any field. + + If `limit` is given twice, it overrides the previous value. + + ## Keywords example + + from(u in User, where: u.id == ^current_user, limit: 1) + + ## Expressions example + + User |> where([u], u.id == ^current_user) |> limit(1) + + """ + defmacro limit(query, binding \\ [], expr) do + Builder.LimitOffset.build(:limit, query, binding, expr, __CALLER__) + end + + @doc """ + Enables or disables ties for limit expressions. + + If there are multiple records tied for the last position in an ordered + limit result, setting this value to `true` will return all of the tied + records, even if the final result exceeds the specified limit. + + Must be a boolean or evaluate to a boolean at runtime. Can only be applied + to queries with a `limit` expression or an error is raised. If `limit` + is redefined then `with_ties` must be reapplied. + + Not all databases support this option and the ones that do might list it + under the `FETCH` command. Databases may require a corresponding `order_by` + statement to evaluate ties. + + ## Keywords example + + from(p in Post, where: p.author_id == ^current_user, order_by: [desc: p.visits], limit: 10, with_ties: true) + + ## Expressions example + + Post |> where([p], p.author_id == ^current_user) |> order_by([p], desc: p.visits) |> limit(10) |> with_ties(true) + + """ + defmacro with_ties(query, binding \\ [], expr) do + Builder.LimitOffset.build(:with_ties, query, binding, expr, __CALLER__) + end + + @doc """ + An offset query expression. + + Offsets the number of rows selected from the result. Can be any expression + but it must evaluate to an integer value and it can't include any field. + + If `offset` is given twice, it overrides the previous value. + + ## Keywords example + + # Get all posts on page 4 + from(p in Post, limit: 10, offset: 30) + + ## Expressions example + + Post |> limit(10) |> offset(30) + + """ + defmacro offset(query, binding \\ [], expr) do + Builder.LimitOffset.build(:offset, query, binding, expr, __CALLER__) + end + + @doc ~S""" + A lock query expression. + + Provides support for row-level pessimistic locking using + `SELECT ... FOR UPDATE` or other, database-specific, locking clauses. + `expr` can be any expression but has to evaluate to a boolean value or to a + string and it can't include any fields. + + If `lock` is used more than once, the last one used takes precedence. + + Ecto also supports [optimistic + locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) but not + through queries. For more information on optimistic locking, have a look at + the `Ecto.Changeset.optimistic_lock/3` function. + + ## Keywords example + + from(u in User, where: u.id == ^current_user, lock: "FOR SHARE NOWAIT") + + ## Expressions example + + User |> where([u], u.id == ^current_user) |> lock("FOR SHARE NOWAIT") + + """ + defmacro lock(query, binding \\ [], expr) do + Builder.Lock.build(query, binding, expr, __CALLER__) + end + + @doc ~S""" + An update query expression. + + Updates are used to update the filtered entries. In order for + updates to be applied, `c:Ecto.Repo.update_all/3` must be invoked. + + ## Keywords example + + from(u in User, update: [set: [name: "new name"]]) + + ## Expressions examples + + User |> update([u], set: [name: "new name"]) + User |> update(set: [name: "new name"]) + + ## Interpolation + + new_name = "new name" + from(u in User, update: [set: [name: ^new_name]]) + + new_name = "new name" + from(u in User, update: [set: [name: fragment("upper(?)", ^new_name)]]) + + ## Operators + + The update expression in Ecto supports the following operators: + + * `set` - sets the given field in the table to the given value + + from(u in User, update: [set: [name: "new name"]]) + + * `inc` - increments (or decrements if the value is negative) the given field in the table by the given value + + from(u in User, update: [inc: [accesses: 1]]) + + * `push` - pushes (appends) the given value to the end of the array field + + from(u in User, update: [push: [tags: "cool"]]) + + * `pull` - pulls (removes) the given value from the array field + + from(u in User, update: [pull: [tags: "not cool"]]) + + ## Composable + + Remember that all query expressions are composable, so you can use `update` + multiple times in the same query to merge the update expressions: + + new_name = "new name" + User + |> update([u], set: [name: fragment("upper(?)", ^new_name)]) + |> update([u], set: [age: 42]) + + This can be useful to compose updates from different functions + or when mixing interpolation, such as `set: ^updates`, with regular + query expressions, such as `set: [age: u.age + 1]`. + """ + defmacro update(query, binding \\ [], expr) do + Builder.Update.build(query, binding, expr, __CALLER__) + end + + @doc """ + A group by query expression. + + Groups together rows from the schema that have the same values in the given + fields. Using `group_by` "groups" the query giving it different semantics + in the `select` expression. If a query is grouped, only fields that were + referenced in the `group_by` can be used in the `select` or if the field + is given as an argument to an aggregate function. + + `group_by` also accepts a list of atoms where each atom refers to + a field in source. For more complicated queries you can access fields + directly instead of atoms. + + ## Keywords examples + + # Returns the number of posts in each category + from(p in Post, + group_by: p.category, + select: {p.category, count(p.id)}) + + # Using atoms + from(p in Post, group_by: :category, select: {p.category, count(p.id)}) + + # Using direct fields access + from(p in Post, + join: c in assoc(p, :category), + group_by: [p.id, c.name]) + + ## Expressions example + + Post |> group_by([p], p.category) |> select([p], count(p.id)) + + """ + defmacro group_by(query, binding \\ [], expr) do + Builder.GroupBy.build(query, binding, expr, __CALLER__) + end + + @doc """ + An AND having query expression. + + Like `where`, `having` filters rows from the schema, but after the grouping is + performed giving it the same semantics as `select` for a grouped query + (see `group_by/3`). `having` groups the query even if the query has no + `group_by` expression. + + ## Keywords example + + # Returns the number of posts in each category where the + # average number of comments is above ten + from(p in Post, + group_by: p.category, + having: avg(p.num_comments) > 10, + select: {p.category, count(p.id)}) + + ## Expressions example + + Post + |> group_by([p], p.category) + |> having([p], avg(p.num_comments) > 10) + |> select([p], count(p.id)) + """ + defmacro having(query, binding \\ [], expr) do + Builder.Filter.build(:having, :and, query, binding, expr, __CALLER__) + end + + @doc """ + An OR having query expression. + + Like `having` but combines with the previous expression by using + `OR`. `or_having` behaves for `having` the same way `or_where` + behaves for `where`. + + ## Keywords example + + # Augment a previous group_by with a having condition. + from(p in query, or_having: avg(p.num_comments) > 10) + + ## Expressions example + + # Augment a previous group_by with a having condition. + Post |> or_having([p], avg(p.num_comments) > 10) + + """ + defmacro or_having(query, binding \\ [], expr) do + Builder.Filter.build(:having, :or, query, binding, expr, __CALLER__) + end + + @doc """ + Preloads the associations into the result set. + + Imagine you have a schema `Post` with a `has_many :comments` + association and you execute the following query: + + Repo.all from p in Post, preload: [:comments] + + The example above will fetch all posts from the database and then do + a separate query returning all comments associated with the given posts. + The comments are then processed and associated to each returned `post` + under the `comments` field. + + Often times, you may want posts and comments to be selected and + filtered in the same query. For such cases, you can explicitly tell + an existing join to be preloaded into the result set: + + Repo.all from p in Post, + join: c in assoc(p, :comments), + where: c.published_at > p.updated_at, + preload: [comments: c] + + In the example above, instead of issuing a separate query to fetch + comments, Ecto will fetch posts and comments in a single query and + then do a separate pass associating each comment to its parent post. + Therefore, instead of returning `number_of_posts * number_of_comments` + results, like a `join` would, it returns only posts with the `comments` + fields properly filled in. + + Nested associations can also be preloaded in both formats: + + Repo.all from p in Post, + preload: [:author, comments: :likes] + + Repo.all from p in Post, + join: c in assoc(p, :comments), + join: l in assoc(c, :likes), + where: l.inserted_at > c.updated_at, + preload: [:author, comments: {c, likes: l}] + + ## Choosing between preloading with joins vs. separate queries + + Deciding between preloading associations via joins, a single large + query, (`preload: [comments: c]`) or separate smaller queries + (`preload: [:comments]`) depends on the specific use case. + Here are some factors to guide your decision: + + * **Joins reduce database round trips:** By fetching data in a single + query, joins can minimize database round trips, potentially reducing + overall latency. + * **Potential for data duplication:** Joins may lead to duplicated + data in the result set, which requires more processing by Ecto + and consumes more bandwidth when transmitting the results. + * **Parallelism with separate queries:** When using separate queries + outside of a transaction, Ecto can parallelize the preload queries, + which can speed up the overall operation. + + In general, a good default is to only use joins in preloads if you're + already joining the associations in the main query. For example, + in the last query in the section above, comments and likes are already + joined, so they are included in the preload. + However, the author is not joined in the main query, so it is preloaded + via a separate query. + + ## Preload queries + + Preload also allows queries to be given, allowing you to filter or + customize how the preloads are fetched: + + comments_query = from c in Comment, order_by: c.published_at + Repo.all from p in Post, preload: [comments: ^comments_query] + + The example above will issue two queries, one for loading posts and + then another for loading the comments associated with the posts. + Comments will be ordered by `published_at`. + + When specifying a preload query, you can still nest preloads. + For instance, you could preload an author's published posts and + their comments as follows: + + posts_query = from p in Post, where: p.state == :published + Repo.all from a in Author, preload: [posts: ^{posts_query, [:comments]}] + + If you prefer, you can also add additional preloads directly in the + `posts_query`: + + posts_query = + from p in Post, where: p.state == :published, preload: :related_posts + + Note: keep in mind operations like limit and offset in the preload + query will affect the whole result set and not each association. For + example, the query below: + + comments_query = from c in Comment, order_by: c.popularity, limit: 5 + Repo.all from p in Post, preload: [comments: ^comments_query] + + won't bring the top of comments per post. Rather, it will only bring + the 5 top comments across all posts. Instead, you must use a window: + + ranking_query = + from c in Comment, + select: %{id: c.id, row_number: over(row_number(), :posts_partition)}, + windows: [posts_partition: [partition_by: :post_id, order_by: :popularity]] + + comments_query = + from c in Comment, + join: r in subquery(ranking_query), + on: c.id == r.id and r.row_number <= 5 + + Repo.all from p in Post, preload: [comments: ^comments_query] + + For `:through` associations, such as a post may have many comments_authors, + written as `has_many :comments_authors, through: [:comments, :author]` + the query given to preload customizes the relationship between comments and + authors, even if preloaded through posts. Another way to put it, in case of + `:through` associations, the query given to preload customizes the last join + of the association chain. This means `order_by` clauses on `:through` + associations affect only the direct relationship between `comments` and + `authors`, not between posts and comments. + + ## Preload functions + + Preload also allows functions to be given. If the function has an arity of 1, + it receives only the IDs of the parent association. If it has an arity of 2, it + receives the IDS of the parent association as the first argument and the association + metadata as the second argument. Both functions must return the associated data. + Ecto then will map this data and sort it by the relationship key: + + comment_preloader = fn post_ids -> fetch_comments_by_post_ids(post_ids) end + Repo.all from p in Post, preload: [comments: ^comment_preloader] + + This is useful when the whole dataset was already loaded or must be + explicitly fetched from elsewhere. The IDs received by the preloading + function and the result returned depends on the association type: + + * For `has_many` and `belongs_to` - the function receives the IDs of + the parent association and it must return a list of maps or structs + with the associated entries. The associated map/struct must contain + the "foreign_key" field. For example, if a post has many comments, + when preloading the comments with a custom function, the function + will receive a list of "post_ids" as the argument and it must return + maps or structs representing the comments. The maps/structs must + include the `:post_id` field + + * For `has_many :through` - it behaves similarly to a regular `has_many` + but note that the IDs received are of the last association. Imagine, + for example, a post has many comments and each comment has an author. + Therefore, a post may have many comments_authors, written as + `has_many :comments_authors, through: [:comments, :author]`. When + preloading authors with a custom function via `:comments_authors`, + the function will receive the IDs of the authors as the last step + + * For `many_to_many` - the function receives the IDs of the parent + association and it must return a tuple with the parent id as the first + element and the association map or struct as the second. For example, + if a post has many tags, when preloading the tags with a custom + function, the function will receive a list of "post_ids" as the argument + and it must return a tuple in the format of `{post_id, tag}` + + The 2-arity version of the function is especially useful if you would like to + build a general preloader that works across all associations. For example, if + you would like to build a preloader for lateral joins that finds the newest + associations you may do the following: + + lateral_preloader = fn ids, assoc -> newest_records(ids, assoc, 5) end + + def newest_records(parent_ids, assoc, n) do + %{related_key: related_key, queryable: queryable} = assoc + + squery = + from q in queryable, + where: field(q, ^related_key) == parent_as(:parent_ids).id, + order_by: {:desc, :created_at}, + limit: ^n + + query = + from f in fragment("SELECT id from UNNEST(?::int[]) AS id", ^parent_ids), as: :parent_ids, + inner_lateral_join: s in subquery(squery), on: true, + select: s + + Repo.all(query) + end + + For the list of available metadata, see the module documentation of the association types. + For example, see `Ecto.Association.BelongsTo`. + + ## Dynamic preloads + + Preloads can also be specified dynamically using the `dynamic` macro: + + preloads = [comments: dynamic([comments: c], c)] + + Repo.all from p in Post, + join: c in assoc(p, :comments), + as: :comments, + where: c.published_at > p.updated_at, + preload: ^preloads + + See `dynamic/2` for more information. + + ## Keywords example + + # Returns all posts, their associated comments, and the associated + # likes for those comments. + from(p in Post, + preload: [comments: :likes], + select: p + ) + + ## Expressions examples + + Post |> preload(:comments) |> select([p], p) + + Post + |> join(:left, [p], c in assoc(p, :comments)) + |> preload([p, c], [:user, comments: c]) + |> select([p], p) + + """ + defmacro preload(query, bindings \\ [], expr) do + Builder.Preload.build(query, bindings, expr, __CALLER__) + end + + @doc """ + Restricts the query to return the first result ordered by primary key. + + The query will be automatically ordered by the primary key + unless `order_by` is given or `order_by` is set in the query. + Limit is always set to 1. + + ## Examples + + Post |> first |> Repo.one + query |> first(:inserted_at) |> Repo.one + """ + def first(queryable, order_by \\ nil) + + def first(%Ecto.Query{} = query, nil) do + query = %{query | limit: limit()} + + case query do + %{order_bys: []} -> + %{query | order_bys: [order_by_pk(query, :asc)]} + + %{} -> + query + end + end + + def first(queryable, nil), do: first(Ecto.Queryable.to_query(queryable), nil) + def first(queryable, key), do: first(order_by(queryable, ^key), nil) + + @doc """ + Restricts the query to return the last result ordered by primary key. + + The query ordering will be automatically reversed, with ASC + columns becoming DESC columns (and vice-versa) and limit is set + to 1. If there is no ordering, the query will be automatically + ordered decreasingly by primary key. + + ## Examples + + Post |> last |> Repo.one + query |> last(:inserted_at) |> Repo.one + """ + def last(queryable, order_by \\ nil) + def last(queryable, nil), do: %{reverse_order(queryable) | limit: limit()} + def last(queryable, key), do: last(order_by(queryable, ^key), nil) + + defp limit do + %LimitExpr{expr: 1, params: [], file: __ENV__.file, line: __ENV__.line} + end + + defp field(ix, field) when is_integer(ix) and is_atom(field) do + {{:., [], [{:&, [], [ix]}, field]}, [], []} + end + + defp order_by_pk(query, dir) do + schema = assert_schema!(query) + pks = schema.__schema__(:primary_key) + expr = for pk <- pks, do: {dir, field(0, pk)} + %ByExpr{expr: expr, file: __ENV__.file, line: __ENV__.line} + end + + defp assert_schema!(%{from: %Ecto.Query.FromExpr{source: {_source, schema}}}) + when schema != nil, + do: schema + + defp assert_schema!(query) do + raise Ecto.QueryError, query: query, message: "expected a from expression with a schema" + end + + @doc """ + Returns `true` if the query has a binding with the given name, otherwise `false`. + + For more information on named bindings see ["Named bindings"](#module-named-bindings) + in this module doc. + """ + def has_named_binding?(%Ecto.Query{aliases: aliases}, key) do + Map.has_key?(aliases, key) + end + + def has_named_binding?(queryable, _key) + when is_atom(queryable) or is_binary(queryable) or is_tuple(queryable) do + false + end + + def has_named_binding?(queryable, key) do + has_named_binding?(Ecto.Queryable.to_query(queryable), key) + end + + @doc """ + Applies a callback function to a query if it doesn't contain the given named binding. + Otherwise, returns the original query. + + The callback function must accept a queryable and return an `Ecto.Query` struct + that contains the provided named binding, otherwise an error is raised. It can also + accept second argument which is the atom representing the name of a binding. + + For example, one might use this function as a convenience to conditionally add a new + named join to a query: + + if has_named_binding?(query, :comments) do + query + else + join(query, :left, [p], c in assoc(p, :comments), as: :comments) + end + + With this function it can be simplified to: + + with_named_binding(query, :comments, fn query, binding -> + join(query, :left, [p], a in assoc(p, ^binding), as: ^binding) + end) + + For more information on named bindings see ["Named bindings"](#module-named-bindings) + in this module doc or `has_named_binding?/2`. + """ + def with_named_binding(%Ecto.Query{} = query, key, fun) do + if has_named_binding?(query, key) do + query + else + query + |> apply_binding_callback(fun, key) + |> raise_on_invalid_callback_return(key) + end + end + + def with_named_binding(queryable, key, fun) do + queryable + |> Ecto.Queryable.to_query() + |> with_named_binding(key, fun) + end + + defp apply_binding_callback(query, fun, _key) when is_function(fun, 1), do: query |> fun.() + defp apply_binding_callback(query, fun, key) when is_function(fun, 2), do: query |> fun.(key) + + defp apply_binding_callback(_query, fun, _key) do + raise ArgumentError, + "callback function for with_named_binding/3 should accept one or two arguments, got: #{inspect(fun)}" + end + + defp raise_on_invalid_callback_return(%Ecto.Query{} = query, key) do + if has_named_binding?(query, key) do + query + else + raise RuntimeError, + "callback function for with_named_binding/3 should create a named binding for key #{inspect(key)}" + end + end + + defp raise_on_invalid_callback_return(other, _key) do + raise RuntimeError, + "callback function for with_named_binding/3 should return an Ecto.Query struct, got: #{inspect(other)}" + end + + @doc """ + The same as `has_named_binding?/2` but allowed in guards. + """ + @doc guard: true + defguard is_named_binding(query, name) + when is_struct(query, Ecto.Query) and is_map_key(query.aliases, name) + + @doc """ + Reverses the ordering of the query. + + ASC columns become DESC columns (and vice-versa). If the query + has no `order_by`s, it orders by the inverse of the primary key. + + ## Examples + + query |> reverse_order() |> Repo.one() + Post |> order_by(asc: :id) |> reverse_order() == Post |> order_by(desc: :id) + """ + def reverse_order(%Ecto.Query{} = query) do + update_in(query.order_bys, fn + [] -> [order_by_pk(query, :desc)] + order_bys -> Enum.map(order_bys, &reverse_order_by/1) + end) + end + + def reverse_order(queryable) do + reverse_order(Ecto.Queryable.to_query(queryable)) + end + + defp reverse_order_by(%{expr: expr} = order_by) do + %{ + order_by + | expr: + Enum.map(expr, fn + {:desc, ast} -> {:asc, ast} + {:desc_nulls_last, ast} -> {:asc_nulls_first, ast} + {:desc_nulls_first, ast} -> {:asc_nulls_last, ast} + {:asc, ast} -> {:desc, ast} + {:asc_nulls_last, ast} -> {:desc_nulls_first, ast} + {:asc_nulls_first, ast} -> {:desc_nulls_last, ast} + end) + } + end +end diff --git a/deps/ecto/lib/ecto/query/api.ex b/deps/ecto/lib/ecto/query/api.ex new file mode 100644 index 0000000000000000000000000000000000000000..9d2c6ce540c56a18880d1521b1e912d4d9f1bab6 --- /dev/null +++ b/deps/ecto/lib/ecto/query/api.ex @@ -0,0 +1,885 @@ +defmodule Ecto.Query.API do + @moduledoc """ + Lists all functions allowed in the query API. + + * Comparison operators: `==`, `!=`, `<=`, `>=`, `<`, `>` + * Arithmetic operators: `+`, `-`, `*`, `/` + * Boolean operators: `and`, `or`, `not` + * Inclusion operator: `in/2` + * Subquery operators: `any`, `all` and `exists` + * Search functions: `like/2` and `ilike/2` + * Null check functions: `is_nil/1` + * Aggregates: `count/0`, `count/1`, `avg/1`, `sum/1`, `min/1`, `max/1` + * Date/time intervals: `datetime_add/3`, `date_add/3`, `from_now/2`, `ago/2` + * Inside select: `struct/2`, `map/2`, `merge/2`, `selected_as/2` and literals (map, tuples, lists, etc) + * General: `fragment/1`, `field/2`, `type/2`, `as/1`, `parent_as/1`, `selected_as/1` + + Note the functions in this module exist for documentation + purposes and one should never need to invoke them directly. + Furthermore, it is possible to define your own macros and + use them in Ecto queries (see docs for `fragment/1`). + + ## Intervals + + Ecto supports following values for `interval` option: `"year"`, `"month"`, + `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`, `"millisecond"`, and + `"microsecond"`. + + `Date`/`Time` functions like `datetime_add/3`, `date_add/3`, `from_now/2`, + `ago/2` take `interval` as an argument. + + ## Window API + + Ecto also supports many of the windows functions found + in SQL databases. See `Ecto.Query.WindowAPI` for more + information. + + ## About the arithmetic operators + + The Ecto implementation of these operators provide only + a thin layer above the adapters. So if your adapter allows you + to use them in a certain way (like adding a date and an + interval in PostgreSQL), it should work just fine in Ecto + queries. + """ + + @dialyzer :no_return + + @doc """ + Binary `==` operation. + """ + def left == right, do: doc!([left, right]) + + @doc """ + Binary `!=` operation. + """ + def left != right, do: doc!([left, right]) + + @doc """ + Binary `<=` operation. + """ + def left <= right, do: doc!([left, right]) + + @doc """ + Binary `>=` operation. + """ + def left >= right, do: doc!([left, right]) + + @doc """ + Binary `<` operation. + """ + def left < right, do: doc!([left, right]) + + @doc """ + Binary `>` operation. + """ + def left > right, do: doc!([left, right]) + + @doc """ + Binary `+` operation. + """ + def left + right, do: doc!([left, right]) + + @doc """ + Binary `-` operation. + """ + def left - right, do: doc!([left, right]) + + @doc """ + Binary `*` operation. + """ + def left * right, do: doc!([left, right]) + + @doc """ + Binary `/` operation. + """ + def left / right, do: doc!([left, right]) + + @doc """ + Binary `and` operation. + """ + def left and right, do: doc!([left, right]) + + @doc """ + Binary `or` operation. + """ + def left or right, do: doc!([left, right]) + + @doc """ + Unary `not` operation. + + It is used to negate values in `:where`. It is also used to match + the assert the opposite of `in/2`, `is_nil/1`, and `exists/1`. + For example: + + from p in Post, where: p.id not in [1, 2, 3] + + from p in Post, where: not is_nil(p.title) + + # Retrieve all the posts that doesn't have comments. + from p in Post, + as: :post, + where: + not exists( + from( + c in Comment, + where: parent_as(:post).id == c.post_id + ) + ) + + """ + def not value, do: doc!([value]) + + @doc """ + Checks if the left-value is included in the right one. + + from p in Post, where: p.id in [1, 2, 3] + + The right side may either be a literal list, an interpolated list, + any struct that implements the `Enumerable` protocol, or even a + column in the database with array type: + + from p in Post, where: "elixir" in p.tags + + Additionally, the right side may also be a subquery, which should return + a single column: + + from c in Comment, where: c.post_id in subquery( + from(p in Post, where: p.created_at > ^since, select: p.id) + ) + """ + def left in right, do: doc!([left, right]) + + @doc """ + Evaluates to true if the provided subquery returns 1 or more rows. + + from p in Post, + as: :post, + where: + exists( + from( + c in Comment, + where: parent_as(:post).id == c.post_id and c.replies_count > 5, + select: 1 + ) + ) + + This is best used in conjunction with `parent_as` to correlate the subquery + with the parent query to test some condition on related rows in a different table. + In the above example the query returns posts which have at least one comment that + has more than 5 replies. + """ + def exists(subquery), do: doc!([subquery]) + + @doc """ + Tests whether one or more values returned from the provided subquery match in a comparison operation. + + from p in Product, where: p.id == any( + from(li in LineItem, select: [li.product_id], where: li.created_at > ^since and li.qty >= 10) + ) + + A product matches in the above example if a line item was created since the provided date where the customer purchased + at least 10 units. + + 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. + Both can be used with every comparison operator: `==`, `!=`, `>`, `>=`, `<`, `<=`. + """ + def any(subquery), do: doc!([subquery]) + + @doc """ + Evaluates whether all values returned from the provided subquery match in a comparison operation. + + from p in Post, where: p.visits >= all( + from(p in Post, select: avg(p.visits), group_by: [p.category_id]) + ) + + For a post to match in the above example it must be visited at least as much as the average post in all categories. + + from p in Post, where: p.visits == all( + from(p in Post, select: max(p.visits)) + ) + + The above example matches all the posts which are tied for being the most visited. + + 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. + Both can be used with every comparison operator: `==`, `!=`, `>`, `>=`, `<`, `<=`. + """ + def all(subquery), do: doc!([subquery]) + + @doc """ + Searches for `search` in `string`. + + from p in Post, where: like(p.body, "Chapter%") + + Translates to the underlying SQL LIKE query, therefore + its behaviour is dependent on the database. In particular, + PostgreSQL will do a case-sensitive operation, while the + majority of other databases will be case-insensitive. For + performing a case-insensitive `like` in PostgreSQL, see `ilike/2`. + + You should be very careful when allowing user sent data to be used + as part of LIKE query, since they allow to perform + [LIKE-injections](https://githubengineering.com/like-injection/). + """ + def like(string, search), do: doc!([string, search]) + + @doc """ + Searches for `search` in `string` in a case insensitive fashion. + + from p in Post, where: ilike(p.body, "Chapter%") + + Translates to the underlying SQL ILIKE query. This operation is + only available on PostgreSQL. + """ + def ilike(string, search), do: doc!([string, search]) + + @doc """ + Checks if the given value is nil. + + from p in Post, where: is_nil(p.published_at) + + To check if a given value is not nil use: + + from p in Post, where: not is_nil(p.published_at) + """ + def is_nil(value), do: doc!([value]) + + @doc """ + Counts the entries in the table. + + from p in Post, select: count() + """ + def count, do: doc!([]) + + @doc """ + Counts the given entry. + + from p in Post, select: count(p.id) + """ + def count(value), do: doc!([value]) + + @doc """ + Counts the distinct values in given entry. + + from p in Post, select: count(p.id, :distinct) + """ + def count(value, :distinct), do: doc!([value, :distinct]) + + @doc """ + Takes the first value which is not null, or null if they both are. + + In SQL, COALESCE takes any number of arguments, but in ecto + it only takes two, so it must be chained to achieve the same + effect. + + from p in Payment, select: p.value |> coalesce(p.backup_value) |> coalesce(0) + """ + def coalesce(value, expr), do: doc!([value, expr]) + + @doc """ + Applies the given expression as a FILTER clause against an + aggregate. This is currently only supported by Postgres. + + from p in Payment, select: filter(avg(p.value), p.value > 0 and p.value < 100) + + from p in Payment, select: avg(p.value) |> filter(p.value < 0) + """ + def filter(value, filter), do: doc!([value, filter]) + + @doc """ + Calculates the average for the given entry. + + from p in Payment, select: avg(p.value) + """ + def avg(value), do: doc!([value]) + + @doc """ + Calculates the sum for the given entry. + + from p in Payment, select: sum(p.value) + """ + def sum(value), do: doc!([value]) + + @doc """ + Calculates the minimum for the given entry. + + from p in Payment, select: min(p.value) + """ + def min(value), do: doc!([value]) + + @doc """ + Calculates the maximum for the given entry. + + from p in Payment, select: max(p.value) + """ + def max(value), do: doc!([value]) + + @doc """ + Adds a given interval to a datetime. + + The first argument is a `datetime`, the second one is the count + for the interval, which may be either positive or negative and + the interval value: + + # Get all items published since the last month + from p in Post, where: p.published_at > + datetime_add(^NaiveDateTime.utc_now(), -1, "month") + + In the example above, we used `datetime_add/3` to subtract one month + from the current datetime and compared it with the `p.published_at`. + If you want to perform operations on date, `date_add/3` could be used. + + See [Intervals](#module-intervals) for supported `interval` values. + """ + def datetime_add(datetime, count, interval), do: doc!([datetime, count, interval]) + + @doc """ + Adds a given interval to a date. + + See `datetime_add/3` for more information. + + See [Intervals](#module-intervals) for supported `interval` values. + """ + def date_add(date, count, interval), do: doc!([date, count, interval]) + + @doc """ + Adds the given interval to the current time in UTC. + + The current time in UTC is retrieved from Elixir and + not from the database. + + See [Intervals](#module-intervals) for supported `interval` values. + + ## Examples + + from a in Account, where: a.expires_at < from_now(3, "month") + + """ + def from_now(count, interval), do: doc!([count, interval]) + + @doc """ + Subtracts the given interval from the current time in UTC. + + The current time in UTC is retrieved from Elixir and + not from the database. + + See [Intervals](#module-intervals) for supported `interval` values. + + ## Examples + + from p in Post, where: p.published_at > ago(3, "month") + """ + def ago(count, interval), do: doc!([count, interval]) + + @doc """ + Send fragments directly to the database. + + It is not possible to represent all possible database queries using + Ecto's query syntax. When such is required, it is possible to use + fragments to send any expression to the database: + + def unpublished_by_title(title) do + from p in Post, + where: is_nil(p.published_at) and + fragment("lower(?)", p.title) == ^title + end + + Every occurrence of the `?` character will be interpreted as a place + for parameters, which must be given as additional arguments to + `fragment`. If the literal character `?` is required as part of the + fragment, it can be escaped with `\\\\?` (one escape for strings, + another for fragment). + + In the example above, we are using the lower procedure in the + database to downcase the title column. + + It is very important to keep in mind that Ecto is unable to do any + type casting when fragments are used. Therefore it may be necessary + to explicitly cast parameters via `type/2`: + + fragment("lower(?)", p.title) == type(^title, :string) + + ## Literals + + Sometimes you need to interpolate a literal value into a fragment, + instead of a parameter. For example, you may need to pass a table + name or a collation, such as: + + collation = "es_ES" + fragment("? COLLATE ?", ^name, ^collation) + + The example above won't work because `collation` will be passed + as a parameter, while it has to be a literal part of the query. + + You can address this by telling Ecto that variable is a literal: + + fragment("? COLLATE ?", ^name, literal(^collation)) + + Ecto will then escape it and make it part of the query. + + > #### Literals and query caching {: .warning} + > + > Because literals are made part of the query, each interpolated + > literal will generate a separate query, with its own cache. + + ## Splicing + + Sometimes you may need to interpolate a variable number of arguments + into the same fragment. For example, when overriding Ecto's default + `where` behaviour for Postgres: + + from p in Post, where: fragment("? in (?, ?)", p.id, val1, val2) + + The example above will only work if you know the number of arguments + upfront. If it can vary, the above will not work. + + You can address this by telling Ecto to splice a list argument into + the fragment: + + from p in Post, where: fragment("? in (?)", p.id, splice(^val_list)) + + This will let Ecto know it should expand the values of the list into + separate fragment arguments. For example: + + from p in Post, where: fragment("? in (?)", p.id, splice(^[1, 2, 3])) + + would be expanded into + + from p in Post, where: fragment("? in (?,?,?)", p.id, ^1, ^2, ^3) + + ## Defining custom functions using macros and fragment + + You can add a custom Ecto query function using macros. For example + to expose SQL's coalesce function you can define this macro: + + defmodule CustomFunctions do + defmacro coalesce(left, right) do + quote do + fragment("coalesce(?, ?)", unquote(left), unquote(right)) + end + end + end + + To have coalesce/2 available, just import the module that defines it. + + import CustomFunctions + + The only downside is that it will show up as a fragment when + inspecting the Elixir query. Other than that, it should be + equivalent to a built-in Ecto query function. + + ## Keyword fragments + + In order to support databases that do not have string-based + queries, like MongoDB, fragments also allow keywords to be given: + + from p in Post, + where: fragment(title: ["$eq": ^some_value]) + + """ + def fragment(fragments), do: doc!([fragments]) + + @doc """ + Allows a literal identifier to be injected into a fragment: + + collation = "es_ES" + fragment("? COLLATE ?", ^name, literal(^collation)) + + The example above will inject `collation` into the query as + a literal identifier instead of a query parameter. Note that + each different value of `collation` will emit a different query, + which will be independently prepared and cached. + """ + def literal(binary), do: doc!([binary]) + + @doc """ + Allows a list argument to be spliced into a fragment. + + from p in Post, where: fragment("? in (?)", p.id, splice(^[1, 2, 3])) + + The example above will be transformed at runtime into the following: + + from p in Post, where: fragment("? in (?,?,?)", p.id, ^1, ^2, ^3) + + You may only splice runtime values. For example, this would not work because + query bindings are compile-time constructs: + + from p in Post, where: fragment("concat(?)", splice(^[p.count, " ", "count"]) + """ + def splice(list), do: doc!([list]) + + @doc """ + Creates a values list/constant table. + + A values list can be used as a source in a query, both in `Ecto.Query.from/2` + and `Ecto.Query.join/5`. + + The first argument is a list of maps representing the values of the constant table. + An error is raised if the list is empty or if every map does not have exactly the + same fields. + + The second argument is a map of types corresponding to the fields in the first argument. + Each field must be given a type or an error is raised. Any type that can be specified in + a schema may be used. + + Queries using a values list are not cacheable by Ecto. + + ## Select example + + values = [%{id: 1, text: "abc"}, %{id: 2, text: "xyz"}] + types = %{id: :integer, text: :string} + + query = + from v1 in values(values, types), + join: v2 in values(values, types), + on: v1.id == v2.id + + Repo.all(query) + + ## Delete example + values = [%{id: 1, text: "abc"}, %{id: 2, text: "xyz"}] + types = %{id: :integer, text: :string} + + query = + from p in Post, + join: v in values(values, types), + on: p.id == v.id, + where: p.counter == ^0 + + Repo.delete_all(query) + + ## Update example + values = [%{id: 1, text: "abc"}, %{id: 2, text: "xyz"}] + types = %{id: :integer, text: :string} + + query = + from p in Post, + join: v in values(values, types), + on: p.id == v.id, + update: [set: [text: v.text]] + + Repo.update_all(query, []) + """ + def values(values, types), do: doc!([values, types]) + + @doc """ + Allows a field to be dynamically accessed. + + def at_least_four(doors_or_tires) do + from c in Car, + where: field(c, ^doors_or_tires) >= 4 + end + + In the example above, both `at_least_four(:doors)` and `at_least_four(:tires)` + would be valid calls as the field is dynamically generated. + """ + def field(source, field), do: doc!([source, field]) + + @doc """ + Used in `select` to specify which struct fields should be returned. + + For example, if you don't need all fields to be returned + as part of a struct, you can filter it to include only certain + fields by using `struct/2`: + + from p in Post, + select: struct(p, [:title, :body]) + + `struct/2` can also be used to dynamically select fields: + + fields = [:title, :body] + from p in Post, select: struct(p, ^fields) + + As a convenience, `select` allows developers to take fields + without an explicit call to `struct/2`: + + from p in Post, select: [:title, :body] + + Or even dynamically: + + fields = [:title, :body] + from p in Post, select: ^fields + + For preloads, the selected fields may be specified from the parent: + + from(city in City, preload: :country, + select: struct(city, [:country_id, :name, country: [:id, :population]])) + + If the same source is selected multiple times with a `struct`, + the fields are merged in order to avoid fetching multiple copies + from the database. In other words, the expression below: + + from(city in City, preload: :country, + select: {struct(city, [:country_id]), struct(city, [:name])}) + + is expanded to: + + from(city in City, preload: :country, + select: {struct(city, [:country_id, :name]), struct(city, [:country_id, :name])}) + + **IMPORTANT**: When filtering fields for associations, you + MUST include the foreign keys used in the relationship, + otherwise Ecto will be unable to find associated records. + """ + def struct(source, fields), do: doc!([source, fields]) + + @doc """ + Used in `select` to specify which fields should be returned as a map. + + For example, if you don't need all fields to be returned or + neither need a struct, you can use `map/2` to achieve both: + + from p in Post, + select: map(p, [:title, :body]) + + `map/2` can also be used to dynamically select fields: + + fields = [:title, :body] + from p in Post, select: map(p, ^fields) + + If the same source is selected multiple times with a `map`, + the fields are merged in order to avoid fetching multiple copies + from the database. In other words, the expression below: + + from(city in City, preload: :country, + select: {map(city, [:country_id]), map(city, [:name])}) + + is expanded to: + + from(city in City, preload: :country, + select: {map(city, [:country_id, :name]), map(city, [:country_id, :name])}) + + For preloads, the selected fields may be specified from the parent: + + from(city in City, preload: :country, + select: map(city, [:country_id, :name, country: [:id, :population]])) + + It's also possible to select a struct from one source but only a subset of + fields from one of its associations: + + from(city in City, preload: :country, + select: %{city | country: map(country: [:id, :population])}) + + **IMPORTANT**: When filtering fields for associations, you + MUST include the foreign keys used in the relationship, + otherwise Ecto will be unable to find associated records. + """ + def map(source, fields), do: doc!([source, fields]) + + @doc """ + Merges the map on the right over the map on the left. + + If the map on the left side is a struct, Ecto will check + all of the field on the right previously exist on the left + before merging. + + from(city in City, select: merge(city, %{virtual_field: "some_value"})) + + This function is primarily used by `Ecto.Query.select_merge/3` + to merge different select clauses. + """ + def merge(left_map, right_map), do: doc!([left_map, right_map]) + + @doc """ + Returns value from the `json_field` pointed to by `path`. + + from(post in Post, select: json_extract_path(post.meta, ["author", "name"])) + + The path can be dynamic: + + path = ["author", "name"] + from(post in Post, select: json_extract_path(post.meta, ^path)) + + And the field can also be dynamic in combination with it: + + path = ["author", "name"] + from(post in Post, select: json_extract_path(field(post, :meta), ^path)) + + The query can be also rewritten as: + + from(post in Post, select: post.meta["author"]["name"]) + + Path elements can be integers to access values in JSON arrays: + + from(post in Post, select: post.meta["tags"][0]["name"]) + + Any element of the path can be dynamic: + + field = "name" + from(post in Post, select: post.meta["author"][^field]) + + ## Warning: indexes on PostgreSQL + + PostgreSQL supports indexing on jsonb columns via GIN indexes. + Whenever comparing the value of a jsonb field against a string + or integer, Ecto will use the containment operator @> which + is optimized. You can even use the more efficient `jsonb_path_ops` + GIN index variant. For more information, consult PostgreSQL's docs + on [JSON indexing](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING). + + ## Warning: return types + + The underlying data in the JSON column is returned without any + additional decoding. This means "null" JSON values are not the + same as SQL's "null". For example, the `Repo.all` operation below + returns an empty list because `p.meta["author"]` returns JSON's + null and therefore `is_nil` does not succeed: + + Repo.insert!(%Post{meta: %{author: nil}}) + Repo.all(from(post in Post, where: is_nil(p.meta["author"]))) + + Similarly, other types, such as datetimes, are returned as strings. + This means conditions like `post.meta["published_at"] > from_now(-1, "day")` + may return incorrect results or fail as the underlying database + tries to compare incompatible types. You can, however, use `type/2` + to force the types on the database level. + """ + def json_extract_path(json_field, path), do: doc!([json_field, path]) + + @doc """ + Casts the given value to the given type at the database level. + + Most of the times, Ecto is able to proper cast interpolated + values due to its type checking mechanism. In some situations + though, you may want to tell Ecto that a parameter has some + particular type: + + type(^title, :string) + + It is also possible to say the type must match the same of a column: + + type(^title, p.title) + + Or a parameterized type, which must be previously initialized + with `Ecto.ParameterizedType.init/2`: + + @my_enum Ecto.ParameterizedType.init(Ecto.Enum, values: [:foo, :bar, :baz]) + type(^title, ^@my_enum) + + Ecto will ensure `^title` is cast to the given type and enforce such + type at the database level. If the value is returned in a `select`, + Ecto will also enforce the proper type throughout. + + When performing arithmetic operations, `type/2` can be used to cast + all the parameters in the operation to the same type: + + from p in Post, + select: type(p.visits + ^a_float + ^a_integer, :decimal) + + Inside `select`, `type/2` can also be used to cast fragments: + + type(fragment("NOW"), :naive_datetime) + + Or to type fields from schemaless queries: + + from p in "posts", select: type(p.cost, :decimal) + + Or to type aggregation results: + + from p in Post, select: type(avg(p.cost), :integer) + from p in Post, select: type(filter(avg(p.cost), p.cost > 0), :integer) + + Or to type comparison expression results: + + from p in Post, select: type(coalesce(p.cost, 0), :integer) + + Or to type fields from a parent query using `parent_as/1`: + + child = from c in Comment, where: type(parent_as(:posts).id, :string) == c.text + from Post, as: :posts, inner_lateral_join: c in subquery(child), select: c.text + + ## `type` vs `fragment` + + `type/2` is all about Ecto types. Therefore, you can perform `type(expr, :string)` + but not `type(expr, :text)`, because `:text` is not an actual Ecto type. If you want + to perform casting exclusively at the database level, you can use fragment. For example, + in PostgreSQL, you might do `fragment("?::text", p.column)`. + """ + def type(interpolated_value, type), do: doc!([interpolated_value, type]) + + @doc """ + Refer to a named atom binding. + + See the "Named bindings" section in `Ecto.Query` for more information. + """ + def as(binding), do: doc!([binding]) + + @doc """ + Refer to a named atom binding in the parent query. + + This is available only inside subqueries. + + See the "Named bindings" section in `Ecto.Query` for more information. + """ + def parent_as(binding), do: doc!([binding]) + + @doc """ + Refer to an alias of a selected value. + + This can be used to refer to aliases created using `selected_as/2`. If + the alias hasn't been created using `selected_as/2`, an error will be raised. + + Each database has its own rules governing which clauses can reference these aliases. + If an error is raised mentioning an unknown column, most likely the alias is being + referenced somewhere that is not allowed. Consult the documentation for the database + to ensure the alias is being referenced correctly. + """ + def selected_as(name), do: doc!([name]) + + @doc """ + Creates an alias for the given selected value. + + When working with calculated values, an alias can be used to simplify + the query. Otherwise, the entire expression would need to be copied when + referencing it outside of select statements. + + This comes in handy when, for instance, you would like to use the calculated + value in `Ecto.Query.group_by/3` or `Ecto.Query.order_by/3`: + + from p in Post, + select: %{ + posted: selected_as(p.posted, :date), + sum_visits: p.visits |> coalesce(0) |> sum() |> selected_as(:sum_visits) + }, + group_by: selected_as(:date), + order_by: selected_as(:sum_visits) + + The name of the alias must be an atom and it can only be used in the outer most + select expression, otherwise an error is raised. Please note that the alias name + does not have to match the key when `select` returns a map, struct or keyword list. + + Using this in conjunction with `selected_as/1` is recommended to ensure only defined aliases + are referenced. + + ## Subqueries and CTEs + + Subqueries and CTEs automatically alias the selected fields, for example, one can write: + + # Subquery + s = from p in Post, select: %{visits: coalesce(p.visits, 0)} + from(s in subquery(s), select: s.visits) + + # CTE + cte_query = from p in Post, select: %{visits: coalesce(p.visits, 0)} + Post |> with_cte("cte", as: ^cte_query) |> join(:inner, [p], c in "cte") |> select([p, c], c.visits) + + However, one can also use `selected_as` to override the default naming: + + # Subquery + s = from p in Post, select: %{visits: coalesce(p.visits, 0) |> selected_as(:num_visits)} + from(s in subquery(s), select: s.num_visits) + + # CTE + cte_query = from p in Post, select: %{visits: coalesce(p.visits, 0) |> selected_as(:num_visits)} + Post |> with_cte("cte", as: ^cte_query) |> join(:inner, [p], c in "cte") |> select([p, c], c.num_visits) + + The name given to `selected_as/2` can also be referenced in `selected_as/1`, + as in regular queries. + """ + def selected_as(selected_value, name), do: doc!([selected_value, name]) + + defp doc!(_) do + raise "the functions in Ecto.Query.API should not be invoked directly, " <> + "they serve for documentation purposes only" + end +end diff --git a/deps/ecto/lib/ecto/query/builder.ex b/deps/ecto/lib/ecto/query/builder.ex new file mode 100644 index 0000000000000000000000000000000000000000..38c9944dc39a1b4a452d5d22f0e40ae593bad7be --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder.ex @@ -0,0 +1,1542 @@ +defmodule Ecto.Query.Builder do + @moduledoc false + + alias Ecto.Query + + @comparisons [ + is_nil: 1, + ==: 2, + !=: 2, + <: 2, + >: 2, + <=: 2, + >=: 2 + ] + + @dynamic_aggregates [ + max: 1, + min: 1, + first_value: 1, + last_value: 1, + nth_value: 2, + lag: 3, + lead: 3, + lag: 2, + lead: 2, + lag: 1, + lead: 1 + ] + + @static_aggregates [ + count: {0, :integer}, + count: {1, :integer}, + count: {2, :integer}, + avg: {1, :any}, + sum: {1, :any}, + row_number: {0, :integer}, + rank: {0, :integer}, + dense_rank: {0, :integer}, + percent_rank: {0, :any}, + cume_dist: {0, :any}, + ntile: {1, :integer} + ] + + @select_alias_dummy_value [] + + @typedoc """ + Quoted types store primitive types and types in the format + {source, quoted}. The latter are handled directly in the planner, + never forwarded to Ecto.Type. + + The Ecto.Type module concerns itself only with runtime types, + which include all primitive types and custom user types. Also + note custom user types do not show up during compilation time. + """ + @type quoted_type :: Ecto.Type.primitive() | {non_neg_integer, atom | Macro.t()} + + @typedoc """ + The accumulator during escape. + + If the subqueries field is available, subquery escaping must take place. + """ + @type acc :: %{ + optional(:subqueries) => list(Macro.t()), + optional(:take) => %{non_neg_integer => Macro.t()}, + optional(any) => any + } + + @doc """ + Smart escapes a query expression and extracts interpolated values in + a map. + + Everything that is a query expression will be escaped, interpolated + expressions (`^foo`) will be moved to a map unescaped and replaced + with `^index` in the query where index is a number indexing into the + map. + """ + @spec escape( + Macro.t(), + quoted_type | {:in, quoted_type} | {:out, quoted_type} | {:splice, quoted_type}, + {list, acc}, + Keyword.t(), + Macro.Env.t() | {Macro.Env.t(), fun} + ) :: {Macro.t(), {list, acc}} + def escape(expr, type, params_acc, vars, env) + + # var.x - where var is bound + def escape({{:., _, [callee, field]}, _, []}, _type, params_acc, vars, _env) + when is_atom(field) do + {escape_field!(callee, field, vars), params_acc} + end + + # field macro + def escape({:field, _, [callee, field]}, _type, params_acc, vars, _env) do + {escape_field!(callee, field, vars), params_acc} + end + + # param interpolation + def escape({:^, _, [arg]}, type, {params, acc}, _vars, _env) do + expr = {:{}, [], [:^, [], [length(params)]]} + params = [{arg, type} | params] + {expr, {params, acc}} + end + + # tagged types + def escape({:type, _, [{:^, _, [arg]}, type]}, _type, {params, acc}, vars, env) do + type = validate_type!(type, vars, env) + expr = {:{}, [], [:type, [], [{:{}, [], [:^, [], [length(params)]]}, type]]} + params = [{arg, type} | params] + {expr, {params, acc}} + end + + def escape( + {:type, _, [{{:., _, [{var, _, context}, field]}, _, []} = expr, type]}, + _type, + params_acc, + vars, + env + ) + when is_atom(var) and is_atom(context) and is_atom(field) do + escape_with_type(expr, type, params_acc, vars, env) + end + + def escape({:type, _, [{:coalesce, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) do + escape_with_type(expr, type, params_acc, vars, env) + end + + def escape({:type, _, [{:field, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) do + escape_with_type(expr, type, params_acc, vars, env) + end + + def escape({:type, _, [{math_op, _, [_, _]} = op_expr, type]}, _type, params_acc, vars, env) + when math_op in ~w(+ - * /)a do + escape_with_type(op_expr, type, params_acc, vars, env) + end + + def escape({:type, _, [{fun, _, args} = expr, type]}, _type, params_acc, vars, env) + when is_list(args) and fun in ~w(fragment avg count max min sum over filter)a do + escape_with_type(expr, type, params_acc, vars, env) + end + + def escape( + {:type, _, [{:json_extract_path, _, [_ | _]} = expr, type]}, + _type, + params_acc, + vars, + env + ) do + escape_with_type(expr, type, params_acc, vars, env) + end + + def escape( + {:type, _, [{{:., _, [Access, :get]}, _, _} = access_expr, type]}, + _type, + params_acc, + vars, + env + ) do + escape_with_type(access_expr, type, params_acc, vars, env) + end + + def escape( + {:type, _, [{{:., _, [{:parent_as, _, [_parent]}, _field]}, _, []} = expr, type]}, + _type, + params_acc, + vars, + env + ) do + escape_with_type(expr, type, params_acc, vars, env) + end + + def escape({:type, meta, [expr, type]}, given_type, params_acc, vars, env) do + case Macro.expand_once(expr, get_env(env)) do + ^expr -> + error!(""" + the first argument of type/2 must be one of: + + * interpolations, such as ^value + * fields, such as p.foo or field(p, :foo) + * fragments, such as fragment("foo(?)", value) + * an arithmetic expression (+, -, *, /) + * an aggregation or window expression (avg, count, min, max, sum, over, filter) + * a conditional expression (coalesce) + * access/json paths (p.column[0].field) + * parent_as/1 (parent_as(:parent).field) + + Got: #{Macro.to_string(expr)} + """) + + expanded -> + escape({:type, meta, [expanded, type]}, given_type, params_acc, vars, env) + end + end + + # fragments + def escape({:fragment, _, [query]}, _type, params_acc, vars, env) when is_list(query) do + {escaped, params_acc} = + Enum.map_reduce(query, params_acc, &escape_kw_fragment(&1, &2, vars, env)) + + {{:{}, [], [:fragment, [], [escaped]]}, params_acc} + end + + def escape({:fragment, _, [{:^, _, [var]} = _expr]}, _type, params_acc, _vars, _env) do + expr = quote do: Ecto.Query.Builder.fragment!(unquote(var)) + {{:{}, [], [:fragment, [], [expr]]}, params_acc} + end + + def escape({:fragment, _, [query | frags]}, _type, params_acc, vars, env) do + pieces = expand_and_split_fragment(query, env) + + if length(pieces) != length(frags) + 1 do + error!( + "fragment(...) expects extra arguments in the same amount of question marks in string. " <> + "It received #{length(frags)} extra argument(s) but expected #{length(pieces) - 1}" + ) + end + + {frags, params_acc} = Enum.map_reduce(frags, params_acc, &escape_fragment(&1, &2, vars, env)) + {{:{}, [], [:fragment, [], merge_fragments(pieces, frags)]}, params_acc} + end + + # subqueries + def escape({:subquery, _, [expr]}, _, {params, %{subqueries: subqueries} = acc}, _vars, _env) do + subquery = quote(do: Ecto.Query.subquery(unquote(expr))) + index = length(subqueries) + # used both in ast and in parameters, as a placeholder. + expr = {:subquery, index} + acc = %{acc | subqueries: [subquery | subqueries]} + {expr, {[expr | params], acc}} + end + + # interval + + def escape({:from_now, meta, [count, interval]}, type, params_acc, vars, env) do + utc = quote do: ^DateTime.utc_now() + escape({:datetime_add, meta, [utc, count, interval]}, type, params_acc, vars, env) + end + + def escape({:ago, meta, [count, interval]}, type, params_acc, vars, env) do + utc = quote do: ^DateTime.utc_now() + + count = + case count do + {:^, meta, [value]} -> + negate = quote do: Ecto.Query.Builder.negate!(unquote(value)) + {:^, meta, [negate]} + + value -> + {:-, [], [value]} + end + + escape({:datetime_add, meta, [utc, count, interval]}, type, params_acc, vars, env) + end + + def escape({:datetime_add, _, [datetime, count, interval]} = expr, type, params_acc, vars, env) do + assert_type!(expr, type, {:supertype, :datetime}) + {datetime, params_acc} = escape(datetime, {:supertype, :datetime}, params_acc, vars, env) + {count, interval, params_acc} = escape_interval(count, interval, params_acc, vars, env) + {{:{}, [], [:datetime_add, [], [datetime, count, interval]]}, params_acc} + end + + def escape({:date_add, _, [date, count, interval]} = expr, type, params_acc, vars, env) do + assert_type!(expr, type, :date) + {date, params_acc} = escape(date, :date, params_acc, vars, env) + {count, interval, params_acc} = escape_interval(count, interval, params_acc, vars, env) + {{:{}, [], [:date_add, [], [date, count, interval]]}, params_acc} + end + + # json + def escape({:json_extract_path, _, [field, path]}, type, params_acc, vars, env) do + validate_json_field!(field) + + path = escape_json_path(path) + {field, params_acc} = escape(field, type, params_acc, vars, env) + {{:{}, [], [:json_extract_path, [], [field, path]]}, params_acc} + end + + def escape({{:., meta, [Access, :get]}, _, [left, _]} = expr, type, params_acc, vars, env) do + case left do + {{:., _, _}, _, _} -> + {expr, path} = parse_access_get(expr, []) + escape({:json_extract_path, meta, [expr, path]}, type, params_acc, vars, env) + + _ -> + error!("`#{Macro.to_string(expr)}` is not a valid query expression") + end + end + + # sigils + def escape({name, _, [_, []]} = sigil, type, params_acc, vars, _env) + when name in ~w(sigil_s sigil_S sigil_w sigil_W)a do + {literal(sigil, type, vars), params_acc} + end + + # lists + def escape(list, type, params_acc, vars, env) when is_list(list) do + if Enum.all?(list, &(is_binary(&1) or is_number(&1) or is_boolean(&1))) do + {literal(list, type, vars), params_acc} + else + fun = + case type do + {:array, inner_type} -> + &escape(&1, inner_type, &2, vars, env) + + _ -> + # In case we don't have an array nor a literal at compile-time, + # such as p.links == [^value], we don't do any casting nor validation. + # We may want to tackle this if the expression above is ever used. + &escape(&1, :any, &2, vars, env) + end + + Enum.map_reduce(list, params_acc, fun) + end + end + + # literals + def escape({:<<>>, _, args} = expr, type, params_acc, vars, _env) do + valid? = + Enum.all?(args, fn + {:"::", _, [left, _]} -> is_integer(left) or is_binary(left) + left -> is_integer(left) or is_binary(left) + end) + + unless valid? do + error!( + "`#{Macro.to_string(expr)}` is not a valid query expression. " <> + "Only literal binaries and strings are allowed, " <> + "dynamic values need to be explicitly interpolated in queries with ^" + ) + end + + {literal(expr, type, vars), params_acc} + end + + def escape({:-, _, [number]}, type, params_acc, vars, _env) when is_number(number), + do: {literal(-number, type, vars), params_acc} + + def escape(number, type, params_acc, vars, _env) when is_number(number), + do: {literal(number, type, vars), params_acc} + + def escape(binary, type, params_acc, vars, _env) when is_binary(binary), + do: {literal(binary, type, vars), params_acc} + + def escape(nil, _type, params_acc, _vars, _env), + do: {nil, params_acc} + + def escape(atom, type, params_acc, vars, _env) when is_atom(atom), + do: {literal(atom, type, vars), params_acc} + + # negate any expression + def escape({:-, meta, arg}, type, params_acc, vars, env) do + {escaped_arg, params_acc} = escape(arg, type, params_acc, vars, env) + expr = {:{}, [], [:-, meta, escaped_arg]} + {expr, params_acc} + end + + # comparison operators + def escape({comp_op, _, [left, right]} = expr, type, params_acc, vars, env) + when comp_op in ~w(== != < > <= >=)a do + assert_type!(expr, type, :boolean) + + if is_nil(left) or is_nil(right) do + error!( + "comparison with nil is forbidden as it is unsafe. " <> + "If you want to check if a value is nil, use is_nil/1 instead" + ) + end + + ltype = quoted_type(right, vars) + rtype = quoted_type(left, vars) + + {left, params_acc} = escape(left, ltype, params_acc, vars, env) + {right, params_acc} = escape(right, rtype, params_acc, vars, env) + + {params, acc} = params_acc + {{:{}, [], [comp_op, [], [left, right]]}, {params |> wrap_nil(left) |> wrap_nil(right), acc}} + end + + # mathematical operators + def escape({math_op, _, [left, right]}, type, params_acc, vars, env) + when math_op in ~w(+ - * /)a do + {left, params_acc} = escape(left, type, params_acc, vars, env) + {right, params_acc} = escape(right, type, params_acc, vars, env) + + {{:{}, [], [math_op, [], [left, right]]}, params_acc} + end + + # in operator + def escape({:in, _, [left, right]} = expr, type, params_acc, vars, env) + when is_list(right) + when is_tuple(right) and elem(right, 0) in ~w(sigil_w sigil_W @)a do + assert_type!(expr, type, :boolean) + + right = Macro.expand_once(right, get_env(env)) + {:array, ltype} = quoted_type(right, vars) + rtype = {:array, quoted_type(left, vars)} + + {left, params_acc} = escape(left, ltype, params_acc, vars, env) + {right, params_acc} = escape(right, rtype, params_acc, vars, env) + {{:{}, [], [:in, [], [left, right]]}, params_acc} + end + + def escape({:in, _, [left, right]} = expr, type, params_acc, vars, env) do + assert_type!(expr, type, :boolean) + + ltype = {:out, quoted_type(right, vars)} + rtype = {:in, quoted_type(left, vars)} + + {left, params_acc} = escape(left, ltype, params_acc, vars, env) + {right, params_acc} = escape(right, rtype, params_acc, vars, env) + + # Remove any type wrapper from the right side + right = + case right do + {:{}, [], [:type, [], [right, _]]} -> right + _ -> right + end + + {{:{}, [], [:in, [], [left, right]]}, params_acc} + end + + def escape({:count, _, [arg, :distinct]}, type, params_acc, vars, env) do + {arg, params_acc} = escape(arg, type, params_acc, vars, env) + expr = {:{}, [], [:count, [], [arg, :distinct]]} + {expr, params_acc} + end + + def escape({:filter, _, [aggregate]}, type, params_acc, vars, env) do + escape(aggregate, type, params_acc, vars, env) + end + + def escape({:filter, _, [aggregate, filter_expr]}, type, params_acc, vars, env) do + {aggregate, params_acc} = escape(aggregate, type, params_acc, vars, env) + {filter_expr, params_acc} = escape(filter_expr, :boolean, params_acc, vars, env) + {{:{}, [], [:filter, [], [aggregate, filter_expr]]}, params_acc} + end + + def escape({:coalesce, _, [left, right]}, type, params_acc, vars, env) do + {left, params_acc} = escape(left, type, params_acc, vars, env) + {right, params_acc} = escape(right, type, params_acc, vars, env) + {{:{}, [], [:coalesce, [], [left, right]]}, params_acc} + end + + def escape({:over, _, [{agg_name, _, agg_args} | over_args]}, type, params_acc, vars, env) do + aggregate = {agg_name, [], agg_args || []} + {aggregate, params_acc} = escape_window_function(aggregate, type, params_acc, vars, env) + {window, params_acc} = escape_window_description(over_args, params_acc, vars, env) + {{:{}, [], [:over, [], [aggregate, window]]}, params_acc} + end + + def escape({:selected_as, _, [_expr, _name]}, _type, _params_acc, _vars, _env) do + error!(""" + selected_as/2 can only be used at the root of a select statement. \ + If you are trying to use it inside of an expression, consider putting the \ + expression inside of `selected_as/2` instead. For instance, instead of: + + from p in Post, select: coalesce(selected_as(p.visits, :v), 0) + + use: + + from p in Post, select: selected_as(coalesce(p.visits, 0), :v) + """) + end + + def escape({:selected_as, _, [name]}, _type, params_acc, _vars, _env) do + name = quoted_atom!(name, "selected_as/1") + expr = {:{}, [], [:selected_as, [], [name]]} + {expr, params_acc} + end + + def escape({quantifier, meta, [subquery]}, type, params_acc, vars, env) + when quantifier in [:all, :any, :exists] do + {subquery, params_acc} = escape({:subquery, meta, [subquery]}, type, params_acc, vars, env) + {{:{}, [], [quantifier, [], [subquery]]}, params_acc} + end + + def escape({:=, _, _} = expr, _type, _params_acc, _vars, _env) do + error!( + "`#{Macro.to_string(expr)}` is not a valid query expression. " <> + "The match operator is not supported: `=`. " <> + "Did you mean to use `==` instead?" + ) + end + + def escape({op, _, _}, _type, _params_acc, _vars, _env) when op in ~w(|| && !)a do + error!( + "short-circuit operators are not supported: `#{op}`. " <> + "Instead use boolean operators: `and`, `or`, and `not`" + ) + end + + # Tuple + def escape({left, right}, type, params_acc, vars, env) do + escape({:{}, [], [left, right]}, type, params_acc, vars, env) + end + + # Tuple + def escape({:{}, _, list}, {:tuple, types}, params_acc, vars, env) do + if Enum.count(list) == Enum.count(types) do + {list, params_acc} = + list + |> Enum.zip(types) + |> Enum.map_reduce(params_acc, fn {expr, type}, params_acc -> + escape(expr, type, params_acc, vars, env) + end) + + expr = {:{}, [], [:{}, [], list]} + {expr, params_acc} + else + escape({:{}, [], list}, :any, params_acc, vars, env) + end + end + + # Tuple + def escape({:{}, _, _}, _, _, _, _) do + error!("Tuples can only be used in comparisons with literal tuples of the same size") + end + + # Unnecessary parentheses around an expression + def escape({:__block__, _, [expr]}, type, params_acc, vars, env) do + escape(expr, type, params_acc, vars, env) + end + + # Other functions - no type casting + def escape({name, _, args} = expr, type, params_acc, vars, env) + when is_atom(name) and is_list(args) do + case call_type(name, length(args)) do + {in_type, out_type} -> + assert_type!(expr, type, out_type) + escape_call(expr, in_type, params_acc, vars, env) + + nil -> + try_expansion(expr, type, params_acc, vars, env) + end + end + + # Finally handle vars + def escape({var, _, context}, _type, params_acc, vars, _env) + when is_atom(var) and is_atom(context) do + {escape_var!(var, vars), params_acc} + end + + # Raise nice error messages for fun calls. + def escape({fun, _, args} = other, _type, _params_acc, _vars, _env) + when is_atom(fun) and is_list(args) do + error!(""" + `#{Macro.to_string(other)}` is not a valid query expression. \ + If you are trying to invoke a function that is not supported by Ecto, \ + you can use fragments: + + fragment("some_function(?, ?, ?)", m.some_field, 1) + + See Ecto.Query.API to learn more about the supported functions and \ + Ecto.Query.API.fragment/1 to learn more about fragments. + """) + end + + # Raise nice error message for remote calls + def escape({{:., _, [_, fun]}, _, _} = other, type, params_acc, vars, env) + when is_atom(fun) do + try_expansion(other, type, params_acc, vars, env) + end + + # For everything else we raise + def escape(other, _type, _params_acc, _vars, _env) do + error!("`#{Macro.to_string(other)}` is not a valid query expression") + end + + defp escape_with_type(expr, {:^, _, [type]}, params_acc, vars, env) do + {expr, params_acc} = escape(expr, :any, params_acc, vars, env) + {{:{}, [], [:type, [], [expr, type]]}, params_acc} + end + + defp escape_with_type(expr, type, params_acc, vars, env) do + type = validate_type!(type, vars, env) + {expr, params_acc} = escape(expr, type, params_acc, vars, env) + {{:{}, [], [:type, [], [expr, escape_type(type)]]}, params_acc} + end + + defp escape_type({:parameterized, _} = param), do: Macro.escape(param) + defp escape_type(type), do: type + + defp validate_json_field!({{:., _, _}, _, _}), do: :ok + defp validate_json_field!({:field, _, _}), do: :ok + + defp validate_json_field!(unsupported_field), + do: error!("`#{Macro.to_string(unsupported_field)}` is not a valid json field") + + defp wrap_nil(params, {:{}, _, [:^, _, [ix]]}), + do: wrap_nil(params, length(params) - ix - 1, []) + + defp wrap_nil(params, _other), do: params + + defp wrap_nil([{val, type} | params], 0, acc) do + val = quote do: Ecto.Query.Builder.not_nil!(unquote(val)) + Enum.reverse(acc, [{val, type} | params]) + end + + defp wrap_nil([pair | params], i, acc) do + wrap_nil(params, i - 1, [pair | acc]) + end + + defp expand_and_split_fragment(query, env) do + case Macro.expand(query, get_env(env)) do + binary when is_binary(binary) -> + split_fragment(binary, "") + + _ -> + error!(bad_fragment_message(Macro.to_string(query))) + end + end + + defp bad_fragment_message(arg) do + "to prevent SQL injection attacks, fragment(...) does not allow strings " <> + "to be interpolated as the first argument via the `^` operator, got: `#{arg}`" + end + + defp split_fragment(<<>>, consumed), + do: [consumed] + + defp split_fragment(<>, consumed), + do: [consumed | split_fragment(rest, "")] + + defp split_fragment(<>, consumed), + do: split_fragment(rest, consumed <> <>) + + defp split_fragment(<>, consumed), + do: split_fragment(rest, consumed <> <>) + + @doc "Returns fragment pieces, given a fragment string and arguments." + def fragment_pieces(frag, args) do + frag + |> split_fragment("") + |> merge_fragments(args) + end + + defp escape_window_description([], params_acc, _vars, _env), + do: {[], params_acc} + + defp escape_window_description([window_name], params_acc, _vars, _env) + when is_atom(window_name), + do: {window_name, params_acc} + + defp escape_window_description([kw], params_acc, vars, env) do + case Ecto.Query.Builder.Windows.escape(kw, params_acc, vars, env) do + {runtime, [], params_acc} -> + {runtime, params_acc} + + {_, [{key, _} | _], _} -> + error!( + "windows definitions given to over/2 do not allow interpolations at the root of " <> + "`#{key}`. Please use Ecto.Query.windows/3 to explicitly define a window instead" + ) + end + end + + defp escape_window_function(expr, type, params_acc, vars, env) do + expr + |> validate_window_function!(env) + |> escape(type, params_acc, vars, env) + end + + defp validate_window_function!({:fragment, _, _} = expr, _env), do: expr + + defp validate_window_function!({agg, _, args} = expr, env) + when is_atom(agg) and is_list(args) do + if Code.ensure_loaded?(Ecto.Query.WindowAPI) and + function_exported?(Ecto.Query.WindowAPI, agg, length(args)) do + expr + else + case Macro.expand_once(expr, get_env(env)) do + ^expr -> + error!( + "unknown window function #{agg}/#{length(args)}. " <> + "See Ecto.Query.WindowAPI for all available functions" + ) + + expr -> + validate_window_function!(expr, env) + end + end + end + + defp validate_window_function!(expr, _), do: expr + + defp escape_call({name, _, args}, type, params_acc, vars, env) do + {args, params_acc} = Enum.map_reduce(args, params_acc, &escape(&1, type, &2, vars, env)) + expr = {:{}, [], [name, [], args]} + {expr, params_acc} + end + + defp escape_field!({var, _, context}, field, vars) + when is_atom(var) and is_atom(context) do + var = escape_var!(var, vars) + field = quoted_atom!(field, "field/2") + dot = {:{}, [], [:., [], [var, field]]} + {:{}, [], [dot, [], []]} + end + + defp escape_field!({kind, _, [value]}, field, _vars) + when kind in [:as, :parent_as] do + value = late_binding!(kind, value) + as = {:{}, [], [kind, [], [value]]} + field = quoted_atom!(field, "field/2") + dot = {:{}, [], [:., [], [as, field]]} + {:{}, [], [dot, [], []]} + end + + defp escape_field!(expr, field, _vars) do + error!(""" + cannot fetch field `#{Macro.to_string(field)}` from `#{Macro.to_string(expr)}`. Can only fetch fields from: + + * sources, such as `p` in `from p in Post` + * named bindings, such as `as(:post)` in `from Post, as: :post` + * parent named bindings, such as `parent_as(:post)` in a subquery + """) + end + + defp escape_interval(count, interval, params_acc, vars, env) do + type = + cond do + is_float(count) -> :float + is_integer(count) -> :integer + true -> :decimal + end + + {count, params_acc} = escape(count, type, params_acc, vars, env) + {count, quoted_interval!(interval), params_acc} + end + + defp escape_kw_fragment({key, [{_, _} | _] = exprs}, params_acc, vars, env) when is_atom(key) do + {escaped, params_acc} = + Enum.map_reduce(exprs, params_acc, &escape_kw_fragment(&1, &2, vars, env)) + + {{key, escaped}, params_acc} + end + + defp escape_kw_fragment({key, expr}, params_acc, vars, env) when is_atom(key) do + {escaped, params_acc} = escape(expr, :any, params_acc, vars, env) + {{key, escaped}, params_acc} + end + + defp escape_kw_fragment({key, _expr}, _params_acc, _vars, _env) do + error!( + "fragment(...) with keywords accepts only atoms as keys, got `#{Macro.to_string(key)}`" + ) + end + + defp escape_fragment({:literal, _meta, [expr]}, params_acc, _vars, _env) do + case expr do + {:^, _, [expr]} -> + checked = quote do: Ecto.Query.Builder.literal!(unquote(expr)) + escaped = {:{}, [], [:literal, [], [checked]]} + {escaped, params_acc} + + _ -> + error!( + "literal/1 in fragment expects an interpolated value, such as literal(^value), got `#{Macro.to_string(expr)}`" + ) + end + end + + defp escape_fragment({:splice, _meta, [splice]}, params_acc, vars, env) do + case splice do + {:^, _, [value]} = expr -> + checked = quote do: Ecto.Query.Builder.splice!(unquote(value)) + length = quote do: length(unquote(checked)) + {expr, params_acc} = escape(expr, {:splice, :any}, params_acc, vars, env) + escaped = {:{}, [], [:splice, [], [expr, length]]} + {escaped, params_acc} + + _ -> + error!( + "splice/1 in fragment expects an interpolated value, such as splice(^value), got `#{Macro.to_string(splice)}`" + ) + end + end + + defp escape_fragment(expr, params_acc, vars, env) do + escape(expr, :any, params_acc, vars, env) + end + + defp merge_fragments([h1 | t1], [h2 | t2]), + do: [{:raw, h1}, {:expr, h2} | merge_fragments(t1, t2)] + + defp merge_fragments([h1], []), + do: [{:raw, h1}] + + for {agg, arity} <- @dynamic_aggregates do + defp call_type(unquote(agg), unquote(arity)), do: {:any, :any} + end + + for {agg, {arity, return}} <- @static_aggregates do + defp call_type(unquote(agg), unquote(arity)), do: {:any, unquote(return)} + end + + for {comp, arity} <- @comparisons do + defp call_type(unquote(comp), unquote(arity)), do: {:any, :boolean} + end + + defp call_type(:or, 2), do: {:boolean, :boolean} + defp call_type(:and, 2), do: {:boolean, :boolean} + defp call_type(:not, 1), do: {:boolean, :boolean} + defp call_type(:like, 2), do: {:string, :boolean} + defp call_type(:ilike, 2), do: {:string, :boolean} + defp call_type(_, _), do: nil + + defp assert_type!(expr, type, actual) do + cond do + not is_atom(type) and not Ecto.Type.primitive?(type) -> + :ok + + Ecto.Type.match?(type, actual) -> + :ok + + true -> + error!( + "expression `#{Macro.to_string(expr)}` does not type check. " <> + "It returns a value of type #{inspect(actual)} but a value of " <> + "type #{inspect(type)} is expected" + ) + end + end + + @doc """ + Validates the type with the given vars. + """ + def validate_type!({:parameterized, _} = type, _vars, _env), + do: type + + def validate_type!({composite, type}, vars, env), + do: {composite, validate_type!(type, vars, env)} + + def validate_type!({:^, _, [type]}, _vars, _env), + do: type + + def validate_type!({:__aliases__, _, _} = type, _vars, env), + do: Macro.expand(type, get_env(env)) + + def validate_type!(type, _vars, _env) when is_atom(type), + do: type + + def validate_type!({{:., _, [{var, _, context}, field]}, _, []}, vars, _env) + when is_atom(var) and is_atom(context) and is_atom(field), + do: {find_var!(var, vars), field} + + def validate_type!({:field, _, [{var, _, context}, field]}, vars, _env) + when is_atom(var) and is_atom(context) and is_atom(field), + do: {find_var!(var, vars), field} + + def validate_type!({:field, _, [{var, _, context}, {:^, _, [field]}]}, vars, _env) + when is_atom(var) and is_atom(context), + do: {find_var!(var, vars), field} + + def validate_type!(type, _vars, _env) do + error!( + "type/2 expects an alias, atom, initialized parameterized type or " <> + "source.field as second argument, got: `#{Macro.to_string(type)}`" + ) + end + + @always_tagged [:binary] + + defp literal(value, expected, vars), + do: do_literal(value, expected, quoted_type(value, vars)) + + defp do_literal(value, _, current) when current in @always_tagged, + do: + {:%, [], + [Ecto.Query.Tagged, {:%{}, [], [value: value, type: normalize_type(value, current)]}]} + + defp do_literal(value, :any, _current), + do: value + + defp do_literal(value, expected, expected), + do: value + + defp do_literal(value, expected, _current), + do: {:%, [], [Ecto.Query.Tagged, {:%{}, [], [value: value, type: expected]}]} + + @doc """ + Escape the params entries list. + """ + @spec escape_params(list()) :: list() + def escape_params(list), do: Enum.reverse(list) + + @doc """ + Escape the select alias map + """ + @spec escape_select_aliases(map()) :: Macro.t() + def escape_select_aliases(%{} = aliases), do: {:%{}, [], Map.to_list(aliases)} + + @doc """ + Escapes a variable according to the given binds. + + A escaped variable is represented internally as + `&0`, `&1` and so on. + """ + @spec escape_var!(atom, Keyword.t()) :: Macro.t() + def escape_var!(var, vars) do + {:{}, [], [:&, [], [find_var!(var, vars)]]} + end + + @doc """ + Escapes a list of bindings as a list of atoms. + + Only variables or `{:atom, value}` tuples are allowed in the `bindings` list, + otherwise an `Ecto.Query.CompileError` is raised. + + ## Examples + + iex> escape_binding(%Ecto.Query{}, quote(do: [x, y, z]), __ENV__) + {%Ecto.Query{}, [x: 0, y: 1, z: 2]} + + iex> escape_binding(%Ecto.Query{}, quote(do: [{x, 0}, {z, 2}]), __ENV__) + {%Ecto.Query{}, [x: 0, z: 2]} + + iex> escape_binding(%Ecto.Query{}, quote(do: [x, y, x]), __ENV__) + ** (Ecto.Query.CompileError) variable `x` is bound twice + + iex> escape_binding(%Ecto.Query{}, quote(do: [a, b, :foo]), __ENV__) + ** (Ecto.Query.CompileError) binding list should contain only variables or `{as, var}` tuples, got: :foo + + """ + @spec escape_binding(Macro.t(), list, Macro.Env.t()) :: {Macro.t(), Keyword.t()} + def escape_binding(query, binding, _env) when is_list(binding) do + vars = binding |> Enum.with_index() |> Enum.map(&escape_bind/1) + assert_no_duplicate_binding!(vars) + + {positional_vars, named_vars} = Enum.split_while(vars, &(not named_bind?(&1))) + assert_named_binds_in_tail!(named_vars, binding) + + {query, positional_binds} = calculate_positional_binds(query, positional_vars) + {query, named_binds} = calculate_named_binds(query, named_vars) + {query, positional_binds ++ named_binds} + end + + def escape_binding(_query, bind, _env) do + error!( + "binding should be list of variables and `{as, var}` tuples " <> + "at the end, got: #{Macro.to_string(bind)}" + ) + end + + defp named_bind?({kind, _, _}), do: kind == :named + + defp assert_named_binds_in_tail!(named_vars, binding) do + if Enum.all?(named_vars, &named_bind?/1) do + :ok + else + error!( + "named binds in the form of `{as, var}` tuples must be at the end " <> + "of the binding list, got: #{Macro.to_string(binding)}" + ) + end + end + + defp assert_no_duplicate_binding!(vars) do + bound_vars = for {_, var, _} <- vars, var != :_, do: var + + case bound_vars -- Enum.uniq(bound_vars) do + [] -> :ok + [var | _] -> error!("variable `#{var}` is bound twice") + end + end + + defp calculate_positional_binds(query, vars) do + case Enum.split_while(vars, &(elem(&1, 1) != :...)) do + {vars, []} -> + vars = for {:pos, var, count} <- vars, do: {var, count} + {query, vars} + + {vars, [_ | tail]} -> + query = + quote do + query = Ecto.Queryable.to_query(unquote(query)) + escape_count = Ecto.Query.Builder.count_binds(query) + query + end + + tail = + tail + |> Enum.with_index(-length(tail)) + |> Enum.map(fn {{:pos, k, _}, count} -> + {k, quote(do: escape_count + unquote(count))} + end) + + vars = for {:pos, var, count} <- vars, do: {var, count} + {query, vars ++ tail} + end + end + + defp calculate_named_binds(query, []), do: {query, []} + + defp calculate_named_binds(query, vars) do + assignments = + for {:named, key, name} <- vars do + quote do + unquote({key, [], __MODULE__}) = unquote(__MODULE__).count_alias!(query, unquote(name)) + end + end + + query = + quote do + query = Ecto.Queryable.to_query(unquote(query)) + unquote_splicing(assignments) + query + end + + pairs = + for {:named, key, _name} <- vars do + {key, {key, [], __MODULE__}} + end + + {query, pairs} + end + + @doc """ + Count the alias for the given query. + """ + def count_alias!(%{aliases: aliases} = query, name) do + case aliases do + %{^name => ix} -> + ix + + %{} -> + raise Ecto.QueryError, message: "unknown bind name `#{inspect(name)}`", query: query + end + end + + defp escape_bind({{:..., _, _context}, ix}), + do: {:pos, :..., ix} + + defp escape_bind({{var, _, context}, ix}) when is_atom(var) and is_atom(context), + do: {:pos, var, ix} + + defp escape_bind({{{var, _, context}, ix}, _}) when is_atom(var) and is_atom(context), + do: {:pos, var, ix} + + defp escape_bind({{name, {var, _, context}}, _ix}) + when is_atom(name) and is_atom(var) and is_atom(context), + do: {:named, var, name} + + defp escape_bind({{{:^, _, [expr]}, {var, _, context}}, _ix}) + when is_atom(var) and is_atom(context), + do: {:named, var, expr} + + defp escape_bind({bind, _ix}), + do: + error!( + "binding list should contain only variables or " <> + "`{as, var}` tuples, got: #{Macro.to_string(bind)}" + ) + + defp try_expansion(expr, type, params, vars, %Macro.Env{} = env) do + try_expansion(expr, type, params, vars, {env, &escape/5}) + end + + defp try_expansion(expr, type, params, vars, {env, fun}) do + case Macro.expand_once(expr, env) do + ^expr -> + error!(""" + `#{Macro.to_string(expr)}` is not a valid query expression. + + * If you intended to call an Elixir function or introduce a value, + you need to explicitly interpolate it with ^ + + * If you intended to call a database function, please check the documentation + for Ecto.Query.API to see the supported database expressions + + * If you intended to extend Ecto's query DSL, make sure that you have required + the module or imported the relevant function. Note that you need macros to + extend Ecto's querying capabilities + """) + + expanded -> + fun.(expanded, type, params, vars, env) + end + end + + @doc """ + Finds the index value for the given var in vars or raises. + """ + def find_var!(var, vars) do + vars[var] || + error!( + "unbound variable `#{var}` in query. If you are attempting to interpolate a value, use ^var" + ) + end + + @doc """ + Checks if the field is an atom at compilation time or + delegates the check to runtime for interpolation. + """ + def quoted_atom!({:^, _, [expr]}, used_ref), + do: quote(do: Ecto.Query.Builder.atom!(unquote(expr), unquote(used_ref))) + + def quoted_atom!(atom, _used_ref) when is_atom(atom), + do: atom + + def quoted_atom!(other, used_ref), + do: + error!( + "expected literal atom or interpolated value in #{used_ref}, got: " <> + "`#{Macro.to_string(other)}`" + ) + + @doc """ + Called by escaper at runtime to verify that value is an atom. + """ + def atom!(atom, _used_ref) when is_atom(atom), + do: atom + + def atom!(other, used_ref), + do: error!("expected atom in #{used_ref}, got: `#{inspect(other)}`") + + @doc """ + Checks if the value of a late binding is an interpolation or + a quoted atom. + """ + def late_binding!(kind, value) do + case value do + {:^, _, [value]} -> + value + + other -> + quoted_atom!(other, "#{kind}/1") + end + end + + defp escape_json_path(path) when is_list(path) do + Enum.map(path, "ed_json_path_element!/1) + end + + defp escape_json_path({:^, _, [path]}) do + quote do + path = Ecto.Query.Builder.json_path!(unquote(path)) + Enum.map(path, &Ecto.Query.Builder.json_path_element!/1) + end + end + + defp escape_json_path(other) do + error!( + "expected JSON path to be a literal list or interpolated value, got: `#{Macro.to_string(other)}`" + ) + end + + defp quoted_json_path_element!({:^, _, [expr]}), + do: quote(do: Ecto.Query.Builder.json_path_element!(unquote(expr))) + + defp quoted_json_path_element!(binary) when is_binary(binary), + do: binary + + defp quoted_json_path_element!(integer) when is_integer(integer), + do: integer + + defp quoted_json_path_element!(other), + do: + error!( + "expected JSON path to contain literal strings, literal integers, or interpolated values, got: " <> + "`#{Macro.to_string(other)}`" + ) + + @doc """ + Called by escaper at runtime to verify that value is a string or an integer. + """ + def json_path_element!(binary) when is_binary(binary), + do: binary + + def json_path_element!(integer) when is_integer(integer), + do: integer + + def json_path_element!(other), + do: error!("expected string or integer in json_extract_path/2, got: `#{inspect(other)}`") + + @doc """ + Called by escaper at runtime to verify that path is a list + """ + def json_path!(path) when is_list(path), + do: path + + def json_path!(path), + do: error!("expected `path` to be a list in json_extract_path/2, got: `#{inspect(path)}`") + + @doc """ + Called by escaper at runtime to verify that a value is not nil. + """ + def not_nil!(nil) do + raise ArgumentError, + "comparison with nil is forbidden as it is unsafe. " <> + "If you want to check if a value is nil, use is_nil/1 instead" + end + + def not_nil!(not_nil) do + not_nil + end + + @doc """ + Checks if the field is a valid interval at compilation time or + delegate the check to runtime for interpolation. + """ + def quoted_interval!({:^, _, [expr]}), + do: quote(do: Ecto.Query.Builder.interval!(unquote(expr))) + + def quoted_interval!(other), + do: interval!(other) + + @doc """ + Called by escaper at runtime to verify fragment keywords. + """ + def fragment!(kw) do + if Keyword.keyword?(kw) do + kw + else + raise ArgumentError, bad_fragment_message(inspect(kw)) + end + end + + @doc """ + Called by escaper at runtime to verify literal in fragments. + """ + def literal!(literal) do + if is_binary(literal) do + literal + else + raise ArgumentError, + "literal(^value) expects `value` to be a string, got `#{inspect(literal)}`" + end + end + + @doc """ + Called by escaper at runtime to verify splice in fragments. + """ + def splice!(value) do + if is_list(value) do + value + else + raise ArgumentError, + "splice(^value) expects `value` to be a list, got `#{inspect(value)}`" + end + end + + @doc """ + Called by escaper at runtime to verify that value is a valid interval. + """ + @interval ~w(year month week day hour minute second millisecond microsecond) + def interval!(interval) when interval in @interval, + do: interval + + def interval!(other_string) when is_binary(other_string), + do: + error!( + "invalid interval: `#{inspect(other_string)}` (expected one of #{Enum.join(@interval, ", ")})" + ) + + def interval!(not_string), + do: error!("invalid interval: `#{inspect(not_string)}` (expected a string)") + + @doc """ + Negates the given number. + """ + def negate!(%Decimal{} = decimal), do: Decimal.negate(decimal) + def negate!(number) when is_number(number), do: -number + + @doc """ + Returns the type of an expression at build time. + """ + @spec quoted_type(Macro.t(), Keyword.t()) :: quoted_type + + # Fields + def quoted_type({{:., _, [{var, _, context}, field]}, _, []}, vars) + when is_atom(var) and is_atom(context) and is_atom(field), + do: {find_var!(var, vars), field} + + def quoted_type({{:., _, [{kind, _, [value]}, field]}, _, []}, _vars) + when kind in [:as, :parent_as] do + value = late_binding!(kind, value) + {{:{}, [], [kind, [], [value]]}, field} + end + + def quoted_type({:field, _, [{var, _, context}, field]}, vars) + when is_atom(var) and is_atom(context) and is_atom(field), + do: {find_var!(var, vars), field} + + def quoted_type({:field, _, [{kind, _, [value]}, field]}, _vars) + when kind in [:as, :parent_as] and is_atom(field) do + value = late_binding!(kind, value) + {{:{}, [], [kind, [], [value]]}, field} + end + + # Unquoting code here means the second argument of field will + # always be unquoted twice, one by the type checking and another + # in the query itself. We are assuming this is not an issue + # as the solution is somewhat complicated. + def quoted_type({:field, _, [{var, _, context}, {:^, _, [code]}]}, vars) + when is_atom(var) and is_atom(context), + do: {find_var!(var, vars), code} + + def quoted_type({:field, _, [{kind, _, [value]}, {:^, _, [code]}]}, _vars) + when kind in [:as, :parent_as] do + value = late_binding!(kind, value) + {{:{}, [], [kind, [], [value]]}, code} + end + + # Interval + def quoted_type({:datetime_add, _, [_, _, _]}, _vars), do: :naive_datetime + def quoted_type({:date_add, _, [_, _, _]}, _vars), do: :date + + # Tagged + def quoted_type({:<<>>, _, _}, _vars), do: :binary + def quoted_type({:type, _, [_, type]}, _vars), do: type + + # Sigils + def quoted_type({sigil, _, [_, []]}, _vars) when sigil in ~w(sigil_s sigil_S)a, do: :string + + def quoted_type({sigil, _, [_, []]}, _vars) when sigil in ~w(sigil_w sigil_W)a, + do: {:array, :string} + + # Lists + def quoted_type(list, vars) when is_list(list) do + case list |> Enum.map("ed_type(&1, vars)) |> Enum.uniq() do + [type] -> {:array, type} + _ -> {:array, :any} + end + end + + # Negative numbers + def quoted_type({:-, _, [number]}, _vars) when is_integer(number), do: :integer + def quoted_type({:-, _, [number]}, _vars) when is_float(number), do: :float + + # Dynamic aggregates + for {agg, arity} <- @dynamic_aggregates do + args = 1..arity |> Enum.map(fn _ -> Macro.var(:_, __MODULE__) end) |> tl() + + def quoted_type({unquote(agg), _, [expr, unquote_splicing(args)]}, vars) do + quoted_type(expr, vars) + end + end + + # Literals + def quoted_type(literal, _vars) when is_float(literal), do: :float + def quoted_type(literal, _vars) when is_binary(literal), do: :string + def quoted_type(literal, _vars) when is_boolean(literal), do: :boolean + def quoted_type(literal, _vars) when is_atom(literal) and not is_nil(literal), do: :atom + def quoted_type(literal, _vars) when is_integer(literal), do: :integer + + # Tuples + def quoted_type({left, right}, vars), do: quoted_type({:{}, [], [left, right]}, vars) + def quoted_type({:{}, _, elems}, vars), do: {:tuple, Enum.map(elems, "ed_type(&1, vars))} + + def quoted_type({name, _, args}, _vars) when is_atom(name) and is_list(args) do + case call_type(name, length(args)) do + {_in, out} -> out + nil -> :any + end + end + + def quoted_type(_, _vars), do: :any + + defp get_env({env, _}), do: env + defp get_env(env), do: env + + defp normalize_type(value, :binary), + do: quote(do: (is_binary(unquote(value)) && :binary) || :bitstring) + + @doc """ + Raises a query building error. + """ + def error!(message) when is_binary(message) do + {:current_stacktrace, [_ | t]} = Process.info(self(), :current_stacktrace) + + t = + Enum.drop_while(t, fn + {mod, _, _, _} -> + String.starts_with?(Atom.to_string(mod), ["Elixir.Ecto.Query.", "Elixir.Enum"]) + + _ -> + false + end) + + reraise Ecto.Query.CompileError, [message: message], t + end + + @doc """ + Counts the bindings in a query expression. + + ## Examples + + iex> count_binds(%Ecto.Query{joins: [1,2,3]}) + 4 + + """ + @spec count_binds(Ecto.Query.t()) :: non_neg_integer + def count_binds(%Query{joins: joins}) do + 1 + length(joins) + end + + @doc """ + Bump interpolations by the length of parameters. + """ + def bump_interpolations(expr, []), do: expr + + def bump_interpolations(expr, params) do + len = length(params) + + Macro.prewalk(expr, fn + {:^, meta, [counter]} when is_integer(counter) -> {:^, meta, [len + counter]} + other -> other + end) + end + + @doc """ + Bump subqueries by the count of pre-existing subqueries. + """ + def bump_subqueries(expr, []), do: expr + + def bump_subqueries(expr, subqueries) do + len = length(subqueries) + + Macro.prewalk(expr, fn + {:subquery, counter} -> {:subquery, len + counter} + other -> other + end) + end + + @doc """ + Called by the select escaper at compile time and dynamic builder at runtime to track select aliases + """ + def add_select_alias(aliases, name) when is_map(aliases) and is_atom(name) do + case aliases do + %{^name => _} -> + error!( + "the alias `#{inspect(name)}` has been specified more than once using `selected_as/2`" + ) + + aliases -> + Map.put(aliases, name, @select_alias_dummy_value) + end + end + + def add_select_alias(aliases, name) do + aliases = + case aliases do + %{} -> Macro.escape(aliases) + aliases -> aliases + end + + quote do: Ecto.Query.Builder.add_select_alias(unquote(aliases), unquote(name)) + end + + @doc """ + Applies a query at compilation time or at runtime. + + This function is responsible for checking if a given query is an + `Ecto.Query` struct at compile time. If it is not it will act + accordingly. + + If a query is available, it invokes the `apply` function in the + given `module`, otherwise, it delegates the call to runtime. + + It is important to keep in mind the complexities introduced + by this function. In particular, a %Query{} is a mixture of escaped + and unescaped expressions which makes it impossible for this + function to properly escape or unescape it at compile/runtime. + For this reason, the apply function should be ready to handle + arguments in both escaped and unescaped form. + + For example, take into account the `Builder.OrderBy`: + + select = %Ecto.Query.QueryExpr{expr: expr, file: env.file, line: env.line} + Builder.apply_query(query, __MODULE__, [order_by], env) + + `expr` is already an escaped expression and we must not escape + it again. However, it is wrapped in an Ecto.Query.QueryExpr, + which must be escaped! Furthermore, the `apply/2` function + in `Builder.OrderBy` very likely will inject the QueryExpr inside + Query, which again, is a mixture of escaped and unescaped expressions. + + That said, you need to obey the following rules: + + 1. In order to call this function, the arguments must be escapable + values supported by the `escape/1` function below; + + 2. The apply function may not manipulate the given arguments, + with exception to the query. + + In particular, when invoked at compilation time, all arguments + (except the query) will be escaped, so they can be injected into + the query properly, but they will be in their runtime form + when invoked at runtime. + """ + @spec apply_query(Macro.t(), Macro.t(), Macro.t(), Macro.Env.t()) :: Macro.t() + def apply_query(query, module, args, env) do + case Macro.expand(query, env) |> unescape_query() do + %Query{} = compiletime_query -> + apply(module, :apply, [compiletime_query | args]) + |> escape_query() + + runtime_query -> + quote do + # Unquote the query before `module.apply()` for any binding variable. + query = unquote(runtime_query) + unquote(module).apply(query, unquote_splicing(args)) + end + end + end + + # Unescapes an `Ecto.Query` struct. + @spec unescape_query(Macro.t()) :: Query.t() | Macro.t() + defp unescape_query({:%, _, [Query, {:%{}, _, list}]}) do + struct(Query, list) + end + + defp unescape_query({:%{}, _, list} = ast) do + if List.keyfind(list, :__struct__, 0) == {:__struct__, Query} do + Map.new(list) + else + ast + end + end + + defp unescape_query(other) do + other + end + + # Escapes an `Ecto.Query` and associated structs. + @spec escape_query(Query.t()) :: Macro.t() + defp escape_query(%Query{} = query), do: {:%{}, [], Map.to_list(query)} + + defp parse_access_get({{:., _, [Access, :get]}, _, [left, right]}, acc) do + parse_access_get(left, [right | acc]) + end + + defp parse_access_get({{:., _, [{var, _, context}, field]}, _, []} = expr, acc) + when is_atom(var) and is_atom(context) and is_atom(field) do + {expr, acc} + end + + defp parse_access_get({{:., _, [{kind, _, [_]}, field]}, _, []} = expr, acc) + when kind in [:as, :parent_as] and is_atom(field) do + {expr, acc} + end +end diff --git a/deps/ecto/lib/ecto/query/builder/combination.ex b/deps/ecto/lib/ecto/query/builder/combination.ex new file mode 100644 index 0000000000000000000000000000000000000000..00f13068291ad3757119b340fc977073d2ac0a2b --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/combination.ex @@ -0,0 +1,36 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Combination do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(atom, Macro.t, Macro.t, Macro.Env.t) :: Macro.t + def build(kind, query, {:^, _, [expr]}, env) do + expr = quote do: Ecto.Queryable.to_query(unquote(expr)) + Builder.apply_query(query, __MODULE__, [[{kind, expr}]], env) + end + + def build(kind, _query, other, _env) do + Builder.error! "`#{Macro.to_string(other)}` is not a valid #{kind}. " <> + "#{kind} must always be an interpolated query, such as ^existing_query" + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t + def apply(%Ecto.Query{combinations: combinations} = query, value) do + %{query | combinations: combinations ++ value} + end + def apply(query, value) do + apply(Ecto.Queryable.to_query(query), value) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/cte.ex b/deps/ecto/lib/ecto/query/builder/cte.ex new file mode 100644 index 0000000000000000000000000000000000000000..a253fd292ff5e353b30f8af4b224fe9a77687a66 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/cte.ex @@ -0,0 +1,121 @@ +import Kernel, except: [apply: 3] + +defmodule Ecto.Query.Builder.CTE do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Escapes the CTE name. + + iex> escape(quote(do: "FOO"), __ENV__) + "FOO" + + """ + @spec escape(Macro.t, Macro.Env.t) :: Macro.t + def escape(name, _env) when is_bitstring(name), do: name + + def escape({:^, _, [expr]}, _env), do: expr + + def escape(expr, env) do + case Macro.expand_once(expr, env) do + ^expr -> + Builder.error! "`#{Macro.to_string(expr)}` is not a valid CTE name. " <> + "It must be a literal string or an interpolated variable." + + expr -> + escape(expr, env) + end + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t, Macro.t, Macro.t, nil | boolean(), nil | :all | :update_all | :delete_all , Macro.Env.t) :: Macro.t + def build(query, name, cte, materialized, operation, env) do + Builder.apply_query(query, __MODULE__, [escape(name, env), build_cte(name, cte, env), materialized, operation], env) + end + + @spec build_cte(Macro.t, Macro.t, Macro.Env.t) :: Macro.t + def build_cte(_name, {:^, _, [expr]}, _env) do + quote do: Ecto.Queryable.to_query(unquote(expr)) + end + + def build_cte(_name, {:fragment, _, _} = fragment, env) do + {expr, {params, _acc}} = Builder.escape(fragment, :any, {[], %{}}, [], env) + params = Builder.escape_params(params) + + quote do + %Ecto.Query.QueryExpr{ + expr: unquote(expr), + params: unquote(params), + file: unquote(env.file), + line: unquote(env.line) + } + end + end + + def build_cte(name, cte, env) do + case Macro.expand_once(cte, env) do + ^cte -> + Builder.error! "`#{Macro.to_string(cte)}` is not a valid CTE (named: #{Macro.to_string(name)}). " <> + "The CTE must be an interpolated query, such as ^existing_query or a fragment." + + cte -> + build_cte(name, cte, env) + end + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, bitstring, Ecto.Queryable.t, nil | boolean(), nil | :all | :update_all | :delete_all) :: Ecto.Query.t + # Runtime + def apply(query, name, with_query, materialized, nil) do + apply(query, name, with_query, materialized, :all) + end + + def apply(_query, _name, _with_query, _materialized, operation) + when operation not in [:all, :update_all, :delete_all] do + Builder.error!("`operation` option must be one of :all, :update_all, or :delete_all") + end + + def apply(%Ecto.Query{with_ctes: with_expr} = query, name, %_{} = with_query, materialized, operation) do + %{query | with_ctes: apply_cte(with_expr, name, with_query, materialized, operation)} + end + + # Compile + def apply(%Ecto.Query{with_ctes: with_expr} = query, name, with_query, materialized, operation) do + update = quote do + Ecto.Query.Builder.CTE.apply_cte(unquote(with_expr), unquote(name), unquote(with_query), unquote(materialized), unquote(operation)) + end + + %{query | with_ctes: update} + end + + # Runtime catch-all + def apply(query, name, with_query, materialized, operation) do + apply(Ecto.Queryable.to_query(query), name, with_query, materialized, operation) + end + + @doc false + def apply_cte(nil, name, with_query, materialized, operation) when is_boolean(materialized) do + %Ecto.Query.WithExpr{queries: [{name, %{materialized: materialized, operation: operation}, with_query}]} + end + + def apply_cte(nil, name, with_query, _materialized, operation) do + %Ecto.Query.WithExpr{queries: [{name, %{operation: operation}, with_query}]} + end + + def apply_cte(%Ecto.Query.WithExpr{queries: queries} = with_expr, name, with_query, materialized, operation) when is_boolean(materialized) do + %{with_expr | queries: List.keystore(queries, name, 0, {name, %{materialized: materialized, operation: operation}, with_query})} + end + + def apply_cte(%Ecto.Query.WithExpr{queries: queries} = with_expr, name, with_query, _materialized, operation) do + %{with_expr | queries: List.keystore(queries, name, 0, {name, %{operation: operation}, with_query})} + end +end diff --git a/deps/ecto/lib/ecto/query/builder/distinct.ex b/deps/ecto/lib/ecto/query/builder/distinct.ex new file mode 100644 index 0000000000000000000000000000000000000000..a919428190d48dc498119dcec618a54ab761f004 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/distinct.ex @@ -0,0 +1,91 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Distinct do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Escapes a list of quoted expressions. + + iex> escape(quote do true end, {[], %{}}, [], __ENV__) + {true, {[], %{}}} + + iex> escape(quote do [x.x, 13] end, {[], %{}}, [x: 0], __ENV__) + {[asc: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]}, + asc: 13], + {[], %{}}} + + """ + @spec escape(Macro.t, {list, term}, Keyword.t, Macro.Env.t) :: {Macro.t, {list, term}} + def escape(expr, params_acc, _vars, _env) when is_boolean(expr) do + {expr, params_acc} + end + + def escape(expr, params_acc, vars, env) do + Builder.OrderBy.escape(:distinct, expr, params_acc, vars, env) + end + + @doc """ + Called at runtime to verify distinct. + """ + def distinct!(query, distinct, file, line) when is_boolean(distinct) do + apply(query, %Ecto.Query.ByExpr{expr: distinct, params: [], line: line, file: file}) + end + def distinct!(query, distinct, file, line) do + {expr, params, subqueries} = + Builder.OrderBy.order_by_or_distinct!(:distinct, query, distinct, []) + + expr = %Ecto.Query.ByExpr{ + expr: expr, + params: Enum.reverse(params), + line: line, + file: file, + subqueries: subqueries + } + + apply(query, expr) + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t + def build(query, _binding, {:^, _, [var]}, env) do + quote do + Ecto.Query.Builder.Distinct.distinct!(unquote(query), unquote(var), unquote(env.file), unquote(env.line)) + end + end + + def build(query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {expr, {params, acc}} = escape(expr, {[], %{subqueries: []}}, binding, env) + params = Builder.escape_params(params) + + distinct = quote do: %Ecto.Query.ByExpr{ + expr: unquote(expr), + params: unquote(params), + subqueries: unquote(acc.subqueries), + file: unquote(env.file), + line: unquote(env.line)} + Builder.apply_query(query, __MODULE__, [distinct], env) + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t + def apply(%Ecto.Query{distinct: nil} = query, expr) do + %{query | distinct: expr} + end + def apply(%Ecto.Query{}, _expr) do + Builder.error! "only one distinct expression is allowed in query" + end + def apply(query, expr) do + apply(Ecto.Queryable.to_query(query), expr) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/dynamic.ex b/deps/ecto/lib/ecto/query/builder/dynamic.ex new file mode 100644 index 0000000000000000000000000000000000000000..32802a1131d2dbdec37de857db643c25b6245076 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/dynamic.ex @@ -0,0 +1,112 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Dynamic do + @moduledoc false + + alias Ecto.Query.Builder + alias Ecto.Query.Builder.Select + + @doc """ + Builds a dynamic expression. + """ + @spec build([Macro.t], Macro.t, Macro.Env.t) :: Macro.t + def build(binding, expr, env) do + {query, vars} = Builder.escape_binding(quote(do: query), binding, env) + {expr, {params, acc}} = escape(expr, {[], %{subqueries: [], aliases: %{}}}, vars, env) + aliases = escape_select_aliases(acc.aliases) + params = Builder.escape_params(params) + + quote do + %Ecto.Query.DynamicExpr{fun: fn query -> + _ = unquote(query) + {unquote(expr), unquote(params), unquote(Enum.reverse(acc.subqueries)), unquote(aliases)} + end, + binding: unquote(Macro.escape(binding)), + file: unquote(env.file), + line: unquote(env.line)} + end + end + + defp escape({:selected_as, _, [_, _]} = expr, _params_acc, vars, env) do + Select.escape(expr, vars, env) + end + + defp escape({:%{}, _, _} = expr, _params_acc, vars, env) do + Select.escape(expr, vars, env) + end + + defp escape(expr, params_acc, vars, env) do + Builder.escape(expr, :any, params_acc, vars, {env, &escape_expansion/5}) + end + + defp escape_expansion(expr, _type, params_acc, vars, env) do + escape(expr, params_acc, vars, env) + end + + defp escape_select_aliases(%{} = aliases), do: Builder.escape_select_aliases(aliases) + defp escape_select_aliases(aliases), do: aliases + + @doc """ + Expands a dynamic expression for insertion into the given query. + """ + def fully_expand(query, %{file: file, line: line, binding: binding} = dynamic) do + {expr, {binding, params, subqueries, _aliases, _count}} = expand(query, dynamic, {binding, [], [], %{}, 0}) + {expr, binding, Enum.reverse(params), Enum.reverse(subqueries), file, line} + end + + @doc """ + Expands a dynamic expression as part of an existing expression. + + Any dynamic expression parameter is prepended and the parameters + list is not reversed. This is useful when the dynamic expression + is given in the middle of an expression. + """ + def partially_expand(query, %{binding: binding} = dynamic, params, subqueries, aliases, count) do + {expr, {_binding, params, subqueries, aliases, count}} = + expand(query, dynamic, {binding, params, subqueries, aliases, count}) + + {expr, params, subqueries, aliases, count} + end + + def partially_expand(kind, query, %{binding: binding} = dynamic, params, count) do + {expr, {_binding, params, subqueries, _aliases, count}} = + expand(query, dynamic, {binding, params, [], %{}, count}) + + if subqueries != [] do + raise ArgumentError, "subqueries are not allowed in `#{kind}` expressions" + end + + {expr, params, count} + end + + defp expand(query, %{fun: fun}, {binding, params, subqueries, aliases, count}) do + {dynamic_expr, dynamic_params, dynamic_subqueries, dynamic_aliases} = fun.(query) + aliases = merge_aliases(aliases, dynamic_aliases) + + Macro.postwalk(dynamic_expr, {binding, params, subqueries, aliases, count}, fn + {:^, meta, [ix]}, {binding, params, subqueries, aliases, count} -> + case Enum.fetch!(dynamic_params, ix) do + {%Ecto.Query.DynamicExpr{binding: new_binding} = dynamic, _} -> + binding = if length(new_binding) > length(binding), do: new_binding, else: binding + expand(query, dynamic, {binding, params, subqueries, aliases, count}) + + param -> + {{:^, meta, [count]}, {binding, [param | params], subqueries, aliases, count + 1}} + end + + {:subquery, i}, {binding, params, subqueries, aliases, count} -> + subquery = Enum.fetch!(dynamic_subqueries, i) + ix = length(subqueries) + {{:subquery, ix}, {binding, [{:subquery, ix} | params], [subquery | subqueries], aliases, count + 1}} + + expr, acc -> + {expr, acc} + end) + end + + defp merge_aliases(old_aliases, new_aliases) do + Enum.reduce(new_aliases, old_aliases, fn {alias, _}, aliases -> + Builder.add_select_alias(aliases, alias) + end) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/filter.ex b/deps/ecto/lib/ecto/query/builder/filter.ex new file mode 100644 index 0000000000000000000000000000000000000000..12a374a76375b38c5a9d0aaeb1ce1a8dd993caaf --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/filter.ex @@ -0,0 +1,196 @@ +import Kernel, except: [apply: 3] + +defmodule Ecto.Query.Builder.Filter do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Escapes a where or having clause. + + It allows query expressions that evaluate to a boolean + or a keyword list of field names and values. In a keyword + list multiple key value pairs will be joined with "and". + + Returned is `{expression, {params, %{subqueries: subqueries}}}` which is + a valid escaped expression, see `Macro.escape/2`. Both `params` + and `subqueries` are reversed. + """ + @spec escape(:where | :having | :on, Macro.t, non_neg_integer, Keyword.t, Macro.Env.t) :: {Macro.t, {list, Builder.acc()}} + def escape(_kind, [], _binding, _vars, _env) do + {true, {[], %{subqueries: []}}} + end + + def escape(kind, expr, binding, vars, env) when is_list(expr) do + {parts, params_acc} = + Enum.map_reduce(expr, {[], %{subqueries: []}}, fn + {field, nil}, _params_acc -> + Builder.error! "nil given for `#{field}`. Comparison with nil is forbidden as it is unsafe. " <> + "Instead write a query with is_nil/1, for example: is_nil(s.#{field})" + + {field, value}, params_acc when is_atom(field) -> + value = check_for_nils(value, field) + {value, params_acc} = Builder.escape(value, {binding, field}, params_acc, vars, env) + {{:{}, [], [:==, [], [to_escaped_field(binding, field), value]]}, params_acc} + + _, _params_acc -> + Builder.error! "expected a keyword list at compile time in #{kind}, " <> + "got: `#{Macro.to_string expr}`. If you would like to " <> + "pass a list dynamically, please interpolate the whole list with ^" + end) + + expr = Enum.reduce parts, &{:{}, [], [:and, [], [&2, &1]]} + {expr, params_acc} + end + + def escape(_kind, expr, _binding, vars, env) do + Builder.escape(expr, :boolean, {[], %{subqueries: []}}, vars, env) + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(:where | :having, :and | :or, Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t + def build(kind, op, query, _binding, {:^, _, [var]}, env) do + quote do + Ecto.Query.Builder.Filter.filter!(unquote(kind), unquote(op), unquote(query), + unquote(var), 0, unquote(env.file), unquote(env.line)) + end + end + + def build(kind, op, query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {expr, {params, acc}} = escape(kind, expr, 0, binding, env) + + params = Builder.escape_params(params) + subqueries = Enum.reverse(acc.subqueries) + + expr = quote do: %Ecto.Query.BooleanExpr{ + expr: unquote(expr), + op: unquote(op), + params: unquote(params), + subqueries: unquote(subqueries), + file: unquote(env.file), + line: unquote(env.line)} + Builder.apply_query(query, __MODULE__, [kind, expr], env) + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, :where | :having, term) :: Ecto.Query.t + def apply(query, _, %{expr: true}) do + query + end + def apply(%Ecto.Query{wheres: wheres} = query, :where, expr) do + %{query | wheres: wheres ++ [expr]} + end + def apply(%Ecto.Query{havings: havings} = query, :having, expr) do + %{query | havings: havings ++ [expr]} + end + def apply(query, kind, expr) do + apply(Ecto.Queryable.to_query(query), kind, expr) + end + + @doc """ + Builds a filter based on the given arguments. + + This is shared by having, where and join's on expressions. + """ + def filter!(kind, query, %Ecto.Query.DynamicExpr{} = dynamic, _binding, _file, _line) do + {expr, _binding, params, subqueries, file, line} = + Ecto.Query.Builder.Dynamic.fully_expand(query, dynamic) + + if subqueries != [] do + raise ArgumentError, "subqueries are not allowed in `#{kind}` expressions" + end + + {expr, params, file, line} + end + + def filter!(_kind, _query, bool, _binding, file, line) when is_boolean(bool) do + {bool, [], file, line} + end + + def filter!(kind, _query, kw, binding, file, line) when is_list(kw) do + {expr, params} = kw!(kind, kw, binding) + {expr, params, file, line} + end + + def filter!(kind, _query, other, _binding, _file, _line) do + raise ArgumentError, "expected a keyword list or dynamic expression in `#{kind}`, got: `#{inspect other}`" + end + + @doc """ + Builds the filter and applies it to the given query as boolean operator. + """ + def filter!(:where, op, query, %Ecto.Query.DynamicExpr{} = dynamic, _binding, _file, _line) do + {expr, _binding, params, subqueries, file, line} = + Ecto.Query.Builder.Dynamic.fully_expand(query, dynamic) + + boolean = %Ecto.Query.BooleanExpr{ + expr: expr, + params: params, + line: line, + file: file, + op: op, + subqueries: subqueries + } + + apply(query, :where, boolean) + end + + def filter!(kind, op, query, expr, binding, file, line) do + {expr, params, file, line} = filter!(kind, query, expr, binding, file, line) + boolean = %Ecto.Query.BooleanExpr{expr: expr, params: params, line: line, file: file, op: op} + apply(query, kind, boolean) + end + + defp kw!(kind, kw, binding) do + case kw!(kw, binding, 0, [], [], kind, kw) do + {[], params} -> {true, params} + {parts, params} -> {Enum.reduce(parts, &{:and, [], [&2, &1]}), params} + end + end + + defp kw!([{field, nil}|_], _binding, _counter, _exprs, _params, _kind, _original) when is_atom(field) do + raise ArgumentError, "nil given for #{inspect field}. Comparison with nil is forbidden as it is unsafe. " <> + "Instead write a query with is_nil/1, for example: is_nil(s.#{field})" + end + defp kw!([{field, value}|t], binding, counter, exprs, params, kind, original) when is_atom(field) do + kw!(t, binding, counter + 1, + [{:==, [], [to_field(binding, field), {:^, [], [counter]}]}|exprs], + [{value, {binding, field}}|params], + kind, original) + end + defp kw!([], _binding, _counter, exprs, params, _kind, _original) do + {Enum.reverse(exprs), Enum.reverse(params)} + end + defp kw!(_, _binding, _counter, _exprs, _params, kind, original) do + raise ArgumentError, "expected a keyword list in `#{kind}`, got: `#{inspect original}`" + end + + defp to_field(binding, field), + do: {{:., [], [{:&, [], [binding]}, field]}, [], []} + defp to_escaped_field(binding, field), + do: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [binding]]}, field]]}, [], []]} + + defp check_for_nils({:^, _, [var]}, field) do + quote do + ^Ecto.Query.Builder.Filter.not_nil!(unquote(var), unquote(field)) + end + end + + defp check_for_nils(value, _field), do: value + + def not_nil!(nil, field) do + raise ArgumentError, "nil given for `#{field}`. comparison with nil is forbidden as it is unsafe. " <> + "Instead write a query with is_nil/1, for example: is_nil(s.#{field})" + end + + def not_nil!(other, _field), do: other +end diff --git a/deps/ecto/lib/ecto/query/builder/from.ex b/deps/ecto/lib/ecto/query/builder/from.ex new file mode 100644 index 0000000000000000000000000000000000000000..9622cd990bc36c85a4e484eaf1dc763e4377900d --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/from.ex @@ -0,0 +1,237 @@ +defmodule Ecto.Query.Builder.From do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Handles from expressions. + + The expressions may either contain an `in` expression or not. + The right side is always expected to Queryable. + + ## Examples + + iex> escape(quote(do: MySchema), __ENV__) + {MySchema, []} + + iex> escape(quote(do: p in posts), __ENV__) + {quote(do: posts), [p: 0]} + + iex> escape(quote(do: p in {"posts", MySchema}), __ENV__) + {{"posts", MySchema}, [p: 0]} + + iex> escape(quote(do: [p, q] in posts), __ENV__) + {quote(do: posts), [p: 0, q: 1]} + + iex> escape(quote(do: [_, _] in abc), __ENV__) + {quote(do: abc), [_: 0, _: 1]} + + iex> escape(quote(do: other), __ENV__) + {quote(do: other), []} + + iex> escape(quote(do: x() in other), __ENV__) + ** (Ecto.Query.CompileError) binding list should contain only variables or `{as, var}` tuples, got: x() + + """ + @spec escape(Macro.t(), Macro.Env.t()) :: {Macro.t(), Keyword.t()} + def escape({:in, _, [var, query]}, env) do + query = escape_source(query, env) + Builder.escape_binding(query, List.wrap(var), env) + end + + def escape(query, env) do + query = escape_source(query, env) + {query, []} + end + + defp escape_source(query, env) do + case Macro.expand_once(query, env) do + {:fragment, _, _} = fragment -> + {fragment, {params, _acc}} = Builder.escape(fragment, :any, {[], %{}}, [], env) + {fragment, Builder.escape_params(params)} + + {:values, _, [values_list, types]} -> + prelude = quote do: values = Ecto.Query.Values.new(unquote(values_list), unquote(types)) + types = quote do: values.types + num_rows = quote do: values.num_rows + params = quote do: Ecto.Query.Builder.escape_params(values.params) + {{:{}, [], [:values, [], [types, num_rows]]}, prelude, params} + + ^query -> + case query do + {left, right} -> {left, Macro.expand(right, env)} + _ -> query + end + + other -> + escape_source(other, env) + end + end + + @typep hints :: [String.t() | Macro.t()] + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t(), Macro.Env.t(), atom, {:ok, Ecto.Schema.prefix | nil} | nil, hints) :: + {Macro.t(), Keyword.t(), non_neg_integer | nil} + def build(query, env, as, prefix, hints) do + hints = Enum.map(hints, &hint!(&1)) + + prefix = case prefix do + nil -> nil + {:ok, prefix} when is_binary(prefix) or is_nil(prefix) -> {:ok, prefix} + {:ok, {:^, _, [prefix]}} -> {:ok, prefix} + {:ok, prefix} -> Builder.error!("`prefix` must be a compile time string or an interpolated value using ^, got: #{Macro.to_string(prefix)}") + end + + as = case as do + {:^, _, [as]} -> as + as when is_atom(as) -> as + as -> Builder.error!("`as` must be a compile time atom or an interpolated value using ^, got: #{Macro.to_string(as)}") + end + + {query, binds} = escape(query, env) + + case query do + schema when is_atom(schema) -> + # Get the source at runtime so no unnecessary compile time + # dependencies between modules are added + source = quote(do: unquote(schema).__schema__(:source)) + {:ok, prefix} = prefix || {:ok, quote(do: unquote(schema).__schema__(:prefix))} + {query(prefix, {source, schema}, [], as, hints, env.file, env.line), binds, 1} + + source when is_binary(source) -> + {:ok, prefix} = prefix || {:ok, nil} + # When a binary is used, there is no schema + {query(prefix, {source, nil}, [], as, hints, env.file, env.line), binds, 1} + + {source, schema} when is_binary(source) and is_atom(schema) -> + {:ok, prefix} = prefix || {:ok, quote(do: unquote(schema).__schema__(:prefix))} + {query(prefix, {source, schema}, [], as, hints, env.file, env.line), binds, 1} + + {{:{}, _, [:fragment, _, _]} = fragment, params} -> + {:ok, prefix} = prefix || {:ok, nil} + {query(prefix, fragment, params, as, hints, env.file, env.line), binds, 1} + + {{:{}, _, [:values, _, _]} = values, prelude, params} -> + {:ok, prefix} = prefix || {:ok, nil} + query = query(prefix, values, params, as, hints, env.file, env.line) + + quoted = + quote do + unquote(prelude) + unquote(query) + end + + {quoted, binds, 1} + + _other -> + quoted = + quote do + Ecto.Query.Builder.From.apply(unquote(query), unquote(length(binds)), unquote(as), unquote(prefix), unquote(hints)) + end + + {quoted, binds, nil} + end + end + + defp query(prefix, source, params, as, hints, file, line) do + aliases = if as, do: [{as, 0}], else: [] + from_fields = [source: source, params: params, as: as, prefix: prefix, hints: hints, file: file, line: line] + + query_fields = [ + from: {:%, [], [Ecto.Query.FromExpr, {:%{}, [], from_fields}]}, + aliases: {:%{}, [], aliases} + ] + + {:%, [], [Ecto.Query, {:%{}, [], query_fields}]} + end + + @doc """ + Validates hints at compile time and runtime + """ + def hint!(hint) when is_binary(hint), do: hint + + def hint!({:unsafe_fragment, _, [fragment]}) do + case fragment do + {:^, _, [value]} -> + quote do: Ecto.Query.Builder.From.hint!(unquote(value)) + + _ -> + Builder.error!( + "`unsafe_fragment/1` in `hints` expects an interpolated value, such as " <> + "unsafe_fragment(^value), got: `#{Macro.to_string(fragment)}`" + ) + end + end + + def hint!(other) do + Builder.error!( + "`hints` must be a compile time string, unsafe fragment of the form `unsafe_fragment(^...)`, " <> + "or list containing either, got: `#{Macro.to_string(other)}`" + ) + end + + @doc """ + The callback applied by `build/2` to build the query. + """ + @spec apply(Ecto.Queryable.t(), non_neg_integer, Macro.t(), {:ok, Ecto.Schema.prefix} | nil, hints) :: Ecto.Query.t() + def apply(query, binds, as, prefix, hints) do + query = + query + |> Ecto.Queryable.to_query() + |> maybe_apply_as(as) + |> maybe_apply_prefix(prefix) + |> maybe_apply_hints(hints) + + check_binds(query, binds) + query + end + + defp maybe_apply_as(query, nil), do: query + + defp maybe_apply_as(%{from: %{as: from_as}}, as) when not is_nil(from_as) do + Builder.error!( + "can't apply alias `#{inspect(as)}`, binding in `from` is already aliased to `#{inspect(from_as)}`" + ) + end + + defp maybe_apply_as(%{from: from, aliases: aliases} = query, as) do + if Map.has_key?(aliases, as) do + Builder.error!("alias `#{inspect(as)}` already exists") + else + %{query | aliases: Map.put(aliases, as, 0), from: %{from | as: as}} + end + end + + defp maybe_apply_prefix(query, nil), do: query + + defp maybe_apply_prefix(query, {:ok, prefix}) do + update_in query.from.prefix, fn + nil -> + prefix + + from_prefix -> + Builder.error!( + "can't apply prefix `#{inspect(prefix)}`, `from` is already prefixed to `#{inspect(from_prefix)}`" + ) + end + end + + defp maybe_apply_hints(query, []), do: query + defp maybe_apply_hints(query, hints), do: update_in(query.from.hints, &(&1 ++ hints)) + + defp check_binds(query, count) do + if count > 1 and count > Builder.count_binds(query) do + Builder.error!( + "`from` in query expression specified #{count} " <> + "binds but query contains #{Builder.count_binds(query)} binds" + ) + end + end +end diff --git a/deps/ecto/lib/ecto/query/builder/group_by.ex b/deps/ecto/lib/ecto/query/builder/group_by.ex new file mode 100644 index 0000000000000000000000000000000000000000..0965d111c60de6b8c060ee8a7e4505d65718d4e2 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/group_by.ex @@ -0,0 +1,118 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.GroupBy do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Escapes a list of quoted expressions. + + See `Ecto.Builder.escape/2`. + + iex> escape(:group_by, quote do [x.x, 13] end, {[], %{}}, [x: 0], __ENV__) + {[{:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]}, + 13], + {[], %{}}} + """ + @spec escape(:group_by | :partition_by, Macro.t, {list, term}, Keyword.t, Macro.Env.t) :: + {Macro.t, {list, term}} + def escape(kind, expr, params_acc, vars, env) do + expr + |> List.wrap + |> Enum.map_reduce(params_acc, &do_escape(&1, &2, kind, vars, env)) + end + + defp do_escape({:^, _, [expr]}, params_acc, kind, _vars, _env) do + {quote(do: Ecto.Query.Builder.GroupBy.field!(unquote(kind), unquote(expr))), params_acc} + end + + defp do_escape(field, params_acc, _kind, _vars, _env) when is_atom(field) do + {Macro.escape(to_field(field)), params_acc} + end + + defp do_escape(expr, params_acc, _kind, vars, env) do + Builder.escape(expr, :any, params_acc, vars, env) + end + + @doc """ + Called at runtime to verify a field. + """ + def field!(_kind, field) when is_atom(field), + do: to_field(field) + def field!(kind, other) do + raise ArgumentError, + "expected a field as an atom in `#{kind}`, got: `#{inspect other}`" + end + + @doc """ + Shared between group_by and partition_by. + """ + def group_or_partition_by!(kind, query, exprs, params) do + {expr, {params, _, subqueries}} = + Enum.map_reduce(List.wrap(exprs), {params, length(params), []}, fn + field, params_count when is_atom(field) -> + {to_field(field), params_count} + + %Ecto.Query.DynamicExpr{} = dynamic, {params, count, subqueries} -> + {expr, params, subqueries, _aliases, count} = Builder.Dynamic.partially_expand(query, dynamic, params, subqueries, %{}, count) + {expr, {params, count, subqueries}} + + other, _params_count -> + raise ArgumentError, + "expected a list of fields and dynamics in `#{kind}`, got: `#{inspect other}`" + end) + + {expr, params, subqueries} + end + + defp to_field(field), do: {{:., [], [{:&, [], [0]}, field]}, [], []} + + @doc """ + Called at runtime to assemble group_by. + """ + def group_by!(query, group_by, file, line) do + {expr, params, subqueries} = group_or_partition_by!(:group_by, query, group_by, []) + expr = %Ecto.Query.ByExpr{expr: expr, params: Enum.reverse(params), line: line, file: file, subqueries: subqueries} + apply(query, expr) + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t + def build(query, _binding, {:^, _, [var]}, env) do + quote do + Ecto.Query.Builder.GroupBy.group_by!(unquote(query), unquote(var), unquote(env.file), unquote(env.line)) + end + end + + def build(query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {expr, {params, acc}} = escape(:group_by, expr, {[], %{subqueries: []}}, binding, env) + params = Builder.escape_params(params) + + group_by = quote do: %Ecto.Query.ByExpr{ + expr: unquote(expr), + params: unquote(params), + subqueries: unquote(acc.subqueries), + file: unquote(env.file), + line: unquote(env.line)} + Builder.apply_query(query, __MODULE__, [group_by], env) + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t + def apply(%Ecto.Query{group_bys: group_bys} = query, expr) do + %{query | group_bys: group_bys ++ [expr]} + end + def apply(query, expr) do + apply(Ecto.Queryable.to_query(query), expr) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/join.ex b/deps/ecto/lib/ecto/query/builder/join.ex new file mode 100644 index 0000000000000000000000000000000000000000..43de1cb09c9cb3e3370a9a93ba33e211141138bb --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/join.ex @@ -0,0 +1,360 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Join do + @moduledoc false + + alias Ecto.Query.Builder + alias Ecto.Query.{JoinExpr, QueryExpr} + + @doc """ + Escapes a join expression (not including the `on` expression). + + It returns a tuple containing the binds, the on expression (if available) + and the association expression. + + ## Examples + + iex> escape(quote(do: x in "foo"), [], __ENV__) + {:x, {"foo", nil}, nil, nil, []} + + iex> escape(quote(do: "foo"), [], __ENV__) + {:_, {"foo", nil}, nil, nil, []} + + iex> escape(quote(do: x in Sample), [], __ENV__) + {:x, {nil, Sample}, nil, nil, []} + + iex> escape(quote(do: x in __MODULE__), [], __ENV__) + {:x, {nil, __MODULE__}, nil, nil, []} + + iex> escape(quote(do: x in {"foo", :sample}), [], __ENV__) + {:x, {"foo", :sample}, nil, nil, []} + + iex> escape(quote(do: x in {"foo", Sample}), [], __ENV__) + {:x, {"foo", Sample}, nil, nil, []} + + iex> escape(quote(do: x in {"foo", __MODULE__}), [], __ENV__) + {:x, {"foo", __MODULE__}, nil, nil, []} + + iex> escape(quote(do: c in assoc(p, :comments)), [p: 0], __ENV__) + {:c, nil, {0, :comments}, nil, []} + + iex> escape(quote(do: x in fragment("foo")), [], __ENV__) + {:x, {:{}, [], [:fragment, [], [raw: "foo"]]}, nil, nil, []} + + """ + @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {atom, Macro.t | nil, Macro.t | nil, list} + def escape({:in, _, [{var, _, context}, expr]}, vars, env) + when is_atom(var) and is_atom(context) do + {_, expr, assoc, prelude, params} = escape(expr, vars, env) + {var, expr, assoc, prelude, params} + end + + def escape({:subquery, _, [expr]}, _vars, _env) do + {:_, quote(do: Ecto.Query.subquery(unquote(expr))), nil, nil, []} + end + + def escape({:subquery, _, [expr, opts]}, _vars, _env) do + {:_, quote(do: Ecto.Query.subquery(unquote(expr), unquote(opts))), nil, nil, []} + end + + def escape({:fragment, _, [_ | _]} = expr, vars, env) do + {expr, {params, _acc}} = Builder.escape(expr, :any, {[], %{}}, vars, env) + {:_, expr, nil, nil, params} + end + + def escape({:values, _, [values_list, types]}, _vars, _env) do + prelude = quote do: values = Ecto.Query.Values.new(unquote(values_list), unquote(types)) + types = quote do: values.types + num_rows = quote do: values.num_rows + params = quote do: values.params + {:_, {:{}, [], [:values, [], [types, num_rows]]}, nil, prelude, params} + end + + def escape({string, schema} = join, _vars, env) when is_binary(string) do + case Macro.expand(schema, env) do + schema when is_atom(schema) -> + {:_, {string, schema}, nil, nil, []} + + _ -> + Builder.error! "malformed join `#{Macro.to_string(join)}` in query expression" + end + end + + def escape({:assoc, _, [{var, _, context}, field]}, vars, _env) + when is_atom(var) and is_atom(context) do + ensure_field!(field) + var = Builder.find_var!(var, vars) + field = Builder.quoted_atom!(field, "field/2") + {:_, nil, {var, field}, nil, []} + end + + def escape({:^, _, [expr]}, _vars, _env) do + {:_, quote(do: Ecto.Query.Builder.Join.join!(unquote(expr))), nil, nil, []} + end + + def escape(string, _vars, _env) when is_binary(string) do + {:_, {string, nil}, nil, nil, []} + end + + def escape(schema, _vars, _env) when is_atom(schema) do + {:_, {nil, schema}, nil, nil, []} + end + + def escape(join, vars, env) do + case Macro.expand(join, env) do + ^join -> + Builder.error! "malformed join `#{Macro.to_string(join)}` in query expression" + join -> + escape(join, vars, env) + end + end + + @doc """ + Called at runtime to check dynamic joins. + """ + def join!(expr) when is_atom(expr), + do: {nil, expr} + def join!(expr) when is_binary(expr), + do: {expr, nil} + def join!({source, module}) when is_binary(source) and is_atom(module), + do: {source, module} + def join!(expr), + do: Ecto.Queryable.to_query(expr) + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @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) :: + {Macro.t, Keyword.t, non_neg_integer | nil} + def build(query, qual, binding, expr, count_bind, on, as, prefix, maybe_hints, env) do + {:ok, prefix} = prefix || {:ok, nil} + hints = List.wrap(maybe_hints) + + unless Enum.all?(hints, &is_binary/1) do + Builder.error!( + "`hints` must be a compile time string or list of strings, " <> + "got: `#{Macro.to_string(maybe_hints)}`" + ) + end + + prefix = case prefix do + nil -> nil + prefix when is_binary(prefix) -> prefix + {:^, _, [prefix]} -> prefix + prefix -> Builder.error!("`prefix` must be a compile time string or an interpolated value using ^, got: #{Macro.to_string(prefix)}") + end + + as = case as do + {:^, _, [as]} -> as + as when is_atom(as) -> as + as -> Builder.error!("`as` must be a compile time atom or an interpolated value using ^, got: #{Macro.to_string(as)}") + end + + {query, binding} = Builder.escape_binding(query, binding, env) + {join_bind, join_source, join_assoc, join_prelude, join_params} = escape(expr, binding, env) + join_params = escape_params(join_params) + + join_qual = validate_qual(qual) + validate_bind(join_bind, binding) + + {count_bind, query} = + if is_nil(count_bind) do + query = + quote do + query = Ecto.Queryable.to_query(unquote(query)) + join_count = Builder.count_binds(query) + query + end + {quote(do: join_count), query} + else + {count_bind, query} + end + + binding = binding ++ [{join_bind, count_bind}] + + next_bind = + if is_integer(count_bind) do + count_bind + 1 + else + quote(do: unquote(count_bind) + 1) + end + + join = [ + as: as, + assoc: join_assoc, + file: env.file, + line: env.line, + params: join_params, + prefix: prefix, + qual: join_qual, + source: join_source, + hints: hints + ] + + on = ensure_on(on, join_assoc, join_qual, join_source, env) + query = build_on(on, join_prelude, join, as, query, binding, count_bind, env) + {query, binding, next_bind} + end + + defp escape_params(params) when is_list(params) do + Builder.escape_params(params) + end + + defp escape_params(params) do + quote do: Builder.escape_params(unquote(params)) + end + + def build_on({:^, _, [var]}, join_prelude, join, as, query, _binding, count_bind, env) do + quote do + query = unquote(query) + unquote(join_prelude) + + Ecto.Query.Builder.Join.join!( + query, + %JoinExpr{unquote_splicing(join), on: %QueryExpr{}}, + unquote(var), + unquote(as), + unquote(count_bind), + unquote(env.file), + unquote(env.line) + ) + end + end + + def build_on(on, join_prelude, join, as, query, binding, count_bind, env) do + case Ecto.Query.Builder.Filter.escape(:on, on, count_bind, binding, env) do + {_on_expr, {_on_params, %{subqueries: [_ | _]}}} -> + raise ArgumentError, "invalid expression for join `:on`, subqueries aren't supported" + + {on_expr, {on_params, _acc}} -> + on_params = Builder.escape_params(on_params) + + join = + quote do + unquote(join_prelude) + + %JoinExpr{ + unquote_splicing(join), + on: %QueryExpr{ + expr: unquote(on_expr), + params: unquote(on_params), + line: unquote(env.line), + file: unquote(env.file) + } + } + end + + Builder.apply_query(query, __MODULE__, [join, as, count_bind], env) + end + end + + defp ensure_on(on, _assoc, _qual, _source, _env) when on != nil, do: on + + defp ensure_on(nil, _assoc = nil, qual, source, env) when qual not in [:cross, :cross_lateral] do + maybe_source = + with {source, alias} <- source, + source when source != nil <- source || alias do + " on #{inspect(source)}" + else + _ -> "" + end + + stacktrace = Macro.Env.stacktrace(env) + IO.warn("missing `:on` in join#{maybe_source}, defaulting to `on: true`.", stacktrace) + + true + end + + defp ensure_on(nil, _assoc, _qual, _source, _env), do: true + + @doc """ + Applies the join expression to the query. + """ + def apply(%Ecto.Query{joins: joins} = query, expr, nil, _count_bind) do + %{query | joins: joins ++ [expr]} + end + def apply(%Ecto.Query{joins: joins, aliases: aliases} = query, expr, as, count_bind) do + aliases = + case aliases do + %{} -> runtime_aliases(aliases, as, count_bind) + _ -> compile_aliases(aliases, as, count_bind) + end + + %{query | joins: joins ++ [expr], aliases: aliases} + end + def apply(query, expr, as, count_bind) do + apply(Ecto.Queryable.to_query(query), expr, as, count_bind) + end + + @doc """ + Called at runtime to build aliases. + """ + def runtime_aliases(aliases, nil, _), do: aliases + + def runtime_aliases(aliases, name, join_count) when is_integer(join_count) do + if Map.has_key?(aliases, name) do + Builder.error! "alias `#{inspect name}` already exists" + else + Map.put(aliases, name, join_count) + end + end + + defp compile_aliases({:%{}, meta, aliases}, name, join_count) + when is_atom(name) and is_integer(join_count) do + {:%{}, meta, aliases |> Map.new |> runtime_aliases(name, join_count) |> Map.to_list} + end + + defp compile_aliases(aliases, name, join_count) do + quote do + Ecto.Query.Builder.Join.runtime_aliases(unquote(aliases), unquote(name), unquote(join_count)) + end + end + + @doc """ + Called at runtime to build a join. + """ + def join!(query, join, expr, as, count_bind, file, line) do + # join without expanded :on is built and applied to the query, + # so that expansion of dynamic :on accounts for the new binding + {on_expr, on_params, on_file, on_line} = + Ecto.Query.Builder.Filter.filter!(:on, apply(query, join, as, count_bind), expr, count_bind, file, line) + + join = %{join | on: %QueryExpr{expr: on_expr, params: on_params, line: on_line, file: on_file}} + apply(query, join, as, count_bind) + end + + defp validate_qual(qual) when is_atom(qual) do + qual!(qual) + end + + defp validate_qual(qual) do + quote(do: Ecto.Query.Builder.Join.qual!(unquote(qual))) + end + + defp validate_bind(bind, all) do + if bind != :_ and bind in all do + Builder.error! "variable `#{bind}` is already defined in query" + end + end + + @qualifiers [:inner, :inner_lateral, :left, :left_lateral, :right, :full, :cross, :cross_lateral] + + @doc """ + Called at runtime to check dynamic qualifier. + """ + def qual!(qual) when qual in @qualifiers, do: qual + def qual!(qual) do + raise ArgumentError, + "invalid join qualifier `#{inspect qual}`, accepted qualifiers are: " <> + Enum.map_join(@qualifiers, ", ", &"`#{inspect &1}`") + end + + defp ensure_field!({var, _, _}) when var != :^ do + Builder.error! "you passed the variable `#{var}` to `assoc/2`. Did you mean to pass the atom `:#{var}`?" + end + defp ensure_field!(_), do: true +end diff --git a/deps/ecto/lib/ecto/query/builder/limit_offset.ex b/deps/ecto/lib/ecto/query/builder/limit_offset.ex new file mode 100644 index 0000000000000000000000000000000000000000..310d2a5f28a8718a6dc61de71113a99431053b9b --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/limit_offset.ex @@ -0,0 +1,111 @@ +import Kernel, except: [apply: 3] + +defmodule Ecto.Query.Builder.LimitOffset do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Validates `with_ties` at runtime. + """ + @spec with_ties!(any) :: boolean + def with_ties!(with_ties) when is_boolean(with_ties), do: with_ties + + def with_ties!(with_ties), + do: raise("`with_ties` expression must evaluate to a boolean at runtime, got: `#{inspect(with_ties)}`") + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(:limit | :with_ties | :offset, Macro.t(), [Macro.t()], Macro.t(), Macro.Env.t()) :: + Macro.t() + def build(type, query, binding, expr, env) do + {query, vars} = Builder.escape_binding(query, binding, env) + {expr, {params, _acc}} = escape(type, expr, {[], %{}}, vars, env) + params = Builder.escape_params(params) + quoted = build_quoted(type, expr, params, env) + + Builder.apply_query(query, __MODULE__, [type, quoted], env) + end + + defp escape(type, expr, params_acc, vars, env) when type in [:limit, :offset] do + Builder.escape(expr, :integer, params_acc, vars, env) + end + + defp escape(:with_ties, expr, params_acc, _vars, _env) when is_boolean(expr) do + {expr, params_acc} + end + + defp escape(:with_ties, {:^, _, [expr]}, params_acc, _vars, _env) do + {quote(do: Ecto.Query.Builder.LimitOffset.with_ties!(unquote(expr))), params_acc} + end + + defp escape(:with_ties, expr, _params_acc, _vars, _env) do + Builder.error!( + "`with_ties` expression must be a compile time boolean or an interpolated value using ^, got: `#{Macro.to_string(expr)}`" + ) + end + + defp build_quoted(:limit, expr, params, env) do + quote do: %Ecto.Query.LimitExpr{ + expr: unquote(expr), + params: unquote(params), + file: unquote(env.file), + line: unquote(env.line) + } + end + + defp build_quoted(:offset, expr, params, env) do + quote do: %Ecto.Query.QueryExpr{ + expr: unquote(expr), + params: unquote(params), + file: unquote(env.file), + line: unquote(env.line) + } + end + + defp build_quoted(:with_ties, expr, _params, _env), do: expr + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t(), :limit | :with_ties | :offset, term) :: Ecto.Query.t() + def apply(%Ecto.Query{} = query, :limit, expr) do + %{query | limit: expr} + end + + def apply(%Ecto.Query{limit: limit} = query, :with_ties, expr) do + %{query | limit: apply_limit(limit, expr)} + end + + def apply(%Ecto.Query{} = query, :offset, expr) do + %{query | offset: expr} + end + + def apply(query, kind, expr) do + apply(Ecto.Queryable.to_query(query), kind, expr) + end + + @doc """ + Applies the `with_ties` value to the `limit` struct. + """ + def apply_limit(nil, _with_ties) do + Builder.error!("`with_ties` can only be applied to queries containing a `limit`") + end + + # Runtime + def apply_limit(%_{} = limit, with_ties) do + %{limit | with_ties: with_ties} + end + + # Compile + def apply_limit(limit, with_ties) do + quote do + Ecto.Query.Builder.LimitOffset.apply_limit(unquote(limit), unquote(with_ties)) + end + end +end diff --git a/deps/ecto/lib/ecto/query/builder/lock.ex b/deps/ecto/lib/ecto/query/builder/lock.ex new file mode 100644 index 0000000000000000000000000000000000000000..ce990301e52701bd9a9ca5b97b9035d917bab844 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/lock.ex @@ -0,0 +1,59 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Lock do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Escapes the lock code. + + iex> escape(quote(do: "FOO"), [], __ENV__) + "FOO" + + """ + @spec escape(Macro.t(), Keyword.t, Macro.Env.t) :: Macro.t() + def escape(lock, _vars, _env) when is_binary(lock), do: lock + + def escape({:fragment, _, [_ | _]} = expr, vars, env) do + {expr, {params, _acc}} = Builder.escape(expr, :any, {[], %{}}, vars, env) + + if params != [] do + Builder.error!("value interpolation is not allowed in :lock") + end + + expr + end + + def escape(other, _, _) do + Builder.error!( + "`#{Macro.to_string(other)}` is not a valid lock. " <> + "For security reasons, a lock must always be a literal string or a fragment" + ) + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t(), Macro.t(), Macro.t(), Macro.Env.t()) :: Macro.t() + def build(query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + Builder.apply_query(query, __MODULE__, [escape(expr, binding, env)], env) + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t(), term) :: Ecto.Query.t() + def apply(%Ecto.Query{} = query, value) do + %{query | lock: value} + end + + def apply(query, value) do + apply(Ecto.Queryable.to_query(query), value) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/order_by.ex b/deps/ecto/lib/ecto/query/builder/order_by.ex new file mode 100644 index 0000000000000000000000000000000000000000..23b62e7ce0be8d9d9990b7d729013930ab21038d --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/order_by.ex @@ -0,0 +1,255 @@ +import Kernel, except: [apply: 3] + +defmodule Ecto.Query.Builder.OrderBy do + @moduledoc false + + alias Ecto.Query.Builder + + @directions [ + :asc, + :asc_nulls_last, + :asc_nulls_first, + :desc, + :desc_nulls_last, + :desc_nulls_first + ] + + @doc """ + Returns `true` if term is a valid order_by direction; otherwise returns `false`. + + ## Examples + + iex> valid_direction?(:asc) + true + + iex> valid_direction?(:desc) + true + + iex> valid_direction?(:invalid) + false + + """ + def valid_direction?(term), do: term in @directions + + @doc """ + Escapes an order by query. + + The query is escaped to a list of `{direction, expression}` + pairs at runtime. Escaping also validates direction is one of + `:asc`, `:asc_nulls_last`, `:asc_nulls_first`, `:desc`, + `:desc_nulls_last` or `:desc_nulls_first`. + + ## Examples + + iex> escape(:order_by, quote do [x.x, desc: 13] end, {[], %{}}, [x: 0], __ENV__) + {[asc: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]}, + desc: 13], + {[], %{}}} + + """ + @spec escape(:order_by | :distinct, Macro.t(), {list, term}, Keyword.t(), Macro.Env.t()) :: + {Macro.t(), {list, term}} + def escape(kind, expr, params_acc, vars, env) do + expr + |> Macro.expand_once(get_env(env)) + |> List.wrap() + |> Enum.map_reduce(params_acc, &do_escape(&1, &2, kind, vars, env)) + end + + defp do_escape({dir, {:^, _, [expr]}}, params_acc, kind, _vars, _env) do + {{quoted_dir!(kind, dir), + quote(do: Ecto.Query.Builder.OrderBy.field!(unquote(kind), unquote(expr)))}, params_acc} + end + + defp do_escape({:^, _, [expr]}, params_acc, kind, _vars, _env) do + {{:asc, quote(do: Ecto.Query.Builder.OrderBy.field!(unquote(kind), unquote(expr)))}, + params_acc} + end + + defp do_escape({dir, field}, params_acc, kind, _vars, _env) when is_atom(field) do + {{quoted_dir!(kind, dir), Macro.escape(to_field(field))}, params_acc} + end + + defp do_escape(field, params_acc, _kind, _vars, _env) when is_atom(field) do + {{:asc, Macro.escape(to_field(field))}, params_acc} + end + + defp do_escape({dir, expr}, params_acc, kind, vars, env) do + {ast, params_acc} = Builder.escape(expr, :any, params_acc, vars, env) + {{quoted_dir!(kind, dir), ast}, params_acc} + end + + defp do_escape(expr, params_acc, _kind, vars, env) do + {ast, params_acc} = Builder.escape(expr, :any, params_acc, vars, env) + {{:asc, ast}, params_acc} + end + + defp get_env({env, _}), do: env + defp get_env(env), do: env + + @doc """ + Checks the variable is a quoted direction at compilation time or + delegate the check to runtime for interpolation. + """ + def quoted_dir!(kind, {:^, _, [expr]}), + do: quote(do: Ecto.Query.Builder.OrderBy.dir!(unquote(kind), unquote(expr))) + + def quoted_dir!(_kind, dir) when dir in @directions, + do: dir + + def quoted_dir!(kind, other) do + Builder.error!( + "expected #{Enum.map_join(@directions, ", ", &inspect/1)} or interpolated value " <> + "in `#{kind}`, got: `#{inspect(other)}`" + ) + end + + @doc """ + Called at runtime to verify the direction. + """ + def dir!(_kind, dir) when dir in @directions, + do: dir + + def dir!(kind, other) do + raise ArgumentError, + "expected one of #{Enum.map_join(@directions, ", ", &inspect/1)} " <> + "in `#{kind}`, got: `#{inspect(other)}`" + end + + @doc """ + Called at runtime to verify a field. + """ + def field!(_kind, field) when is_atom(field) do + to_field(field) + end + + def field!(kind, %Ecto.Query.DynamicExpr{} = dynamic_expression) do + raise ArgumentError, + "expected a field as an atom in `#{kind}`, got: `#{inspect(dynamic_expression)}`. " <> + "To use dynamic expressions, you need to interpolate at root level, as in: " <> + "`^[asc: dynamic, desc: :id]`" + end + + def field!(kind, other) do + raise ArgumentError, "expected a field as an atom in `#{kind}`, got: `#{inspect(other)}`" + end + + defp to_field(field), do: {{:., [], [{:&, [], [0]}, field]}, [], []} + + @doc """ + Shared between order_by and distinct. + """ + def order_by_or_distinct!(kind, query, exprs, params) do + {expr, {params, _, subqueries}} = + Enum.map_reduce(List.wrap(exprs), {params, length(params), []}, fn + {dir, expr}, params_count when dir in @directions -> + {expr, params} = dynamic_or_field!(kind, expr, query, params_count) + {{dir, expr}, params} + + expr, params_count -> + {expr, params} = dynamic_or_field!(kind, expr, query, params_count) + {{:asc, expr}, params} + end) + + {expr, params, subqueries} + end + + @doc """ + Called at runtime to assemble order_by. + """ + def order_by!(query, exprs, op, file, line) do + {expr, params, subqueries} = order_by_or_distinct!(:order_by, query, exprs, []) + expr = %Ecto.Query.ByExpr{expr: expr, params: Enum.reverse(params), line: line, file: file, subqueries: subqueries} + apply(query, expr, op) + end + + defp dynamic_or_field!( + _kind, + %Ecto.Query.DynamicExpr{} = dynamic, + query, + {params, count, subqueries} + ) do + {expr, params, subqueries, _aliases, count} = + Ecto.Query.Builder.Dynamic.partially_expand( + query, + dynamic, + params, + subqueries, + %{}, + count + ) + + {expr, {params, count, subqueries}} + end + + defp dynamic_or_field!(_kind, field, _query, params_count) when is_atom(field) do + {to_field(field), params_count} + end + + defp dynamic_or_field!(kind, other, _query, _params_count) do + raise ArgumentError, + "`#{kind}` interpolated on root expects a field or a keyword list " <> + "with the direction as keys and fields or dynamics as values, got: `#{inspect(other)}`" + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t(), [Macro.t()], Macro.t(), :append | :prepend, Macro.Env.t()) :: Macro.t() + def build(query, _binding, {:^, _, [var]}, op, env) do + quote do + Ecto.Query.Builder.OrderBy.order_by!( + unquote(query), + unquote(var), + unquote(op), + unquote(env.file), + unquote(env.line) + ) + end + end + + def build(query, binding, expr, op, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {expr, {params, acc}} = escape(:order_by, expr, {[], %{subqueries: []}}, binding, env) + params = Builder.escape_params(params) + + order_by = + quote do: %Ecto.Query.ByExpr{ + expr: unquote(expr), + params: unquote(params), + subqueries: unquote(acc.subqueries), + file: unquote(env.file), + line: unquote(env.line) + } + + Builder.apply_query(query, __MODULE__, [order_by, op], env) + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t(), term, term) :: Ecto.Query.t() + def apply(%Ecto.Query{order_bys: orders} = query, expr, op) do + %{query | order_bys: update_order_bys(orders, expr, op)} + end + + def apply(query, expr, op) do + apply(Ecto.Queryable.to_query(query), expr, op) + end + + @doc """ + Updates the `order_bys` value for a query. + """ + def update_order_bys(orders, expr, :append), do: orders ++ [expr] + def update_order_bys(orders, expr, :prepend), do: [expr | orders] + + def update_order_bys(orders, expr, mode) do + quote do + Ecto.Query.Builder.OrderBy.update_order_bys(unquote(orders), unquote(expr), unquote(mode)) + end + end +end diff --git a/deps/ecto/lib/ecto/query/builder/preload.ex b/deps/ecto/lib/ecto/query/builder/preload.ex new file mode 100644 index 0000000000000000000000000000000000000000..4ae820997def69fa646fc73d832f7f46fc19d81b --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/preload.ex @@ -0,0 +1,322 @@ +import Kernel, except: [apply: 3] + +defmodule Ecto.Query.Builder.Preload do + @moduledoc false + alias Ecto.Query.Builder + + @doc """ + Escapes a preload. + + A preload may be an atom, a list of atoms or a keyword list + nested as a rose tree. + + iex> escape(:foo, []) + {[:foo], []} + + iex> escape([foo: :bar], []) + {[foo: [:bar]], []} + + iex> escape([:foo, :bar], []) + {[:foo, :bar], []} + + iex> escape([foo: [:bar, bar: :bat]], []) + {[foo: [:bar, bar: [:bat]]], []} + + iex> escape([foo: {:^, [], ["external"]}], []) + {[foo: "external"], []} + + iex> escape([foo: [:bar, {:^, [], ["external"]}], baz: :bat], []) + {[foo: [:bar, "external"], baz: [:bat]], []} + + iex> escape([foo: {:c, [], nil}], [c: 1]) + {[], [foo: {1, []}]} + + iex> escape([foo: {{:c, [], nil}, bar: {:l, [], nil}}], [c: 1, l: 2]) + {[], [foo: {1, [bar: {2, []}]}]} + + iex> escape([foo: {:c, [], nil}, bar: {:l, [], nil}], [c: 1, l: 2]) + {[], [foo: {1, []}, bar: {2, []}]} + + iex> escape([foo: {{:c, [], nil}, :bar}], [c: 1]) + {[foo: [:bar]], [foo: {1, []}]} + + iex> escape([foo: [bar: {:c, [], nil}]], [c: 1]) + ** (Ecto.Query.CompileError) cannot preload join association `:bar` with binding `c` because parent preload is not a join association + + """ + @spec escape(Macro.t, Keyword.t) :: {[Macro.t], [Macro.t]} + def escape(preloads, vars) do + {preloads, assocs} = escape(preloads, :both, [], [], vars) + {Enum.reverse(preloads), Enum.reverse(assocs)} + end + + defp escape(atom, _mode, preloads, assocs, _vars) when is_atom(atom) do + {[atom|preloads], assocs} + end + + defp escape(list, mode, preloads, assocs, vars) when is_list(list) do + Enum.reduce list, {preloads, assocs}, fn item, acc -> + escape_each(item, mode, acc, vars) + end + end + + defp escape({:^, _, [inner]}, _mode, preloads, assocs, _vars) do + {[inner|preloads], assocs} + end + + defp escape(other, _mode, _preloads, _assocs, _vars) do + Builder.error! "`#{Macro.to_string other}` is not a valid preload expression. " <> + "preload expects an atom, a list of atoms or a keyword list with " <> + "more preloads as values. Use ^ on the outermost preload to interpolate a value" + end + + defp escape_each({key, {:^, _, [inner]}}, _mode, {preloads, assocs}, _vars) do + key = escape_key(key) + {[{key, inner}|preloads], assocs} + end + + defp escape_each({key, {var, _, context}}, mode, {preloads, assocs}, vars) when is_atom(context) do + assert_assoc!(mode, key, var) + key = escape_key(key) + idx = Builder.find_var!(var, vars) + {preloads, [{key, {idx, []}}|assocs]} + end + + defp escape_each({key, {{var, _, context}, list}}, mode, {preloads, assocs}, vars) when is_atom(context) do + assert_assoc!(mode, key, var) + key = escape_key(key) + idx = Builder.find_var!(var, vars) + {inner_preloads, inner_assocs} = escape(list, :assoc, [], [], vars) + assocs = [{key, {idx, Enum.reverse(inner_assocs)}}|assocs] + + case inner_preloads do + [] -> {preloads, assocs} + _ -> {[{key, Enum.reverse(inner_preloads)}|preloads], assocs} + end + end + + defp escape_each({key, list}, _mode, {preloads, assocs}, vars) do + key = escape_key(key) + {inner_preloads, []} = escape(list, :preload, [], [], vars) + {[{key, Enum.reverse(inner_preloads)}|preloads], assocs} + end + + defp escape_each(other, mode, {preloads, assocs}, vars) do + escape(other, mode, preloads, assocs, vars) + end + + defp escape_key(atom) when is_atom(atom) do + atom + end + + defp escape_key({:^, _, [expr]}) do + quote(do: Ecto.Query.Builder.Preload.key!(unquote(expr))) + end + + defp escape_key(other) do + Builder.error! "malformed key in preload `#{Macro.to_string(other)}` in query expression" + end + + @doc """ + Called at runtime to check dynamic preload keys. + """ + def key!(key) when is_atom(key), + do: key + def key!(key) do + raise ArgumentError, + "expected key in preload to be an atom, got: `#{inspect key}`" + end + + @doc """ + Applies the preloaded value into the query. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t + def build(query, _binding, {:^, _, [expr]}, _env) do + quote do + Ecto.Query.Builder.Preload.preload!(unquote(query), unquote(expr)) + end + end + + def build(query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {preloads, assocs} = escape(expr, binding) + Builder.apply_query(query, __MODULE__, [Enum.reverse(preloads), Enum.reverse(assocs)], env) + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, term, term) :: Ecto.Query.t + def apply(%Ecto.Query{preloads: p, assocs: a} = query, preloads, assocs) do + %{query | preloads: p ++ preloads, assocs: a ++ assocs} + end + def apply(query, preloads, assocs) do + apply(Ecto.Queryable.to_query(query), preloads, assocs) + end + + @doc """ + Called at runtime to assemble preload. + """ + def preload!(query, preload) do + {preloads, assocs} = expand(preload, query) + apply(query, preloads, assocs) + end + + @doc """ + Expands preloads at runtime. + + ## Examples + + iex> expand(:foo, []) + {[:foo], []} + + iex> expand([foo: :bar], []) + {[foo: :bar], []} + + iex> expand([:foo, :bar], []) + {[:foo, :bar], []} + + iex> expand([foo: [:bar, bar: :bat]], []) + {[foo: [:bar, bar: :bat]], []} + + iex> expand([:a, :b, c: [:d]], []) + {[:a, :b, c: [:d]], []} + + iex> expand([foo: ["external"]], []) + ** (ArgumentError) `"external"` is not a valid preload expression, expected an atom or a list. + + iex> require Ecto.Query + iex> expand([b: Ecto.Query.dynamic([_a, b], b)], Ecto.Query.from(a in "a", join: b in "b", on: true)) + {[], [b: {1, []}]} + + iex> require Ecto.Query + iex> expand( + ...> [b: {Ecto.Query.dynamic([_a, b], b), c: Ecto.Query.dynamic([_a, _b, c], c)}], + ...> Ecto.Query.from(a in "a", join: b in "b", on: true, join: c in "c", on: true) + ...> ) + {[], [b: {1, [c: {2, []}]}]} + """ + def expand(preloads, query) do + expand(preloads, query, :both, [], []) + end + + defp expand(atom, _query, _mode, preloads, assocs) when is_atom(atom) do + {[atom|preloads], assocs} + end + + defp expand(list, query, mode, preloads, assocs) when is_list(list) do + {preloads, assocs} = + Enum.reduce(list, {preloads, assocs}, fn item, acc -> + expand_each(item, query, mode, acc) + end) + + {Enum.reverse(preloads), Enum.reverse(assocs)} + end + + defp expand(other, _query, _mode, _preloads, _assocs) do + raise ArgumentError, + "`#{inspect(other)}` is not a valid preload expression, " <> + "expected an atom or a list." + end + + defp expand_each(atom, _query, _mode, {preloads, assocs}) when is_atom(atom) do + {[atom|preloads], assocs} + end + + defp expand_each({key, atom}, _query, _mode, {preloads, assocs}) when is_atom(atom) do + assert_key!(key) + + {[{key, atom}|preloads], assocs} + end + + defp expand_each({key, %Ecto.Query.DynamicExpr{} = dynamic}, query, mode, {preloads, assocs}) do + assert_key!(key) + assert_assoc!(mode, key) + + idx = expand_dynamic(dynamic, query) + {preloads, [{key, {idx, []}}|assocs]} + end + + defp expand_each({key, {%Ecto.Query.DynamicExpr{} = dynamic, inner}}, query, mode, {preloads, assocs}) do + assert_key!(key) + assert_assoc!(mode, key) + + idx = expand_dynamic(dynamic, query) + {inner_preloads, inner_assocs} = expand(inner, query, :assoc, [], []) + assocs = [{key, {idx, inner_assocs}}|assocs] + + case inner_preloads do + [] -> {preloads, assocs} + _ -> {[{key, inner_preloads}|preloads], assocs} + end + end + + defp expand_each({key, {query_or_fun, inner}}, query, _mode, {preloads, assocs}) do + assert_key!(key) + assert_query_or_fun!(query_or_fun, key) + + {inner_preloads, []} = expand(inner, query, :preload, [], []) + {[{key, {query_or_fun, inner_preloads}}|preloads], assocs} + end + + defp expand_each({key, list}, query, _mode, {preloads, assocs}) when is_list(list) do + assert_key!(key) + + {inner_preloads, []} = expand(list, query, :preload, [], []) + {[{key, inner_preloads}|preloads], assocs} + end + + defp expand_each({key, query_or_fun}, _query, _mode, {preloads, assocs}) do + assert_key!(key) + assert_query_or_fun!(query_or_fun, key) + + {[{key, query_or_fun}|preloads], assocs} + end + + defp expand_each(other, query, mode, {preloads, assocs}) do + expand(other, query, mode, preloads, assocs) + end + + defp expand_dynamic(%Ecto.Query.DynamicExpr{} = dynamic, query) do + case Builder.Dynamic.fully_expand(query, dynamic) do + {{:&, [], [idx]}, _, _, _, _, _} when is_integer(idx) -> + idx + + _ -> + raise ArgumentError, + "invalid dynamic in preload: `#{inspect(dynamic)}`. " <> + "Dynamic expressions in preload must evaluate to a single binding, as in: " <> + "`dynamic([comments: c], c)`" + end + end + + defp assert_key!(key), do: key!(key) && :ok + + defp assert_query_or_fun!(%Ecto.Query{}, _key), do: :ok + defp assert_query_or_fun!(fun, _key) when is_function(fun, 1), do: :ok + defp assert_query_or_fun!(other, key) do + raise ArgumentError, + "invalid preload for key `#{inspect(key)}`: #{inspect(other)}. " <> + "Preloads can be a query, a function (arity 1), or a dynamic that " <> + "evaluates to a single binding." + end + + defp assert_assoc!(mode, _atom) when mode in [:both, :assoc], do: :ok + defp assert_assoc!(_mode, atom) do + raise ArgumentError, + "cannot preload join association `#{inspect(atom)}` " <> + "because parent preload is not a join association" + end + + defp assert_assoc!(mode, _atom, _var) when mode in [:both, :assoc], do: :ok + defp assert_assoc!(_mode, atom, var) do + Builder.error!( + "cannot preload join association `#{Macro.to_string atom}` with binding `#{var}` " <> + "because parent preload is not a join association" + ) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/select.ex b/deps/ecto/lib/ecto/query/builder/select.ex new file mode 100644 index 0000000000000000000000000000000000000000..01c34ad33f0606e563d5ab0509e082511bd40724 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/select.ex @@ -0,0 +1,579 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Select do + @moduledoc false + + alias Ecto.Query.Builder + + @doc """ + Escapes a select. + + It allows tuples, lists and variables at the top level. Inside the + tuples and lists query expressions are allowed. + + ## Examples + + iex> escape({1, 2}, [], __ENV__) + {{:{}, [], [:{}, [], [1, 2]]}, {[], %{take: %{}, subqueries: [], aliases: %{}}}} + + iex> escape([1, 2], [], __ENV__) + {[1, 2], {[], %{take: %{}, subqueries: [], aliases: %{}}}} + + iex> escape(quote(do: x), [x: 0], __ENV__) + {{:{}, [], [:&, [], [0]]}, {[], %{take: %{}, subqueries: [], aliases: %{}}}} + + """ + @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {Macro.t, {list, %{take: map, subqueries: list}}} + def escape(atom, _vars, _env) + when is_atom(atom) and not is_boolean(atom) and atom != nil do + Builder.error! """ + #{inspect(atom)} is not a valid query expression, :select expects a query expression or a list of fields + """ + end + + def escape(other, vars, env) do + cond do + take?(other) -> + { + {:{}, [], [:&, [], [0]]}, + {[], %{take: %{0 => {:any, Macro.expand(other, env)}}, subqueries: [], aliases: %{}}} + } + + maybe_take?(other) -> + Builder.error! """ + Cannot mix fields with interpolations, such as: `select: [:foo, ^:bar, :baz]`. \ + Instead interpolate all fields at once, such as: `select: ^[:foo, :bar, :baz]`. \ + Got: #{Macro.to_string(other)}. + """ + + true -> + {expr, {params, acc}} = escape(other, {[], %{take: %{}, subqueries: [], aliases: %{}}}, vars, env) + acc = %{acc | subqueries: Enum.reverse(acc.subqueries)} + {expr, {params, acc}} + end + end + + # Tuple + defp escape({left, right}, params_acc, vars, env) do + escape({:{}, [], [left, right]}, params_acc, vars, env) + end + + # Tuple + defp escape({:{}, _, list}, params_acc, vars, env) do + {list, params_acc} = Enum.map_reduce(list, params_acc, &escape(&1, &2, vars, env)) + expr = {:{}, [], [:{}, [], list]} + {expr, params_acc} + end + + # Struct + defp escape({:%, _, [name, map]}, params_acc, vars, env) do + name = Macro.expand(name, env) + {escaped_map, params_acc} = escape(map, params_acc, vars, env) + {{:{}, [], [:%, [], [name, escaped_map]]}, params_acc} + end + + # Map + defp escape({:%{}, _, [{:|, _, [data, pairs]}]}, params_acc, vars, env) do + {escaped_data, params_acc} = escape(data, params_acc, vars, env) + {pairs, params_acc} = escape_pairs(pairs, data, params_acc, vars, env) + {{:{}, [], [:%{}, [], [{:{}, [], [:|, [], [escaped_data, pairs]]}]]}, params_acc} + end + + # Merge + defp escape({:merge, _, [left, {kind, _, _} = right]}, params_acc, vars, env) + when kind in [:%{}, :map] do + {left, params_acc} = escape(left, params_acc, vars, env) + {right, params_acc} = escape(right, params_acc, vars, env) + {{:{}, [], [:merge, [], [left, right]]}, params_acc} + end + + defp escape({:merge, _, [_left, right]}, _params_acc, _vars, _env) do + Builder.error! "expected the second argument of merge/2 in select to be a map, got: `#{Macro.to_string(right)}`" + end + + # Map + defp escape({:%{}, _, pairs}, params_acc, vars, env) do + {pairs, params_acc} = escape_pairs(pairs, nil, params_acc, vars, env) + {{:{}, [], [:%{}, [], pairs]}, params_acc} + end + + # List + defp escape(list, params_acc, vars, env) when is_list(list) do + Enum.map_reduce(list, params_acc, &escape(&1, &2, vars, env)) + end + + # map/struct(var, [:foo, :bar]) + defp escape({tag, _, [{var, _, context}, fields]}, {params, acc}, vars, env) + when tag in [:map, :struct] and is_atom(var) and is_atom(context) do + taken = escape_fields(fields, tag, env) + expr = Builder.escape_var!(var, vars) + acc = add_take(acc, Builder.find_var!(var, vars), {tag, taken}) + {expr, {params, acc}} + end + + # aliased values + defp escape({:selected_as, _, [expr, name]}, {params, acc}, vars, env) do + name = Builder.quoted_atom!(name, "selected_as/2") + {escaped, {params, acc}} = Builder.escape(expr, :any, {params, acc}, vars, env) + expr = {:{}, [], [:selected_as, [], [escaped, name]]} + aliases = Builder.add_select_alias(acc.aliases, name) + {expr, {params, %{acc | aliases: aliases}}} + end + + defp escape(expr, params_acc, vars, env) do + Builder.escape(expr, :any, params_acc, vars, {env, &escape_expansion/5}) + end + + defp escape_expansion(expr, _type, params_acc, vars, env) do + escape(expr, params_acc, vars, env) + end + + defp escape_pairs(pairs, update_data, params_acc, vars, env) do + Enum.map_reduce(pairs, params_acc, fn {k, v}, acc -> + v = tag_update_param(update_data, k, v) + {k, acc} = escape_key(k, acc, vars, env) + {v, acc} = escape(v, acc, vars, env) + {{k, v}, acc} + end) + end + + defp tag_update_param({var, _, context}, field, {:^, _,[_]} = param) when is_atom(var) and is_atom(context) do + {:type, [], [param, {{:., [], [{var, [], context}, field]}, [], []}]} + end + + defp tag_update_param(_, _, value), do: value + + defp escape_key(k, params_acc, _vars, _env) when is_atom(k) do + {k, params_acc} + end + + defp escape_key({:^, _, [k]}, params_acc, _vars, _env) do + checked = quote do: Ecto.Query.Builder.Select.map_key!(unquote(k)) + {checked, params_acc} + end + + defp escape_key(k, params_acc, vars, env) do + escape(k, params_acc, vars, env) + end + + defp escape_fields({:^, _, [interpolated]}, tag, _env) do + quote do + Ecto.Query.Builder.Select.fields!(unquote(tag), unquote(interpolated)) + end + end + defp escape_fields(expr, tag, env) do + case Macro.expand(expr, env) do + fields when is_list(fields) -> + fields + _ -> + Builder.error!( + "`#{tag}/2` in `select` expects either a literal or " <> + "an interpolated (1) list of atom fields, (2) dynamic, or " <> + "(3) map with dynamic values" + ) + end + end + + @doc """ + Called at runtime to verify a field. + """ + def fields!(tag, fields) do + if take?(fields) do + fields + else + raise ArgumentError, + "expected a list of fields in `#{tag}/2` inside `select`, got: `#{inspect fields}`" + end + end + + @doc """ + Called at runtime to verify a map key + """ + def map_key!(key) when is_binary(key), do: key + def map_key!(key) when is_integer(key), do: key + def map_key!(key) when is_float(key), do: key + def map_key!(key) when is_atom(key), do: key + + def map_key!(other) do + Builder.error!( + "interpolated map keys in `:select` can only be atoms, strings or numbers, got: #{inspect(other)}" + ) + end + + # atom list sigils + defp take?({name, _, [_, modifiers]}) when name in ~w(sigil_w sigil_W)a do + ?a in modifiers + end + + defp take?(fields) do + is_list(fields) and Enum.all?(fields, fn + {k, v} when is_atom(k) -> take?(List.wrap(v)) + k when is_atom(k) -> true + _ -> false + end) + end + + defp maybe_take?(fields) do + is_list(fields) and Enum.any?(fields, fn + {k, v} when is_atom(k) -> maybe_take?(List.wrap(v)) + k when is_atom(k) -> true + _ -> false + end) + end + + @doc """ + Called at runtime for interpolated/dynamic selects. + """ + def select!(kind, query, fields, file, line) when is_map(fields) do + {expr, {params, subqueries, aliases, _count}} = expand_nested(fields, {[], [], %{}, 0}, query) + + %Ecto.Query.SelectExpr{ + expr: expr, + params: Enum.reverse(params), + subqueries: Enum.reverse(subqueries), + aliases: aliases, + file: file, + line: line + } + |> apply_or_merge(kind, query) + end + + def select!(kind, query, fields, file, line) do + take = %{0 => {:any, fields!(:select, fields)}} + + %Ecto.Query.SelectExpr{expr: {:&, [], [0]}, take: take, file: file, line: line} + |> apply_or_merge(kind, query) + end + + defp apply_or_merge(select, kind, query) do + if kind == :select do + apply(query, select) + else + merge(query, select) + end + end + + defp expand_nested(%Ecto.Query.DynamicExpr{} = dynamic, {params, subqueries, aliases, count}, query) do + {expr, params, subqueries, aliases, count} = + Ecto.Query.Builder.Dynamic.partially_expand(query, dynamic, params, subqueries, aliases, count) + + {expr, {params, subqueries, aliases, count}} + end + + defp expand_nested(%Ecto.SubQuery{} = subquery, {params, subqueries, aliases, count}, _query) do + index = length(subqueries) + # used both in ast and in parameters, as a placeholder. + expr = {:subquery, index} + params = [expr | params] + subqueries = [subquery | subqueries] + count = count + 1 + + {expr, {params, subqueries, aliases, count}} + end + + defp expand_nested(%type{} = fields, acc, query) do + {fields, acc} = fields |> Map.from_struct() |> expand_nested(acc, query) + {{:%, [], [type, fields]}, acc} + end + + defp expand_nested(fields, acc, query) when is_map(fields) do + {fields, acc} = fields |> Enum.map_reduce(acc, &expand_nested_pair(&1, &2, query)) + {{:%{}, [], fields}, acc} + end + + defp expand_nested(invalid, _acc, query) when is_list(invalid) or is_tuple(invalid) do + raise Ecto.QueryError, + query: query, + message: + "Interpolated map values in :select can only be " <> + "maps, structs, dynamics, subqueries and literals. Got #{inspect(invalid)}" + end + + defp expand_nested(other, acc, _query) do + {other, acc} + end + + defp expand_nested_pair({key, val}, acc, query) do + {val, acc} = expand_nested(val, acc, query) + {{key, val}, acc} + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(:select | :merge, Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t + + def build(kind, query, _binding, {:^, _, [var]}, env) do + quote do + Ecto.Query.Builder.Select.select!(unquote(kind), unquote(query), unquote(var), + unquote(env.file), unquote(env.line)) + end + end + + def build(kind, query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {expr, {params, acc}} = escape(expr, binding, env) + params = Builder.escape_params(params) + take = {:%{}, [], Map.to_list(acc.take)} + aliases = escape_aliases(acc.aliases) + + select = quote do: %Ecto.Query.SelectExpr{ + expr: unquote(expr), + params: unquote(params), + file: unquote(env.file), + line: unquote(env.line), + take: unquote(take), + subqueries: unquote(acc.subqueries), + aliases: unquote(aliases)} + + if kind == :select do + Builder.apply_query(query, __MODULE__, [select], env) + else + quote do + query = unquote(query) + Builder.Select.merge(query, unquote(select)) + end + end + end + + defp escape_aliases(%{} = aliases), do: {:%{}, [], Map.to_list(aliases)} + defp escape_aliases(aliases), do: aliases + + @doc """ + The callback applied by `build/5` to build the query. + """ + @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t + def apply(%Ecto.Query{select: nil} = query, expr) do + %{query | select: expr} + end + def apply(%Ecto.Query{}, _expr) do + Builder.error! "only one select expression is allowed in query" + end + def apply(query, expr) do + apply(Ecto.Queryable.to_query(query), expr) + end + + @doc """ + The callback applied by `build/5` when merging. + """ + def merge(%Ecto.Query{select: nil} = query, new_select) do + merge(query, new_select, {:&, [], [0]}, [], [], %{}, %{}, new_select) + end + def merge(%Ecto.Query{select: old_select} = query, new_select) do + %{expr: old_expr, params: old_params, subqueries: old_subqueries, take: old_take, aliases: old_aliases} = old_select + merge(query, old_select, old_expr, old_params, old_subqueries, old_take, old_aliases, new_select) + end + def merge(query, expr) do + merge(Ecto.Queryable.to_query(query), expr) + end + + defp merge(query, select, old_expr, old_params, old_subqueries, old_take, old_aliases, new_select) do + %{expr: new_expr, params: new_params, subqueries: new_subqueries, take: new_take, aliases: new_aliases} = new_select + + new_expr = + new_expr + |> Ecto.Query.Builder.bump_interpolations(old_params) + |> Ecto.Query.Builder.bump_subqueries(old_subqueries) + + expr = + case {classify_merge(old_expr, old_take), classify_merge(new_expr, new_take)} do + {_, _} when old_expr == new_expr -> + new_expr + + {{:source, meta, ix}, {:source, _, ix}} -> + {:&, meta, [ix]} + + {{:struct, meta, name, old_fields}, {:map, _, new_fields}} when old_params == [] -> + cond do + new_fields == [] -> + old_expr + + Keyword.keyword?(old_fields) and Keyword.keyword?(new_fields) -> + {:%, meta, [name, {:%{}, meta, Keyword.merge(old_fields, new_fields)}]} + + true -> + {:merge, [], [old_expr, new_expr]} + end + + {{:map, meta, old_fields}, {:map, _, new_fields}} -> + cond do + old_fields == [] -> + new_expr + + new_fields == [] -> + old_expr + + true -> + require_distinct_keys? = old_params != [] + + case merge_map_fields(old_fields, new_fields, require_distinct_keys?) do + fields when is_list(fields) -> + {:%{}, meta, fields} + + :error -> + {:merge, [], [old_expr, new_expr]} + end + end + + {_, {:map, _, _}} -> + {:merge, [], [old_expr, new_expr]} + + {_, _} -> + message = """ + cannot select_merge #{merge_argument_to_error(new_expr, query)} into \ + #{merge_argument_to_error(old_expr, query)}, those select expressions \ + are incompatible. You can only select_merge: + + * a source (such as post) with another source (of the same type) + * a source (such as post) with a map + * a struct with a map + * a map with a map + + Incompatible merge found + """ + + raise Ecto.QueryError, query: query, message: message + end + + select = %{ + select | expr: expr, + params: old_params ++ bump_subquery_params(new_params, old_subqueries), + subqueries: old_subqueries ++ new_subqueries, + take: merge_take(query, old_expr, old_take, new_take), + aliases: merge_aliases(old_aliases, new_aliases) + } + + %{query | select: select} + end + + defp classify_merge({:&, meta, [ix]}, take) when is_integer(ix) do + case take do + %{^ix => {:map, _}} -> {:map, meta, :runtime} + _ -> {:source, meta, ix} + end + end + + defp classify_merge({:%, meta, [name, {:%{}, _, fields}]}, _take) + when fields == [] or tuple_size(hd(fields)) == 2 do + {:struct, meta, name, fields} + end + + defp classify_merge({:%{}, meta, fields}, _take) + when fields == [] or tuple_size(hd(fields)) == 2 do + {:map, meta, fields} + end + + defp classify_merge({:%{}, meta, _}, _take) do + {:map, meta, :runtime} + end + + defp classify_merge(_, _take) do + :error + end + + defp merge_map_fields(old_fields, new_fields, false) do + if Keyword.keyword?(old_fields) and Keyword.keyword?(new_fields) do + Keyword.merge(old_fields, new_fields) + else + :error + end + end + + defp merge_map_fields(old_fields, new_fields, true) when is_list(old_fields) do + if Keyword.keyword?(new_fields) do + valid? = + Enum.reduce_while(old_fields, true, fn + {k, _v}, _ when is_atom(k) -> + if Keyword.has_key?(new_fields, k), + do: {:halt, false}, + else: {:cont, true} + + _, _ -> + {:halt, false} + end) + + if valid?, do: old_fields ++ new_fields, else: :error + else + :error + end + end + + defp merge_map_fields(_, _, true), do: :error + + defp merge_argument_to_error({:&, _, [0]}, %{from: %{source: {source, alias}}}) do + "source #{inspect(source || alias)}" + end + + defp merge_argument_to_error({:&, _, [ix]}, _query) do + "join (at position #{ix})" + end + + defp merge_argument_to_error(other, _query) do + Macro.to_string(other) + end + + defp add_take(acc, key, value) do + take = Map.update(acc.take, key, value, &merge_take_kind_and_fields(key, &1, value)) + %{acc | take: take} + end + + defp bump_subquery_params(new_params, old_subqueries) do + len = length(old_subqueries) + + Enum.map(new_params, fn + {:subquery, counter} -> {:subquery, len + counter} + other -> other + end) + end + + defp merge_take(query, old_expr, %{} = old_take, %{} = new_take) do + Enum.reduce(new_take, old_take, fn {binding, {new_kind, new_fields} = new_value}, acc -> + case acc do + %{^binding => old_value} -> + Map.put(acc, binding, merge_take_kind_and_fields(binding, old_value, new_value)) + + %{} -> + # If merging with a schema, add the schema's query fields. This comes in handy if the user + # is merging fields with load_in_query = false. + # If merging with a schemaless source, do nothing so the planner can take all the fields. + case old_expr do + {:&, _, [^binding]} -> + source = Enum.at([query.from | query.joins], binding).source + + case source do + {_, schema} when schema != nil -> + Map.put(acc, binding, {new_kind, Enum.uniq(new_fields ++ schema.__schema__(:query_fields))}) + + _ -> + acc + end + + _ -> + Map.put(acc, binding, new_value) + end + end + end) + end + + defp merge_take_kind_and_fields(binding, {old_kind, old_fields}, {new_kind, new_fields}) do + {merge_take_kind(binding, old_kind, new_kind), Enum.uniq(old_fields ++ new_fields)} + end + + defp merge_take_kind(_, kind, kind), do: kind + defp merge_take_kind(_, :any, kind), do: kind + defp merge_take_kind(_, kind, :any), do: kind + defp merge_take_kind(binding, old, new) do + Builder.error! "cannot select_merge because the binding at position #{binding} " <> + "was previously specified as a `#{old}` and later as `#{new}`" + end + + defp merge_aliases(old_aliases, new_aliases) do + Enum.reduce(new_aliases, old_aliases, fn {alias, _}, aliases -> + Builder.add_select_alias(aliases, alias) + end) + end +end diff --git a/deps/ecto/lib/ecto/query/builder/update.ex b/deps/ecto/lib/ecto/query/builder/update.ex new file mode 100644 index 0000000000000000000000000000000000000000..29c0e69b18fbb175b81acee6f406e6a97e15de67 --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/update.ex @@ -0,0 +1,200 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Update do + @moduledoc false + + @keys [:set, :inc, :push, :pull] + alias Ecto.Query.Builder + + @doc """ + Escapes a list of quoted expressions. + + iex> escape([], [], __ENV__) + {[], [], []} + + iex> escape([set: []], [], __ENV__) + {[], [], []} + + iex> escape(quote(do: ^[set: []]), [], __ENV__) + {[], [set: []], []} + + iex> escape(quote(do: [set: ^[foo: 1]]), [], __ENV__) + {[], [set: [foo: 1]], []} + + iex> escape(quote(do: [set: [foo: ^1]]), [], __ENV__) + {[], [set: [foo: 1]], []} + + """ + @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {Macro.t, Macro.t, list} + def escape(expr, vars, env) when is_list(expr) do + escape_op(expr, [], [], [], vars, env) + end + + def escape({:^, _, [v]}, _vars, _env) do + {[], v, []} + end + + def escape(expr, _vars, _env) do + compile_error!(expr) + end + + defp escape_op([{k, v}|t], compile, runtime, params, vars, env) when is_atom(k) and is_list(v) do + validate_op!(k) + {compile_values, runtime_values, params} = escape_kw(k, v, params, vars, env) + compile = + if compile_values == [], do: compile, else: [{k, Enum.reverse(compile_values)} | compile] + runtime = + if runtime_values == [], do: runtime, else: [{k, Enum.reverse(runtime_values)} | runtime] + escape_op(t, compile, runtime, params, vars, env) + end + + defp escape_op([{k, {:^, _, [v]}}|t], compile, runtime, params, vars, env) when is_atom(k) do + validate_op!(k) + escape_op(t, compile, [{k, v}|runtime], params, vars, env) + end + + defp escape_op([], compile, runtime, params, _vars, _env) do + {Enum.reverse(compile), Enum.reverse(runtime), params} + end + + defp escape_op(expr, _compile, _runtime, _params, _vars, _env) do + compile_error!(expr) + end + + defp escape_kw(op, kw, params, vars, env) do + Enum.reduce kw, {[], [], params}, fn + {k, {:^, _, [v]}}, {compile, runtime, params} when is_atom(k) -> + {compile, [{k, v} | runtime], params} + {k, v}, {compile, runtime, params} -> + k = escape_field!(k) + {v, {params, _acc}} = Builder.escape(v, type_for_key(op, {0, k}), {params, %{}}, vars, env) + {[{k, v} | compile], runtime, params} + _, _acc -> + Builder.error! "malformed #{inspect op} in update `#{Macro.to_string(kw)}`, " <> + "expected a keyword list" + end + end + + defp escape_field!({:^, _, [k]}), do: quote(do: Ecto.Query.Builder.Update.field!(unquote(k))) + defp escape_field!(k) when is_atom(k), do: k + + defp escape_field!(k) do + Builder.error!( + "expected an atom field or an interpolated field in `update`, got `#{inspect(k)}`" + ) + end + + def field!(field) when is_atom(field), do: field + + def field!(other) do + raise ArgumentError, "expected a field as an atom in `update`, got: `#{inspect other}`" + end + + defp compile_error!(expr) do + Builder.error! "malformed update `#{Macro.to_string(expr)}` in query expression, " <> + "expected a keyword list with set/push/pull as keys with field-value " <> + "pairs as values" + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t + def build(query, binding, expr, env) do + {query, binding} = Builder.escape_binding(query, binding, env) + {compile, runtime, params} = escape(expr, binding, env) + + query = + if compile == [] do + query + else + params = Builder.escape_params(params) + + update = quote do + %Ecto.Query.QueryExpr{expr: unquote(compile), params: unquote(params), + file: unquote(env.file), line: unquote(env.line)} + end + + Builder.apply_query(query, __MODULE__, [update], env) + end + + if runtime == [] do + query + else + quote do + Ecto.Query.Builder.Update.update!(unquote(query), unquote(runtime), + unquote(env.file), unquote(env.line)) + end + end + end + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t + def apply(%Ecto.Query{updates: updates} = query, expr) do + %{query | updates: updates ++ [expr]} + end + def apply(query, expr) do + apply(Ecto.Queryable.to_query(query), expr) + end + + @doc """ + If there are interpolated updates at compile time, + we need to handle them at runtime. We do such in + this callback. + """ + def update!(query, runtime, file, line) when is_list(runtime) do + {runtime, {params, _count}} = + Enum.map_reduce runtime, {[], 0}, fn + {k, v}, acc when is_atom(k) and is_list(v) -> + validate_op!(k) + {v, params} = runtime_field!(query, k, v, acc) + {{k, v}, params} + _, _ -> + runtime_error!(runtime) + end + + expr = %Ecto.Query.QueryExpr{expr: runtime, params: Enum.reverse(params), + file: file, line: line} + + apply(query, expr) + end + + def update!(_query, runtime, _file, _line) do + runtime_error!(runtime) + end + + defp runtime_field!(query, key, kw, acc) do + Enum.map_reduce kw, acc, fn + {k, %Ecto.Query.DynamicExpr{} = v}, {params, count} when is_atom(k) -> + {v, params, count} = Ecto.Query.Builder.Dynamic.partially_expand(:update, query, v, params, count) + {{k, v}, {params, count}} + {k, v}, {params, count} when is_atom(k) -> + params = [{v, type_for_key(key, {0, k})} | params] + {{k, {:^, [], [count]}}, {params, count + 1}} + _, _acc -> + raise ArgumentError, "malformed #{inspect key} in update `#{inspect(kw)}`, " <> + "expected a keyword list" + end + end + + defp runtime_error!(value) do + raise ArgumentError, + "malformed update `#{inspect(value)}` in query expression, " <> + "expected a keyword list with set/push/pull as keys with field-value pairs as values" + end + + defp validate_op!(key) when key in @keys, do: :ok + defp validate_op!(key), do: Builder.error! "unknown key `#{inspect(key)}` in update" + + # Out means the given type must be taken out of an array + # It is the opposite of "left in right" in the query API. + defp type_for_key(:push, type), do: {:out, type} + defp type_for_key(:pull, type), do: {:out, type} + defp type_for_key(_, type), do: type +end diff --git a/deps/ecto/lib/ecto/query/builder/windows.ex b/deps/ecto/lib/ecto/query/builder/windows.ex new file mode 100644 index 0000000000000000000000000000000000000000..c5bfb930b6bab2943abc9d2aca71a8669dffca6b --- /dev/null +++ b/deps/ecto/lib/ecto/query/builder/windows.ex @@ -0,0 +1,204 @@ +import Kernel, except: [apply: 2] + +defmodule Ecto.Query.Builder.Windows do + @moduledoc false + + alias Ecto.Query.Builder + alias Ecto.Query.Builder.{GroupBy, OrderBy} + @sort_order [:partition_by, :order_by, :frame] + + @doc """ + Escapes a window params. + + ## Examples + + iex> escape(quote do [order_by: [desc: 13]] end, {[], %{}}, [x: 0], __ENV__) + {[order_by: [desc: 13]], [], {[], %{}}} + + """ + @spec escape([Macro.t], {list, term}, Keyword.t, Macro.Env.t | {Macro.Env.t, fun}) + :: {Macro.t, [{atom, term}], {list, term}} + def escape(kw, params_acc, vars, env) when is_list(kw) do + {compile, runtime} = sort(@sort_order, kw, :compile, [], []) + {compile, params_acc} = Enum.map_reduce(compile, params_acc, &escape_compile(&1, &2, vars, env)) + {compile, runtime, params_acc} + end + + def escape(kw, _params_acc, _vars, _env) do + error!(kw) + end + + defp sort([key | keys], kw, mode, compile, runtime) do + case Keyword.pop(kw, key) do + {nil, kw} -> + sort(keys, kw, mode, compile, runtime) + + {{:^, _, [var]}, kw} -> + sort(keys, kw, :runtime, compile, [{key, var} | runtime]) + + {_, _} when mode == :runtime -> + [{runtime_key, _} | _] = runtime + raise ArgumentError, "window has an interpolated value under `#{runtime_key}` " <> + "and therefore `#{key}` must also be interpolated" + + {expr, kw} -> + sort(keys, kw, mode, [{key, expr} | compile], runtime) + end + end + + defp sort([], [], _mode, compile, runtime) do + {Enum.reverse(compile), Enum.reverse(runtime)} + end + + defp sort([], kw, _mode, _compile, _runtime) do + error!(kw) + end + + defp escape_compile({:partition_by, fields}, params_acc, vars, env) do + {fields, params_acc} = GroupBy.escape(:partition_by, fields, params_acc, vars, env) + {{:partition_by, fields}, params_acc} + end + + defp escape_compile({:order_by, fields}, params_acc, vars, env) do + {fields, params_acc} = OrderBy.escape(:order_by, fields, params_acc, vars, env) + {{:order_by, fields}, params_acc} + end + + defp escape_compile({:frame, frame_clause}, params_acc, vars, env) do + {frame_clause, params_acc} = escape_frame(frame_clause, params_acc, vars, env) + {{:frame, frame_clause}, params_acc} + end + + defp escape_frame({:fragment, _, _} = fragment, params_acc, vars, env) do + Builder.escape(fragment, :any, params_acc, vars, env) + end + defp escape_frame(other, _, _, _) do + Builder.error!("expected a dynamic or fragment in `:frame`, got: `#{inspect other}`") + end + + defp error!(other) do + Builder.error!( + "expected window definition to be a keyword list " <> + "with partition_by, order_by or frame as keys, got: `#{inspect other}`" + ) + end + + @doc """ + Builds a quoted expression. + + The quoted expression should evaluate to a query at runtime. + If possible, it does all calculations at compile time to avoid + runtime work. + """ + @spec build(Macro.t, [Macro.t], Keyword.t, Macro.Env.t) :: Macro.t + def build(query, binding, windows, env) when is_list(windows) do + {query, binding} = Builder.escape_binding(query, binding, env) + + {compile, runtime} = + windows + |> Enum.map(&escape_window(binding, &1, env)) + |> Enum.split_with(&elem(&1, 2) == []) + + compile = Enum.map(compile, &build_compile_window(&1, env)) + runtime = Enum.map(runtime, &build_runtime_window(&1, env)) + query = Builder.apply_query(query, __MODULE__, [compile], env) + + if runtime == [] do + query + else + quote do + Ecto.Query.Builder.Windows.runtime!( + unquote(query), + unquote(runtime), + unquote(env.file), + unquote(env.line) + ) + end + end + end + + def build(_, _, windows, _) do + Builder.error!( + "expected window definitions to be a keyword list with window names as keys and " <> + "a keyword list with the window definition as value, got: `#{inspect windows}`" + ) + end + + defp escape_window(vars, {name, expr}, env) do + {compile_acc, runtime_acc, {params, acc}} = escape(expr, {[], %{subqueries: []}}, vars, env) + {name, compile_acc, runtime_acc, Builder.escape_params(params), acc} + end + + defp build_compile_window({name, compile_acc, _, params, acc}, env) do + {name, + quote do + %Ecto.Query.ByExpr{ + expr: unquote(compile_acc), + params: unquote(params), + subqueries: unquote(acc.subqueries), + file: unquote(env.file), + line: unquote(env.line) + } + end} + end + + defp build_runtime_window({name, compile_acc, runtime_acc, params, acc}, _env) do + {:{}, [], [name, Enum.reverse(compile_acc), runtime_acc, Enum.reverse(params), {:%{}, [], Map.to_list(acc)}]} + end + + @doc """ + Invoked for runtime windows. + """ + def runtime!(query, runtime, file, line) do + windows = + Enum.map(runtime, fn {name, compile_acc, runtime_acc, params, escape_acc} -> + {{acc, subqueries}, params} = do_runtime_window!(runtime_acc, query, {compile_acc, escape_acc.subqueries}, params) + expr = %Ecto.Query.ByExpr{expr: Enum.reverse(acc), params: Enum.reverse(params), file: file, line: line, subqueries: subqueries} + {name, expr} + end) + + apply(query, windows) + end + + defp do_runtime_window!([{:order_by, order_by} | kw], query, {acc, subqueries_acc}, params) do + {order_by, params, subqueries} = OrderBy.order_by_or_distinct!(:order_by, query, order_by, params) + + do_runtime_window!(kw, query, {[{:order_by, order_by} | acc], subqueries_acc ++ subqueries}, params) + end + + defp do_runtime_window!([{:partition_by, partition_by} | kw], query, {acc, subqueries_acc}, params) do + {partition_by, params, subqueries} = GroupBy.group_or_partition_by!(:partition_by, query, partition_by, params) + + do_runtime_window!(kw, query, {[{:partition_by, partition_by} | acc], subqueries_acc ++ subqueries}, params) + end + + defp do_runtime_window!([{:frame, frame} | kw], query, {acc, subqueries_acc}, params) do + case frame do + %Ecto.Query.DynamicExpr{} -> + {frame, params, _count} = Builder.Dynamic.partially_expand(:windows, query, frame, params, length(params)) + do_runtime_window!(kw, query, {[{:frame, frame} | acc], subqueries_acc}, params) + + _ -> + raise ArgumentError, + "expected a dynamic or fragment in `:frame`, got: `#{inspect frame}`" + end + end + + defp do_runtime_window!([], _query, acc, params), do: {acc, params} + + @doc """ + The callback applied by `build/4` to build the query. + """ + @spec apply(Ecto.Queryable.t, Keyword.t) :: Ecto.Query.t + def apply(%Ecto.Query{windows: windows} = query, definitions) do + merged = Keyword.merge(windows, definitions, fn name, _, _ -> + Builder.error! "window with name #{name} is already defined" + end) + + %{query | windows: merged} + end + + def apply(query, definitions) do + apply(Ecto.Queryable.to_query(query), definitions) + end +end diff --git a/deps/ecto/lib/ecto/query/inspect.ex b/deps/ecto/lib/ecto/query/inspect.ex new file mode 100644 index 0000000000000000000000000000000000000000..b09d2602ee6f909642366dbe76b2fdd576243e04 --- /dev/null +++ b/deps/ecto/lib/ecto/query/inspect.ex @@ -0,0 +1,436 @@ +import Inspect.Algebra +import Kernel, except: [to_string: 1] + +alias Ecto.Query.{DynamicExpr, JoinExpr, QueryExpr, WithExpr, LimitExpr} + +defimpl Inspect, for: Ecto.Query.DynamicExpr do + def inspect(%DynamicExpr{binding: binding} = dynamic, opts) do + binding = + Enum.map(binding, fn + {{:^, _, [as]}, bind} when is_atom(as) -> {as, bind} + other -> other + end) + + dynamic = %{dynamic | binding: binding} + + joins = + binding + |> Enum.drop(1) + |> Enum.with_index() + |> Enum.map(&%JoinExpr{ix: &1}) + + aliases = + for({as, _} when is_atom(as) <- binding, do: as) + |> Enum.with_index() + |> Map.new() + + query = %Ecto.Query{joins: joins, aliases: aliases} + + {expr, binding, params, subqueries, _, _} = + Ecto.Query.Builder.Dynamic.fully_expand(query, dynamic) + + names = + Enum.map(binding, fn + {_, {name, _, _}} -> name + {name, _, _} -> name + end) + + query_expr = %{expr: expr, params: params, subqueries: subqueries} + inspected = Inspect.Ecto.Query.expr(expr, List.to_tuple(names), query_expr) + + container_doc("dynamic(", [Macro.to_string(binding), inspected], ")", opts, fn str, _ -> + str + end) + end +end + +defimpl Inspect, for: Ecto.Query do + @doc false + def inspect(query, opts) do + list = + Enum.map(to_list(query), fn + {key, string} -> + concat(Atom.to_string(key) <> ": ", string) + + string -> + string + end) + + result = container_doc("#Ecto.Query<", list, ">", opts, fn str, _ -> str end) + + case query.with_ctes do + %WithExpr{recursive: recursive, queries: [_ | _] = queries} -> + with_ctes = + Enum.map(queries, fn {name, cte_opts, query} -> + cte = + case query do + %Ecto.Query{} -> __MODULE__.inspect(query, opts) + %Ecto.Query.QueryExpr{} -> expr(query, {}) + end + + concat([ + "|> with_cte(\"" <> name <> "\", materialized: ", + inspect(cte_opts[:materialized]), + ", as: ", + cte, + ")" + ]) + end) + + result = if recursive, do: glue(result, "\n", "|> recursive_ctes(true)"), else: result + [result | with_ctes] |> Enum.intersperse(break("\n")) |> concat() + + _ -> + result + end + end + + @doc false + def to_string(query) do + Enum.map_join(to_list(query), ",\n ", fn + {key, string} -> + Atom.to_string(key) <> ": " <> string + + string -> + string + end) + end + + defp to_list(query) do + names = + query + |> collect_sources() + |> generate_letters() + |> generate_names() + |> List.to_tuple() + + from = bound_from(query.from, elem(names, 0), names) + joins = joins(query.joins, names) + preloads = preloads(query.preloads) + assocs = assocs(query.assocs, names) + windows = windows(query.windows, names) + combinations = combinations(query.combinations) + limit = limit(query.limit, names) + + wheres = bool_exprs(%{and: :where, or: :or_where}, query.wheres, names) + group_bys = kw_exprs(:group_by, query.group_bys, names) + havings = bool_exprs(%{and: :having, or: :or_having}, query.havings, names) + order_bys = kw_exprs(:order_by, query.order_bys, names) + updates = kw_exprs(:update, query.updates, names) + + lock = kw_inspect(:lock, query.lock) + offset = kw_expr(:offset, query.offset, names) + select = kw_expr(:select, query.select, names) + distinct = kw_expr(:distinct, query.distinct, names) + + Enum.concat([ + from, + joins, + wheres, + group_bys, + havings, + windows, + combinations, + order_bys, + limit, + offset, + lock, + distinct, + updates, + select, + preloads, + assocs + ]) + end + + defp bound_from(nil, name, _names), do: ["from #{name} in query"] + + defp bound_from(from, name, names) do + ["from #{name} in #{inspect_source(from, names)}"] ++ kw_as_and_prefix(from) + end + + defp inspect_source(%{source: %Ecto.Query{} = query}, _names), do: "^" <> inspect(query) + + defp inspect_source(%{source: %Ecto.SubQuery{query: query}}, _names), + do: "subquery(#{to_string(query)})" + + defp inspect_source(%{source: {source, nil}}, _names), do: inspect(source) + defp inspect_source(%{source: {nil, schema}}, _names), do: inspect(schema) + + defp inspect_source(%{source: {:fragment, _, _} = source} = part, names), + do: "#{expr(source, names, part)}" + + defp inspect_source(%{source: {:values, _, [types | _]}}, _names) do + fields = Keyword.keys(types) + "values (#{Enum.join(fields, ", ")})" + end + + defp inspect_source(%{source: {source, schema}}, _names) do + inspect(if source == schema.__schema__(:source), do: schema, else: {source, schema}) + end + + defp joins(joins, names) do + joins + |> Enum.with_index() + |> Enum.flat_map(fn {expr, ix} -> join(expr, elem(names, expr.ix || ix + 1), names) end) + end + + defp join(%JoinExpr{qual: qual, assoc: {ix, right}, on: on} = join, name, names) do + string = "#{name} in assoc(#{elem(names, ix)}, #{inspect(right)})" + [{join_qual(qual), string}] ++ kw_as_and_prefix(join) ++ maybe_on(on, names) + end + + defp join(%JoinExpr{qual: qual, on: on} = join, name, names) do + string = "#{name} in #{inspect_source(join, names)}" + [{join_qual(qual), string}] ++ kw_as_and_prefix(join) ++ [on: expr(on, names)] + end + + defp maybe_on(%QueryExpr{expr: true}, _names), do: [] + defp maybe_on(%QueryExpr{} = on, names), do: [on: expr(on, names)] + + defp preloads([]), do: [] + defp preloads(preloads), do: [preload: inspect(preloads)] + + defp assocs([], _names), do: [] + defp assocs(assocs, names), do: [preload: expr(assocs(assocs), names, %{})] + + defp assocs(assocs) do + Enum.map(assocs, fn + {field, {idx, []}} -> + {field, {:&, [], [idx]}} + + {field, {idx, children}} -> + {field, {{:&, [], [idx]}, assocs(children)}} + end) + end + + defp windows(windows, names) do + Enum.map(windows, &window(&1, names)) + end + + defp window({name, %{expr: definition} = part}, names) do + {:windows, "[#{name}: " <> expr(definition, names, part) <> "]"} + end + + defp combinations(combinations) do + Enum.map(combinations, fn {key, val} -> {key, "(" <> to_string(val) <> ")"} end) + end + + defp limit(nil, _names), do: [] + + defp limit(%LimitExpr{with_ties: false} = limit, names) do + [{:limit, expr(limit, names)}] + end + + defp limit(%LimitExpr{with_ties: with_ties} = limit, names) do + [{:limit, expr(limit, names)}] ++ kw_inspect(:with_ties, with_ties) + end + + defp bool_exprs(keys, exprs, names) do + Enum.map(exprs, fn %{expr: expr, op: op} = part -> + {Map.fetch!(keys, op), expr(expr, names, part)} + end) + end + + defp kw_exprs(key, exprs, names) do + Enum.map(exprs, &{key, expr(&1, names)}) + end + + defp kw_expr(_key, nil, _names), do: [] + defp kw_expr(key, expr, names), do: [{key, expr(expr, names)}] + + defp kw_inspect(_key, nil), do: [] + defp kw_inspect(key, val), do: [{key, inspect(val)}] + + defp kw_as_and_prefix(%{as: as, prefix: prefix}) do + kw_inspect(:as, as) ++ kw_inspect(:prefix, prefix) + end + + defp expr(%{expr: expr} = part, names) do + expr(expr, names, part) + end + + @doc false + def expr(expr, names, part) do + expr + |> Macro.traverse(:ok, &{prewalk(&1, names), &2}, &{postwalk(&1, names, part), &2}) + |> elem(0) + |> macro_to_string() + end + + defp macro_to_string(expr), do: Macro.to_string(expr) + + # Tagged values + defp prewalk(%Ecto.Query.Tagged{value: value, tag: nil}, _) do + value + end + + defp prewalk(%Ecto.Query.Tagged{value: value, tag: tag}, _) do + {:type, [], [value, tag]} + end + + defp prewalk({{:., dot_meta, [{:&, _, [ix]}, field]}, meta, []}, names) do + {{:., dot_meta, [binding(names, ix), field]}, meta, []} + end + + defp prewalk(node, _) do + node + end + + # Convert variables to proper names + defp postwalk({:&, _, [ix]}, names, part) do + binding_to_expr(ix, names, part) + end + + # Remove parens from field calls + defp postwalk({{:., _, [_, _]} = dot, meta, []}, _names, _part) do + {dot, [no_parens: true] ++ meta, []} + end + + # Interpolated unknown value + defp postwalk({:^, _, [_ix, _len]}, _names, _part) do + {:^, [], [{:..., [], nil}]} + end + + # Interpolated known value + defp postwalk({:^, _, [ix]}, _, %{params: params}) do + value = + case Enum.at(params || [], ix) do + # Wrap the head in a block so it is not treated as a charlist + {[head | tail], _type} -> [{:__block__, [], [head]} | tail] + {value, _type} -> value + _ -> {:..., [], nil} + end + + {:^, [], [value]} + end + + # Types need to be converted back to AST for fields + defp postwalk({:type, meta, [expr, type]}, names, part) do + {:type, meta, [expr, type_to_expr(type, names, part)]} + end + + # For keyword and interpolated fragments use normal escaping + defp postwalk({:fragment, _, [{_, _} | _] = parts}, _names, _part) do + {:fragment, [], unmerge_fragments(parts, "", [])} + end + + # Subqueries + defp postwalk({:subquery, i}, _names, %{subqueries: subqueries}) do + {:subquery, [], [Enum.fetch!(subqueries, i).query]} + end + + # Jason + defp postwalk({:json_extract_path, _, [expr, path]}, _names, _part) do + Enum.reduce(path, expr, fn element, acc -> + {{:., [], [Access, :get]}, [], [acc, element]} + end) + end + + defp postwalk(node, _names, _part) do + node + end + + defp binding_to_expr(ix, names, part) do + case part do + %{take: %{^ix => {:any, fields}}} when ix == 0 -> + fields + + %{take: %{^ix => {tag, fields}}} -> + {tag, [], [binding(names, ix), fields]} + + _ -> + binding(names, ix) + end + end + + defp type_to_expr({ix, type}, names, part) when is_integer(ix) do + {{:., [], [binding_to_expr(ix, names, part), type]}, [no_parens: true], []} + end + + defp type_to_expr({composite, type}, names, part) when is_atom(composite) do + {composite, type_to_expr(type, names, part)} + end + + defp type_to_expr(type, _names, _part) do + type + end + + defp unmerge_fragments([{:raw, s}, {:expr, v} | t], frag, args) do + unmerge_fragments(t, frag <> s <> "?", [v | args]) + end + + defp unmerge_fragments([{:raw, s}], frag, args) do + [frag <> s | Enum.reverse(args)] + end + + defp join_qual(:inner), do: :join + defp join_qual(:inner_lateral), do: :inner_lateral_join + defp join_qual(:left), do: :left_join + defp join_qual(:left_lateral), do: :left_lateral_join + defp join_qual(:right), do: :right_join + defp join_qual(:full), do: :full_join + defp join_qual(:cross), do: :cross_join + defp join_qual(:cross_lateral), do: :cross_lateral_join + + defp collect_sources(%{from: nil, joins: joins}) do + ["query" | join_sources(joins)] + end + + defp collect_sources(%{from: %{source: source}, joins: joins}) do + [from_sources(source) | join_sources(joins)] + end + + defp from_sources(%Ecto.SubQuery{query: query}), do: from_sources(query.from.source) + defp from_sources({source, schema}), do: schema || source + defp from_sources(nil), do: "query" + defp from_sources({:fragment, _, _}), do: "fragment" + defp from_sources({:values, _, _}), do: "values" + + defp join_sources(joins) do + joins + |> Enum.sort_by(& &1.ix) + |> Enum.map(fn + %JoinExpr{assoc: {_var, assoc}} -> + assoc + + %JoinExpr{source: {:fragment, _, _}} -> + "fragment" + + %JoinExpr{source: %Ecto.Query{from: from}} -> + from_sources(from.source) + + %JoinExpr{source: source} -> + from_sources(source) + end) + end + + defp generate_letters(sources) do + Enum.map(sources, fn source -> + source + |> Kernel.to_string() + |> normalize_source() + |> String.first() + |> String.downcase() + end) + end + + defp generate_names(letters) do + {names, _} = Enum.map_reduce(letters, 0, &{:"#{&1}#{&2}", &2 + 1}) + names + end + + defp binding(names, pos) do + try do + {elem(names, pos), [], nil} + rescue + ArgumentError -> {:"unknown_binding_#{pos}!", [], nil} + end + end + + defp normalize_source("Elixir." <> _ = source), + do: source |> Module.split() |> List.last() + + defp normalize_source(source), + do: source +end diff --git a/deps/ecto/lib/ecto/query/planner.ex b/deps/ecto/lib/ecto/query/planner.ex new file mode 100644 index 0000000000000000000000000000000000000000..ce57afe200ab86a4adaaa951532b7a2f5febf111 --- /dev/null +++ b/deps/ecto/lib/ecto/query/planner.ex @@ -0,0 +1,2699 @@ +defmodule Ecto.Query.Planner do + # Normalizes a query and its parameters. + @moduledoc false + + alias Ecto.Query.{ + BooleanExpr, + ByExpr, + DynamicExpr, + FromExpr, + JoinExpr, + QueryExpr, + SelectExpr, + LimitExpr + } + + if map_size(%Ecto.Query{}) != 21 do + raise "Ecto.Query match out of date in builder" + end + + @parent_as __MODULE__ + @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 + + @doc """ + Converts a query to a list of joins. + + The from is moved as last join with the where conditions as its "on" + in order to keep proper binding order. + """ + def query_to_joins(qual, source, %{wheres: wheres, joins: joins}, position) do + on = %QueryExpr{file: __ENV__.file, line: __ENV__.line, expr: true, params: []} + + on = + Enum.reduce(wheres, on, fn %BooleanExpr{op: op, expr: expr, params: params}, acc -> + merge_expr_and_params(op, acc, expr, params) + end) + + join = %JoinExpr{qual: qual, source: source, file: __ENV__.file, line: __ENV__.line, on: on} + last = length(joins) + position + + mapping = fn + 0 -> last + ix -> ix + position - 1 + end + + for {%{on: on} = join, ix} <- Enum.with_index(joins ++ [join]) do + %{join | on: rewrite_sources(on, mapping), ix: ix + position} + end + end + + defp merge_expr_and_params( + op, + %QueryExpr{expr: left_expr, params: left_params} = struct, + right_expr, + right_params + ) do + right_expr = Ecto.Query.Builder.bump_interpolations(right_expr, left_params) + %{struct | expr: merge_expr(op, left_expr, right_expr), params: left_params ++ right_params} + end + + defp merge_expr(_op, left, true), do: left + defp merge_expr(_op, true, right), do: right + defp merge_expr(op, left, right), do: {op, [], [left, right]} + + @doc """ + Rewrites the given query expression sources using the given mapping. + """ + def rewrite_sources(%{expr: expr, params: params} = part, mapping) do + expr = + Macro.prewalk(expr, fn + %Ecto.Query.Tagged{type: type, tag: tag} = tagged -> + %{tagged | type: rewrite_type(type, mapping), tag: rewrite_type(tag, mapping)} + + {:&, meta, [ix]} -> + {:&, meta, [mapping.(ix)]} + + other -> + other + end) + + params = + Enum.map(params, fn + {val, type} -> + {val, rewrite_type(type, mapping)} + + val -> + val + end) + + %{part | expr: expr, params: params} + end + + defp rewrite_type({composite, {ix, field}}, mapping) when is_integer(ix) do + {composite, {mapping.(ix), field}} + end + + defp rewrite_type({ix, field}, mapping) when is_integer(ix) do + {mapping.(ix), field} + end + + defp rewrite_type(other, _mapping) do + other + end + + @doc """ + Define the query cache table. + """ + def new_query_cache(atom_name) do + :ets.new(atom_name || __MODULE__, [:set, :public, read_concurrency: true]) + end + + @doc """ + Plans the query for execution. + + Planning happens in multiple steps: + + 1. First the query is planned by retrieving + its cache key, casting and merging parameters + + 2. Then a cache lookup is done, if the query is + cached, we are done + + 3. If there is no cache, we need to actually + normalize and validate the query, asking the + adapter to prepare it + + 4. The query is sent to the adapter to be generated + + ## Cache + + All entries in the query, except the preload and sources + field, should be part of the cache key. + + The cache value is the compiled query by the adapter + along-side the select expression. + """ + def query(query, operation, cache, adapter, counter) do + {query, params, key} = plan(query, operation, adapter) + {cast_params, dump_params} = Enum.unzip(params) + query_with_cache(key, query, operation, cache, adapter, counter, cast_params, dump_params) + end + + defp query_with_cache(key, query, operation, cache, adapter, counter, cast_params, dump_params) do + case query_lookup(key, query, operation, cache, adapter, counter) do + {_, select, prepared} -> + {build_meta(query, select), {:nocache, prepared}, cast_params, dump_params} + + {_key, :cached, select, cached} -> + update = &cache_update(cache, key, &1) + reset = &cache_reset(cache, key, &1) + {build_meta(query, select), {:cached, update, reset, cached}, cast_params, dump_params} + + {_key, :cache, select, prepared} -> + update = &cache_update(cache, key, &1) + {build_meta(query, select), {:cache, update, prepared}, cast_params, dump_params} + end + end + + defp query_lookup(:nocache, query, operation, _cache, adapter, counter) do + query_without_cache(query, operation, adapter, counter) + end + + defp query_lookup(key, query, operation, cache, adapter, counter) do + case :ets.lookup(cache, key) do + [term] -> term + [] -> query_prepare(query, operation, adapter, counter, cache, key) + end + end + + defp query_prepare(query, operation, adapter, counter, cache, key) do + case query_without_cache(query, operation, adapter, counter) do + {:cache, select, prepared} -> + cache_insert(cache, key, {key, :cache, select, prepared}) + + {:nocache, _, _} = nocache -> + nocache + end + end + + defp cache_insert(cache, key, elem) do + case :ets.insert_new(cache, elem) do + true -> + elem + + false -> + [elem] = :ets.lookup(cache, key) + elem + end + end + + defp cache_update(cache, key, cached) do + _ = :ets.update_element(cache, key, [{2, :cached}, {4, cached}]) + :ok + end + + defp cache_reset(cache, key, prepared) do + _ = :ets.update_element(cache, key, [{2, :cache}, {4, prepared}]) + :ok + end + + defp query_without_cache(query, operation, adapter, counter) do + {query, select} = normalize(query, operation, adapter, counter) + {cache, prepared} = adapter.prepare(operation, query) + {cache, select, prepared} + end + + defp build_meta(%{sources: sources, preloads: preloads}, select) do + %{select: select, preloads: preloads, sources: sources} + end + + @doc """ + Prepares the query for cache. + + This means all the parameters from query expressions are + merged into a single value and their entries are pruned + from the query. + + This function is called by the backend before invoking + any cache mechanism. + """ + @spec plan(Ecto.Query.t(), atom(), module, map()) :: + {planned_query :: Ecto.Query.t(), parameters :: list(), cache_key :: any()} + def plan(query, operation, adapter, cte_names \\ %{}) do + {query, cte_names} = plan_ctes(query, adapter, cte_names) + query = plan_sources(query, adapter, cte_names) + plan_subquery = &plan_subquery(&1, query, nil, adapter, false, cte_names) + + query + |> plan_assocs() + |> plan_combinations(adapter, cte_names) + |> plan_expr_subqueries(:wheres, plan_subquery) + |> plan_expr_subqueries(:havings, plan_subquery) + |> plan_expr_subqueries(:order_bys, plan_subquery) + |> plan_expr_subqueries(:group_bys, plan_subquery) + |> plan_expr_subquery(:distinct, plan_subquery) + |> plan_expr_subquery(:select, plan_subquery) + |> plan_windows(plan_subquery) + |> plan_cache(operation, adapter) + rescue + e -> + # Reraise errors so we ignore the planner inner stacktrace + filter_and_reraise(e, __STACKTRACE__) + end + + @doc """ + Prepare all sources, by traversing and expanding from, joins, subqueries. + """ + def plan_sources(query, adapter, cte_names) do + {from, source} = plan_from(query, adapter, cte_names) + + # Set up the initial source so we can refer + # to the parent in subqueries in joins + query = %{query | sources: {source}} + + {joins, sources, tail_sources} = + plan_joins(query, [source], length(query.joins), adapter, cte_names) + + %{ + query + | from: from, + joins: joins |> Enum.reverse(), + sources: (tail_sources ++ sources) |> Enum.reverse() |> List.to_tuple() + } + end + + defp plan_from(%{from: nil} = query, _adapter, _cte_names) do + error!(query, "query must have a from expression") + end + + defp plan_from( + %{from: %{source: {kind, _, _}}, preloads: preloads, assocs: assocs} = query, + _adapter, + _cte_names + ) + when kind in [:fragment, :values] and (assocs != [] or preloads != []) do + error!(query, "cannot preload associations with a #{kind} source") + end + + defp plan_from(%{from: from} = query, adapter, cte_names) do + plan_source(query, from, adapter, cte_names) + end + + defp plan_source( + query, + %{source: %Ecto.SubQuery{} = subquery, prefix: prefix} = expr, + adapter, + cte_names + ) do + subquery = plan_subquery(subquery, query, prefix, adapter, true, cte_names) + {%{expr | source: subquery}, subquery} + end + + defp plan_source(query, %{source: {nil, schema}} = expr, _adapter, cte_names) + when is_atom(schema) and schema != nil do + source = schema.__schema__(:source) + source_prefix = plan_source_schema_prefix(expr, schema) + + prefix = + case cte_names do + %{^source => _} -> source_prefix + _ -> source_prefix || query.prefix + end + + {%{expr | source: {source, schema}}, {source, schema, prefix}} + end + + defp plan_source(query, %{source: {source, schema}, prefix: prefix} = expr, _adapter, cte_names) + when is_binary(source) and is_atom(schema) do + prefix = + case cte_names do + %{^source => _} -> prefix + _ -> prefix || query.prefix + end + + {expr, {source, schema, prefix}} + end + + defp plan_source( + _query, + %{source: {kind, _, _} = source, prefix: nil} = expr, + _adapter, + _cte_names + ) + when kind in [:fragment, :values], + do: {expr, source} + + defp plan_source(query, %{source: {kind, _, _}, prefix: prefix} = expr, _adapter, _cte_names) + when kind in [:fragment, :values], + do: error!(query, expr, "cannot set prefix: #{inspect(prefix)} option for #{kind} sources") + + defp plan_subquery(subquery, query, prefix, adapter, source?, cte_names) do + %{query: inner_query} = subquery + + inner_query = %{ + inner_query + | prefix: prefix || subquery.query.prefix || query.prefix, + aliases: Map.put(inner_query.aliases, @parent_as, query) + } + + {inner_query, params, key} = plan(inner_query, :all, adapter, cte_names) + assert_no_subquery_assocs!(inner_query) + + {inner_query, select} = + inner_query + |> ensure_select(true) + |> normalize_subquery_select(adapter, source?) + + {_, inner_query} = pop_in(inner_query.aliases[@parent_as]) + %{subquery | query: inner_query, params: params, cache: key, select: select} + rescue + e -> raise Ecto.SubQueryError, query: query, exception: e + end + + # The prefix for form are computed upfront, but not for joins + defp plan_source_schema_prefix(%FromExpr{prefix: prefix}, _schema), + do: prefix + + defp plan_source_schema_prefix(%JoinExpr{prefix: prefix}, schema), + do: prefix || schema.__schema__(:prefix) + + defp assert_no_subquery_assocs!(%{assocs: assocs, preloads: preloads} = query) + when assocs != [] or preloads != [] do + error!(query, "cannot preload associations in subquery") + end + + defp assert_no_subquery_assocs!(query) do + query + end + + defp normalize_subquery_select(query, adapter, source?) do + {schema_or_source, expr, %{select: select} = query} = + rewrite_subquery_select_expr(query, source?) + + {expr, _} = prewalk(expr, :select, query, select, 0, adapter) + + {{:map, types}, fields, _from} = + collect_fields(expr, [], :none, query, select.take, true, %{}) + + # types must take into account selected_as/2 aliases so that the correct fields are + # referenced when the outer query selects the entire subquery + types = normalize_subquery_types(types, Enum.reverse(fields), query.select.aliases, []) + {query, subquery_source(schema_or_source, types)} + end + + defp normalize_subquery_types(types, _fields, select_aliases, _acc) + when select_aliases == %{} do + types + end + + defp normalize_subquery_types([], [], _aliases, acc) do + Enum.reverse(acc) + end + + defp normalize_subquery_types( + [{alias, _} = type | types], + [{alias, _} | fields], + select_aliases, + acc + ) do + normalize_subquery_types(types, fields, select_aliases, [type | acc]) + end + + defp normalize_subquery_types( + [{source_alias, type_value} | types], + [field | fields], + select_aliases, + acc + ) do + if Map.has_key?(select_aliases, source_alias) do + raise ArgumentError, """ + the alias, #{inspect(source_alias)}, provided to `selected_as/2` conflicts + with the subquery's automatic aliasing. + + For example, the following query is not allowed because the alias `:y` + given to `selected_as/2` is also used by the subquery to automatically + alias `s.y`: + + s = from(s in Schema, select: %{x: selected_as(s.x, :y), y: s.y}) + from s in subquery(s) + """ + end + + type = + case field do + {select_alias, _} -> {select_alias, type_value} + _ -> {source_alias, type_value} + end + + normalize_subquery_types(types, fields, select_aliases, [type | acc]) + end + + defp subquery_source(nil, types), do: {:map, types} + defp subquery_source(name, types) when is_atom(name), do: {:struct, name, types} + + defp subquery_source({:source, schema, prefix, types}, only) do + types = + Enum.map(only, fn {field, {:value, type}} -> {field, Keyword.get(types, field, type)} end) + + {:source, schema, prefix, types} + end + + defp rewrite_subquery_select_expr(%{select: select} = query, source?) do + %{expr: expr, take: take} = select + + case subquery_select(expr, take, query) do + {schema_or_source, fields} -> + expr = {:%{}, [], fields} + {schema_or_source, expr, put_in(query.select.expr, expr)} + + :error when source? -> + error!( + query, + "subquery/cte must select a source (t), a field (t.field) or a map, got: `#{Macro.to_string(expr)}`" + ) + + :error -> + expr = {:%{}, [], [result: expr]} + {nil, expr, put_in(query.select.expr, expr)} + end + end + + defp subquery_select({:merge, _, [left, right]}, take, query) do + {left_struct, left_fields} = subquery_select(left, take, query) + {right_struct, right_fields} = subquery_select(right, take, query) + {left_struct || right_struct, Keyword.merge(left_fields, right_fields)} + end + + defp subquery_select({:%, _, [name, map]}, take, query) do + {_, fields} = subquery_select(map, take, query) + {name, fields} + end + + defp subquery_select({:%{}, _, [{:|, _, [{:&, [], [ix]}, pairs]}]} = expr, take, query) do + assert_subquery_fields!(query, expr, pairs) + drop = Map.new(pairs, fn {key, _} -> {key, nil} end) + {source, _} = source_take!(:select, query, take, ix, ix, drop) + + # In case of map updates, we need to remove duplicated fields + # at query time because we use the field names as aliases and + # duplicate aliases will lead to invalid queries. + kept_keys = subquery_source_fields(source) -- Keyword.keys(pairs) + {keep_source_or_struct(source), subquery_fields(kept_keys, ix) ++ pairs} + end + + defp subquery_select({:%{}, _, pairs} = expr, _take, query) do + assert_subquery_fields!(query, expr, pairs) + {nil, pairs} + end + + defp subquery_select({:&, _, [ix]}, take, query) do + {source, _} = source_take!(:select, query, take, ix, ix, %{}) + fields = subquery_source_fields(source) + {keep_source_or_struct(source), subquery_fields(fields, ix)} + end + + defp subquery_select({{:., _, [{:&, _, [_]}, field]}, _, []} = expr, _take, _query) do + {nil, [{field, expr}]} + end + + defp subquery_select(_expr, _take, _query) do + :error + end + + defp subquery_fields(fields, ix) do + for field <- fields do + {field, {{:., [], [{:&, [], [ix]}, field]}, [], []}} + end + end + + defp keep_source_or_struct({:source, _, _, _} = source), do: source + defp keep_source_or_struct({:struct, name, _}), do: name + defp keep_source_or_struct(_), do: nil + + defp subquery_source_fields({:source, _, _, types}), do: Keyword.keys(types) + defp subquery_source_fields({:struct, _, types}), do: Keyword.keys(types) + defp subquery_source_fields({:map, types}), do: Keyword.keys(types) + + defp subquery_type_for({:source, _, _, fields}, field), do: Keyword.fetch(fields, field) + + defp subquery_type_for({:struct, _name, types}, field), + do: subquery_type_for_value(types, field) + + defp subquery_type_for({:map, types}, field), do: subquery_type_for_value(types, field) + + defp subquery_type_for_value(types, field) do + case Keyword.fetch(types, field) do + {:ok, {:value, type}} -> {:ok, type} + {:ok, _} -> {:ok, :any} + :error -> :error + end + end + + defp assert_subquery_fields!(query, expr, pairs) do + Enum.each(pairs, fn + {key, _} when not is_atom(key) -> + error!( + query, + "only atom keys are allowed when selecting a map in subquery, got: `#{Macro.to_string(expr)}`" + ) + + {key, value} -> + if valid_subquery_value?(value) do + {key, value} + else + error!( + query, + "atoms, structs, maps, lists, tuples and sources are not allowed as map values in subquery, got: `#{Macro.to_string(expr)}`" + ) + end + end) + end + + defp valid_subquery_value?({_, _}), do: false + defp valid_subquery_value?(args) when is_list(args), do: false + + defp valid_subquery_value?({container, _, args}) + when container in [:{}, :%{}, :&, :%] and is_list(args), + do: false + + defp valid_subquery_value?(nil), do: true + defp valid_subquery_value?(arg) when is_atom(arg), do: is_boolean(arg) + defp valid_subquery_value?(_), do: true + + defp plan_joins(query, sources, offset, adapter, cte_names) do + plan_joins(query.joins, query, [], sources, [], 1, offset, adapter, cte_names) + end + + defp plan_joins( + [%JoinExpr{assoc: {ix, assoc}, qual: qual, on: on, prefix: prefix} = join | t], + query, + joins, + sources, + tail_sources, + counter, + offset, + adapter, + cte_names + ) do + source = fetch_source!(sources, ix) + schema = schema_for_association_join!(query, join, source) + refl = schema.__schema__(:association, assoc) + + unless refl do + error!(query, join, "could not find association `#{assoc}` on schema #{inspect(schema)}") + end + + # If we have the following join: + # + # from p in Post, + # join: p in assoc(p, :comments) + # + # The callback below will return a query that contains only + # joins in a way it starts with the Post and ends in the + # Comment. + # + # This means we need to rewrite the joins below to properly + # shift the &... identifier in a way that: + # + # &0 -> becomes assoc ix + # &LAST_JOIN -> becomes counter + # + # All values in the middle should be shifted by offset, + # all values after join are already correct. + child = refl.__struct__.joins_query(refl) + + # Rewrite prefixes: + # 1. the child query has the parent query prefix + # (note the child query should NEVER have a prefix) + # 2. from and joins can have their prefixes explicitly + # overwritten by the join prefix + child = rewrite_prefix(child, query.prefix) + child = update_in(child.from, &rewrite_prefix(&1, prefix)) + child = update_in(child.joins, &Enum.map(&1, fn join -> rewrite_prefix(join, prefix) end)) + + last_ix = length(child.joins) + source_ix = counter + + {_, child_from_source} = plan_source(child, child.from, adapter, cte_names) + + {child_joins, child_sources, child_tail} = + plan_joins(child, [child_from_source], offset + last_ix - 1, adapter, cte_names) + + # Rewrite joins indexes as mentioned above + child_joins = Enum.map(child_joins, &rewrite_join(&1, qual, ix, last_ix, source_ix, offset)) + + # Drop the last resource which is the association owner (it is reversed) + child_sources = Enum.drop(child_sources, -1) + + [current_source | child_sources] = child_sources + child_sources = child_tail ++ child_sources + + plan_joins( + t, + query, + attach_on(child_joins, on) ++ joins, + [current_source | sources], + child_sources ++ tail_sources, + counter + 1, + offset + length(child_sources), + adapter, + cte_names + ) + end + + defp plan_joins( + [ + %JoinExpr{source: %Ecto.Query{} = join_query, qual: qual, on: on, prefix: prefix} = + join + | t + ], + query, + joins, + sources, + tail_sources, + counter, + offset, + adapter, + cte_names + ) do + case join_query do + %{ + order_bys: [], + limit: nil, + offset: nil, + group_bys: [], + joins: [], + havings: [], + preloads: [], + assocs: [], + distinct: nil, + lock: nil + } -> + join_query = rewrite_prefix(join_query, query.prefix) + from = rewrite_prefix(join_query.from, prefix) + {from, source} = plan_source(join_query, from, adapter, cte_names) + [join] = attach_on(query_to_joins(qual, from.source, join_query, counter), on) + + plan_joins( + t, + query, + [join | joins], + [source | sources], + tail_sources, + counter + 1, + offset, + adapter, + cte_names + ) + + _ -> + error!(query, join, """ + invalid query was interpolated in a join. + If you want to pass a query to a join, you must either: + + 1. Make sure the query only has `where` conditions (which will be converted to ON clauses) + 2. Or wrap the query in a subquery by calling subquery(query) + """) + end + end + + defp plan_joins( + [%JoinExpr{} = join | t], + query, + joins, + sources, + tail_sources, + counter, + offset, + adapter, + cte_names + ) do + {join, source} = plan_source(query, %{join | ix: counter}, adapter, cte_names) + + plan_joins( + t, + query, + [join | joins], + [source | sources], + tail_sources, + counter + 1, + offset, + adapter, + cte_names + ) + end + + defp plan_joins( + [], + _query, + joins, + sources, + tail_sources, + _counter, + _offset, + _adapter, + _cte_names + ) do + {joins, sources, tail_sources} + end + + defp attach_on([%{on: on} = h | t], %{expr: expr, params: params}) do + [%{h | on: merge_expr_and_params(:and, on, expr, params)} | t] + end + + defp rewrite_prefix(expr, nil), do: expr + defp rewrite_prefix(%{prefix: nil} = expr, prefix), do: %{expr | prefix: prefix} + defp rewrite_prefix(expr, _prefix), do: expr + + defp rewrite_join(%{on: on, ix: join_ix} = join, qual, ix, last_ix, source_ix, inc_ix) do + expr = + Macro.prewalk(on.expr, fn + {:&, meta, [join_ix]} -> + {:&, meta, [rewrite_ix(join_ix, ix, last_ix, source_ix, inc_ix)]} + + expr = %Ecto.Query.Tagged{type: {type_ix, type}} when is_integer(type_ix) -> + %{expr | type: {rewrite_ix(type_ix, ix, last_ix, source_ix, inc_ix), type}} + + other -> + other + end) + + params = Enum.map(on.params, &rewrite_param_ix(&1, ix, last_ix, source_ix, inc_ix)) + + %{ + join + | on: %{on | expr: expr, params: params}, + qual: qual, + ix: rewrite_ix(join_ix, ix, last_ix, source_ix, inc_ix) + } + end + + # We need to replace the source by the one from the assoc + defp rewrite_ix(0, ix, _last_ix, _source_ix, _inc_x), do: ix + + # The last entry will have the current source index + defp rewrite_ix(last_ix, _ix, last_ix, source_ix, _inc_x), do: source_ix + + # All above last are already correct + defp rewrite_ix(join_ix, _ix, last_ix, _source_ix, _inc_ix) when join_ix > last_ix, do: join_ix + + # All others need to be incremented by the offset sources + defp rewrite_ix(join_ix, _ix, _last_ix, _source_ix, inc_ix), do: join_ix + inc_ix + + defp rewrite_param_ix({value, {upper, {type_ix, field}}}, ix, last_ix, source_ix, inc_ix) + when is_integer(type_ix) do + {value, {upper, {rewrite_ix(type_ix, ix, last_ix, source_ix, inc_ix), field}}} + end + + defp rewrite_param_ix({value, {type_ix, field}}, ix, last_ix, source_ix, inc_ix) + when is_integer(type_ix) do + {value, {rewrite_ix(type_ix, ix, last_ix, source_ix, inc_ix), field}} + end + + defp rewrite_param_ix(param, _, _, _, _), do: param + + defp fetch_source!(sources, ix) when is_integer(ix) do + case Enum.reverse(sources) |> Enum.fetch(ix) do + {:ok, source} -> + source + + :error -> + raise ArgumentError, "could not find a source with index `#{ix}` in `#{inspect(sources)}" + end + end + + defp fetch_source!(_, ix) do + raise ArgumentError, + "invalid binding index: `#{inspect(ix)}` (check if you're binding using a valid :as atom)" + end + + defp schema_for_association_join!(query, join, source) do + case source do + {:fragment, _, _} -> + error!(query, join, "cannot perform association joins on fragment sources") + + {source, nil, _} -> + error!( + query, + join, + "cannot perform association join on #{inspect(source)} " <> + "because it does not have a schema" + ) + + {_, schema, _} -> + schema + + %Ecto.SubQuery{select: {:source, {_, schema}, _, _}} -> + schema + + %Ecto.SubQuery{select: {:struct, schema, _}} -> + schema + + %Ecto.SubQuery{} -> + error!( + query, + join, + "can only perform association joins on subqueries " <> + "that return a source with schema in select" + ) + + _ -> + error!(query, join, "can only perform association joins on sources with a schema") + end + end + + # An optimized version of plan subqueries that only modifies the query when necessary. + defp plan_expr_subqueries(query, key, fun) do + query + |> Map.fetch!(key) + |> plan_expr_subqueries([], query, key, fun) + end + + defp plan_expr_subqueries([%{subqueries: []} = head | tail], acc, query, key, fun) do + plan_expr_subqueries(tail, [head | acc], query, key, fun) + end + + defp plan_expr_subqueries([head | tail], acc, query, key, fun) do + exprs = + Enum.reduce([head | tail], acc, fn + %{subqueries: []} = expr, acc -> + [expr | acc] + + %{subqueries: subqueries} = expr, acc -> + [%{expr | subqueries: Enum.map(subqueries, fun)} | acc] + end) + + %{query | key => Enum.reverse(exprs)} + end + + defp plan_expr_subqueries([], _acc, query, _key, _fun) do + query + end + + defp plan_expr_subquery(query, key, fun) do + with %{^key => %{subqueries: [_ | _] = subqueries} = expr} <- query do + %{query | key => %{expr | subqueries: Enum.map(subqueries, fun)}} + end + end + + defp plan_windows(%{windows: []} = query, _fun), do: query + + defp plan_windows(query, fun) do + windows = + Enum.map(query.windows, fn + {key, %{subqueries: []} = window} -> + {key, window} + + {key, %{subqueries: subqueries} = window} -> + {key, %{window | subqueries: Enum.map(subqueries, fun)}} + end) + + %{query | windows: windows} + end + + @doc """ + Prepare the parameters by merging and casting them according to sources. + """ + def plan_cache(query, operation, adapter) do + {query, params, cache} = traverse_cache(query, operation, {[], []}, adapter) + {query, Enum.reverse(params), cache} + end + + defp traverse_cache(query, operation, cache_params, adapter) do + fun = &{&3, merge_cache(&1, &2, &3, &4, operation, adapter)} + {query, {cache, params}} = traverse_exprs(query, operation, cache_params, fun) + {query, params, finalize_cache(query, operation, cache)} + end + + defp merge_cache(:from, query, from, {cache, params}, _operation, adapter) do + {key, params} = source_cache(from, params) + {params, source_cacheable?} = cast_and_merge_params(:from, query, from, params, adapter) + {merge_cache({:from, key, from.hints}, cache, source_cacheable? and key != :nocache), params} + end + + defp merge_cache(kind, query, expr, {cache, params}, _operation, adapter) + when kind in ~w(select distinct limit offset)a do + if expr do + {params, cacheable?} = cast_and_merge_params(kind, query, expr, params, adapter) + {merge_cache({kind, expr_to_cache(expr)}, cache, cacheable?), params} + else + {cache, params} + end + end + + defp merge_cache(kind, query, exprs, {cache, params}, _operation, adapter) + when kind in ~w(where update group_by having order_by)a do + {expr_cache, {params, cacheable?}} = + Enum.map_reduce(exprs, {params, true}, fn expr, {params, cacheable?} -> + {params, current_cacheable?} = cast_and_merge_params(kind, query, expr, params, adapter) + {expr_to_cache(expr), {params, cacheable? and current_cacheable?}} + end) + + case expr_cache do + [] -> {cache, params} + _ -> {merge_cache({kind, expr_cache}, cache, cacheable?), params} + end + end + + defp merge_cache(:join, query, exprs, {cache, params}, _operation, adapter) do + {expr_cache, {params, cacheable?}} = + Enum.map_reduce(exprs, {params, true}, fn + %JoinExpr{on: on, qual: qual, hints: hints} = join, {params, cacheable?} -> + {key, params} = source_cache(join, params) + {params, join_cacheable?} = cast_and_merge_params(:join, query, join, params, adapter) + {params, on_cacheable?} = cast_and_merge_params(:join, query, on, params, adapter) + + {{qual, key, on.expr, hints}, + {params, cacheable? and join_cacheable? and on_cacheable? and key != :nocache}} + end) + + case expr_cache do + [] -> {cache, params} + _ -> {merge_cache({:join, expr_cache}, cache, cacheable?), params} + end + end + + defp merge_cache(:windows, query, exprs, {cache, params}, _operation, adapter) do + {expr_cache, {params, cacheable?}} = + Enum.map_reduce(exprs, {params, true}, fn {key, expr}, {params, cacheable?} -> + {params, current_cacheable?} = + cast_and_merge_params(:windows, query, expr, params, adapter) + + {{key, expr_to_cache(expr)}, {params, cacheable? and current_cacheable?}} + end) + + case expr_cache do + [] -> {cache, params} + _ -> {merge_cache({:windows, expr_cache}, cache, cacheable?), params} + end + end + + defp merge_cache(:combination, _query, combinations, cache_and_params, operation, adapter) do + # In here we add each combination as its own entry in the cache key. + # We could group them to avoid multiple keys, but since they are uncommon, we keep it simple. + Enum.reduce(combinations, cache_and_params, fn {modifier, query}, {cache, params} -> + {_, params, inner_cache} = traverse_cache(query, operation, {[], params}, adapter) + {merge_cache({modifier, inner_cache}, cache, inner_cache != :nocache), params} + end) + end + + defp merge_cache(:with_cte, _query, nil, cache_and_params, _operation, _adapter) do + cache_and_params + end + + defp merge_cache(:with_cte, query, with_expr, cache_and_params, _operation, adapter) do + %{queries: queries, recursive: recursive} = with_expr + key = if recursive, do: :recursive_cte, else: :non_recursive_cte + + # In here we add each cte as its own entry in the cache key. + # We could group them to avoid multiple keys, but since they are uncommon, we keep it simple. + Enum.reduce(queries, cache_and_params, fn + {name, opts, %Ecto.Query{} = query}, {cache, params} -> + {_, params, inner_cache} = traverse_cache(query, :all, {[], params}, adapter) + + {merge_cache( + {key, name, opts[:materialized], opts[:operation], inner_cache}, + cache, + inner_cache != :nocache + ), params} + + {name, opts, %Ecto.Query.QueryExpr{} = query_expr}, {cache, params} -> + {params, cacheable?} = + cast_and_merge_params(:with_cte, query, query_expr, params, adapter) + + {merge_cache( + {key, name, opts[:materialized], opts[:operation], expr_to_cache(query_expr)}, + cache, + cacheable? + ), params} + end) + end + + defp expr_to_cache(%QueryExpr{expr: expr}), do: expr + + defp expr_to_cache(%SelectExpr{expr: expr, subqueries: []}), do: expr + + defp expr_to_cache(%SelectExpr{expr: expr, subqueries: subqueries}) do + {expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)} + end + + defp expr_to_cache(%ByExpr{expr: expr, subqueries: []}), do: expr + + defp expr_to_cache(%ByExpr{expr: expr, subqueries: subqueries}) do + {expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)} + end + + defp expr_to_cache(%BooleanExpr{op: op, expr: expr, subqueries: []}), do: {op, expr} + + defp expr_to_cache(%BooleanExpr{op: op, expr: expr, subqueries: subqueries}) do + # Alternate implementation could be replace {:subquery, i} expression in expr. + # Current strategy appends [{:subquery, i, cache}], where cache is the cache key for this subquery. + {op, expr, Enum.map(subqueries, fn %{cache: cache} -> {:subquery, cache} end)} + end + + defp expr_to_cache(%LimitExpr{expr: expr, with_ties: with_ties}), do: {with_ties, expr} + + @spec cast_and_merge_params(atom, Ecto.Query.t(), any, list, module) :: + {params :: list, cacheable? :: boolean} + defp cast_and_merge_params(kind, query, expr, params, adapter) do + Enum.reduce(expr.params, {params, true}, fn + {:subquery, i}, {acc, cacheable?} -> + # This is the place holder to intersperse subquery parameters. + %Ecto.SubQuery{params: subparams, cache: cache} = Enum.fetch!(expr.subqueries, i) + {Enum.reverse(subparams, acc), cacheable? and cache != :nocache} + + {v, type}, {acc, cacheable?} -> + case cast_param(kind, query, expr, v, type, adapter) do + {cast_v, {:in, dump_v}} -> {split_variadic_params(cast_v, dump_v, acc), false} + {cast_v, {:splice, dump_v}} -> {split_variadic_params(cast_v, dump_v, acc), cacheable?} + cast_v_and_dump_v -> {[cast_v_and_dump_v | acc], cacheable?} + end + end) + end + + defp split_variadic_params(cast_v, dump_v, acc) do + Enum.zip(cast_v, dump_v) |> Enum.reverse(acc) + end + + defp merge_cache(_left, _right, false), do: :nocache + defp merge_cache(_left, :nocache, true), do: :nocache + defp merge_cache(left, right, true), do: [left | right] + + defp finalize_cache(_query, _operation, :nocache) do + :nocache + end + + defp finalize_cache(query, operation, cache) do + %{assocs: assocs, prefix: prefix, lock: lock, select: select, aliases: aliases} = query + aliases = Map.delete(aliases, @parent_as) + + cache = + case select do + %{take: take} when take != %{} -> + [take: take] ++ cache + + _ -> + cache + end + + cache = + cache + |> prepend_if(assocs != [], assocs: assocs) + |> prepend_if(prefix != nil, prefix: prefix) + |> prepend_if(lock != nil, lock: lock) + |> prepend_if(aliases != %{}, aliases: aliases) + + [operation | cache] + end + + defp prepend_if(cache, true, prepend), do: prepend ++ cache + defp prepend_if(cache, false, _prepend), do: cache + + defp source_cache(%{source: {_, nil} = source, prefix: prefix}, params), + do: {{source, prefix}, params} + + defp source_cache(%{source: {bin, schema}, prefix: prefix}, params), + do: {{bin, schema, schema.__schema__(:hash), prefix}, params} + + defp source_cache(%{source: {:fragment, _, _} = source, prefix: prefix}, params), + do: {{source, prefix}, params} + + defp source_cache(%{source: {:values, _, _}}, params), + do: {:nocache, params} + + defp source_cache(%{source: %Ecto.SubQuery{params: inner, cache: key}}, params), + do: {key, Enum.reverse(inner, params)} + + defp cast_param(_kind, query, expr, %DynamicExpr{}, _type, _value) do + error!( + query, + expr, + "invalid dynamic expression", + "dynamic expressions can only be interpolated at the top level of where, having, group_by, order_by, select, update or a join's on" + ) + end + + defp cast_param(_kind, query, expr, [{key, _} | _], _type, _value) when is_atom(key) do + error!( + query, + expr, + "invalid keyword list", + "keyword lists are only allowed at the top level of where, having, distinct, order_by, update or a join's on" + ) + end + + defp cast_param(_kind, query, expr, %x{}, {:in, _type}, _value) + when x in [Ecto.Query, Ecto.SubQuery] do + error!( + query, + expr, + "an #{inspect(x)} struct is not supported as right-side value of `in` operator", + "Did you mean to write `expr in subquery(query)` instead?" + ) + end + + defp cast_param(kind, query, expr, v, type, adapter) do + type = field_type!(kind, query, expr, type) + + with {:ok, type} <- normalize_param(kind, type, v), + {:ok, cast_v} <- cast_param(kind, type, v), + {:ok, dump_v} <- dump_param(adapter, type, cast_v) do + {cast_v, dump_v} + else + {:error, message} -> + e = + Ecto.QueryError.exception( + message: message, + query: query, + file: expr.file, + line: expr.line + ) + + raise Ecto.Query.CastError, value: v, type: type, message: Exception.message(e) + end + end + + @doc """ + Prepare association fields found in the query. + """ + def plan_assocs(query) do + plan_assocs(query, 0, query.assocs) + query + end + + defp plan_assocs(_query, _ix, []), do: :ok + + defp plan_assocs(query, ix, assocs) do + # We validate the schema exists when preparing joins. + parent_schema = + case get_preload_source!(query, ix) do + {_, schema, _} -> + schema + + %Ecto.SubQuery{select: {:source, {_, schema}, _, _}} -> + schema + end + + Enum.each(assocs, fn {assoc, {child_ix, child_assocs}} -> + refl = parent_schema.__schema__(:association, assoc) + + unless refl do + error!( + query, + "field `#{inspect(parent_schema)}.#{assoc}` " <> + "in preload is not an association" + ) + end + + case find_source_expr(query, child_ix) do + %JoinExpr{qual: qual} when qual in [:inner, :left, :inner_lateral, :left_lateral] -> + :ok + + %JoinExpr{qual: qual} -> + error!( + query, + "association `#{inspect(parent_schema)}.#{assoc}` " <> + "in preload requires an inner, left or lateral join, got #{qual} join" + ) + + _ -> + :ok + end + + plan_assocs(query, child_ix, child_assocs) + end) + end + + defp plan_combinations(query, adapter, cte_names) do + combinations = + Enum.map(query.combinations, fn {type, combination_query} -> + {prepared_query, _params, _key} = + combination_query |> attach_prefix(query) |> plan(:all, adapter, cte_names) + + prepared_query = prepared_query |> ensure_select(true) + {type, prepared_query} + end) + + %{query | combinations: combinations} + end + + defp plan_ctes(%Ecto.Query{with_ctes: nil} = query, _adapter, cte_names), do: {query, cte_names} + + defp plan_ctes(%Ecto.Query{with_ctes: %{queries: queries}} = query, adapter, cte_names) do + {queries, cte_names} = + Enum.map_reduce(queries, cte_names, fn + {name, opts, %Ecto.Query{} = cte_query}, cte_names -> + cte_names = Map.put(cte_names, name, []) + + {planned_query, _params, _key} = + cte_query |> attach_prefix(query) |> plan(:all, adapter, cte_names) + + planned_query = planned_query |> ensure_select(true) + {{name, opts, planned_query}, cte_names} + + {name, opts, other}, cte_names -> + {{name, opts, other}, cte_names} + end) + + {put_in(query.with_ctes.queries, queries), cte_names} + end + + defp find_source_expr(query, 0) do + query.from + end + + defp find_source_expr(query, ix) do + Enum.find(query.joins, &(&1.ix == ix)) + end + + @doc """ + Used for customizing the query returning result. + """ + def ensure_select(%{select: select} = query, _fields) when select != nil do + query + end + + def ensure_select(%{select: nil}, []) do + raise ArgumentError, ":returning expects at least one field to be given, got an empty list" + end + + def ensure_select(%{select: nil} = query, fields) when is_list(fields) do + %{ + query + | select: %SelectExpr{ + expr: {:&, [], [0]}, + take: %{0 => {:any, fields}}, + line: __ENV__.line, + file: __ENV__.file + } + } + end + + def ensure_select(%{select: nil, from: %{source: {_, nil}}} = query, true) do + error!(query, "queries that do not have a schema need to explicitly pass a :select clause") + end + + def ensure_select(%{select: nil, from: %{source: {:fragment, _, _}}} = query, true) do + error!(query, "queries from a fragment need to explicitly pass a :select clause") + end + + def ensure_select(%{select: nil} = query, true) do + %{query | select: %SelectExpr{expr: {:&, [], [0]}, line: __ENV__.line, file: __ENV__.file}} + end + + def ensure_select(%{select: nil} = query, false) do + query + end + + @doc """ + Normalizes and validates the query. + + After the query was planned and there is no cache + entry, we need to update its interpolations and check + its fields and associations exist and are valid. + """ + def normalize(query, operation, adapter, counter) do + query + |> normalize_query(operation, adapter, counter) + |> elem(0) + |> normalize_select(keep_literals?(operation, query)) + rescue + e -> + # Reraise errors so we ignore the planner inner stacktrace + filter_and_reraise(e, __STACKTRACE__) + end + + defp keep_literals?(:insert_all, _), do: true + defp keep_literals?(_, %{combinations: combinations}), do: combinations != [] + + defp normalize_query(query, operation, adapter, counter) do + case operation do + :all -> + assert_no_update!(query, operation) + + :insert_all -> + assert_no_update!(query, operation) + + :update_all -> + assert_update!(query, operation) + assert_only_filter_expressions!(query, operation) + + :delete_all -> + assert_no_update!(query, operation) + assert_only_filter_expressions!(query, operation) + end + + traverse_exprs( + query, + operation, + counter, + &validate_and_increment(&1, &2, &3, &4, operation, adapter) + ) + end + + defp validate_and_increment(:from, query, %{source: %Ecto.SubQuery{}}, _counter, kind, _adapter) + when kind not in ~w(all insert_all)a do + error!(query, "`#{kind}` does not allow subqueries in `from`") + end + + defp validate_and_increment(:from, query, %{source: source} = expr, counter, _kind, adapter) do + {source, acc} = prewalk_source(source, :from, query, expr, counter, adapter) + {%{expr | source: source}, acc} + end + + defp validate_and_increment(kind, query, expr, counter, _operation, adapter) + when kind in ~w(select distinct limit offset)a do + if expr do + prewalk(kind, query, expr, counter, adapter) + else + {nil, counter} + end + end + + defp validate_and_increment(kind, query, exprs, counter, _operation, adapter) + when kind in ~w(where group_by having order_by update)a do + {exprs, counter} = + Enum.reduce(exprs, {[], counter}, fn + %{expr: []}, {list, acc} -> + {list, acc} + + expr, {list, acc} -> + {expr, acc} = prewalk(kind, query, expr, acc, adapter) + {[expr | list], acc} + end) + + {Enum.reverse(exprs), counter} + end + + defp validate_and_increment(:with_cte, _query, nil, counter, _operation, _adapter) do + {nil, counter} + end + + defp validate_and_increment(:with_cte, query, with_expr, counter, _operation, adapter) do + fun = &validate_and_increment(&1, &2, &3, &4, :all, adapter) + + {queries, counter} = + Enum.reduce(with_expr.queries, {[], counter}, fn + {name, opts, %Ecto.Query{} = inner_query}, {queries, counter} -> + inner_query = put_in(inner_query.aliases[@parent_as], query) + + # We don't want to use normalize_subquery_select because we are + # going to prepare the whole query ourselves next. + {_, _, inner_query} = rewrite_subquery_select_expr(inner_query, true) + {inner_query, counter} = traverse_exprs(inner_query, opts.operation, counter, fun) + + # Now compute the fields as keyword lists so we emit AS in Ecto query. + %{select: %{expr: expr, take: take, aliases: aliases}} = inner_query + + {{:map, types}, fields, _from} = + collect_fields(expr, [], :none, inner_query, take, true, %{}) + + fields = cte_fields(Keyword.keys(types), Enum.reverse(fields), aliases) + inner_query = put_in(inner_query.select.fields, fields) + {_, inner_query} = pop_in(inner_query.aliases[@parent_as]) + + {[{name, opts, inner_query} | queries], counter} + + {name, opts, %QueryExpr{expr: {:fragment, _, _} = fragment} = query_expr}, + {queries, counter} -> + {fragment, counter} = + prewalk_source(fragment, :with_cte, query, with_expr, counter, adapter) + + query_expr = %{query_expr | expr: fragment} + {[{name, opts, query_expr} | queries], counter} + end) + + {%{with_expr | queries: Enum.reverse(queries)}, counter} + end + + defp validate_and_increment(:join, query, exprs, counter, _operation, adapter) do + Enum.map_reduce(exprs, counter, fn join, acc -> + {source, acc} = prewalk_source(join.source, :join, query, join, acc, adapter) + {on, acc} = prewalk(:join, query, join.on, acc, adapter) + {%{join | on: on, source: source, params: nil}, acc} + end) + end + + defp validate_and_increment(:windows, query, exprs, counter, _operation, adapter) do + {exprs, counter} = + Enum.reduce(exprs, {[], counter}, fn {name, expr}, {list, acc} -> + {expr, acc} = prewalk(:windows, query, expr, acc, adapter) + {[{name, expr} | list], acc} + end) + + {Enum.reverse(exprs), counter} + end + + defp validate_and_increment(:combination, query, combinations, counter, operation, adapter) do + fun = &validate_and_increment(&1, &2, &3, &4, operation, adapter) + parent_aliases = query.aliases[@parent_as] + + {combinations, counter} = + Enum.reduce(combinations, {[], counter}, fn {type, combination_query}, + {combinations, counter} -> + combination_query = put_in(combination_query.aliases[@parent_as], parent_aliases) + {combination_query, counter} = traverse_exprs(combination_query, operation, counter, fun) + {combination_query, _} = combination_query |> normalize_select(true) + {_, combination_query} = pop_in(combination_query.aliases[@parent_as]) + {[{type, combination_query} | combinations], counter} + end) + + {Enum.reverse(combinations), counter} + end + + defp validate_json_path!([path_field | rest], field, {:parameterized, {Ecto.Embedded, embed}}) do + case embed do + %{related: related, cardinality: :one} -> + unless Enum.any?(related.__schema__(:fields), &(Atom.to_string(&1) == path_field)) do + raise "field `#{path_field}` does not exist in #{inspect(related)}" + end + + type = related.__schema__(:type, String.to_atom(path_field)) + validate_json_path!(rest, path_field, type) + + %{related: _, cardinality: :many} -> + unless is_integer(path_field) do + raise "cannot use `#{path_field}` to refer to an item in `embeds_many`" + end + + updated_embed = %{embed | cardinality: :one} + validate_json_path!(rest, path_field, {:parameterized, {Ecto.Embedded, updated_embed}}) + + other -> + raise "expected field `#{field}` to be of type embed, got: `#{inspect(other)}`" + end + end + + defp validate_json_path!([_path_field | _rest] = path, field, other_type) do + case Ecto.Type.type(other_type) do + :any -> + :ok + + :map -> + :ok + + {:map, _} -> + :ok + + {:parameterized, {type, _}} -> + validate_json_path!(path, field, type) + + type -> + raise "expected field `#{field}` to be an embed or a map, got: `#{inspect(type)}`" + end + end + + defp validate_json_path!([], _field, _type) do + :ok + end + + defp prewalk_source({:fragment, meta, fragments}, kind, query, expr, acc, adapter) do + {fragments, acc} = prewalk(fragments, kind, query, expr, acc, adapter) + {{:fragment, meta, fragments}, acc} + end + + defp prewalk_source({:values, meta, [types, num_rows]}, _kind, _query, _expr, acc, _adapter) do + length = num_rows * length(types) + # Adapters will use the schema types to cast the values + schema_types = Enum.map(types, fn {field, type} -> {field, Ecto.Type.type(type)} end) + {{:values, meta, [schema_types, acc, num_rows]}, acc + length} + end + + defp prewalk_source( + %Ecto.SubQuery{query: inner_query} = subquery, + kind, + query, + _expr, + counter, + adapter + ) do + try do + inner_query = put_in(inner_query.aliases[@parent_as], query) + {inner_query, counter} = normalize_query(inner_query, :all, adapter, counter) + {inner_query, _} = normalize_select(inner_query, true) + {_, inner_query} = pop_in(inner_query.aliases[@parent_as]) + + # If the subquery comes from a select, we are not really interested on the fields + inner_query = + if kind == :where do + inner_query + else + update_in(inner_query.select.fields, fn fields -> + # fields are aliased by the subquery source, unless + # already aliased by selected_as/2 + subquery.select + |> subquery_source_fields() + |> Enum.zip(fields) + |> Enum.map(fn + {_source_alias, {select_alias, field}} -> {select_alias, field} + {source_alias, field} -> {source_alias, field} + end) + end) + end + + {%{subquery | query: inner_query}, counter} + rescue + e -> raise Ecto.SubQueryError, query: query, exception: e + end + end + + defp prewalk_source(source, _kind, _query, _expr, acc, _adapter) do + {source, acc} + end + + defp prewalk(:update, query, expr, counter, adapter) do + source = get_source!(:update, query, 0) + + {inner, acc} = + Enum.map_reduce(expr.expr, counter, fn {op, kw}, counter -> + {kw, acc} = + Enum.map_reduce(kw, counter, fn {field, value}, counter -> + {value, acc} = prewalk(value, :update, query, expr, counter, adapter) + {{field_source(source, field), value}, acc} + end) + + {{op, kw}, acc} + end) + + {%{expr | expr: inner, params: nil}, acc} + end + + defp prewalk(kind, query, expr, counter, adapter) do + {inner, acc} = prewalk(expr.expr, kind, query, expr, counter, adapter) + {%{expr | expr: inner, params: nil}, acc} + end + + defp prewalk({:subquery, i}, kind, query, expr, acc, adapter) do + prewalk_source(Enum.fetch!(expr.subqueries, i), kind, query, expr, acc, adapter) + end + + defp prewalk({:in, in_meta, [left, {:^, meta, [param]}]}, kind, query, expr, acc, adapter) do + {left, acc} = prewalk(left, kind, query, expr, acc, adapter) + {right, acc} = validate_in(meta, expr, param, acc, adapter) + {{:in, in_meta, [left, right]}, acc} + end + + defp prewalk({:in, in_meta, [left, {:subquery, _} = right]}, kind, query, expr, acc, adapter) do + {left, acc} = prewalk(left, kind, query, expr, acc, adapter) + {right, acc} = prewalk(right, kind, query, expr, acc, adapter) + + case right.query.select.fields do + [_] -> + :ok + + _ -> + error!( + query, + "subquery must return a single field in order to be used on the right-side of `in`" + ) + end + + {{:in, in_meta, [left, right]}, acc} + end + + defp prewalk({quantifier, meta, [{:subquery, _} = subquery]}, kind, query, expr, acc, adapter) + when quantifier in [:exists, :any, :all] do + {subquery, acc} = prewalk(subquery, kind, query, expr, acc, adapter) + + case {quantifier, subquery.query.select.fields} do + {:exists, _} -> + :ok + + {_, [_]} -> + :ok + + _ -> + error!( + query, + "subquery must return a single field in order to be used with #{quantifier}" + ) + end + + {{quantifier, meta, [subquery]}, acc} + end + + defp prewalk( + {:splice, splice_meta, [{:^, meta, [_]}, length]}, + _kind, + _query, + _expr, + acc, + _adapter + ) do + param = {:^, meta, [acc, length]} + {{:splice, splice_meta, [param]}, acc + length} + end + + defp prewalk({{:., dot_meta, [left, field]}, meta, []}, kind, query, expr, acc, _adapter) do + {ix, ix_expr, ix_query} = get_ix!(left, kind, query) + extra = if kind == :select, do: [type: type!(kind, ix_query, expr, ix, field)], else: [] + field = field_source(get_source!(kind, ix_query, ix), field) + {{{:., extra ++ dot_meta, [ix_expr, field]}, meta, []}, acc} + end + + defp prewalk({:^, meta, [ix]}, _kind, _query, _expr, acc, _adapter) when is_integer(ix) do + {{:^, meta, [acc]}, acc + 1} + end + + defp prewalk({:type, _, [arg, type]}, kind, query, expr, acc, adapter) do + {arg, acc} = prewalk(arg, kind, query, expr, acc, adapter) + type = field_type!(kind, query, expr, type, true) + {%Ecto.Query.Tagged{value: arg, tag: type, type: Ecto.Type.type(type)}, acc} + end + + defp prewalk({:json_extract_path, meta, [json_field, path]}, kind, query, expr, acc, _adapter) do + {{:., dot_meta, [left, field]}, expr_meta, []} = json_field + {ix, ix_expr, ix_query} = get_ix!(left, kind, query) + + type = type!(kind, ix_query, expr, ix, field) + validate_json_path!(path, field, type) + + field_source = kind |> get_source!(ix_query, ix) |> field_source(field) + + json_field = {{:., dot_meta, [ix_expr, field_source]}, expr_meta, []} + {{:json_extract_path, meta, [json_field, path]}, acc} + end + + defp prewalk({:selected_as, [], [name]}, _kind, query, _expr, acc, _adapter) do + name = selected_as!(query.select.aliases, name) + {{:selected_as, [], [name]}, acc} + end + + defp prewalk(%Ecto.Query.Tagged{value: v, type: type} = tagged, kind, query, expr, acc, adapter) do + if Ecto.Type.base?(type) do + {tagged, acc} + else + type = field_type!(kind, query, expr, type) + + with {:ok, type} <- normalize_param(kind, type, v), + {:ok, value} <- dump_param(adapter, type, v) do + # We cannot encode binary/uuid in queries because they would emit + # invalid queries with binary parts in them. In theory, we could + # wrap them in Ecto.Query.Tagged, but a tagged UUID would most + # likely wrap its string representation, not its binary one. + # So it is best to be consistent and not support query-dumping of + # non-base types. + if is_binary(value) and Ecto.Type.type(type) in [:binary_id, :binary, :uuid] do + error = + "cannot encode value `#{inspect(v)}` of type `#{inspect(type)}` within a query, please interpolate (using ^) instead" + + error!(query, expr, error) + else + {value, acc} + end + else + {:error, error} -> + error = + error <> + ". Or the value is incompatible or it must be " <> + "interpolated (using ^) so it may be cast accordingly" + + error!(query, expr, error) + end + end + end + + defp prewalk({left, right}, kind, query, expr, acc, adapter) do + {left, acc} = prewalk(left, kind, query, expr, acc, adapter) + {right, acc} = prewalk(right, kind, query, expr, acc, adapter) + {{left, right}, acc} + end + + defp prewalk({left, meta, args}, kind, query, expr, acc, adapter) do + {left, acc} = prewalk(left, kind, query, expr, acc, adapter) + {args, acc} = prewalk(args, kind, query, expr, acc, adapter) + {{left, meta, args}, acc} + end + + defp prewalk(list, kind, query, expr, acc, adapter) when is_list(list) do + Enum.map_reduce(list, acc, &prewalk(&1, kind, query, expr, &2, adapter)) + end + + defp prewalk(other, _kind, _query, _expr, acc, _adapter) do + {other, acc} + end + + defp selected_as!(select_aliases, name) do + case select_aliases do + %{^name => _} -> + name + + _ -> + raise ArgumentError, + "invalid alias: `#{inspect(name)}`. Use `selected_as/2` to define aliases in the outer most `select` expression." + end + end + + defp validate_in(meta, expr, param, acc, adapter) do + {v, t} = Enum.fetch!(expr.params, param) + length = length(v) + + case adapter.dumpers(t, t) do + [{:in, _} | _] -> {{:^, meta, [acc, length]}, acc + length} + _ -> {{:^, meta, [acc, length]}, acc + 1} + end + end + + defp normalize_select(%{select: nil} = query, _keep_literals?) do + {query, nil} + end + + defp normalize_select(query, keep_literals?) do + %{assocs: assocs, preloads: preloads, select: select} = query + %{take: take, expr: expr} = select + {tag, from_take} = Map.get(take, 0, {:any, []}) + source = get_source!(:select, query, 0) + assocs = merge_assocs(assocs, query) + + # In from, if there is a schema and we have a map tag with preloads, + # it needs to be converted to a map in a later pass. + {take, from_tag} = + case source do + {source, schema, _} + when tag == :map and preloads != [] and is_binary(source) and schema != nil -> + {Map.put(take, 0, {:struct, from_take}), :map} + + _ -> + {take, :any} + end + + {postprocess, fields, from} = + collect_fields(expr, [], :none, query, take, keep_literals?, %{}) + + {fields, preprocess, from} = + case from do + {from_expr, from_source, from_fields} -> + {assoc_exprs, assoc_fields} = collect_assocs([], [], query, tag, from_take, assocs) + fields = from_fields ++ Enum.reverse(assoc_fields, Enum.reverse(fields)) + preprocess = [from_expr | Enum.reverse(assoc_exprs)] + {fields, preprocess, {from_tag, from_source}} + + :none when preloads != [] or assocs != [] -> + error!( + query, + "the binding used in `from` must be selected in `select` when using `preload`" + ) + + :none -> + {Enum.reverse(fields), [], :none} + end + + select = %{ + preprocess: preprocess, + postprocess: postprocess, + take: from_take, + assocs: assocs, + from: from + } + + {put_in(query.select.fields, fields), select} + end + + # Handling of source + + # The idea of collect_fields is to collect all fields used in select. + # However, special care is taken in for `from`. Because `from` is used + # earlier in assoc/preloads, any operation done on `from` is separately + # collected in the `from` information. Then, everything else refers to + # the preprocessed `from` as `{:source, :from}`. + + defp collect_fields( + {:merge, _, [left, right]}, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + case collect_fields(left, fields, from, query, take, keep_literals?, %{}) do + {{:source, :from}, fields, left_from} -> + {right, right_fields, _} = + collect_fields(right, [], left_from, query, take, keep_literals?, %{}) + + {from_expr, from_source, from_fields} = left_from + + from = + {{:merge, from_expr, right}, from_source, from_fields ++ Enum.reverse(right_fields)} + + {{:source, :from}, fields, from} + + {left, left_fields, left_from} -> + {right, right_fields, right_from} = + collect_fields(right, left_fields, left_from, query, take, keep_literals?, %{}) + + {{:merge, left, right}, right_fields, right_from} + end + end + + defp collect_fields({:&, _, [0]}, fields, :none, query, take, _keep_literals?, drop) do + {expr, taken} = source_take!(:select, query, take, 0, 0, drop) + {{:source, :from}, fields, {{:source, :from}, expr, taken}} + end + + defp collect_fields({:&, _, [0]}, fields, from, _query, _take, _keep_literals?, _drop) do + {{:source, :from}, fields, from} + end + + defp collect_fields({:&, _, [ix]}, fields, from, query, take, _keep_literals?, drop) do + {expr, taken} = source_take!(:select, query, take, ix, ix, drop) + {expr, Enum.reverse(taken, fields), from} + end + + # Expression handling + + defp collect_fields( + {agg, _, [{{:., dot_meta, [{:&, _, [_]}, _]}, _, []} | _]} = expr, + fields, + from, + _query, + _take, + _keep_literals?, + _drop + ) + when agg in @aggs do + type = + case agg do + :count -> :integer + :row_number -> :integer + :rank -> :integer + :dense_rank -> :integer + :ntile -> :integer + # If it is possible to upcast, we do it, otherwise keep the DB value. + # For example, an average of integers will return a decimal, which can't be cast + # as an integer. But an average of "moneys" should be upcast. + _ -> {:try, Keyword.fetch!(dot_meta, :type)} + end + + {{:value, type}, [expr | fields], from} + end + + defp collect_fields( + {:filter, _, [call, _]} = expr, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + case call do + {agg, _, _} when agg in @aggs -> + :ok + + {:fragment, _, [_ | _]} -> + :ok + + _ -> + error!( + query, + "filter(...) expects the first argument to be an aggregate expression, got: `#{Macro.to_string(expr)}`" + ) + end + + {type, _, _} = collect_fields(call, fields, from, query, take, keep_literals?, %{}) + {type, [expr | fields], from} + end + + defp collect_fields( + {:coalesce, _, [left, right]} = expr, + fields, + from, + query, + take, + _keep_literals?, + _drop + ) do + {left_type, _, _} = collect_fields(left, fields, from, query, take, true, %{}) + {right_type, _, _} = collect_fields(right, fields, from, query, take, true, %{}) + + type = if left_type == right_type, do: left_type, else: {:value, :any} + {type, [expr | fields], from} + end + + defp collect_fields( + {:over, _, [call, window]} = expr, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + if is_atom(window) and not Keyword.has_key?(query.windows, window) do + error!(query, "unknown window #{inspect(window)} given to over/2") + end + + {type, _, _} = collect_fields(call, fields, from, query, take, keep_literals?, %{}) + {type, [expr | fields], from} + end + + defp collect_fields( + {{:., dot_meta, [{:&, _, [_]}, _]}, _, []} = expr, + fields, + from, + _query, + _take, + _keep_literals?, + _drop + ) do + {{:value, Keyword.fetch!(dot_meta, :type)}, [expr | fields], from} + end + + defp collect_fields({left, right}, fields, from, query, take, keep_literals?, _drop) do + {args, fields, from} = + collect_args([left, right], fields, from, query, take, keep_literals?, []) + + {{:tuple, args}, fields, from} + end + + defp collect_fields({:{}, _, args}, fields, from, query, take, keep_literals?, _drop) do + {args, fields, from} = collect_args(args, fields, from, query, take, keep_literals?, []) + {{:tuple, args}, fields, from} + end + + defp collect_fields( + {:%{}, _, [{:|, _, [data, args]}]}, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + drop = Map.new(args, fn {key, _} -> {key, nil} end) + {data, fields, from} = collect_fields(data, fields, from, query, take, keep_literals?, drop) + {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, []) + {{:map, data, args}, fields, from} + end + + defp collect_fields({:%{}, _, args}, fields, from, query, take, keep_literals?, _drop) do + {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, []) + {{:map, args}, fields, from} + end + + defp collect_fields( + {:%, _, [name, {:%{}, _, [{:|, _, [data, args]}]}]}, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + drop = Map.new(args, fn {key, _} -> {key, nil} end) + {data, fields, from} = collect_fields(data, fields, from, query, take, keep_literals?, drop) + {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, []) + struct!(name, args) + {{:struct, name, data, args}, fields, from} + end + + defp collect_fields( + {:%, _, [name, {:%{}, _, args}]}, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + {args, fields, from} = collect_kv(args, fields, from, query, take, keep_literals?, []) + struct!(name, args) + {{:struct, name, args}, fields, from} + end + + defp collect_fields( + {:date_add, _, [arg | _]} = expr, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + case collect_fields(arg, fields, from, query, take, keep_literals?, %{}) do + {{:value, :any}, _, _} -> {{:value, :date}, [expr | fields], from} + {type, _, _} -> {type, [expr | fields], from} + end + end + + defp collect_fields( + {:datetime_add, _, [arg | _]} = expr, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + case collect_fields(arg, fields, from, query, take, keep_literals?, %{}) do + {{:value, :any}, _, _} -> {{:value, :naive_datetime}, [expr | fields], from} + {type, _, _} -> {type, [expr | fields], from} + end + end + + defp collect_fields(args, fields, from, query, take, keep_literals?, _drop) + when is_list(args) do + {args, fields, from} = collect_args(args, fields, from, query, take, keep_literals?, []) + {{:list, args}, fields, from} + end + + defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_binary(expr) do + {{:value, :binary}, [expr | fields], from} + end + + defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_integer(expr) do + {{:value, :integer}, [expr | fields], from} + end + + defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_float(expr) do + {{:value, :float}, [expr | fields], from} + end + + defp collect_fields(expr, fields, from, _query, _take, true, _drop) when is_boolean(expr) do + {{:value, :boolean}, [expr | fields], from} + end + + defp collect_fields(nil, fields, from, _query, _take, true, _drop) do + {{:value, :any}, [nil | fields], from} + end + + defp collect_fields(expr, fields, from, _query, _take, _keep_literals?, _drop) + when is_atom(expr) do + {expr, fields, from} + end + + defp collect_fields(expr, fields, from, _query, _take, false, _drop) + when is_binary(expr) or is_number(expr) do + {expr, fields, from} + end + + defp collect_fields( + %Ecto.Query.Tagged{tag: tag} = expr, + fields, + from, + _query, + _take, + _keep_literals?, + _drop + ) do + {{:value, tag}, [expr | fields], from} + end + + defp collect_fields({op, _, [_]} = expr, fields, from, _query, _take, _keep_literals?, _drop) + when op in ~w(not is_nil)a do + {{:value, :boolean}, [expr | fields], from} + end + + defp collect_fields({op, _, [_, _]} = expr, fields, from, _query, _take, _keep_literals?, _drop) + when op in ~w(< > <= >= == != and or like ilike)a do + {{:value, :boolean}, [expr | fields], from} + end + + defp collect_fields( + {:selected_as, _, [select_expr, name]}, + fields, + from, + query, + take, + keep_literals?, + _drop + ) do + {type, _, _} = collect_fields(select_expr, fields, from, query, take, keep_literals?, %{}) + {type, [{name, select_expr} | fields], from} + end + + defp collect_fields(expr, fields, from, _query, _take, _keep_literals?, _drop) do + {{:value, :any}, [expr | fields], from} + end + + defp collect_kv([{key, value} | elems], fields, from, query, take, keep_literals?, acc) do + {key, fields, from} = collect_fields(key, fields, from, query, take, keep_literals?, %{}) + {value, fields, from} = collect_fields(value, fields, from, query, take, keep_literals?, %{}) + collect_kv(elems, fields, from, query, take, keep_literals?, [{key, value} | acc]) + end + + defp collect_kv([], fields, from, _query, _take, _keep_literals?, acc) do + {Enum.reverse(acc), fields, from} + end + + defp collect_args([elem | elems], fields, from, query, take, keep_literals?, acc) do + {elem, fields, from} = collect_fields(elem, fields, from, query, take, keep_literals?, %{}) + collect_args(elems, fields, from, query, take, keep_literals?, [elem | acc]) + end + + defp collect_args([], fields, from, _query, _take, _keep_literals?, acc) do + {Enum.reverse(acc), fields, from} + end + + defp merge_assocs(assocs, query) do + assocs + |> Enum.reduce(%{}, fn {field, {index, children}}, acc -> + children = merge_assocs(children, query) + + Map.update(acc, field, {index, children}, fn + {^index, current_children} -> + {index, merge_assocs(children ++ current_children, query)} + + {other_index, _} -> + error!( + query, + "association `#{field}` is being set to binding at position #{index} " <> + "and at position #{other_index} at the same time" + ) + end) + end) + |> Map.to_list() + end + + defp collect_assocs(exprs, fields, query, tag, take, [{assoc, {ix, children}} | tail]) do + to_take = get_preload_source!(query, ix) + {fetch, take_children} = fetch_assoc(tag, take, assoc) + {expr, taken} = take!(to_take, query, fetch, assoc, ix, %{}) + exprs = [expr | exprs] + fields = Enum.reverse(taken, fields) + {exprs, fields} = collect_assocs(exprs, fields, query, tag, take_children, children) + {exprs, fields} = collect_assocs(exprs, fields, query, tag, take, tail) + {exprs, fields} + end + + defp collect_assocs(exprs, fields, _query, _tag, _take, []) do + {exprs, fields} + end + + defp fetch_assoc(tag, take, assoc) do + case Access.fetch(take, assoc) do + {:ok, value} -> {{:ok, {tag, value}}, value} + :error -> {:error, []} + end + end + + defp source_take!(kind, query, take, field, ix, drop) do + source = get_source!(kind, query, ix) + take!(source, query, Access.fetch(take, field), field, ix, drop) + end + + defp take!(source, query, fetched, field, ix, drop) do + case {fetched, source} do + {{:ok, {:struct, _}}, {:fragment, _, _}} -> + error!(query, "it is not possible to return a struct subset of a fragment") + + {{:ok, {:struct, _}}, %Ecto.SubQuery{}} -> + error!(query, "it is not possible to return a struct subset of a subquery") + + {{:ok, {_, []}}, {_, _, _}} -> + error!( + query, + "at least one field must be selected for binding `#{field}`, got an empty list" + ) + + {{:ok, {:struct, _}}, {_, nil, _}} -> + error!(query, "struct/2 in select expects a source with a schema") + + {{:ok, {kind, fields}}, {source, schema, prefix}} when is_binary(source) -> + dumper = if schema, do: schema.__schema__(:dump), else: %{} + schema = if kind == :map, do: nil, else: schema + {types, fields} = select_dump(List.wrap(fields), dumper, ix, drop) + {{:source, {source, schema}, prefix || query.prefix, types}, fields} + + {{:ok, {_, fields}}, _} -> + {{:map, Enum.map(fields, &{&1, {:value, :any}})}, + Enum.map(fields, &select_field(&1, ix, :always))} + + {:error, {:fragment, _, _}} -> + {{:value, :map}, [{:&, [], [ix]}]} + + {:error, {:values, _, [types, _]}} -> + fields = Keyword.keys(types) + + dumper = + types + |> Enum.map(fn {field, type} -> {field, {field, type, :always}} end) + |> Enum.into(%{}) + + {types, fields} = select_dump(fields, dumper, ix, drop) + {{:source, :values, nil, types}, fields} + + {:error, {_, nil, _}} -> + {{:value, :map}, [{:&, [], [ix]}]} + + {:error, {source, schema, prefix}} -> + {types, fields} = + select_dump(schema.__schema__(:query_fields), schema.__schema__(:dump), ix, drop) + + {{:source, {source, schema}, prefix || query.prefix, types}, fields} + + {:error, %Ecto.SubQuery{select: select}} -> + fields = subquery_source_fields(select) + {select, Enum.map(fields, &select_field(&1, ix, :always))} + end + end + + defp select_dump(fields, dumper, ix, drop) do + fields + |> Enum.reverse() + |> Enum.reduce({[], []}, fn + field, {types, exprs} when is_atom(field) and not is_map_key(drop, field) -> + {source, type, writable} = Map.get(dumper, field, {field, :any, :always}) + {[{field, type} | types], [select_field(source, ix, writable) | exprs]} + + _field, acc -> + acc + end) + end + + defp select_field(field, ix, writable) do + {{:., [writable: writable], [{:&, [], [ix]}, field]}, [], []} + end + + defp get_ix!({:&, _, [ix]} = expr, _kind, query) do + {ix, expr, query} + end + + defp get_ix!({:as, meta, [as]}, _kind, query) do + case query.aliases do + %{^as => ix} -> {ix, {:&, meta, [ix]}, query} + %{} -> error!(query, "could not find named binding `as(#{inspect(as)})`") + end + end + + defp get_ix!({:parent_as, meta, [as]}, kind, query) do + case query.aliases[@parent_as] do + %{aliases: %{^as => ix}, sources: sources} = query -> + if kind == :select and not (ix < tuple_size(sources)) do + error!( + query, + "the parent_as in a subquery select used as a join can only access the `from` binding" + ) + else + {ix, {:parent_as, [], [as]}, query} + end + + %{} = parent -> + get_ix!({:parent_as, meta, [as]}, kind, parent) + + nil -> + error!(query, "could not find named binding `parent_as(#{inspect(as)})`") + end + end + + defp get_source!(where, %{sources: sources} = query, ix) do + elem(sources, ix) + rescue + ArgumentError -> + error!( + query, + "invalid query has specified more bindings than bindings available " <> + "in `#{where}` (look for `unknown_binding!` in the printed query below)" + ) + end + + defp get_preload_source!(query, ix) do + case get_source!(:preload, query, ix) do + {source, schema, _} = all when is_binary(source) and schema != nil -> + all + + %Ecto.SubQuery{select: {:source, {source, schema}, _, _}} = subquery + when is_binary(source) and schema != nil -> + subquery + + _ -> + error!( + query, + "can only preload sources with a schema " <> + "(fragments, binaries, and subqueries that do not select a from/join schema are not supported)" + ) + end + end + + @doc """ + Puts the prefix given via `opts` into the given query, if available. + """ + def attach_prefix(%{prefix: nil} = query, opts) when is_list(opts) do + case Keyword.fetch(opts, :prefix) do + {:ok, prefix} -> + %{query | prefix: prefix} + + :error -> + query + end + end + + def attach_prefix(%{prefix: nil} = query, %{prefix: prefix}) do + %{query | prefix: prefix} + end + + def attach_prefix(query, _), do: query + + ## Helpers + + @all_exprs [ + with_cte: :with_ctes, + distinct: :distinct, + select: :select, + from: :from, + join: :joins, + where: :wheres, + group_by: :group_bys, + having: :havings, + windows: :windows, + combination: :combinations, + order_by: :order_bys, + limit: :limit, + offset: :offset + ] + + # Although joins come before updates in the actual query, + # the on fields are moved to where, so they effectively + # need to come later for MySQL. This means subqueries + # with parameters are not supported as a join on MySQL. + # The only way to address it is by splitting how join + # and their on expressions are processed. + @update_all_exprs [ + with_cte: :with_ctes, + from: :from, + update: :updates, + join: :joins, + where: :wheres, + select: :select + ] + + @delete_all_exprs [ + with_cte: :with_ctes, + from: :from, + join: :joins, + where: :wheres, + select: :select + ] + + # Traverse all query components with expressions. + # Therefore from, preload, assocs and lock are not traversed. + defp traverse_exprs(query, operation, acc, fun) do + exprs = + case operation do + :all -> @all_exprs + :insert_all -> @all_exprs + :update_all -> @update_all_exprs + :delete_all -> @delete_all_exprs + end + + Enum.reduce(exprs, {query, acc}, fn {kind, key}, {query, acc} -> + {traversed, acc} = fun.(kind, query, Map.fetch!(query, key), acc) + {%{query | key => traversed}, acc} + end) + end + + defp field_type!(kind, query, expr, type, allow_virtuals? \\ false) + + defp field_type!(kind, query, expr, {composite, {ix, field}}, allow_virtuals?) + when is_integer(ix) do + {composite, type!(kind, query, expr, ix, field, allow_virtuals?)} + end + + defp field_type!( + kind, + query, + expr, + {composite, {{bind_kind, _, [_]} = bind_expr, field}}, + allow_virtuals? + ) + when bind_kind in [:as, :parent_as] do + {ix, _, ix_query} = get_ix!(bind_expr, kind, query) + {composite, type!(kind, ix_query, expr, ix, field, allow_virtuals?)} + end + + defp field_type!(kind, query, expr, {{bind_kind, _, [_]} = bind_expr, field}, allow_virtuals?) + when bind_kind in [:as, :parent_as] do + {ix, _, ix_query} = get_ix!(bind_expr, kind, query) + type!(kind, ix_query, expr, ix, field, allow_virtuals?) + end + + defp field_type!(kind, query, expr, {ix, field}, allow_virtuals?) when is_integer(ix) do + type!(kind, query, expr, ix, field, allow_virtuals?) + end + + defp field_type!(_kind, _query, _expr, type, _) do + type + end + + defp type!(kind, query, expr, schema, field, allow_virtuals? \\ false) + + defp type!(_kind, _query, _expr, nil, _field, _allow_virtuals?), do: :any + + defp type!(kind, query, expr, ix, field, allow_virtuals?) when is_integer(ix) do + case get_source!(kind, query, ix) do + {:fragment, _, _} -> + :any + + {:values, _, [types, _]} -> + case Keyword.fetch(types, field) do + {:ok, type} -> + type + + :error -> + error!(query, expr, "field `#{field}` in `#{kind}` does not exist in values list") + end + + {_, schema, _} -> + type!(kind, query, expr, schema, field, allow_virtuals?) + + %Ecto.SubQuery{select: select} -> + case subquery_type_for(select, field) do + {:ok, type} -> type + :error -> error!(query, expr, "field `#{field}` does not exist in subquery") + end + end + end + + defp type!(kind, query, expr, schema, field, allow_virtuals?) when is_atom(schema) do + cond do + type = schema.__schema__(:type, field) -> + type + + type = allow_virtuals? && schema.__schema__(:virtual_type, field) -> + type + + Map.has_key?(schema.__struct__(), field) -> + case schema.__schema__(:association, field) do + %Ecto.Association.BelongsTo{owner_key: owner_key} -> + error!( + query, + expr, + "field `#{field}` in `#{kind}` is an association in schema #{inspect(schema)}. " <> + "Did you mean to use `#{owner_key}`?" + ) + + %_{} -> + error!( + query, + expr, + "field `#{field}` in `#{kind}` is an association in schema #{inspect(schema)}" + ) + + _ -> + error!( + query, + expr, + "field `#{field}` in `#{kind}` is a virtual field in schema #{inspect(schema)}" + ) + end + + true -> + hint = closest_fields_hint(field, schema) + + error!( + query, + expr, + "field `#{field}` in `#{kind}` does not exist in schema #{inspect(schema)}", + hint + ) + end + end + + defp closest_fields_hint(input, schema) do + input_string = Atom.to_string(input) + + schema.__schema__(:fields) + |> Enum.map(fn field -> {field, String.jaro_distance(input_string, Atom.to_string(field))} end) + |> Enum.filter(fn {_field, score} -> score >= 0.77 end) + |> Enum.sort(&(elem(&1, 0) >= elem(&2, 0))) + |> Enum.take(5) + |> Enum.map(&elem(&1, 0)) + |> case do + [] -> + nil + + [suggestion] -> + "Did you mean `#{suggestion}`?" + + suggestions -> + Enum.reduce(suggestions, "Did you mean one of: \n", fn suggestion, acc -> + acc <> "\n * `#{suggestion}`" + end) + end + end + + defp normalize_param(_kind, {:out, {:array, type}}, _value) do + {:ok, type} + end + + defp normalize_param(_kind, {:out, :any}, _value) do + {:ok, :any} + end + + defp normalize_param(kind, {:out, other}, value) do + {:error, + "value `#{inspect(value)}` in `#{kind}` expected to be part of an array " <> + "but matched type is #{inspect(other)}"} + end + + defp normalize_param(_kind, type, _value) do + {:ok, type} + end + + defp cast_param(kind, type, v) do + case Ecto.Type.cast(type, v) do + {:ok, v} -> + {:ok, v} + + :error -> + {:error, + "value `#{inspect(v)}` in `#{kind}` cannot be cast to type #{Ecto.Type.format(type)}"} + + {:error, _meta} -> + {:error, + "value `#{inspect(v)}` in `#{kind}` cannot be cast to type #{Ecto.Type.format(type)}"} + + other -> + raise "expected #{inspect(type)}.cast/1 to return {:ok, v}, :error, or {:error, meta}" <> + ", got: #{inspect(other)}" + end + end + + defp dump_param(adapter, type, v) do + case Ecto.Type.adapter_dump(adapter, type, v) do + {:ok, v} -> + {:ok, v} + + :error -> + {:error, "value `#{inspect(v)}` cannot be dumped to type #{Ecto.Type.format(type)}"} + end + end + + defp field_source({source, schema, _}, field) when is_binary(source) and schema != nil do + # If the field is not found we return the field itself + # which will be checked and raise later. + schema.__schema__(:field_source, field) || field + end + + defp field_source(_, field) do + field + end + + defp cte_fields([key | rest_keys], [{key, select_expr} | rest_fields], aliases) do + [{key, select_expr} | cte_fields(rest_keys, rest_fields, aliases)] + end + + defp cte_fields([key | rest_keys], [field | rest_fields], aliases) do + if Map.has_key?(aliases, key) do + raise ArgumentError, + "the alias, #{inspect(key)}, provided to `selected_as/2` conflicts" <> + "with the CTE's automatic aliasing. When using `selected_as/2`" <> + "inside of a CTE, you must ensure it does not conflict with any of the other" <> + "field names" + end + + {key, field} = + case field do + {alias, select_expr} -> {alias, select_expr} + field -> {key, field} + end + + [{key, field} | cte_fields(rest_keys, rest_fields, aliases)] + end + + defp cte_fields([], [], _aliases), do: [] + + defp assert_update!(%Ecto.Query{updates: updates} = query, operation) do + dumper = dumper_for_update(query) + + changes = + Enum.reduce(updates, %{}, fn update, acc -> + Enum.reduce(update.expr, acc, fn {_op, kw}, acc -> + Enum.reduce(kw, acc, fn {k, v}, acc -> + if Map.has_key?(acc, k) do + error!(query, "duplicate field `#{k}` for `#{operation}`") + end + + case dumper do + %{^k => {_, _, :always}} -> :ok + %{} -> error!(query, "cannot update non-updatable field `#{inspect(k)}`") + nil -> :ok + end + + Map.put(acc, k, v) + end) + end) + end) + + if changes == %{} do + error!(query, "`#{operation}` requires at least one field to be updated") + end + end + + defp assert_no_update!(query, operation) do + case query do + %Ecto.Query{updates: []} -> + query + + _ -> + error!(query, "`#{operation}` does not allow `update` expressions") + end + end + + defp assert_only_filter_expressions!(query, operation) do + case query do + %Ecto.Query{ + order_bys: [], + limit: nil, + offset: nil, + group_bys: [], + havings: [], + preloads: [], + assocs: [], + distinct: nil, + lock: nil, + windows: [], + combinations: [] + } -> + query + + _ when operation == :delete_all -> + error!( + query, + "`#{operation}` allows only `with_cte`, `where`, `select`, and `join` expressions. " <> + "You can exclude unwanted expressions from a query by using " <> + "Ecto.Query.exclude/2. Error found" + ) + + _ -> + error!( + query, + "`#{operation}` allows only `with_cte`, `where` and `join` expressions. " <> + "You can exclude unwanted expressions from a query by using " <> + "Ecto.Query.exclude/2. Error found" + ) + end + end + + defp dumper_for_update(query) do + case get_source!(:updates, query, 0) do + {source, schema, _} when is_binary(source) and schema != nil -> + schema.__schema__(:dump) + + _ -> + nil + end + end + + defp filter_and_reraise(exception, stacktrace) do + reraise exception, Enum.reject(stacktrace, &match?({__MODULE__, _, _, _}, &1)) + end + + defp error!(query, message) do + raise Ecto.QueryError, message: message, query: query + end + + defp error!(query, expr, message) do + raise Ecto.QueryError, message: message, query: query, file: expr.file, line: expr.line + end + + defp error!(query, expr, message, hint) do + raise Ecto.QueryError, + message: message, + query: query, + file: expr.file, + line: expr.line, + hint: hint + end +end diff --git a/deps/ecto/lib/ecto/query/window_api.ex b/deps/ecto/lib/ecto/query/window_api.ex new file mode 100644 index 0000000000000000000000000000000000000000..6e6a900d23080b3261b8b8bb43293cb09e97ff81 --- /dev/null +++ b/deps/ecto/lib/ecto/query/window_api.ex @@ -0,0 +1,232 @@ +defmodule Ecto.Query.WindowAPI do + @moduledoc """ + Lists all windows functions. + + Windows functions must always be used as the first argument + of `over/2` where the second argument is the name of a window: + + from e in Employee, + select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)}, + windows: [department: [partition_by: e.depname]] + + In the example above, we get the average salary per department. + `:department` is the window name, partitioned by `e.depname` + and `avg/1` is the window function. + + However, note that defining a window is not necessary, as the + window definition can be given as the second argument to `over`: + + from e in Employee, + select: {e.depname, e.empno, e.salary, over(avg(e.salary), partition_by: e.depname)} + + Both queries are equivalent. However, if you are using the same + partitioning over and over again, defining a window will reduce + the query size. See `Ecto.Query.windows/3` for all possible window + expressions, such as `:partition_by` and `:order_by`. + """ + + @dialyzer :no_return + + @doc """ + Counts the entries in the table. + + from p in Post, select: count() + """ + def count, do: doc! [] + + @doc """ + Counts the given entry. + + from p in Post, select: count(p.id) + """ + def count(value), do: doc! [value] + + @doc """ + Calculates the average for the given entry. + + from p in Payment, select: avg(p.value) + """ + def avg(value), do: doc! [value] + + @doc """ + Calculates the sum for the given entry. + + from p in Payment, select: sum(p.value) + """ + def sum(value), do: doc! [value] + + @doc """ + Calculates the minimum for the given entry. + + from p in Payment, select: min(p.value) + """ + def min(value), do: doc! [value] + + @doc """ + Calculates the maximum for the given entry. + + from p in Payment, select: max(p.value) + """ + def max(value), do: doc! [value] + + @doc """ + Defines a value based on the function and the window. See moduledoc for more information. + + from e in Employee, select: over(avg(e.salary), partition_by: e.depname) + """ + def over(window_function, window_name), do: doc! [window_function, window_name] + + @doc """ + Returns number of the current row within its partition, counting from 1. + + from p in Post, + select: row_number() |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def row_number(), do: doc! [] + + @doc """ + Returns rank of the current row with gaps; same as `row_number/0` of its first peer. + + from p in Post, + select: rank() |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def rank(), do: doc! [] + + @doc """ + Returns rank of the current row without gaps; this function counts peer groups. + + from p in Post, + select: dense_rank() |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def dense_rank(), do: doc! [] + + @doc """ + Returns relative rank of the current row: (rank - 1) / (total rows - 1). + + from p in Post, + select: percent_rank() |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def percent_rank(), do: doc! [] + + @doc """ + Returns relative rank of the current row: + (number of rows preceding or peer with current row) / (total rows). + + from p in Post, + select: cume_dist() |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def cume_dist(), do: doc! [] + + @doc """ + Returns integer ranging from 1 to the argument value, dividing the partition as equally as possible. + + from p in Post, + select: ntile(10) |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def ntile(num_buckets), do: doc! [num_buckets] + + @doc """ + Returns value evaluated at the row that is the first row of the window frame. + + from p in Post, + select: first_value(p.id) |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def first_value(value), do: doc! [value] + + @doc """ + Returns value evaluated at the row that is the last row of the window frame. + + from p in Post, + select: last_value(p.id) |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def last_value(value), do: doc! [value] + + + @doc """ + Applies the given expression as a FILTER clause against an + aggregate. This is currently only supported by Postgres. + + from p in Post, + select: avg(p.value) + |> filter(p.value > 0 and p.value < 100) + |> over(partition_by: p.category_id, order_by: p.date) + """ + + def filter(value, filter), do: doc! [value, filter] + + @doc """ + Returns value evaluated at the row that is the nth row of the window + frame (counting from 1); `nil` if no such row. + + from p in Post, + select: nth_value(p.id, 4) |> over(partition_by: p.category_id, order_by: p.date) + + Note that this function must be invoked using window function syntax. + """ + def nth_value(value, nth), do: doc! [value, nth] + + @doc """ + Returns value evaluated at the row that is offset rows before + the current row within the partition. + + If there is no such row, instead return default (which must be of the + same type as value). Both offset and default are evaluated with respect + to the current row. If omitted, offset defaults to 1 and default to `nil`. + + from e in Events, + windows: [w: [partition_by: e.name, order_by: e.tick]], + select: { + e.tick, + e.action, + e.name, + lag(e.action) |> over(:w), # previous_action + lead(e.action) |> over(:w) # next_action + } + + Note that this function must be invoked using window function syntax. + """ + def lag(value, offset \\ 1, default \\ nil), do: doc! [value, offset, default] + + @doc """ + Returns value evaluated at the row that is offset rows after + the current row within the partition. + + If there is no such row, instead return default (which must be of the + same type as value). Both offset and default are evaluated with respect + to the current row. If omitted, offset defaults to 1 and default to `nil`. + + from e in Events, + windows: [w: [partition_by: e.name, order_by: e.tick]], + select: { + e.tick, + e.action, + e.name, + lag(e.action) |> over(:w), # previous_action + lead(e.action) |> over(:w) # next_action + } + + Note that this function must be invoked using window function syntax. + """ + def lead(value, offset \\ 1, default \\ nil), do: doc! [value, offset, default] + + defp doc!(_) do + raise "the functions in Ecto.Query.WindowAPI should not be invoked directly, " <> + "they serve for documentation purposes only" + end +end diff --git a/deps/ecto/lib/ecto/queryable.ex b/deps/ecto/lib/ecto/queryable.ex new file mode 100644 index 0000000000000000000000000000000000000000..7ee46accdf9f0a6a7d39c46502e8aeab88ffae3f --- /dev/null +++ b/deps/ecto/lib/ecto/queryable.ex @@ -0,0 +1,150 @@ +defprotocol Ecto.Queryable do + @moduledoc """ + Converts a data structure into an `Ecto.Query`. + + This is used by `Ecto.Repo` and also `from` macro. For example, `Repo.all` + expects any queryable as argument, which is why you can do `Repo.all(MySchema)` + or `Repo.all(query)`. Furthermore, when you write `from ALIAS in QUERYABLE`, + `QUERYABLE` accepts any data structure that implements `Ecto.Queryable`. + + This module defines a few default implementations so let us go over each and + how to use them. + + ## Atom + + The most common use case for this protocol is to convert atoms representing + an `Ecto.Schema` module into a query. This is what happens when you write: + + query = from(p in Person) + + Or when you directly pass a schema to a repository: + + Repo.all(Person) + + In case you did not know, Elixir modules are just atoms. This implementation + takes the provided module name and then tries to load the associated schema. + If no schema exists, it will raise `Protocol.UndefinedError`. + + ## BitString + + This implementation allows you to directly specify a table that you would like + to query from: + + from( + p in "people", + select: {p.first_name, p.last_name} + ) + + Or: + + Repo.delete_all("people") + + While this is quite simple to use, some repository operations, such as + `Repo.all`, require a `select` clause. When you query a schema, the + select is automatically defined for you based on the schema fields, + but when you pass a table directly, you need to explicitly list them. + This limitation now brings us to our next implementation! + + ## Tuple + + Similar to the `BitString` implementation, this allows you to specify the + underlying table that you would like to query; however, this additionally + allows you to specify the schema you would like to use: + + from(p in {"filtered_people", Person}) + + This can be particularly useful if you have database views that filter or + aggregate the underlying data of a table but share the same schema. This means + that you can reuse the same schema while specifying a separate "source" for + the data. + + ## Ecto.Query + + This is a simple pass through. After all, all `Ecto.Query` instances + can be converted into `Ecto.Query`: + + Repo.all(from u in User, where: u.active) + + This also enables Ecto queries to compose, since we can pass one query + as the source of another: + + active_users = from u in User, where: u.active + ordered_active_users = from u in active_users, order_by: u.created_at + + ## Ecto.SubQuery + + Ecto also allows you to compose queries using subqueries. Imagine you + have a table of "people". Now imagine that you want to do something with + people with the most common last names. To get that list, you could write + something like: + + sub = from( + p in Person, + group_by: p.last_name, + having: count(p.last_name) > 1, + select: %{last_name: p.last_name, count: count(p.last_name)} + ) + + Now if you want to do something else with this data, perhaps join on + additional tables and perform some calculations, you can do that as so: + + from( + p in subquery(sub), + # other filtering etc here + ) + + Please note that the `Ecto.Query.subquery/2` is needed here to convert the + `Ecto.Query` into an instance of `Ecto.SubQuery`. This protocol then wraps + it into an `Ecto.Query`, but using the provided subquery in the FROM clause. + Please see `Ecto.Query.subquery/2` for more information. + """ + + @doc """ + Converts the given `data` into an `Ecto.Query`. + """ + def to_query(data) +end + +defimpl Ecto.Queryable, for: Ecto.Query do + def to_query(query), do: query +end + +defimpl Ecto.Queryable, for: Ecto.SubQuery do + def to_query(subquery) do + %Ecto.Query{from: %Ecto.Query.FromExpr{source: subquery}} + end +end + +defimpl Ecto.Queryable, for: BitString do + def to_query(source) when is_binary(source) do + %Ecto.Query{from: %Ecto.Query.FromExpr{source: {source, nil}}} + end +end + +defimpl Ecto.Queryable, for: Atom do + def to_query(module) do + try do + module.__schema__(:query) + rescue + UndefinedFunctionError -> + message = + if :code.is_loaded(module) do + "the given module does not provide a schema" + else + "the given module does not exist" + end + + raise Protocol.UndefinedError, protocol: @protocol, value: module, description: message + + FunctionClauseError -> + raise Protocol.UndefinedError, protocol: @protocol, value: module, description: "the given module is an embedded schema" + end + end +end + +defimpl Ecto.Queryable, for: Tuple do + def to_query({source, schema} = from) + when is_binary(source) and is_atom(schema) and not is_nil(schema) do + %Ecto.Query{from: %Ecto.Query.FromExpr{source: from, prefix: schema.__schema__(:prefix)}} + end +end diff --git a/deps/ecto/lib/ecto/repo.ex b/deps/ecto/lib/ecto/repo.ex new file mode 100644 index 0000000000000000000000000000000000000000..128cd8b97f8cd9955830ace4107c09485120cb05 --- /dev/null +++ b/deps/ecto/lib/ecto/repo.ex @@ -0,0 +1,2227 @@ +defmodule Ecto.Repo do + @moduledoc """ + Defines a repository. + + A repository maps to an underlying data store, controlled by the + adapter. For example, Ecto ships with a Postgres adapter that + stores data into a PostgreSQL database. + + When used, the repository expects the `:otp_app` and `:adapter` as + option. The `:otp_app` should point to an OTP application that has + the repository configuration. For example, the repository: + + defmodule Repo do + use Ecto.Repo, + otp_app: :my_app, + adapter: Ecto.Adapters.Postgres + end + + Could be configured with: + + config :my_app, Repo, + database: "ecto_simple", + username: "postgres", + password: "postgres", + hostname: "localhost" + + Most of the configuration that goes into the `config` is specific + to the adapter. For this particular example, you can check + [`Ecto.Adapters.Postgres`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.Postgres.html) + for more information. In spite of this, the following configuration values + are common across all adapters: + + * `:name`- The name of the Repo supervisor process + + * `:priv` - the directory where to keep repository data, like + migrations, schema and more. Defaults to "priv/YOUR_REPO". + It must always point to a subdirectory inside the priv directory + + * `:url` - an URL that specifies storage information. Read below + for more information + + * `:log` - the log level used when logging the query with Elixir's + Logger. Can be any of `Logger.level/0` values or `false`. If false, + disables logging for that repository. Defaults to `:debug` + + * `:pool_size` - the size of the pool used by the connection module. + Defaults to `10` + + * `:pool_count` - the number of pools to run concurrently, + increase this option when the pool itself may be under contention. + When running multiple pools, queries are randomly routed to different + pools, without taking into account how many connections are available + in each. So in some circumstances, you may be routed to a fully busy + pool while others have connections available. The overall number of + connections used will be `pool_size * pool_count`. Defaults to `1` + + * `:telemetry_prefix` - we recommend adapters to publish events + using the [Telemetry](`:telemetry`) library. By default, the telemetry prefix + is based on the module name, so if your module is called + `MyApp.Repo`, the prefix will be `[:my_app, :repo]`. See the + ["Telemetry Events"](#module-telemetry-events) section to see which events we recommend + adapters to publish. Note that if you have multiple databases, you + should keep the `:telemetry_prefix` consistent for each repo and + use the `:repo` property in the event metadata for distinguishing + between repos. + + * `:stacktrace`- when true, publishes the stacktrace in telemetry events + and allows more advanced logging. + + ## URLs + + Repositories by default support URLs. For example, the configuration + above could be rewritten to: + + config :my_app, Repo, + url: "ecto://postgres:postgres@localhost/ecto_simple" + + The schema can be of any value and the path represents the database name. + The URL will be used generate the relevant Repo configuration values, such + as `:database`, `:username`, `:password`, `:hostname` and `:port`. These + values take precedence over those already specified in the Repo's configuration. + + URL can include query parameters to override shared and adapter-specific + options, like `ssl`, `timeout` and `pool_size`. The following example + shows how to pass these configuration values: + + config :my_app, Repo, + url: "ecto://postgres:postgres@localhost/ecto_simple?ssl=true&pool_size=10" + + ## Shared options + + Almost all of the repository functions outlined in this module accept the following + options: + + * `:timeout` - The time in milliseconds (as an integer) to wait for the query call to + finish. `:infinity` will wait indefinitely (default: `15_000`) + * `:log` - Can be any of the `Logger.level/0` values or `false`. If `false`, + logging is disabled. Defaults to the configured Repo logger level + * `:telemetry_event` - The telemetry event name to dispatch the event under. + See the next section for more information + * `:telemetry_options` - Extra options to attach to telemetry event name. + See the next section for more information + + ## Adapter-Specific Errors + + Many of the functions in this module may raise adapter-specific errors, such as `PostgrexError`. + This can happen, for example, when the underlying database cannot execute the specified query. + + ## Telemetry events + + There are two types of telemetry events. The ones emitted by Ecto and the + ones that are adapter specific. + + ### Ecto telemetry events + + The following events are emitted by all Ecto repositories: + + * `[:ecto, :repo, :init]` - it is invoked whenever a repository starts. + The measurement is a single `system_time` entry in native unit. The + metadata is the `:repo` and all initialization options under `:opts`. + + ### Adapter-specific events + + We recommend adapters to publish certain `Telemetry` events listed below. + Those events will use the `:telemetry_prefix` outlined above which defaults + to `[:my_app, :repo]`. + + For instance, to receive all query events published by a repository called + `MyApp.Repo`, one would define a module: + + defmodule MyApp.Telemetry do + def handle_event([:my_app, :repo, :query], measurements, metadata, config) do + IO.inspect binding() + end + end + + Then, in the `Application.start/2` callback, attach the handler to this event using + a unique handler id: + + :ok = :telemetry.attach("my-app-handler-id", [:my_app, :repo, :query], &MyApp.Telemetry.handle_event/4, %{}) + + For details, see [the telemetry documentation](https://hexdocs.pm/telemetry/). + + Below we list all events developers should expect from Ecto. All examples + below consider a repository named `MyApp.Repo`: + + #### `[:my_app, :repo, :query]` + + This event should be invoked on every query sent to the adapter, including + queries that are related to the transaction management. + + The `:measurements` map may include the following, all given in the + `:native` time unit: + + * `:idle_time` - the time the connection spent waiting before being checked out for the query + * `:queue_time` - the time spent waiting to check out a database connection + * `:query_time` - the time spent executing the query + * `:decode_time` - the time spent decoding the data received from the database + * `:total_time` - the sum of (`queue_time`, `query_time`, and `decode_time`)️ + + All measurements are given in the `:native` time unit. You can read more + about it in the docs for `System.convert_time_unit/3`. + + A telemetry `:metadata` map including the following fields. Each database + adapter may emit different information here. For Ecto.SQL databases, it + will look like this: + + * `:type` - the type of the Ecto query. For example, for Ecto.SQL + databases, it would be `:ecto_sql_query` + * `:repo` - the Ecto repository + * `:result` - the query result + * `:params` - the dumped query parameters (formatted for database drivers like Postgrex) + * `:cast_params` - the casted query parameters (normalized before dumping) + * `:query` - the query sent to the database as a string + * `:source` - the source the query was made on (may be `nil`) + * `:stacktrace` - the stacktrace information, if enabled, or `nil` + * `:options` - extra options given to the repo operation under + `:telemetry_options` + + ## Read-only repositories + + You can mark a repository as read-only by passing the `:read_only` + flag on `use`: + + use Ecto.Repo, otp_app: ..., adapter: ..., read_only: true + + By passing the `:read_only` option, none of the functions that perform + write operations, such as `c:insert/2`, `c:insert_all/3`, `c:update_all/3`, + and friends will be defined. + """ + + @type t :: module + + @doc """ + Returns all running Ecto repositories. + + The list is returned in no particular order. The list + contains either atoms, for named Ecto repositories, or + PIDs. + """ + @spec all_running() :: [atom() | pid()] + defdelegate all_running(), to: Ecto.Repo.Registry + + @doc false + defmacro __using__(opts) do + quote bind_quoted: [opts: opts] do + @behaviour Ecto.Repo + + {otp_app, adapter, behaviours} = + Ecto.Repo.Supervisor.compile_config(__MODULE__, opts) + + @otp_app otp_app + @adapter adapter + @default_dynamic_repo opts[:default_dynamic_repo] || __MODULE__ + @read_only opts[:read_only] || false + @before_compile adapter + @aggregates [:count, :avg, :max, :min, :sum] + + def config do + {:ok, config} = Ecto.Repo.Supervisor.init_config(:runtime, __MODULE__, @otp_app, []) + config + end + + def __adapter__ do + @adapter + end + + def child_spec(opts) do + %{ + id: __MODULE__, + start: {__MODULE__, :start_link, [opts]}, + type: :supervisor + } + end + + def start_link(opts \\ []) do + Ecto.Repo.Supervisor.start_link(__MODULE__, @otp_app, @adapter, opts) + end + + def stop(timeout \\ 5000) do + Supervisor.stop(get_dynamic_repo(), :normal, timeout) + end + + def load(schema_or_types, data) do + Ecto.Repo.Schema.load(@adapter, schema_or_types, data) + end + + def checkout(fun, opts \\ []) when is_function(fun) do + %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(get_dynamic_repo()) + adapter.checkout(meta, opts, fun) + end + + def checked_out? do + %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(get_dynamic_repo()) + adapter.checked_out?(meta) + end + + @compile {:inline, get_dynamic_repo: 0} + + def get_dynamic_repo() do + Process.get({__MODULE__, :dynamic_repo}, @default_dynamic_repo) + end + + def put_dynamic_repo(dynamic) when is_atom(dynamic) or is_pid(dynamic) do + Process.put({__MODULE__, :dynamic_repo}, dynamic) || @default_dynamic_repo + end + + def default_options(_operation), do: [] + defoverridable default_options: 1 + + defp prepare_opts(operation_name, []), do: default_options(operation_name) + + defp prepare_opts(operation_name, [{key, _} | _rest] = opts) when is_atom(key) do + operation_name + |> default_options() + |> Keyword.merge(opts) + end + + ## Transactions + + if Ecto.Adapter.Transaction in behaviours do + def transaction(fun_or_multi, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Transaction.transaction( + __MODULE__, + repo, + fun_or_multi, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:transaction, opts)) + ) + end + + def in_transaction? do + Ecto.Repo.Transaction.in_transaction?(get_dynamic_repo()) + end + + @spec rollback(term) :: no_return + def rollback(value) do + Ecto.Repo.Transaction.rollback(get_dynamic_repo(), value) + end + end + + ## Schemas + + if Ecto.Adapter.Schema in behaviours and not @read_only do + def insert(struct, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.insert( + __MODULE__, + repo, + struct, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert, opts)) + ) + end + + def update(struct, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.update( + __MODULE__, + repo, + struct, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update, opts)) + ) + end + + def insert_or_update(changeset, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.insert_or_update( + __MODULE__, + repo, + changeset, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_or_update, opts)) + ) + end + + def delete(struct, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.delete( + __MODULE__, + repo, + struct, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete, opts)) + ) + end + + def insert!(struct, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.insert!( + __MODULE__, + repo, + struct, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert, opts)) + ) + end + + def update!(struct, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.update!( + __MODULE__, + repo, + struct, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update, opts)) + ) + end + + def insert_or_update!(changeset, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.insert_or_update!( + __MODULE__, + repo, + changeset, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_or_update, opts)) + ) + end + + def delete!(struct, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.delete!( + __MODULE__, + repo, + struct, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete, opts)) + ) + end + + def insert_all(schema_or_source, entries, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Schema.insert_all( + __MODULE__, + repo, + schema_or_source, + entries, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_all, opts)) + ) + end + end + + ## Queryable + + if Ecto.Adapter.Queryable in behaviours do + if not @read_only do + def update_all(queryable, updates, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.update_all( + repo, + queryable, + updates, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update_all, opts)) + ) + end + + def delete_all(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.delete_all( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete_all, opts)) + ) + end + end + + def all(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.all( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def stream(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.stream( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:stream, opts)) + ) + end + + def get(queryable, id, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.get( + repo, + queryable, + id, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def get!(queryable, id, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.get!( + repo, + queryable, + id, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def get_by(queryable, clauses, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.get_by( + repo, + queryable, + clauses, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def get_by!(queryable, clauses, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.get_by!( + repo, + queryable, + clauses, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def reload(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.reload( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:reload, opts)) + ) + end + + def reload!(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.reload!( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:reload, opts)) + ) + end + + def one(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.one( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def one!(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.one!( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def aggregate(queryable, aggregate, opts \\ []) + + def aggregate(queryable, aggregate, opts) + when aggregate in [:count] and is_list(opts) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.aggregate( + repo, + queryable, + aggregate, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def aggregate(queryable, aggregate, field) + when aggregate in @aggregates and is_atom(field) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.aggregate( + repo, + queryable, + aggregate, + field, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, [])) + ) + end + + def aggregate(queryable, aggregate, field, opts) + when aggregate in @aggregates and is_atom(field) and is_list(opts) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.aggregate( + repo, + queryable, + aggregate, + field, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def exists?(queryable, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Queryable.exists?( + repo, + queryable, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts)) + ) + end + + def preload(struct_or_structs_or_nil, preloads, opts \\ []) do + repo = get_dynamic_repo() + + Ecto.Repo.Preloader.preload( + struct_or_structs_or_nil, + repo, + preloads, + Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:preload, opts)) + ) + end + + def prepare_query(operation, query, opts), do: {query, opts} + defoverridable prepare_query: 3 + end + end + end + + ## User callbacks + + @optional_callbacks init: 2 + + @doc """ + A callback executed when the repo starts or when configuration is read. + + This callback is available for backwards compatibility purposes. Most + runtime configuration in Elixir today can be done via config/runtime.exs. + + The first argument is the context the callback is being invoked. If it + is called because the Repo supervisor is starting, it will be `:supervisor`. + It will be `:runtime` if it is called for reading configuration without + actually starting a process. + + The second argument is the repository configuration as stored in the + application environment. It must return `{:ok, keyword}` with the updated + list of configuration or `:ignore` (only in the `:supervisor` case). + """ + @doc group: "User callbacks" + @callback init(context :: :supervisor | :runtime, config :: Keyword.t()) :: + {:ok, Keyword.t()} | :ignore + + ## Ecto.Adapter + + @doc """ + Returns the adapter tied to the repository. + """ + @doc group: "Config API" + @callback __adapter__ :: Ecto.Adapter.t() + + @doc """ + Returns the adapter configuration stored in the `:otp_app` environment. + + If the `c:init/2` callback is implemented in the repository, + it will be invoked with the first argument set to `:runtime`. + It does not consider the options given on `c:start_link/1`. + """ + @doc group: "Config API" + @callback config() :: Keyword.t() + + @doc """ + Starts the Repo supervision tree. + + Returns `{:error, {:already_started, pid}}` if the repo is already + started or `{:error, term}` in case anything else goes wrong. + + ## Options + + See the configuration in the moduledoc for options shared between adapters, + for adapter-specific configuration see the adapter's documentation. + """ + @doc group: "Process API" + @callback start_link(opts :: Keyword.t()) :: + {:ok, pid} + | {:error, {:already_started, pid}} + | {:error, term} + + @doc """ + Shuts down the repository. + """ + @doc group: "Process API" + @callback stop(timeout) :: :ok + + @doc """ + Checks out a connection for the duration of the function. + + It returns the result of the function. This is useful when + you need to perform multiple operations against the repository + in a row and you want to avoid checking out the connection + multiple times. + + `checkout/2` and `transaction/2` can be combined and nested + multiple times. If `checkout/2` is called inside the function + of another `checkout/2` call, the function is simply executed, + without checking out a new connection. + + ## Options + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + """ + @doc group: "Transaction API" + @callback checkout((-> result), opts :: Keyword.t()) :: result when result: var + + @doc """ + Returns true if a connection has been checked out. + + This is true if inside a `c:Ecto.Repo.checkout/2` or + `c:Ecto.Repo.transaction/2`. + + ## Examples + + MyRepo.checked_out? + #=> false + + MyRepo.transaction(fn -> + MyRepo.checked_out? #=> true + end) + + MyRepo.checkout(fn -> + MyRepo.checked_out? #=> true + end) + + """ + @doc group: "Transaction API" + @callback checked_out?() :: boolean + + @doc """ + Loads `data` into a schema or a map. + + The first argument can be a schema module or a map (of types). + The first argument determines the return value: a struct or a map, + respectively. + + The second argument `data` specifies fields and values that are to be loaded. + It can be a map, a keyword list, or a `{fields, values}` tuple. + Fields can be atoms or strings. + + Fields that are not present in the schema (or `types` map) are ignored. + If any of the values has invalid type, an error is raised. + + To load data from non-database sources, use `Ecto.embedded_load/3`. + + ## Examples + + iex> MyRepo.load(User, %{name: "Alice", age: 25}) + %User{name: "Alice", age: 25} + + iex> MyRepo.load(User, [name: "Alice", age: 25]) + %User{name: "Alice", age: 25} + + `data` can also take form of `{fields, values}`: + + iex> MyRepo.load(User, {[:name, :age], ["Alice", 25]}) + %User{name: "Alice", age: 25, ...} + + The first argument can also be a `types` map: + + iex> types = %{name: :string, age: :integer} + iex> MyRepo.load(types, %{name: "Alice", age: 25}) + %{name: "Alice", age: 25} + + This function is especially useful when parsing raw query results: + + iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT * FROM users", []) + iex> Enum.map(result.rows, &MyRepo.load(User, {result.columns, &1})) + [%User{...}, ...] + + """ + @doc group: "Schema API" + @callback load( + schema_or_map :: module | map(), + data :: map() | Keyword.t() | {list, list} + ) :: Ecto.Schema.t() | map() + + @doc """ + Returns the atom name or pid of the current repository. + + See `c:put_dynamic_repo/1` for more information. + """ + @doc group: "Process API" + @callback get_dynamic_repo() :: atom() | pid() + + @doc """ + Sets the dynamic repository to be used in further interactions. + + Sometimes you may want a single Ecto repository to talk to + many different database instances. By default, when you call + `MyApp.Repo.start_link/1`, it will start a repository with + name `MyApp.Repo`. But if you want to start multiple repositories, + you can give each of them a different name: + + MyApp.Repo.start_link(name: :tenant_foo, hostname: "foo.example.com") + MyApp.Repo.start_link(name: :tenant_bar, hostname: "bar.example.com") + + You can also start repositories without names by explicitly + setting the name to nil: + + MyApp.Repo.start_link(name: nil, hostname: "temp.example.com") + + However, once the repository is started, you can't directly interact with + it, since all operations in `MyApp.Repo` are sent by default to the repository + named `MyApp.Repo`. You can change the default repo at compile time with: + + use Ecto.Repo, default_dynamic_repo: :name_of_repo + + Or you can change it anytime at runtime by calling `put_dynamic_repo/1`: + + MyApp.Repo.put_dynamic_repo(:tenant_foo) + + From this moment on, all future queries done by the current process will + run on `:tenant_foo`. + """ + @doc group: "Process API" + @callback put_dynamic_repo(name_or_pid :: atom() | pid()) :: atom() | pid() + + ## Ecto.Adapter.Queryable + + @optional_callbacks get: 3, + get!: 3, + get_by: 3, + get_by!: 3, + reload: 2, + reload!: 2, + aggregate: 3, + aggregate: 4, + exists?: 2, + one: 2, + one!: 2, + preload: 3, + all: 2, + stream: 2, + update_all: 3, + delete_all: 2 + + @doc """ + Fetches a single struct from the data store where the primary key matches the + given id. + + Returns `nil` if no result was found. If the struct in the queryable + has no or more than one primary key, it will raise an argument error. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + MyRepo.get(Post, 42) + + MyRepo.get(Post, 42, prefix: "public") + + """ + @doc group: "Query API" + @callback get(queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t()) :: + Ecto.Schema.t() | term | nil + + @doc """ + Similar to `c:get/3` but raises `Ecto.NoResultsError` if no record was found. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + MyRepo.get!(Post, 42) + + MyRepo.get!(Post, 42, prefix: "public") + + """ + @doc group: "Query API" + @callback get!(queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t()) :: + Ecto.Schema.t() | term + + @doc """ + Fetches a single result from the query. + + Returns `nil` if no result was found. Raises if more than one entry. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + MyRepo.get_by(Post, title: "My post") + + MyRepo.get_by(Post, [title: "My post"], prefix: "public") + + """ + @doc group: "Query API" + @callback get_by( + queryable :: Ecto.Queryable.t(), + clauses :: Keyword.t() | map, + opts :: Keyword.t() + ) :: Ecto.Schema.t() | term | nil + + @doc """ + Similar to `c:get_by/3` but raises `Ecto.NoResultsError` if no record was found. + + Raises if more than one entry. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + MyRepo.get_by!(Post, title: "My post") + + MyRepo.get_by!(Post, [title: "My post"], prefix: "public") + + """ + @doc group: "Query API" + @callback get_by!( + queryable :: Ecto.Queryable.t(), + clauses :: Keyword.t() | map, + opts :: Keyword.t() + ) :: Ecto.Schema.t() | term + + @doc """ + Reloads a given schema or schema list from the database. + + When using with lists, it is expected that all of the structs in the list belong + to the same schema. Ordering is guaranteed to be kept. Results not found in + the database will be returned as `nil`. + + ## Example + + MyRepo.reload(post) + %Post{} + + MyRepo.reload([post1, post2]) + [%Post{}, %Post{}] + + MyRepo.reload([deleted_post, post1]) + [nil, %Post{}] + """ + @doc group: "Schema API" + @callback reload( + struct_or_structs :: Ecto.Schema.t() | [Ecto.Schema.t()], + opts :: Keyword.t() + ) :: Ecto.Schema.t() | [Ecto.Schema.t() | nil] | nil + + @doc """ + Similar to `c:reload/2`, but raises when something is not found. + + When using with lists, ordering is guaranteed to be kept. + + ## Example + + MyRepo.reload!(post) + %Post{} + + MyRepo.reload!([post1, post2]) + [%Post{}, %Post{}] + """ + @doc group: "Schema API" + @callback reload!(struct_or_structs, opts :: Keyword.t()) :: struct_or_structs + when struct_or_structs: Ecto.Schema.t() | [Ecto.Schema.t()] + + @doc """ + Calculate the given `aggregate`. + + If the query has a limit, offset, distinct or combination set, it will be + automatically wrapped in a subquery in order to return the + proper result. + + Any preload or select in the query will be ignored in favor of + the column being aggregated. + + The aggregation will fail if any `group_by` field is set. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Examples + + # Returns the number of blog posts + Repo.aggregate(Post, :count) + + # Returns the number of blog posts in the "private" schema path + # (in Postgres) or database (in MySQL) + Repo.aggregate(Post, :count, prefix: "private") + + """ + @doc group: "Query API" + @callback aggregate( + queryable :: Ecto.Queryable.t(), + aggregate :: :count, + opts :: Keyword.t() + ) :: term | nil + + @doc """ + Calculate the given `aggregate` over the given `field`. + + See `c:aggregate/3` for general considerations and options. + + ## Examples + + # Returns the sum of the number of visits for every blog post + Repo.aggregate(Post, :sum, :visits) + + # Returns the sum of the number of visits for every blog post in the + # "private" schema path (in Postgres) or database (in MySQL) + Repo.aggregate(Post, :sum, :visits, prefix: "private") + + # Returns the average number of visits for the first 10 blog posts + query = from Post, limit: 10 + Repo.aggregate(query, :avg, :visits) + """ + @doc group: "Query API" + @callback aggregate( + queryable :: Ecto.Queryable.t(), + aggregate :: :avg | :count | :max | :min | :sum, + field :: atom, + opts :: Keyword.t() + ) :: term | nil + + @doc """ + Checks if there exists an entry that matches the given queryable. + + Returns a boolean. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + > #### Generated Query {: .info} + > + > Ecto will take the provided queryable and modify it to reduce its footprint + > as much as possible. For example, by forcing `SELECT 1` and `LIMIT 1`. Any + > additional filtering must be provided directly on the queryable using expressions + > such as `where` and `having`. + + ## Examples + + # checks if any posts exist + Repo.exists?(Post) + + # checks if any posts exist in the "private" schema path (in Postgres) or + # database (in MySQL) + Repo.exists?(Post, prefix: "private") + + # checks if any post with a like count greater than 10 exists + query = from p in Post, where: p.like_count > 10 + Repo.exists?(query) + """ + @doc group: "Query API" + @callback exists?(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: boolean() + + @doc """ + Fetches a single result from the query. + + Returns `nil` if no result was found. Raises if more than one entry. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Examples + + Repo.one(from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id) + + query = from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id + Repo.one(query, prefix: "private") + """ + @doc group: "Query API" + @callback one(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: + Ecto.Schema.t() | term | nil + + @doc """ + Similar to `c:one/2` but raises `Ecto.NoResultsError` if no record was found. + + Raises if more than one entry. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + """ + @doc group: "Query API" + @callback one!(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: + Ecto.Schema.t() | term + + @doc """ + Preloads all associations on the given struct or structs. + + This is similar to `Ecto.Query.preload/3` except it allows + you to preload structs after they have been fetched from the + database. + + In case the association was already loaded, preload won't attempt + to reload it. Preload assumes each association has the same nested + associations already loaded. If this is not the case, it is + possible to lose information. For example: + + comment1 = TestRepo.preload(comment1, [author: [:permalink]]) + TestRepo.preload([comment1, comment2], :author) + + If both comments are associated to the same author, the first comment + will lose its nested `:permalink` association because the second comment + does not have it preloaded. To avoid this, you must preload the nested + associations as well. + + If you want to reset the loaded fields, see `Ecto.reset_fields/2`. + + ## Options + + * `:force` - By default, Ecto won't preload associations that + are already loaded. By setting this option to true, any existing + association will be discarded and reloaded. + * `:in_parallel` - If the preloads must be done in parallel. It can + only be performed when we have more than one preload and the + repository is not in a transaction. Defaults to `true`. + * `:prefix` - the prefix to fetch preloads from. By default, queries + will use the same prefix as the first struct in the given collection. + This option allows the prefix to be changed. + * `:on_preloader_spawn` - when preloads are done in parallel, this function + will be called in the processes that perform the preloads. This can be useful + for context propagation for traces. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Examples + + # Use a single atom to preload an association + posts = Repo.preload posts, :comments + + # Use a list of atoms to preload multiple associations + posts = Repo.preload posts, [:comments, :authors] + + # Use a keyword list to preload nested associations as well + posts = Repo.preload posts, [comments: [:replies, :likes], authors: []] + + # You can mix atoms and keywords, but the atoms must come first + posts = Repo.preload posts, [:authors, comments: [:likes, replies: [:reactions]]] + + # Use a keyword list to customize how associations are queried + posts = Repo.preload posts, [comments: from(c in Comment, order_by: c.published_at)] + + # Use a two-element tuple for a custom query and nested association definition + query = from c in Comment, order_by: c.published_at + posts = Repo.preload posts, [comments: {query, [:replies, :likes]}] + + The query given to preload may also preload its own associations. + """ + @doc group: "Schema API" + @callback preload(structs_or_struct_or_nil, preloads :: term, opts :: Keyword.t()) :: + structs_or_struct_or_nil + when structs_or_struct_or_nil: [Ecto.Schema.t()] | Ecto.Schema.t() | nil + + @doc """ + A user customizable callback invoked for query-based operations. + + This callback can be used to further modify the query and options + before it is transformed and sent to the database. + + This callback is invoked for all query APIs, including the `stream` + functions. It is also invoked for `insert_all` if a source query is + given. It is not invoked for any of the other schema functions. + + ## Examples + + Let's say you want to filter out records that were "soft-deleted" + (have `deleted_at` column set) from all operations unless an admin + is running the query; you can define the callback like this: + + @impl true + def prepare_query(_operation, query, opts) do + if opts[:admin] do + {query, opts} + else + query = from(x in query, where: is_nil(x.deleted_at)) + {query, opts} + end + end + + And then execute the query: + + Repo.all(query) # only non-deleted records are returned + Repo.all(query, admin: true) # all records are returned + + The callback will be invoked for all queries, including queries + made from associations and preloads. It is not invoked for each + individual join inside a query. + """ + @doc group: "User callbacks" + @callback prepare_query(operation, query :: Ecto.Query.t(), opts :: Keyword.t()) :: + {Ecto.Query.t(), Keyword.t()} + when operation: :all | :update_all | :delete_all | :stream | :insert_all + + @doc """ + A user customizable callback invoked to retrieve default options + for operations. + + This can be used to provide default values per operation that + have higher precedence than the values given on configuration + or when starting the repository. It can also be used to set + query specific options, such as `:prefix`. + + This callback is invoked as the entry point for all repository + operations. For example, if you are executing a query with preloads, + this callback will be invoked once at the beginning, but the + options returned here will be passed to all following operations. + """ + @doc group: "User callbacks" + @callback default_options(operation) :: Keyword.t() + when operation: + :all + | :delete + | :delete_all + | :insert + | :insert_all + | :insert_or_update + | :preload + | :reload + | :stream + | :transaction + | :update + | :update_all + @doc """ + Fetches all entries from the data store matching the given query. + + May raise `Ecto.QueryError` if query validation fails. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + # Fetch all post titles + query = from p in Post, + select: p.title + MyRepo.all(query) + """ + @doc group: "Query API" + @callback all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: [Ecto.Schema.t() | term] + + @doc """ + Returns a lazy enumerable that emits all entries from the data store + matching the given query. + + SQL adapters, such as Postgres and MySQL, can only enumerate a stream + inside a transaction. + + May raise `Ecto.QueryError` if query validation fails. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + * `:max_rows` - The number of rows to load from the database as we stream. + It is supported at least by Postgres and MySQL and defaults to 500. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + # Fetch all post titles + query = from p in Post, + select: p.title + stream = MyRepo.stream(query) + MyRepo.transaction(fn -> + Enum.to_list(stream) + end) + """ + @doc group: "Query API" + @callback stream(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: Enum.t() + + @doc """ + Updates all entries matching the given query with the given values. + + It returns a tuple containing the number of entries and any returned + result as second element. The second element is `nil` by default + unless a `select` is supplied in the update query. Note, however, + not all databases support returning data from UPDATEs. + + Keep in mind this `update_all` will not update autogenerated + fields like the `updated_at` columns. + + See `Ecto.Query.update/3` for update operations that can be + performed on fields. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for remaining options. + + ## Examples + + MyRepo.update_all(Post, set: [title: "New title"]) + + MyRepo.update_all(Post, inc: [visits: 1]) + + from(p in Post, where: p.id < 10, select: p.visits) + |> MyRepo.update_all(set: [title: "New title"]) + + from(p in Post, where: p.id < 10, update: [set: [title: "New title"]]) + |> MyRepo.update_all([]) + + from(p in Post, where: p.id < 10, update: [set: [title: ^new_title]]) + |> MyRepo.update_all([]) + + from(p in Post, where: p.id < 10, update: [set: [title: fragment("upper(?)", ^new_title)]]) + |> MyRepo.update_all([]) + + from(p in Post, where: p.id < 10, update: [set: [visits: p.visits * 1000]]) + |> MyRepo.update_all([]) + + """ + @doc group: "Query API" + @callback update_all( + queryable :: Ecto.Queryable.t(), + updates :: Keyword.t(), + opts :: Keyword.t() + ) :: {non_neg_integer, nil | [term]} + + @doc """ + Deletes all entries matching the given query. + + It returns a tuple containing the number of entries and any returned + result as second element. The second element is `nil` by default + unless a `select` is supplied in the delete query. Note, however, + not all databases support returning data from DELETEs. + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This will be applied to all `from` + and `join`s in the query that did not have a prefix previously given + either via the `:prefix` option on `join`/`from` or via `@schema_prefix` + in the schema. For more information see the ["Query Prefix"](`m:Ecto.Query#module-query-prefix`) section of the + `Ecto.Query` documentation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for remaining options. + + ## Examples + + MyRepo.delete_all(Post) + + from(p in Post, where: p.id < 10) |> MyRepo.delete_all() + + # With returning results, if supported by the database. + {_count, posts} = from(p in Post, where: p.id < 10, select: p) |> MyRepo.delete_all() + + """ + @doc group: "Query API" + @callback delete_all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: + {non_neg_integer, nil | [term]} + + ## Ecto.Adapter.Schema + + @optional_callbacks insert_all: 3, + insert: 2, + insert!: 2, + update: 2, + update!: 2, + delete: 2, + delete!: 2, + insert_or_update: 2, + insert_or_update!: 2, + prepare_query: 3 + + @doc """ + Inserts all entries into the repository. + + It expects a schema module (`MyApp.User`) or a source (`"users"`) or + both (`{"users", MyApp.User}`) as the first argument. The second + argument is a list of entries to be inserted, either as keyword + lists or as maps. The keys of the entries are the field names as + atoms, when a schema module is specified in the first argument. + Otherwise, the keys can be either atoms or strings representing + the names of the columns in the underlying datastore. The value + should be the respective value for the field type or, optionally, + an `Ecto.Query` that returns a single entry with a single value. + + It returns a tuple containing the number of entries + and any returned result as second element. If the database + does not support RETURNING in INSERT statements or no + return result was selected, the second element will be `nil`. + + When a schema module is given, the entries given will be properly dumped + before being sent to the database. If the schema primary key has type + `:id` or `:binary_id`, it will be handled either at the adapter + or the storage layer. However any other primary key type or autogenerated + value, like `Ecto.UUID` and timestamps, won't be autogenerated when + using `c:insert_all/3`. You must set those fields explicitly. This is by + design as this function aims to be a more direct way to insert data into + the database without the conveniences of `c:insert/2`. This is also + consistent with `c:update_all/3` that does not handle auto generated + values as well. + + It is also not possible to use `insert_all` to insert across multiple + tables, therefore associations are not supported. + + If a source is given, without a schema module, the given fields are passed + as is to the adapter. + + ## Options + + * `:returning` - selects which fields to return. When `true`, + returns all fields in the given schema. May be a list of + fields, where a struct is still returned but only with the + given fields. Or `false`, where nothing is returned (the default). + This option is not supported by all databases. + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This overrides the prefix set + in the query and any `@schema_prefix` set in the schema. + + * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, + `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`, + a keyword list of update instructions or an `Ecto.Query` + query for updates. See the "[Upserts](#c:insert_all/3-upserts)" section for more information. + + * `:conflict_target` - A list of column names to verify for conflicts. + It is expected those columns to have unique indexes on them that may conflict. + If none is specified, the conflict target is left up to the database. + It may also be `{:unsafe_fragment, binary_fragment}` to pass any + expression to the database without any sanitization, this is useful + for partial index or index with expressions, such as + `{:unsafe_fragment, "(coalesce(firstname, ''), coalesce(lastname, '')) WHERE middlename IS NULL"}` for + `ON CONFLICT (coalesce(firstname, ''), coalesce(lastname, '')) WHERE middlename IS NULL` SQL query. + + * `:placeholders` - A map with placeholders. This feature is not supported + by all databases. See the ["Placeholders" section](#c:insert_all/3-placeholders) for more information. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for remaining options. + + ## Source query + + A query can be given instead of a list with entries. This query needs to select + into a map containing only keys that are available as writeable columns in the + schema. This will query and insert the values all inside one query, without + another round trip to the application. + + ## Examples + + MyRepo.insert_all(Post, [[title: "My first post"], [title: "My second post"]]) + + MyRepo.insert_all(Post, [%{title: "My first post"}, %{title: "My second post"}]) + + query = from p in Post, + join: c in assoc(p, :comments), + select: %{ + author_id: p.author_id, + posts: count(p.id, :distinct), + interactions: sum(p.likes) + count(c.id) + }, + group_by: p.author_id + MyRepo.insert_all(AuthorStats, query) + + ## Upserts + + `c:insert_all/3` provides upserts (update or inserts) via the `:on_conflict` + option. The `:on_conflict` option supports the following values: + + * `:raise` - raises if there is a conflicting primary key or unique index + + * `:nothing` - ignores the error in case of conflicts + + * `:replace_all` - replace **all** values on the existing row with the values + in the schema/changeset, including fields not explicitly set in the changeset, + such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`). + Do not use this option if you have auto-incrementing primary keys, as they + will also be replaced. You most likely want to use `{:replace_all_except, [:id]}` + or `{:replace, fields}` explicitly instead. This option requires a schema + + * `{:replace_all_except, fields}` - same as above except the given fields + are not replaced. This option requires a schema + + * `{:replace, fields}` - replace only specific columns. This option requires + `:conflict_target` + + * a keyword list of update instructions - such as the one given to + `c:update_all/3`, for example: `[set: [title: "new title"]]` + + * an `Ecto.Query` that will act as an `UPDATE` statement, such as the + one given to `c:update_all/3` + + Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" + on databases such as MySQL. + + ## Return values + + By default, both Postgres and MySQL will return the number of entries + inserted on `c:insert_all/3`. However, when the `:on_conflict` option + is specified, Postgres and MySQL will return different results. + + Postgres will only count a row if it was affected and will + return 0 if no new entry was added. + + MySQL will return, at a minimum, the number of entries attempted. For example, + if `:on_conflict` is set to `:nothing`, MySQL will return + the number of entries attempted to be inserted, even when no entry + was added. + + Also note that if `:on_conflict` is a query, MySQL will return + the number of attempted entries plus the number of entries modified + by the UPDATE query. + + ## Placeholders + + Passing in a map for the `:placeholders` allows you to send less + data over the wire when you have many entries with the same value + for a field. To use a placeholder, replace its value in each of your + entries with `{:placeholder, key}`, where `key` is the key you + are using in the `:placeholders` option map. For example: + + placeholders = %{blob: large_blob_of_text(...)} + + entries = [ + %{title: "v1", body: {:placeholder, :blob}}, + %{title: "v2", body: {:placeholder, :blob}} + ] + + Repo.insert_all(Post, entries, placeholders: placeholders) + + Keep in mind that: + + * placeholders cannot be nested in other values. For example, you + cannot put a placeholder inside an array. Instead, the whole + array has to be the placeholder + + * a placeholder key can only be used with columns of the same type + + * placeholders require a database that supports index parameters, + so they are not currently compatible with MySQL + + """ + @doc group: "Schema API" + @callback insert_all( + schema_or_source :: binary() | {binary(), module()} | module(), + entries_or_query :: + [%{(atom() | String.t()) => value} | Keyword.t(value)] | Ecto.Query.t(), + opts :: Keyword.t() + ) :: {non_neg_integer(), nil | [term()]} + when value: term() | Ecto.Query.t() + + @doc """ + Inserts a struct defined via `Ecto.Schema` or a changeset. + + In case a struct is given, the struct is converted into a changeset + with all non-nil fields as part of the changeset. + + In case a changeset is given, the changes in the changeset are + merged with the struct fields, and all of them are sent to the + database. If more than one database operation is required, they're + automatically wrapped in a transaction. + + It returns `{:ok, struct}` if the struct has been successfully + inserted or `{:error, changeset}` if there was a validation + or a known constraint error. + + ## Options + + * `:returning` - selects which fields to return. It accepts a list + of fields to be returned from the database. When `true`, returns + all fields, including those marked as `load_in_query: false`. When + `false`, no extra fields are returned. It will always include all + fields in `read_after_writes` as well as any autogenerated id. Be + aware that the fields returned from the database overwrite what was + supplied by the user. Any field not returned by the database will be + present with the original value supplied by the user. Not all databases + support this option and it may not be available during upserts. + See the ["Upserts"](`c:insert/2#upserts`) section for more information. + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This overrides the prefix set + in the query and any `@schema_prefix` set on any schemas. Also, the + `@schema_prefix` for the parent record will override all default + `@schema_prefix`s set in any child schemas for associations. + + * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, + `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`, + a keyword list of update instructions or an `Ecto.Query` query for updates. + See the ["Upserts"](`c:insert/2#upserts`) section for more information. + + * `:conflict_target` - A list of column names to verify for conflicts. + It is expected those columns to have unique indexes on them that may conflict. + If none is specified, the conflict target is left up to the database. + It may also be `{:unsafe_fragment, binary_fragment}` to pass any + expression to the database without any sanitization, this is useful + for partial index or index with expressions, such as + `{:unsafe_fragment, "(coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL"}` for + `ON CONFLICT (coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL` SQL query. + + * `:stale_error_field` - The field where stale errors will be added in + the returning changeset. This option can be used to avoid raising + `Ecto.StaleEntryError`. + + * `:stale_error_message` - The message to add to the configured + `:stale_error_field` when stale errors happen, defaults to "is stale". + + * `:allow_stale` - Doesn't error when structs are stale. Defaults to `false`. + This may happen if there are rules or triggers in the database that + rejects the insert operation. This option cascades to associations. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Examples + + A typical example is calling `MyRepo.insert/1` with a struct + and acting on the return value: + + case MyRepo.insert %Post{title: "Ecto is great"} do + {:ok, struct} -> # Inserted with success + {:error, changeset} -> # Something went wrong + end + + ## Upserts + + `c:insert/2` provides upserts (update or inserts) via the `:on_conflict` + option. The `:on_conflict` option supports the following values: + + * `:raise` - raises if there is a conflicting primary key or unique index + + * `:nothing` - ignores the error in case of conflicts + + * `:replace_all` - replace **all** values on the existing row with the values + in the schema/changeset, including fields not explicitly set in the changeset, + such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`). + Do not use this option if you have auto-incrementing primary keys, as they + will also be replaced. You most likely want to use `{:replace_all_except, [:id]}` + or `{:replace, fields}` explicitly instead. This option requires a schema + + * `{:replace_all_except, fields}` - same as above except the given fields are + not replaced. This option requires a schema + + * `{:replace, fields}` - replace only specific columns. This option requires + `:conflict_target` + + * a keyword list of update instructions - such as the one given to + `c:update_all/3`, for example: `[set: [title: "new title"]]` + + * an `Ecto.Query` that will act as an `UPDATE` statement, such as the + one given to `c:update_all/3`. Similarly to `c:update_all/3`, auto + generated values, such as timestamps are not automatically updated. + If the struct cannot be found, `Ecto.StaleEntryError` will be raised. + + Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" + on databases such as MySQL. + + As an example, imagine `:title` is marked as a unique column in + the database: + + {:ok, inserted} = MyRepo.insert(%Post{title: "this is unique"}) + + Now we can insert with the same title but do nothing on conflicts: + + {:ok, ignored} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: :nothing) + + Because we used `on_conflict: :nothing`, instead of getting an error, + we got `{:ok, struct}`. However the returned struct does not reflect + the data in the database. If the primary key is auto-generated by the + database, the primary key in the `ignored` record will be nil if there + was no insertion. For example, if you use the default primary key + (which has name `:id` and a type of `:id`), then `ignored.id` above + will be nil if there was no insertion. + + If your id is generated by your application (typically the case for + `:binary_id`) or if you pass another value for `:on_conflict`, detecting + if an insert or update happened is slightly more complex, as the database + does not actually inform us what happened. Let's insert a post with the + same title but use a query to update the body column in case of conflicts: + + # In Postgres (it requires the conflict target for updates): + on_conflict = [set: [body: "updated"]] + {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, + on_conflict: on_conflict, conflict_target: :title) + + # In MySQL (conflict target is not supported): + on_conflict = [set: [title: "updated"]] + {:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"}, + on_conflict: on_conflict) + + In the examples above, even though it returned `:ok`, we do not know + if we inserted new data or if we updated only the `:on_conflict` fields. + In case an update happened, the data in the struct most likely does + not match the data in the database. For example, autogenerated fields + such as `inserted_at` will point to now rather than the time the + struct was actually inserted. + + If you need to guarantee the data in the returned struct mirrors the + database, you have three options: + + * Use `on_conflict: :replace_all`, although that will replace all + fields in the database with the ones in the struct/changeset, + including autogenerated fields such as `inserted_at` and `updated_at`: + + MyRepo.insert(%Post{title: "this is unique"}, + on_conflict: :replace_all, conflict_target: :title) + + * Specify `read_after_writes: true` in your schema for choosing + fields that are read from the database after every operation. + Or pass `returning: true` to `insert` to read all fields back. + (Note that it will only read from the database if at least one + field is updated). + + MyRepo.insert(%Post{title: "this is unique"}, returning: true, + on_conflict: on_conflict, conflict_target: :title) + + * Alternatively, read the data again from the database in a separate + query. This option requires the primary key to be generated by the + database: + + {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: on_conflict) + Repo.get(Post, updated.id) + + Because of the inability to know if the struct is up to date or not, + inserting a struct with associations and using the `:on_conflict` option + at the same time is not recommended, as Ecto will be unable to actually + track the proper status of the association. + + ## Advanced Upserts + + Using an `Ecto.Query` for `:on_conflict` can allow us to use more advanced + database features. For example, PostgreSQL supports conditional upserts like + `DO UPDATE SET title = EXCLUDED.title, version = EXCLUDED.version + WHERE EXCLUDED.version > post.version`. + This means that the title and version will be updated only if the proposed + row has a greater version value than the existing row. + + Ecto can support this as follows: + + conflict_query = + from(p in Post, + update: [set: [ + title: fragment("EXCLUDED.title"), + version: fragment("EXCLUDED.version") + ]], + where: fragment("EXCLUDED.version > ?", p.version) + ) + + MyRepo.insert( + %Post{id: 1, title: "Ecto Upserts (Dance Remix)", version: 2}, + conflict_target: [:id], + on_conflict: conflict_query + ) + """ + @doc group: "Schema API" + @callback insert( + struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), + opts :: Keyword.t() + ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} + + @doc """ + Updates a changeset using its primary key. + + A changeset is required as it is the only mechanism for + tracking dirty changes. Only the fields present in the `changes` part + of the changeset are sent to the database. Any other, in-memory + changes done to the schema are ignored. If more than one database + operation is required, they're automatically wrapped in a transaction. + + If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError` + will be raised. + + If the struct cannot be found, `Ecto.StaleEntryError` will be raised. + + It returns `{:ok, struct}` if the struct has been successfully + updated or `{:error, changeset}` if there was a validation + or a known constraint error. + + ## Options + + * `:returning` - selects which fields to return. It accepts a list + of fields to be returned from the database. When `true`, returns + all fields, including those marked as `load_in_query: false`. When + `false`, no extra fields are returned. It will always include all + fields in `read_after_writes`. Be aware that the fields returned + from the database overwrite what was supplied by the user. Any field + not returned by the database will be present with the original value + supplied by the user. Not all databases support this option. + + * `:force` - By default, if there are no changes in the changeset, + `c:update/2` is a no-op. By setting this option to true, update + callbacks will always be executed, even if there are no changes + (including timestamps). + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This overrides the prefix set + in the query and any `@schema_prefix` set on any schemas. Also, the + `@schema_prefix` for the parent record will override all default + `@schema_prefix`s set in any child schemas for associations. + + * `:stale_error_field` - The field where stale errors will be added in + the returning changeset. This option can be used to avoid raising + `Ecto.StaleEntryError`. + + * `:stale_error_message` - The message to add to the configured + `:stale_error_field` when stale errors happen, defaults to "is stale". + + * `:allow_stale` - Doesn't error if update is stale. Defaults to `false`. + This may happen if the struct has been deleted from the database before + the update or if there is a rule or a trigger on the database that rejects + the update operation. This option cascades to associations. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + post = MyRepo.get!(Post, 42) + post = Ecto.Changeset.change post, title: "New title" + case MyRepo.update post do + {:ok, struct} -> # Updated with success + {:error, changeset} -> # Something went wrong + end + """ + @doc group: "Schema API" + @callback update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: + {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} + + @doc """ + Inserts or updates a changeset depending on whether the struct is persisted + or not. + + The distinction whether to insert or update will be made on the + `Ecto.Schema.Metadata` field `:state`. The `:state` is automatically set by + Ecto when loading or building a schema. + + Please note that for this to work, you will have to load existing structs from + the database. So even if the struct exists, this won't work: + + struct = %Post{id: "existing_id", ...} + MyRepo.insert_or_update changeset + # => {:error, changeset} # id already exists + + ## Options + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This overrides the prefix set + in the query and any `@schema_prefix` set any schemas. Also, the + `@schema_prefix` for the parent record will override all default + `@schema_prefix`s set in any child schemas for associations. + * `:stale_error_field` - The field where stale errors will be added in + the returning changeset. This option can be used to avoid raising + `Ecto.StaleEntryError`. Only applies to updates. + * `:stale_error_message` - The message to add to the configured + `:stale_error_field` when stale errors happen, defaults to "is stale". + Only applies to updates. + * `:allow_stale` - Doesn't error when structs are stale. Defaults to `false`. + This option cascades to associations. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + result = + case MyRepo.get(Post, id) do + nil -> %Post{id: id} # Post not found, we build one + post -> post # Post exists, let's use it + end + |> Post.changeset(changes) + |> MyRepo.insert_or_update + + case result do + {:ok, struct} -> # Inserted or updated with success + {:error, changeset} -> # Something went wrong + end + """ + @doc group: "Schema API" + @callback insert_or_update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: + {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} + + @doc """ + Deletes a struct using its primary key. + + If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError` + will be raised. If the struct has been removed prior to the call, + `Ecto.StaleEntryError` will be raised. If more than one database + operation is required, they're automatically wrapped in a transaction. + + It returns `{:ok, struct}` if the struct has been successfully + deleted or `{:error, changeset}` if there was a validation + or a known constraint error. By default, constraint errors will + raise the `Ecto.ConstraintError` exception, unless a changeset is + given as the first argument with the relevant constraints declared + in it (see `Ecto.Changeset`). + + ## Options + + * `:returning` - selects which fields to return. It accepts a list + of fields to be returned from the database. When `true`, returns + all fields, including those marked as `load_in_query: false`. When + `false`, no extra fields are returned. It will always include all + fields in `read_after_writes`. Be aware that the fields returned + from the database overwrite what was supplied by the user. Any field + not returned by the database will be present with the original value + supplied by the user. Not all databases support this option. + + * `:prefix` - The prefix to run the query on (such as the schema path + in Postgres or the database in MySQL). This overrides the prefix set + in the query and any `@schema_prefix` set in the schema. + + * `:stale_error_field` - The field where stale errors will be added in + the returning changeset. This option can be used to avoid raising + `Ecto.StaleEntryError`. + + * `:stale_error_message` - The message to add to the configured + `:stale_error_field` when stale errors happen, defaults to "is stale". + + * `:allow_stale` - Doesn't error if delete is stale. Defaults to `false`. + This may happen if the struct has been deleted from the database before + this deletion or if there is a rule or a trigger on the database that rejects + the delete operation. + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + + ## Example + + post = MyRepo.get!(Post, 42) + case MyRepo.delete post do + {:ok, struct} -> # Deleted with success + {:error, changeset} -> # Something went wrong + end + + """ + @doc group: "Schema API" + @callback delete( + struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), + opts :: Keyword.t() + ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} + + @doc """ + Same as `c:insert/2` but returns the struct or raises if the changeset is invalid. + """ + @doc group: "Schema API" + @callback insert!( + struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), + opts :: Keyword.t() + ) :: Ecto.Schema.t() + + @doc """ + Same as `c:update/2` but returns the struct or raises if the changeset is invalid. + """ + @doc group: "Schema API" + @callback update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: + Ecto.Schema.t() + + @doc """ + Same as `c:insert_or_update/2` but returns the struct or raises if the changeset + is invalid. + """ + @doc group: "Schema API" + @callback insert_or_update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: + Ecto.Schema.t() + + @doc """ + Same as `c:delete/2` but returns the struct or raises if the changeset is invalid. + """ + @doc group: "Schema API" + @callback delete!( + struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), + opts :: Keyword.t() + ) :: Ecto.Schema.t() + + ## Ecto.Adapter.Transaction + + @optional_callbacks transaction: 2, in_transaction?: 0, rollback: 1 + + @doc """ + Runs the given function or `Ecto.Multi` inside a transaction. + + ## Use with function + + `c:transaction/2` can be called with both a function of arity + zero or one. The arity zero function will just be executed as is: + + import Ecto.Changeset, only: [change: 2] + + MyRepo.transaction(fn -> + MyRepo.update!(change(alice, balance: alice.balance - 10)) + MyRepo.update!(change(bob, balance: bob.balance + 10)) + end) + + While the arity one function will receive the repo of the transaction + as its first argument: + + MyRepo.transaction(fn repo -> + repo.insert!(%Post{}) + end) + + If an Elixir exception occurs the transaction will be rolled back + and the exception will bubble up from the transaction function. + If no exception occurs, the transaction is committed when the + function returns. A transaction can be explicitly rolled back + by calling `c:rollback/1`, this will immediately leave the function + and return the value given to `rollback` as `{:error, value}`. + + A successful transaction returns the value returned by the function + wrapped in a tuple as `{:ok, value}`. + + ### Nested transactions + + If `c:transaction/2` is called inside another transaction, the function + is simply executed, without wrapping the new transaction call in any + way. If there is an error in the inner transaction and the error is + rescued, or the inner transaction is rolled back, the whole outer + transaction is aborted, guaranteeing nothing will be committed. + + Below is an example of how rollbacks work with nested transactions: + + {:error, :rollback} = + MyRepo.transaction(fn -> + {:error, :posting_not_allowed} = + MyRepo.transaction(fn -> + # This function call causes the following to happen: + # + # * the transaction is rolled back in the database, + # * code execution is stopped within the current function, + # * and the value, passed to `rollback/1` is returned from + # `MyRepo.transaction/1` as the second element in the error + # tuple. + # + MyRepo.rollback(:posting_not_allowed) + + # `rollback/1` stops execution, so code here won't be run + end) + + # The transaction here is now aborted and any further + # operation will raise an exception. + end) + + See the ["Aborted transactions"](`c:transaction/2#aborted-transactions`) section for more examples of aborted + transactions and how to handle them. + + In practice, managing nested transactions can become complex quickly. + For this reason, Ecto provides `Ecto.Multi` for composing transactions. + + ## Use with Ecto.Multi + + `c:transaction/2` also accepts the `Ecto.Multi` struct as first argument. + `Ecto.Multi` allows you to compose transactions operations, step by step, + and manage what happens in case of success or failure. + + When an `Ecto.Multi` is given to this function, a transaction will be started, + all operations applied and in case of success committed returning `{:ok, changes}`: + + # With Ecto.Multi + Ecto.Multi.new() + |> Ecto.Multi.insert(:post, %Post{}) + |> MyRepo.transaction + + In case of any errors the transaction will be rolled back and + `{:error, failed_operation, failed_value, changes_so_far}` will be returned. + + Explore the `Ecto.Multi` documentation to learn more and find detailed examples. + + ## Aborted transactions + + When an operation inside a transaction fails, the transaction is aborted in the database. + For instance, if you attempt an insert that violates a unique constraint, the insert fails + and the transaction is aborted. In such cases, any further operation inside the transaction + will raise exceptions. + + Take the following transaction as an example: + + Repo.transaction(fn repo -> + case repo.insert(changeset) do + {:ok, post} -> + repo.insert(%Status{value: "success"}) + + {:error, changeset} -> + repo.insert(%Status{value: "failure"}) + end + end) + + If the changeset is valid, but the insert operation fails due to a database constraint, + the subsequent `repo.insert(%Status{value: "failure"})` operation will raise an exception + because the database has already aborted the transaction and thus making the operation invalid. + In Postgres, the exception would look like this: + + ** (Postgrex.Error) ERROR 25P02 (in_failed_sql_transaction) current transaction is aborted, commands ignored until end of transaction block + + If the changeset is invalid before it reaches the database due to a validation error, + no statement is sent to the database, an `:error` tuple is returned, and `repo.insert(%Status{value: "failure"})` + operation will execute as usual. + + We have two options to deal with such scenarios: + + If you don't want to change the semantics of your code, you can also use the savepoints + feature by passing the `:mode` option like this: `repo.insert(changeset, mode: :savepoint)`. + In case of an exception, the transaction will rollback to the savepoint and prevent + the transaction from failing. + + Another alternative is to handle this operation outside of the transaction. + For example, you can choose to perform an explicit `repo.rollback` call in the + `{:error, changeset}` clause and then perform the `repo.insert(%Status{value: "failure"})` outside + of the transaction. You might also consider using `Ecto.Multi`, as they automatically + rollback whenever an operation fails. + + ## Working with processes + + The transaction is per process. A separate process started inside a + transaction won't be part of the same transaction and will use a separate + connection altogether. + + When using the `Ecto.Adapters.SQL.Sandbox` in tests, while it may be + possible to share the connection between processes, the parent process + will typically hold the connection until the transaction completes. This + may lead to a deadlock if the child process attempts to use the same connection. + See the docs for + [`Ecto.Adapters.SQL.Sandbox`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html) + for more information. + + ## Options + + See the ["Shared options"](#module-shared-options) section at the module + documentation for more options. + """ + @doc group: "Transaction API" + @callback transaction(fun_or_multi :: fun | Ecto.Multi.t(), opts :: Keyword.t()) :: + {:ok, any} + | {:error, any} + | Ecto.Multi.failure() + + @doc """ + Returns true if the current process is inside a transaction. + + If you are using the `Ecto.Adapters.SQL.Sandbox` in tests, note that even + though each test is inside a transaction, `in_transaction?/0` will only + return true inside transactions explicitly created with `transaction/2`. This + is done so the test environment mimics dev and prod. + + ## Examples + + MyRepo.in_transaction? + #=> false + + MyRepo.transaction(fn -> + MyRepo.in_transaction? #=> true + end) + + """ + @doc group: "Transaction API" + @callback in_transaction?() :: boolean + + @doc """ + Rolls back the current transaction. + + The transaction will return the value given as `{:error, value}`. + + Note that calling `rollback` causes the code in the transaction to stop executing. + """ + @doc group: "Transaction API" + @callback rollback(value :: any) :: no_return +end diff --git a/deps/ecto/lib/ecto/repo/assoc.ex b/deps/ecto/lib/ecto/repo/assoc.ex new file mode 100644 index 0000000000000000000000000000000000000000..e49b316aee91639eb8e8a92e1cb10a2e39d2c3da --- /dev/null +++ b/deps/ecto/lib/ecto/repo/assoc.ex @@ -0,0 +1,131 @@ +defmodule Ecto.Repo.Assoc do + # The module invoked by repo modules + # for association related functionality. + @moduledoc false + + @doc """ + Transforms a result set based on query assocs, loading + the associations onto their parent schema. + """ + @spec query([list], list, tuple, (list -> list)) :: [Ecto.Schema.t] + def query(rows, assocs, sources, fun) + + def query([], _assocs, _sources, _fun), do: [] + def query(rows, [], _sources, fun), do: Enum.map(rows, fun) + + def query(rows, assocs, sources, fun) do + # Create rose tree of accumulator dicts in the same + # structure as the fields tree + accs = create_accs(0, assocs, sources, []) + + # Populate tree of dicts of associated entities from the result set + {_keys, _cache, rows, sub_dicts} = Enum.reduce(rows, accs, fn row, acc -> + merge(fun.(row), acc, 0) |> elem(0) + end) + + # Create the reflections that will be loaded into memory. + refls = create_refls(0, assocs, sub_dicts, sources) + + # Retrieve and load the assocs from cached dictionaries recursively + for {item, sub_structs} <- Enum.reverse(rows) do + [load_assocs(item, refls)|sub_structs] + end + end + + defp merge([struct|sub_structs], {primary_keys, cache, dict, sub_dicts}, parent_key) do + child_key = + if struct do + for primary_key <- primary_keys do + case Map.get(struct, primary_key) do + nil -> raise Ecto.NoPrimaryKeyValueError, struct: struct + value -> value + end + end + end + + # Traverse sub_structs adding one by one to the tree. + # Note we need to traverse even if we don't have a child_key + # due to nested associations. + {sub_dicts, sub_structs} = Enum.map_reduce(sub_dicts, sub_structs, &merge(&2, &1, child_key)) + + cache_key = cache_key(parent_key, child_key, sub_structs, dict) + + if struct && parent_key && not Map.get(cache, cache_key, false) do + cache = Map.put(cache, cache_key, true) + item = {child_key, struct} + + # If we have a list, we are at the root, so we also store the sub structs + dict = update_dict(dict, parent_key, item, sub_structs) + + {{primary_keys, cache, dict, sub_dicts}, sub_structs} + else + {{primary_keys, cache, dict, sub_dicts}, sub_structs} + end + end + + defp cache_key(parent_key, child_key, sub_structs, dict) when is_list(dict) do + {parent_key, child_key, sub_structs} + end + + defp cache_key(parent_key, child_key, _sub_structs, dict) when is_map(dict) do + {parent_key, child_key} + end + + defp update_dict(dict, _parent_key, item, sub_structs) when is_list(dict) do + [{item, sub_structs} | dict] + end + + defp update_dict(dict, parent_key, item, _sub_structs) when is_map(dict) do + Map.update(dict, parent_key, [item], &[item | &1]) + end + + defp load_assocs({child_key, struct}, refls) do + Enum.reduce refls, struct, fn {dict, refl, sub_refls}, acc -> + %{field: field, cardinality: cardinality} = refl + loaded = + dict + |> Map.get(child_key, []) + |> Enum.reverse() + |> Enum.map(&load_assocs(&1, sub_refls)) + |> maybe_first(cardinality) + Map.put(acc, field, loaded) + end + end + + defp maybe_first(list, :one), do: List.first(list) + defp maybe_first(list, _), do: list + + defp create_refls(idx, fields, dicts, sources) do + schema = get_assoc_schema(sources, idx) + + Enum.map(:lists.zip(dicts, fields), fn + {{_primary_keys, _cache, dict, sub_dicts}, {field, {child_idx, child_fields}}} -> + refl = schema.__schema__(:association, field) + sub_refls = create_refls(child_idx, child_fields, sub_dicts, sources) + {dict, refl, sub_refls} + end) + end + + defp create_accs(idx, fields, sources, initial_dict) do + acc = Enum.map(fields, fn {_field, {child_idx, child_fields}} -> + create_accs(child_idx, child_fields, sources, %{}) + end) + + schema = get_assoc_schema(sources, idx) + + case schema.__schema__(:primary_key) do + [] -> raise Ecto.NoPrimaryKeyFieldError, schema: schema + pk -> {pk, %{}, initial_dict, acc} + end + end + + defp get_assoc_schema(sources, idx) do + case elem(sources, idx) do + {_, schema, _} -> + schema + + %Ecto.SubQuery{select: {:source, {_, schema}, _, _}} -> + schema + end + end +end diff --git a/deps/ecto/lib/ecto/repo/preloader.ex b/deps/ecto/lib/ecto/repo/preloader.ex new file mode 100644 index 0000000000000000000000000000000000000000..376decc0b535f01f761d229f9940453e8a10a8c2 --- /dev/null +++ b/deps/ecto/lib/ecto/repo/preloader.ex @@ -0,0 +1,712 @@ +defmodule Ecto.Repo.Preloader do + # The module invoked by user defined repo_names + # for preload related functionality. + @moduledoc false + + require Ecto.Query + require Logger + + alias Ecto.Query.DynamicExpr + + @doc """ + Transforms a result set based on query preloads, loading + the associations onto their parent schema. + """ + @spec query([list], Ecto.Repo.t, list, Access.t, list, fun, {adapter_meta :: map, opts :: Keyword.t}) :: [list] + def query([], _repo_name, _preloads, _take, _assocs, _fun, _tuplet), do: [] + def query(rows, _repo_name, [], _take, _assocs, fun, _tuplet), do: Enum.map(rows, fun) + + def query(rows, repo_name, preloads, take, assocs, fun, tuplet) do + assocs = normalize_query_assocs(assocs) + + rows + |> extract() + |> normalize_and_preload_each(repo_name, preloads, take, assocs, tuplet) + |> unextract(rows, fun) + end + + defp extract([[nil|_]|t2]), do: extract(t2) + defp extract([[h|_]|t2]), do: [h|extract(t2)] + defp extract([]), do: [] + + defp unextract(structs, [[nil|_] = h2|t2], fun), do: [fun.(h2)|unextract(structs, t2, fun)] + defp unextract([h1|structs], [[_|t1]|t2], fun), do: [fun.([h1|t1])|unextract(structs, t2, fun)] + defp unextract([], [], _fun), do: [] + + @doc """ + Implementation for `Ecto.Repo.preload/2`. + """ + @spec preload(structs, atom, atom | list, {adapter_meta :: map, opts :: Keyword.t}) :: + structs when structs: [Ecto.Schema.t] | Ecto.Schema.t | nil + def preload(nil, _repo_name, _preloads, _tuplet) do + nil + end + + def preload(structs, repo_name, preloads, {_adapter_meta, opts} = tuplet) when is_list(structs) do + normalize_and_preload_each(structs, repo_name, preloads, opts[:take], %{}, tuplet) + end + + def preload(struct, repo_name, preloads, {_adapter_meta, opts} = tuplet) when is_map(struct) do + normalize_and_preload_each([struct], repo_name, preloads, opts[:take], %{}, tuplet) |> hd() + end + + defp normalize_and_preload_each( + structs, + repo_name, + preloads, + take, + query_assocs, + {adapter_meta, opts} + ) do + tuplet = {adapter_meta, Keyword.put(opts, :ecto_query, :preload)} + preloads = normalize(preloads, take, preloads) + preload_each(structs, repo_name, preloads, query_assocs, tuplet) + rescue + e -> + # Reraise errors so we ignore the preload inner stacktrace + filter_and_reraise e, __STACKTRACE__ + end + + ## Preloading + + defp preload_each(structs, _repo_name, [], _query_assocs, _tuplet), do: structs + defp preload_each([], _repo_name, _preloads, _query_assocs, _tuplet), do: [] + defp preload_each(structs, repo_name, preloads, query_assocs, tuplet) do + if sample = Enum.find(structs, & &1) do + module = sample.__struct__ + prefix = preload_prefix(tuplet, sample) + {assocs, throughs, embeds} = expand(module, preloads, query_assocs, {%{}, [], []}) + structs = preload_embeds(structs, embeds, repo_name, tuplet) + structs = preload_throughs(structs, throughs, repo_name, query_assocs, tuplet) + + {fetched_assocs, to_fetch_queries} = + prepare_queries(structs, module, assocs, prefix, repo_name, tuplet) + + fetched_queries = maybe_pmap(to_fetch_queries, repo_name, tuplet) + assocs = preload_assocs(fetched_assocs, fetched_queries, repo_name, query_assocs, tuplet) + + for struct <- structs do + struct = Enum.reduce assocs, struct, &load_assoc/2 + struct = Enum.reduce throughs, struct, &load_through/2 + struct + end + else + structs + end + end + + defp preload_prefix({_adapter_meta, opts}, sample) do + case Keyword.fetch(opts, :prefix) do + {:ok, prefix} -> + prefix + + :error -> + case sample do + %{__meta__: %{prefix: prefix}} -> prefix + # Must be an embedded schema + _ -> nil + end + end + end + + ## Association preloading + + # First we traverse all assocs and find which queries we need to run. + defp prepare_queries(structs, module, assocs, prefix, repo_name, tuplet) do + Enum.reduce(assocs, {[], []}, fn + {_key, {{:assoc, assoc, related_key}, take, query, preloads}}, {assocs, queries} -> + {fetch_ids, loaded_ids, loaded_structs} = fetch_ids(structs, module, assoc, tuplet) + + queries = + if fetch_ids != [] do + [ + fn tuplet -> + fetch_query(fetch_ids, assoc, repo_name, query, prefix, related_key, take, tuplet) + end + | queries + ] + else + queries + end + + {[{assoc, fetch_ids != [], loaded_ids, loaded_structs, preloads} | assocs], queries} + end) + end + + # Then we execute queries in parallel + defp maybe_pmap(preloaders, _repo_name, {adapter_meta, opts}) do + if match?([_, _ | _] , preloaders) and not adapter_meta.adapter.checked_out?(adapter_meta) and + Keyword.get(opts, :in_parallel, true) do + # We pass caller: self() so the ownership pool knows where + # to fetch the connection from and set the proper timeouts. + # Note while the ownership pool uses '$callers' from pdict, + # it does not do so in automatic mode, hence this line is + # still necessary. + opts = Keyword.put_new(opts, :caller, self()) + on_preloader_spawn = Keyword.get(opts, :on_preloader_spawn, fn -> :ok end) + + preloaders + |> Task.async_stream(fn preloader -> + on_preloader_spawn.() + preloader.({adapter_meta, opts}) + end, timeout: :infinity) + |> Enum.map(fn + {:ok, assoc} -> assoc + {:exit, reason} -> exit(reason) + end) + else + Enum.map(preloaders, &(&1.({adapter_meta, opts}))) + end + end + + # Then we unpack the query results, merge them, and preload recursively + defp preload_assocs( + [{assoc, query?, loaded_ids, loaded_structs, sub_preloads} | assocs], + queries, + repo_name, + query_assocs, + tuplet + ) do + {fetch_ids, fetch_structs, queries} = maybe_unpack_query(query?, queries) + sub_query_assocs = Map.get(query_assocs, assoc.field, %{}) + all = preload_each(Enum.reverse(loaded_structs, fetch_structs), repo_name, sub_preloads, sub_query_assocs, tuplet) + entry = {:assoc, assoc, assoc_map(assoc.cardinality, Enum.reverse(loaded_ids, fetch_ids), all)} + [entry | preload_assocs(assocs, queries, repo_name, query_assocs, tuplet)] + end + + defp preload_assocs([] = _assocs, [] = _queries, _, _, _), do: [] + + defp preload_embeds(structs, [] = _embeds, _, _), do: structs + + defp preload_embeds(structs, [embed | embeds], repo_name, tuplet) do + {%{field: field, cardinality: card}, sub_preloads} = embed + + {embed_structs, counts} = + Enum.flat_map_reduce(structs, [], fn + %{^field => embeds}, counts when is_list(embeds) -> {embeds, [length(embeds) | counts]} + %{^field => nil}, counts -> {[], [0 | counts]} + %{^field => embed}, counts -> {[embed], [1 | counts]} + nil, counts -> {[], [0 | counts]} + struct, _counts -> raise ArgumentError, "expected #{inspect(struct)} to contain embed `#{field}`" + end) + + # It is not possible for an embed to be preloaded through Ecto.Query.preload + # Therefore, we don't consider associations coming from queries + embed_structs = preload_each(embed_structs, repo_name, sub_preloads, %{}, tuplet) + structs = put_through_or_embed(card, field, structs, embed_structs, Enum.reverse(counts), []) + preload_embeds(structs, embeds, repo_name, tuplet) + end + + defp preload_throughs(structs, [] = _throughs, _, _, _), do: structs + + defp preload_throughs( + structs, + [{_, _, false = _from_query?} | throughs], + repo_name, + query_assocs, + tuplet + ) do + # Through associations will not be preloaded directly unless they were + # loaded through a join using Ecto.Query.preload. When using Ecto.Repo.preload + # or Ecto.Query.preload where the through association is not part of a join, + # the chain of associations making up the through association are preloaded instead. + preload_throughs(structs, throughs, repo_name, query_assocs, tuplet) + end + + defp preload_throughs(structs, [through | throughs], repo_name, query_assocs, tuplet) do + {{_, %{field: field, cardinality: card}, _}, sub_preloads, true} = through + sub_query_assocs = Map.get(query_assocs, field, %{}) + + {through_structs, counts} = + Enum.flat_map_reduce(structs, [], fn + %{^field => throughs}, counts when is_list(throughs) -> {throughs, [length(throughs) | counts]} + %{^field => nil}, counts -> {[], [0 | counts]} + %{^field => through}, counts -> {[through], [1 | counts]} + nil, counts -> {[], [0 | counts]} + struct, _counts -> raise ArgumentError, "expected #{inspect(struct)} to contain through association `#{field}`" + end) + + through_structs = preload_each(through_structs, repo_name, sub_preloads, sub_query_assocs, tuplet) + structs = put_through_or_embed(card, field, structs, through_structs, Enum.reverse(counts), []) + preload_throughs(structs, throughs, repo_name, query_assocs, tuplet) + end + + defp put_through_or_embed(_card, _field, [], [], [], acc), do: Enum.reverse(acc) + + defp put_through_or_embed(card, field, [struct | structs], loaded_structs, [0 | counts], acc), + do: put_through_or_embed(card, field, structs, loaded_structs, counts, [struct | acc]) + + defp put_through_or_embed(:one, field, [struct | structs], [loaded | loaded_structs], [1 | counts], acc), + do: put_through_or_embed(:one, field, structs, loaded_structs, counts, [Map.put(struct, field, loaded) | acc]) + + defp put_through_or_embed(:many, field, [struct | structs], loaded_structs, [count | counts], acc) do + {current_loaded, rest_loaded} = split_n(loaded_structs, count, []) + acc = [Map.put(struct, field, Enum.reverse(current_loaded)) | acc] + put_through_or_embed(:many, field, structs, rest_loaded, counts, acc) + end + + defp maybe_unpack_query(false, queries), do: {[], [], queries} + defp maybe_unpack_query(true, [{ids, structs} | queries]), do: {ids, structs, queries} + + defp fetch_ids(structs, module, assoc, {_adapter_meta, opts}) do + %{field: field, owner_key: owner_key, cardinality: card} = assoc + force? = Keyword.get(opts, :force, false) + + Enum.reduce structs, {[], [], []}, fn + nil, acc -> + acc + struct, {fetch_ids, loaded_ids, loaded_structs} -> + assert_struct!(module, struct) + %{^owner_key => id, ^field => value} = struct + loaded? = Ecto.assoc_loaded?(value) and not force? + + if loaded? and is_nil(id) and not Ecto.Changeset.Relation.empty?(assoc, value) do + Logger.warning """ + association `#{field}` for `#{inspect(module)}` has a loaded value but \ + its association key `#{owner_key}` is nil. This usually means one of: + + * `#{owner_key}` was not selected in a query + * the struct was set with default values for `#{field}` which now you want to override + + If this is intentional, set force: true to disable this warning + """ + end + + cond do + card == :one and loaded? -> + {fetch_ids, [id | loaded_ids], [value | loaded_structs]} + card == :many and loaded? -> + {fetch_ids, [{id, length(value)} | loaded_ids], value ++ loaded_structs} + is_nil(id) -> + {fetch_ids, loaded_ids, loaded_structs} + true -> + {[id | fetch_ids], loaded_ids, loaded_structs} + end + end + end + + defp fetch_query(ids, assoc, _repo_name, query, _prefix, related_key, _take, _tuplet) + when is_function(query, 1) or is_function(query, 2) do + # Note we use an explicit sort because we don't want + # to reorder based on the struct. Only the ID. + ids + |> Enum.uniq() + |> preload_function(assoc, query) + |> fetched_records_to_tuple_ids(assoc, related_key) + |> Enum.sort(fn {id1, _}, {id2, _} -> id1 <= id2 end) + |> unzip_ids([], []) + end + + defp fetch_query(ids, %{cardinality: card} = assoc, repo_name, query, prefix, related_key, take, tuplet) do + query = assoc.__struct__.assoc_query(assoc, query, Enum.uniq(ids)) + related_field_ast = related_key_to_field(query, related_key) + + # Normalize query + query = %{Ecto.Query.Planner.ensure_select(query, take || true) | prefix: prefix} + + # Add the related key to the query results + query = update_in query.select.expr, &{:{}, [], [related_field_ast, &1]} + + # If we are returning many results, we must sort by the key too + query = + case {card, query.combinations} do + {:many, [{kind, _} | []]} -> + raise ArgumentError, + "`#{kind}` queries must be wrapped inside of a subquery " <> + "when preloading a `has_many` or `many_to_many` association. " <> + "You must also ensure that all members of the `#{kind}` query " <> + "select the parent's foreign key" + + {:many, _} -> + query = add_preload_order(assoc.preload_order, query) + + update_in query.order_bys, fn order_bys -> + [%Ecto.Query.ByExpr{expr: [asc: related_field_ast], params: [], + file: __ENV__.file, line: __ENV__.line}|order_bys] + end + + {:one, _} -> + query + end + + unzip_ids Ecto.Repo.Queryable.all(repo_name, query, tuplet), [], [] + end + + defp preload_function(ids, _assoc, query) when is_function(query, 1), do: query.(ids) + defp preload_function(ids, assoc, query) when is_function(query, 2), do: query.(ids, assoc) + + defp fetched_records_to_tuple_ids([], _assoc, _related_key), + do: [] + + defp fetched_records_to_tuple_ids([%{} | _] = entries, _assoc, {0, key}), + do: Enum.map(entries, &{Map.fetch!(&1, key), &1}) + + defp fetched_records_to_tuple_ids([{_, %{}} | _] = entries, _assoc, _related_key), + do: entries + + defp fetched_records_to_tuple_ids([entry | _], assoc, _), + do: raise """ + invalid custom preload for `#{assoc.field}` on `#{inspect assoc.owner}`. + + For many_to_many associations, the custom function given to preload should \ + return a tuple with the associated key as first element and the struct as \ + second element. + + For example, imagine posts has many to many tags through a posts_tags table. \ + When preloading the tags, you may write: + + custom_tags = fn post_ids -> + Repo.all( + from t in Tag, + join: pt in "posts_tags", + where: t.custom and pt.post_id in ^post_ids and pt.tag_id == t.id + ) + end + + from Post, preload: [tags: ^custom_tags] + + Unfortunately the query above is not enough because Ecto won't know how to \ + associate the posts with the tags. In those cases, you need to return a tuple \ + with the `post_id` as first element and the tag struct as second. The new query \ + will have a select field as follows: + + from t in Tag, + join: pt in "posts_tags", + where: t.custom and pt.post_id in ^post_ids and pt.tag_id == t.id, + select: {pt.post_id, t} + + Expected a tuple with ID and struct, got: #{inspect(entry)} + """ + + defp related_key_to_field(query, {pos, key, field_type}) do + field_ast = related_key_to_field(query, {pos, key}) + + {:type, [], [field_ast, field_type]} + end + + defp related_key_to_field(query, {pos, key}) do + {{:., [], [{:&, [], [related_key_pos(query, pos)]}, key]}, [], []} + end + + defp related_key_pos(_query, pos) when pos >= 0, do: pos + defp related_key_pos(query, pos), do: Ecto.Query.Builder.count_binds(query) + pos + + defp add_preload_order([], query), do: query + + defp add_preload_order(order, query) when is_list(order) do + Ecto.Query.prepend_order_by(query, [q], ^order) + end + + defp add_preload_order({m, f, a}, query) do + order = + case apply(m, f, a) do + order when is_list(order) -> + order + + other -> + raise ArgumentError, + "`:preload_order` must resolve to a keyword list or a list of atoms/fields, " <> + "got: `#{inspect(other)}`" + end + + Enum.each(order, fn + {direction, field} when is_atom(field) or is_struct(field, DynamicExpr) -> + unless Ecto.Query.Builder.OrderBy.valid_direction?(direction) do + raise ArgumentError, + "`:preload_order` must specify valid directions, " <> + "got: `#{inspect(order)}`, `#{inspect(direction)}` is not a valid direction" + end + + :ok + + field when is_atom(field) or is_struct(field, DynamicExpr) -> + :ok + + other -> + raise ArgumentError, + "`:preload_order` must resolve to a keyword list or a list of atoms/fields, " <> + "got: `#{inspect(order)}`, `#{inspect(other)}` is not valid" + end) + + add_preload_order(order, query) + end + + defp unzip_ids([{k, v}|t], acc1, acc2), do: unzip_ids(t, [k|acc1], [v|acc2]) + defp unzip_ids([], acc1, acc2), do: {acc1, acc2} + + defp assert_struct!(mod, %{__struct__: mod}), do: true + defp assert_struct!(mod, %{__struct__: struct}) do + raise ArgumentError, "expected a homogeneous list containing the same struct, " <> + "got: #{inspect mod} and #{inspect struct}" + end + + defp assoc_map(:one, ids, structs) do + one_assoc_map(ids, structs, %{}) + end + defp assoc_map(:many, ids, structs) do + many_assoc_map(ids, structs, %{}) + end + + defp one_assoc_map([id|ids], [struct|structs], map) do + one_assoc_map(ids, structs, Map.put(map, id, struct)) + end + defp one_assoc_map([], [], map) do + map + end + + defp many_assoc_map([{id, n}|ids], structs, map) do + {acc, structs} = split_n(structs, n, []) + many_assoc_map(ids, structs, Map.put(map, id, acc)) + end + defp many_assoc_map([id|ids], [struct|structs], map) do + {ids, structs, acc} = split_while(ids, structs, id, [struct]) + many_assoc_map(ids, structs, Map.put(map, id, acc)) + end + defp many_assoc_map([], [], map) do + map + end + + defp split_n(structs, 0, acc), do: {acc, structs} + defp split_n([struct | structs], n, acc), do: split_n(structs, n - 1, [struct | acc]) + + defp split_while([id|ids], [struct|structs], id, acc), + do: split_while(ids, structs, id, [struct|acc]) + defp split_while(ids, structs, _id, acc), + do: {ids, structs, acc} + + ## Load preloaded data + + defp load_assoc({:assoc, _assoc, _ids}, nil) do + nil + end + + defp load_assoc({:assoc, assoc, ids}, struct) do + %{field: field, owner_key: owner_key, cardinality: cardinality} = assoc + key = Map.fetch!(struct, owner_key) + + loaded = + case ids do + %{^key => value} -> value + _ when cardinality == :many -> [] + _ -> nil + end + + Map.put(struct, field, loaded) + end + + defp load_through({_, _, _}, nil), do: nil + defp load_through({_, _, true = _from_query?}, struct), do: struct + + defp load_through({{:through, assoc, throughs}, _, false = _from_query?}, struct) do + %{cardinality: cardinality, field: field, owner: owner} = assoc + {loaded, _} = Enum.reduce(throughs, {[struct], owner}, &recur_through/2) + Map.put(struct, field, maybe_first(loaded, cardinality)) + end + + defp maybe_first(list, :one), do: List.first(list) + defp maybe_first(list, _), do: list + + defp recur_through(field, {structs, owner}) do + assoc = owner.__schema__(:association, field) + case assoc.__struct__.preload_info(assoc) do + {:assoc, %{related: related}, _} -> + pk_fields = + related.__schema__(:primary_key) + |> validate_has_pk_field!(related, assoc) + + {children, _} = + Enum.reduce(structs, {[], %{}}, fn struct, acc -> + struct + |> Map.fetch!(field) + |> List.wrap() + |> Enum.reduce(acc, fn child, {fresh, set} -> + pk_values = + child + |> through_pks(pk_fields, assoc) + |> validate_non_null_pk!(child, pk_fields, assoc) + + case set do + %{^pk_values => true} -> + {fresh, set} + _ -> + {[child|fresh], Map.put(set, pk_values, true)} + end + end) + end) + + {Enum.reverse(children), related} + + {:through, _, through} -> + Enum.reduce(through, {structs, owner}, &recur_through/2) + end + end + + defp validate_has_pk_field!([], related, assoc) do + raise ArgumentError, + "cannot preload through association `#{assoc.field}` on " <> + "`#{inspect assoc.owner}`. Ecto expected the #{inspect related} schema " <> + "to have at least one primary key field" + end + + defp validate_has_pk_field!(pk_fields, _related, _assoc), do: pk_fields + + defp through_pks(map, pks, assoc) do + Enum.map(pks, fn pk -> + case map do + %{^pk => value} -> + value + + _ -> + raise ArgumentError, + "cannot preload through association `#{assoc.field}` on " <> + "`#{inspect assoc.owner}`. Ecto expected a map/struct with " <> + "the key `#{pk}` but got: #{inspect map}" + end + end) + end + + defp validate_non_null_pk!(values, map, pks, assoc) do + case values do + [nil | _] -> + raise ArgumentError, + "cannot preload through association `#{assoc.field}` on " <> + "`#{inspect assoc.owner}` because the primary key `#{hd(pks)}` " <> + "is nil for map/struct: #{inspect map}" + + _ -> + values + end + end + + ## Normalizer + + def normalize(preload, take, original) do + normalize_each(wrap(preload, original), [], take, original) + end + + defp normalize_each({atom, {query, list}}, acc, take, original) + when is_atom(atom) and (is_map(query) or is_function(query, 1) or is_function(query, 2)) do + fields = take(take, atom) + [{atom, {fields, query!(query), normalize_each(wrap(list, original), [], fields, original)}}|acc] + end + + defp normalize_each({atom, query}, acc, take, _original) + when is_atom(atom) and (is_map(query) or is_function(query, 1) or is_function(query, 2)) do + [{atom, {take(take, atom), query!(query), []}}|acc] + end + + defp normalize_each({atom, list}, acc, take, original) when is_atom(atom) do + fields = take(take, atom) + [{atom, {fields, nil, normalize_each(wrap(list, original), [], fields, original)}}|acc] + end + + defp normalize_each(atom, acc, take, _original) when is_atom(atom) do + [{atom, {take(take, atom), nil, []}}|acc] + end + + defp normalize_each(other, acc, take, original) do + Enum.reduce(wrap(other, original), acc, &normalize_each(&1, &2, take, original)) + end + + defp query!(query) when is_function(query, 1), do: query + defp query!(query) when is_function(query, 2), do: query + defp query!(%Ecto.Query{} = query), do: query + + defp take(take, field) do + case Access.fetch(take, field) do + {:ok, fields} -> List.wrap(fields) + :error -> nil + end + end + + defp wrap(list, _original) when is_list(list), + do: list + defp wrap(atom, _original) when is_atom(atom), + do: atom + defp wrap(other, original) do + raise ArgumentError, "invalid preload `#{inspect other}` in `#{inspect original}`. " <> + "preload expects an atom, a (nested) keyword or a (nested) list of atoms" + end + + defp normalize_query_assocs([]), do: %{} + + defp normalize_query_assocs(assocs) when is_list(assocs) do + Enum.reduce(assocs, %{}, &normalize_each_query_assoc(&1, &2)) + end + + defp normalize_each_query_assoc({field, {_idx, sub_assocs}}, acc) do + Map.put(acc, field, normalize_query_assocs(sub_assocs)) + end + + ## Expand + + def expand(schema, preloads, query_assocs, acc) do + Enum.reduce(preloads, acc, fn {preload, {fields, query, sub_preloads}}, + {assocs, throughs, embeds} -> + assoc_or_embed = association_or_embed!(schema, preload) + + info = assoc_or_embed.__struct__.preload_info(assoc_or_embed) + + case info do + {:assoc, _, _} -> + value = {info, fields, query, sub_preloads} + assocs = Map.update(assocs, preload, value, &merge_preloads(preload, value, &1)) + {assocs, throughs, embeds} + + {:through, _, through} -> + case query_assocs do + %{^preload => _} -> + {assocs, [{info, sub_preloads, true} | throughs], embeds} + + _ -> + {_, _, through} = + through + |> Enum.reverse() + |> Enum.reduce({fields, query, sub_preloads}, &{nil, nil, [{&1, &2}]}) + + expand(schema, through, query_assocs, {assocs, [{info, sub_preloads, false} | throughs], embeds}) + end + + :embed -> + if sub_preloads == [] do + raise ArgumentError, + "cannot preload embedded field #{inspect(assoc_or_embed.field)} " <> + "without also preloading one of its associations as it has no effect" + end + + embeds = [{assoc_or_embed, sub_preloads} | embeds] + {assocs, throughs, embeds} + end + end) + end + + defp merge_preloads(_preload, {info, _, nil, left}, {info, take, query, right}), + do: {info, take, query, left ++ right} + defp merge_preloads(_preload, {info, take, query, left}, {info, _, nil, right}), + do: {info, take, query, left ++ right} + defp merge_preloads(preload, {info, _, left, _}, {info, _, right, _}) do + raise ArgumentError, "cannot preload `#{preload}` as it has been supplied more than once " <> + "with different queries: #{inspect left} and #{inspect right}" + end + + defp association_or_embed!(schema, preload) do + schema.__schema__(:association, preload) || schema.__schema__(:embed, preload) || + raise ArgumentError, "schema #{inspect schema} does not have association or embed #{inspect preload}#{maybe_module(preload)}" + end + + defp maybe_module(assoc) do + case Atom.to_string(assoc) do + "Elixir." <> _ -> + " (if you were trying to pass a schema as a query to preload, " <> + "you have to explicitly convert it to a query by doing `from x in #{inspect assoc}` " <> + "or by calling Ecto.Queryable.to_query/1)" + + _ -> + "" + end + end + + defp filter_and_reraise(exception, stacktrace) do + reraise exception, Enum.reject(stacktrace, &match?({__MODULE__, _, _, _}, &1)) + end +end diff --git a/deps/ecto/lib/ecto/repo/queryable.ex b/deps/ecto/lib/ecto/repo/queryable.ex new file mode 100644 index 0000000000000000000000000000000000000000..f3caf32db8ead6ee3805afc45a45e4947f292a41 --- /dev/null +++ b/deps/ecto/lib/ecto/repo/queryable.ex @@ -0,0 +1,600 @@ +defmodule Ecto.Repo.Queryable do + @moduledoc false + + alias Ecto.Queryable + alias Ecto.Query + alias Ecto.Query.Planner + alias Ecto.Query.SelectExpr + + import Ecto.Query.Planner, only: [attach_prefix: 2] + + require Ecto.Query + + def all(name, queryable, tuplet) do + query = + queryable + |> Ecto.Queryable.to_query() + |> Ecto.Query.Planner.ensure_select(true) + + execute(:all, name, query, tuplet) |> elem(1) + end + + def stream(_name, queryable, {adapter_meta, opts}) do + %{adapter: adapter, cache: cache, repo: repo} = adapter_meta + + query = + queryable + |> Ecto.Queryable.to_query() + |> Ecto.Query.Planner.ensure_select(true) + + {query, opts} = repo.prepare_query(:stream, query, opts) + query = attach_prefix(query, opts) + + {query_meta, prepared, cast_params, dump_params} = + Planner.query(query, :all, cache, adapter, 0) + + opts = [cast_params: cast_params] ++ opts + + case query_meta do + %{select: nil} -> + adapter_meta + |> adapter.stream(query_meta, prepared, dump_params, opts) + |> Stream.flat_map(fn {_, nil} -> [] end) + + %{select: select, preloads: preloads} -> + %{ + assocs: assocs, + preprocess: preprocess, + postprocess: postprocess, + take: take, + from: from + } = select + + if preloads != [] or assocs != [] do + raise Ecto.QueryError, query: query, message: "preloads are not supported on streams" + end + + preprocessor = preprocessor(from, preprocess, adapter) + stream = adapter.stream(adapter_meta, query_meta, prepared, dump_params, opts) + postprocessor = postprocessor(from, postprocess, take, adapter) + + stream + |> Stream.flat_map(fn {_, rows} -> rows end) + |> Stream.map(preprocessor) + |> Stream.map(postprocessor) + end + end + + def get(name, queryable, id, opts) do + one(name, query_for_get(queryable, id), opts) + end + + def get!(name, queryable, id, opts) do + one!(name, query_for_get(queryable, id), opts) + end + + def get_by(name, queryable, clauses, opts) do + one(name, query_for_get_by(queryable, clauses), opts) + end + + def get_by!(name, queryable, clauses, opts) do + one!(name, query_for_get_by(queryable, clauses), opts) + end + + def reload(name, [head | _] = structs, opts) when is_list(structs) do + results = all(name, query_for_reload(structs), opts) + + [pk] = head.__struct__.__schema__(:primary_key) + + for struct <- structs do + struct_pk = Map.fetch!(struct, pk) + Enum.find(results, &(Map.fetch!(&1, pk) == struct_pk)) + end + end + + def reload(name, struct, opts) do + one(name, query_for_reload([struct]), opts) + end + + def reload!(name, [head | _] = structs, opts) when is_list(structs) do + query = query_for_reload(structs) + results = all(name, query, opts) + + [pk] = head.__struct__.__schema__(:primary_key) + + for struct <- structs do + struct_pk = Map.fetch!(struct, pk) + + Enum.find(results, &(Map.fetch!(&1, pk) == struct_pk)) || + raise "could not reload #{inspect(struct)}, maybe it doesn't exist or was deleted" + end + end + + def reload!(name, struct, opts) do + query = query_for_reload([struct]) + one!(name, query, opts) + end + + def aggregate(name, queryable, aggregate, opts) do + one!(name, query_for_aggregate(queryable, aggregate), opts) + end + + def aggregate(name, queryable, aggregate, field, opts) do + one!(name, query_for_aggregate(queryable, aggregate, field), opts) + end + + def exists?(name, queryable, opts) do + queryable = + Query.exclude(queryable, :select) + |> Query.exclude(:preload) + |> Query.exclude(:order_by) + |> Query.exclude(:distinct) + |> Query.select(1) + |> Query.limit(1) + |> rewrite_combinations() + + case all(name, queryable, opts) do + [1] -> true + [] -> false + end + end + + defp rewrite_combinations(%{combinations: []} = query), do: query + + defp rewrite_combinations(%{combinations: combinations} = query) do + combinations = + Enum.map(combinations, fn {type, query} -> + {type, query |> Query.exclude(:select) |> Query.select(1)} + end) + + %{query | combinations: combinations} + end + + def one(name, queryable, tuplet) do + case all(name, queryable, tuplet) do + [one] -> one + [] -> nil + other -> raise Ecto.MultipleResultsError, queryable: queryable, count: length(other) + end + end + + def one!(name, queryable, tuplet) do + case all(name, queryable, tuplet) do + [one] -> one + [] -> raise Ecto.NoResultsError, queryable: queryable + other -> raise Ecto.MultipleResultsError, queryable: queryable, count: length(other) + end + end + + def update_all(name, queryable, [], tuplet) do + update_all(name, queryable, tuplet) + end + + def update_all(name, queryable, updates, tuplet) do + query = Query.from(queryable, update: ^updates) + update_all(name, query, tuplet) + end + + defp update_all(name, queryable, tuplet) do + query = Ecto.Queryable.to_query(queryable) + execute(:update_all, name, query, tuplet) + end + + def delete_all(name, queryable, tuplet) do + query = Ecto.Queryable.to_query(queryable) + execute(:delete_all, name, query, tuplet) + end + + @doc """ + Load structs from query. + """ + def struct_load!([{field, type} | types], [value | values], acc, all_nil?, struct, adapter) do + all_nil? = all_nil? and value == nil + value = load!(type, value, field, struct, adapter) + struct_load!(types, values, [{field, value} | acc], all_nil?, struct, adapter) + end + + def struct_load!([], values, _acc, true, _struct, _adapter) do + {nil, values} + end + + def struct_load!([], values, acc, false, struct, _adapter) do + {Map.merge(struct, Map.new(acc)), values} + end + + ## Helpers + + defp execute(operation, name, query, {adapter_meta, opts} = tuplet) do + %{adapter: adapter, cache: cache, repo: repo} = adapter_meta + + {query, opts} = repo.prepare_query(operation, query, opts) + query = attach_prefix(query, opts) + + {query_meta, prepared, cast_params, dump_params} = + Planner.query(query, operation, cache, adapter, 0) + + opts = [cast_params: cast_params] ++ opts + + case query_meta do + %{select: nil} -> + adapter.execute(adapter_meta, query_meta, prepared, dump_params, opts) + + %{select: select, sources: sources, preloads: preloads} -> + %{ + preprocess: preprocess, + postprocess: postprocess, + take: take, + assocs: assocs, + from: from + } = select + + preprocessor = preprocessor(from, preprocess, adapter) + {count, rows} = adapter.execute(adapter_meta, query_meta, prepared, dump_params, opts) + postprocessor = postprocessor(from, postprocess, take, adapter) + + {count, + rows + |> Ecto.Repo.Assoc.query(assocs, sources, preprocessor) + |> Ecto.Repo.Preloader.query(name, preloads, take, assocs, postprocessor, tuplet)} + end + end + + defp preprocessor({_, {:source, {source, schema}, prefix, types}}, preprocess, adapter) do + struct = Ecto.Schema.Loader.load_struct(schema, prefix, source) + + fn row -> + {entry, rest} = struct_load!(types, row, [], false, struct, adapter) + preprocess(rest, preprocess, entry, adapter) + end + end + + defp preprocessor({_, from}, preprocess, adapter) do + fn row -> + {entry, rest} = process(row, from, nil, adapter) + preprocess(rest, preprocess, entry, adapter) + end + end + + defp preprocessor(:none, preprocess, adapter) do + fn row -> + preprocess(row, preprocess, nil, adapter) + end + end + + defp preprocess(row, [], _from, _adapter) do + row + end + + defp preprocess(row, [source | sources], from, adapter) do + {entry, rest} = process(row, source, from, adapter) + [entry | preprocess(rest, sources, from, adapter)] + end + + defp postprocessor({:any, _}, postprocess, _take, adapter) do + fn [from | row] -> + row |> process(postprocess, from, adapter) |> elem(0) + end + end + + defp postprocessor({:map, _}, postprocess, take, adapter) do + fn [from | row] -> + row |> process(postprocess, to_map(from, take), adapter) |> elem(0) + end + end + + defp postprocessor(:none, postprocess, _take, adapter) do + fn row -> row |> process(postprocess, nil, adapter) |> elem(0) end + end + + defp process(row, {:source, :from}, from, _adapter) do + {from, row} + end + + defp process(row, {:source, {source, schema}, prefix, types}, _from, adapter) do + struct = Ecto.Schema.Loader.load_struct(schema, prefix, source) + struct_load!(types, row, [], true, struct, adapter) + end + + defp process(row, {:source, :values, _prefix, types}, _from, adapter) do + values_list_load!(types, row, [], true, adapter) + end + + defp process(row, {:merge, left, right}, from, adapter) do + {left, row} = process(row, left, from, adapter) + {right, row} = process(row, right, from, adapter) + + data = + case {left, right} do + {%{__struct__: s}, %{__struct__: s}} -> + Map.merge(left, right) + + {%{__struct__: left_struct}, %{__struct__: right_struct}} -> + raise ArgumentError, + "cannot merge structs of different types, " <> + "got: #{inspect(left_struct)} and #{inspect(right_struct)}" + + {%{__struct__: name}, %{}} -> + for {key, _} <- right, not Map.has_key?(left, key) do + raise ArgumentError, "struct #{inspect(name)} does not have the key #{inspect(key)}" + end + + Map.merge(left, right) + + {%{}, %{}} -> + Map.merge(left, right) + + {%{}, nil} -> + left + + {_, %{}} -> + raise ArgumentError, + "cannot merge because the left side is not a map, got: #{inspect(left)}" + + {%{}, _} -> + raise ArgumentError, + "cannot merge because the right side is not a map, got: #{inspect(right)}" + end + + {data, row} + end + + defp process(row, {:struct, struct, data, args}, from, adapter) do + case process(row, data, from, adapter) do + {%{__struct__: ^struct} = data, row} -> + process_update(data, args, row, from, adapter) + + {data, _row} -> + raise BadStructError, struct: struct, term: data + end + end + + defp process(row, {:struct, struct, args}, from, adapter) do + {fields, row} = process_kv(args, row, from, adapter) + + case Map.merge(struct.__struct__(), Map.new(fields)) do + %{__meta__: %Ecto.Schema.Metadata{state: state} = metadata} = struct + when state != :loaded -> + {Map.replace!(struct, :__meta__, %{metadata | state: :loaded}), row} + + map -> + {map, row} + end + end + + defp process(row, {:map, data, args}, from, adapter) do + {data, row} = process(row, data, from, adapter) + process_update(data, args, row, from, adapter) + end + + defp process(row, {:map, args}, from, adapter) do + {args, row} = process_kv(args, row, from, adapter) + {Map.new(args), row} + end + + defp process(row, {:list, args}, from, adapter) do + process_args(args, row, from, adapter) + end + + defp process(row, {:tuple, args}, from, adapter) do + {args, row} = process_args(args, row, from, adapter) + {List.to_tuple(args), row} + end + + defp process([value | row], {:value, :any}, _from, _adapter) do + {value, row} + end + + defp process([value | row], {:value, type}, _from, adapter) do + {load!(type, value, nil, nil, adapter), row} + end + + defp process(row, value, _from, _adapter) + when is_binary(value) or is_number(value) or is_atom(value) do + {value, row} + end + + defp process_update(nil, args, row, from, adapter) do + {_args, row} = process_kv(args, row, from, adapter) + {nil, row} + end + + defp process_update(data, args, row, from, adapter) do + {args, row} = process_kv(args, row, from, adapter) + data = Enum.reduce(args, data, fn {key, value}, acc -> %{acc | key => value} end) + {data, row} + end + + defp process_args(args, row, from, adapter) do + Enum.map_reduce(args, row, fn arg, row -> + process(row, arg, from, adapter) + end) + end + + defp process_kv(kv, row, from, adapter) do + Enum.map_reduce(kv, row, fn {key, value}, row -> + {key, row} = process(row, key, from, adapter) + {value, row} = process(row, value, from, adapter) + {{key, value}, row} + end) + end + + @compile {:inline, load!: 5} + defp load!(type, value, field, struct, adapter) do + case Ecto.Type.adapter_load(adapter, type, value) do + {:ok, value} -> + value + + :error -> + field = field && " for field #{inspect(field)}" + struct = struct && " in #{inspect(struct)}" + + raise ArgumentError, + "cannot load `#{inspect(value)}` as type #{Ecto.Type.format(type)}#{field}#{struct}" + end + end + + defp values_list_load!([{field, type} | types], [value | values], acc, all_nil?, adapter) do + all_nil? = all_nil? and value == nil + value = load!(type, value, field, nil, adapter) + values_list_load!(types, values, [{field, value} | acc], all_nil?, adapter) + end + + defp values_list_load!([], values, _acc, true, _adapter) do + {nil, values} + end + + defp values_list_load!([], values, acc, false, _adapter) do + {Map.new(acc), values} + end + + defp to_map(nil, _fields) do + nil + end + + defp to_map(value, fields) when is_list(value) do + Enum.map(value, &to_map(&1, fields)) + end + + defp to_map(value, fields) do + for field <- fields, into: %{} do + case field do + {k, v} -> {k, to_map(Map.fetch!(value, k), List.wrap(v))} + k -> {k, Map.fetch!(value, k)} + end + end + end + + defp query_for_get(_queryable, nil) do + raise ArgumentError, "cannot perform Ecto.Repo.get/2 because the given value is nil" + end + + defp query_for_get(queryable, id) do + query = Queryable.to_query(queryable) + schema = assert_schema!(query) + + case schema.__schema__(:primary_key) do + [pk] -> + Query.from(x in query, where: field(x, ^pk) == ^id) + + pks -> + raise ArgumentError, + "Ecto.Repo.get/2 requires the schema #{inspect(schema)} " <> + "to have exactly one primary key, got: #{inspect(pks)}" + end + end + + defp query_for_get_by(queryable, clauses) do + Query.where(queryable, [], ^Enum.to_list(clauses)) + end + + defp query_for_reload([head | _] = structs) do + assert_structs!(structs) + + schema = head.__struct__ + %{prefix: prefix, source: source} = head.__meta__ + + case schema.__schema__(:primary_key) do + [pk] -> + keys = Enum.map(structs, &get_pk!(&1, pk)) + query = Query.from(x in {source, schema}, where: field(x, ^pk) in ^keys) + %{query | prefix: prefix} + + pks -> + raise ArgumentError, + "Ecto.Repo.reload/2 requires the schema #{inspect(schema)} " <> + "to have exactly one primary key, got: #{inspect(pks)}" + end + end + + defp query_for_aggregate(queryable, aggregate) do + query = + case prepare_for_aggregate(queryable) do + %{distinct: nil, limit: nil, offset: nil, combinations: []} = query -> + %{query | order_bys: []} + + %{prefix: prefix} = query -> + query = + query + |> Query.subquery() + |> Queryable.Ecto.SubQuery.to_query() + + %{query | prefix: prefix} + end + + select = %SelectExpr{expr: {aggregate, [], []}, file: __ENV__.file, line: __ENV__.line} + %{query | select: select} + end + + defp query_for_aggregate(queryable, aggregate, field) do + ast = field(0, field) + + query = + case prepare_for_aggregate(queryable) do + %{distinct: nil, limit: nil, offset: nil, combinations: []} = query -> + %{query | order_bys: []} + + %{prefix: prefix} = query -> + select = %SelectExpr{expr: ast, file: __ENV__.file, line: __ENV__.line} + + query = + %{query | select: select} + |> Query.subquery() + |> Queryable.Ecto.SubQuery.to_query() + + %{query | prefix: prefix} + end + + select = %SelectExpr{expr: {aggregate, [], [ast]}, file: __ENV__.file, line: __ENV__.line} + %{query | select: select} + end + + defp prepare_for_aggregate(queryable) do + case %{Queryable.to_query(queryable) | preloads: [], assocs: []} do + %{group_bys: [_ | _]} = query -> + raise Ecto.QueryError, message: "cannot aggregate on query with group_by", query: query + + %{} = query -> + query + end + end + + defp field(ix, field) when is_integer(ix) and is_atom(field) do + {{:., [], [{:&, [], [ix]}, field]}, [], []} + end + + defp assert_schema!(%{from: %{source: {_source, schema}}}) when schema != nil, do: schema + + defp assert_schema!(query) do + raise Ecto.QueryError, + query: query, + message: "expected a from expression with a schema" + end + + defp assert_structs!([head | _] = structs) when is_list(structs) do + unless Enum.all?(structs, &schema?/1) do + raise ArgumentError, "expected a struct or a list of structs, received #{inspect(structs)}" + end + + unless Enum.all?(structs, &(&1.__struct__ == head.__struct__)) do + raise ArgumentError, "expected an homogeneous list, received different struct types" + end + + :ok + end + + defp schema?(%{__meta__: _}), do: true + defp schema?(_), do: false + + defp get_pk!(struct, pk) do + struct + |> Map.fetch!(pk) + |> case do + nil -> + raise ArgumentError, + "Ecto.Repo.reload/2 expects existent structs, found a `nil` primary key" + + key -> + key + end + end +end diff --git a/deps/ecto/lib/ecto/repo/registry.ex b/deps/ecto/lib/ecto/repo/registry.ex new file mode 100644 index 0000000000000000000000000000000000000000..88f9cd3bc8b910932df66bbd6c439ca844603b19 --- /dev/null +++ b/deps/ecto/lib/ecto/repo/registry.ex @@ -0,0 +1,51 @@ +defmodule Ecto.Repo.Registry do + @moduledoc false + + use GenServer + + def start_link(_opts) do + GenServer.start_link(__MODULE__, :ok, name: __MODULE__) + end + + def associate(pid, name, value) when is_pid(pid) do + GenServer.call(__MODULE__, {:associate, pid, name, value}) + end + + def all_running() do + for [pid, name] <- :ets.match(__MODULE__, {:"$1", :_, :"$2", :_}) do + name || pid + end + end + + def lookup(repo) when is_atom(repo) do + GenServer.whereis(repo) + |> Kernel.||(raise "could not lookup Ecto repo #{inspect repo} because it was not started or it does not exist") + |> lookup() + end + + def lookup(pid) when is_pid(pid) do + :ets.lookup_element(__MODULE__, pid, 4) + end + + ## Callbacks + + @impl true + def init(:ok) do + table = :ets.new(__MODULE__, [:named_table, read_concurrency: true]) + {:ok, table} + end + + @impl true + def handle_call({:associate, pid, name, value}, _from, table) do + ref = Process.monitor(pid) + true = :ets.insert(table, {pid, ref, name, value}) + {:reply, :ok, table} + end + + @impl true + def handle_info({:DOWN, ref, _type, pid, _reason}, table) do + [{^pid, ^ref, _, _}] = :ets.lookup(table, pid) + :ets.delete(table, pid) + {:noreply, table} + end +end diff --git a/deps/ecto/lib/ecto/repo/schema.ex b/deps/ecto/lib/ecto/repo/schema.ex new file mode 100644 index 0000000000000000000000000000000000000000..6fc921166a8f4b3c4d26664b5025e439f5babb78 --- /dev/null +++ b/deps/ecto/lib/ecto/repo/schema.ex @@ -0,0 +1,1127 @@ +defmodule Ecto.Repo.Schema do + # The module invoked by user defined repos + # for schema related functionality. + @moduledoc false + + alias Ecto.Changeset + alias Ecto.Changeset.Relation + require Ecto.Query + + import Ecto.Query.Planner, only: [attach_prefix: 2] + + @doc """ + Implementation for `Ecto.Repo.insert_all/3`. + """ + def insert_all(repo, name, schema, rows, tuplet) when is_atom(schema) do + do_insert_all(repo, name, schema, schema.__schema__(:prefix), + schema.__schema__(:source), rows, tuplet) + end + + def insert_all(repo, name, table, rows, tuplet) when is_binary(table) do + do_insert_all(repo, name, nil, nil, table, rows, tuplet) + end + + def insert_all(repo, name, {source, schema}, rows, tuplet) when is_atom(schema) do + do_insert_all(repo, name, schema, schema.__schema__(:prefix), source, rows, tuplet) + end + + defp do_insert_all(_repo, _name, _schema, _prefix, _source, [], {_adapter_meta, opts}) do + if opts[:returning] do + {0, []} + else + {0, nil} + end + end + + defp do_insert_all(repo, _name, schema, prefix, source, rows_or_query, {adapter_meta, opts}) do + %{adapter: adapter} = adapter_meta + autogen_id = schema && schema.__schema__(:autogenerate_id) + dumper = schema && schema.__schema__(:dump) + placeholder_map = Keyword.get(opts, :placeholders, %{}) + + {return_fields_or_types, return_sources} = + schema + |> returning(opts) + |> fields_to_sources(dumper) + + {rows_or_query, header, row_cast_params, placeholder_cast_params, placeholder_dump_params, counter} = + extract_header_and_fields(repo, rows_or_query, schema, dumper, autogen_id, placeholder_map, adapter, opts) + + schema_meta = metadata(schema, prefix, source, autogen_id, nil, opts) + + on_conflict = Keyword.get(opts, :on_conflict, :raise) + conflict_target = Keyword.get(opts, :conflict_target, []) + conflict_target = conflict_target(conflict_target, dumper) + {on_conflict, conflict_cast_params} = on_conflict(on_conflict, conflict_target, schema_meta, counter, dumper, adapter) + opts = Keyword.put(opts, :cast_params, placeholder_cast_params ++ row_cast_params ++ conflict_cast_params) + + {count, rows_or_query} = + adapter.insert_all(adapter_meta, schema_meta, header, rows_or_query, on_conflict, return_sources, placeholder_dump_params, opts) + + {count, postprocess(rows_or_query, return_fields_or_types, adapter, schema, schema_meta)} + end + + defp postprocess(nil, [], _adapter, _schema, _schema_meta) do + nil + end + + defp postprocess(rows, fields, _adapter, nil, _schema_meta) do + for row <- rows, do: Map.new(Enum.zip(fields, row)) + end + + defp postprocess(rows, types, adapter, schema, %{prefix: prefix, source: source}) do + struct = Ecto.Schema.Loader.load_struct(schema, prefix, source) + + for row <- rows do + {loaded, _} = Ecto.Repo.Queryable.struct_load!(types, row, [], false, struct, adapter) + loaded + end + end + + defp extract_header_and_fields(_repo, rows, schema, dumper, autogen_id, placeholder_map, adapter, _opts) + when is_list(rows) do + mapper = init_mapper(schema, dumper, adapter, placeholder_map) + + {rows, {header, placeholder_dump, _}} = + Enum.map_reduce(rows, {%{}, %{}, 1}, fn fields, acc -> + {fields, {header, placeholder_dump, counter}} = Enum.map_reduce(fields, acc, mapper) + {fields, header} = autogenerate_id(autogen_id, fields, header, adapter) + {fields, {header, placeholder_dump, counter}} + end) + + header = Map.keys(header) + + placeholder_size = map_size(placeholder_dump) + + {placeholder_cast_params, placeholder_dump_params} = + placeholder_dump + |> Enum.map(fn {_, {idx, _, cast_value, dump_value}} -> {idx, cast_value, dump_value} end) + |> Enum.sort + |> Enum.map(&{elem(&1, 1), elem(&1, 2)}) + |> Enum.unzip + + {rows, row_cast_params, counter} = plan_query_in_rows(rows, header, adapter, placeholder_size) + {rows, header, row_cast_params, placeholder_cast_params, placeholder_dump_params, fn -> counter end} + end + + defp extract_header_and_fields(repo, %Ecto.Query{} = query, _schema, dumper, _autogen_id, _placeholder_map, adapter, opts) do + {query, opts} = repo.prepare_query(:insert_all, query, opts) + query = attach_prefix(query, opts) + + {query, cast_params, dump_params} = + Ecto.Adapter.Queryable.plan_query(:insert_all, adapter, query) + + ix = + case query.select do + %Ecto.Query.SelectExpr{expr: {:&, _, [ix]}} -> ix + _ -> nil + end + + header = + case query.select do + %Ecto.Query.SelectExpr{expr: {:%{}, [], [{:|, _, [{:&, _, [ix]}, args]}]}, fields: fields} -> + {updated_fields, updated_set} = + Enum.map_reduce(args, MapSet.new(), fn {field, _}, set -> + dumped_field = insert_all_select_dump!(field, dumper) + {dumped_field, MapSet.put(set, dumped_field)} + end) + + unchanged_fields = + for {{:., _, [{:&, _, [^ix]}, field]}, [], []} = expr <- fields, + not MapSet.member?(updated_set, field), + do: insert_all_select_dump!(expr) + + unchanged_fields ++ updated_fields + + %Ecto.Query.SelectExpr{expr: {:%{}, _ctx, args}} -> + Enum.map(args, fn {field, _} -> insert_all_select_dump!(field, dumper) end) + + %Ecto.Query.SelectExpr{take: %{^ix => {_fun, fields}}} -> + Enum.map(fields, &insert_all_select_dump!(&1, dumper)) + + %Ecto.Query.SelectExpr{expr: {:&, _, [_ix]}, fields: fields} -> + Enum.map(fields, &insert_all_select_dump!(&1)) + + _ -> + raise ArgumentError, """ + cannot generate a fields list for insert_all from the given source query: + + #{inspect(query)} + + The select clause must be one of the following: + + * A single `map/2` or several `map/2` expressions combined with `select_merge` + * A single `struct/2` or several `struct/2` expressions combined with `select_merge` + * A source such as `p` in the query `from p in Post` + * A single literal map or several literal maps combined with `select_merge`. If + combining several literal maps, there cannot be any query interpolations + except in the last `select_merge`. Consider using `Ecto.Query.exclude/2` + to rebuild the select expression from scratch if you need multiple `select_merge` + statements with interpolations + + All keys must exist in the schema that is being inserted into + """ + end + + counter = fn -> length(dump_params) end + + {{query, dump_params}, header, cast_params, [], [], counter} + end + + defp extract_header_and_fields(_repo, rows_or_query, _schema, _dumper, _autogen_id, _placeholder_map, _adapter, _opts) do + raise ArgumentError, "expected a list of rows or a query, but got #{inspect rows_or_query} as rows_or_query argument in insert_all" + end + + defp init_mapper(nil, _dumper, _adapter, placeholder_map) do + fn {field, value}, acc -> + extract_value(field, value, :any, placeholder_map, acc, & &1) + end + end + + defp init_mapper(schema, dumper, adapter, placeholder_map) do + fn {field, value}, acc -> + case dumper do + %{^field => {source, type, writable}} when writable != :never -> + extract_value(source, value, type, placeholder_map, acc, fn val -> + dump_field!(:insert_all, schema, field, type, val, adapter) + end) + + %{} -> + raise ArgumentError, + "unknown field `#{inspect(field)}` in schema #{inspect(schema)} given to " <> + "insert_all. Unwritable fields, such as virtual and read only fields " <> + "are not supported. Associations are also not supported" + end + end + end + + defp extract_value(source, value, type, placeholder_map, acc, dumper) do + {header, placeholder_dump, counter} = acc + + case value do + %Ecto.Query{} = query -> + {{source, query}, {Map.put(header, source, true), placeholder_dump, counter}} + + {:placeholder, key} -> + {value, placeholder_dump, counter} = + extract_placeholder(key, type, placeholder_map, placeholder_dump, counter, dumper) + + {{source, value}, + {Map.put(header, source, true), placeholder_dump, counter}} + + cast_value -> + {{source, cast_value, dumper.(value)}, + {Map.put(header, source, true), placeholder_dump, counter}} + end + end + + defp extract_placeholder(key, type, placeholder_map, placeholder_dump, counter, dumper) do + case placeholder_dump do + %{^key => {idx, ^type, _, _}} -> + {{:placeholder, idx}, placeholder_dump, counter} + + %{^key => {_, type, _}} -> + raise ArgumentError, + "a placeholder key can only be used with columns of the same type. " <> + "The key #{inspect(key)} has already been dumped as a #{inspect(type)}" + + %{} -> + {cast_value, dump_value} = + case placeholder_map do + %{^key => cast_value} -> + {cast_value, dumper.(cast_value)} + + _ -> + raise KeyError, + "placeholder key #{inspect(key)} not found in #{inspect(placeholder_map)}" + end + + placeholder_dump = Map.put(placeholder_dump, key, {counter, type, cast_value, dump_value}) + {{:placeholder, counter}, placeholder_dump, counter + 1} + end + end + + defp plan_query_in_rows(rows, header, adapter, counter) do + {rows, {cast_params, counter}} = + Enum.map_reduce(rows, {[], counter}, fn fields, {cast_param_acc, counter} -> + Enum.flat_map_reduce(header, {cast_param_acc, counter}, fn key, {cast_param_acc, counter} -> + case :lists.keyfind(key, 1, fields) do + {^key, %Ecto.Query{} = query} -> + {query, params, _} = Ecto.Query.Planner.plan(query, :all, adapter) + {cast_params, dump_params} = Enum.unzip(params) + {query, _} = Ecto.Query.Planner.normalize(query, :all, adapter, counter) + num_params = length(dump_params) + + {[{key, {query, dump_params}}], {Enum.reverse(cast_params, cast_param_acc), counter + num_params}} + + {^key, {:placeholder, _} = value} -> + {[{key, value}], {cast_param_acc, counter}} + + {^key, cast_value, dump_value} -> + {[{key, dump_value}], {[cast_value | cast_param_acc], counter + 1}} + + false -> + {[], {cast_param_acc, counter}} + end + end) + end) + + {rows, Enum.reverse(cast_params), counter} + end + + defp insert_all_select_dump!({{:., dot_meta, [{:&, _, [_]}, field]}, [], []}) do + if dot_meta[:writable] == :never do + raise ArgumentError, "cannot select unwritable field `#{inspect(field)}` for insert_all" + else + field + end + end + + defp insert_all_select_dump!(field, dumper) when is_atom(field) do + case dumper do + %{^field => {source, _, writable}} when writable != :never -> source + %{} -> raise ArgumentError, "cannot select unwritable field `#{inspect(field)}` for insert_all" + nil -> field + end + end + + defp autogenerate_id(nil, fields, header, _adapter) do + {fields, header} + end + + defp autogenerate_id({key, source, type}, fields, header, adapter) do + case :lists.keyfind(key, 1, fields) do + {^key, _, _} -> + {fields, header} + + false -> + if dump_value = Ecto.Type.adapter_autogenerate(adapter, type) do + {:ok, cast_value} = Ecto.Type.adapter_load(adapter, type, dump_value) + {[{source, cast_value, dump_value} | fields], Map.put(header, source, true)} + else + {fields, header} + end + end + end + + @doc """ + Implementation for `Ecto.Repo.insert!/2`. + """ + def insert!(repo, name, struct_or_changeset, tuplet) do + case insert(repo, name, struct_or_changeset, tuplet) do + {:ok, struct} -> + struct + + {:error, %Ecto.Changeset{} = changeset} -> + raise Ecto.InvalidChangesetError, action: :insert, changeset: changeset + end + end + + @doc """ + Implementation for `Ecto.Repo.update!/2`. + """ + def update!(repo, name, struct_or_changeset, tuplet) do + case update(repo, name, struct_or_changeset, tuplet) do + {:ok, struct} -> + struct + + {:error, %Ecto.Changeset{} = changeset} -> + raise Ecto.InvalidChangesetError, action: :update, changeset: changeset + end + end + + @doc """ + Implementation for `Ecto.Repo.delete!/2`. + """ + def delete!(repo, name, struct_or_changeset, tuplet) do + case delete(repo, name, struct_or_changeset, tuplet) do + {:ok, struct} -> + struct + + {:error, %Ecto.Changeset{} = changeset} -> + raise Ecto.InvalidChangesetError, action: :delete, changeset: changeset + end + end + + @doc """ + Implementation for `Ecto.Repo.insert/2`. + """ + def insert(repo, name, %Changeset{} = changeset, tuplet) do + do_insert(repo, name, changeset, tuplet) + end + + def insert(repo, name, %{__struct__: _} = struct, tuplet) do + do_insert(repo, name, Ecto.Changeset.change(struct), tuplet) + end + + defp do_insert(repo, _name, %Changeset{valid?: true} = changeset, {adapter_meta, opts} = tuplet) do + %{adapter: adapter} = adapter_meta + %{prepare: prepare, repo_opts: repo_opts} = changeset + opts = Keyword.merge(repo_opts, opts) + + struct = struct_from_changeset!(:insert, changeset) + schema = struct.__struct__ + dumper = schema.__schema__(:dump) + {keep_fields, drop_fields} = schema.__schema__(:insertable_fields) + assocs = schema.__schema__(:associations) + embeds = schema.__schema__(:embeds) + + {return_types, return_sources} = + schema + |> returning(opts) + |> add_read_after_writes(schema) + |> fields_to_sources(dumper) + + on_conflict = Keyword.get(opts, :on_conflict, :raise) + conflict_target = Keyword.get(opts, :conflict_target, []) + conflict_target = conflict_target(conflict_target, dumper) + + # On insert, we always merge the whole struct into the + # changeset as changes, except the primary key if it is nil. + changeset = put_repo_and_action(changeset, :insert, repo, tuplet) + changeset = Relation.surface_changes(changeset, struct, keep_fields ++ assocs) + changeset = update_in(changeset.changes, &Map.drop(&1, drop_fields)) + + wrap_in_transaction(adapter, adapter_meta, opts, changeset, assocs, embeds, prepare, fn -> + assoc_opts = assoc_opts(assocs, opts) + user_changeset = run_prepare(changeset, prepare) + + {changeset, parents, children, _} = pop_assocs(user_changeset, assocs) + changeset = process_parents(changeset, user_changeset, parents, [], adapter, assoc_opts) + + if changeset.valid? do + embeds = Ecto.Embedded.prepare(changeset, embeds, adapter, :insert) + + autogen_id = schema.__schema__(:autogenerate_id) + schema_meta = metadata(struct, autogen_id, opts) + changes = Map.merge(changeset.changes, embeds) + + {changes, cast_extra, dump_extra, return_types, return_sources} = + autogenerate_id(autogen_id, changes, return_types, return_sources, adapter) + + changes = Map.take(changes, keep_fields) + autogen = autogenerate_changes(schema, :insert, changes) + + dump_changes = + dump_changes!(:insert, changes, autogen, schema, dump_extra, dumper, adapter) + + {on_conflict, conflict_cast_params} = + on_conflict(on_conflict, conflict_target, schema_meta, fn -> length(dump_changes) end, dumper, adapter) + + change_values = Enum.map(changes, &elem(&1, 1)) + autogen_values = Enum.map(autogen, &elem(&1, 1)) + opts = Keyword.put(opts, :cast_params, change_values ++ autogen_values ++ cast_extra ++ conflict_cast_params) + args = [adapter_meta, schema_meta, dump_changes, on_conflict, return_sources, opts] + + case apply(user_changeset, adapter, :insert, args) do + {:ok, values} -> + values = dump_extra ++ values + + changeset + |> load_changes(:loaded, return_types, values, embeds, autogen, adapter, schema_meta) + |> process_children(user_changeset, children, adapter, assoc_opts) + + {:error, _} = error -> + error + end + else + {:error, changeset} + end + end) + end + + defp do_insert(repo, _name, %Changeset{valid?: false} = changeset, tuplet) do + {:error, put_repo_and_action(changeset, :insert, repo, tuplet)} + end + + @doc """ + Implementation for `Ecto.Repo.update/2`. + """ + def update(repo, name, %Changeset{} = changeset, tuplet) do + do_update(repo, name, changeset, tuplet) + end + + def update(_repo, _name, %{__struct__: _}, _tuplet) do + raise ArgumentError, "giving a struct to Ecto.Repo.update/2 is not supported. " <> + "Ecto is unable to properly track changes when a struct is given, " <> + "an Ecto.Changeset must be given instead" + end + + defp do_update(repo, _name, %Changeset{valid?: true} = changeset, {adapter_meta, opts} = tuplet) do + %{adapter: adapter} = adapter_meta + %{prepare: prepare, repo_opts: repo_opts} = changeset + opts = Keyword.merge(repo_opts, opts) + + struct = struct_from_changeset!(:update, changeset) + schema = struct.__struct__ + dumper = schema.__schema__(:dump) + {keep_fields, drop_fields} = schema.__schema__(:updatable_fields) + assocs = schema.__schema__(:associations) + embeds = schema.__schema__(:embeds) + + force? = !!opts[:force] + filters = add_pk_filter!(changeset.filters, struct) + + {return_types, return_sources} = + schema + |> returning(opts) + |> add_read_after_writes(schema) + |> fields_to_sources(dumper) + + # Differently from insert, update does not copy the struct + # fields into the changeset. All changes must be in the + # changeset before hand. + changeset = put_repo_and_action(changeset, :update, repo, tuplet) + changeset = update_in(changeset.changes, &Map.drop(&1, drop_fields)) + + if changeset.changes != %{} or force? do + wrap_in_transaction(adapter, adapter_meta, opts, changeset, assocs, embeds, prepare, fn -> + assoc_opts = assoc_opts(assocs, opts) + user_changeset = run_prepare(changeset, prepare) + + {changeset, parents, children, reset_parents} = pop_assocs(user_changeset, assocs) + changeset = process_parents(changeset, user_changeset, parents, reset_parents, adapter, assoc_opts) + + if changeset.valid? do + embeds = Ecto.Embedded.prepare(changeset, embeds, adapter, :update) + + changes = changeset.changes |> Map.merge(embeds) |> Map.take(keep_fields) + autogen = autogenerate_changes(schema, :update, changes) + dump_changes = dump_changes!(:update, changes, autogen, schema, [], dumper, adapter) + + schema_meta = metadata(struct, schema.__schema__(:autogenerate_id), opts) + dump_filters = dump_fields!(:update, schema, filters, dumper, adapter) + + change_values = Enum.map(changes, &elem(&1, 1)) + autogen_values = Enum.map(autogen, &elem(&1, 1)) + filter_values = Enum.map(filters, &elem(&1, 1)) + opts = Keyword.put(opts, :cast_params, change_values ++ autogen_values ++ filter_values) + args = [adapter_meta, schema_meta, dump_changes, dump_filters, return_sources, opts] + + # If there are no changes or all the changes were autogenerated but not forced, we skip + {action, autogen} = + if changes != %{} or (autogen != [] and force?), + do: {:update, autogen}, + else: {:noop, []} + + case apply(user_changeset, adapter, action, args) do + {:ok, values} -> + changeset + |> load_changes(:loaded, return_types, values, embeds, autogen, adapter, schema_meta) + |> process_children(user_changeset, children, adapter, assoc_opts) + + {:error, _} = error -> + error + end + else + {:error, changeset} + end + end) + else + {:ok, changeset.data} + end + end + + defp do_update(repo, _name, %Changeset{valid?: false} = changeset, tuplet) do + {:error, put_repo_and_action(changeset, :update, repo, tuplet)} + end + + @doc """ + Implementation for `Ecto.Repo.insert_or_update/2`. + """ + def insert_or_update(repo, name, changeset, tuplet) do + case get_state(changeset) do + :built -> insert(repo, name, changeset, tuplet) + :loaded -> update(repo, name, changeset, tuplet) + state -> raise ArgumentError, "the changeset has an invalid state " <> + "for Repo.insert_or_update/2: #{state}" + end + end + + @doc """ + Implementation for `Ecto.Repo.insert_or_update!/2`. + """ + def insert_or_update!(repo, name, changeset, tuplet) do + case get_state(changeset) do + :built -> insert!(repo, name, changeset, tuplet) + :loaded -> update!(repo, name, changeset, tuplet) + state -> raise ArgumentError, "the changeset has an invalid state " <> + "for Repo.insert_or_update!/2: #{state}" + end + end + + defp get_state(%Changeset{data: %{__meta__: %{state: state}}}), do: state + defp get_state(%{__struct__: _}) do + raise ArgumentError, "giving a struct to Repo.insert_or_update/2 or " <> + "Repo.insert_or_update!/2 is not supported. " <> + "Please use an Ecto.Changeset" + end + + @doc """ + Implementation for `Ecto.Repo.delete/2`. + """ + def delete(repo, name, %Changeset{} = changeset, tuplet) do + do_delete(repo, name, changeset, tuplet) + end + + def delete(repo, name, %{__struct__: _} = struct, tuplet) do + changeset = Ecto.Changeset.change(struct) + do_delete(repo, name, changeset, tuplet) + end + + defp do_delete(repo, name, %Changeset{valid?: true} = changeset, {adapter_meta, opts} = tuplet) do + %{adapter: adapter} = adapter_meta + %{prepare: prepare, repo_opts: repo_opts} = changeset + opts = Keyword.merge(repo_opts, opts) + + struct = struct_from_changeset!(:delete, changeset) + schema = struct.__struct__ + assocs = to_delete_assocs(schema) + dumper = schema.__schema__(:dump) + changeset = put_repo_and_action(changeset, :delete, repo, tuplet) + + {return_types, return_sources} = + schema + |> returning(opts) + |> add_read_after_writes(schema) + |> fields_to_sources(dumper) + + wrap_in_transaction(adapter, adapter_meta, opts, assocs != [], prepare, fn -> + changeset = run_prepare(changeset, prepare) + + if changeset.valid? do + filters = add_pk_filter!(changeset.filters, struct) + dump_filters = dump_fields!(:delete, schema, filters, dumper, adapter) + + # Delete related associations + for %{__struct__: mod, on_delete: on_delete} = reflection <- assocs do + apply(mod, on_delete, [reflection, changeset.data, name, tuplet]) + end + + schema_meta = metadata(struct, schema.__schema__(:autogenerate_id), opts) + filter_values = Enum.map(filters, &elem(&1, 1)) + opts = Keyword.put(opts, :cast_params, filter_values) + # Remove backwards compatibility in later release + args = if function_exported?(adapter, :delete, 5) do + [adapter_meta, schema_meta, dump_filters, return_sources, opts] + else + [adapter_meta, schema_meta, dump_filters, opts] + end + + case apply(changeset, adapter, :delete, args) do + {:ok, values} -> + changeset = load_changes(changeset, :deleted, return_types, values, %{}, [], adapter, schema_meta) + {:ok, changeset.data} + + {:error, _} = error -> + error + end + else + {:error, changeset} + end + end) + end + + defp do_delete(repo, _name, %Changeset{valid?: false} = changeset, tuplet) do + {:error, put_repo_and_action(changeset, :delete, repo, tuplet)} + end + + def load(adapter, schema_or_types, data) do + do_load(schema_or_types, data, &Ecto.Type.adapter_load(adapter, &1, &2)) + end + + defp do_load(schema, data, loader) when is_list(data), + do: do_load(schema, Map.new(data), loader) + defp do_load(schema, {fields, values}, loader) when is_list(fields) and is_list(values), + do: do_load(schema, Enum.zip(fields, values), loader) + defp do_load(schema, data, loader) when is_atom(schema), + do: Ecto.Schema.Loader.unsafe_load(schema, data, loader) + defp do_load(types, data, loader) when is_map(types), + do: Ecto.Schema.Loader.unsafe_load(%{}, types, data, loader) + + ## Helpers + + defp returning(schema, opts) do + case Keyword.get(opts, :returning, false) do + [_ | _] = fields -> + fields + [] -> + raise ArgumentError, ":returning expects at least one field to be given, got an empty list" + true when is_nil(schema) -> + raise ArgumentError, ":returning option can only be set to true if a schema is given" + true -> + schema.__schema__(:fields) + false -> + [] + end + end + + defp add_read_after_writes([], schema), + do: schema.__schema__(:read_after_writes) + + defp add_read_after_writes(return, schema), + do: Enum.uniq(return ++ schema.__schema__(:read_after_writes)) + + defp fields_to_sources(fields, nil) do + {fields, fields} + end + defp fields_to_sources(fields, dumper) do + Enum.reduce(fields, {[], []}, fn field, {types, sources} -> + {source, type, _writable} = Map.fetch!(dumper, field) + {[{field, type} | types], [source | sources]} + end) + end + + defp struct_from_changeset!(action, %{data: nil}), + do: raise(ArgumentError, "cannot #{action} a changeset without :data") + defp struct_from_changeset!(_action, %{data: struct}), + do: struct + + defp put_repo_and_action(%{action: :ignore, valid?: valid?} = changeset, action, repo, {_adapter_meta, opts}) do + if valid? do + raise ArgumentError, "a valid changeset with action :ignore was given to " <> + "#{inspect repo}.#{action}/2. Changesets can only be ignored " <> + "in a repository action if they are also invalid" + else + %{changeset | action: action, repo: repo, repo_opts: opts} + end + end + defp put_repo_and_action(%{action: given}, action, repo, _tuplet) when given != nil and given != action, + do: raise(ArgumentError, "a changeset with action #{inspect given} was given to #{inspect repo}.#{action}/2") + defp put_repo_and_action(changeset, action, repo, {_adapter_meta, opts}), + do: %{changeset | action: action, repo: repo, repo_opts: opts} + + defp run_prepare(changeset, prepare) do + Enum.reduce(Enum.reverse(prepare), changeset, fn fun, acc -> + case fun.(acc) do + %Ecto.Changeset{} = acc -> + acc + + other -> + raise "expected function #{inspect fun} given to Ecto.Changeset.prepare_changes/2 " <> + "to return an Ecto.Changeset, got: `#{inspect other}`" + end + end) + end + + defp metadata(schema, prefix, source, autogen_id, context, opts) do + %{ + autogenerate_id: autogen_id, + context: context, + schema: schema, + source: source, + prefix: Keyword.get(opts, :prefix, prefix) + } + end + defp metadata(%{__struct__: schema, __meta__: %{context: context, source: source, prefix: prefix}}, + autogen_id, opts) do + metadata(schema, prefix, source, autogen_id, context, opts) + end + defp metadata(%{__struct__: schema}, _, _) do + raise ArgumentError, "#{inspect(schema)} needs to be a schema with source" + end + + defp conflict_target({:unsafe_fragment, fragment}, _dumper) when is_binary(fragment) do + {:unsafe_fragment, fragment} + end + defp conflict_target(conflict_target, dumper) do + for target <- List.wrap(conflict_target) do + case dumper do + %{^target => {alias, _, _}} -> + alias + %{} when is_atom(target) -> + raise ArgumentError, "unknown field `#{inspect(target)}` in conflict_target" + _ -> + target + end + end + end + + defp on_conflict(on_conflict, conflict_target, schema_meta, counter_fun, dumper, adapter) do + %{source: source, schema: schema, prefix: prefix} = schema_meta + + case on_conflict do + :raise when conflict_target == [] -> + {{:raise, [], []}, []} + + :raise -> + raise ArgumentError, ":conflict_target option is forbidden when :on_conflict is :raise" + + :nothing -> + {{:nothing, [], conflict_target}, []} + + {:replace, []} -> + raise ArgumentError, ":on_conflict option with `{:replace, fields}` requires a non-empty list of fields" + + {:replace, keys} when is_list(keys) -> + {{replace_fields!(dumper, keys), [], conflict_target}, []} + + :replace_all -> + # Remove the conflict targets from the replacing fields + # since the values don't change and this allows postgres to + # possibly perform a HOT optimization: https://www.postgresql.org/docs/current/storage-hot.html + to_remove = List.wrap(conflict_target) + {{replace_all_fields!(:replace_all, schema, to_remove), [], conflict_target}, []} + + {:replace_all_except, fields} -> + {{replace_all_fields!(:replace_all_except, schema, fields), [], conflict_target}, []} + + [_ | _] = on_conflict -> + from = if schema, do: {source, schema}, else: source + query = Ecto.Query.from from, update: ^on_conflict + on_conflict_query(query, {source, schema}, prefix, counter_fun, adapter, conflict_target) + + %Ecto.Query{} = query -> + on_conflict_query(query, {source, schema}, prefix, counter_fun, adapter, conflict_target) + + other -> + raise ArgumentError, "unknown value for :on_conflict, got: #{inspect other}" + end + end + + defp replace_fields!(nil, fields), do: fields + + defp replace_fields!(dumper, fields) do + Enum.map(fields, fn field -> + case dumper do + %{^field => {source, _type, :always}} -> + source + + _ -> + raise ArgumentError, + "cannot replace non-updatable field `#{inspect(field)}` in :on_conflict option" + end + end) + end + + defp replace_all_fields!(kind, nil, _to_remove) do + raise ArgumentError, "cannot use #{inspect(kind)} on operations without a schema" + end + + defp replace_all_fields!(_kind, schema, to_remove) do + {updatable_fields, _} = schema.__schema__(:updatable_fields) + Enum.map(updatable_fields -- to_remove, &field_source!(schema, &1)) + end + + defp field_source!(nil, field) do + field + end + + defp field_source!(schema, field) do + schema.__schema__(:field_source, field) || + raise ArgumentError, "unknown field for :on_conflict, got: #{inspect(field)}" + end + + defp on_conflict_query(query, from, prefix, counter_fun, adapter, conflict_target) do + {query, params, _} = + Ecto.Query.Planner.plan(%{query | prefix: prefix}, :update_all, adapter) + + {cast_params, dump_params} = Enum.unzip(params) + + unless query.from.source == from do + raise ArgumentError, "cannot run on_conflict: query because the query " <> + "has a different {source, schema} pair than the " <> + "original struct/changeset/query. Got #{inspect query.from} " <> + "and #{inspect from} respectively" + end + + {query, _} = Ecto.Query.Planner.normalize(query, :update_all, adapter, counter_fun.()) + {{query, dump_params, conflict_target}, cast_params} + end + + defp apply(_user_changeset, _adapter, :noop, _args) do + {:ok, []} + end + + defp apply(user_changeset, adapter, action, args) do + case apply(adapter, action, args) do + {:ok, values} -> + {:ok, values} + + {:invalid, constraints} -> + {:error, constraints_to_errors(user_changeset, action, constraints)} + + {:error, :stale} -> + opts = List.last(args) + + if Keyword.get(opts, :allow_stale, false) do + {:ok, []} + else + case Keyword.fetch(opts, :stale_error_field) do + {:ok, stale_error_field} when is_atom(stale_error_field) -> + stale_message = Keyword.get(opts, :stale_error_message, "is stale") + user_changeset = Changeset.add_error(user_changeset, stale_error_field, stale_message, [stale: true]) + {:error, user_changeset} + + _other -> + raise Ecto.StaleEntryError, changeset: user_changeset, action: action + end + end + end + end + + defp constraints_to_errors(%{constraints: user_constraints, errors: errors} = changeset, action, constraints) do + constraint_errors = + Enum.map constraints, fn {type, constraint} -> + user_constraint = + Enum.find(user_constraints, fn c -> + case {c.type, c.constraint, c.match} do + {^type, ^constraint, :exact} -> true + {^type, cc, :suffix} -> String.ends_with?(constraint, cc) + {^type, cc, :prefix} -> String.starts_with?(constraint, cc) + {^type, %Regex{} = r, _match} -> Regex.match?(r, constraint) + _ -> false + end + end) + + case user_constraint do + %{field: field, error_message: error_message, error_type: error_type} -> + {field, {error_message, [constraint: error_type, constraint_name: constraint]}} + nil -> + raise Ecto.ConstraintError, action: action, type: type, + constraint: constraint, changeset: changeset + end + end + + %{changeset | errors: constraint_errors ++ errors, valid?: false} + end + + defp load_changes(changeset, state, types, values, embeds, autogen, adapter, schema_meta) do + %{data: data, changes: changes} = changeset + + data = + data + |> merge_changes(changes) + |> Map.merge(embeds) + |> merge_autogen(autogen) + |> apply_metadata(state, schema_meta) + |> load_each(values, types, adapter) + + Map.put(changeset, :data, data) + end + + defp merge_changes(data, changes) do + changes = + Enum.reduce(changes, changes, fn {key, _value}, changes -> + if Map.has_key?(data, key), do: changes, else: Map.delete(changes, key) + end) + + Map.merge(data, changes) + end + + defp merge_autogen(data, autogen) do + Enum.reduce(autogen, data, fn {k, v}, acc -> %{acc | k => v} end) + end + + defp apply_metadata(%{__meta__: meta} = data, state, %{source: source, prefix: prefix}) do + %{data | __meta__: %{meta | state: state, source: source, prefix: prefix}} + end + + defp load_each(struct, [{_, value} | kv], [{key, type} | types], adapter) do + case Ecto.Type.adapter_load(adapter, type, value) do + {:ok, value} -> + load_each(%{struct | key => value}, kv, types, adapter) + :error -> + raise ArgumentError, "cannot load `#{inspect value}` as type #{Ecto.Type.format(type)} " <> + "for field `#{key}` in schema #{inspect struct.__struct__}" + end + end + defp load_each(struct, [], _types, _adapter) do + struct + end + + defp pop_assocs(changeset, []) do + {changeset, [], [], []} + end + + defp pop_assocs(%{changes: changes, types: types, data: data} = changeset, assocs) do + {changes, parent, child, reset} = + Enum.reduce(assocs, {changes, [], [], []}, fn assoc, {changes, parent, child, reset} -> + case changes do + %{^assoc => value} -> + changes = Map.delete(changes, assoc) + + case types do + %{^assoc => {:assoc, %{relationship: :parent} = refl}} -> + {changes, [{refl, value} | parent], child, reset} + + %{^assoc => {:assoc, %{relationship: :child} = refl}} -> + {changes, parent, [{refl, value} | child], reset} + end + + %{} -> + with %{^assoc => {:assoc, %{relationship: :parent} = refl}} <- types, + true <- reset_parent?(changes, data, refl) do + {changes, parent, child, [assoc | reset]} + else + _ -> {changes, parent, child, reset} + end + end + end) + + {%{changeset | changes: changes}, parent, child, reset} + end + + defp reset_parent?(changes, data, assoc) do + %{field: field, owner_key: owner_key, related_key: related_key} = assoc + + with %{^owner_key => owner_value} <- changes, + %{^field => %{^related_key => related_value}} when owner_value != related_value <- data do + true + else + _ -> false + end + end + + # Don't mind computing options if there are no assocs + defp assoc_opts([], _opts), do: [] + + defp assoc_opts(_assocs, opts) do + Keyword.take(opts, [:timeout, :log, :telemetry_event, :prefix, :allow_stale]) + end + + defp process_parents(changeset, user_changeset, assocs, reset_assocs, adapter, opts) do + %{changes: changes, valid?: valid?} = changeset + + # Even if the changeset is invalid, we want to run parent callbacks + # to collect feedback. But if all is ok, still return the user changeset. + case Ecto.Association.on_repo_change(changeset, assocs, adapter, opts) do + {:ok, struct} when valid? -> + changes = change_parents(changes, struct, assocs) + struct = Ecto.reset_fields(struct, reset_assocs) + %{changeset | changes: changes, data: struct} + + {:ok, _} -> + user_changeset + + {:error, changes} -> + %{user_changeset | changes: Map.merge(user_changeset.changes, changes), valid?: false} + end + end + + defp change_parents(changes, struct, assocs) do + Enum.reduce assocs, changes, fn {refl, _}, acc -> + %{field: field, owner_key: owner_key, related_key: related_key} = refl + related = Map.get(struct, field) + value = related && Map.fetch!(related, related_key) + + case Map.fetch(changes, owner_key) do + {:ok, current} when current != value -> + raise ArgumentError, + "cannot change belongs_to association `#{field}` because there is " <> + "already a change setting its foreign key `#{owner_key}` to `#{inspect current}`" + + _ -> + Map.put(acc, owner_key, value) + end + end + end + + defp process_children(changeset, user_changeset, assocs, adapter, opts) do + case Ecto.Association.on_repo_change(changeset, assocs, adapter, opts) do + {:ok, struct} -> + {:ok, struct} + + {:error, changes} -> + changes = Map.merge(user_changeset.changes, changes) + {:error, %{user_changeset | changes: changes, valid?: false}} + end + end + + defp to_delete_assocs(schema) do + for assoc <- schema.__schema__(:associations), + reflection = schema.__schema__(:association, assoc), + match?(%{on_delete: on_delete} when on_delete != :nothing, reflection), + do: reflection + end + + defp autogenerate_id(nil, changes, return_types, return_sources, _adapter) do + {changes, [], [], return_types, return_sources} + end + + defp autogenerate_id({key, source, type}, changes, return_types, return_sources, adapter) do + cond do + Map.has_key?(changes, key) -> # Set by user + {changes, [], [], return_types, return_sources} + dump_value = Ecto.Type.adapter_autogenerate(adapter, type) -> # Autogenerated now + {:ok, cast_value} = Ecto.Type.adapter_load(adapter, type, dump_value) + {changes, [cast_value], [{source, dump_value}] , [{key, type} | return_types], return_sources} + true -> # Autogenerated in storage + {changes, [], [], [{key, type} | return_types], [source | List.delete(return_sources, source)]} + end + end + + defp dump_changes!(action, changes, autogen, schema, extra, dumper, adapter) do + dump_fields!(action, schema, changes, dumper, adapter) ++ + dump_fields!(action, schema, autogen, dumper, adapter) ++ + extra + end + + defp autogenerate_changes(schema, action, changes) do + autogen_fields = action |> action_to_auto() |> schema.__schema__() + + Enum.flat_map(autogen_fields, fn {fields, {mod, fun, args}} -> + case Enum.reject(fields, &Map.has_key?(changes, &1)) do + [] -> + [] + + fields -> + generated = apply(mod, fun, args) + Enum.map(fields, &{&1, generated}) + end + end) + end + + defp action_to_auto(:insert), do: :autogenerate + defp action_to_auto(:update), do: :autoupdate + + defp add_pk_filter!(filters, struct) do + Enum.reduce Ecto.primary_key!(struct), filters, fn + {_k, nil}, _acc -> + raise Ecto.NoPrimaryKeyValueError, struct: struct + {k, v}, acc -> + Map.put(acc, k, v) + end + end + + defp wrap_in_transaction(adapter, adapter_meta, opts, changeset, assocs, embeds, prepare, fun) do + %{changes: changes} = changeset + changed = &Map.has_key?(changes, &1) + relations_changed? = Enum.any?(assocs, changed) or Enum.any?(embeds, changed) + wrap_in_transaction(adapter, adapter_meta, opts, relations_changed?, prepare, fun) + end + + defp wrap_in_transaction(adapter, adapter_meta, opts, relations_changed?, prepare, fun) do + if (relations_changed? or prepare != []) and + function_exported?(adapter, :transaction, 3) and + not adapter.in_transaction?(adapter_meta) do + adapter.transaction(adapter_meta, opts, fn -> + case fun.() do + {:ok, struct} -> struct + {:error, changeset} -> adapter.rollback(adapter_meta, changeset) + end + end) + else + fun.() + end + end + + defp dump_field!(action, schema, field, type, value, adapter) do + case Ecto.Type.adapter_dump(adapter, type, value) do + {:ok, value} -> + value + + :error -> + raise Ecto.ChangeError, + "value `#{inspect(value)}` for `#{inspect(schema)}.#{field}` " <> + "in `#{action}` does not match type #{Ecto.Type.format(type)}" + end + end + + defp dump_fields!(action, schema, kw, dumper, adapter) do + for {field, value} <- kw do + {alias, type, _writable} = Map.fetch!(dumper, field) + {alias, dump_field!(action, schema, field, type, value, adapter)} + end + end +end diff --git a/deps/ecto/lib/ecto/repo/supervisor.ex b/deps/ecto/lib/ecto/repo/supervisor.ex new file mode 100644 index 0000000000000000000000000000000000000000..1be968d8165b381e7cefea54b29bf799ff60a4e7 --- /dev/null +++ b/deps/ecto/lib/ecto/repo/supervisor.ex @@ -0,0 +1,227 @@ +defmodule Ecto.Repo.Supervisor do + @moduledoc false + use Supervisor + require Logger + + @defaults [timeout: 15000, pool_size: 10] + @integer_url_query_params ["timeout", "pool_size", "idle_interval"] + + @doc """ + Starts the repo supervisor. + """ + def start_link(repo, otp_app, adapter, opts) do + name = Keyword.get(opts, :name, repo) + sup_opts = if name, do: [name: name], else: [] + Supervisor.start_link(__MODULE__, {name, repo, otp_app, adapter, opts}, sup_opts) + end + + @doc """ + Retrieves the runtime configuration. + """ + def init_config(type, repo, otp_app, opts) do + config = Application.get_env(otp_app, repo, []) + config = [otp_app: otp_app] ++ (@defaults |> Keyword.merge(config) |> Keyword.merge(opts)) + config = Keyword.put_new_lazy(config, :telemetry_prefix, fn -> telemetry_prefix(repo) end) + + case repo_init(type, repo, config) do + {:ok, config} -> + {url, config} = Keyword.pop(config, :url) + url_config = parse_url(url || "") + + url_config = + if is_list(config[:ssl]) and url_config[:ssl] == true do + Logger.warning( + "ignoring `ssl=true` parameter in URL because `ssl` is already set in the configuration: #{inspect(config[:ssl])}" + ) + + Keyword.delete(url_config, :ssl) + else + url_config + end + + {:ok, Keyword.merge(config, url_config)} + + :ignore -> + :ignore + end + end + + defp telemetry_prefix(repo) do + repo + |> Module.split() + |> Enum.map(&(&1 |> Macro.underscore() |> String.to_atom())) + end + + defp repo_init(type, repo, config) do + if Code.ensure_loaded?(repo) and function_exported?(repo, :init, 2) do + repo.init(type, config) + else + {:ok, config} + end + end + + @doc """ + Retrieves the compile time configuration. + """ + def compile_config(_repo, opts) do + otp_app = Keyword.fetch!(opts, :otp_app) + adapter = opts[:adapter] + + unless adapter do + raise ArgumentError, "missing :adapter option on use Ecto.Repo" + end + + if Code.ensure_compiled(adapter) != {:module, adapter} do + raise ArgumentError, + "adapter #{inspect(adapter)} was not compiled, " <> + "ensure it is correct and it is included as a project dependency" + end + + behaviours = + for {:behaviour, behaviours} <- adapter.__info__(:attributes), + behaviour <- behaviours, + do: behaviour + + unless Ecto.Adapter in behaviours do + raise ArgumentError, + "expected :adapter option given to Ecto.Repo to list Ecto.Adapter as a behaviour" + end + + {otp_app, adapter, behaviours} + end + + @doc """ + Parses an Ecto URL allowed in configuration. + + The format must be: + + "ecto://username:password@hostname:port/database?ssl=true&timeout=1000" + + """ + def parse_url(""), do: [] + + def parse_url(url) when is_binary(url) do + info = URI.parse(url) + + if is_nil(info.host) do + raise Ecto.InvalidURLError, url: url, message: "host is not present" + end + + if is_nil(info.path) or not (info.path =~ ~r"^/([^/])+$") do + raise Ecto.InvalidURLError, url: url, message: "path should be a database name" + end + + destructure [username, password], info.userinfo && String.split(info.userinfo, ":") + "/" <> database = info.path + + url_opts = [ + scheme: info.scheme, + username: username, + password: password, + database: database, + port: info.port + ] + + url_opts = put_hostname_if_present(url_opts, info.host) + query_opts = parse_uri_query(info) + + for {k, v} <- url_opts ++ query_opts, + not is_nil(v), + do: {k, if(is_binary(v), do: URI.decode(v), else: v)} + end + + defp put_hostname_if_present(keyword, "") do + keyword + end + + defp put_hostname_if_present(keyword, hostname) when is_binary(hostname) do + Keyword.put(keyword, :hostname, hostname) + end + + defp parse_uri_query(%URI{query: nil}), + do: [] + + defp parse_uri_query(%URI{query: query} = url) do + query + |> URI.query_decoder() + |> Enum.reduce([], fn + {"ssl", "true"}, acc -> + [{:ssl, true}] ++ acc + + {"ssl", "false"}, acc -> + [{:ssl, false}] ++ acc + + {key, value}, acc when key in @integer_url_query_params -> + [{String.to_atom(key), parse_integer!(key, value, url)}] ++ acc + + {key, value}, acc -> + [{String.to_atom(key), value}] ++ acc + end) + end + + defp parse_integer!(key, value, url) do + case Integer.parse(value) do + {int, ""} -> + int + + _ -> + raise Ecto.InvalidURLError, + url: url, + message: "cannot parse value `#{value}` for parameter `#{key}` as an integer" + end + end + + @doc false + def tuplet(name, opts) do + adapter_meta = Ecto.Repo.Registry.lookup(name) + + if opts[:stacktrace] || Map.get(adapter_meta, :stacktrace) do + {:current_stacktrace, stacktrace} = :erlang.process_info(self(), :current_stacktrace) + {adapter_meta, Keyword.put(opts, :stacktrace, stacktrace)} + else + {adapter_meta, opts} + end + end + + ## Callbacks + + @doc false + def init({name, repo, otp_app, adapter, opts}) do + case init_config(:supervisor, repo, otp_app, opts) do + {:ok, opts} -> + :telemetry.execute( + [:ecto, :repo, :init], + %{system_time: System.system_time()}, + %{repo: repo, opts: opts} + ) + + {:ok, child, meta} = adapter.init([repo: repo] ++ opts) + + # Normalize name to atom, ignore via/global names + name = if is_atom(name), do: name, else: nil + cache = Ecto.Query.Planner.new_query_cache(name) + meta = Map.merge(meta, %{repo: repo, cache: cache}) + child_spec = wrap_child_spec(child, [name, adapter, meta]) + Supervisor.init([child_spec], strategy: :one_for_one, max_restarts: 0) + + :ignore -> + :ignore + end + end + + def start_child({mod, fun, args}, name, adapter, meta) do + case apply(mod, fun, args) do + {:ok, pid} -> + meta = Map.merge(meta, %{pid: pid, adapter: adapter}) + Ecto.Repo.Registry.associate(self(), name, meta) + {:ok, pid} + + other -> + other + end + end + + defp wrap_child_spec(%{start: start} = spec, args) do + %{spec | start: {__MODULE__, :start_child, [start | args]}} + end +end diff --git a/deps/ecto/lib/ecto/repo/transaction.ex b/deps/ecto/lib/ecto/repo/transaction.ex new file mode 100644 index 0000000000000000000000000000000000000000..2daa0cb2b7a275225dd9346adb8195deb11d951b --- /dev/null +++ b/deps/ecto/lib/ecto/repo/transaction.ex @@ -0,0 +1,47 @@ +defmodule Ecto.Repo.Transaction do + @moduledoc false + @dialyzer :no_opaque + + def transaction(_repo, _name, fun, {adapter_meta, opts}) when is_function(fun, 0) do + adapter_meta.adapter.transaction(adapter_meta, opts, fun) + end + + def transaction(repo, _name, fun, {adapter_meta, opts}) when is_function(fun, 1) do + adapter_meta.adapter.transaction(adapter_meta, opts, fn -> fun.(repo) end) + end + + def transaction(repo, _name, %Ecto.Multi{} = multi, {adapter_meta, opts}) do + %{adapter: adapter} = adapter_meta + wrap = &adapter.transaction(adapter_meta, opts, &1) + return = &adapter.rollback(adapter_meta, &1) + + case Ecto.Multi.__apply__(multi, repo, wrap, return) do + {:ok, values} -> + {:ok, values} + + {:error, {key, error_value, values}} -> + {:error, key, error_value, values} + + {:error, operation} -> + raise """ + operation #{inspect operation} is rolling back unexpectedly. + + This can happen if `repo.rollback/1` is manually called, which is not \ + supported by `Ecto.Multi`. It can also occur if a nested transaction \ + has rolled back and its error is not bubbled up to the outer multi. \ + Nested transactions are discouraged when using `Ecto.Multi`. Consider \ + flattening out the transaction instead. + """ + end + end + + def in_transaction?(name) do + %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(name) + adapter.in_transaction?(meta) + end + + def rollback(name, value) do + %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(name) + adapter.rollback(meta, value) + end +end diff --git a/deps/ecto/lib/ecto/schema.ex b/deps/ecto/lib/ecto/schema.ex new file mode 100644 index 0000000000000000000000000000000000000000..842698573da4182276f0129a362d7e0bcccf6b5b --- /dev/null +++ b/deps/ecto/lib/ecto/schema.ex @@ -0,0 +1,2616 @@ +defmodule Ecto.Schema do + @moduledoc ~S""" + An Ecto schema maps external data into Elixir structs. + + The definition of the schema is possible through two main APIs: + `schema/2` and `embedded_schema/1`. + + `schema/2` is typically used to map data from a persisted source, + usually a database table, into Elixir structs and vice-versa. For + this reason, the first argument of `schema/2` is the source (table) + name. Structs defined with `schema/2` also contain a `__meta__` field + with metadata holding the status of the struct, for example, if it + has been built, loaded or deleted. + + On the other hand, `embedded_schema/1` is used for defining schemas + that are embedded in other schemas or only exist in-memory. For example, + you can use such schemas to receive data from a command line interface + and validate it, without ever persisting it elsewhere. Such structs + do not contain a `__meta__` field, as they are never persisted. + + Besides working as data mappers, `embedded_schema/1` and `schema/2` can + also be used together to decouple how the data is represented in your + applications from the database. Let's see some examples. + + ## Example + + defmodule User do + use Ecto.Schema + + schema "users" do + field :name, :string + field :age, :integer, default: 0 + field :password, :string, redact: true + has_many :posts, Post + end + end + + By default, a schema will automatically generate a primary key which is named + `id` and of type `:integer`. The `field` macro defines a field in the schema + with given name and type. `has_many` associates many posts with the user + schema. Schemas are regular structs and can be created and manipulated directly + using Elixir's struct API: + + iex> user = %User{name: "jane"} + iex> %{user | age: 30} + + However, most commonly, structs are cast, validated and manipulated with the + `Ecto.Changeset` module. + + The first argument of `schema/2` is the name of database's table, which does + not need to correlate to your module name (commonly referred to as the schema/schema name). + For example, if you are working with a legacy database, you can reference the table name + (`legacy_users`) when you define your schema (`User`): + + defmodule User do + use Ecto.Schema + + schema "legacy_users" do + # ... fields ... + end + end + + Source-based schemas are queryable by default, which means we can pass them + to `Ecto.Repo` modules and also build queries: + + MyRepo.all(User) + MyRepo.all(from u in User, where: u.id == 13) + + The repository will then run the query against the source/table. + + Embedded schemas are defined similarly to source-based schemas. For example, + you can use an embedded schema to represent your UI, mapping and validating + its inputs, and then you convert such embedded schema to other schemas that + are persisted to the database: + + defmodule SignUp do + use Ecto.Schema + + embedded_schema do + field :name, :string + field :age, :integer + field :email, :string + field :accepts_conditions, :boolean + end + end + + defmodule Profile do + use Ecto.Schema + + schema "profiles" do + field :name + field :age + belongs_to :account, Account + end + end + + defmodule Account do + use Ecto.Schema + + schema "accounts" do + field :email + end + end + + The `SignUp` schema can be cast and validated with the help of the + `Ecto.Changeset` module, and afterwards, you can copy its data to + the `Profile` and `Account` structs that will be persisted to the + database with the help of `Ecto.Repo`. On the other hand, embedded + schemas cannot be queried directly (they are not queryable). + + > #### `use Ecto.Schema` {: .info} + > + > When you `use Ecto.Schema`, it will: + > + > - import `Ecto.Schema` macros `schema/2` and `embedded_schema/1` + > - register default values for module attributes that can be overridden, such as + > `@primary_key` and `@timestamps_opts` + > - define reflection functions such as `__schema__/1` and `__changeset__/1` + > + > We detail those throughout the module documentation. + + ## Redacting fields + + A field marked with `redact: true` will display a value of `**redacted**` + when inspected in changes inside a `Ecto.Changeset` and be excluded from + inspect on the schema unless the schema module is tagged with + the option `@ecto_derive_inspect_for_redacted_fields false`. + + ## Schema attributes + + Supported attributes for configuring the defined schema. They must + be set after the `use Ecto.Schema` call and before the `schema/2` + definition. + + These attributes are: + + * `@primary_key` - configures the schema primary key. It expects + a tuple `{field_name, type, options}` with the primary key field + name, type (typically `:id` or `:binary_id`, but can be any type) and + options. It also accepts `false` to disable the generation of a primary + key field. Defaults to `{:id, :id, autogenerate: true}`. + + * `@schema_prefix` - configures the schema prefix. Defaults to `nil`, + which generates structs and queries without prefix. When set, the + prefix will be used by every built struct and on queries whenever + the schema is used in a `from` or a `join`. In PostgreSQL, the prefix + is called "SCHEMA" (typically set via Postgres' `search_path`). + In MySQL the prefix points to databases. + + * `@schema_context` - configures the schema context. Defaults to `nil`, + which generates structs and queries without context. Context are not used + by the built-in SQL adapters. + + * `@foreign_key_type` - configures the default foreign key type + used by `belongs_to` associations. It must be set in the same + module that defines the `belongs_to`. Defaults to `:id`; + + * `@timestamps_opts` - configures the default timestamps type + used by `timestamps`. Defaults to `[type: :naive_datetime]`; + + * `@derive` - the same as `@derive` available in `Kernel.defstruct/1` + as the schema defines a struct behind the scenes; + + * `@field_source_mapper` - a function that receives the current field name + and returns the mapping of this field name in the underlying source. + In other words, it is a mechanism to automatically generate the `:source` + option for the `field` macro. It defaults to `fn x -> x end`, where no + field transformation is done; + + The advantage of configuring the schema via those attributes is + that they can be set with a macro to configure application wide + defaults. + + For example, if your database does not support autoincrementing + primary keys and requires something like UUID or a RecordID, you + can configure and use `:binary_id` as your primary key type as follows: + + # Define a module to be used as base + defmodule MyApp.Schema do + defmacro __using__(_) do + quote do + use Ecto.Schema + @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id + end + end + end + + # Now use MyApp.Schema to define new schemas + defmodule MyApp.Comment do + use MyApp.Schema + + schema "comments" do + belongs_to :post, MyApp.Post + end + end + + Any schemas using `MyApp.Schema` will get the `:id` field with type + `:binary_id` as the primary key. We explain what the `:binary_id` type + entails in the next section. + + The `belongs_to` association on `MyApp.Comment` will also define + a `:post_id` field with `:binary_id` type that references the `:id` + field of the `MyApp.Post` schema. + + ## Primary keys + + Ecto supports two ID types, called `:id` and `:binary_id`, which are + often used as the type for primary keys and associations. + + The `:id` type is used when the primary key is an integer while the + `:binary_id` is used for primary keys in particular binary formats, + which may be `Ecto.UUID` for databases like PostgreSQL and MySQL, + or some specific ObjectID or RecordID often imposed by NoSQL databases. + + In both cases, both types have their semantics specified by the + underlying adapter/database. If you use the `:id` type with + `:autogenerate`, it means the database will be responsible for + auto-generation of the id. This is often the case for primary keys + in relational databases which are auto-incremented. + + There are two ways to define primary keys in Ecto: using the `@primary_key` + module attribute and using `primary_key: true` as option for `field/3` in + your schema definition. They are not mutually exclusive and can be used + together. + + Using `@primary_key` should be preferred for single field primary keys and + sharing primary key definitions between multiple schemas using macros. + Setting `@primary_key` also automatically configures the reference types + for `has_one` and `has_many` associations. + + Ecto also supports composite primary keys, which is where you need to use + `primary_key: true` for the fields in your schema. This usually goes along + with setting `@primary_key false` to disable generation of additional + primary key fields. + + Besides `:id` and `:binary_id`, which are often used by primary + and foreign keys, Ecto provides a huge variety of types to be used + by any field. + + ## Types and casting + + When defining the schema, types need to be given. Types are split + into two categories, primitive types and custom types. + + ### Primitive types + + The primitive types are: + + Ecto type | Elixir type | Literal syntax in query + :---------------------- | :---------------------- | :--------------------- + `:id` | `integer` | 1, 2, 3 + `:binary_id` | `binary` | `<>` + `:integer` | `integer` | 1, 2, 3 + `:float` | `float` | 1.0, 2.0, 3.0 + `:boolean` | `boolean` | true, false + `:string` | UTF-8 encoded `string` | "hello" + `:binary` | `binary` | `<>` + `:bitstring` | `bitstring` | `<<_::size>>` + `{:array, inner_type}` | `list` | `[value, value, value, ...]` + `:map` | `map` | + `{:map, inner_type}` | `map` | + `:decimal` | [`Decimal`](https://github.com/ericmj/decimal) | + `:date` | `Date` | + `:time` | `Time` | + `:time_usec` | `Time` | + `:naive_datetime` | `NaiveDateTime` | + `:naive_datetime_usec` | `NaiveDateTime` | + `:utc_datetime` | `DateTime` | + `:utc_datetime_usec` | `DateTime` | + `:duration` | `Duration` | + + **Notes:** + + * When using database migrations provided by "Ecto SQL", you can pass + your Ecto type as the column type. However, note the same Ecto type + may support multiple database types. For example, all of `:varchar`, + `:text`, `:bytea`, etc. translate to Ecto's `:string`. Similarly, + Ecto's `:decimal` can be used for `:numeric` and other database + types. For more information, see [all migration types](https://hexdocs.pm/ecto_sql/Ecto.Migration.html#module-field-types). + + * For the `{:array, inner_type}` and `{:map, inner_type}` type, + replace `inner_type` with one of the valid types, such as `:string`. + + * For the `:decimal` type, `+Infinity`, `-Infinity`, and `NaN` values + are not supported, even though the `Decimal` library handles them. + To support them, you can create a custom type. + + * For calendar types with and without microseconds, the precision is + enforced when persisting to the DB. For example, casting `~T[09:00:00]` + as `:time_usec` will succeed and result in `~T[09:00:00.000000]`, but + persisting a type without microseconds as `:time_usec` will fail. + Similarly, casting `~T[09:00:00.000000]` as `:time` will succeed, but + persisting will not. This is the same behaviour as seen in other types, + where casting has to be done explicitly and is never performed + implicitly when loading from or dumping to the database. + + * For the `:duration` type, you may need to enable `Duration` support in + your adapter. For information on how to enable it in Postgrex, see their + [HexDocs page](https://hexdocs.pm/postgrex/readme.html#data-representation). + + ### Custom types + + Besides providing primitive types, Ecto allows custom types to be + implemented by developers, allowing Ecto behaviour to be extended. + + A custom type is a module that implements one of the `Ecto.Type` + or `Ecto.ParameterizedType` behaviours. By default, Ecto provides + the following custom types: + + Custom type | Database type | Elixir type + :---------------------- | :---------------------- | :--------------------- + `Ecto.UUID` | `:uuid` (as a binary) | `string()` (as a UUID) + `Ecto.Enum` | `:string` | `atom()` + + Finally, schemas can also have virtual fields by passing the + `virtual: true` option. These fields are not persisted to the database + and can optionally not be type checked by declaring type `:any`. + + ### The datetime types + + Four different datetime primitive types are available: + + * `naive_datetime` - has a precision of seconds and casts values + to Elixir's `NaiveDateTime` struct which has no timezone information. + + * `naive_datetime_usec` - has a default precision of microseconds and + also casts values to `NaiveDateTime` with no timezone information. + + * `utc_datetime` - has a precision of seconds and casts values to + Elixir's `DateTime` struct and expects the time zone to be set to UTC. + + * `utc_datetime_usec` has a default precision of microseconds and also + casts values to `DateTime` expecting the time zone be set to UTC. + + All of those types are represented by the same timestamp/datetime in the + underlying data storage, the difference are in their precision and how the + data is loaded into Elixir. + + Having different precisions allows developers to choose a type that will + be compatible with the database and your project's precision requirements. + For example, some older versions of MySQL do not support microseconds in + datetime fields. + + When choosing what datetime type to work with, keep in mind that Elixir + functions like `NaiveDateTime.utc_now/0` have a default precision of 6. + Casting a value with a precision greater than 0 to a non-`usec` type will + truncate all microseconds and set the precision to 0. + + ### The map type + + The map type allows developers to store an Elixir map directly + in the database: + + # In your migration + create table(:users) do + add :data, :map + end + + # In your schema + field :data, :map + + # Now in your code + user = Repo.insert! %User{data: %{"foo" => "bar"}} + + Keep in mind that we advise the map keys to be strings or integers + instead of atoms. Atoms may be accepted depending on how maps are + serialized but the database will always convert atom keys to strings + due to security reasons. + + In order to support maps, different databases may employ different + techniques. For example, PostgreSQL will store those values in jsonb + fields, allowing you to just query parts of it. MSSQL, on + the other hand, does not yet provide a JSON type, so the value will be + stored in a text field. + + For maps to work in such databases, Ecto will need a JSON library. + By default Ecto will use [Jason](https://github.com/michalmuskala/jason) + which needs to be added to your deps in `mix.exs`: + + {:jason, "~> 1.0"} + + You can however configure the adapter to use another library. For example, + if using Postgres: + + config :postgrex, :json_library, YourLibraryOfChoice + + Or if using MySQL: + + config :myxql, :json_library, YourLibraryOfChoice + + If changing the JSON library, remember to recompile the adapter afterwards + by cleaning the current build: + + mix deps.clean --build postgrex + + ### Casting + + When directly manipulating the struct, it is the responsibility of + the developer to ensure the field values have the proper type. For + example, you can create a user struct with an invalid value + for `age`: + + iex> user = %User{age: "0"} + iex> user.age + "0" + + However, if you attempt to persist the struct above, an error will + be raised since Ecto validates the types when sending them to the + adapter/database. + + Therefore, when working with and manipulating external data, it is + recommended to use `Ecto.Changeset`'s that are able to filter + and properly cast external data: + + changeset = Ecto.Changeset.cast(%User{}, %{"age" => "0"}, [:age]) + user = Repo.insert!(changeset) + + **You can use Ecto schemas and changesets to cast and validate any kind + of data, regardless if the data will be persisted to an Ecto repository + or not**. + + ## Reflection + + Any schema module will generate the `__schema__` function that can be + used for runtime introspection of the schema: + + * `__schema__(:source)` - Returns the source as given to `schema/2`; + * `__schema__(:prefix)` - Returns optional prefix for source provided by + `@schema_prefix` schema attribute; + * `__schema__(:primary_key)` - Returns a list of primary key fields (empty if there is none); + + * `__schema__(:fields)` - Returns a list of all non-virtual field names; + * `__schema__(:virtual_fields)` - Returns a list of all virtual field names; + * `__schema__(:field_source, field)` - Returns the alias of the given field; + + * `__schema__(:type, field)` - Returns the type of the given non-virtual field; + * `__schema__(:virtual_type, field)` - Returns the type of the given virtual field; + + * `__schema__(:associations)` - Returns a list of all association field names; + * `__schema__(:association, assoc)` - Returns the association reflection of the given assoc; + + * `__schema__(:embeds)` - Returns a list of all embedded field names; + * `__schema__(:embed, embed)` - Returns the embedding reflection of the given embed; + + * `__schema__(:read_after_writes)` - Non-virtual fields that must be read back + from the database after every write (insert, update, and delete); + + * `__schema__(:autogenerate_id)` - Primary key that is auto generated on insert; + * `__schema__(:autogenerate_fields)` - Returns a list of fields names that are auto + generated on insert, except for the primary key; + + * `__schema__(:redact_fields)` - Returns a list of redacted field names; + + Furthermore, both `__struct__` and `__changeset__` functions are + defined so structs and changeset functionalities are available. + + ## Working with typespecs + + Generating typespecs for schemas is out of the scope of `Ecto.Schema`. + + In order to be able to use types such as `User.t()`, `t/0` has to be defined manually: + + defmodule User do + use Ecto.Schema + + @type t :: %__MODULE__{ + name: String.t(), + age: non_neg_integer() + } + + # ... schema ... + end + + Defining the type of each field is not mandatory, but it is preferable. + """ + + alias Ecto.Schema.Metadata + + @type source :: String.t() + @type prefix :: any() + @type schema :: %{optional(atom) => any, __struct__: atom, __meta__: Metadata.t()} + @type embedded_schema :: %{optional(atom) => any, __struct__: atom} + @type t :: schema | embedded_schema + @type belongs_to(t) :: t | Ecto.Association.NotLoaded.t() + @type has_one(t) :: t | Ecto.Association.NotLoaded.t() + @type has_many(t) :: [t] | Ecto.Association.NotLoaded.t() + @type many_to_many(t) :: [t] | Ecto.Association.NotLoaded.t() + @type embeds_one(t) :: t + @type embeds_many(t) :: [t] + + @doc false + defmacro __using__(_) do + quote do + import Ecto.Schema, only: [schema: 2, embedded_schema: 1] + + @primary_key nil + @timestamps_opts [] + @foreign_key_type :id + @schema_prefix nil + @schema_context nil + @field_source_mapper fn x -> x end + + Module.register_attribute(__MODULE__, :ecto_primary_keys, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_fields, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_virtual_fields, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_query_fields, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_field_sources, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_assocs, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_embeds, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_raw, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_autogenerate, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_autoupdate, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_redact_fields, accumulate: true) + Module.put_attribute(__MODULE__, :ecto_derive_inspect_for_redacted_fields, true) + Module.put_attribute(__MODULE__, :ecto_autogenerate_id, nil) + end + end + + @field_opts [ + :default, + :source, + :autogenerate, + :read_after_writes, + :virtual, + :primary_key, + :load_in_query, + :redact, + :foreign_key, + :on_replace, + :defaults, + :type, + :where, + :references, + :skip_default_validation, + :writable + ] + + @doc """ + Defines an embedded schema with the given field definitions. + + An embedded schema is either embedded into another + schema or kept exclusively in memory. For this reason, + an embedded schema does not require a source name and + it does not include a metadata field. + + Embedded schemas by default set the primary key type + to `:binary_id` but such can be configured with the + `@primary_key` attribute. + + `belongs_to/3` associations may be defined inside of + embedded schemas. However, any association nested inside + of an embedded schema won't be persisted to the database + when calling `c:Ecto.Repo.insert/2` or `c:Ecto.Repo.update/2`. + """ + defmacro embedded_schema(do: block) do + schema(__CALLER__, nil, false, :binary_id, block) + end + + @doc """ + Defines a schema struct with a source name and field definitions. + + An additional field called `__meta__` is added to the struct for storing + internal Ecto state. This field always has a `Ecto.Schema.Metadata` struct + as value and can be manipulated with the `Ecto.put_meta/2` function. + """ + defmacro schema(source, do: block) do + schema(__CALLER__, source, true, :id, block) + end + + defp schema(caller, source, meta?, type, block) do + prelude = + quote do + if line = Module.get_attribute(__MODULE__, :ecto_schema_defined) do + raise "schema already defined for #{inspect(__MODULE__)} on line #{line}" + end + + @ecto_schema_defined unquote(caller.line) + + @after_compile Ecto.Schema + Module.register_attribute(__MODULE__, :ecto_changeset_fields, accumulate: true) + Module.register_attribute(__MODULE__, :ecto_struct_fields, accumulate: true) + + meta? = unquote(meta?) + source = unquote(source) + prefix = @schema_prefix + context = @schema_context + + # Those module attributes are accessed only dynamically + # so we explicitly reference them here to avoid warnings. + _ = @foreign_key_type + _ = @timestamps_opts + + if meta? do + unless is_binary(source) do + raise ArgumentError, "schema source must be a string, got: #{inspect(source)}" + end + + meta = %Metadata{ + state: :built, + source: source, + prefix: prefix, + context: context, + schema: __MODULE__ + } + + Module.put_attribute(__MODULE__, :ecto_struct_fields, {:__meta__, meta}) + end + + if @primary_key == nil do + @primary_key {:id, unquote(type), autogenerate: true} + end + + primary_key_fields = + case @primary_key do + false -> + [] + + {name, type, opts} -> + Ecto.Schema.__field__(__MODULE__, name, type, [primary_key: true] ++ opts) + [name] + + other -> + raise ArgumentError, "@primary_key must be false or {name, type, opts}" + end + + try do + import Ecto.Schema + unquote(block) + after + :ok + end + end + + postlude = + quote unquote: false do + primary_key_fields = @ecto_primary_keys |> Enum.reverse() + autogenerate = @ecto_autogenerate |> Enum.reverse() + autoupdate = @ecto_autoupdate |> Enum.reverse() + fields = @ecto_fields |> Enum.reverse() + query_fields = @ecto_query_fields |> Enum.reverse() + virtual_fields = @ecto_virtual_fields |> Enum.reverse() + field_sources = @ecto_field_sources |> Enum.reverse() + assocs = @ecto_assocs |> Enum.reverse() + embeds = @ecto_embeds |> Enum.reverse() + redacted_fields = @ecto_redact_fields + loaded = Ecto.Schema.__loaded__(__MODULE__, @ecto_struct_fields) + + if redacted_fields != [] and not List.keymember?(@derive, Inspect, 0) and + @ecto_derive_inspect_for_redacted_fields do + @derive {Inspect, except: @ecto_redact_fields} + end + + defstruct Enum.reverse(@ecto_struct_fields) + + def __changeset__ do + %{unquote_splicing(Macro.escape(@ecto_changeset_fields))} + end + + def __schema__(:prefix), do: unquote(Macro.escape(prefix)) + def __schema__(:source), do: unquote(source) + def __schema__(:fields), do: unquote(Enum.map(fields, &elem(&1, 0))) + def __schema__(:query_fields), do: unquote(Enum.map(query_fields, &elem(&1, 0))) + def __schema__(:primary_key), do: unquote(primary_key_fields) + def __schema__(:hash), do: unquote(:erlang.phash2({primary_key_fields, query_fields})) + def __schema__(:read_after_writes), do: unquote(Enum.reverse(@ecto_raw)) + def __schema__(:autogenerate_id), do: unquote(Macro.escape(@ecto_autogenerate_id)) + def __schema__(:autogenerate), do: unquote(Macro.escape(autogenerate)) + def __schema__(:autoupdate), do: unquote(Macro.escape(autoupdate)) + def __schema__(:loaded), do: unquote(Macro.escape(loaded)) + def __schema__(:redact_fields), do: unquote(redacted_fields) + def __schema__(:virtual_fields), do: unquote(Enum.map(virtual_fields, &elem(&1, 0))) + + def __schema__(:updatable_fields) do + unquote( + for {name, {_, writable}} <- fields, reduce: {[], []} do + {keep, drop} -> + case writable do + :always -> {[name | keep], drop} + _ -> {keep, [name | drop]} + end + end + ) + end + + def __schema__(:insertable_fields) do + unquote( + for {name, {_, writable}} <- fields, reduce: {[], []} do + {keep, drop} -> + case writable do + :never -> {keep, [name | drop]} + _ -> {[name | keep], drop} + end + end + ) + end + + def __schema__(:autogenerate_fields), + do: unquote(Enum.flat_map(autogenerate, &elem(&1, 0))) + + if meta? do + def __schema__(:query) do + %Ecto.Query{ + from: %Ecto.Query.FromExpr{ + source: {unquote(source), __MODULE__}, + prefix: unquote(Macro.escape(prefix)) + } + } + end + end + + for clauses <- + Ecto.Schema.__schema__( + fields, + field_sources, + assocs, + embeds, + virtual_fields + ), + {args, body} <- clauses do + def __schema__(unquote_splicing(args)), do: unquote(body) + end + + :ok + end + + quote do + unquote(prelude) + unquote(postlude) + end + end + + ## API + + @doc """ + Defines a field on the schema with given name and type. + + The field name will be used as is to read and write to the database + by all of the built-in adapters unless overridden with the `:source` + option. + + ## Options + + * `:default` - Sets the default value on the schema and the struct. + + The default value is calculated at compilation time, so don't use + expressions like `DateTime.utc_now` or `Ecto.UUID.generate` as + they would then be the same for all records: in this scenario you can use + the `:autogenerate` option to generate at insertion time. + + The default value is validated against the field's type at compilation time + and it will raise an ArgumentError if there is a type mismatch. If you cannot + infer the field's type at compilation time, you can use the + `:skip_default_validation` option on the field to skip validations. + + Once a default value is set, if you send changes to the changeset that + contains the same value defined as default, validations will not be performed + since there are no changes after all. + + * `:source` - Defines the name that is to be used in the database for this field. + This is useful when attaching to an existing database. The value should be + an atom. This is a last minute translation before the query goes to the database. + All references within your Elixir code must still be to the field name, + such as in association foreign keys. + + * `:autogenerate` - a `{module, function, args}` tuple for a function + to call to generate the field value before insertion if value is not set. + A shorthand value of `true` is equivalent to `{type, :autogenerate, []}`. + + * `:read_after_writes` - When true, the field is always read back + from the database after inserts, updates, and deletes. + + For relational databases, this means the RETURNING option of those + statements is used. For this reason, MySQL does not support this + option and will raise an error if a schema is inserted/updated with + read after writes fields. + + * `:virtual` - When true, the field is not persisted to the database. + Notice virtual fields do not support `:autogenerate` nor + `:read_after_writes`. + + * `:primary_key` - When true, the field is used as part of the + composite primary key. + + * `:load_in_query` - When false, the field will not be loaded when + selecting the whole struct in a query, such as `from p in Post, select: p`. + Defaults to `true`. + + * `:redact` - When true, it will display a value of `**redacted**` + when inspected in changes inside a `Ecto.Changeset` and be excluded + from inspect on the schema. Defaults to `false`. + + * `:skip_default_validation` - When true, it will skip the type validation + step at compile time. + + * `:writable` - Defines when a field is allowed to be modified. Must be one of + `:always`, `:insert`, or `:never`. If set to `:always`, the field can be modified + by any repo operation. If set to `:insert`, the field can be inserted but cannot + be further modified, even in an upsert. If set to `:never`, the field becomes + read only. Defaults to `:always`. + + """ + defmacro field(name, type \\ :string, opts \\ []) do + quote do + Ecto.Schema.__field__(__MODULE__, unquote(name), unquote(type), unquote(opts)) + end + end + + @doc """ + Generates `:inserted_at` and `:updated_at` timestamp fields. + + The fields generated by this macro will automatically be set to + the current time when inserting and updating values in a repository. + + ## Options + + * `:inserted_at` - the Ecto schema name of the field for insertion times or `false` + * `:updated_at` - the Ecto schema name of the field for update times or `false` + * `:inserted_at_source` - the name of the database column for insertion times or `false` + * `:updated_at_source` - the name of the database column for update times or `false` + * `:type` - the timestamps type, defaults to `:naive_datetime`. + * `:autogenerate` - a module-function-args tuple used for generating + both `inserted_at` and `updated_at` timestamps + + All options can be pre-configured by setting `@timestamps_opts`. + """ + defmacro timestamps(opts \\ []) do + quote bind_quoted: binding() do + Ecto.Schema.__define_timestamps__(__MODULE__, Keyword.merge(@timestamps_opts, opts)) + end + end + + @doc ~S""" + Indicates a one-to-many association with another schema. + + The current schema has zero or more records of the other schema. The other + schema often has a `belongs_to` field with the reverse association. + + ## Options + + * `:foreign_key` - Sets the foreign key, this should map to a field on the + other schema, defaults to the underscored name of the current schema + suffixed by `_id` + + * `:references` - Sets the key on the current schema to be used for the + association, defaults to the primary key on the schema + + * `:through` - Allow this association to be defined in terms of existing + associations. Read the [section on `:through` associations](#has_many/3-has_many-has_one-through) + for more info + + * `:on_delete` - The action taken on associations when parent record + is deleted. May be `:nothing` (default), `:nilify_all` and `:delete_all`. + Using this option is DISCOURAGED for most relational databases. Instead, + in your migration, set `references(:parent_id, on_delete: :delete_all)`. + Opposite to the migration option, this option cannot guarantee integrity + and it is only triggered for `c:Ecto.Repo.delete/2` (and not on + `c:Ecto.Repo.delete_all/2`) and it never cascades. If posts has many comments, + which has many tags, and you delete a post, only comments will be deleted. + If your database does not support references, cascading can be manually + implemented by using `Ecto.Multi` or `Ecto.Changeset.prepare_changes/2`. + + * `:on_replace` - The action taken on associations when the record is + replaced when casting or manipulating parent changeset. May be + `:raise` (default), `:mark_as_invalid`, `:nilify`, `:delete` or + `:delete_if_exists`. See `Ecto.Changeset`'s section about `:on_replace` for + more info. + + * `:defaults` - Default values to use when building the association. + It may be a keyword list of options that override the association schema + or an `atom`/`{module, function, args}` that receives the association struct + and the owner struct as arguments. For example, if you set + `Post.has_many :comments, defaults: [public: true]`, + then when using `Ecto.build_assoc(post, :comments)`, the comment will have + `comment.public == true`. Alternatively, you can set it to + `Post.has_many :comments, defaults: :update_comment`, which will invoke + `Post.update_comment(comment, post)`, or set it to a MFA tuple such as + `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(comment, post, arg3, arg4)` + + * `:where` - A filter for the association. See "Filtering associations" below. + It does not apply to `:through` associations. + + * `:preload_order` - Sets the default `order_by` when preloading the association. + It may be a keyword list/list of fields or an MFA tuple, such as `{Mod, fun, []}`. + Both cases must resolve to a valid `order_by` expression. + For example, if you set `Post.has_many :comments, preload_order: [asc: :content]`, + whenever the `:comments` associations is preloaded, + the comments will be ordered by the `:content` field. + See `Ecto.Query.order_by/3` to learn more about ordering expressions. + + ## Examples + + defmodule Post do + use Ecto.Schema + schema "posts" do + has_many :comments, Comment + end + end + + # Get all comments for a given post + post = Repo.get(Post, 42) + comments = Repo.all assoc(post, :comments) + + # The comments can come preloaded on the post struct + [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments)) + post.comments #=> [%Comment{...}, ...] + + `has_many` can be used to define hierarchical relationships within a single + schema, for example threaded comments. + + defmodule Comment do + use Ecto.Schema + schema "comments" do + field :content, :string + field :parent_id, :integer + belongs_to :parent, Comment, foreign_key: :parent_id, references: :id, define_field: false + has_many :children, Comment, foreign_key: :parent_id, references: :id + end + end + + ## Filtering associations + + It is possible to specify a `:where` option that will filter the records + returned by the association. Querying, joining or preloading the association + will use the given conditions as shown next: + + defmodule Post do + use Ecto.Schema + + schema "posts" do + has_many :public_comments, Comment, + where: [public: true] + end + end + + The `:where` option expects a keyword list where the key is an atom + representing the field and the value is either: + + * `nil` - which specifies the field must be nil + * `{:not, nil}` - which specifies the field must not be nil + * `{:in, list}` - which specifies the field must be one of the values in a list + * `{:fragment, expr}` - which specifies a fragment string as the filter + (see `Ecto.Query.API.fragment/1`) with the field's value given to it + as the only argument + * or any other value which the field is compared directly against + + Note the values above are distinctly different from the values you + would pass to `where` when building a query. For example, if you + attempt to build a query such as + + from Post, where: [id: nil] + + it will emit an error. This is because queries can be built dynamically, + and therefore passing `nil` can lead to security errors. However, the + `:where` values for an association are given at compile-time, which is + less dynamic and cannot leverage the full power of Ecto queries, which + explains why they have different APIs. + + **Important!** Please use this feature only when strictly necessary, + otherwise it is very easy to end-up with large schemas with dozens of + different associations polluting your schema and affecting your + application performance. For instance, if you are using associations + only for different querying purposes, then it is preferable to build + and compose queries. For instance, instead of having two associations, + one for comments and another for deleted comments, you might have + a single comments association and filter it instead: + + posts + |> Ecto.assoc(:comments) + |> Comment.deleted() + + Or when preloading: + + from posts, preload: [comments: ^Comment.deleted()] + + ## has_many/has_one :through + + Ecto also supports defining associations in terms of other associations + via the `:through` option. Let's see an example: + + defmodule Post do + use Ecto.Schema + + schema "posts" do + has_many :comments, Comment + has_one :permalink, Permalink + + # In the has_many :through example below, the `:comments` + # in the list [:comments, :author] refers to the + # `has_many :comments` in the Post own schema and the + # `:author` refers to the `belongs_to :author` of the + # Comment's schema (the module below). + # (see the description below for more details) + has_many :comments_authors, through: [:comments, :author] + + # Specify the association with custom source + has_many :tags, {"posts_tags", Tag} + end + end + + defmodule Comment do + use Ecto.Schema + + schema "comments" do + belongs_to :author, Author + belongs_to :post, Post + has_one :post_permalink, through: [:post, :permalink] + end + end + + In the example above, we have defined a `has_many :through` association + named `:comments_authors`. A `:through` association always expects a list + and the first element of the list must be a previously defined association + in the current module. For example, `:comments_authors` first points to + `:comments` in the same module (Post), which then points to `:author` in + the next schema, `Comment`. + + This `:through` association will return all authors for all comments + that belongs to that post: + + # Get all comments authors for a given post + post = Repo.get(Post, 42) + authors = Repo.all assoc(post, :comments_authors) + + `:through` associations can also be preloaded. In such cases, not only + the `:through` association is preloaded but all intermediate steps are + preloaded too: + + [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments_authors)) + post.comments_authors #=> [%Author{...}, ...] + + # The comments for each post will be preloaded too + post.comments #=> [%Comment{...}, ...] + + # And the author for each comment too + hd(post.comments).author #=> %Author{...} + + When the `:through` association is expected to return one or zero items, + `has_one :through` should be used instead, as in the example at the beginning + of this section: + + # How we defined the association above in Comments + has_one :post_permalink, through: [:post, :permalink] + + # Get a preloaded comment + [comment] = Repo.all(Comment) |> Repo.preload(:post_permalink) + comment.post_permalink #=> %Permalink{...} + + If possible, Ecto will avoid traversing intermediate associations in + queries. For example, in the example above, `Comment` has a `post_id` + column (defined by `belongs_to :post`) and it is expected for + `Permalink` to have the same. Therefore, when preloading the permalinks, + Ecto may avoid traversing the "posts" table altogether. Of course, this + assumes your database guarantees those references are valid, which can + be done by defining foreign key constraints and references your database + (often done via `EctoSQL` migrations). + + Note `:through` associations are read-only. For example, you cannot use + `Ecto.Changeset.cast_assoc/3` to modify through associations. + """ + defmacro has_many(name, schema, opts \\ []) do + schema = expand_literals(schema, __CALLER__) + opts = expand_literals(opts, __CALLER__) + + quote do + Ecto.Schema.__has_many__(__MODULE__, unquote(name), unquote(schema), unquote(opts)) + end + end + + @doc ~S""" + Indicates a one-to-one association with another schema. + + The current schema has zero or one records of the other schema. The other + schema often has a `belongs_to` field with the reverse association. + + ## Options + + * `:foreign_key` - Sets the foreign key, this should map to a field on the + other schema, defaults to the underscored name of the current module + suffixed by `_id` + + * `:references` - Sets the key on the current schema to be used for the + association, defaults to the primary key on the schema + + * `:through` - If this association must be defined in terms of existing + associations. Read the section in `has_many/3` for more information + + * `:on_delete` - The action taken on associations when parent record + is deleted. May be `:nothing` (default), `:nilify_all` and `:delete_all`. + Using this option is DISCOURAGED for most relational databases. Instead, + in your migration, set `references(:parent_id, on_delete: :delete_all)`. + Opposite to the migration option, this option cannot guarantee integrity + and it is only triggered for `c:Ecto.Repo.delete/2` (and not on + `c:Ecto.Repo.delete_all/2`) and it never cascades. If posts has many comments, + which has many tags, and you delete a post, only comments will be deleted. + If your database does not support references, cascading can be manually + implemented by using `Ecto.Multi` or `Ecto.Changeset.prepare_changes/2` + + * `:on_replace` - The action taken on associations when the record is + replaced when casting or manipulating parent changeset. May be + `:raise` (default), `:mark_as_invalid`, `:nilify`, `:update`, or + `:delete`. See `Ecto.Changeset`'s section on related data for more info. + + * `:defaults` - Default values to use when building the association. + It may be a keyword list of options that override the association schema + or an `atom`/`{module, function, args}` that receives the association struct + and the owner struct as arguments. For example, if you set + `Post.has_one :banner, defaults: [public: true]`, + then when using `Ecto.build_assoc(post, :banner)`, the banner will have + `banner.public == true`. Alternatively, you can set it to + `Post.has_one :banner, defaults: :update_banner`, which will invoke + `Post.update_banner(banner, post)`, or set it to a MFA tuple such as + `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(banner, post, arg3, arg4)` + + * `:where` - A filter for the association. When loading `has_one` associations, + Ecto emits a query with `LIMIT` set to one. If your association may return + multiple entries, you can use this option to guarantee it returns a single + unique result. See "Filtering associations" in `has_many/3`. It does not + apply to `:through` associations. + + ## Examples + + defmodule Post do + use Ecto.Schema + + schema "posts" do + has_one :permalink, Permalink + + # Specify the association with custom source + has_one :category, {"posts_categories", Category} + end + end + + # The permalink can come preloaded on the post struct + [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :permalink)) + post.permalink #=> %Permalink{...} + """ + defmacro has_one(name, schema, opts \\ []) do + schema = expand_literals(schema, __CALLER__) + + quote do + Ecto.Schema.__has_one__(__MODULE__, unquote(name), unquote(schema), unquote(opts)) + end + end + + @doc ~S""" + Indicates a one-to-one or many-to-one association with another schema. + + The current schema belongs to zero or one records of the other schema. The other + schema often has a `has_one` or a `has_many` field with the reverse association. + + You should use `belongs_to` in the table that contains the foreign key. Imagine + a company <-> employee relationship. If the employee contains the `company_id` in + the underlying database table, we say the employee belongs to company. + + In fact, when you invoke this macro, a field with the name of foreign key is + automatically defined in the schema for you. + + ## Options + + * `:foreign_key` - Sets the foreign key field name, defaults to the name + of the association suffixed by `_id`. For example, `belongs_to :company` + will define foreign key of `:company_id`. The associated `has_one` or `has_many` + field in the other schema should also have its `:foreign_key` option set + with the same value. + + * `:references` - Sets the key on the other schema to be used for the + association, defaults to: `:id` + + * `:define_field` - When false, does not automatically define a `:foreign_key` + field, implying the user is defining the field manually elsewhere + + * `:type` - Sets the type of automatically defined `:foreign_key`. + Defaults to: `:integer` and can be set per schema via `@foreign_key_type` + + * `:on_replace` - The action taken on associations when the record is + replaced when casting or manipulating parent changeset. May be + `:raise` (default), `:mark_as_invalid`, `:nilify`, `:update`, or `:delete`. + See `Ecto.Changeset`'s section on related data for more info. + + * `:defaults` - Default values to use when building the association. + It may be a keyword list of options that override the association schema + or an `atom`/`{module, function, args}` that receives the association struct + and the owner struct as arguments. For example, if you set + `Comment.belongs_to :post, defaults: [public: true]`, + then when using `Ecto.build_assoc(comment, :post)`, the post will have + `post.public == true`. Alternatively, you can set it to + `Comment.belongs_to :post, defaults: :update_post`, which will invoke + `Comment.update_post(post, comment)`, or set it to a MFA tuple such as + `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(post, comment, arg3, arg4)` + + * `:primary_key` - If the underlying belongs_to field is a primary key + + * `:source` - Defines the name that is to be used in database for this field + + * `:where` - A filter for the association. See "Filtering associations" + in `has_many/3`. + + ## Examples + + defmodule Comment do + use Ecto.Schema + + schema "comments" do + belongs_to :post, Post + end + end + + # The post can come preloaded on the comment record + [comment] = Repo.all(from(c in Comment, where: c.id == 42, preload: :post)) + comment.post #=> %Post{...} + + If you need custom options on the underlying field, you can define the + field explicitly and then pass `define_field: false` to `belongs_to`: + + defmodule Comment do + use Ecto.Schema + + schema "comments" do + field :post_id, :integer, ... # custom options + belongs_to :post, Post, define_field: false + end + end + + ## Polymorphic associations + + One common use case for belongs to associations is to handle + polymorphism. For example, imagine you have defined a Comment + schema and you wish to use it for commenting on both tasks and + posts. + + Some abstractions would force you to define some sort of + polymorphic association with two fields in your database: + + * commentable_type + * commentable_id + + The problem with this approach is that it breaks references in + the database. You can't use foreign keys and it is very inefficient, + both in terms of query time and storage. + + In Ecto, we have three ways to solve this issue. The simplest + is to define multiple fields in the Comment schema, one for each + association: + + * task_id + * post_id + + Unless you have dozens of columns, this is simpler for the developer, + more DB friendly and more efficient in all aspects. + + Alternatively, because Ecto does not tie a schema to a given table, + we can use separate tables for each association. Let's start over + and define a new Comment schema: + + defmodule Comment do + use Ecto.Schema + + schema "abstract table: comments" do + # This will be used by associations on each "concrete" table + field :assoc_id, :integer + end + end + + Notice we have changed the table name to "abstract table: comments". + You can choose whatever name you want, the point here is that this + particular table will never exist. + + Now in your Post and Task schemas: + + defmodule Post do + use Ecto.Schema + + schema "posts" do + has_many :comments, {"posts_comments", Comment}, foreign_key: :assoc_id + end + end + + defmodule Task do + use Ecto.Schema + + schema "tasks" do + has_many :comments, {"tasks_comments", Comment}, foreign_key: :assoc_id + end + end + + Now each association uses its own specific table, "posts_comments" + and "tasks_comments", which must be created on migrations. The + advantage of this approach is that we never store unrelated data + together, also ensuring we keep database references fast and correct. + + When using this technique, the only limitation is that you cannot + build comments directly. For example, the command below + + Repo.insert!(%Comment{}) + + will attempt to use the abstract table. Instead, one should use + + Repo.insert!(build_assoc(post, :comments)) + + leveraging the `Ecto.build_assoc/3` function. You can also + use `Ecto.assoc/2` or pass a tuple in the query syntax + to easily retrieve associated comments to a given post or + task: + + # Fetch all comments associated with the given task + Repo.all(Ecto.assoc(task, :comments)) + + Or all comments in a given table: + + Repo.all from(c in {"posts_comments", Comment}), ...) + + The third and final option is to use `many_to_many/3` to + define the relationships between the resources. In this case, + the comments table won't have the foreign key, instead there + is an intermediary table responsible for associating the entries: + + defmodule Comment do + use Ecto.Schema + schema "comments" do + # ... + end + end + + In your posts and tasks: + + defmodule Post do + use Ecto.Schema + + schema "posts" do + many_to_many :comments, Comment, join_through: "posts_comments" + end + end + + defmodule Task do + use Ecto.Schema + + schema "tasks" do + many_to_many :comments, Comment, join_through: "tasks_comments" + end + end + + See `many_to_many/3` for more information on this particular approach. + """ + defmacro belongs_to(name, schema, opts \\ []) do + schema = expand_literals(schema, __CALLER__) + + quote do + Ecto.Schema.__belongs_to__(__MODULE__, unquote(name), unquote(schema), unquote(opts)) + end + end + + @doc ~S""" + Indicates a many-to-many association with another schema. + + The association happens through a join schema or source, containing + foreign keys to the associated schemas. For example, the association + below: + + # from MyApp.Post + many_to_many :tags, MyApp.Tag, join_through: "posts_tags" + + is backed by relational databases through a join table as follows: + + [Post] <-> [posts_tags] <-> [Tag] + id <-- post_id + tag_id --> id + + More information on the migration for creating such a schema is shown + below. + + ## Options + + * `:join_through` - Specifies the source of the associated data. + It may be a string, like "posts_tags", representing the + underlying storage table or an atom, like `MyApp.PostTag`, + representing a schema. This option is required. + + * `:join_keys` - Specifies how the schemas are associated. It + expects a keyword list with two entries, the first being how + the join table should reach the current schema and the second + how the join table should reach the associated schema. In the + example above, it defaults to: `[post_id: :id, tag_id: :id]`. + The keys are inflected from the schema names. + + * `:on_delete` - The action taken on associations when the parent record + is deleted. May be `:nothing` (default) or `:delete_all`. + Using this option is DISCOURAGED for most relational databases. Instead, + in your migration, set `references(:parent_id, on_delete: :delete_all)`. + Opposite to the migration option, this option cannot guarantee integrity + and it is only triggered for `c:Ecto.Repo.delete/2` (and not on + `c:Ecto.Repo.delete_all/2`). This option can only remove data from the + join source, never the associated records, and it never cascades. + + * `:on_replace` - The action taken on associations when the record is + replaced when casting or manipulating parent changeset. May be + `:raise` (default), `:mark_as_invalid`, or `:delete`. + `:delete` will only remove data from the join source, never the + associated records. See `Ecto.Changeset`'s section on related data + for more info. + + * `:defaults` - Default values to use when building the association. + It may be a keyword list of options that override the association schema + or an `atom`/`{module, function, args}` that receives the association struct + and the owner struct as arguments. For example, if you set + `Post.many_to_many :tags, defaults: [public: true]`, + then when using `Ecto.build_assoc(post, :tags)`, the tag will have + `tag.public == true`. Alternatively, you can set it to + `Post.many_to_many :tags, defaults: :update_tag`, which will invoke + `Post.update_tag(tag, post)`, or set it to a MFA tuple such as + `{Mod, fun, [arg3, arg4]}`, which will invoke `Mod.fun(tag, post, arg3, arg4)` + + * `:join_defaults` - The same as `:defaults` but it applies to the join schema + instead. This option will raise if it is given and the `:join_through` value + is not a schema. + + * `:unique` - When true, checks if the associated entries are unique + whenever the association is cast or changed via the parent record. + For instance, it would verify that a given tag cannot be attached to + the same post more than once. This exists mostly as a quick check + for user feedback, as it does not guarantee uniqueness at the database + level. Therefore, you should also set a unique index in the database + join table, such as: `create unique_index(:posts_tags, [:post_id, :tag_id])` + + * `:where` - A filter for the association. See "Filtering associations" + in `has_many/3` + + * `:join_where` - A filter for the join table. See "Filtering associations" + in `has_many/3` + + * `:preload_order` - Sets the default `order_by` when preloading the association. + It may be a keyword list/list of fields or an MFA tuple, such as `{Mod, fun, []}`. + Both cases must resolve to a valid `order_by` expression. See `Ecto.Query.order_by/3` + to learn more about ordering expressions. + See the [preload order](#many_to_many/3-preload-order) section below to learn how + this option can be utilized + + ## Using Ecto.assoc/2 + + One of the benefits of using `many_to_many` is that Ecto will avoid + loading the intermediate whenever possible, making your queries more + efficient. For this reason, developers should not refer to the join + table of `many_to_many` in queries. The join table is accessible in + few occasions, such as in `Ecto.assoc/2`. For example, if you do this: + + post + |> Ecto.assoc(:tags) + |> where([t, _pt, p], p.public == t.public) + + It may not work as expected because the `posts_tags` table may not be + included in the query. You can address this problem in multiple ways. + One option is to use `...`: + + post + |> Ecto.assoc(:tags) + |> where([t, ..., p], p.public == t.public) + + Another and preferred option is to rewrite to an explicit `join`, which + leaves out the intermediate bindings as they are resolved only later on: + + # keyword syntax + from t in Tag, + join: p in assoc(t, :post), on: p.id == ^post.id + + # pipe syntax + Tag + |> join(:inner, [t], p in assoc(t, :post), on: p.id == ^post.id) + + If you need to access the join table, then you likely want to use + `has_many/3` with the `:through` option instead. + + ## Removing data + + If you attempt to remove associated `many_to_many` data, **Ecto will + always remove data from the join schema and never from the target + associations** be it by setting `:on_replace` to `:delete`, `:on_delete` + to `:delete_all` or by using changeset functions such as + `Ecto.Changeset.put_assoc/3`. For example, if a `Post` has a many to many + relationship with `Tag`, setting `:on_delete` to `:delete_all` will + only delete entries from the "posts_tags" table in case `Post` is + deleted. + + ## Migration + + How your migration should be structured depends on the value you pass + in `:join_through`. If `:join_through` is simply a string, representing + a table, you may define a table without primary keys and you must not + include any further columns, as those values won't be set by Ecto: + + create table(:posts_tags, primary_key: false) do + add :post_id, references(:posts) + add :tag_id, references(:tags) + end + + However, if your `:join_through` is a schema, like `MyApp.PostTag`, your + join table may be structured as any other table in your codebase, + including timestamps: + + create table(:posts_tags) do + add :post_id, references(:posts) + add :tag_id, references(:tags) + timestamps() + end + + Because `:join_through` contains a schema, in such cases, autogenerated + values and primary keys will be automatically handled by Ecto. + + ## Preload Order + + The `:preload_order` option may be used to return the preloaded structs + in a deterministic order. It accepts either a compile-time keyword list/list + or an MFA tuple, such as `{Mod, fun, []}`. The MFA tuple will be used to + generate the `order_by` expression at runtime. + + When specifying a compile-time keyword list/list, the ordering applies to the + association's table and not the join table. Ordering by the join table can be + achieved by specifying an MFA tuple that utilizes `Ecto.Query.dynamic/2`. + + For example, say we have an association `Assoc` being joined through the table + `join_through`. The default preload query generated by Ecto is roughly: + + from a in Assoc, join: jt in "join_through", on: ... + + If `:preload_order` is given as `[asc: :field]` then the preload query will be + changed to the following: + + from a in Assoc, join: jt in "join_through", on: ..., order_by: [asc: a.field] + + Similarly, any compile-time keyword list/list will have its fields interpreted + as belonging to the association's table. To order by a field from the join table, + an MFA tuple can be specified that utilizes `Ecto.Query.dynamic/2`. + + For example, if `:preload_order` is given as `{Mod, fun, []}`, corresponding to + the following function: + + defmodule Mod do + def fun() do + [desc: dynamic([assoc, join], join.field)] + end + end + + then the preload query will be changed to the following: + + from a in Assoc, join: jt in "join_through", on: ..., order_by: [desc: jt.field] + + Note the ordering of the bindings. The join table always comes last. + + ## Examples + + defmodule Post do + use Ecto.Schema + schema "posts" do + many_to_many :tags, Tag, join_through: "posts_tags" + end + end + + # Let's create a post and a tag + post = Repo.insert!(%Post{}) + tag = Repo.insert!(%Tag{name: "introduction"}) + + # We can associate at any time post and tags together using changesets + post + |> Repo.preload(:tags) # Load existing data + |> Ecto.Changeset.change() # Build the changeset + |> Ecto.Changeset.put_assoc(:tags, [tag]) # Set the association + |> Repo.update! + + # In a later moment, we may get all tags for a given post + post = Repo.get(Post, 42) + tags = Repo.all(assoc(post, :tags)) + + # The tags may also be preloaded on the post struct for reading + [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :tags)) + post.tags #=> [%Tag{...}, ...] + + ## Join Schema Example + + You may prefer to use a join schema to handle many_to_many associations. The + decoupled nature of Ecto allows us to create a "join" struct which + `belongs_to` both sides of the many to many association. + + In our example, a `User` has and belongs to many `Organization`s: + + defmodule MyApp.Repo.Migrations.CreateUserOrganization do + use Ecto.Migration + + def change do + create table(:users_organizations) do + add :user_id, references(:users) + add :organization_id, references(:organizations) + + timestamps() + end + end + end + + defmodule UserOrganization do + use Ecto.Schema + + @primary_key false + schema "users_organizations" do + belongs_to :user, User + belongs_to :organization, Organization + timestamps() # Added bonus, a join schema will also allow you to set timestamps + end + + def changeset(struct, params \\ %{}) do + struct + |> Ecto.Changeset.cast(params, [:user_id, :organization_id]) + |> Ecto.Changeset.validate_required([:user_id, :organization_id]) + # Maybe do some counter caching here! + end + end + + defmodule User do + use Ecto.Schema + + schema "users" do + many_to_many :organizations, Organization, join_through: UserOrganization + end + end + + defmodule Organization do + use Ecto.Schema + + schema "organizations" do + many_to_many :users, User, join_through: UserOrganization + end + end + + To create the association, pass in the IDs of an existing `User` and + `Organization` to `UserOrganization.changeset/2`: + + changeset = UserOrganization.changeset(%UserOrganization{}, %{user_id: id, organization_id: id}) + + case Repo.insert(changeset) do + {:ok, assoc} -> # Assoc was created! + {:error, changeset} -> # Handle the error + end + """ + defmacro many_to_many(name, schema, opts \\ []) do + schema = expand_literals(schema, __CALLER__) + opts = expand_literals(opts, __CALLER__) + + quote do + Ecto.Schema.__many_to_many__(__MODULE__, unquote(name), unquote(schema), unquote(opts)) + end + end + + ## Embeds + + @doc ~S""" + Indicates an embedding of a schema. + + The current schema has zero or one records of the other schema embedded + inside of it. It uses a field similar to the `:map` type for storage, + but allows embeds to have all the things regular schema can. + + You must declare your `embeds_one/3` field with type `:map` at the + database level. + + The embedded may or may not have a primary key. Ecto uses the primary keys + to detect if an embed is being updated or not. If a primary key is not present, + `:on_replace` should be set to either `:update` or `:delete` if there is a + desire to either update or delete the current embed when a new one is set. + + ## Options + + * `:primary_key` - The `:primary_key` option can be used with the same arguments + as `@primary_key` (see the [Schema attributes](https://hexdocs.pm/ecto/Ecto.Schema.html#module-schema-attributes) + section for more info). Primary keys are automatically set up for embedded schemas as well, + defaulting to `{:id, :binary_id, autogenerate: true}`. + + * `:on_replace` - The action taken on associations when the embed is + replaced when casting or manipulating parent changeset. May be + `:raise` (default), `:mark_as_invalid`, `:update`, or `:delete`. + See `Ecto.Changeset`'s section on related data for more info. + + * `:source` - Defines the name that is to be used in database for this field. + This is useful when attaching to an existing database. The value should be + an atom. + + * `:load_in_query` - When false, the field will not be loaded when + selecting the whole struct in a query, such as `from p in Post, select: p`. + Defaults to `true`. + + * `:defaults_to_struct` - When true, the field will default to the initialized + struct instead of nil, the same you would get from something like `%Order.Item{}`. + One important thing is that if the underlying data is explicitly nil when loading + the schema, it will still be loaded as nil, similar to how `:default` works in fields. + Defaults to `false`. + + ## Examples + + defmodule Order do + use Ecto.Schema + + schema "orders" do + embeds_one :item, Item + end + end + + defmodule Item do + use Ecto.Schema + + embedded_schema do + field :title + end + end + + # The item is loaded with the order + order = Repo.get!(Order, 42) + order.item #=> %Item{...} + + Adding and removal of embeds can only be done via the `Ecto.Changeset` + API so Ecto can properly track the embed life-cycle: + + order = Repo.get!(Order, 42) + item = %Item{title: "Soap"} + + # Generate a changeset + changeset = Ecto.Changeset.change(order) + + # Put a new embed to the changeset + changeset = Ecto.Changeset.put_embed(changeset, :item, item) + + # Update the order, and fetch the item + item = Repo.update!(changeset).item + + # Item is generated with a unique identification + item + # => %Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Soap"} + + ## Inline embedded schema + + The schema module can be defined inline in the parent schema in simple + cases: + + defmodule Parent do + use Ecto.Schema + + schema "parents" do + field :name, :string + + embeds_one :child, Child do + field :name, :string + field :age, :integer + end + end + end + + Options should be passed before the `do` block like this: + + embeds_one :child, Child, on_replace: :delete, primary_key: false do + field :name, :string + field :age, :integer + end + + Defining embedded schema in such a way will define a `Parent.Child` module + with the appropriate struct. In order to properly cast the embedded schema. + When casting the inline-defined embedded schemas you need to use the `:with` + option of `Ecto.Changeset.cast_embed/3` to provide the proper function to do the casting. + For example: + + def changeset(schema, params) do + schema + |> cast(params, [:name]) + |> cast_embed(:child, with: &child_changeset/2) + end + + defp child_changeset(schema, params) do + schema + |> cast(params, [:name, :age]) + end + + ## Encoding and decoding + + Because many databases do not support direct encoding and decoding + of embeds, it is often emulated by Ecto by using specific encoding + and decoding rules. + + For example, PostgreSQL will store embeds on top of JSONB columns, + which means types in embedded schemas won't go through the usual + dump->DB->load cycle but rather encode->DB->decode->cast. This means + that, when using embedded schemas with databases like PG or MySQL, + make sure all of your types can be JSON encoded/decoded correctly. + Ecto provides this guarantee for all built-in types. + + When decoding, if a key exists in the database not defined in the + schema, it'll be ignored. If a field exists in the schema that's not + in the database, it's value will be `nil`. + """ + defmacro embeds_one(name, schema, opts \\ []) + + defmacro embeds_one(name, schema, do: block) do + quote do + embeds_one(unquote(name), unquote(schema), [], do: unquote(block)) + end + end + + defmacro embeds_one(name, schema, opts) do + schema = expand_literals(schema, __CALLER__) + + quote do + Ecto.Schema.__embeds_one__(__MODULE__, unquote(name), unquote(schema), unquote(opts)) + end + end + + @doc """ + Indicates an embedding of a schema. + + For options and examples see documentation of `embeds_one/3`. + """ + defmacro embeds_one(name, schema, opts, do: block) do + schema = expand_nested_module_alias(schema, __CALLER__) + + quote do + {schema, opts} = + Ecto.Schema.__embeds_module__( + __ENV__, + unquote(schema), + unquote(opts), + unquote(Macro.escape(block)) + ) + + Ecto.Schema.__embeds_one__(__MODULE__, unquote(name), schema, opts) + end + end + + @doc ~S""" + Indicates an embedding of many schemas. + + The current schema has zero or more records of the other schema embedded + inside of it. Embeds have all the things regular schemas have. + + It is recommended to declare your `embeds_many/3` field with type `:map` + in your migrations, instead of using `{:array, :map}`. Ecto can work with + both maps and arrays as the container for embeds (and in most databases + maps are represented as JSON which allows Ecto to choose what works best). + + The embedded may or may not have a primary key. Ecto uses the primary keys + to detect if an embed is being updated or not. If a primary key is not + present and you still want the list of embeds to be updated, `:on_replace` + must be set to `:delete`, forcing all current embeds to be deleted and + replaced by new ones whenever a new list of embeds is set. + + For encoding and decoding of embeds, please read the docs for + `embeds_one/3`. + + ## Options + + * `:on_replace` - The action taken on associations when the embed is + replaced when casting or manipulating parent changeset. May be + `:raise` (default), `:mark_as_invalid`, or `:delete`. + See `Ecto.Changeset`'s section on related data for more info. + + * `:source` - Defines the name that is to be used in database for this field. + This is useful when attaching to an existing database. The value should be + an atom. + + * `:load_in_query` - When false, the field will not be loaded when + selecting the whole struct in a query, such as `from p in Post, select: p`. + Defaults to `true`. + + ## Examples + + defmodule Order do + use Ecto.Schema + + schema "orders" do + embeds_many :items, Item + end + end + + defmodule Item do + use Ecto.Schema + + embedded_schema do + field :title + end + end + + # The items are loaded with the order + order = Repo.get!(Order, 42) + order.items #=> [%Item{...}, ...] + + Adding and removal of embeds can only be done via the `Ecto.Changeset` + API so Ecto can properly track the embed life-cycle: + + # Order has no items + order = Repo.get!(Order, 42) + order.items + # => [] + + items = [%Item{title: "Soap"}] + + # Generate a changeset + changeset = Ecto.Changeset.change(order) + + # Put a one or more new items + changeset = Ecto.Changeset.put_embed(changeset, :items, items) + + # Update the order and fetch items + items = Repo.update!(changeset).items + + # Items are generated with a unique identification + items + # => [%Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Soap"}] + + Updating of embeds must be done using a changeset for each changed embed. + + # Order has an existing items + order = Repo.get!(Order, 42) + order.items + # => [%Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Soap"}] + + # Generate a changeset + changeset = Ecto.Changeset.change(order) + + # Put the updated item as a changeset + current_item = List.first(order.items) + item_changeset = Ecto.Changeset.change(current_item, title: "Mujju's Soap") + order_changeset = Ecto.Changeset.put_embed(changeset, :items, [item_changeset]) + + # Update the order and fetch items + items = Repo.update!(order_changeset).items + + # Item has the updated title + items + # => [%Item{id: "20a97d94-f79b-4e63-a875-85deed7719b7", title: "Mujju's Soap"}] + + ## Inline embedded schema + + The schema module can be defined inline in the parent schema in simple + cases: + + defmodule Parent do + use Ecto.Schema + + schema "parents" do + field :name, :string + + embeds_many :children, Child do + field :name, :string + field :age, :integer + end + end + end + + Primary keys are automatically set up for embedded schemas as well, + defaulting to `{:id, :binary_id, autogenerate: true}`. You can + customize it by passing a `:primary_key` option with the same arguments + as `@primary_key` (see the [Schema attributes](https://hexdocs.pm/ecto/Ecto.Schema.html#module-schema-attributes) + section for more info). + + Defining embedded schema in such a way will define a `Parent.Child` module + with the appropriate struct. In order to properly cast the embedded schema. + When casting the inline-defined embedded schemas you need to use the `:with` + option of `cast_embed/3` to provide the proper function to do the casting. + For example: + + def changeset(schema, params) do + schema + |> cast(params, [:name]) + |> cast_embed(:children, with: &child_changeset/2) + end + + defp child_changeset(schema, params) do + schema + |> cast(params, [:name, :age]) + end + + """ + defmacro embeds_many(name, schema, opts \\ []) + + defmacro embeds_many(name, schema, do: block) do + quote do + embeds_many(unquote(name), unquote(schema), [], do: unquote(block)) + end + end + + defmacro embeds_many(name, schema, opts) do + schema = expand_literals(schema, __CALLER__) + + quote do + Ecto.Schema.__embeds_many__(__MODULE__, unquote(name), unquote(schema), unquote(opts)) + end + end + + @doc """ + Indicates an embedding of many schemas. + + For options and examples see documentation of `embeds_many/3`. + """ + defmacro embeds_many(name, schema, opts, do: block) do + schema = expand_nested_module_alias(schema, __CALLER__) + + quote do + {schema, opts} = + Ecto.Schema.__embeds_module__( + __ENV__, + unquote(schema), + unquote(opts), + unquote(Macro.escape(block)) + ) + + Ecto.Schema.__embeds_many__(__MODULE__, unquote(name), schema, opts) + end + end + + # Internal function for integrating associations into schemas. + # + # This function exists as an extension point for libraries to + # experiment new types of associations to Ecto, although it may + # break at any time (as with any of the association callbacks). + # + # This function expects the current schema, the association cardinality, + # the association name, the association module (that implements + # `Ecto.Association` callbacks) and a keyword list of options. + @doc false + @spec association(module, :one | :many, atom(), module, Keyword.t()) :: Ecto.Association.t() + def association(schema, cardinality, name, association, opts) do + not_loaded = %Ecto.Association.NotLoaded{ + __owner__: schema, + __field__: name, + __cardinality__: cardinality + } + + put_struct_field(schema, name, not_loaded) + opts = [cardinality: cardinality] ++ opts + struct = association.struct(schema, name, opts) + Module.put_attribute(schema, :ecto_assocs, {name, struct}) + struct + end + + ## Callbacks + + @doc false + def __timestamps__(:naive_datetime) do + %{NaiveDateTime.utc_now() | microsecond: {0, 0}} + end + + def __timestamps__(:naive_datetime_usec) do + NaiveDateTime.utc_now() + end + + def __timestamps__(:utc_datetime) do + %{DateTime.utc_now() | microsecond: {0, 0}} + end + + def __timestamps__(:utc_datetime_usec) do + DateTime.utc_now() + end + + def __timestamps__(type) do + type.from_unix!(System.os_time(:microsecond), :microsecond) + end + + @doc false + def __loaded__(module, struct_fields) do + case Map.new([{:__struct__, module} | struct_fields]) do + %{__meta__: meta} = struct -> %{struct | __meta__: Map.put(meta, :state, :loaded)} + struct -> struct + end + end + + @doc false + def __field__(mod, name, type, opts) do + # Check the field type before we check options because it is + # better to raise unknown type first than unsupported option. + type = check_field_type!(mod, name, type, opts) + + if type == :any && !opts[:virtual] do + raise ArgumentError, + "only virtual fields can have type :any, " <> + "invalid type for field #{inspect(name)}" + end + + check_options!(type, opts, @field_opts, "field/3") + Module.put_attribute(mod, :ecto_changeset_fields, {name, type}) + validate_default!(type, opts[:default], opts[:skip_default_validation]) + define_field(mod, name, type, opts) + end + + defp define_field(mod, name, type, opts) do + virtual? = opts[:virtual] || false + pk? = opts[:primary_key] || false + writable = opts[:writable] || :always + put_struct_field(mod, name, Keyword.get(opts, :default)) + + if Keyword.get(opts, :redact, false) do + Module.put_attribute(mod, :ecto_redact_fields, name) + end + + if virtual? do + Module.put_attribute(mod, :ecto_virtual_fields, {name, type}) + else + source = opts[:source] || Module.get_attribute(mod, :field_source_mapper).(name) + + if not is_atom(source) do + raise ArgumentError, + "the :source for field `#{name}` must be an atom, got: #{inspect(source)}" + end + + if name != source do + Module.put_attribute(mod, :ecto_field_sources, {name, source}) + end + + if raw = opts[:read_after_writes] do + Module.put_attribute(mod, :ecto_raw, name) + end + + case gen = opts[:autogenerate] do + {_, _, _} -> + store_mfa_autogenerate!(mod, name, type, gen) + + true -> + store_type_autogenerate!(mod, name, source || name, type, pk?) + + _ -> + :ok + end + + if raw && gen do + raise ArgumentError, "cannot mark the same field as autogenerate and read_after_writes" + end + + if writable != :always && gen do + raise ArgumentError, "autogenerated fields must always be writable" + end + + if pk? do + Module.put_attribute(mod, :ecto_primary_keys, name) + end + + if Keyword.get(opts, :load_in_query, true) do + Module.put_attribute(mod, :ecto_query_fields, {name, type}) + end + + Module.put_attribute(mod, :ecto_fields, {name, {type, writable}}) + end + end + + @doc false + def __define_timestamps__(mod, timestamps) do + type = Keyword.get(timestamps, :type, :naive_datetime) + autogen = timestamps[:autogenerate] || {Ecto.Schema, :__timestamps__, [type]} + + inserted_at = Keyword.get(timestamps, :inserted_at, :inserted_at) + updated_at = Keyword.get(timestamps, :updated_at, :updated_at) + + if inserted_at do + opts = if source = timestamps[:inserted_at_source], do: [source: source], else: [] + Ecto.Schema.__field__(mod, inserted_at, type, opts) + end + + if updated_at do + opts = if source = timestamps[:updated_at_source], do: [source: source], else: [] + Ecto.Schema.__field__(mod, updated_at, type, opts) + Module.put_attribute(mod, :ecto_autoupdate, {[updated_at], autogen}) + end + + with [_ | _] = fields <- Enum.filter([inserted_at, updated_at], & &1) do + Module.put_attribute(mod, :ecto_autogenerate, {fields, autogen}) + end + + :ok + end + + @valid_has_options [ + :foreign_key, + :references, + :through, + :on_delete, + :defaults, + :on_replace, + :where, + :preload_order + ] + + @doc false + def __has_many__(mod, name, queryable, opts) do + if is_list(queryable) and Keyword.has_key?(queryable, :through) do + check_options!(queryable, @valid_has_options, "has_many/3") + association(mod, :many, name, Ecto.Association.HasThrough, queryable) + else + check_options!(opts, @valid_has_options, "has_many/3") + struct = association(mod, :many, name, Ecto.Association.Has, [queryable: queryable] ++ opts) + Module.put_attribute(mod, :ecto_changeset_fields, {name, {:assoc, struct}}) + end + end + + @doc false + def __has_one__(mod, name, queryable, opts) do + if is_list(queryable) and Keyword.has_key?(queryable, :through) do + check_options!(queryable, @valid_has_options, "has_one/3") + association(mod, :one, name, Ecto.Association.HasThrough, queryable) + else + check_options!(opts, @valid_has_options, "has_one/3") + struct = association(mod, :one, name, Ecto.Association.Has, [queryable: queryable] ++ opts) + Module.put_attribute(mod, :ecto_changeset_fields, {name, {:assoc, struct}}) + end + end + + # :primary_key is valid here to support associative entity + # https://en.wikipedia.org/wiki/Associative_entity + @valid_belongs_to_options [ + :foreign_key, + :references, + :define_field, + :type, + :on_replace, + :defaults, + :primary_key, + :source, + :where + ] + + @doc false + def __belongs_to__(mod, name, queryable, opts) do + opts = Keyword.put_new(opts, :foreign_key, :"#{name}_id") + + foreign_key_name = opts[:foreign_key] + foreign_key_type = opts[:type] || Module.get_attribute(mod, :foreign_key_type) + foreign_key_type = check_field_type!(mod, name, foreign_key_type, opts) + check_options!(foreign_key_type, opts, @valid_belongs_to_options, "belongs_to/3") + + if foreign_key_name == name do + raise ArgumentError, + "foreign_key #{inspect(name)} must be distinct from corresponding association name" + end + + if Keyword.get(opts, :define_field, true) do + Module.put_attribute(mod, :ecto_changeset_fields, {foreign_key_name, foreign_key_type}) + define_field(mod, foreign_key_name, foreign_key_type, opts) + end + + struct = + association(mod, :one, name, Ecto.Association.BelongsTo, [queryable: queryable] ++ opts) + + Module.put_attribute(mod, :ecto_changeset_fields, {name, {:assoc, struct}}) + end + + @valid_many_to_many_options [ + :join_through, + :join_defaults, + :join_keys, + :on_delete, + :defaults, + :on_replace, + :unique, + :where, + :join_where, + :preload_order + ] + + @doc false + def __many_to_many__(mod, name, queryable, opts) do + check_options!(opts, @valid_many_to_many_options, "many_to_many/3") + + struct = + association(mod, :many, name, Ecto.Association.ManyToMany, [queryable: queryable] ++ opts) + + Module.put_attribute(mod, :ecto_changeset_fields, {name, {:assoc, struct}}) + end + + @valid_embeds_one_options [:on_replace, :source, :load_in_query, :defaults_to_struct] + + @doc false + def __embeds_one__(mod, name, schema, opts) when is_atom(schema) do + check_options!(opts, @valid_embeds_one_options, "embeds_one/3") + + opts = + if Keyword.get(opts, :defaults_to_struct) do + Keyword.put(opts, :default, schema.__schema__(:loaded)) + else + opts + end + + embed(mod, :one, name, schema, opts) + end + + def __embeds_one__(_mod, _name, schema, _opts) do + raise ArgumentError, + "`embeds_one/3` expects `schema` to be a module name, but received #{inspect(schema)}" + end + + @valid_embeds_many_options [:on_replace, :source, :load_in_query] + + @doc false + def __embeds_many__(mod, name, schema, opts) when is_atom(schema) do + check_options!(opts, @valid_embeds_many_options, "embeds_many/3") + opts = Keyword.put(opts, :default, []) + embed(mod, :many, name, schema, opts) + end + + def __embeds_many__(_mod, _name, schema, _opts) do + raise ArgumentError, + "`embeds_many/3` expects `schema` to be a module name, but received #{inspect(schema)}" + end + + @doc false + def __embeds_module__(env, module, opts, block) do + {pk, opts} = Keyword.pop(opts, :primary_key, {:id, :binary_id, autogenerate: true}) + + block = + quote do + use Ecto.Schema + + @primary_key unquote(Macro.escape(pk)) + embedded_schema do + unquote(block) + end + end + + Module.create(module, block, env) + {module, opts} + end + + ## Quoted callbacks + + @doc false + def __after_compile__(%{module: module} = env, _) do + # If we are compiling code, we can validate associations now, + # as the Elixir compiler will solve dependencies. + if Code.can_await_module_compilation?() do + for name <- module.__schema__(:associations) do + assoc = module.__schema__(:association, name) + + case assoc.__struct__.after_compile_validation(assoc, env) do + :ok -> + :ok + + {:error, message} -> + IO.warn( + "invalid association `#{assoc.field}` in schema #{inspect(module)}: #{message}", + Macro.Env.stacktrace(env) + ) + end + end + end + + :ok + end + + @doc false + def __schema__(fields, field_sources, assocs, embeds, virtual_fields) do + load = + for {name, {type, _writable}} <- fields do + if alias = field_sources[name] do + {name, {:source, alias, type}} + else + {name, type} + end + end + + dump = + for {name, {type, writable}} <- fields do + {name, {field_sources[name] || name, type, writable}} + end + + field_sources_quoted = + for {name, {_type, _writable}} <- fields do + {[:field_source, name], field_sources[name] || name} + end + + types_quoted = + for {name, {type, _writable}} <- fields do + {[:type, name], Macro.escape(type)} + end + + virtual_types_quoted = + for {name, type} <- virtual_fields do + {[:virtual_type, name], Macro.escape(type)} + end + + assoc_quoted = + for {name, refl} <- assocs do + {[:association, name], Macro.escape(refl)} + end + + assoc_names = Enum.map(assocs, &elem(&1, 0)) + + embed_quoted = + for {name, refl} <- embeds do + {[:embed, name], Macro.escape(refl)} + end + + embed_names = Enum.map(embeds, &elem(&1, 0)) + + single_arg = [ + {[:dump], dump |> Map.new() |> Macro.escape()}, + {[:load], load |> Macro.escape()}, + {[:associations], assoc_names}, + {[:embeds], embed_names} + ] + + catch_all = [ + {[:field_source, quote(do: _)], nil}, + {[:type, quote(do: _)], nil}, + {[:virtual_type, quote(do: _)], nil}, + {[:association, quote(do: _)], nil}, + {[:embed, quote(do: _)], nil} + ] + + [ + single_arg, + field_sources_quoted, + types_quoted, + virtual_types_quoted, + assoc_quoted, + embed_quoted, + catch_all + ] + end + + ## Private + + defp embed(mod, cardinality, name, schema, opts) do + opts = [cardinality: cardinality, related: schema, owner: mod, field: name] ++ opts + struct = Ecto.Embedded.init(opts) + + Module.put_attribute(mod, :ecto_changeset_fields, {name, {:embed, struct}}) + Module.put_attribute(mod, :ecto_embeds, {name, struct}) + define_field(mod, name, {:parameterized, {Ecto.Embedded, struct}}, opts) + end + + defp put_struct_field(mod, name, assoc) do + fields = Module.get_attribute(mod, :ecto_struct_fields) + + if List.keyfind(fields, name, 0) do + raise ArgumentError, + "field/association #{inspect(name)} already exists on schema, you must either remove the duplication or choose a different name" + end + + Module.put_attribute(mod, :ecto_struct_fields, {name, assoc}) + end + + defp validate_default!(_type, _value, true), do: :ok + + defp validate_default!(type, value, _skip) do + case Ecto.Type.dump(type, value) do + {:ok, _} -> + :ok + + _ -> + raise ArgumentError, + "value #{inspect(value)} is invalid for type #{Ecto.Type.format(type)}, can't set default" + end + end + + defp check_options!(opts, valid, fun_arity) do + case Enum.find(opts, fn {k, _} -> k not in valid end) do + {k, _} -> raise ArgumentError, "invalid option #{inspect(k)} for #{fun_arity}" + nil -> :ok + end + end + + defp check_options!({:parameterized, _}, _opts, _valid, _fun_arity) do + :ok + end + + defp check_options!({_, type}, opts, valid, fun_arity) do + check_options!(type, opts, valid, fun_arity) + end + + defp check_options!(_type, opts, valid, fun_arity) do + check_options!(opts, valid, fun_arity) + end + + defp check_field_type!(_mod, name, :datetime, _opts) do + raise ArgumentError, + "invalid type :datetime for field #{inspect(name)}. " <> + "You probably meant to choose one between :naive_datetime " <> + "(no time zone information) or :utc_datetime (time zone is set to UTC)" + end + + defp check_field_type!(mod, name, type, opts) do + cond do + composite?(type, name) -> + {outer_type, inner_type} = type + {outer_type, check_field_type!(mod, name, inner_type, opts)} + + not is_atom(type) -> + raise ArgumentError, "invalid type #{Ecto.Type.format(type)} for field #{inspect(name)}" + + Ecto.Type.base?(type) -> + type + + Code.ensure_compiled(type) == {:module, type} -> + cond do + function_exported?(type, :type, 0) -> + type + + function_exported?(type, :type, 1) -> + Ecto.ParameterizedType.init(type, Keyword.merge(opts, field: name, schema: mod)) + + function_exported?(type, :__schema__, 1) -> + raise ArgumentError, + "schema #{inspect(type)} is not a valid type for field #{inspect(name)}." <> + " Did you mean to use belongs_to, has_one, has_many, embeds_one, or embeds_many instead?" + + true -> + raise ArgumentError, + "module #{inspect(type)} given as type for field #{inspect(name)} is not an Ecto.Type/Ecto.ParameterizedType" + end + + true -> + raise ArgumentError, "unknown type #{inspect(type)} for field #{inspect(name)}" + end + end + + defp composite?({composite, _} = type, name) do + if Ecto.Type.composite?(composite) do + true + else + raise ArgumentError, + "invalid or unknown composite #{inspect(type)} for field #{inspect(name)}. " <> + "Did you mean to use :array or :map as first element of the tuple instead?" + end + end + + defp composite?(_type, _name), do: false + + defp store_mfa_autogenerate!(mod, name, type, mfa) do + if autogenerate_id?(type) do + raise ArgumentError, ":autogenerate with {m, f, a} not supported by ID types" + end + + Module.put_attribute(mod, :ecto_autogenerate, {[name], mfa}) + end + + defp store_type_autogenerate!(mod, name, source, {:parameterized, typemod_params} = type, pk?) do + {typemod, params} = typemod_params + + cond do + store_autogenerate_id!(mod, name, source, type, pk?) -> + :ok + + not function_exported?(typemod, :autogenerate, 1) -> + raise ArgumentError, + "field #{inspect(name)} does not support :autogenerate because it uses a " <> + "parameterized type #{Ecto.Type.format(type)} that does not define autogenerate/1" + + true -> + Module.put_attribute( + mod, + :ecto_autogenerate, + {[name], {typemod, :autogenerate, [params]}} + ) + end + end + + defp store_type_autogenerate!(mod, name, source, type, pk?) do + cond do + store_autogenerate_id!(mod, name, source, type, pk?) -> + :ok + + Ecto.Type.primitive?(type) -> + raise ArgumentError, + "field #{inspect(name)} does not support :autogenerate because it uses a " <> + "primitive type #{Ecto.Type.format(type)}" + + # Note the custom type has already been loaded in check_type!/3 + not function_exported?(type, :autogenerate, 0) -> + raise ArgumentError, + "field #{inspect(name)} does not support :autogenerate because it uses a " <> + "custom type #{Ecto.Type.format(type)} that does not define autogenerate/0" + + true -> + Module.put_attribute(mod, :ecto_autogenerate, {[name], {type, :autogenerate, []}}) + end + end + + defp store_autogenerate_id!(mod, name, source, type, pk?) do + cond do + not autogenerate_id?(type) -> + false + + not pk? -> + raise ArgumentError, + "only primary keys allow :autogenerate for type #{Ecto.Type.format(type)}, " <> + "field #{inspect(name)} is not a primary key" + + Module.get_attribute(mod, :ecto_autogenerate_id) -> + raise ArgumentError, "only one primary key with ID type may be marked as autogenerated" + + true -> + Module.put_attribute(mod, :ecto_autogenerate_id, {name, source, type}) + true + end + end + + defp autogenerate_id?(type), do: Ecto.Type.type(type) in [:id, :binary_id] + + defp expand_literals(ast, env) do + if Macro.quoted_literal?(ast) do + Macro.prewalk(ast, &expand_alias(&1, env)) + else + ast + end + end + + defp expand_alias({:__aliases__, _, _} = alias, env), + do: Macro.expand(alias, %{env | function: {:__schema__, 2}}) + + defp expand_alias(other, _env), do: other + + defp expand_nested_module_alias({:__aliases__, _, [Elixir, _ | _] = alias}, _env), + do: Module.concat(alias) + + defp expand_nested_module_alias({:__aliases__, _, [h | t]}, env) when is_atom(h), + do: Module.concat([env.module, h | t]) + + defp expand_nested_module_alias(other, _env), do: other +end diff --git a/deps/ecto/lib/ecto/schema/loader.ex b/deps/ecto/lib/ecto/schema/loader.ex new file mode 100644 index 0000000000000000000000000000000000000000..8ee64714679284caea8570fe59ef705962094b19 --- /dev/null +++ b/deps/ecto/lib/ecto/schema/loader.ex @@ -0,0 +1,106 @@ +defmodule Ecto.Schema.Loader do + @moduledoc false + + alias Ecto.Schema.Metadata + + @doc """ + Loads a struct to be used as a template in further operations. + """ + def load_struct(nil, _prefix, _source), do: %{} + + def load_struct(schema, prefix, source) do + case schema.__schema__(:loaded) do + %{__meta__: %Metadata{prefix: ^prefix, source: ^source}} = struct -> + struct + + %{__meta__: %Metadata{} = metadata} = struct -> + Map.put(struct, :__meta__, %{metadata | source: source, prefix: prefix}) + + %{} = struct -> + struct + end + end + + @doc """ + Loads data coming from the user/embeds into schema. + + Assumes data does not all belong to schema/struct + and that it may also require source-based renaming. + """ + def unsafe_load(schema, data, loader) do + types = schema.__schema__(:load) + struct = schema.__schema__(:loaded) + unsafe_load(struct, types, data, loader) + end + + @doc """ + Loads data coming from the user/embeds into struct and types. + + Assumes data does not all belong to schema/struct + and that it may also require source-based renaming. + """ + def unsafe_load(struct, types, map, loader) when is_map(map) do + Enum.reduce(types, struct, fn pair, acc -> + {field, source, type} = field_source_and_type(pair) + + case fetch_string_or_atom_field(map, source) do + {:ok, value} -> Map.put(acc, field, load!(struct, field, type, value, loader)) + :error -> acc + end + end) + end + + @compile {:inline, field_source_and_type: 1, fetch_string_or_atom_field: 2} + defp field_source_and_type({field, {:source, source, type}}) do + {field, source, type} + end + + defp field_source_and_type({field, type}) do + {field, field, type} + end + + defp fetch_string_or_atom_field(map, field) when is_atom(field) do + case Map.fetch(map, Atom.to_string(field)) do + {:ok, value} -> {:ok, value} + :error -> Map.fetch(map, field) + end + end + + @compile {:inline, load!: 5} + defp load!(struct, field, type, value, loader) do + case loader.(type, value) do + {:ok, value} -> + value + + :error -> + raise ArgumentError, + "cannot load `#{inspect(value)}` as type #{Ecto.Type.format(type)} " <> + "for field `#{field}`#{error_data(struct)}" + end + end + + defp error_data(%{__struct__: atom}) do + " in schema #{inspect(atom)}" + end + + defp error_data(other) when is_map(other) do + "" + end + + @doc """ + Dumps the given data. + """ + def safe_dump(struct, types, dumper) do + Enum.reduce(types, %{}, fn {field, {source, type, _writable}}, acc -> + value = Map.get(struct, field) + + case dumper.(type, value) do + {:ok, value} -> + Map.put(acc, source, value) + :error -> + raise ArgumentError, "cannot dump `#{inspect value}` as type #{Ecto.Type.format(type)} " <> + "for field `#{field}` in schema #{inspect struct.__struct__}" + end + end) + end +end diff --git a/deps/ecto/lib/ecto/schema/metadata.ex b/deps/ecto/lib/ecto/schema/metadata.ex new file mode 100644 index 0000000000000000000000000000000000000000..cfbec0a98b3ea56a69c95395875f50b66036e063 --- /dev/null +++ b/deps/ecto/lib/ecto/schema/metadata.ex @@ -0,0 +1,66 @@ +defmodule Ecto.Schema.Metadata do + @moduledoc """ + Stores metadata of a struct. + + ## State + + The state of the schema is stored in the `:state` field and allows + following values: + + * `:built` - the struct was constructed in memory and is not persisted + to database yet; + * `:loaded` - the struct was loaded from database and represents + persisted data; + * `:deleted` - the struct was deleted and no longer represents persisted + data. + + ## Source + + The `:source` tracks the (table or collection) where the struct is or should + be persisted to. + + ## Prefix + + Tracks the source prefix in the data storage. + + ## Context + + The `:context` field represents additional state some databases require + for proper updates of data. It is not used by the built-in adapters of + `Ecto.Adapters.Postgres` and `Ecto.Adapters.MySQL`. + + ## Schema + + The `:schema` field refers the module name for the schema this metadata belongs to. + """ + defstruct [:state, :source, :context, :schema, :prefix] + + @type state :: :built | :loaded | :deleted + + @type context :: any + + @type t(schema) :: %__MODULE__{ + context: context, + prefix: Ecto.Schema.prefix(), + schema: schema, + source: Ecto.Schema.source(), + state: state + } + + @type t :: t(module) + + defimpl Inspect do + import Inspect.Algebra + + def inspect(metadata, opts) do + %{source: source, prefix: prefix, state: state, context: context} = metadata + + entries = + for entry <- [state, prefix, source, context], + entry != nil, + do: to_doc(entry, opts) + + concat(["#Ecto.Schema.Metadata<"] ++ Enum.intersperse(entries, ", ") ++ [">"]) + end + end +end diff --git a/deps/ecto/lib/ecto/type.ex b/deps/ecto/lib/ecto/type.ex new file mode 100644 index 0000000000000000000000000000000000000000..1f990cb8e188d32900bd959b31fa1aba330c5c58 --- /dev/null +++ b/deps/ecto/lib/ecto/type.ex @@ -0,0 +1,1590 @@ +defmodule Ecto.Type do + @moduledoc """ + Defines functions and the `Ecto.Type` behaviour for implementing + basic custom types. + + Ecto provides two types of custom types: basic types and + parameterized types. Basic types are simple, requiring only four + callbacks to be implemented, and are enough for most occasions. + Parameterized types can be customized on the field definition and + provide a wide variety of callbacks. + + The definition of basic custom types and all of their callbacks are + available in this module. You can learn more about parameterized + types in `Ecto.ParameterizedType`. If in doubt, prefer to use + basic custom types and rely on parameterized types if you need + the extra functionality. + + ## External vs internal vs database representation + + The core functionality of a custom type is the mapping between + external, internal and database representations of a value belonging + to the type. + + For a definition of external and internal data take a look at the + [related section](`Ecto.Changeset#module-external-vs-internal-data`) + in the changeset documentation. + + ```mermaid + stateDiagram-v2 + external: External Data + internal: Internal Data + database: Database Data + external --> internal: cast/1 + external --> database: dump/1 + internal --> database: dump/1 + database --> internal: load/1 + ``` + + ## Example + + Imagine you want to store a URI struct as part of a schema in a + url-shortening service. There isn't an Ecto field type to support + that value at runtime therefore a custom one is needed. + + You also want to query not only by the full url, but for example + by specific ports used. This is possible by putting the URI data + into a map field instead of just storing the plain + string representation. + + from s in ShortUrl, + where: fragment("?->>? ILIKE ?", s.original_url, "port", "443") + + So the custom type does need to handle the conversion from + external data to runtime data (`c:cast/1`) as well as + transforming that runtime data into the `:map` Ecto native type and + back (`c:dump/1` and `c:load/1`). + + defmodule EctoURI do + use Ecto.Type + def type, do: :map + + # Provide custom casting rules. + # Cast strings into the URI struct to be used at runtime + def cast(uri) when is_binary(uri) do + {:ok, URI.parse(uri)} + end + + # Accept casting of URI structs as well + def cast(%URI{} = uri), do: {:ok, uri} + + # Everything else is a failure though + def cast(_), do: :error + + # When loading data from the database, as long as it's a map, + # we just put the data back into a URI struct to be stored in + # the loaded schema struct. + def load(data) when is_map(data) do + data = + for {key, val} <- data do + {String.to_existing_atom(key), val} + end + {:ok, struct!(URI, data)} + end + + # When dumping data to the database, we *expect* a URI struct + # but any value could be inserted into the schema struct at runtime, + # so we need to guard against them. + def dump(%URI{} = uri), do: {:ok, Map.from_struct(uri)} + def dump(_), do: :error + end + + Now we can use our new field type above in our schemas: + + defmodule ShortUrl do + use Ecto.Schema + + schema "posts" do + field :original_url, EctoURI + end + end + + Note: `nil` values are always bypassed and cannot be handled by + custom types. + + > #### `use Ecto.Type` {: .info} + > + > When you `use Ecto.Type`, it will set `@behaviour Ecto.Type` and define + > default, overridable implementations for `c:embed_as/1` and `c:equal?/2`. + + ## Custom types and primary keys + + Remember that, if you change the type of your primary keys, + you will also need to change the type of all associations that + point to said primary key. + + Imagine you want to encode the ID so they cannot enumerate the + content in your application. An Ecto type could handle the conversion + between the encoded version of the id and its representation in the + database. For the sake of simplicity, we'll use base64 encoding in + this example: + + defmodule EncodedId do + use Ecto.Type + + def type, do: :id + + def cast(id) when is_integer(id) do + {:ok, encode_id(id)} + end + def cast(_), do: :error + + def dump(id) when is_binary(id) do + {:ok, id_decoded} = Base.decode64(id) + {:ok, String.to_integer(id_decoded)} + end + + def load(id) when is_integer(id) do + {:ok, encode_id(id)} + end + + defp encode_id(id) do + id + |> Integer.to_string() + |> Base.encode64() + end + end + + To use it as the type for the id in our schema, we can use the + `@primary_key` module attribute: + + defmodule BlogPost do + use Ecto.Schema + + @primary_key {:id, EncodedId, autogenerate: true} + schema "posts" do + belongs_to :author, Author, type: EncodedId + field :content, :string + end + end + + defmodule Author do + use Ecto.Schema + + @primary_key {:id, EncodedId, autogenerate: true} + schema "authors" do + field :name, :string + has_many :posts, BlogPost + end + end + + The `@primary_key` attribute will tell ecto which type to + use for the id. + + Note the `type: EncodedId` option given to `belongs_to` in + the `BlogPost` schema. By default, Ecto will treat + associations as if their keys were `:integer`s. Our primary + keys are a custom type, so when Ecto tries to cast those + ids, it will fail. + + Alternatively, you can set `@foreign_key_type EncodedId` + after `@primary_key` to automatically configure the type + of all `belongs_to` fields. + """ + + import Kernel, except: [match?: 2] + + @doc false + defmacro __using__(_opts) do + quote location: :keep do + @behaviour Ecto.Type + def embed_as(_), do: :self + def equal?(term1, term2), do: term1 == term2 + defoverridable embed_as: 1, equal?: 2 + end + end + + @typedoc "An Ecto type, primitive or custom." + @type t :: primitive | custom + + @typedoc "Primitive Ecto types (handled by Ecto)." + @type primitive :: base | composite + + @typedoc "Custom types are represented by user-defined modules." + @type custom :: module | {:parameterized, {module, term}} + + @type base :: + :integer + | :float + | :boolean + | :string + | :bitstring + | :map + | :binary + | :decimal + | :id + | :binary_id + | :utc_datetime + | :naive_datetime + | :date + | :time + | :any + | :utc_datetime_usec + | :naive_datetime_usec + | :time_usec + | :duration + + @type composite :: {:array, t} | {:map, t} | private_composite + + @typep private_composite :: {:try, t} | {:in, t} | {:supertype, :datetime} + + @base ~w( + integer float decimal boolean string bitstring map binary id binary_id any + utc_datetime naive_datetime date time + utc_datetime_usec naive_datetime_usec time_usec + duration + )a + @composite ~w(array map try in param)a + @variadic ~w(in splice)a + + @doc """ + Returns the underlying schema type for the custom type. + + For example, if you want to provide your own date + structures, the type function should return `:date`. + + Note this function is not required to return Ecto primitive + types, the type is only required to be known by the adapter. + """ + @callback type :: t + + @doc """ + Casts the given input to the custom type. + + This callback is called on external input and can return any type, + as long as the `dump/1` function is able to convert the returned + value into an Ecto native type. There are two situations where + this callback is called: + + 1. When casting values by `Ecto.Changeset` + 2. When passing arguments to `Ecto.Query` + + You can return `:error` if the given term cannot be cast. + A default error message of "is invalid" will be added to the + changeset. + + You may also return `{:error, keyword()}` to customize the + changeset error message and its metadata. Passing a `:message` + key, will override the default message. It is not possible to + override the `:type` key. + + For `{:array, CustomType}` or `{:map, CustomType}` the returned + keyword list will be erased and the default error will be shown. + """ + @callback cast(term) :: {:ok, term} | :error | {:error, keyword()} + + @doc """ + Loads the given term into a custom type. + + This callback is called when loading data from the database and + receives an Ecto native type. It can return any type, as long as + the `dump/1` function is able to convert the returned value back + into an Ecto native type. + """ + @callback load(term) :: {:ok, term} | :error + + @doc """ + Dumps the given term into an Ecto native type. + + This callback is called with any term that was stored in the struct + and it needs to validate them and convert it to an Ecto native type. + """ + @callback dump(term) :: {:ok, term} | :error + + @doc """ + Checks if two terms are semantically equal. + + This callback is used for determining equality of types in + `Ecto.Changeset`. + + By default the terms are compared with the equal operator `==/2`. + """ + @callback equal?(term, term) :: boolean + + @doc """ + Dictates how the type should be treated inside embeds. + + By default, the type is sent as itself, without calling + dumping to keep the higher level representation. But + it can be set to `:dump` so that it is dumped before + being encoded. + """ + @callback embed_as(format :: atom) :: :self | :dump + + @doc """ + Generates a loaded version of the data. + + This is callback is invoked when a custom type is given + to `field` with the `:autogenerate` flag. + """ + @callback autogenerate() :: term() + + @optional_callbacks autogenerate: 0 + + ## Functions + + @doc """ + Checks if we have a primitive type. + + iex> primitive?(:string) + true + iex> primitive?(Another) + false + + iex> primitive?({:array, :string}) + true + iex> primitive?({:array, Another}) + true + + """ + @spec primitive?(t) :: boolean + def primitive?({:parameterized, _}), do: true + def primitive?({composite, _}) when composite in @composite, do: true + def primitive?(base) when base in @base, do: true + def primitive?(_), do: false + + @doc """ + Checks if the given type is parameterized by the given module. + + iex> type = Ecto.ParameterizedType.init(Ecto.Enum, values: [a: 1]) + iex> Ecto.Type.parameterized?(type, Ecto.Enum) + true + iex> Ecto.Type.parameterized?(type, MyEnum) + false + + """ + @spec parameterized?(t, module) :: boolean + def parameterized?({:parameterized, {module, _}}, module), do: true + def parameterized?(_, _), do: false + + @doc """ + Checks if the given atom can be used as composite type. + + iex> composite?(:array) + true + iex> composite?(:string) + false + + """ + @spec composite?(atom) :: boolean + def composite?(atom), do: atom in @composite + + @doc """ + Checks if the given atom can be used as base type. + + iex> base?(:string) + true + iex> base?(:array) + false + iex> base?(Custom) + false + + """ + @spec base?(atom) :: boolean + def base?(atom), do: atom in @base + + @doc """ + Gets how the type is treated inside embeds for the given format. + + See `c:embed_as/1`. + """ + def embed_as({:parameterized, {module, params}}, format), do: module.embed_as(format, params) + def embed_as({composite, type}, format) when composite in @composite, do: embed_as(type, format) + def embed_as(base, _format) when base in @base, do: :self + def embed_as(mod, format), do: mod.embed_as(format) + + @doc """ + Dumps the `value` for `type` considering it will be embedded in `format`. + + ## Examples + + iex> Ecto.Type.embedded_dump(:decimal, Decimal.new("1"), :json) + {:ok, Decimal.new("1")} + + """ + def embedded_dump(type, value, format) do + case embed_as(type, format) do + :self -> {:ok, value} + :dump -> dump(type, value, &embedded_dump(&1, &2, format)) + end + end + + @doc """ + Loads the `value` for `type` considering it was embedded in `format`. + + ## Examples + + iex> Ecto.Type.embedded_load(:decimal, "1", :json) + {:ok, Decimal.new("1")} + + """ + def embedded_load(type, value, format) do + case embed_as(type, format) do + :self -> + case cast(type, value) do + {:ok, _} = ok -> ok + _ -> :error + end + + :dump -> + load(type, value, &embedded_load(&1, &2, format)) + end + end + + @doc """ + Retrieves the underlying schema type for the given, possibly custom, type. + + iex> type(:string) + :string + iex> type(Ecto.UUID) + :uuid + + iex> type({:array, :string}) + {:array, :string} + iex> type({:array, Ecto.UUID}) + {:array, :uuid} + + iex> type({:map, Ecto.UUID}) + {:map, :uuid} + + """ + @spec type(t) :: t + def type(type) + def type({:parameterized, {type, params}}), do: type.type(params) + def type({:array, type}), do: {:array, type(type)} + def type({:map, type}), do: {:map, type(type)} + def type({:try, type}), do: type(type) + def type(type) when type in @base, do: type + def type(type) when is_atom(type), do: type.type() + def type(type), do: type + + @doc """ + Checks if a given type matches with a primitive type + that can be found in queries. + + iex> match?(:string, :any) + true + iex> match?(:any, :string) + true + iex> match?(:string, :string) + true + + iex> match?({:array, :string}, {:array, :any}) + true + + iex> match?(Ecto.UUID, :uuid) + true + iex> match?(Ecto.UUID, :string) + false + + """ + @spec match?(t, primitive) :: boolean + def match?(schema_type, query_type) do + if primitive?(schema_type) do + do_match?(schema_type, query_type) + else + do_match?(schema_type.type(), query_type) + end + end + + defp do_match?(_left, :any), do: true + defp do_match?(:any, _right), do: true + defp do_match?({outer, left}, {outer, right}), do: match?(left, right) + defp do_match?(:decimal, type) when type in [:float, :integer], do: true + defp do_match?(:binary_id, :binary), do: true + defp do_match?(:id, :integer), do: true + defp do_match?(type, type), do: true + defp do_match?(:naive_datetime, {:supertype, :datetime}), do: true + defp do_match?(:naive_datetime_usec, {:supertype, :datetime}), do: true + defp do_match?(:utc_datetime, {:supertype, :datetime}), do: true + defp do_match?(:utc_datetime_usec, {:supertype, :datetime}), do: true + defp do_match?(_, _), do: false + + @doc """ + Dumps a value to the given type. + + Opposite to casting, dumping requires the returned value + to be a valid Ecto type, as it will be sent to the + underlying data store. + + iex> dump(:string, nil) + {:ok, nil} + iex> dump(:string, "foo") + {:ok, "foo"} + + iex> dump(:integer, 1) + {:ok, 1} + iex> dump(:integer, "10") + :error + + iex> dump(:binary, "foo") + {:ok, "foo"} + iex> dump(:binary, 1) + :error + + iex> dump({:array, :integer}, [1, 2, 3]) + {:ok, [1, 2, 3]} + iex> dump({:array, :integer}, [1, "2", 3]) + :error + iex> dump({:array, :binary}, ["1", "2", "3"]) + {:ok, ["1", "2", "3"]} + + """ + @spec dump(t, term) :: {:ok, term} | :error + @spec dump(t, term, (t, term -> {:ok, term} | :error)) :: {:ok, term} | :error + def dump(type, value, dumper \\ &dump/2) + + def dump({:parameterized, {module, params}}, value, dumper) do + module.dump(value, dumper, params) + end + + def dump(_type, nil, _dumper) do + {:ok, nil} + end + + def dump({:try, type}, value, dumper) do + case dump(type, value, dumper) do + {:ok, _} = ok -> ok + :error -> {:ok, value} + end + end + + def dump({qual, type}, value, dumper) when qual in @variadic do + case dump({:array, type}, value, dumper) do + {:ok, value} -> {:ok, {qual, value}} + :error -> :error + end + end + + def dump({:array, {:parameterized, _} = type}, value, dumper), + do: array_with_type(value, type, dumper, false, []) + + def dump({:array, type}, value, dumper), do: array_with_type(value, type, dumper, true, []) + def dump({:map, type}, value, dumper), do: map(value, type, dumper, false, %{}) + + def dump(:any, value, _dumper), do: {:ok, value} + def dump(:integer, value, _dumper), do: same_integer(value) + def dump(:float, value, _dumper), do: dump_float(value) + def dump(:boolean, value, _dumper), do: same_boolean(value) + def dump(:map, value, _dumper), do: same_map(value) + def dump(:string, value, _dumper), do: same_binary(value) + def dump(:binary, value, _dumper), do: same_binary(value) + def dump(:bitstring, value, _dumper), do: same_bitstring(value) + def dump(:id, value, _dumper), do: same_integer(value) + def dump(:binary_id, value, _dumper), do: same_binary(value) + def dump(:decimal, value, _dumper), do: same_decimal(value) + def dump(:date, value, _dumper), do: same_date(value) + def dump(:time, value, _dumper), do: dump_time(value) + def dump(:time_usec, value, _dumper), do: dump_time_usec(value) + def dump(:naive_datetime, value, _dumper), do: dump_naive_datetime(value) + def dump(:naive_datetime_usec, value, _dumper), do: dump_naive_datetime_usec(value) + def dump(:utc_datetime, value, _dumper), do: dump_utc_datetime(value) + def dump(:utc_datetime_usec, value, _dumper), do: dump_utc_datetime_usec(value) + def dump(:duration, value, _dumper), do: same_duration(value) + def dump({:supertype, :datetime}, value, _dumper), do: dump_any_datetime(value) + def dump(mod, value, _dumper) when is_atom(mod), do: mod.dump(value) + + defp dump_float(term) when is_float(term), do: {:ok, term} + defp dump_float(_), do: :error + + defp dump_time(%Time{} = term), do: {:ok, check_no_usec!(term, :time)} + defp dump_time(_), do: :error + + defp dump_time_usec(%Time{} = term), do: {:ok, check_usec!(term, :time_usec)} + defp dump_time_usec(_), do: :error + + defp dump_any_datetime(%NaiveDateTime{} = term), do: {:ok, term} + defp dump_any_datetime(%DateTime{} = term), do: {:ok, term} + defp dump_any_datetime(_), do: :error + + defp dump_naive_datetime(%NaiveDateTime{} = term), + do: {:ok, check_no_usec!(term, :naive_datetime)} + + defp dump_naive_datetime(_), do: :error + + defp dump_naive_datetime_usec(%NaiveDateTime{} = term), + do: {:ok, check_usec!(term, :naive_datetime_usec)} + + defp dump_naive_datetime_usec(_), do: :error + + defp dump_utc_datetime(%DateTime{} = datetime) do + kind = :utc_datetime + {:ok, datetime |> check_utc_timezone!(kind) |> check_no_usec!(kind)} + end + + defp dump_utc_datetime(_), do: :error + + defp dump_utc_datetime_usec(%DateTime{} = datetime) do + kind = :utc_datetime_usec + {:ok, datetime |> check_utc_timezone!(kind) |> check_usec!(kind)} + end + + defp dump_utc_datetime_usec(_), do: :error + + @doc """ + Loads a value with the given type. + + iex> load(:string, nil) + {:ok, nil} + iex> load(:string, "foo") + {:ok, "foo"} + + iex> load(:integer, 1) + {:ok, 1} + iex> load(:integer, "10") + :error + + """ + @spec load(t, term) :: {:ok, term} | :error + @spec load(t, term, (t, term -> {:ok, term} | :error)) :: {:ok, term} | :error + def load(type, value, loader \\ &load/2) + + def load({:parameterized, {module, params}}, value, loader) do + module.load(value, loader, params) + end + + def load(_type, nil, _loader) do + {:ok, nil} + end + + def load({:try, type}, value, loader) do + case load(type, value, loader) do + {:ok, _} = ok -> ok + :error -> {:ok, value} + end + end + + def load({:array, {:parameterized, _} = type}, value, loader), + do: array_with_type(value, type, loader, false, []) + + def load({:array, type}, value, loader), do: array_with_type(value, type, loader, true, []) + def load({:map, type}, value, loader), do: map(value, type, loader, false, %{}) + + def load(:any, value, _loader), do: {:ok, value} + def load(:integer, value, _loader), do: same_integer(value) + def load(:float, value, _loader), do: load_float(value) + def load(:boolean, value, _loader), do: same_boolean(value) + def load(:map, value, _loader), do: same_map(value) + def load(:string, value, _loader), do: same_binary(value) + def load(:binary, value, _loader), do: same_binary(value) + def load(:bitstring, value, _loader), do: same_bitstring(value) + def load(:id, value, _loader), do: same_integer(value) + def load(:binary_id, value, _loader), do: same_binary(value) + def load(:decimal, value, _loader), do: same_decimal(value) + def load(:date, value, _loader), do: same_date(value) + def load(:time, value, _loader), do: load_time(value) + def load(:time_usec, value, _loader), do: load_time_usec(value) + def load(:naive_datetime, value, _loader), do: load_naive_datetime(value) + def load(:naive_datetime_usec, value, _loader), do: load_naive_datetime_usec(value) + def load(:utc_datetime, value, _loader), do: load_utc_datetime(value) + def load(:utc_datetime_usec, value, _loader), do: load_utc_datetime_usec(value) + def load(:duration, value, _loader), do: same_duration(value) + def load(mod, value, _loader), do: mod.load(value) + + defp load_float(term) when is_float(term), do: {:ok, term} + defp load_float(term) when is_integer(term), do: {:ok, :erlang.float(term)} + defp load_float(_), do: :error + + defp load_time(%Time{} = time), do: {:ok, truncate_usec(time)} + defp load_time(_), do: :error + + defp load_time_usec(%Time{} = time), do: {:ok, pad_usec(time)} + defp load_time_usec(_), do: :error + + # This is a downcast, which is always fine, and in case + # we try to send a naive datetime where a datetime is expected, + # the adapter will either explicitly error (Postgres) or it will + # accept the data (MySQL), which is fine as we always assume UTC + defp load_naive_datetime(%DateTime{} = datetime), + do: + {:ok, + datetime |> check_utc_timezone!(:naive_datetime) |> DateTime.to_naive() |> truncate_usec()} + + defp load_naive_datetime(%NaiveDateTime{} = naive_datetime), + do: {:ok, truncate_usec(naive_datetime)} + + defp load_naive_datetime(_), do: :error + + defp load_naive_datetime_usec(%DateTime{} = datetime), + do: + {:ok, + datetime |> check_utc_timezone!(:naive_datetime_usec) |> DateTime.to_naive() |> pad_usec()} + + defp load_naive_datetime_usec(%NaiveDateTime{} = naive_datetime), + do: {:ok, pad_usec(naive_datetime)} + + defp load_naive_datetime_usec(_), do: :error + + # This is an upcast but because we assume the database + # is always in UTC, we can perform it. + defp load_utc_datetime(%NaiveDateTime{} = naive_datetime), + do: {:ok, naive_datetime |> truncate_usec() |> DateTime.from_naive!("Etc/UTC")} + + defp load_utc_datetime(%DateTime{} = datetime), + do: {:ok, datetime |> check_utc_timezone!(:utc_datetime) |> truncate_usec()} + + defp load_utc_datetime(_), + do: :error + + defp load_utc_datetime_usec(%NaiveDateTime{} = naive_datetime), + do: {:ok, naive_datetime |> pad_usec() |> DateTime.from_naive!("Etc/UTC")} + + defp load_utc_datetime_usec(%DateTime{} = datetime), + do: {:ok, datetime |> check_utc_timezone!(:utc_datetime_usec) |> pad_usec()} + + defp load_utc_datetime_usec(_), + do: :error + + @doc """ + Casts a value to the given type. + + `cast/2` is used by the finder queries and changesets to cast outside values to + specific types. + + Note that nil can be cast to all primitive types as data stores allow nil to be + set on any column. + + NaN and infinite decimals are not supported, use custom types instead. + + iex> cast(:any, "whatever") + {:ok, "whatever"} + + iex> cast(:any, nil) + {:ok, nil} + iex> cast(:string, nil) + {:ok, nil} + + iex> cast(:integer, 1) + {:ok, 1} + iex> cast(:integer, "1") + {:ok, 1} + iex> cast(:integer, "1.0") + :error + + iex> cast(:id, 1) + {:ok, 1} + iex> cast(:id, "1") + {:ok, 1} + iex> cast(:id, "1.0") + :error + + iex> cast(:float, 1.0) + {:ok, 1.0} + iex> cast(:float, 1) + {:ok, 1.0} + iex> cast(:float, "1") + {:ok, 1.0} + iex> cast(:float, "1.0") + {:ok, 1.0} + iex> cast(:float, "1-foo") + :error + + iex> cast(:boolean, true) + {:ok, true} + iex> cast(:boolean, false) + {:ok, false} + iex> cast(:boolean, "1") + {:ok, true} + iex> cast(:boolean, "0") + {:ok, false} + iex> cast(:boolean, "whatever") + :error + + iex> cast(:string, "beef") + {:ok, "beef"} + iex> cast(:binary, "beef") + {:ok, "beef"} + + iex> cast(:decimal, Decimal.new("1.0")) + {:ok, Decimal.new("1.0")} + iex> cast(:decimal, "1.0bad") + :error + + iex> cast({:array, :integer}, [1, 2, 3]) + {:ok, [1, 2, 3]} + iex> cast({:array, :integer}, ["1", "2", "3"]) + {:ok, [1, 2, 3]} + iex> cast({:array, :string}, [1, 2, 3]) + :error + iex> cast(:string, [1, 2, 3]) + :error + + iex> cast(:utc_datetime, "2014-04-17T14:00:00Z") + {:ok, ~U[2014-04-17 14:00:00Z]} + iex> cast(:utc_datetime, "2014-04-17T14:00:00.030Z") + {:ok, ~U[2014-04-17 14:00:00Z]} + iex> cast(:utc_datetime, "2014-04-17T12:00:00-02:00") + {:ok, ~U[2014-04-17 14:00:00Z]} + + """ + @spec cast(t, term) :: {:ok, term} | {:error, keyword()} | :error + def cast({:parameterized, {type, params}}, value), do: type.cast(value, params) + def cast({:in, _type}, nil), do: :error + def cast(_type, nil), do: {:ok, nil} + + def cast({:try, type}, value) do + case cast(type, value) do + {:ok, _} = ok -> ok + _ -> {:ok, value} + end + end + + def cast(type, value) do + cast_fun(type).(value) + end + + defp cast_fun(:integer), do: &cast_integer/1 + defp cast_fun(:float), do: &cast_float/1 + defp cast_fun(:boolean), do: &cast_boolean/1 + defp cast_fun(:map), do: &cast_map/1 + defp cast_fun(:string), do: &cast_binary/1 + defp cast_fun(:binary), do: &cast_binary/1 + defp cast_fun(:bitstring), do: &cast_bitstring/1 + defp cast_fun(:id), do: &cast_integer/1 + defp cast_fun(:binary_id), do: &cast_binary/1 + defp cast_fun(:any), do: &{:ok, &1} + defp cast_fun(:decimal), do: &cast_decimal/1 + defp cast_fun(:date), do: &cast_date/1 + defp cast_fun(:time), do: &maybe_truncate_usec(cast_time(&1)) + defp cast_fun(:time_usec), do: &maybe_pad_usec(cast_time(&1)) + defp cast_fun(:naive_datetime), do: &maybe_truncate_usec(cast_naive_datetime(&1)) + defp cast_fun(:naive_datetime_usec), do: &maybe_pad_usec(cast_naive_datetime(&1)) + defp cast_fun(:utc_datetime), do: &maybe_truncate_usec(cast_utc_datetime(&1)) + defp cast_fun(:utc_datetime_usec), do: &maybe_pad_usec(cast_utc_datetime(&1)) + defp cast_fun(:duration), do: &cast_duration/1 + defp cast_fun({:supertype, :datetime}), do: &cast_any_datetime(&1) + defp cast_fun({:parameterized, {mod, params}}), do: &mod.cast(&1, params) + defp cast_fun({qual, type}) when qual in @variadic, do: cast_fun({:array, type}) + + defp cast_fun({:array, {:parameterized, _} = type}) do + fun = cast_fun(type) + &array_with_index(&1, fun, false, 0, []) + end + + defp cast_fun({:array, type}) do + fun = cast_fun(type) + &array_with_index(&1, fun, true, 0, []) + end + + defp cast_fun({:map, {:parameterized, _} = type}) do + fun = cast_fun(type) + &map(&1, fun, false, %{}) + end + + defp cast_fun({:map, type}) do + fun = cast_fun(type) + &map(&1, fun, true, %{}) + end + + defp cast_fun(mod) when is_atom(mod) do + fn + nil -> {:ok, nil} + value -> mod.cast(value) + end + end + + # We check for the byte size to avoid creating unnecessary large integers + # which would never map to a database key (u64 is 20 digits only). + defp cast_integer(term) when is_binary(term) and byte_size(term) < 32 do + case Integer.parse(term) do + {integer, ""} -> {:ok, integer} + _ -> :error + end + end + + defp cast_integer(term) when is_integer(term), do: {:ok, term} + defp cast_integer(_), do: :error + + defp cast_float(term) when is_binary(term) do + case Float.parse(term) do + {float, ""} -> {:ok, float} + _ -> :error + end + end + + defp cast_float(term) when is_float(term), do: {:ok, term} + defp cast_float(term) when is_integer(term), do: {:ok, :erlang.float(term)} + defp cast_float(_), do: :error + + defp cast_decimal(term) when is_binary(term) do + case Decimal.parse(term) do + {decimal, ""} -> check_decimal(decimal, false) + {_, remainder} when is_binary(remainder) and byte_size(remainder) > 0 -> :error + :error -> :error + end + end + + defp cast_decimal(term), do: same_decimal(term) + + defp cast_boolean(term) when term in ~w(true 1), do: {:ok, true} + defp cast_boolean(term) when term in ~w(false 0), do: {:ok, false} + defp cast_boolean(term) when is_boolean(term), do: {:ok, term} + defp cast_boolean(_), do: :error + + defp cast_binary(term) when is_binary(term), do: {:ok, term} + defp cast_binary(_), do: :error + + defp cast_bitstring(term) when is_bitstring(term), do: {:ok, term} + defp cast_bitstring(_), do: :error + + defp cast_map(term) when is_map(term), do: {:ok, term} + defp cast_map(_), do: :error + + if Code.ensure_loaded?(Duration) do + defp cast_duration(%Duration{} = term), do: {:ok, term} + end + + defp cast_duration(_), do: :error + + @doc """ + Casts a value to the given type or raises an error. + + See `cast/2` for more information. + + ## Examples + + iex> Ecto.Type.cast!(:integer, "1") + 1 + iex> Ecto.Type.cast!(:integer, 1) + 1 + iex> Ecto.Type.cast!(:integer, nil) + nil + + iex> Ecto.Type.cast!(:integer, 1.0) + ** (Ecto.CastError) cannot cast 1.0 to :integer + """ + def cast!(type, value) do + case Ecto.Type.cast(type, value) do + {:ok, value} -> + value + + :error -> + raise Ecto.CastError, type: type, value: value + + {:error, metadata} -> + raise Ecto.CastError, [type: type, value: value] ++ Keyword.take(metadata, [:message]) + end + end + + ## Shared helpers + + @compile {:inline, same_integer: 1, same_boolean: 1, same_map: 1, same_decimal: 1, same_date: 1} + defp same_integer(term) when is_integer(term), do: {:ok, term} + defp same_integer(_), do: :error + + defp same_boolean(term) when is_boolean(term), do: {:ok, term} + defp same_boolean(_), do: :error + + defp same_binary(term) when is_binary(term), do: {:ok, term} + defp same_binary(_), do: :error + + defp same_bitstring(term) when is_bitstring(term), do: {:ok, term} + defp same_bitstring(_), do: :error + + defp same_map(term) when is_map(term), do: {:ok, term} + defp same_map(_), do: :error + + defp same_decimal(term) when is_integer(term), do: {:ok, Decimal.new(term)} + defp same_decimal(term) when is_float(term), do: {:ok, Decimal.from_float(term)} + defp same_decimal(%Decimal{} = term), do: check_decimal(term, true) + defp same_decimal(_), do: :error + + defp same_date(%Date{} = term), do: {:ok, term} + defp same_date(_), do: :error + + if Code.ensure_loaded?(Duration) do + defp same_duration(%Duration{} = term), do: {:ok, term} + end + + defp same_duration(_), do: :error + + @doc false + def empty_trimmed_string?(value) do + is_binary(value) and String.trim_leading(value) == "" + end + + ## Adapter related + + @doc false + def adapter_autogenerate(adapter, type) do + type + |> type() + |> adapter.autogenerate() + end + + @doc false + def adapter_load(adapter, type, value) do + if of_base_type?(type, value) do + {:ok, value} + else + process_loaders(adapter.loaders(type(type), type), {:ok, value}, adapter) + end + end + + defp process_loaders(_, :error, _adapter), + do: :error + + defp process_loaders([fun | t], {:ok, value}, adapter) when is_function(fun), + do: process_loaders(t, fun.(value), adapter) + + defp process_loaders([type | t], {:ok, value}, adapter), + do: process_loaders(t, load(type, value, &adapter_load(adapter, &1, &2)), adapter) + + defp process_loaders([], {:ok, _} = acc, _adapter), + do: acc + + @doc false + def adapter_dump(adapter, type, value) do + process_dumpers(adapter.dumpers(type(type), type), {:ok, value}, adapter) + end + + defp process_dumpers(_, :error, _adapter), + do: :error + + defp process_dumpers([fun | t], {:ok, value}, adapter) when is_function(fun), + do: process_dumpers(t, fun.(value), adapter) + + defp process_dumpers([type | t], {:ok, value}, adapter), + do: process_dumpers(t, dump(type, value, &adapter_dump(adapter, &1, &2)), adapter) + + defp process_dumpers([], {:ok, _} = acc, _adapter), + do: acc + + ## Date + + defp cast_date(binary) when is_binary(binary) do + case Date.from_iso8601(binary) do + {:ok, _} = ok -> + ok + + {:error, _} -> + case NaiveDateTime.from_iso8601(binary) do + {:ok, naive_datetime} -> {:ok, NaiveDateTime.to_date(naive_datetime)} + {:error, _} -> :error + end + end + end + + defp cast_date(%{"year" => empty, "month" => empty, "day" => empty}) when empty in ["", nil], + do: {:ok, nil} + + defp cast_date(%{year: empty, month: empty, day: empty}) when empty in ["", nil], + do: {:ok, nil} + + defp cast_date(%{"year" => year, "month" => month, "day" => day}), + do: cast_date(to_i(year), to_i(month), to_i(day)) + + defp cast_date(%{year: year, month: month, day: day}), + do: cast_date(to_i(year), to_i(month), to_i(day)) + + defp cast_date(_), + do: :error + + defp cast_date(year, month, day) + when is_integer(year) and is_integer(month) and is_integer(day) do + case Date.new(year, month, day) do + {:ok, _} = ok -> ok + {:error, _} -> :error + end + end + + defp cast_date(_, _, _), + do: :error + + ## Time + + defp cast_time(<>), + do: cast_time(to_i(hour), to_i(minute), 0, nil) + + defp cast_time(binary) when is_binary(binary) do + case Time.from_iso8601(binary) do + {:ok, _} = ok -> ok + {:error, _} -> :error + end + end + + defp cast_time(%{"hour" => empty, "minute" => empty}) when empty in ["", nil], + do: {:ok, nil} + + defp cast_time(%{hour: empty, minute: empty}) when empty in ["", nil], + do: {:ok, nil} + + defp cast_time(%{"hour" => hour, "minute" => minute} = map), + do: + cast_time( + to_i(hour), + to_i(minute), + to_i(Map.get(map, "second")), + to_i(Map.get(map, "microsecond")) + ) + + defp cast_time(%{ + hour: hour, + minute: minute, + second: second, + microsecond: {microsecond, precision} + }), + do: cast_time(to_i(hour), to_i(minute), to_i(second), {to_i(microsecond), to_i(precision)}) + + defp cast_time(%{hour: hour, minute: minute} = map), + do: + cast_time( + to_i(hour), + to_i(minute), + to_i(Map.get(map, :second)), + to_i(Map.get(map, :microsecond)) + ) + + defp cast_time(_), + do: :error + + defp cast_time(hour, minute, sec, usec) when is_integer(usec) do + cast_time(hour, minute, sec, {usec, 6}) + end + + defp cast_time(hour, minute, sec, nil) do + cast_time(hour, minute, sec, {0, 0}) + end + + defp cast_time(hour, minute, sec, {usec, precision}) + when is_integer(hour) and is_integer(minute) and + (is_integer(sec) or is_nil(sec)) and is_integer(usec) and is_integer(precision) do + case Time.new(hour, minute, sec || 0, {usec, precision}) do + {:ok, _} = ok -> ok + {:error, _} -> :error + end + end + + defp cast_time(_, _, _, _) do + :error + end + + defp cast_any_datetime(%DateTime{} = datetime), do: cast_utc_datetime(datetime) + defp cast_any_datetime(other), do: cast_naive_datetime(other) + + ## Naive datetime + + defp cast_naive_datetime("-" <> rest) do + with {:ok, naive_datetime} <- cast_naive_datetime(rest) do + {:ok, %{naive_datetime | year: naive_datetime.year * -1}} + end + end + + defp cast_naive_datetime( + <> + ) + when sep in [?\s, ?T] do + case NaiveDateTime.new(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(minute), 0) do + {:ok, _} = ok -> ok + _ -> :error + end + end + + defp cast_naive_datetime(binary) when is_binary(binary) do + case NaiveDateTime.from_iso8601(binary) do + {:ok, _} = ok -> ok + {:error, _} -> :error + end + end + + defp cast_naive_datetime(%{ + "year" => empty, + "month" => empty, + "day" => empty, + "hour" => empty, + "minute" => empty + }) + when empty in ["", nil], + do: {:ok, nil} + + defp cast_naive_datetime(%{year: empty, month: empty, day: empty, hour: empty, minute: empty}) + when empty in ["", nil], + do: {:ok, nil} + + defp cast_naive_datetime(%{} = map) do + with {:ok, %Date{} = date} <- cast_date(map), + {:ok, %Time{} = time} <- cast_time(map) do + NaiveDateTime.new(date, time) + else + _ -> :error + end + end + + defp cast_naive_datetime(_) do + :error + end + + ## UTC datetime + + defp cast_utc_datetime("-" <> rest) do + with {:ok, utc_datetime} <- cast_utc_datetime(rest) do + {:ok, %{utc_datetime | year: utc_datetime.year * -1}} + end + end + + defp cast_utc_datetime( + <> + ) + when sep in [?\s, ?T] do + case NaiveDateTime.new(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(minute), 0) do + {:ok, naive_datetime} -> {:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")} + _ -> :error + end + end + + defp cast_utc_datetime(binary) when is_binary(binary) do + case DateTime.from_iso8601(binary) do + {:ok, datetime, _offset} -> + {:ok, datetime} + + {:error, :missing_offset} -> + case NaiveDateTime.from_iso8601(binary) do + {:ok, naive_datetime} -> {:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")} + {:error, _} -> :error + end + + {:error, _} -> + :error + end + end + + defp cast_utc_datetime(%DateTime{time_zone: "Etc/UTC"} = datetime), do: {:ok, datetime} + + defp cast_utc_datetime(%DateTime{} = datetime) do + case datetime |> DateTime.to_unix(:microsecond) |> DateTime.from_unix(:microsecond) do + {:ok, _} = ok -> ok + {:error, _} -> :error + end + end + + defp cast_utc_datetime(value) do + case cast_naive_datetime(value) do + {:ok, %NaiveDateTime{} = naive_datetime} -> + {:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")} + + {:ok, _} = ok -> + ok + + :error -> + :error + end + end + + @doc """ + Checks if two terms are equal. + + Depending on the given `type` performs a structural or semantical comparison. + + ## Examples + + iex> equal?(:integer, 1, 1) + true + iex> equal?(:decimal, Decimal.new("1"), Decimal.new("1.00")) + true + + """ + @spec equal?(t, term, term) :: boolean + def equal?(_, nil, nil), do: true + + def equal?(type, term1, term2) do + if fun = equal_fun(type) do + fun.(term1, term2) + else + term1 == term2 + end + end + + @doc """ + Checks if `collection` includes a `term`. + + Depending on the given `type` performs a structural or semantical comparison. + + ## Examples + + iex> include?(:integer, 1, 1..3) + true + iex> include?(:decimal, Decimal.new("1"), [Decimal.new("1.00"), Decimal.new("2.00")]) + true + + """ + @spec include?(t, term, Enum.t()) :: boolean + def include?(type, term, collection) do + if fun = equal_fun(type) do + Enum.any?(collection, &fun.(term, &1)) + else + term in collection + end + end + + defp equal_fun(:decimal), do: &equal_decimal?/2 + defp equal_fun(t) when t in [:time, :time_usec], do: &equal_time?/2 + defp equal_fun(t) when t in [:utc_datetime, :utc_datetime_usec], do: &equal_utc_datetime?/2 + + defp equal_fun(t) when t in [:naive_datetime, :naive_datetime_usec], + do: &equal_naive_datetime?/2 + + defp equal_fun(t) when t in @base, do: nil + + defp equal_fun({:array, type}) do + if fun = equal_fun(type) do + &equal_list?(fun, &1, &2) + end + end + + defp equal_fun({:map, type}) do + if fun = equal_fun(type) do + &equal_map?(fun, &1, &2) + end + end + + defp equal_fun({:parameterized, {mod, params}}) do + &mod.equal?(&1, &2, params) + end + + defp equal_fun(mod) when is_atom(mod), do: &mod.equal?/2 + + defp equal_decimal?(%Decimal{} = a, %Decimal{} = b), do: Decimal.equal?(a, b) + defp equal_decimal?(_, _), do: false + + defp equal_time?(%Time{} = a, %Time{} = b), do: Time.compare(a, b) == :eq + defp equal_time?(_, _), do: false + + defp equal_utc_datetime?(%DateTime{} = a, %DateTime{} = b), do: DateTime.compare(a, b) == :eq + defp equal_utc_datetime?(_, _), do: false + + defp equal_naive_datetime?(%NaiveDateTime{} = a, %NaiveDateTime{} = b), + do: NaiveDateTime.compare(a, b) == :eq + + defp equal_naive_datetime?(_, _), + do: false + + defp equal_list?(fun, [nil | xs], [nil | ys]), do: equal_list?(fun, xs, ys) + defp equal_list?(fun, [x | xs], [y | ys]), do: fun.(x, y) and equal_list?(fun, xs, ys) + defp equal_list?(_fun, [], []), do: true + defp equal_list?(_fun, _, _), do: false + + defp equal_map?(_fun, map1, map2) when map_size(map1) != map_size(map2) do + false + end + + defp equal_map?(fun, %{} = map1, %{} = map2) do + equal_map?(fun, Map.to_list(map1), map2) + end + + defp equal_map?(fun, [{key, nil} | tail], other_map) do + case other_map do + %{^key => nil} -> equal_map?(fun, tail, other_map) + _ -> false + end + end + + defp equal_map?(fun, [{key, val} | tail], other_map) do + case other_map do + %{^key => other_val} -> fun.(val, other_val) and equal_map?(fun, tail, other_map) + _ -> false + end + end + + defp equal_map?(_fun, [], _) do + true + end + + defp equal_map?(_fun, _, _) do + false + end + + @doc """ + Format type for error messaging and logs. + """ + def format({:parameterized, {type, params}}) do + if function_exported?(type, :format, 1) do + apply(type, :format, [params]) + else + "##{inspect(type)}<#{inspect(params)}>" + end + end + + def format({composite, type}) when composite in [:array, :map] do + "{#{inspect(composite)}, #{format(type)}}" + end + + def format(type), do: inspect(type) + + ## Helpers + + # Checks if a value is of the given primitive type. + defp of_base_type?(:any, _), do: true + defp of_base_type?(:id, term), do: is_integer(term) + defp of_base_type?(:float, term), do: is_float(term) + defp of_base_type?(:integer, term), do: is_integer(term) + defp of_base_type?(:boolean, term), do: is_boolean(term) + defp of_base_type?(:binary, term), do: is_binary(term) + defp of_base_type?(:string, term), do: is_binary(term) + defp of_base_type?(:map, term), do: is_map(term) and not Map.has_key?(term, :__struct__) + defp of_base_type?(:decimal, value), do: Kernel.match?(%Decimal{}, value) + defp of_base_type?(:date, value), do: Kernel.match?(%Date{}, value) + defp of_base_type?(_, _), do: false + + defp array_with_index([nil | t], fun, true, index, acc) do + array_with_index(t, fun, true, index + 1, [nil | acc]) + end + + defp array_with_index([h | t], fun, skip_nil?, index, acc) do + case fun.(h) do + {:ok, h} -> + array_with_index(t, fun, skip_nil?, index + 1, [h | acc]) + + :error -> + :error + + {:error, custom_errors} -> + {:error, Keyword.update(custom_errors, :source, [index], &[index | &1])} + end + end + + defp array_with_index([], _fun, _skip_nil?, _index, acc) do + {:ok, Enum.reverse(acc)} + end + + defp array_with_index(%_{} = struct, fun, skip_nil?, index, acc) do + case Enumerable.impl_for(struct) do + nil -> :error + _ -> struct |> Enum.to_list() |> array_with_index(fun, skip_nil?, index, acc) + end + end + + defp array_with_index(_, _, _, _, _) do + :error + end + + defp map(map, fun, skip_nil?, acc) when is_map(map) do + map_each(Map.to_list(map), fun, skip_nil?, acc) + end + + defp map(_, _, _, _) do + :error + end + + defp map_each([{key, nil} | t], fun, true, acc) do + map_each(t, fun, true, Map.put(acc, key, nil)) + end + + defp map_each([{key, value} | t], fun, skip_nil?, acc) do + case fun.(value) do + {:ok, value} -> + map_each(t, fun, skip_nil?, Map.put(acc, key, value)) + + :error -> + :error + + {:error, custom_errors} -> + {:error, Keyword.update(custom_errors, :source, [key], &[key | &1])} + end + end + + defp map_each([], _fun, _skip_nil?, acc) do + {:ok, acc} + end + + defp array_with_type([nil | t], type, fun, true, acc) do + array_with_type(t, type, fun, true, [nil | acc]) + end + + defp array_with_type([h | t], type, fun, skip_nil?, acc) do + case fun.(type, h) do + {:ok, h} -> array_with_type(t, type, fun, skip_nil?, [h | acc]) + :error -> :error + end + end + + defp array_with_type([], _type, _fun, _skip_nil?, acc) do + {:ok, Enum.reverse(acc)} + end + + defp array_with_type(_, _, _, _, _) do + :error + end + + defp map(map, type, fun, skip_nil?, acc) when is_map(map) do + map_each(Map.to_list(map), type, fun, skip_nil?, acc) + end + + defp map(_, _, _, _, _) do + :error + end + + defp map_each([{key, value} | t], type, fun, skip_nil?, acc) do + case fun.(type, value) do + {:ok, value} -> map_each(t, type, fun, skip_nil?, Map.put(acc, key, value)) + :error -> :error + end + end + + defp map_each([], _type, _fun, _skip_nil?, acc) do + {:ok, acc} + end + + defp to_i(bin) when is_binary(bin) and byte_size(bin) < 32 do + case Integer.parse(bin) do + {int, ""} -> int + _ -> nil + end + end + + defp to_i(int) when is_integer(int), do: int + defp to_i(_), do: nil + + defp maybe_truncate_usec({:ok, struct}), do: {:ok, truncate_usec(struct)} + defp maybe_truncate_usec(:error), do: :error + + defp maybe_pad_usec({:ok, struct}), do: {:ok, pad_usec(struct)} + defp maybe_pad_usec(:error), do: :error + + defp truncate_usec(nil), do: nil + defp truncate_usec(%{microsecond: {0, 0}} = struct), do: struct + defp truncate_usec(struct), do: %{struct | microsecond: {0, 0}} + + defp pad_usec(nil), do: nil + defp pad_usec(%{microsecond: {_, 6}} = struct), do: struct + + defp pad_usec(%{microsecond: {microsecond, _}} = struct), + do: %{struct | microsecond: {microsecond, 6}} + + defp check_utc_timezone!(%{time_zone: "Etc/UTC"} = datetime, _kind), do: datetime + + defp check_utc_timezone!(datetime, kind) do + raise ArgumentError, + "#{inspect(kind)} expects the time zone to be \"Etc/UTC\", got `#{inspect(datetime)}`" + end + + defp check_usec!(%{microsecond: {_, 6}} = datetime, _kind), do: datetime + + defp check_usec!(datetime, kind) do + raise ArgumentError, + "#{inspect(kind)} expects microsecond precision, got: #{inspect(datetime)}" + end + + defp check_no_usec!(%{microsecond: {0, 0}} = datetime, _kind), do: datetime + + defp check_no_usec!(%struct{} = datetime, kind) do + raise ArgumentError, """ + #{inspect(kind)} expects microseconds to be empty, got: #{inspect(datetime)} + + Use `#{inspect(struct)}.truncate(#{kind}, :second)` (available in Elixir v1.6+) to remove microseconds. + """ + end + + defp check_decimal(%Decimal{coef: coef} = decimal, _) when is_integer(coef), do: {:ok, decimal} + defp check_decimal(_decimal, false), do: :error + + defp check_decimal(decimal, true) do + raise ArgumentError, """ + #{inspect(decimal)} is not allowed for type :decimal + + `+Infinity`, `-Infinity`, and `NaN` values are not supported, even though the `Decimal` library handles them. \ + To support them, you can create a custom type. + """ + end +end diff --git a/deps/ecto/lib/ecto/uuid.ex b/deps/ecto/lib/ecto/uuid.ex new file mode 100644 index 0000000000000000000000000000000000000000..75a5974fbe8af6fe05cf780a2ef4ab9acb25ff6b --- /dev/null +++ b/deps/ecto/lib/ecto/uuid.ex @@ -0,0 +1,234 @@ +defmodule Ecto.UUID do + @moduledoc """ + An Ecto type for UUID strings. + """ + + use Ecto.Type + + @typedoc """ + A hex-encoded UUID string. + """ + @type t :: <<_::288>> + + @typedoc """ + A raw binary representation of a UUID. + """ + @type raw :: <<_::128>> + + @doc false + def type, do: :uuid + + @doc """ + Casts either a string in the canonical, human-readable UUID format or a + 16-byte binary to a UUID in its canonical, human-readable UUID format. + + If `uuid` is neither of these, `:error` will be returned. + + Since both binaries and strings are represented as binaries, this means some + strings you may not expect are actually also valid UUIDs in their binary form + and so will be casted into their string form. + + If you need further-restricted behavior or validation, you should define your + own custom `Ecto.Type`. There is also `Ecto.UUID.load/1` if you only want to + process `raw` UUIDs, which may be a more suitable reverse operation to + `Ecto.UUID.dump/1`. + + ## Examples + + iex> Ecto.UUID.cast(<<0x60, 0x1D, 0x74, 0xE4, 0xA8, 0xD3, 0x4B, 0x6E, + ...> 0x83, 0x65, 0xED, 0xDB, 0x4C, 0x89, 0x33, 0x27>>) + {:ok, "601d74e4-a8d3-4b6e-8365-eddb4c893327"} + + iex> Ecto.UUID.cast("601d74e4-a8d3-4b6e-8365-eddb4c893327") + {:ok, "601d74e4-a8d3-4b6e-8365-eddb4c893327"} + + iex> Ecto.UUID.cast("warehouse worker") + {:ok, "77617265-686f-7573-6520-776f726b6572"} + """ + @spec cast(t | raw | any) :: {:ok, t} | :error + def cast(uuid) + def cast( + <> + ) do + <> + catch + :error -> :error + else + hex_uuid -> {:ok, hex_uuid} + end + + def cast(<<_::128>> = raw_uuid), do: {:ok, encode(raw_uuid)} + def cast(_), do: :error + + @doc """ + Same as `cast/1` but raises `Ecto.CastError` on invalid arguments. + """ + @spec cast!(t | raw | any) :: t + def cast!(uuid) do + case cast(uuid) do + {:ok, hex_uuid} -> hex_uuid + :error -> raise Ecto.CastError, type: __MODULE__, value: uuid + end + end + + @compile {:inline, c: 1} + + defp c(?0), do: ?0 + defp c(?1), do: ?1 + defp c(?2), do: ?2 + defp c(?3), do: ?3 + defp c(?4), do: ?4 + defp c(?5), do: ?5 + defp c(?6), do: ?6 + defp c(?7), do: ?7 + defp c(?8), do: ?8 + defp c(?9), do: ?9 + defp c(?A), do: ?a + defp c(?B), do: ?b + defp c(?C), do: ?c + defp c(?D), do: ?d + defp c(?E), do: ?e + defp c(?F), do: ?f + defp c(?a), do: ?a + defp c(?b), do: ?b + defp c(?c), do: ?c + defp c(?d), do: ?d + defp c(?e), do: ?e + defp c(?f), do: ?f + defp c(_), do: throw(:error) + + @doc """ + Converts a string representing a UUID into a raw binary. + """ + @spec dump(uuid_string :: t | any) :: {:ok, raw} | :error + def dump(uuid_string) + def dump( + <> + ) do + <> + catch + :error -> :error + else + raw_uuid -> {:ok, raw_uuid} + end + + def dump(_), do: :error + + @compile {:inline, d: 1} + + defp d(?0), do: 0 + defp d(?1), do: 1 + defp d(?2), do: 2 + defp d(?3), do: 3 + defp d(?4), do: 4 + defp d(?5), do: 5 + defp d(?6), do: 6 + defp d(?7), do: 7 + defp d(?8), do: 8 + defp d(?9), do: 9 + defp d(?A), do: 10 + defp d(?B), do: 11 + defp d(?C), do: 12 + defp d(?D), do: 13 + defp d(?E), do: 14 + defp d(?F), do: 15 + defp d(?a), do: 10 + defp d(?b), do: 11 + defp d(?c), do: 12 + defp d(?d), do: 13 + defp d(?e), do: 14 + defp d(?f), do: 15 + defp d(_), do: throw(:error) + + @doc """ + Same as `dump/1` but raises `Ecto.ArgumentError` on invalid arguments. + """ + @spec dump!(t | any) :: raw + def dump!(uuid) do + case dump(uuid) do + {:ok, raw_uuid} -> raw_uuid + :error -> raise ArgumentError, "cannot dump given UUID to binary: #{inspect(uuid)}" + end + end + + @doc """ + Converts a binary UUID into a string. + """ + @spec load(raw | any) :: {:ok, t} | :error + def load(<<_::128>> = raw_uuid), do: {:ok, encode(raw_uuid)} + + def load(<<_::64, ?-, _::32, ?-, _::32, ?-, _::32, ?-, _::96>> = string) do + raise ArgumentError, + "trying to load string UUID as Ecto.UUID: #{inspect(string)}. " <> + "Maybe you wanted to declare :uuid as your database field?" + end + + def load(_), do: :error + + @doc """ + Same as `load/1` but raises `Ecto.ArgumentError` on invalid arguments. + """ + @spec load!(raw | any) :: t + def load!(value) do + case load(value) do + {:ok, hex_uuid} -> hex_uuid + :error -> raise ArgumentError, "cannot load given binary as UUID: #{inspect(value)}" + end + end + + @doc """ + Generates a random, version 4 UUID. + """ + @spec generate() :: t + def generate(), do: encode(bingenerate()) + + @doc """ + Generates a random, version 4 UUID in the binary format. + """ + @spec bingenerate() :: raw + def bingenerate() do + <> = :crypto.strong_rand_bytes(16) + <> + end + + # Callback invoked by autogenerate fields. + @doc false + def autogenerate, do: generate() + + @spec encode(raw) :: t + defp encode( + <> + ) do + <> + end + + @compile {:inline, e: 1} + + defp e(0), do: ?0 + defp e(1), do: ?1 + defp e(2), do: ?2 + defp e(3), do: ?3 + defp e(4), do: ?4 + defp e(5), do: ?5 + defp e(6), do: ?6 + defp e(7), do: ?7 + defp e(8), do: ?8 + defp e(9), do: ?9 + defp e(10), do: ?a + defp e(11), do: ?b + defp e(12), do: ?c + defp e(13), do: ?d + defp e(14), do: ?e + defp e(15), do: ?f +end diff --git a/deps/ecto/lib/mix/ecto.ex b/deps/ecto/lib/mix/ecto.ex new file mode 100644 index 0000000000000000000000000000000000000000..7f5a37a3db2d5204ef123429f4fe48613855bcb4 --- /dev/null +++ b/deps/ecto/lib/mix/ecto.ex @@ -0,0 +1,148 @@ +defmodule Mix.Ecto do + @moduledoc """ + Conveniences for writing Ecto related Mix tasks. + """ + + @doc """ + Parses the repository option from the given command line args list. + + If no repo option is given, it is retrieved from the application environment. + """ + @spec parse_repo([term]) :: [Ecto.Repo.t] + def parse_repo(args) do + parse_repo(args, []) + end + + defp parse_repo([key, value|t], acc) when key in ~w(--repo -r) do + parse_repo t, [Module.concat([value])|acc] + end + + defp parse_repo([_|t], acc) do + parse_repo t, acc + end + + defp parse_repo([], []) do + apps = + if apps_paths = Mix.Project.apps_paths() do + Enum.filter(Mix.Project.deps_apps(), &is_map_key(apps_paths, &1)) + else + [Mix.Project.config()[:app]] + end + + apps + |> Enum.flat_map(fn app -> + Application.load(app) + Application.get_env(app, :ecto_repos, []) + end) + |> Enum.uniq() + |> case do + [] -> + Mix.shell().error """ + warning: could not find Ecto repos in any of the apps: #{inspect apps}. + + You can avoid this warning by passing the -r flag or by setting the + repositories managed by those applications in your config/config.exs: + + config #{inspect hd(apps)}, ecto_repos: [...] + """ + [] + repos -> + repos + end + end + + defp parse_repo([], acc) do + Enum.reverse(acc) + end + + @doc """ + Ensures the given module is an Ecto.Repo. + """ + @spec ensure_repo(module, list) :: Ecto.Repo.t + def ensure_repo(repo, args) do + # Do not pass the --force switch used by some tasks downstream + args = List.delete(args, "--force") + Mix.Task.run("app.config", args) + + case Code.ensure_compiled(repo) do + {:module, _} -> + if function_exported?(repo, :__adapter__, 0) do + repo + else + Mix.raise "Module #{inspect repo} is not an Ecto.Repo. " <> + "Please configure your app accordingly or pass a repo with the -r option." + end + + {:error, error} -> + Mix.raise "Could not load #{inspect repo}, error: #{inspect error}. " <> + "Please configure your app accordingly or pass a repo with the -r option." + end + end + + @doc """ + Asks if the user wants to open a file based on ECTO_EDITOR. + + By default, it attempts to open the file and line using the + `file:line` notation. For example, if your editor is called + `subl`, it will open the file as: + + subl path/to/file:line + + It is important that you choose an editor command that does + not block nor that attempts to run an editor directly in the + terminal. Command-line based editors likely need extra + configuration so they open up the given file and line in a + separate window. + + Custom editors are supported by using the `__FILE__` and + `__LINE__` notations, for example: + + ECTO_EDITOR="my_editor +__LINE__ __FILE__" + + and Elixir will properly interpolate values. + + """ + @spec open?(binary, non_neg_integer) :: boolean + def open?(file, line \\ 1) do + editor = System.get_env("ECTO_EDITOR") || "" + + if editor != "" do + command = + if editor =~ "__FILE__" or editor =~ "__LINE__" do + editor + |> String.replace("__FILE__", inspect(file)) + |> String.replace("__LINE__", Integer.to_string(line)) + else + "#{editor} #{inspect(file)}:#{line}" + end + + Mix.shell().cmd(command) + true + else + false + end + end + + @doc """ + Gets a path relative to the application path. + + Raises on umbrella application. + """ + def no_umbrella!(task) do + if Mix.Project.umbrella?() do + Mix.raise "Cannot run task #{inspect task} from umbrella project root. " <> + "Change directory to one of the umbrella applications and try again" + end + end + + @doc """ + Returns `true` if module implements behaviour. + """ + def ensure_implements(module, behaviour, message) do + all = Keyword.take(module.__info__(:attributes), [:behaviour]) + unless [behaviour] in Keyword.values(all) do + Mix.raise "Expected #{inspect module} to implement #{inspect behaviour} " <> + "in order to #{message}" + end + end +end diff --git a/deps/ecto/lib/mix/tasks/ecto.create.ex b/deps/ecto/lib/mix/tasks/ecto.create.ex new file mode 100644 index 0000000000000000000000000000000000000000..c9a03f1f941c3f5b858e1cf078e7b6371c064782 --- /dev/null +++ b/deps/ecto/lib/mix/tasks/ecto.create.ex @@ -0,0 +1,77 @@ +defmodule Mix.Tasks.Ecto.Create do + use Mix.Task + import Mix.Ecto + + @shortdoc "Creates the repository storage" + + @switches [ + quiet: :boolean, + repo: [:string, :keep], + no_compile: :boolean, + no_deps_check: :boolean + ] + + @aliases [ + r: :repo, + q: :quiet + ] + + @moduledoc """ + Create the storage for the given repository. + + The repositories to create are the ones specified under the + `:ecto_repos` option in the current app configuration. However, + if the `-r` option is given, it replaces the `:ecto_repos` config. + + Since Ecto tasks can only be executed once, if you need to create + multiple repositories, set `:ecto_repos` accordingly or pass the `-r` + flag multiple times. + + ## Examples + + $ mix ecto.create + $ mix ecto.create -r Custom.Repo + + ## Command line options + + * `-r`, `--repo` - the repo to create + * `--quiet` - do not log output + * `--no-compile` - do not compile before creating + * `--no-deps-check` - do not compile before creating + + """ + + @impl true + def run(args) do + repos = parse_repo(args) + {opts, _} = OptionParser.parse!(args, strict: @switches, aliases: @aliases) + + Enum.each(repos, fn repo -> + ensure_repo(repo, args) + + ensure_implements( + repo.__adapter__(), + Ecto.Adapter.Storage, + "create storage for #{inspect(repo)}" + ) + + case repo.__adapter__().storage_up(repo.config()) do + :ok -> + unless opts[:quiet] do + Mix.shell().info("The database for #{inspect(repo)} has been created") + end + + {:error, :already_up} -> + unless opts[:quiet] do + Mix.shell().info("The database for #{inspect(repo)} has already been created") + end + + {:error, term} when is_binary(term) -> + Mix.raise("The database for #{inspect(repo)} couldn't be created: #{term}") + + {:error, term} -> + Mix.raise("The database for #{inspect(repo)} couldn't be created: #{inspect(term)}") + end + end) + end +end diff --git a/deps/ecto/lib/mix/tasks/ecto.drop.ex b/deps/ecto/lib/mix/tasks/ecto.drop.ex new file mode 100644 index 0000000000000000000000000000000000000000..69275c807cc66c2cb0d1ba41fc5e1f241c9cfc2e --- /dev/null +++ b/deps/ecto/lib/mix/tasks/ecto.drop.ex @@ -0,0 +1,106 @@ +defmodule Mix.Tasks.Ecto.Drop do + use Mix.Task + import Mix.Ecto + + @shortdoc "Drops the repository storage" + @default_opts [force: false, force_drop: false] + + @aliases [ + f: :force, + q: :quiet, + r: :repo + ] + + @switches [ + force: :boolean, + force_drop: :boolean, + quiet: :boolean, + repo: [:keep, :string], + no_compile: :boolean, + no_deps_check: :boolean + ] + + @moduledoc """ + Drop the storage for the given repository. + + The repositories to drop are the ones specified under the + `:ecto_repos` option in the current app configuration. However, + if the `-r` option is given, it replaces the `:ecto_repos` config. + + Since Ecto tasks can only be executed once, if you need to drop + multiple repositories, set `:ecto_repos` accordingly or pass the `-r` + flag multiple times. + + ## Examples + + $ mix ecto.drop + $ mix ecto.drop -r Custom.Repo + + ## Command line options + + * `-r`, `--repo` - the repo to drop + * `-q`, `--quiet` - run the command quietly + * `-f`, `--force` - do not ask for confirmation when dropping the database. + Configuration is asked only when `:start_permanent` is set to true + (typically in production) + * `--force-drop` - force the database to be dropped even + if it has connections to it (requires PostgreSQL 13+) + * `--no-compile` - do not compile before dropping + * `--no-deps-check` - do not compile before dropping + + """ + + @impl true + def run(args) do + repos = parse_repo(args) + {opts, _} = OptionParser.parse!(args, strict: @switches, aliases: @aliases) + opts = Keyword.merge(@default_opts, opts) + + Enum.each(repos, fn repo -> + ensure_repo(repo, args) + + ensure_implements( + repo.__adapter__(), + Ecto.Adapter.Storage, + "drop storage for #{inspect(repo)}" + ) + + if skip_safety_warnings?() or + opts[:force] or + Mix.shell().yes?( + "Are you sure you want to drop the database for repo #{inspect(repo)}?" + ) do + drop_database(repo, opts) + end + end) + end + + defp skip_safety_warnings? do + Mix.Project.config()[:start_permanent] != true + end + + defp drop_database(repo, opts) do + config = + opts + |> Keyword.take([:force_drop]) + |> Keyword.merge(repo.config()) + + case repo.__adapter__().storage_down(config) do + :ok -> + unless opts[:quiet] do + Mix.shell().info("The database for #{inspect(repo)} has been dropped") + end + + {:error, :already_down} -> + unless opts[:quiet] do + Mix.shell().info("The database for #{inspect(repo)} has already been dropped") + end + + {:error, term} when is_binary(term) -> + Mix.raise("The database for #{inspect(repo)} couldn't be dropped: #{term}") + + {:error, term} -> + Mix.raise("The database for #{inspect(repo)} couldn't be dropped: #{inspect(term)}") + end + end +end diff --git a/deps/ecto/lib/mix/tasks/ecto.ex b/deps/ecto/lib/mix/tasks/ecto.ex new file mode 100644 index 0000000000000000000000000000000000000000..14d10da448da25ca8407771732af43666d24b1ad --- /dev/null +++ b/deps/ecto/lib/mix/tasks/ecto.ex @@ -0,0 +1,30 @@ +defmodule Mix.Tasks.Ecto do + use Mix.Task + + @shortdoc "Prints Ecto help information" + + @moduledoc """ + Prints Ecto tasks and their information. + + $ mix ecto + + """ + + @impl true + def run(args) do + {_opts, args} = OptionParser.parse!(args, strict: []) + + case args do + [] -> general() + _ -> Mix.raise "Invalid arguments, expected: mix ecto" + end + end + + defp general() do + Application.ensure_all_started(:ecto) + Mix.shell().info "Ecto v#{Application.spec(:ecto, :vsn)}" + Mix.shell().info "A toolkit for data mapping and language integrated query for Elixir." + Mix.shell().info "\nAvailable tasks:\n" + Mix.Tasks.Help.run(["--search", "ecto."]) + end +end diff --git a/deps/ecto/lib/mix/tasks/ecto.gen.repo.ex b/deps/ecto/lib/mix/tasks/ecto.gen.repo.ex new file mode 100644 index 0000000000000000000000000000000000000000..e6f7a31902f0c8ddf0d515b60463bde514918de0 --- /dev/null +++ b/deps/ecto/lib/mix/tasks/ecto.gen.repo.ex @@ -0,0 +1,110 @@ +defmodule Mix.Tasks.Ecto.Gen.Repo do + use Mix.Task + + import Mix.Ecto + import Mix.Generator + + @shortdoc "Generates a new repository" + + @switches [ + repo: [:string, :keep], + ] + + @aliases [ + r: :repo, + ] + + @moduledoc """ + Generates a new repository. + + The repository will be placed in the `lib` directory. + + ## Examples + + $ mix ecto.gen.repo -r Custom.Repo + + This generator will automatically open the config/config.exs + after generation if you have `ECTO_EDITOR` set in your environment + variable. + + ## Command line options + + * `-r`, `--repo` - the repo to generate + + """ + + @impl true + def run(args) do + no_umbrella!("ecto.gen.repo") + {opts, _} = OptionParser.parse!(args, strict: @switches, aliases: @aliases) + + repo = + case Keyword.get_values(opts, :repo) do + [] -> Mix.raise "ecto.gen.repo expects the repository to be given as -r MyApp.Repo" + [repo] -> Module.concat([repo]) + [_ | _] -> Mix.raise "ecto.gen.repo expects a single repository to be given" + end + + config = Mix.Project.config() + underscored = Macro.underscore(inspect(repo)) + + base = Path.basename(underscored) + file = Path.join("lib", underscored) <> ".ex" + app = config[:app] || :YOUR_APP_NAME + opts = [mod: repo, app: app, base: base] + + create_directory Path.dirname(file) + create_file file, repo_template(opts) + config_path = config[:config_path] || "config/config.exs" + + case File.read(config_path) do + {:ok, contents} -> + check = String.contains?(contents, "import Config") + config_first_line = get_first_config_line(check) <> "\n" + new_contents = config_first_line <> "\n" <> config_template(opts) + Mix.shell().info [:green, "* updating ", :reset, config_path] + File.write! config_path, String.replace(contents, config_first_line, new_contents) + + {:error, _} -> + create_file config_path, "import Config\n\n" <> config_template(opts) + end + + open?(config_path, 3) + + Mix.shell().info """ + Don't forget to add your new repo to your supervision tree + (typically in lib/#{app}/application.ex): + + def start(_type, _args) do + children = [ + #{inspect repo}, + ] + + And to add it to the list of Ecto repositories in your + configuration files (so Ecto tasks work as expected): + + config #{inspect app}, + ecto_repos: [#{inspect repo}] + + """ + end + + defp get_first_config_line(true), do: "import Config" + defp get_first_config_line(false), do: "use Mix.Config" + + embed_template :repo, """ + defmodule <%= inspect @mod %> do + use Ecto.Repo, + otp_app: <%= inspect @app %>, + adapter: Ecto.Adapters.Postgres + end + """ + + embed_template :config, """ + config <%= inspect @app %>, <%= inspect @mod %>, + database: "<%= @app %>_<%= @base %>", + username: "user", + password: "pass", + hostname: "localhost" + """ +end diff --git a/deps/ecto/mix.exs b/deps/ecto/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..856d7e6251f385ec0fca311caf03599670e54ab9 --- /dev/null +++ b/deps/ecto/mix.exs @@ -0,0 +1,177 @@ +defmodule Ecto.MixProject do + use Mix.Project + + @source_url "https://github.com/elixir-ecto/ecto" + @version "3.12.5" + + def project do + [ + app: :ecto, + version: @version, + elixir: "~> 1.11", + deps: deps(), + consolidate_protocols: Mix.env() != :test, + elixirc_paths: elixirc_paths(Mix.env()), + + # Hex + description: "A toolkit for data mapping and language integrated query for Elixir", + package: package(), + + # Docs + name: "Ecto", + docs: docs() + ] + end + + def application do + [ + extra_applications: [:logger, :crypto, :eex], + mod: {Ecto.Application, []} + ] + end + + defp deps do + [ + {:telemetry, "~> 0.4 or ~> 1.0"}, + {:decimal, "~> 2.0"}, + {:jason, "~> 1.0", optional: true}, + {:ex_doc, "~> 0.20", only: :docs} + ] + end + + defp package do + [ + maintainers: ["Eric Meadows-Jönsson", "José Valim", "Felipe Stival", "Greg Rychlewski"], + licenses: ["Apache-2.0"], + links: %{"GitHub" => @source_url}, + files: + ~w(.formatter.exs mix.exs README.md CHANGELOG.md lib) ++ + ~w(integration_test/cases integration_test/support) + ] + end + + defp docs do + [ + main: "Ecto", + source_ref: "v#{@version}", + logo: "guides/images/e.png", + extra_section: "GUIDES", + source_url: @source_url, + skip_undefined_reference_warnings_on: ["CHANGELOG.md"], + extras: extras(), + groups_for_extras: groups_for_extras(), + groups_for_docs: [ + group_for_function("Query API"), + group_for_function("Schema API"), + group_for_function("Transaction API"), + group_for_function("Process API"), + group_for_function("Config API"), + group_for_function("User callbacks") + ], + groups_for_modules: [ + # Ecto, + # Ecto.Changeset, + # Ecto.Multi, + # Ecto.Query, + # Ecto.Repo, + # Ecto.Schema, + # Ecto.Schema.Metadata, + # Mix.Ecto, + + Types: [ + Ecto.Enum, + Ecto.ParameterizedType, + Ecto.Type, + Ecto.UUID + ], + "Query APIs": [ + Ecto.Query.API, + Ecto.Query.WindowAPI, + Ecto.Queryable, + Ecto.SubQuery + ], + "Adapter specification": [ + Ecto.Adapter, + Ecto.Adapter.Queryable, + Ecto.Adapter.Schema, + Ecto.Adapter.Storage, + Ecto.Adapter.Transaction + ], + "Relation structs": [ + Ecto.Association.BelongsTo, + Ecto.Association.Has, + Ecto.Association.HasThrough, + Ecto.Association.ManyToMany, + Ecto.Association.NotLoaded, + Ecto.Embedded + ] + ], + before_closing_body_tag: fn + :html -> + """ + + + """ + + _ -> + "" + end + ] + end + + def extras() do + [ + "guides/introduction/Getting Started.md", + "guides/introduction/Embedded Schemas.md", + "guides/introduction/Testing with Ecto.md", + "guides/howtos/Aggregates and subqueries.md", + "guides/howtos/Composable transactions with Multi.md", + "guides/howtos/Constraints and Upserts.md", + "guides/howtos/Data mapping and validation.md", + "guides/howtos/Dynamic queries.md", + "guides/howtos/Multi tenancy with query prefixes.md", + "guides/howtos/Multi tenancy with foreign keys.md", + "guides/howtos/Self-referencing many to many.md", + "guides/howtos/Polymorphic associations with many to many.md", + "guides/howtos/Replicas and dynamic repositories.md", + "guides/howtos/Schemaless queries.md", + "guides/howtos/Test factories.md", + "guides/cheatsheets/crud.cheatmd", + "guides/cheatsheets/associations.cheatmd", + "CHANGELOG.md" + ] + end + + defp group_for_function(group), do: {String.to_atom(group), &(&1[:group] == group)} + + defp groups_for_extras do + [ + Introduction: ~r/guides\/introduction\/.?/, + Cheatsheets: ~r/cheatsheets\/.?/, + "How-To's": ~r/guides\/howtos\/.?/ + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] +end diff --git a/deps/safetensors/.formatter.exs b/deps/safetensors/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..d2cda26eddc9110057ce9e8002585682217542cc --- /dev/null +++ b/deps/safetensors/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/deps/safetensors/.hex b/deps/safetensors/.hex new file mode 100644 index 0000000000000000000000000000000000000000..1a23ace1151c2f2b552477e9d1a3d8617772f0d8 Binary files /dev/null and b/deps/safetensors/.hex differ diff --git a/deps/safetensors/CHANGELOG.md b/deps/safetensors/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..0d69081d955c18e24135a9526530421a1137e847 --- /dev/null +++ b/deps/safetensors/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v0.1.3](https://github.com/elixir-nx/safetensors/tree/v0.1.3) (2024-02-23) + +### Added + +- Added `Safetensors.write!/2` for memory-efficient writing to file ([#8](https://github.com/elixir-nx/safetensors/pull/8)) +- Added `:lazy` option to `Safetensors.read!/2` for reading tensors lazily ([#9](https://github.com/elixir-nx/safetensors/pull/9)) + +## [v0.1.2](https://github.com/elixir-nx/safetensors/tree/v0.1.2) (2023-09-27) + +### Added + +- Added `Safetensors.read!/1` for more efficient loading from file ([#4](https://github.com/elixir-nx/safetensors/pull/4)) + +## [v0.1.1](https://github.com/elixir-nx/safetensors/tree/v0.1.1) (2023-08-04) + +### Added + +- Added `Safetensors.dump/1` for serializing tensors + +### Fixed + +- Fixed `Safetensors.load!/1` for big-endian systems ([#2](https://github.com/elixir-nx/safetensors/pull/2)) + +## [v0.1.0](https://github.com/elixir-nx/safetensors/tree/v0.1.0) (2023-08-01) + +Initial release. diff --git a/deps/safetensors/LICENSE b/deps/safetensors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/deps/safetensors/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/deps/safetensors/README.md b/deps/safetensors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..20cc9f78239205ca17b2ac5f44052694a439aa63 --- /dev/null +++ b/deps/safetensors/README.md @@ -0,0 +1,37 @@ +# Safetensors + +[![ci](https://github.com/mimiquate/safetensors/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mimiquate/safetensors/actions?query=branch%3Amain) +[![Hex.pm](https://img.shields.io/hexpm/v/safetensors.svg)](https://hex.pm/packages/safetensors) +[![Docs](https://img.shields.io/badge/docs-gray.svg)](https://hexdocs.pm/safetensors) + +[Safetensors](https://huggingface.co/docs/safetensors/index) implementation for [Nx](https://github.com/elixir-nx/nx). + +Safetensors is a simple format for storing tensors in a language-agnostic manner. This packages allows loading and storing data in this format. + +## Installation + +You can add the `:safetensors` dependency to your `mix.exs`: + +```elixir +def deps do + [ + {:safetensors, "~> 0.1.3"} + ] +end +``` + +## License + +Copyright 2023 Mimiquate + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/deps/safetensors/hex_metadata.config b/deps/safetensors/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..1504b11c6c03f733c4f38199f9ffe7e820e8f33f --- /dev/null +++ b/deps/safetensors/hex_metadata.config @@ -0,0 +1,24 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-nx/safetensors">>}]}. +{<<"name">>,<<"safetensors">>}. +{<<"version">>,<<"0.1.3">>}. +{<<"description">>,<<"Safetensors implementation for Nx">>}. +{<<"elixir">>,<<"~> 1.14">>}. +{<<"app">>,<<"safetensors">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>, + [[{<<"name">>,<<"jason">>}, + {<<"app">>,<<"jason">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 1.4">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"nx">>}, + {<<"app">>,<<"nx">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.5">>}, + {<<"repository">>,<<"hexpm">>}]]}. +{<<"files">>, + [<<"lib">>,<<"lib/safetensors.ex">>,<<"lib/safetensors">>, + <<"lib/safetensors/file_tensor.ex">>,<<"lib/safetensors/shared.ex">>, + <<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"LICENSE">>, + <<"CHANGELOG.md">>]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/safetensors/lib/safetensors.ex b/deps/safetensors/lib/safetensors.ex new file mode 100644 index 0000000000000000000000000000000000000000..4f46b0edb465765a5b5d4e9746d84279723723a4 --- /dev/null +++ b/deps/safetensors/lib/safetensors.ex @@ -0,0 +1,232 @@ +defmodule Safetensors do + @moduledoc """ + [Safetensors](https://huggingface.co/docs/safetensors/index) implementation for `Nx`. + + ## Examples + + iex> x = Nx.tensor([1, 2, 3]) + iex> y = Nx.tensor([1.0, 2.0, 3.0]) + iex> tensors = %{"x" => x, "y" => y} + iex> data = Safetensors.dump(tensors) + iex> tensors = Safetensors.load!(data) + iex> tensors["x"] + #Nx.Tensor< + s64[3] + [1, 2, 3] + > + iex> tensors["y"] + #Nx.Tensor< + f32[3] + [1.0, 2.0, 3.0] + > + + """ + + alias Safetensors.Shared + + @header_metadata_key "__metadata__" + + @type_to_dtype %{ + {:bf, 16} => "BF16", + {:f, 64} => "F64", + {:f, 32} => "F32", + {:f, 16} => "F16", + {:s, 64} => "I64", + {:s, 32} => "I32", + {:s, 16} => "I16", + {:s, 8} => "I8", + {:u, 64} => "U64", + {:u, 32} => "U32", + {:u, 16} => "U16", + {:u, 8} => "U8" + } + + @dtype_to_type for {k, v} <- @type_to_dtype, into: %{}, do: {v, k} + + @doc """ + Writes a map of tensors to a file. + + Tensors are written into the file one by one, without the need to + dump all of them into the memory at once. + """ + @spec write!(path :: Path.t(), %{String.t() => Nx.Tensor.t()}) :: :ok + def write!(path, tensors) when is_map(tensors) do + File.open!(path, [:write, :raw], fn file -> + tensors = Enum.sort(tensors) + + {header_entries, _offset} = + Enum.map_reduce(tensors, 0, fn {tensor_name, tensor}, offset -> + tensor_header_entry(tensor_name, tensor, offset) + end) + + :ok = :file.write(file, header_binary(header_entries)) + + for {_tensor_name, tensor} <- tensors do + :ok = :file.write(file, tensor_to_iodata(tensor)) + end + end) + + :ok + end + + defp tensor_header_entry(tensor_name, tensor, offset) do + end_offset = offset + tensor_byte_size(tensor) + + header_entry = { + tensor_name, + Jason.OrderedObject.new( + dtype: tensor |> Nx.type() |> type_to_dtype(), + shape: tensor |> Nx.shape() |> Tuple.to_list(), + data_offsets: [offset, end_offset] + ) + } + + {header_entry, end_offset} + end + + defp header_binary(header_entries) do + header_json = + header_entries + |> Jason.OrderedObject.new() + |> Jason.encode!() + + [<>, header_json] + end + + defp tensor_byte_size(tensor) do + {_, elem_size} = Nx.type(tensor) + elem_byte_size = div(elem_size, 8) + Nx.size(tensor) * elem_byte_size + end + + defp tensor_to_iodata(tensor) do + {_, elem_size} = Nx.type(tensor) + + tensor + |> Nx.to_binary() + |> Shared.new_byte_order(elem_size, :little) + end + + @doc """ + Serializes the given map of tensors to iodata. + + `iodata` is a list of binaries that can be written to any IO device, + such as a file or a socket. You can ensure the result is a binary by + calling `IO.iodata_to_binary/1`. + """ + @spec dump(%{String.t() => Nx.Tensor.t()}) :: iodata() + def dump(tensors) when is_map(tensors) do + tensors = Enum.sort(tensors) + + {header_entries, {buffer, _offset}} = + Enum.map_reduce(tensors, {[], 0}, fn {tensor_name, tensor}, {buffer, offset} -> + {header_entry, end_offset} = tensor_header_entry(tensor_name, tensor, offset) + binary = tensor_to_iodata(tensor) + {header_entry, {[buffer, binary], end_offset}} + end) + + [header_binary(header_entries), buffer] + end + + @doc """ + Reads a serialized map of tensors from a file. + + Tensors are loaded into Nx one by one, without the need to load the + entire file from disk into memory. + + ## Options + + * `:lazy` - when `true`, instead of returning tensors, the function + returns lazy containers. Such a container can be converted to a + tensor using `Nx.to_tensor/1` and it is only at that point that + it is read from the file. Defaults to `false` + + """ + @spec read!(path :: Path.t(), keyword()) :: %{String.t() => Nx.LazyContainer.t()} + def read!(path, opts \\ []) do + opts = Keyword.validate!(opts, lazy: false) + + File.open!(path, [:read, :raw], fn file -> + {:ok, <>} = :file.read(file, 8) + {:ok, header_json} = :file.read(file, header_size) + + header = decode_header!(header_json) + + for {tensor_name, tensor_info} <- header, into: %{} do + %{"data_offsets" => [offset_start, offset_end]} = tensor_info + + {shape, type} = shape_and_type(tensor_info) + + byte_offset = header_size + 8 + offset_start + byte_size = offset_end - offset_start + + value = + if opts[:lazy] do + %Safetensors.FileTensor{ + shape: shape, + type: type, + path: path, + byte_offset: byte_offset, + byte_size: byte_size + } + else + {:ok, binary} = :file.pread(file, byte_offset, byte_size) + Shared.build_tensor(binary, shape, type) + end + + {tensor_name, value} + end + end) + end + + @doc """ + Loads a serialized map of tensors. + + It is the opposite of `dump/1`. + """ + @spec load!(iodata()) :: %{String.t() => Nx.Tensor.t()} + def load!(data) when is_binary(data) or is_list(data) do + data = IO.iodata_to_binary(data) + + << + header_size::unsigned-64-integer-little, + header_json::binary-size(header_size), + buffer::binary + >> = data + + header = decode_header!(header_json) + + for {tensor_name, tensor_info} <- header, into: %{} do + %{"data_offsets" => [offset_start, offset_end]} = tensor_info + {shape, type} = shape_and_type(tensor_info) + + tensor = + buffer + |> binary_slice(offset_start, offset_end - offset_start) + |> Shared.build_tensor(shape, type) + + {tensor_name, tensor} + end + end + + defp decode_header!(header_json) do + {_metadata, header} = + header_json + |> Jason.decode!() + |> Map.pop(@header_metadata_key) + + header + end + + defp shape_and_type(%{"dtype" => dtype, "shape" => shape}) do + {List.to_tuple(shape), dtype_to_type(dtype)} + end + + defp type_to_dtype(type) do + @type_to_dtype[type] || raise "unrecognized type #{inspect(type)}" + end + + defp dtype_to_type(dtype) do + @dtype_to_type[dtype] || raise "unrecognized dtype #{inspect(dtype)}" + end +end diff --git a/deps/safetensors/mix.exs b/deps/safetensors/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..e9fe78b7f454a18196c1acb0363ae29e1067c5de --- /dev/null +++ b/deps/safetensors/mix.exs @@ -0,0 +1,49 @@ +defmodule Safetensors.MixProject do + use Mix.Project + + @version "0.1.3" + @description "Safetensors implementation for Nx" + + def project do + [ + app: :safetensors, + version: @version, + description: @description, + name: "Safetensors", + elixir: "~> 1.14", + start_permanent: Mix.env() == :prod, + deps: deps(), + docs: docs(), + package: package() + ] + end + + def application do + [] + end + + defp deps do + [ + {:jason, "~> 1.4"}, + {:nx, "~> 0.5"}, + {:ex_doc, "~> 0.30.3", only: :dev, runtime: false} + ] + end + + defp docs do + [ + main: "Safetensors", + source_url: "https://github.com/elixir-nx/safetensors", + source_ref: "v#{@version}" + ] + end + + defp package do + [ + licenses: ["Apache-2.0"], + links: %{ + "GitHub" => "https://github.com/elixir-nx/safetensors" + } + ] + end +end