graphql-batch icon indicating copy to clipboard operation
graphql-batch copied to clipboard

Detect N+1 Queries

Open eshaiju opened this issue 8 years ago • 4 comments

Is there any tool like bullet gem to detect N+1 queries in GraphQL resolvers. Does Bullet gem will detect it?

eshaiju avatar Sep 07 '17 08:09 eshaiju

You can use GraphQL::Batch::Executor.current.loading to detect whether, at the time of a query, it is in a loaders perform method or from outside of a loaders perform method.

For active record, I think you can use something like the following to raise for unbatched queries

def assert_no_unbatched_queries
  callback = lambda do |name, start, finish, message_id, values|
    raise "unbatched query: #{values[:sql]}" unless GraphQL::Batch::Executor.current.loading
  end
  ActiveSupport::Notifications.subscribed('sql.active_record', callback) do
    yield
  end
end

which allow you to write tests for unbatched queries.

You would need something similar to prevent N+1 queries against other datastores (e.g. memcached or redis).

Let me know if that works for you. This repo should probably at least have an example and mention of how to do something like this in the README.

Does Bullet gem will detect it?

You tell me. I don't have any experience with it.

dylanahsmith avatar Sep 07 '17 15:09 dylanahsmith

@dylanahsmith Bullet gem seams not picking GraphQl N+1queries.

eshaiju avatar Oct 18 '17 20:10 eshaiju

@eshaiju I have used bullet on a few projects using GraphQL and it does detect N+1 queries.For reference, I'm using the following configuration on my development.rb environment file:

config.after_initialize do
    Bullet.enable = true
    Bullet.alert = true
    Bullet.bullet_logger = true
    Bullet.console = true
    Bullet.rails_logger = true
    Bullet.add_footer = true
  end

feliperoveran avatar Mar 19 '18 22:03 feliperoveran

@eshaiju I am currently using bullet along with GraphQL and it looks like I am also facing the same issue. Bullet gem not detecting N+1 queries for GraphQL requests.

Is there any update on this?

jiss-joy avatar Jan 30 '24 06:01 jiss-joy