1

Field

module Types
  class QueryType < GraphQL::Schema::Object
      field :restaurants, [RestaurantType], null: true do
        description "Lists all restaurants"
      end

      def restaurants
        Restaurant.all
      end
    end
  end

Query

query Restaurants {
  restaurants {
    name
    cuisine
  }
}

In the example above, Restaurants.all will initially get all the rows from the restaurant table and then filter them out according to the query.

This is quite inefficient as we can use the query to filter out our data on the actual sql request:

module Types
  class QueryType < GraphQL::Schema::Object
    field :restaurant, RestaurantType, null: true do
      description "Find a restaurant by ID"
      argument :id, Int, required: true
    end

    field :restaurants, [RestaurantType], null: true, resolve: -> (obj, args, ctx) {
                                        children = ctx.irep_node.scoped_children
                                        root_key = children.keys.first
                                        params = children[root_key].keys
                                        Restaurant.all.select(params.join(", "))
                                      } do
      description "Lists all restaurants"
    end
  end
end

The underline sql representation is then

Option A SELECT "restaurants".* FROM "restaurants" - returns more rows than needed

Option B SELECT name, cuisine FROM "restaurants" - only returns the requested rows

This is not ideal as it won't work with joins, unless explicitly handled.

Since I'm quite new to Ruby and/or Rails I've been wondering if that's a good practice, or are there any other ways to achieve such optimization?

silicakes
  • 6,364
  • 3
  • 28
  • 39
  • Both `SELECT` statements you mention will select the same number of rows. The difference will be in the columns, all (*) vs. only name/cuisine – Ohad Dahan Feb 21 '19 at 23:08

0 Answers0