Class: GraphQL::Query

Inherits:
Object
  • Object
show all
Extended by:
Forwardable, Autoload
Includes:
Runnable, Tracing::Traceable
Defined in:
lib/graphql/query.rb,
lib/graphql/query/result.rb,
lib/graphql/query/context.rb,
lib/graphql/query/partial.rb,
lib/graphql/query/fingerprint.rb,
lib/graphql/query/null_context.rb,
lib/graphql/query/validation_pipeline.rb,
lib/graphql/query/context/scoped_context.rb,
lib/graphql/query/input_validation_result.rb,
lib/graphql/query/variable_validation_error.rb

Overview

A combination of query string and Schema instance which can be reduced to a result.

The API-specific portions of guides/queries/executing_queries.md were migrated to Schema#execute, Schema#multiplex, and this initializer. Those APIs accept query strings or parsed documents, variables, context, root values, operation names, validation controls, and depth/complexity limits. The guide remains a standalone execution tutorial.

API-specific portions

GraphQL::Schema.execute runs one query and GraphQL::Schema.multiplex runs several queries with shared multiplex-level context. Both delegate to this class, so the following options have the same meaning in each API:

  • query or the positional query string is a GraphQL document to parse.
  • document: accepts an already-parsed GraphQL::Language::Nodes::Document; pass one or the other, not both.
  • variables: is a Hash of values for $-named variables. Keys omit the leading $; values may contain nested input objects.
  • context: contains application values made available to field resolvers, schema hooks, and Query::Context.
  • root_value: is passed as obj to root-level fields.
  • operation_name: selects which named operation to execute when a document contains more than one operation.
  • validate: false skips static validation. Use this only when the document has already been validated; execution of an invalid document is undefined.
  • max_depth: and max_complexity: override the corresponding schema limits for this query. nil uses the schema configuration.

The executing queries guide keeps examples for variables, context, scoped context, and root values. This class and the Schema#execute/Schema#multiplex method comments are the source of truth for option names, defaults, and execution behavior.

Defined Under Namespace

Modules: Fingerprint, Runnable Classes: Context, InputValidationResult, NullContext, OperationNameMissingError, Partial, Result, ValidationPipeline, VariableValidationError

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Autoload

autoload, eager_load!

Methods included from Runnable

#after_lazy, #arguments_cache, #arguments_for, #handle_or_reraise

Methods included from Tracing::Traceable

#trace

Constructor Details

#initialize(schema, query_string = nil, query: nil, document: nil, context: nil, variables: nil, multiplex: nil, validate: true, static_validator: nil, visibility_profile: nil, subscription_topic: nil, operation_name: nil, root_value: nil, max_depth: schema.max_depth, max_complexity: schema.max_complexity, warden: nil, use_visibility_profile: nil) ⇒ Query

Prepare query query_string on schema

