0

I have a following setup:

class Product < ApplicationRecord
  has_many :variants
end

class Variant < ApplicationRecord
  belongs_to :product
end

Types::QueryType = GraphQL::ObjectType.define do
  connection :products, Types::ProductType.connection_type do
    resolve -> (obj, _, _) do
      Product.all.includes(:variants)
    end
  end
end

Types::ProductType = GraphQL::ObjectType.define do
  connection :variants, Types::VariantType.connection_type do
    resolve -> (obj, _, _) { obj.variants }
  end
end

And running a following query:

{
  products {
    edges {
      nodes {
        variants {
          edges {
            node {
              id
            }
          }
        }
      }
    }
  }
}

produces following SQL queries:

  Product Load (2.7ms)  SELECT  "products".* FROM "products" LIMIT $1  [["LIMIT", 25]]
  Variant Load (8.6ms)  SELECT "variants".* FROM "variants" WHERE "variants"."product_id" IN (1, 2, 3)
  Variant Load (19.0ms)  SELECT  "variants".* FROM "variants" WHERE "variants"."product_id" = $1 LIMIT $2  [["product_id", 1], ["LIMIT", 25]]
  Variant Load (13.6ms)  SELECT  "variants".* FROM "variants" WHERE "variants"."product_id" = $1 LIMIT $2  [["product_id", 2], ["LIMIT", 25]]
  Variant Load (2.4ms)  SELECT  "variants".* FROM "variants" WHERE "variants"."product_id" = $1 LIMIT $2  [["product_id", 3], ["LIMIT", 25]]

As we can see in the sql output, includes works but graphql don't care and makes a n+1 anyway. Is that normal behaviour and i'm forced to use solutions like graphql-batch to fix that or something is not right with my setup? As far as i have seen all over the internet, using includes should be enough for such simple scenario and graphql should use the eager loaded data instead of producing the n+1. Have i done anything wrong in here?

I'm on graphql-ruby 1.7.9

mbajur
  • 4,406
  • 5
  • 49
  • 79

1 Answers1

0

I just received a reply on graphql-ruby issue tracker :

Hey, I noticed that LIMIT 25 is being applied to those queries. Do you know where that's being applied? If you want to use the result from the initial query, you should remove the LIMIT clause. (I'm guessing that if you ask for .limit(25), ActiveRecord won't use a cached relation.) Maybe you have a default_max_page_size? What happens if you remove it?

So, long story short, i removed the default_max_page_size config from my schema and it resolved the issue.

mbajur
  • 4,406
  • 5
  • 49
  • 79