lighthouse-graphql 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/README.md +15 -7
  4. data/docs/best-practices.md +6 -4
  5. data/docs/configuration.md +19 -5
  6. data/docs/custom-directives.md +2 -1
  7. data/docs/directives.md +65 -7
  8. data/docs/federation.md +1 -1
  9. data/docs/filtering-and-ordering.md +330 -30
  10. data/docs/generators.md +2 -2
  11. data/docs/getting-started.md +43 -10
  12. data/docs/motivation.md +3 -2
  13. data/docs/performance.md +4 -3
  14. data/docs/relationships.md +2 -1
  15. data/docs/relay.md +52 -3
  16. data/docs/resolvers.md +2 -2
  17. data/docs/schema-organisation.md +177 -0
  18. data/lib/generators/lighthouse/install/graphql_ruby_install.rb +14 -0
  19. data/lib/generators/lighthouse/install/install_generator.rb +31 -12
  20. data/lib/generators/lighthouse/install/templates/graphql.config.yml.tt +2 -1
  21. data/lib/generators/lighthouse/install/templates/initializer.rb.tt +11 -4
  22. data/lib/generators/lighthouse/install/templates/schema.graphql.tt +30 -0
  23. data/lib/lighthouse/ast_builder.rb +124 -0
  24. data/lib/lighthouse/config.rb +23 -4
  25. data/lib/lighthouse/contracts/arg_manipulator.rb +9 -5
  26. data/lib/lighthouse/contracts/field_builder.rb +13 -0
  27. data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +1 -2
  28. data/lib/lighthouse/directive_resolvers/all_resolver.rb +0 -2
  29. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +9 -6
  30. data/lib/lighthouse/directive_resolvers/base.rb +6 -37
  31. data/lib/lighthouse/directive_resolvers/builder_applier.rb +21 -6
  32. data/lib/lighthouse/directive_resolvers/count_resolver.rb +0 -1
  33. data/lib/lighthouse/directive_resolvers/first_resolver.rb +0 -2
  34. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +2 -3
  35. data/lib/lighthouse/directives/arguments/order_by.rb +190 -26
  36. data/lib/lighthouse/directives/arguments/where_conditions.rb +25 -0
  37. data/lib/lighthouse/directives/arguments/where_conditions_base.rb +84 -0
  38. data/lib/lighthouse/directives/arguments/where_has_conditions.rb +56 -0
  39. data/lib/lighthouse/directives/definitions.rb +0 -1
  40. data/lib/lighthouse/directives/generated_types.rb +103 -0
  41. data/lib/lighthouse/directives/registry.rb +39 -10
  42. data/lib/lighthouse/document_ast.rb +111 -0
  43. data/lib/lighthouse/graphql/version.rb +1 -1
  44. data/lib/lighthouse/ide_helper.rb +80 -23
  45. data/lib/lighthouse/namespaces.rb +1 -0
  46. data/lib/lighthouse/order_by/types.rb +137 -0
  47. data/lib/lighthouse/railtie.rb +9 -2
  48. data/lib/lighthouse/rb_lighthouse.rb +15 -5
  49. data/lib/lighthouse/resolve_info.rb +5 -5
  50. data/lib/lighthouse/schema_cache.rb +8 -4
  51. data/lib/lighthouse/schema_factory.rb +6 -9
  52. data/lib/lighthouse/schema_generator.rb +4 -15
  53. data/lib/lighthouse/schema_stitcher.rb +64 -0
  54. data/lib/lighthouse/support/naming.rb +0 -12
  55. data/lib/lighthouse/where_conditions/columns.rb +36 -0
  56. data/lib/lighthouse/where_conditions/handler.rb +152 -0
  57. data/lib/lighthouse/where_conditions/json_column.rb +99 -0
  58. data/lib/lighthouse/where_conditions/operator_map.rb +1 -4
  59. data/lib/lighthouse/where_conditions/types.rb +110 -0
  60. data/sig/lighthouse/directives.rbs +16 -3
  61. data/sig/lighthouse/graphql.rbs +48 -4
  62. data/sig/lighthouse.rbs +8 -2
  63. metadata +15 -4
  64. data/lib/lighthouse/directive_resolvers/where_conditions_applier.rb +0 -170
  65. data/lib/lighthouse/directives/where_conditions_directive.rb +0 -244
  66. data/lib/lighthouse/sdl_loader.rb +0 -22
@@ -38,7 +38,9 @@ require_relative 'namespaces'
38
38
  contracts/field_manipulator
39
39
  contracts/arg_manipulator
40
40
  contracts/arg_builder
41
- sdl_loader
41
+ contracts/field_builder
42
+ schema_stitcher
43
+ document_ast
42
44
  generated_resolvers
43
45
  default_resolve_dispatcher
44
46
  federation_directives
@@ -49,6 +51,7 @@ require_relative 'namespaces'
49
51
  events/schema_build
50
52
  resolver_bases
51
53
  root_types
54
+ ast_builder
52
55
  schema_generator
53
56
  schema_cache
54
57
  persisted_queries
@@ -79,14 +82,18 @@ require_relative 'namespaces'
79
82
  relation_counts
80
83
  nested_mutations
81
84
  directives/pagination_manipulator
82
- directives/where_conditions_directive
85
+ directives/generated_types
86
+ order_by/types
87
+ where_conditions/json_column
88
+ where_conditions/columns
89
+ where_conditions/types
90
+ where_conditions/handler
83
91
  directives/soft_deletes_directive
84
92
  directives/node_directive
85
93
  directives/model_directive
86
94
  directives/visibility_directive
87
95
  directive_resolvers/aggregate_resolver
88
96
  directive_resolvers/field_resolver
89
- directive_resolvers/where_conditions_applier
90
97
  directive_resolvers/all_resolver
91
98
  directive_resolvers/find_resolver
92
99
  directive_resolvers/paginate_resolver
@@ -124,6 +131,9 @@ require_relative 'namespaces'
124
131
  directives/arguments/filters
125
132
  directives/arguments/more_filters
126
133
  directives/arguments/order_by
134
+ directives/arguments/where_conditions_base
135
+ directives/arguments/where_conditions
136
+ directives/arguments/where_has_conditions
127
137
  directives/arguments/soft_deletes
128
138
  directives/definitions
129
139
  directives/registry
@@ -148,12 +158,12 @@ require_relative 'railtie' if defined?(Rails::Railtie)
148
158
 
149
159
  module Lighthouse::GraphQL::RbLightHouse
150
160
  class << self
151
- def get_schema(sdl_folder: nil, options: {})
161
+ def get_schema(schema_path: nil, options: {})
152
162
  base_types = options.delete(:base_types) || {}
153
163
  schema_class = options.delete(:base_schema)
154
164
 
155
165
  Lighthouse::GraphQL::SchemaFactory.build_base_schema(
156
- sdl_folder: sdl_folder,
166
+ schema_path: schema_path,
157
167
  base_types: base_types,
158
168
  schema_options: options.merge(schema_class: schema_class)
159
169
  )
@@ -6,7 +6,7 @@
6
6
  # directives to a query the resolver builds.
7
7
  #
8
8
  # type Query {
9
- # posts(title: String @eq, orderBy: [PostOrderByClause!] @orderBy): [Post!]! @builder(class: "Published")
9
+ # posts(title: String @eq, orderBy: _ @orderBy(columns: ["title"])): [Post!]! @builder(class: "Published")
10
10
  # }
11
11
  #
12
12
  # class Resolvers::Posts < Resolvers::BaseResolver
@@ -51,14 +51,14 @@ class Lighthouse::GraphQL::ResolveInfo
51
51
  context.respond_to?(:[]) ? context[:current_path] : nil
52
52
  end
53
53
 
54
- # `relation` with the field's model `scopes`, its @builder classes, and the
55
- # argument directives the client used (@eq, @where, @in, @like, @orderBy,
56
- # @whereConditions, @trashed, ...), as @all / @paginate apply them.
54
+ # `relation` with the field's model `scopes`, the argument directives the
55
+ # client used (@eq, @where, @in, @like, @orderBy, @whereConditions, @trashed,
56
+ # ...), then the field's @builder, @whereAuth and @orderBy(column:), as
57
+ # @all / @paginate apply them and as PHP Lighthouse's enhanceBuilder does.
57
58
  def enhance_builder(relation, scopes: [])
58
59
  resolver = Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver.new(field, parent_type, nil)
