graph_query 0.2.0

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.
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQuery
4
+ # One kind of edge between two node models, read from a table: each row whose source and target columns are both
5
+ # set is one edge from the source node to the target node.
6
+ #
7
+ # Edges come from an association (belongs_to, has_many/has_one, or has_many :through a join model), from a join
8
+ # model named outright, or from SQL that selects source_id and target_id. Node and model names are kept as strings
9
+ # and looked up when a query runs, so code reloading never leaves a stale class behind.
10
+ class Edge
11
+ attr_reader :name, :from, :to, :table_model, :source_column, :target_column, :conditions, :sql, :declared_by
12
+
13
+ # name: the edge's name (a Symbol). from/to: node model names. table_model: the model whose table holds the
14
+ # rows. conditions: [scope Proc or Hash, ...] applied to that table. sql: instead of a table, SQL selecting
15
+ # source_id and target_id, or a callable returning that SQL or a relation (a computed edge, built per query).
16
+ def initialize(name:, from:, to:, declared_by:, table_model: nil, source_column: nil, target_column: nil,
17
+ conditions: [], sql: nil)
18
+ @name = name.to_sym
19
+ @from = from.to_s
20
+ @to = to.to_s
21
+ @declared_by = declared_by.to_s
22
+ @table_model = table_model&.to_s
23
+ @source_column = source_column&.to_s
24
+ @target_column = target_column&.to_s
25
+ @conditions = conditions.compact
26
+ @sql = sql
27
+ return if @sql || (@table_model && @source_column && @target_column)
28
+
29
+ raise ArgumentError,
30
+ "edge #{name} needs a table or SQL"
31
+ end
32
+
33
+ # What makes two declarations the same edge, so that reloading a model replaces its edges instead of adding more.
34
+ def key = [declared_by, name, from, to, table_model, source_column, target_column, sql]
35
+
36
+ # SQL for these edges walked in a direction, as rows (from_type, from_id, to_type, to_id): out goes source to
37
+ # target, in goes target to source. edge_where filters the edge table's rows (not for SQL edges). With bound:,
38
+ # only edges leaving the current row of that alias (node_type, node_id), for a LATERAL join that can use the
39
+ # edge table's indexes.
40
+ def rows_sql(direction, edge_where: nil, bound: nil)
41
+ tail, head = direction == :in ? [to, from] : [from, to]
42
+ tail_id, head_id = direction == :in ? %w[target_id source_id] : %w[source_id target_id]
43
+ conn = ActiveRecord::Base.connection
44
+ <<~SQL.squish
45
+ SELECT #{conn.quote(tail)}::text AS from_type, edge_rows.#{tail_id} AS from_id,
46
+ #{conn.quote(head)}::text AS to_type, edge_rows.#{head_id} AS to_id
47
+ FROM (#{source_sql(edge_where)}) edge_rows
48
+ #{"WHERE edge_rows.#{tail_id} = #{bound}.node_id AND #{bound}.node_type = #{conn.quote(tail)}" if bound}
49
+ SQL
50
+ end
51
+
52
+ def model = table_model&.constantize
53
+
54
+ # Whether rows of this edge can meet an edge filter. Like a missing property in Cypher, an edge kept somewhere
55
+ # without the filter's columns never matches it; SQL edges match no filter.
56
+ def filterable_by?(edge_where)
57
+ return true if edge_where.blank?
58
+ return false if sql
59
+ return true unless edge_where.is_a?(Hash)
60
+
61
+ edge_where.keys.all? do |key|
62
+ key.is_a?(Hash) || model.column_names.include?(key.to_s) || model.reflect_on_association(key)
63
+ end
64
+ end
65
+
66
+ def inspect = "#<GraphQuery::Edge #{from} -[:#{name}]-> #{to}>"
67
+
68
+ private
69
+
70
+ def source_sql(edge_where)
71
+ if sql
72
+ raise ArgumentError, "edge #{inspect} is SQL, so it can't take edge filters" if edge_where.present?
73
+
74
+ return computed_sql
75
+ end
76
+
77
+ relation = model.unscoped
78
+ table = model.arel_table
79
+ relation = relation.where.not(table[source_column].eq(nil)).where.not(table[target_column].eq(nil))
80
+ conditions.each { relation = apply(relation, it) }
81
+ relation = apply(relation, edge_where) if edge_where.present?
82
+ relation.unscope(:order, :limit, :offset, :select)
83
+ .select(table[source_column].as('source_id'), table[target_column].as('target_id'))
84
+ .to_sql
85
+ end
86
+
87
+ # A computed edge's SQL, from its callable (run each time a query is built): a relation or a String selecting
88
+ # source_id and target_id.
89
+ def computed_sql
90
+ return sql unless sql.respond_to?(:call)
91
+
92
+ result = sql.call
93
+ result = result.to_sql if result.respond_to?(:to_sql)
94
+ unless result.is_a?(String)
95
+ raise ArgumentError,
96
+ "computed edge #{inspect} must return a relation or SQL, not #{result.class}"
97
+ end
98
+
99
+ result
100
+ end
101
+
102
+ def apply(relation, condition)
103
+ case condition
104
+ when Hash, String, Array then relation.where(condition)
105
+ when ActiveRecord::Relation then relation.merge(condition)
106
+ when Proc
107
+ if condition.arity.positive?
108
+ raise ArgumentError,
109
+ "edge #{inspect}: scopes that take the owner record can't be walked"
110
+ end
111
+
112
+ relation.instance_exec(&condition) || relation
113
+ else raise ArgumentError, "edge #{inspect}: unknown condition #{condition.inspect}"
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,329 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'graphql'
4
+ require 'graph_query'
5
+
6
+ module GraphQuery
7
+ # graphql-ruby support, loaded with require 'graph_query/graphql'.
8
+ #
9
+ # Fields backed by walks, batched through GraphQL::Dataloader so a list of 50 locales asking for their venues runs
10
+ # one statement, not 50:
11
+ #
12
+ # class Types::LocaleType < Types::BaseObject
13
+ # extend GraphQuery::GraphQL::Fields
14
+ #
15
+ # graph_field :children, [Types::LocaleType], edge: :contains # one hop
16
+ # graph_field :venues, [Types::VenueType], edge: [:contains, :has_venue], depth: 0.. # see below
17
+ # graph_field :bars, Types::VenueType.connection_type, # paginated
18
+ # pattern: '()-[:contains*0..]->()-[:has_venue]->(v:Venue)',
19
+ # scope: ->(venues, context) { venues.where(kind: 'bar').order(:name) }
20
+ # graph_edges Locale # a field for every edge Locale declares
21
+ # end
22
+ #
23
+ # And mutations that run in one transaction, with a GraphQuery::Transaction to write edges through:
24
+ #
25
+ # class Mutations::MoveVenue < Types::BaseMutation
26
+ # include GraphQuery::GraphQL::TransactionalMutation
27
+ # argument :venue_id, ID; argument :locale_id, ID
28
+ # field :venue, Types::VenueType
29
+ #
30
+ # def resolve(venue_id:, locale_id:)
31
+ # venue = Venue.find(venue_id)
32
+ # graph.relink(Locale.find(locale_id), :has_venue, venue, from: venue.locale)
33
+ # { venue: venue.reload }
34
+ # end
35
+ # end
36
+ #
37
+ # GraphQuery::GraphQL.edge_mutation(Locale, :contains, Locale, graphql_name: 'AddSubLocale') # link/unlink by ID
38
+ module GraphQL
39
+ class << self
40
+ # Finds the GraphQL type for a model name ('Venue' -> Types::VenueType, else Types::Venue). Set your own.
41
+ attr_writer :type_for
42
+
43
+ # Defaults to the name "Types::<Model>Type", which graphql-ruby resolves lazily, so a type can name itself
44
+ # (or a type not loaded yet) while its class body is still running. Return a type or a type name.
45
+ def type_for = @type_for ||= ->(name) { "Types::#{name}Type" }
46
+
47
+ # Turns a GraphQL ID into a record. Defaults to the schema's object_from_id, else Model.find.
48
+ attr_writer :record_for
49
+
50
+ def record_for
51
+ @record_for ||= lambda do |model, id, context|
52
+ schema = context&.schema
53
+ found = schema.object_from_id(id, context) if schema.respond_to?(:object_from_id)
54
+ found.is_a?(model) ? found : model.find(id)
55
+ rescue ::GraphQL::RequiredImplementationMissingError, NotImplementedError
56
+ model.find(id)
57
+ end
58
+ end
59
+
60
+ # A mutation class that links (or unlinks) the edge name from a from_model record to a to_model record by ID.
61
+ def edge_mutation(from_model, name, to_model, action: :link, via: nil, name_prefix: nil,
62
+ base: ::GraphQL::Schema::RelayClassicMutation, graphql_name: nil)
63
+ graphql_name ||= "#{name_prefix}#{action.to_s.camelize}#{from_model.name}#{name.to_s.camelize}#{to_model.name}"
64
+ EdgeMutation.build(from_model, name, to_model, action:, via:, base:, graphql_name:)
65
+ end
66
+ end
67
+
68
+ # A field's walk: which nodes it reaches from its object.
69
+ class Walk
70
+ attr_reader :model_name
71
+
72
+ def initialize(edge: nil, pattern: nil, traverse: {}, model: nil, &block)
73
+ unless [edge, pattern, block].compact.one?
74
+ raise ArgumentError, 'graph_field takes one of edge:, pattern: or a block'
75
+ end
76
+
77
+ @edge = edge
78
+ @pattern = pattern
79
+ @traverse = traverse
80
+ @block = block
81
+ @model_name = model && GraphQuery.type_name(model)
82
+ end
83
+
84
+ # The Query from start (a relation of the field's objects).
85
+ def call(start)
86
+ if @block then @block.call(GraphQuery.from(start))
87
+ elsif @pattern then GraphQuery.match(@pattern, __start: start).query
88
+ else
89
+ Array(@edge).each_with_index.reduce(GraphQuery.from(start)) do |query, (name, i)|
90
+ # depth: and the other options apply to every step but the last, which takes one hop (has_venue after
91
+ # contains*0..), unless the field names one edge.
92
+ options = i == Array(@edge).size - 1 && Array(@edge).size > 1 ? @traverse.except(:depth) : @traverse
93
+ query.traverse(name, **options)
94
+ end
95
+ end
96
+ end
97
+
98
+ def model_for(start) = (model_name || call(start).types.then { only(it) }).constantize
99
+
100
+ private
101
+
102
+ def only(types)
103
+ return types.first if types.one?
104
+
105
+ raise AmbiguousResult, "this field reaches #{types.join(', ')}: give graph_field model:"
106
+ end
107
+ end
108
+
109
+ # Loads every object's nodes for one field in one query.
110
+ class Source < ::GraphQL::Dataloader::Source
111
+ def initialize(walk, scope, context)
112
+ super()
113
+ @walk = walk
114
+ @scope = scope
115
+ @context = context
116
+ end
117
+
118
+ def fetch(records)
119
+ found = records.group_by(&:class).each_with_object({}) do |(model, group), by_record|
120
+ start = model.where(model.primary_key => group.map(&:id))
121
+ target = @walk.model_for(start)
122
+ pairs = @walk.call(start).origin_pairs(target)
123
+ nodes = target.where(target.primary_key => pairs.map(&:last).uniq)
124
+ nodes = @scope.call(nodes, @context) if @scope
125
+ nodes = nodes.to_a
126
+ by_origin = pairs.group_by(&:first).transform_values { |list| list.to_set(&:last) }
127
+ group.each do |record|
128
+ reached = by_origin.fetch(record.id, Set.new)
129
+ by_record[record] = nodes.select { reached.include?(it.id) }
130
+ end
131
+ end
132
+ records.map { found.fetch(it) }
133
+ end
134
+ end
135
+
136
+ # Class methods for GraphQL object types: extend GraphQuery::GraphQL::Fields.
137
+ module Fields
138
+ TRAVERSE = %i[depth direction to through edge_where].freeze
139
+
140
+ # A field whose value is the nodes a walk reaches from the object: edge: (a name, or several in a row),
141
+ # pattern: (Cypher-style, the first node being the object) or a block given the start Query. depth:,
142
+ # direction:, to:, through: and edge_where: go to the walk. scope: (relation, context) -> relation narrows,
143
+ # orders or authorizes the nodes. model: names the model when the walk can reach several. A connection type
144
+ # gives a paginated relation per object; a list type is batched for every object on the page.
145
+ def graph_field(name, type, *, edge: nil, pattern: nil, scope: nil, model: nil, **options, &)
146
+ walk = Walk.new(edge:, pattern:, traverse: options.slice(*TRAVERSE), model:, &)
147
+ connection = type.is_a?(Class) && type < ::GraphQL::Types::Relay::BaseConnection
148
+ field(name, type, *, null: false, **options.except(*TRAVERSE))
149
+ define_method(name) do
150
+ if connection
151
+ start = object.class.where(object.class.primary_key => object.id)
152
+ nodes = walk.call(start).to_relation(walk.model_for(start))
153
+ scope ? scope.call(nodes, context) : nodes
154
+ else
155
+ dataloader.with(Source, walk, scope, context).load(object)
156
+ end
157
+ end
158
+ end
159
+
160
+ # A list field for every edge model declares (one hop out): named after the edge, or edge_model when the edge
161
+ # reaches several models. only:/except: pick edges by name; type_for: maps a model name to its GraphQL type.
162
+ def graph_edges(model, only: nil, except: [], type_for: GraphQuery::GraphQL.type_for, scope: nil)
163
+ edges = GraphQuery.registry.walkable([model.polymorphic_name], nil, :out).map(&:first)
164
+ edges.group_by(&:name).each do |name, list|
165
+ next if (only && !Array(only).include?(name)) || Array(except).include?(name)
166
+
167
+ targets = list.map(&:to).uniq
168
+ targets.each do |target|
169
+ field_name = targets.one? ? name : :"#{name}_#{target.underscore.tr('/', '_').pluralize}"
170
+ description = "#{target} nodes this #{model.name} #{name.to_s.humanize(capitalize: false)}."
171
+ graph_field(field_name, [type_for.call(target)], edge: name, to: target, model: target, scope:,
172
+ description:)
173
+ end
174
+ end
175
+ end
176
+ end
177
+
178
+ # Runs a mutation's resolve in one database transaction and gives it graph, a GraphQuery::Transaction. Raising
179
+ # rolls everything back; a validation failure or GraphQuery error becomes a GraphQL error (or, when the mutation
180
+ # has an errors field, { errors: [...] }).
181
+ module TransactionalMutation
182
+ def graph = @graph || raise(Error, 'graph is only open during resolve')
183
+
184
+ def resolve_with_support(**)
185
+ result = nil
186
+ GraphQuery.transaction do |graph|
187
+ @graph = graph
188
+ result = super
189
+ raise ActiveRecord::Rollback if result.is_a?(Hash) && result[:errors].present?
190
+ end
191
+ result
192
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotDestroyed, GraphQuery::Error => e
193
+ raise ::GraphQL::ExecutionError, e.message unless self.class.fields.key?('errors')
194
+
195
+ { errors: [e.message] }
196
+ ensure
197
+ @graph = nil
198
+ end
199
+ end
200
+
201
+ # Class methods for the schema's mutation type: extend GraphQuery::GraphQL::MutationFields, then
202
+ # graph_mutations Locale, Venue adds a field for each graph mutation those models declare (locale_adopt, ...).
203
+ module MutationFields
204
+ def graph_mutations(*models, only: nil, except: [], base: ::GraphQL::Schema::RelayClassicMutation)
205
+ models.each do |model|
206
+ model.graph_mutations.each_value do |mutation|
207
+ next if (only && !Array(only).include?(mutation.name)) || Array(except).include?(mutation.name)
208
+
209
+ klass = ModelMutation.build(mutation, base:)
210
+ field(:"#{model.model_name.singular}_#{mutation.name}", mutation: klass)
211
+ end
212
+ end
213
+ end
214
+ end
215
+
216
+ # Builds a GraphQL mutation for a model's graph mutation: id (the record it runs on) and the method's arguments in;
217
+ # result (what it returns) and errors out.
218
+ module ModelMutation
219
+ SCALARS = {
220
+ String => ::GraphQL::Types::String, Integer => ::GraphQL::Types::Int, Float => ::GraphQL::Types::Float,
221
+ boolean: ::GraphQL::Types::Boolean, TrueClass => ::GraphQL::Types::Boolean, id: ::GraphQL::Types::ID,
222
+ json: ::GraphQL::Types::JSON, Date => ::GraphQL::Types::ISO8601Date,
223
+ Time => ::GraphQL::Types::ISO8601DateTime, DateTime => ::GraphQL::Types::ISO8601DateTime
224
+ }.freeze
225
+
226
+ module_function
227
+
228
+ def build(mutation, base:)
229
+ model = mutation.model
230
+ type_for = GraphQuery::GraphQL.type_for
231
+ loaders = {}
232
+ result_type = result_type(mutation, type_for)
233
+ Class.new(base) do
234
+ include TransactionalMutation
235
+
236
+ graphql_name("#{model.name.gsub('::', '')}#{mutation.name.to_s.camelize}")
237
+ description(mutation.description) if mutation.description
238
+ argument :id, ::GraphQL::Types::ID, required: true, description: "The #{model.name} to run on."
239
+ mutation.keywords.each do |key|
240
+ spec = mutation.arguments.fetch(key) do
241
+ raise ArgumentError, "#{mutation.inspect}: give #{key} a type in arguments:"
242
+ end
243
+ graphql_name, graphql_type, loader = ModelMutation.argument(key, spec)
244
+ loaders[graphql_name] = [key, loader]
245
+ argument graphql_name, graphql_type, required: mutation.required.include?(key)
246
+ end
247
+ field :result, result_type, null: true
248
+ field :errors, [::GraphQL::Types::String], null: false
249
+
250
+ define_method(:resolve) do |id:, **inputs|
251
+ record = GraphQuery::GraphQL.record_for.call(model, id, context)
252
+ keywords = inputs.to_h do |graphql_name, value|
253
+ key, loader = loaders.fetch(graphql_name)
254
+ [key, loader ? loader.call(value, context) : value]
255
+ end
256
+ keywords[:graph] = graph if mutation.takes_graph?
257
+ # Already inside this mutation's transaction: the method's own wrapper opens a savepoint in it.
258
+ { result: mutation.call(record, **keywords), errors: [] }
259
+ end
260
+ end
261
+ end
262
+
263
+ # [GraphQL argument name, type, loader or nil] for one keyword.
264
+ def argument(key, spec)
265
+ list = spec.is_a?(Array)
266
+ inner = list ? spec.first : spec
267
+ inner = inner.constantize if inner.is_a?(String)
268
+ return model_argument(key, inner, list) if inner.is_a?(Class) && inner < ActiveRecord::Base
269
+
270
+ type = SCALARS.fetch(inner) { inner.is_a?(Class) && inner < ::GraphQL::Schema::Member ? inner : nil }
271
+ raise ArgumentError, "can't map #{inner.inspect} to a GraphQL type for #{key}" unless type
272
+
273
+ [key, list ? [type] : type, nil]
274
+ end
275
+
276
+ # A model keyword takes IDs (child: becomes childId, venues: becomes venueIds) loaded through record_for.
277
+ def model_argument(key, model, list)
278
+ name = list ? :"#{key.to_s.singularize}_ids" : :"#{key}_id"
279
+ loader = lambda do |value, context|
280
+ load = ->(id) { GraphQuery::GraphQL.record_for.call(model, id, context) }
281
+ list ? value.map(&load) : load.call(value)
282
+ end
283
+ [name, list ? [::GraphQL::Types::ID] : ::GraphQL::Types::ID, loader]
284
+ end
285
+
286
+ def result_type(mutation, type_for)
287
+ returns = mutation.returns || mutation.model
288
+ returns = returns.constantize if returns.is_a?(String)
289
+ return SCALARS.fetch(returns) if SCALARS.key?(returns)
290
+ return returns if returns.is_a?(Class) && returns < ::GraphQL::Schema::Member
291
+
292
+ type_for.call(GraphQuery.type_name(returns))
293
+ end
294
+ end
295
+
296
+ # Builds link/unlink mutations for one edge (GraphQuery::GraphQL.edge_mutation).
297
+ module EdgeMutation
298
+ module_function
299
+
300
+ def build(from_model, name, to_model, action:, via:, base:, graphql_name:)
301
+ raise ArgumentError, "action must be :link or :unlink, not #{action.inspect}" unless %i[link
302
+ unlink].include?(action)
303
+
304
+ type_for = GraphQuery::GraphQL.type_for
305
+ Class.new(base) do
306
+ include TransactionalMutation
307
+
308
+ graphql_name(graphql_name)
309
+ description("#{action.to_s.capitalize}s the #{name} edge from a #{from_model.name} to a #{to_model.name}.")
310
+ argument :from_id, ::GraphQL::Types::ID, required: true
311
+ argument :to_id, ::GraphQL::Types::ID, required: true
312
+ field :from, type_for.call(from_model.name), null: true
313
+ field :to, type_for.call(to_model.name), null: true
314
+ field :changed, ::GraphQL::Types::Boolean, null: false
315
+ field :errors, [::GraphQL::Types::String], null: false
316
+
317
+ define_method(:resolve) do |from_id:, to_id:|
318
+ record_for = GraphQuery::GraphQL.record_for
319
+ from = record_for.call(from_model, from_id, context)
320
+ to = record_for.call(to_model, to_id, context)
321
+ before = graph.changes.size
322
+ graph.public_send(action, from, name, to, via:)
323
+ { from:, to:, changed: graph.changes.size > before, errors: [] }
324
+ end
325
+ end
326
+ end
327
+ end
328
+ end
329
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQuery
4
+ # A Pattern with its variables bound, run as Queries. #nodes gives the last node's matches (or any variable's:
5
+ # nodes(:v)); a variable in the middle of the pattern gives only nodes that lie on a full match, found by walking
6
+ # back from the end. Relation methods go to the last node's relation, as with Query.
7
+ class Match
8
+ attr_reader :pattern, :bindings
9
+
10
+ def initialize(pattern, bindings)
11
+ @pattern = pattern
12
+ @bindings = bindings.transform_keys(&:to_sym)
13
+ unknown = @bindings.keys - pattern.variables.keys - [:__start]
14
+ raise PatternError, "#{unknown.join(', ')} not in the pattern" if unknown.any?
15
+ end
16
+
17
+ # The Query for the whole pattern (or up to node index upto).
18
+ def query(upto = pattern.rels.size)
19
+ pattern.rels.first(upto).each_with_index.reduce(GraphQuery.from(start)) do |query, (rel, i)|
20
+ query.traverse(rel.names, depth: rel.max ? rel.min..rel.max : rel.min.., direction: rel.direction,
21
+ **arrival(i + 1), edge_where: edge_binding(rel))
22
+ end
23
+ end
24
+
25
+ # The nodes a variable (by default the last node) matches, as a relation.
26
+ def nodes(var = nil, model: nil)
27
+ index = var ? node_index(var) : pattern.nodes.size - 1
28
+ forward = query(index)
29
+ return forward.to_relation(model) if index == pattern.rels.size
30
+
31
+ backward = backward_query(index)
32
+ relation = forward.to_relation(model)
33
+ ids = "SELECT node_id FROM (#{backward.to_sql}) back " \
34
+ "WHERE node_type = #{relation.connection.quote(relation.klass.polymorphic_name)}"
35
+ column = "#{relation.quoted_table_name}.#{relation.connection.quote_column_name(relation.klass.primary_key)}"
36
+ relation.where(Arel.sql("#{column} IN (#{ids})"))
37
+ end
38
+
39
+ # Every path matching the whole pattern, as [[type, id], ...].
40
+ delegate :paths, to: :query
41
+
42
+ def to_relation(model = nil) = nodes(model:)
43
+
44
+ def respond_to_missing?(name, include_private = false)
45
+ ActiveRecord::Relation.method_defined?(name) || super
46
+ end
47
+
48
+ def method_missing(name, ...)
49
+ return super unless ActiveRecord::Relation.method_defined?(name)
50
+
51
+ nodes.public_send(name, ...)
52
+ end
53
+
54
+ private
55
+
56
+ def start
57
+ node = pattern.nodes.first
58
+ scope = node_scope(0)
59
+ return scope if scope
60
+ raise PatternError, 'the first node needs a binding or one label' unless node.labels&.size == 1
61
+
62
+ node.labels.first.constantize.all
63
+ end
64
+
65
+ # The conditions on node index i as traverse options.
66
+ def arrival(index)
67
+ node = pattern.nodes[index]
68
+ options = {}
69
+ options[:to] = node.labels if node.labels
70
+ scope = node_scope(index)
71
+ options[:where] = scope if scope
72
+ options
73
+ end
74
+
75
+ # What node index i must be in: its binding (a relation, record or model) narrowed by its property map.
76
+ def node_scope(index)
77
+ node = pattern.nodes[index]
78
+ bound = node.var && @bindings[node.var]
79
+ bound ||= @bindings[:__start] if index.zero?
80
+ return bound && GraphQuery.relation_for(bound) if node.props.blank?
81
+
82
+ relation = if bound then GraphQuery.relation_for(bound)
83
+ elsif node.labels&.size == 1 then node.labels.first.constantize.all
84
+ else raise PatternError, "(#{node.var}) needs one label or a binding for its property map"
85
+ end
86
+ relation.where(node.props)
87
+ end
88
+
89
+ # The rows a relationship's edges must match: its binding (a Hash or scope Proc) and its property map.
90
+ def edge_binding(rel)
91
+ bound = rel.var && @bindings[rel.var]
92
+ return bound if rel.props.blank?
93
+ return rel.props if bound.nil?
94
+ raise PatternError, "[#{rel.var}] has a property map and a binding that isn't a Hash" unless bound.is_a?(Hash)
95
+
96
+ bound.merge(rel.props)
97
+ end
98
+
99
+ def node_index(var)
100
+ kind, index = pattern.variables[var.to_sym]
101
+ raise PatternError, "#{var} is not a node in the pattern" unless kind == :node
102
+
103
+ index
104
+ end
105
+
106
+ # From every full match's last node, walk the pattern backwards to node index, checking each node on the way.
107
+ def backward_query(index)
108
+ rels = pattern.rels
109
+ (index...rels.size).reverse_each.reduce(GraphQuery.from_query(query)) do |query, i|
110
+ rel = rels[i]
111
+ options = i.zero? ? { where: start } : arrival(i)
112
+ query.traverse(rel.names, depth: rel.max ? rel.min..rel.max : rel.min.., direction: flip(rel.direction),
113
+ **options, edge_where: edge_binding(rel))
114
+ end
115
+ end
116
+
117
+ def flip(direction) = { out: :in, in: :out, both: :both }.fetch(direction)
118
+ end
119
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQuery
4
+ # What every Active Record model gets: graph_edge to declare edges, and traverse / graph_match to walk them from
5
+ # the current scope (or from one record).
6
+ module Model
7
+ extend ActiveSupport::Concern
8
+
9
+ class_methods do
10
+ # Declares an edge named name leaving this model's nodes.
11
+ #
12
+ # graph_edge :contains, association: :children # has_many: locales.parent_id
13
+ # graph_edge :within, association: :parent # belongs_to
14
+ # graph_edge :billed_on, association: :events # has_many :events, through: :event_people
15
+ # graph_edge :contains, to: 'Locale', through: 'LocaleGrouping', # a join model named outright
16
+ # source: :super_locale_id, target: :member_locale_id
17
+ # graph_edge :near, to: 'Venue', sql: 'SELECT a_id AS source_id, b_id AS target_id FROM venue_pairs'
18
+ # graph_edge :near, to: 'Venue', computed: -> { VenuePair.where(active: true) # built per query
19
+ # .select('a_id AS source_id, b_id AS target_id') }
20
+ # graph_edge(:near, to: 'Venue') { VenuePair.select('a_id AS source_id, b_id AS target_id') } # the same
21
+ #
22
+ # where: a Hash or a scope Proc (run on the edge's table) that rows must match, besides the association's own
23
+ # scope. Several declarations with one name make one edge kind that unions them.
24
+ def graph_edge(name, association: nil, to: nil, through: nil, source: nil, target: nil, sql: nil, where: nil,
25
+ computed: nil, &block)
26
+ sql = computed || block || sql
27
+ @graph_edges_declared ||= begin
28
+ GraphQuery.registry.clear(self.name)
29
+ true
30
+ end
31
+ key = [self.name, name, association, to, through, source, target, sql, where]
32
+ GraphQuery.registry.add(key:, declared_by: self.name) do
33
+ build_graph_edge(name, association:, to:, through:, source:, target:, sql:, where:)
34
+ end
35
+ end
36
+
37
+ def build_graph_edge(name, association:, to:, through:, source:, target:, sql:, where:)
38
+ if association
39
+ reflection = reflect_on_association(association) || raise(ArgumentError,
40
+ "#{self.name} has no association #{association}")
41
+ Associations.edge_for(self, name, reflection, where:)
42
+ elsif through
43
+ Edge.new(name:, from: polymorphic_name, to: to || raise(ArgumentError, 'to: is required'),
44
+ declared_by: self.name, table_model: through, source_column: source || foreign_key,
45
+ target_column: target || raise(ArgumentError, 'target: is required'), conditions: [where])
46
+ elsif sql
47
+ Edge.new(name:, from: polymorphic_name, to: to || raise(ArgumentError, 'to: is required'),
48
+ declared_by: self.name, sql:)
49
+ else
50
+ raise ArgumentError, 'graph_edge needs association:, through: or sql:'
51
+ end
52
+ end
53
+
54
+ # Declares a graph mutation (see GraphQuery::Mutation): graph_mutation def name(...) ... end, options decorates
55
+ # that method; graph_mutation options alone decorates the next method defined.
56
+ def graph_mutation(name = nil, arguments: {}, returns: nil, description: nil)
57
+ options = { arguments:, returns:, description: }
58
+ return @pending_graph_mutation = options if name.nil?
59
+
60
+ mutation = Mutation.new(model: self, name:, **options)
61
+ graph_mutations[mutation.name] = mutation
62
+ Mutation::Wrapping.wrap(self, mutation.name)
63
+ mutation.name
64
+ end
65
+
66
+ # This model's graph mutations, by name.
67
+ def graph_mutations = @graph_mutations ||= {}
68
+
69
+ def method_added(name)
70
+ super
71
+ options = @pending_graph_mutation or return
72
+ @pending_graph_mutation = nil
73
+ graph_mutation(name, **options)
74
+ end
75
+
76
+ # Walks edges from every node in the current scope (Locale.where(...).traverse(:contains, depth: 0..)).
77
+ # Returns a Query, which acts as a relation of the nodes it reaches.
78
+ def traverse(names = nil, **)
79
+ Query.new(GraphQuery.start_set(all)).traverse(names, **)
80
+ end
81
+
82
+ # A Query starting from the current scope that walks nothing yet (chain .out / .inbound / .traverse).
83
+ def graph = Query.new(GraphQuery.start_set(all))
84
+
85
+ # A Cypher-style pattern whose first node is the current scope:
86
+ # Locale.where(slug: 'seattle').graph_match('(l)-[:contains*0..]->()-[:has_venue]->(v:Venue)')
87
+ def graph_match(pattern, params: {}, **bindings)
88
+ first = Pattern.parse(pattern, params).nodes.first
89
+ GraphQuery.match(pattern, params:, **bindings, first.var || :__start => all)
90
+ end
91
+ end
92
+
93
+ # The same walks, starting from this record alone.
94
+ def traverse(names = nil, **) = self.class.where(id:).traverse(names, **)
95
+ def graph = self.class.where(id:).graph
96
+ end
97
+ end