Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rmosolgo/d84fb3e707661e6ea6c6a3c18e5f6084 to your computer and use it in GitHub Desktop.
Save rmosolgo/d84fb3e707661e6ea6c6a3c18e5f6084 to your computer and use it in GitHub Desktop.
Only query for selected columns with ActiveRecord and GraphQL
require "bundler/inline"
gemfile do
gem "graphql", "2.3.7"
gem "sqlite3", "~>1.4"
gem "activerecord", require: "active_record"
end
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
self.verbose = false
create_table :books, force: true do |t|
t.column :author, :string
t.column :title, :string
t.column :stars, :integer
end
end
class Book < ActiveRecord::Base; end
Book.create!(title: "Remembering", author: "Wendell Berry", stars: 3)
Book.create!(title: "The Going to Bed Book", author: "Sandra Boynton", stars: 5)
Book.create!(title: "Historical Brewing Techniques", author: "Lars Marius Garshol", stars: 4)
Book.create!(title: "The Tale of Tom Kitten", author: "Beatrix Potter", stars: 3)
class BookSchema < GraphQL::Schema
class Book < GraphQL::Schema::Object
field :author, String
field :title, String
field :stars, Integer
end
class Query < GraphQL::Schema::Object
field :books, [Book], extras: [:lookahead]
def books(lookahead:)
fields = lookahead.selections.map(&:name)
::Book.select(fields)
end
end
query(Query)
end
ActiveRecord::Base.logger = Logger.new($stdout)
# Select only `title` from the database:
pp BookSchema.execute("{ books { title } }").to_h
# D, [2024-07-03T09:13:41.119094 #83491] DEBUG -- : Book Load (0.1ms) SELECT "books"."title" FROM "books"
# {"data"=>{"books"=>[{"title"=>"Remembering"}, {"title"=>"The Going to Bed Book"}, {"title"=>"Historical Brewing Techniques"}, {"title"=>"The Tale of Tom Kitten"}]}}
# Select only `author` and `stars`:
pp BookSchema.execute("{ books { author stars } }").to_h
# D, [2024-07-03T09:13:41.152586 #83491] DEBUG -- : Book Load (0.1ms) SELECT "books"."author", "books"."stars" FROM "books"
# {"data"=>{"books"=>[{"author"=>"Wendell Berry", "stars"=>3}, {"author"=>"Sandra Boynton", "stars"=>5}, {"author"=>"Lars Marius Garshol", "stars"=>4}, {"author"=>"Beatrix Potter", "stars"=>3}]}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment