Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No need for validation query unless relevant fields were changed #2905

Merged
merged 1 commit into from
Feb 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/ecto/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1719,8 1719,13 @@ defmodule Ecto.Changeset do
{field, get_field(changeset, field)}
end

# No need to query if we haven't changed any of the fields in question
unrelated_changes? = fields -- Map.keys(changeset.changes) == fields

# If we don't have values for all fields, we can't query for uniqueness
if Enum.any?(where_clause, &(&1 |> elem(1) |> is_nil())) do
any_nil_values_for_fields? = Enum.any?(where_clause, &(&1 |> elem(1) |> is_nil()))

if unrelated_changes? || any_nil_values_for_fields? do
changeset
else
pk_pairs = pk_fields_and_values(changeset, struct)
Expand Down
16 changes: 16 additions & 0 deletions test/ecto/changeset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 1316,22 @@ defmodule Ecto.ChangesetTest do
Process.put(:test_repo_all_results, no_dup_result)
changeset = unsafe_validate_unique(base_changeset, :title, TestRepo, prefix: "public")
assert changeset.valid?

# The validation runs a query only when the changes are relevant to it
defmodule DetectionRepo do
def one(query) do
send(self(), [function: :one, query: query])
end
end
body_change = changeset(%Post{title: "Hello World", body: "hi"}, %{body: "ho"})
unsafe_validate_unique(body_change, :body, DetectionRepo)
assert_receive [function: :one, query: �to.Query{}]

unsafe_validate_unique(body_change, [:body, :title], DetectionRepo)
assert_receive [function: :one, query: �to.Query{}]

unsafe_validate_unique(body_change, :title, DetectionRepo)
refute_receive [function: :one, query: �to.Query{}]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to say we should break this apart but given everything is together for now, then it is best to leave it for another PR. :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@josevalim Here's a PR to break apart the test: #2909

end

## Locks
Expand Down