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

Fix for custom distinct handling in laterals #174

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

antonsatin
Copy link

Hi folks 👋🏻

I noticed that I wasn't able to add custom distinct clause to my has_many assoc query - it was raising "multiple distinct clauses not allowed" error. Then I looked at source code and there was a bypass clause for custom distinct already, but it was ignored. It looks like a bug, here's an explanation:

Ecto represents distinct clauses in a query as a
%Ecto.Query.QueryExpr{} struct. In Elixir, guards pass only when the evaluated condition is true but since the distinct struct is not explicitly true, the guard fails to pass.

This update reverses the guard logic so that it passes as long as the distinct value is not nil.

I wasn't sure if I should use is_nil vs matching on %QueryExpr{} struct explicitly - that struct is part of Ecto's internals, but on the other hand Dataloader already matches on different structs like assocs representation. Let me know what you think.

Test was passing because more general clause with limit and order_by keys was located before one that adds distinct, changing the order resulted in:

  1) test Loads has-many association with limit and pre-existing distinct (Dataloader.LimitQueryTest)
     test/dataloader/ecto/limit_query_test.exs:171
     ** (Dataloader.GetError) {%Ecto.Query.CompileError{message: "only one distinct expression is allowed in query"}, [{Dataloader.Source.Dataloader.Ecto, :preload_lateral, 5, [file: 'lib/dataloader/ecto.ex', line: 725]}, {Dataloader.Source.Dataloader.Ecto, :run_batch, 2, [file: 'lib/dataloader/ecto.ex', line: 700]}, {Dataloader.Source.Dataloader.Ecto, :"-run_batches/1-fun-1-", 2, [file: 'lib/dataloader/ecto.ex', line: 621]}, {Task.Supervised, :invoke_mfa, 2, [file: 'lib/task/supervised.ex', line: 89]}, {Task.Supervised, :reply, 4, [file: 'lib/task/supervised.ex', line: 34]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 226]}]}

Ecto represents distinct clauses in a query as a
`%Ecto.Query.QueryExpr{}` struct. In Elixir, guards pass only when the
evaluated condition is true but since the distinct struct is not explicitly true, the guard fails to pass.

This update reverses the guard logic so that it passes as long as the distinct value is not nil.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant