absinthe-graphql / dataloader

DataLoader for Elixir
MIT License
489 stars 99 forks source link

Fix for custom `distinct` handling in laterals #174

Open antonsatin opened 2 months ago

antonsatin commented 2 months ago

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]}]}