59
60
  args = arguments.respond_to?(:to_h) ? arguments.to_h : {}
60
61
  relation = Array(scopes).reduce(relation) { |acc, scope| acc.public_send(scope) }
61
- relation = Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.apply(relation, field.ast_node, args, context, resolver)
62
62
  resolver.apply_where_filters(relation, args, context)
63
63
  end
64
64
 
@@ -68,6 +68,10 @@ module Lighthouse::GraphQL::SchemaCache
68
68
  def fingerprint
69
69
  registry = Lighthouse::DirectiveRegistry.default
70
70
  manipulators = registry.sdl_manipulators.map { |manipulator| [manipulator.to_s, source_digest(manipulator)] }
71
+ phase = { Lighthouse::GraphQL::ASTBuilder => :build, Lighthouse::GraphQL::Directives::GeneratedTypes => :columns_enum,
72
+ Lighthouse::WhereConditions::Types => :define }
73
+ phase.merge!(registry.arg_manipulator_classes.index_with(:manipulate_arg_definition))
74
+ manipulators += phase.map { |manipulator, method_name| [manipulator.to_s, source_digest(manipulator, method_name)] }
71
75
  [
72
76
  registry.directive_definitions.sort,
73
77
  registry.type_definitions.sort,
@@ -77,10 +81,10 @@ module Lighthouse::GraphQL::SchemaCache
77
81
  ].inspect
78
82
  end
79
83
 
80
- # Build the schema document now (from Config.sdl_folder, unless given)
84
+ # Build the schema document now (from Config.schema_path, unless given)
81
85
  # and return the cache file's path.
82
86
  def warm!(sdl = nil)
83
- sdl ||= Lighthouse::GraphQL::SDLLoader.load_from_folder(Lighthouse::Config.sdl_folder.to_s)
87
+ sdl ||= Lighthouse::GraphQL::SchemaFactory.load_sdl
84
88
  Lighthouse::GraphQL::SchemaGenerator.build_document(sdl, force: true)
85
89
  File.join(directory.to_s, "#{PREFIX}#{key(sdl)}.bin")
86
90
  end
@@ -119,8 +123,8 @@ module Lighthouse::GraphQL::SchemaCache
119
123
  Lighthouse::Config.handle_error(e)
120
124
  end
121
125
 
122
- def source_digest(manipulator)
123
- file, = manipulator.method(:manipulate).source_location
126
+ def source_digest(manipulator, method_name = :manipulate)
127
+ file, = (manipulator.respond_to?(method_name) ? manipulator.method(method_name) : manipulator.instance_method(method_name)).source_location
124
128
  file && File.exist?(file) ? Digest::SHA256.file(file).hexdigest : nil
125
129
  rescue NameError
126
130
  nil
@@ -7,13 +7,13 @@
7
7
  module Lighthouse::GraphQL::SchemaFactory
8
8
  module_function
9
9
 
10
- def build_base_schema(sdl_folder: nil, sdl: nil, base_types: {}, schema_options: {}, **extra_options)
10
+ def build_base_schema(schema_path: nil, sdl: nil, base_types: {}, schema_options: {}, **extra_options)
11
11
  # Absorb any extra keyword options (e.g. `federation: true`) into the
12
12
  # schema options bag so callers can pass schema-level flags directly
13
13
  # without the factory needing to enumerate every one.
14
14
  schema_options = extra_options.merge(schema_options)
15
15
 
16
- sdl_string = sdl || load_sdl(sdl_folder)
16
+ sdl_string = sdl || load_sdl(schema_path)
17
17
  schema_class = schema_options.delete(:schema_class)
18
18
 
19
19
  Lighthouse::GraphQL::SchemaGenerator.build(
@@ -24,12 +24,9 @@ module Lighthouse::GraphQL::SchemaFactory
24
24
  )
25
25
  end
26
26
 
27
- # The SDL in `sdl_folder` (default: Config.sdl_folder), or the bundled
28
- # schema.graphql when there is no such folder.
29
- def load_sdl(sdl_folder)
30
- folder = sdl_folder || (Lighthouse::GraphQL::Config.sdl_folder if defined?(Lighthouse::GraphQL::Config))
31
- return Lighthouse::GraphQL::SDLLoader.load_from_folder(folder) if folder && Dir.exist?(folder)
32
-
33
- File.read(File.expand_path('../../schema.graphql', __dir__))
27
+ # The schema read from `schema_path` (default: Config.schema_path) and the
28
+ # files it imports.
29
+ def load_sdl(schema_path = nil)
30
+ Lighthouse::GraphQL::SchemaStitcher.new(schema_path || Lighthouse::Config.schema_path).schema_string
34
31
  end
35
32
  end
@@ -122,10 +122,11 @@ module Lighthouse::GraphQL::SchemaGenerator
122
122
  end
123
123
 
124
124
  # The SDL as the schema is built from it: directive definitions injected
125
- # (so apps don't hand-declare Lighthouse's directives), then every
126
- # registered manipulator run (pagination types, whereConditions inputs, ...).
125
+ # (so apps don't hand-declare Lighthouse's directives), then the
126
+ # manipulation phase (ASTBuilder: type extensions merged, pagination types,
127
+ # whereConditions / orderBy inputs, ...).
127
128
  def manipulate(sdl)
128
- augment_sdl_with_connections(inject_directive_definitions(sdl))
129
+ Lighthouse::GraphQL::ASTBuilder.build(inject_directive_definitions(sdl))
129
130
  end
130
131
 
131
132
  # `bases`: { root kind => the base class its fields' classes inherit from } (ResolverBases).
@@ -194,18 +195,6 @@ module Lighthouse::GraphQL::SchemaGenerator
194
195
  # ignore failures during post-processing
195
196
  end
196
197
 
197
- # Scan SDL string for list-typed fields that carry relationship directives
198
- # and produce Connection/Edge types where missing. This is a lightweight
199
- # transformation that mirrors Lighthouse behavior: clients can declare
200
- # `roles: [Role!]! @belongsToMany` and the builder will expose a
201
- # `RoleConnection` type and swap the field to return that connection.
202
- def augment_sdl_with_connections(sdl)
203
- # Drive SDL manipulation through the registry so each directive owns its
204
- # manipulation behavior and new manipulators can be added by registering
205
- # a class (no edits here).
206
- Lighthouse::DirectiveRegistry.default.manipulate_sdl(sdl)
207
- end
208
-
209
198
  # Prepend `directive @name(...) on ...` definitions for registered,
210
199
  # self-describing directives that the SDL uses but has not declared.
