dataloader icon indicating copy to clipboard operation
dataloader copied to clipboard

[Ecto] Don't preload if only requesting the "id" field of a belongs_to association

Open Betree opened this issue 7 years ago • 1 comments
trafficstars

Let's say I have a :fruits_basket object that can contains fruits and that can be placed in another basket. Something like:

object :fruits_basket do
  field :id, non_null(:id)
  field :slug, non_null(:string)
  field :fruits, list_of(:delicious_fruit), do: resolve dataloader(:db, :fruits)
  field :parent, :fruits_basket, do: resolve dataloader(:db, :parent_basket)
end

As of today a request like:

basket(slug: "grandma-basket") {
  id
  fruits {
    name
    color
  }
  parent {
    id # We only ask for parent's id and no other field
  }
}

...would make two queries like:

SELECT (...) FROM fruits_baskets WHERE slug = "grandma-basket" -- Get basket
SELECT (...) FROM fruits_baskets WHERE id = 42 -- Get parent basket

The thing is that second query is not necessary: we already have the parent id in grandma's basket.

I think it is a very common pattern to query only for the id of an association. In this example, the request could be used to show a "Go to parent" link on the frontend.

My real use case is a comment system where comments can reply to each others by using a reply_to field. I would love to see Dataloader return the reply_to_id field instead of preloading the full reply_to when requesting only the id.

The easiest way to achieve this with actual system is to add a field for the id:

...
field :reply_to_id, :id
field :reply_to :comment, do: resolve dataloader(:db, :reply_to)
...

But that doesn't look very neat to me.

Betree avatar Dec 14 '17 05:12 Betree

This is a good idea :)

Implementation is a bit tricky. You gotta do some projection to determine if there's only an id field AND you gotta determine if the id field is using a custom resolver or not. If it's using a custom resolver then we're out of luck.

Still, probably doable. I probably won't have time to take a crack at it for a bit though unfortunately.

benwilson512 avatar Dec 21 '17 00:12 benwilson512