Parameters

  • schema (GraphQL::Schema)
  • query_string (String)
  • context (#[]) — an arbitrary hash of values which you can access in Schema::Field#resolve
  • variables (Hash) — values for $variables in the query
  • operation_name (String) — if the query string contains many operations, this is the one which should be executed
  • root_value (Object) — the object used to resolve fields on the root type
  • max_depth (Numeric) — the maximum number of nested selections allowed for this query (falls back to schema-level value)
  • max_complexity (Numeric) — the maximum field complexity for this query (falls back to schema-level value)
  • visibility_profile (Symbol) — Another way to assign context[:visibility_profile]

:call-seq:

initialize(GraphQL::Schema schema, String query_string, query:, document:, #[] context:, Hash variables:, multiplex:, validate:, static_validator:, Symbol visibility_profile:, subscription_topic:, String operation_name:, Object root_value:, Numeric max_depth:, Numeric max_complexity:, warden:, use_visibility_profile:)


213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/graphql/query.rb', line 213

def initialize(schema, query_string = nil, query: nil, document: nil, context: nil, variables: nil, multiplex: nil, validate: true, static_validator: nil, visibility_profile: nil, subscription_topic: nil, operation_name: nil, root_value: nil, max_depth: schema.max_depth, max_complexity: schema.max_complexity, warden: nil, use_visibility_profile: nil)
  # Even if `variables: nil` is passed, use an empty hash for simpler logic
  variables ||= {}
  @multiplex = multiplex
  @schema = schema
  @context = schema.context_class.new(query: self, values: context)
  if visibility_profile
    @context[:visibility_profile] ||= visibility_profile
  end

  if use_visibility_profile.nil?
    use_visibility_profile = warden ? false : schema.use_visibility_profile?
  end

  if use_visibility_profile
    @visibility_profile = @schema.visibility.profile_for(@context)
    @warden = Schema::Warden::NullWarden.new(context: @context, schema: @schema)
  else
    @visibility_profile = nil
    @warden = warden
  end

  @subscription_topic = subscription_topic
  @root_value = root_value
  @fragments = nil
  @operations = nil
  @input_values = nil
  @finalizers = @top_level_finalizers = nil
  @validate = validate
  self.static_validator = static_validator if static_validator
  context_tracers = (context ? context.fetch(:tracers, []) : [])
  @tracers = schema.tracers + context_tracers

  if !context_tracers.empty? && !(schema.trace_class <= GraphQL::Tracing::CallLegacyTracers)
    raise ArgumentError, "context[:tracers] are not supported without `trace_with(GraphQL::Tracing::CallLegacyTracers)` in the schema configuration, please add it."
  end

  @analysis_errors = []
  if variables.is_a?(String)
    raise ArgumentError, "Query variables should be a Hash, not a String. Try JSON.parse to prepare variables."
  else
    @provided_variables = variables || {}
  end

  @query_string = query_string || query
  @document = document

  if @query_string && @document
    raise ArgumentError, "Query should only be provided a query string or a document, not both."
  end

  if @query_string && !@query_string.is_a?(String)
    raise ArgumentError, "Query string argument should be a String, got #{@query_string.class.name} instead."
  end

  # A two-layer cache of type resolution:
  # { abstract_type => { value => resolved_type } }
  @resolved_types_cache = Hash.new do |h1, k1|
    h1[k1] = Hash.new do |h2, k2|
      h2[k2] = @schema.resolve_type(k1, k2, @context)
    end
  end

  # Trying to execute a document
  # with no operations returns an empty hash
  @ast_variables = []
  @mutation = false
  @operation_name = operation_name
  @prepared_ast = false
  @validation_pipeline = nil
  @max_depth = max_depth
  @max_complexity = max_complexity

  @result_values = nil
  @executed = false

  @logger = schema.logger_for(context)
end

Instance Attribute Details

#analysis_errors ⇒ Object

Returns the value of attribute analysis_errors.



504
505
506
# File 'lib/graphql/query.rb', line 504

def analysis_errors
  @analysis_errors
end

#context ⇒ Object (readonly)

Returns the value of attribute context.



108
109
110
# File 'lib/graphql/query.rb', line 108

def context
  @context
end

#logger ⇒ Object (readonly)

Returns the value of attribute logger.



583
584
585
# File 'lib/graphql/query.rb', line 583

def logger
  @logger
end

#multiplex ⇒ Object

Returns the value of attribute multiplex.



302
303
304
# File 'lib/graphql/query.rb', line 302

def multiplex
  @multiplex
end

#operation_name ⇒ Object

Returns

  • nil, String — The operation name provided by client or the one inferred from the document. Used to determine which operation to run.


116
117
118
# File 'lib/graphql/query.rb', line 116

def operation_name
  @operation_name
end

#provided_variables ⇒ Object (readonly)

Returns the value of attribute provided_variables.



108
109
110
# File 'lib/graphql/query.rb', line 108

def provided_variables
  @provided_variables
end

#query_string ⇒ Object

If a document was provided to GraphQL::Schema#execute instead of the raw query string, we will need to get it from the document



293
294
295
# File 'lib/graphql/query.rb', line 293

def query_string
  @query_string ||= (document ? document.to_query_string : nil)
end

#result_values ⇒ Object

:nodoc:



349
350
351
# File 'lib/graphql/query.rb', line 349

def result_values
  @result_values
end

#root_value ⇒ Object

The value for root types



111
112
113
# File 'lib/graphql/query.rb', line 111

def root_value
  @root_value
end

#schema ⇒ Object (readonly)

Returns the value of attribute schema.



108
109
110
# File 'lib/graphql/query.rb', line 108

def schema
  @schema
end

#static_validator ⇒ Object

Returns

  • GraphQL::StaticValidation::Validator — if present, the query will validate with these rules.


140
141
142
# File 'lib/graphql/query.rb', line 140

def static_validator
  @static_validator
end

#subscription_topic ⇒ Object (readonly)

Returns

  • String, nil — the triggered event, if this query is a subscription update


193
194
195
# File 'lib/graphql/query.rb', line 193

def subscription_topic
  @subscription_topic
end

#tracers ⇒ Object (readonly)

Returns the value of attribute tracers.



195
196
197
# File 'lib/graphql/query.rb', line 195

def tracers
  @tracers
end

#validate ⇒ Object

Returns

  • Boolean — if false, static validation is skipped (execution behavior for invalid queries is undefined)


121
122
123
# File 'lib/graphql/query.rb', line 121

def validate
  @validate
end

#visibility_profile ⇒ Object (readonly)

Returns

  • Symbol, nil


300
301
302
# File 'lib/graphql/query.rb', line 300

def visibility_profile
  @visibility_profile
end

Instance Method Details

#current_trace ⇒ Object

Returns

  • GraphQL::Tracing::Trace

:call-seq:

current_trace() -> GraphQL::Tracing::Trace


310
311
312
# File 'lib/graphql/query.rb', line 310

def current_trace
  @current_trace ||= context[:trace] || (multiplex ? multiplex.current_trace : schema.new_trace(multiplex: multiplex, query: self))
end

#document ⇒ Object

Returns

  • GraphQL::Language::Nodes::Document

:call-seq:

document() -> GraphQL::Language::Nodes::Document


166
167
168
169
170
171
172
173
# File 'lib/graphql/query.rb', line 166

def document
  # It's ok if this hasn't been assigned yet
  if @query_string || @document
    with_prepared_ast { @document }
  else
    nil
  end
end

#executed? ⇒ Boolean

Returns:

  • (Boolean)


404
405
406
# File 'lib/graphql/query.rb', line 404

def executed?
  @executed
end

#fingerprint ⇒ Object

This contains a few components:

  • The selected operation name (or anonymous)
  • The fingerprint of the query string
  • The number of given variables (for readability)
  • The fingerprint of the given variables

This fingerprint can be used to track runs of the same operation-variables combination over time.

See operation_fingerprint and variables_fingerprint for the components.

Returns

  • String — An opaque hash identifying this operation-variables combination

:call-seq:

fingerprint() -> String


473
474
475
# File 'lib/graphql/query.rb', line 473

def fingerprint
  @fingerprint ||= "#{operation_fingerprint}/#{variables_fingerprint}"
end

#fragments ⇒ Object



351
352
353
# File 'lib/graphql/query.rb', line 351

def fragments
  with_prepared_ast { @fragments }
end

#get_field(owner, field_name) ⇒ Object



517
518
519
# File 'lib/graphql/query.rb', line 517

def get_field(owner, field_name)
  types.field(owner, field_name) # rubocop:disable Development/ContextIsPassedCop
end

#get_type(type_name) ⇒ Object



513
514
515
# File 'lib/graphql/query.rb', line 513

def get_type(type_name)
  types.type(type_name) # rubocop:disable Development/ContextIsPassedCop
end

#input_values ⇒ Object

:nodoc:



336
337
338
# File 'lib/graphql/query.rb', line 336

def input_values # :nodoc:
  @input_values ||= Execution::InputValues.new(self)
end

#inspect ⇒ Object



175
176
177
# File 'lib/graphql/query.rb', line 175

def inspect
  "query ..."
end

#lookahead ⇒ Object

A lookahead for the root selections of this query

Returns

  • GraphQL::Execution::Lookahead

:call-seq:

lookahead() -> GraphQL::Execution::Lookahead


326
327
328
329
330
331
332
333
334
# File 'lib/graphql/query.rb', line 326

def lookahead
  @lookahead ||= begin
    if selected_operation.nil?
      GraphQL::Execution::Lookahead::NULL_LOOKAHEAD
    else
      GraphQL::Execution::Lookahead.new(query: self, root_type: root_type, ast_nodes: [selected_operation])
    end
  end
end

#mutation? ⇒ Boolean

Returns:

  • (Boolean)


571
572
573
# File 'lib/graphql/query.rb', line 571

def mutation?
  with_prepared_ast { @mutation }
end

#operation_fingerprint ⇒ Object

Returns

  • String — An opaque hash for identifying this query's given query string and selected operation

:call-seq:

operation_fingerprint() -> String


483
484
485
# File 'lib/graphql/query.rb', line 483

def operation_fingerprint
  @operation_fingerprint ||= "#{selected_operation_name || "anonymous"}/#{Fingerprint.generate(query_string || "")}"
end

#operations ⇒ Object



355
356
357
# File 'lib/graphql/query.rb', line 355

def operations
  with_prepared_ast { @operations }
end

#path ⇒ Object



359
360
361
# File 'lib/graphql/query.rb', line 359

def path
  EmptyObjects::EMPTY_ARRAY
end

#possible_types(type) ⇒ Object



521
522
523
# File 'lib/graphql/query.rb', line 521

def possible_types(type)
  types.possible_types(type) # rubocop:disable Development/ContextIsPassedCop
end

#query? ⇒ Boolean

Returns:

  • (Boolean)


575
576
577
# File 'lib/graphql/query.rb', line 575

def query?
  with_prepared_ast { @query }
end

#resolve_type(abstract_type, value = NOT_CONFIGURED) ⇒ Object

See possible_types to apply filtering from only / except

Parameters

  • abstract_type (GraphQL::UnionType, GraphQL::InterfaceType)
  • value (Object) — Any runtime value

Returns

:call-seq:

resolve_type(GraphQL::UnionType | GraphQL::InterfaceType abstract_type, Object value) -> GraphQL::ObjectType | nil


559
560
561
562
563
564
565
566
567
568
569
# File 'lib/graphql/query.rb', line 559

def resolve_type(abstract_type, value = NOT_CONFIGURED)
  if value.is_a?(Symbol) && value == NOT_CONFIGURED
    # Old method signature
    value = abstract_type
    abstract_type = nil
  end
  if value.is_a?(GraphQL::Schema::Object)
    value = value.object
  end
  @resolved_types_cache[abstract_type][value]
end

#result ⇒ Object

Get the result for this query, executing it once

Returns

  • GraphQL::Query::Result — A Hash-like GraphQL response, with "data" and/or "errors" keys

:call-seq:

result() -> GraphQL::Query::Result


396
397
398
399
400
401
402
# File 'lib/graphql/query.rb', line 396

def result
  if !@executed
    execution_engine = @schema.default_execution_next ? Execution::Next : Execution::Interpreter
    execution_engine.run_all(@schema, [self], context: @context)
  end
  @result ||= Query::Result.new(query: self, values: @result_values)
end

#root_type ⇒ Object



538
539
540
# File 'lib/graphql/query.rb', line 538

def root_type
  root_type_for_operation(selected_operation.operation_type)
end

#root_type_for_operation(op_type) ⇒ Object



525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/graphql/query.rb', line 525

def root_type_for_operation(op_type)
  case op_type
  when "query", nil
    types.query_root # rubocop:disable Development/ContextIsPassedCop
  when "mutation"
    types.mutation_root # rubocop:disable Development/ContextIsPassedCop
  when "subscription"
    types.subscription_root # rubocop:disable Development/ContextIsPassedCop
  else
    raise ArgumentError, "unexpected root type name: #{op_type.inspect}; expected nil, 'query', 'mutation', or 'subscription'"
  end
end

#run_partials(partials_hashes) ⇒ Object

Run subtree partials of this query and return their results. Each partial is identified with a path: and object: where the path references a field in the AST and the object will be treated as the return value from that field. Subfields of the field named by path will be executed with object as the starting point

Parameters

  • partials_hashes (Array<Hash{Symbol => Object}>) — Hashes with path: and object: keys

Returns

  • Array<GraphQL::Query::Result>

:call-seq:

run_partials(Array[Hash[Symbol, Object]] partials_hashes) -> Array[GraphQL::Query::Result]


379
380
381
382
383
384
385
386
# File 'lib/graphql/query.rb', line 379

def run_partials(partials_hashes)
  partials = partials_hashes.map { |partial_options| Partial.new(**partial_options, query: self) }
  if context[:__graphql_execute_next]
    Execution::Next.run_all(@schema, partials, context: @context)
  else
    Execution::Interpreter.run_all(@schema, partials, context: @context)
  end
end

#sanitized_query_string(inline_variables: true) ⇒ Object

A version of the given query string, with:

  • Variables inlined to the query
  • Strings replaced with <REDACTED>

Returns

  • String, nil — Returns nil if the query is invalid.

:call-seq:

sanitized_query_string(inline_variables:) -> String | nil


450
451
452
453
454
# File 'lib/graphql/query.rb', line 450

def sanitized_query_string(inline_variables: true)
  with_prepared_ast {
    schema.sanitized_printer.new(self, inline_variables: inline_variables).sanitized_query_string
  }
end

#selected_operation ⇒ Object

This is the operation to run for this query. If more than one operation is present, it must be named at runtime.

Returns

  • GraphQL::Language::Nodes::OperationDefinition, nil

:call-seq:

selected_operation() -> GraphQL::Language::Nodes::OperationDefinition | nil


421
422
423
# File 'lib/graphql/query.rb', line 421

def selected_operation
  with_prepared_ast { @selected_operation }
end

#selected_operation_name ⇒ Object

Returns

  • String, nil — The name of the operation to run (may be inferred)

:call-seq:

selected_operation_name() -> String | nil


185
186
187
188
# File 'lib/graphql/query.rb', line 185

def selected_operation_name
  return nil unless selected_operation
  selected_operation.name
end

#static_errors ⇒ Object



408
409
410
# File 'lib/graphql/query.rb', line 408

def static_errors
  validation_errors + analysis_errors + context.errors
end

#subscription? ⇒ Boolean

Returns:

  • (Boolean)


579
580
581
# File 'lib/graphql/query.rb', line 579

def subscription?
  with_prepared_ast { @subscription }
end

#subscription_update? ⇒ Boolean

Returns:

  • (Boolean)


314
315
316
# File 'lib/graphql/query.rb', line 314

def subscription_update?
  @subscription_topic && subscription?
end

#types ⇒ Object



542
543
544
# File 'lib/graphql/query.rb', line 542

def types
  @visibility_profile || warden.visibility_profile
end

#valid? ⇒ Boolean

Returns:

  • (Boolean)


505
506
507
# File 'lib/graphql/query.rb', line 505

def valid?
  validation_pipeline.valid? && analysis_errors.empty?
end

#validation_pipeline ⇒ Object



497
498
499
# File 'lib/graphql/query.rb', line 497

def validation_pipeline
  with_prepared_ast { @validation_pipeline }
end

#variables ⇒ Object

Determine the values for variables of this query, using default values if a value isn't provided at runtime.

If some variable is invalid, errors are added to the query's validation errors.

Returns

  • GraphQL::Execution::VariableValues — Variables to apply to this query

:call-seq:

variables() -> GraphQL::Execution::VariableValues


436
437
438
# File 'lib/graphql/query.rb', line 436

def variables
  @variables ||= with_prepared_ast { input_values.variable_values }
end

#variables_fingerprint ⇒ Object

Returns

  • String — An opaque hash for identifying this query's given a variable values (not including defaults)

:call-seq:

variables_fingerprint() -> String


493
494
495
# File 'lib/graphql/query.rb', line 493

def variables_fingerprint
  @variables_fingerprint ||= "#{provided_variables.size}/#{Fingerprint.generate(provided_variables.to_json)}"
end

#warden ⇒ Object



509
510
511
# File 'lib/graphql/query.rb', line 509

def warden
  with_prepared_ast { @warden }
end