211
200
  # Already-declared directives are left untouched (no duplicates).
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Reads the schema from one entrypoint (Config.schema_path,
4
+ # graphql/schema.graphql by default) and pastes in the files it imports, as PHP
5
+ # Lighthouse's SchemaStitcher does:
6
+ #
7
+ # type Query
8
+ #
9
+ # #import user.graphql
10
+ # #import blog/*.graphql
11
+ #
12
+ # An import names a path relative to the file it is in, and may be a glob.
13
+ # Imported files are read the same way, so they can import others. A file is
14
+ # read once: importing it again, or importing a file that imports it back,
15
+ # adds nothing. Only the files reached from the entrypoint are in the schema.
16
+ class Lighthouse::GraphQL::SchemaStitcher
17
+ IMPORT = '#import '
18
+
19
+ attr_reader :root_schema_path
20
+
21
+ def initialize(root_schema_path)
22
+ path = File.expand_path(root_schema_path.to_s)
23
+ unless File.file?(path)
24
+ raise Lighthouse::DefinitionError,
25
+ "Failed to find a GraphQL schema file at #{path}. Set config.schema_path, or run bin/rails generate lighthouse:install."
26
+ end
27
+
28
+ @root_schema_path = File.realpath(path)
29
+ end
30
+
31
+ # The stitched schema: the entrypoint with every import replaced by the file's content.
32
+ def schema_string
33
+ gather(@root_schema_path, Set.new)
34
+ end
35
+
36
+ # Every file the schema is read from, the entrypoint first.
37
+ def files
38
+ visited = Set.new
39
+ gather(@root_schema_path, visited)
40
+ visited.to_a
41
+ end
42
+
43
+ private
44
+
45
+ def gather(path, visited)
46
+ return '' unless visited.add?(path)
47
+
48
+ File.readlines(path, chomp: true).map { |line| import_line?(line) ? import(path, line, visited) : "#{line}\n" }.join
49
+ end
50
+
51
+ def import_line?(line)
52
+ line.strip.start_with?(IMPORT)
53
+ end
54
+
55
+ def import(path, line, visited)
56
+ name = line.strip.delete_prefix(IMPORT).strip
57
+ import_path = File.join(File.dirname(path), name)
58
+ return Dir.glob(import_path).map { |file| gather(File.realpath(file), visited) }.join if name.include?('*')
59
+
60
+ raise Lighthouse::DefinitionError, "Did not find GraphQL schema import at #{import_path}." unless File.file?(import_path)
61
+
62
+ gather(File.realpath(import_path), visited)
63
+ end
64
+ end
@@ -52,16 +52,4 @@ module Lighthouse::Support::Naming
52
52
  snake = raw.underscore
53
53
  [raw.to_sym, raw, snake.to_sym, snake].uniq
54
54
  end
55
-
56
- # Derive an Eloquent-style relation name from a `has<Relation>` argument
57
- # name, e.g. "hasContact" -> "contacts". Returns nil when the argument does
58
- # not follow the `has` convention.
59
- def derive_relation_name(arg_name)
60
- return nil unless arg_name.to_s.match?(/^has/i)
61
-
62
- trailing = arg_name.to_s.sub(/^has/i, '')
63
- return nil if trailing.empty?
64
-
65
- trailing.underscore.pluralize
66
- end
67
55
  end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The column a client names in @whereConditions or @orderBy, as an Arel node.
4
+ # Enum values (`CREATED_AT`, or the column an @enum(value:) gives) map onto
5
+ # columns as everywhere (Support::Naming). A column of an unrestricted input
6
+ # (`column: String`) comes from the client as is, so it must be an identifier,
7
+ # `table.column`, or either with a path into a JSON document (`meta->tags`,
8
+ # JsonColumn), as PHP Lighthouse checks it.
9
+ module Lighthouse::WhereConditions::Columns
10
+ IDENTIFIER = /\A[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?\z/
11
+
12
+ module_function
13
+
14
+ # The column on `klass`'s table, or `table.column`. A JSON path's value is
15
+ # compiled `as` JsonColumn.node says: :sort to order by, :text, :numeric or
16
+ # :boolean to compare with.
17
+ def attribute(klass, column, as: :sort)
18
+ json = Lighthouse::WhereConditions::JsonColumn
19
+ if json.json?(column)
20
+ raise ::GraphQL::ExecutionError, invalid_column_name(column) unless json.valid?(column)
21
+
22
+ return json.node(klass, column, as: as)
23
+ end
24
+
25
+ name = Lighthouse::Support::Naming.column(column)
26
+ raise ::GraphQL::ExecutionError, invalid_column_name(column) unless IDENTIFIER.match?(name)
27
+
28
+ table, name = name.split('.', 2) if name.include?('.')
29
+ table ? ::Arel::Table.new(table)[name] : klass.arel_table[name]
30
+ end
31
+
32
+ def invalid_column_name(column)
33
+ 'Column names may contain only alphanumerics or underscores, optionally a table and a JSON path ' \
34
+ "(posts.meta->tags), and may not begin with a digit, got: #{column}"
35
+ end
36
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Applies a @whereConditions value to a relation, as PHP Lighthouse's
4
+ # WhereConditionsHandler: the conditions of one level all hold, an AND list is
5
+ # a nested group whose conditions all hold, an OR list one where at least one
6
+ # does, and HAS checks how many related records match a condition.
7
+ #
8
+ # { column: AGE, operator: GT, value: 37, OR: [{ column: TYPE, value: "Actor" }, ...] }
9
+ # -> age > 37 AND (type = 'Actor' OR ...)
10
+ #
11
+ # { HAS: { relation: "posts", amount: 3, condition: { column: "published", value: true } } }
12
+ # -> users with at least 3 published posts
13
+ #
14
+ # A column the client names (an unrestricted WhereConditions takes any) must
15
+ # be an identifier, `table.column` at most (Columns). The columns of a HAS
16
+ # condition are those of the related model's table.
17
+ #
18
+ # A custom handler (`@whereConditions(handler: "...")`) is any object or
19
+ # class answering `call(relation, conditions)` with the relation.
20
+ module Lighthouse::WhereConditions::Handler
21
+ Types = Lighthouse::WhereConditions::Types
22
+
23
+ # How a HAS operator compares the number of related records with `amount`.
24
+ COUNT_COMPARISONS = { 'EQ' => :eq, 'NEQ' => :not_eq, 'GT' => :gt, 'GTE' => :gteq, 'LT' => :lt, 'LTE' => :lteq }.freeze
25
+ RUBY_COMPARISONS = { 'EQ' => :==, 'NEQ' => :!=, 'GT' => :>, 'GTE' => :>=, 'LT' => :<, 'LTE' => :<= }.freeze
26
+
27
+ # The Arel predicate of each operator that takes a value: [method, how the value is passed].
28
+ PREDICATES = {
29
+ 'LIKE' => [:matches, :pattern], 'NOT_LIKE' => [:does_not_match, :pattern],
30
+ 'IN' => [:in, :list], 'NOT_IN' => [:not_in, :list],
31
+ 'BETWEEN' => [:between, :range], 'NOT_BETWEEN' => [:not_between, :range]
32
+ }.merge(COUNT_COMPARISONS.transform_values { |method| [method, :value] }).freeze
33
+
34
+ module_function
35
+
36
+ def call(relation, conditions)
37
+ predicate = predicate(relation.klass, normalize(conditions))
38
+ predicate ? relation.where(predicate) : relation
39
+ end
40
+
41
+ # The conditions as a Hash of :column, :operator, :value, :and, :or, :has
42
+ # (and :relation, :amount, :condition in a HAS), leaving the value as given.
43
+ def normalize(conditions)
44
+ return nil if conditions.nil?
45
+
46
+ hash = conditions.respond_to?(:to_h) ? conditions.to_h : conditions
47
+ hash.each_with_object({}) do |(key, value), normalized|
48
+ key = key.to_s.underscore.to_sym
49
+ normalized[key] =
50
+ case key
51
+ when :and, :or then Array(value).map { |condition| normalize(condition) }
52
+ when :has, :condition then normalize(value)
53
+ else value
54
+ end
55
+ end
56
+ end
57
+
58
+ # The Arel predicate of one level of conditions, or nil when it has none.
59
+ def predicate(klass, conditions)
60
+ return nil if conditions.blank?
61
+
62
+ nodes = [
63
+ group(klass, conditions[:and], :and),
64
+ group(klass, conditions[:or], :or),
65
+ conditions[:has] && has(klass, conditions[:has]),
66
+ conditions[:column] && column_condition(klass, conditions)
67
+ ].compact
68
+ nodes.empty? ? nil : nodes.reduce { |left, right| left.and(right) }
69
+ end
70
+
71
+ def group(klass, conditions, boolean)
72
+ nodes = Array(conditions).filter_map { |condition| predicate(klass, condition) }
73
+ return nil if nodes.empty?
74
+
75
+ boolean == :and ? ::Arel::Nodes::Grouping.new(::Arel::Nodes::And.new(nodes)) : nodes.reduce { |left, right| left.or(right) }
76
+ end
77
+
78
+ def column_condition(klass, conditions)
79
+ operator = (conditions[:operator] || Types::DEFAULT_OPERATOR).to_s.upcase
80
+ compared_as = Lighthouse::WhereConditions::JsonColumn.compared_as(operator, conditions[:value])
81
+ attribute = Lighthouse::WhereConditions::Columns.attribute(klass, conditions[:column], as: compared_as)
82
+ return attribute.eq(nil) if operator == 'IS_NULL'
83
+ return attribute.not_eq(nil) if operator == 'IS_NOT_NULL'
84
+
85
+ unless conditions.key?(:value)
86
+ raise ::GraphQL::ExecutionError, "Did not receive a value to match the WhereConditions for column #{conditions[:column]}."
87
+ end
88
+
89
+ compare(attribute, operator, conditions[:value])
90
+ end
91
+
92
+ def compare(attribute, operator, value)
93
+ method, kind = PREDICATES[operator]
94
+ raise ::GraphQL::ExecutionError, "Unknown SQLOperator #{operator}." unless method
95
+
96
+ case kind
97
+ when :pattern then attribute.public_send(method, value, nil, true) # LIKE, case-sensitive as SQL's
98
+ when :list then attribute.public_send(method, Array(value))
99
+ when :range then attribute.public_send(method, range(value))
100
+ else attribute.public_send(method, value)
101
+ end
102
+ end
103
+
104
+ def range(value)
105
+ values = Array(value)
106
+ raise ::GraphQL::ExecutionError, 'BETWEEN needs a value of two elements: [from, to].' unless values.size == 2
107
+
108
+ values.first..values.last
109
+ end
110
+
111
+ # Records of `klass` with `amount` (compared by `operator`) related records
112
+ # matching the condition: an IN over the records that have them, and, when
113
+ # having none satisfies the comparison, the records that have none too.
114
+ def has(klass, has)
115
+ reflection = reflection(klass, has[:relation])
116
+ operator = (has[:operator] || Types::DEFAULT_HAS_OPERATOR).to_s.upcase
117
+ amount = (has[:amount] || Types::DEFAULT_HAS_AMOUNT).to_i
118
+ raise ::GraphQL::ExecutionError, "HAS can not compare the amount with #{operator}." unless COUNT_COMPARISONS.key?(operator)
119
+
120
+ key = klass.arel_table[klass.primary_key]
121
+ related = related_scope(klass, reflection, has[:condition])
122
+ predicate = key.in(owners(related, key, reflection.klass, operator, amount).arel)
123
+ 0.public_send(RUBY_COMPARISONS.fetch(operator), amount) ? predicate.or(key.not_in(related.select(key).arel)) : predicate
124
+ end
125
+
126
+ # `klass` joined to its related records that match the condition.
127
+ def related_scope(klass, reflection, condition)
128
+ scope = klass.unscoped.joins(reflection.name)
129
+ predicate = predicate(reflection.klass, condition)
130
+ predicate ? scope.where(predicate) : scope
131
+ end
132
+
133
+ # The keys of the records with `amount` related records, by `operator`. At
134
+ # least one is any join; another amount needs them counted.
135
+ def owners(related_scope, key, related, operator, amount)
136
+ return related_scope.select(key) if (operator == 'GTE' && amount == 1) || (operator == 'GT' && amount.zero?)
137
+
138
+ counted = related.primary_key ? related.arel_table[related.primary_key] : ::Arel.star
139
+ count = ::Arel::Nodes::Count.new([counted], true)
140
+ related_scope.group(key).having(count.public_send(COUNT_COMPARISONS.fetch(operator), amount)).select(key)
141
+ end
142
+
143
+ # The association `name` names on `klass`: as written, snake_cased, singular or plural.
144
+ def reflection(klass, name)
145
+ candidates = [name.to_s, name.to_s.underscore, name.to_s.underscore.singularize, name.to_s.underscore.pluralize].uniq
146
+ reflection = candidates.lazy.filter_map { |candidate| klass.reflect_on_association(candidate.to_sym) }.first
147
+ raise ::GraphQL::ExecutionError, "#{klass.name} has no relation #{name}." unless reflection
148
+ raise ::GraphQL::ExecutionError, "HAS can not check the polymorphic relation #{name}." if reflection.polymorphic?
149
+
150
+ reflection
151
+ end
152
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A column with a path into its JSON document, as Laravel names one and PHP
4
+ # Lighthouse's @whereConditions and @orderBy take it: `meta->tags`,
5
+ # `posts.meta->author->name`, `meta->tags->0` (an array index). The value at
6
+ # the path is compiled for the database, as Laravel's query grammars do:
7
+ #
8
+ # PostgreSQL "posts"."meta"->'author'->>'name'
9
+ # MySQL JSON_UNQUOTE(JSON_EXTRACT(`posts`.`meta`, '$."author"."name"'))
10
+ # SQLite json_extract("posts"."meta", '$."author"."name"')
11
+ #
12
+ # Unlike Laravel, it compares numbers and booleans as such, and orders by the
13
+ # JSON value (numbers numerically), on every database. The result is an Arel
14
+ # node: a condition calls its predicates (`eq`, `in`, `matches`, ...) and an
15
+ # order its `asc` / `desc`.
16
+ module Lighthouse::WhereConditions::JsonColumn
17
+ PATH = /\A(?:(?<table>[A-Za-z_]\w*)\.)?(?<column>[A-Za-z_]\w*)(?<path>(?:->[A-Za-z0-9_-]+)+)\z/
18
+
19
+ module_function
20
+
21
+ def json?(name)
22
+ name.to_s.include?('->')
23
+ end
24
+
25
+ def valid?(name)
26
+ PATH.match?(name.to_s)
27
+ end
28
+
29
+ # The value at the path, as `as` says: :text, :numeric, :boolean, :null (NULL
30
+ # when the path is missing or holds JSON null), or :sort (the JSON value,
31
+ # ordered by type, numbers numerically).
32
+ def node(klass, name, as: :text)
33
+ match = PATH.match(name.to_s) or raise ArgumentError, "not a JSON column: #{name}"
34
+ connection = klass.connection
35
+ target = [match[:table] || klass.table_name, match[:column]].then do |table, column|
36
+ "#{connection.quote_table_name(table)}.#{connection.quote_column_name(column)}"
37
+ end
38
+ segments = match[:path].split('->').drop(1)
39
+
40
+ ::Arel.sql(public_send(dialect(connection), target, segments, as))
41
+ end
42
+
43
+ # How a condition with `operator` compares the value at the path: patterns as
44
+ # text, nulls as JSON null too, the rest as the value is.
45
+ def compared_as(operator, value)
46
+ case operator
47
+ when 'LIKE', 'NOT_LIKE' then :text
48
+ when 'IS_NULL', 'IS_NOT_NULL' then :null
49
+ else kind_of_value(value)
50
+ end
51
+ end
52
+
53
+ # What a value compares as: numbers as numbers, booleans as booleans, the rest as text.
54
+ def kind_of_value(value)
55
+ sample = value.is_a?(Array) ? value.first : value
56
+ case sample
57
+ when Numeric then :numeric
58
+ when true, false then :boolean
59
+ else :text
60
+ end
61
+ end
62
+
63
+ def dialect(connection)
64
+ case connection.adapter_name
65
+ when /postg/i then :postgresql
66
+ when /mysql|trilogy/i then :mysql
67
+ else :sqlite
68
+ end
69
+ end
70
+
71
+ def postgresql(target, segments, as)
72
+ keys = segments.map { |segment| segment.match?(/\A\d+\z/) ? segment : "'#{segment}'" }
73
+ return "(#{target}->#{keys.join('->')})::jsonb" if as == :sort
74
+
75
+ text = keys.size == 1 ? "#{target}->>#{keys.first}" : "#{target}->#{keys[0...-1].join('->')}->>#{keys.last}"
76
+ { numeric: "(#{text})::numeric", boolean: "(#{text})::boolean" }.fetch(as, text) # :text, :null
77
+ end
78
+
79
+ def mysql(target, segments, as)
80
+ extract = "JSON_EXTRACT(#{target}, '#{json_path(segments)}')"
81
+ case as
82
+ when :text then "JSON_UNQUOTE(#{extract})"
83
+ when :numeric then "CAST(JSON_UNQUOTE(#{extract}) AS DECIMAL(65, 10))"
84
+ when :boolean then "(#{extract} = CAST('true' AS JSON))"
85
+ when :null then "NULLIF(JSON_TYPE(#{extract}), 'NULL')"
86
+ else extract
87
+ end
88
+ end
89
+
90
+ # json_extract answers SQLite's own types: numbers compare and order as numbers,
91
+ # booleans are 1 and 0.
92
+ def sqlite(target, segments, _as)
93
+ "json_extract(#{target}, '#{json_path(segments)}')"
94
+ end
95
+
96
+ def json_path(segments)
97
+ "$#{segments.map { |segment| segment.match?(/\A\d+\z/) ? "[#{segment}]" : %(."#{segment}") }.join}"
98
+ end
99
+ end
@@ -1,9 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Maps the GraphQL SQLOperator enum values to Arel predicate methods.
4
- # Extracted from WhereConditionsApplier so that simple argument-filter
5
- # directives (@eq, @neq, @in, @notIn, @like, @where) can share the same
6
- # operator semantics.
3
+ # Maps the operators @where(operator:) takes to Arel predicate methods.
7
4
  module Lighthouse::WhereConditions::OperatorMap
8
5
  OPERATORS = {
9
6
  'EQ' => :eq,