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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +33 -0
- data/LICENSE.txt +21 -0
- data/README.md +96 -0
- data/docs/01-getting-started.md +82 -0
- data/docs/02-declaring-edges.md +134 -0
- data/docs/03-walking.md +121 -0
- data/docs/04-results.md +106 -0
- data/docs/05-patterns.md +80 -0
- data/docs/06-cypher.md +94 -0
- data/docs/07-writes.md +81 -0
- data/docs/08-graphql.md +118 -0
- data/docs/09-internals.md +108 -0
- data/docs/10-reference.md +114 -0
- data/lib/graph_query/age.rb +31 -0
- data/lib/graph_query/associations.rb +73 -0
- data/lib/graph_query/compiler.rb +224 -0
- data/lib/graph_query/cypher.rb +378 -0
- data/lib/graph_query/edge.rb +117 -0
- data/lib/graph_query/graphql.rb +329 -0
- data/lib/graph_query/match.rb +119 -0
- data/lib/graph_query/model.rb +97 -0
- data/lib/graph_query/mutation.rb +82 -0
- data/lib/graph_query/pattern.rb +104 -0
- data/lib/graph_query/query.rb +168 -0
- data/lib/graph_query/registry.rb +52 -0
- data/lib/graph_query/syntax.rb +85 -0
- data/lib/graph_query/transaction.rb +140 -0
- data/lib/graph_query/version.rb +5 -0
- data/lib/graph_query.rb +123 -0
- data/rbi/graph_query.rbi +356 -0
- data/sig/graph_query.rbs +231 -0
- metadata +106 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQuery
|
|
4
|
+
# A model method declared as a graph mutation: it runs in a GraphQuery.transaction, and it carries what a GraphQL
|
|
5
|
+
# mutation needs to expose it (arguments and their types, what it returns, a description).
|
|
6
|
+
#
|
|
7
|
+
# class Locale < ApplicationRecord
|
|
8
|
+
# graph_mutation def adopt(child:, role: nil, graph:) # decorates the method defined here
|
|
9
|
+
# graph.link(self, :contains, child)
|
|
10
|
+
# graph.link(child, :tagged, Tag.find_by!(name: role)) if role
|
|
11
|
+
# self
|
|
12
|
+
# end, arguments: { child: Locale, role: String }, description: 'Files a locale under this one.'
|
|
13
|
+
#
|
|
14
|
+
# graph_mutation arguments: { venue: Venue }, returns: Venue # or decorates the next method defined
|
|
15
|
+
# def take_venue(venue:, graph:) = graph.relink(self, :has_venue, venue, from: venue.locale) && venue
|
|
16
|
+
# end
|
|
17
|
+
#
|
|
18
|
+
# seattle.adopt(child: hill) # in a transaction: any error rolls every write back
|
|
19
|
+
#
|
|
20
|
+
# A graph: keyword parameter receives the GraphQuery::Transaction. Keyword parameters without a default are
|
|
21
|
+
# required arguments. Argument types: String, Integer, Float, :boolean, :id, :json, Date, Time, a model (passed as
|
|
22
|
+
# an ID, loaded into a record; a model name String works too, for models not loaded yet), [Model] (IDs, loaded),
|
|
23
|
+
# or a GraphQL type. GraphQuery::GraphQL exposes them as
|
|
24
|
+
# GraphQL mutations (graph_mutations Locale).
|
|
25
|
+
class Mutation
|
|
26
|
+
attr_reader :model, :name, :arguments, :returns, :description
|
|
27
|
+
|
|
28
|
+
def initialize(model:, name:, arguments:, returns:, description:)
|
|
29
|
+
@model = model
|
|
30
|
+
@name = name.to_sym
|
|
31
|
+
@arguments = arguments.transform_keys(&:to_sym)
|
|
32
|
+
@returns = returns
|
|
33
|
+
@description = description
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Argument names the method requires (keyword parameters without a default), graph: aside.
|
|
37
|
+
def required
|
|
38
|
+
parameters.filter_map { |kind, arg| arg if kind == :keyreq && arg != :graph }
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Every keyword the method takes, graph: aside.
|
|
42
|
+
def keywords = parameters.filter_map { |kind, arg| arg if %i[key keyreq].include?(kind) && arg != :graph }
|
|
43
|
+
|
|
44
|
+
def takes_graph? = parameters.any? { |kind, arg| %i[key keyreq].include?(kind) && arg == :graph }
|
|
45
|
+
|
|
46
|
+
def inspect = "#<GraphQuery::Mutation #{model.name}##{name}>"
|
|
47
|
+
|
|
48
|
+
# Runs the method on record with keyword arguments, in a transaction.
|
|
49
|
+
def call(record, **arguments) = record.public_send(name, **arguments)
|
|
50
|
+
|
|
51
|
+
private
|
|
52
|
+
|
|
53
|
+
# The decorated method's parameters (past the transaction wrapper).
|
|
54
|
+
def parameters
|
|
55
|
+
method = model.instance_method(name)
|
|
56
|
+
method = method.super_method if method.owner == model.instance_variable_get(:@graph_mutation_wrapper)
|
|
57
|
+
method.parameters
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# The module each model prepends to run its graph mutations in transactions.
|
|
61
|
+
module Wrapping
|
|
62
|
+
module_function
|
|
63
|
+
|
|
64
|
+
def wrap(model, name)
|
|
65
|
+
wrapper = model.instance_variable_get(:@graph_mutation_wrapper) ||
|
|
66
|
+
Module.new.tap do |mod|
|
|
67
|
+
model.instance_variable_set(:@graph_mutation_wrapper, mod)
|
|
68
|
+
model.prepend(mod)
|
|
69
|
+
end
|
|
70
|
+
mutation = model.graph_mutations.fetch(name)
|
|
71
|
+
wrapper.define_method(name) do |*args, **kwargs, &block|
|
|
72
|
+
result = nil
|
|
73
|
+
GraphQuery.transaction do |graph|
|
|
74
|
+
kwargs = kwargs.merge(graph:) if mutation.takes_graph? && !kwargs.key?(:graph)
|
|
75
|
+
result = super(*args, **kwargs, &block)
|
|
76
|
+
end
|
|
77
|
+
result
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQuery
|
|
4
|
+
# A linear Cypher-style path pattern: nodes in parentheses joined by relationships.
|
|
5
|
+
#
|
|
6
|
+
# (s:Locale {name: 'Seattle'})-[:contains*0..]->(c)-[:has_venue]->(v:Venue)<-[:plays_at|hosts]-(p:Person)
|
|
7
|
+
#
|
|
8
|
+
# Nodes: (var), (var:Label), (:Label|Other), (), each with an optional property map ({name: 'x', kind: $kind}).
|
|
9
|
+
# Relationships: -[var:name|other*min..max {prop: value}]-> (out), <-[...]- (in), -[...]- (either way), and
|
|
10
|
+
# --> / <-- / -- for any edge, one hop. Lengths: * (1 or more), *2 (exactly 2), *1..3, *..3 (1 to 3), *0.. (0 or
|
|
11
|
+
# more). Names may be written CONTAINS or hasVenue; they are matched as :contains and :has_venue. Labels are model
|
|
12
|
+
# names. $name in a property map reads params. For WHERE, RETURN and more than one path, see GraphQuery::Cypher.
|
|
13
|
+
class Pattern
|
|
14
|
+
include Syntax
|
|
15
|
+
|
|
16
|
+
Node = Data.define(:var, :labels, :props)
|
|
17
|
+
Rel = Data.define(:var, :names, :direction, :min, :max, :props)
|
|
18
|
+
|
|
19
|
+
attr_reader :nodes, :rels, :source
|
|
20
|
+
|
|
21
|
+
def self.parse(source, params = {}) = new(source, params:)
|
|
22
|
+
|
|
23
|
+
# With scanner:, reads one pattern from where the scanner stands and leaves it after the last node (Cypher reads
|
|
24
|
+
# the rest); otherwise the whole source must be one pattern.
|
|
25
|
+
def initialize(source, params: {}, scanner: nil)
|
|
26
|
+
@source = source
|
|
27
|
+
@params = params
|
|
28
|
+
@scanner = scanner || StringScanner.new(source)
|
|
29
|
+
@nodes = []
|
|
30
|
+
@rels = []
|
|
31
|
+
parse
|
|
32
|
+
fail!('the end of the pattern') unless scanner || skip_space.eos?
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Every variable, and where it is: [:node, index] or [:rel, index].
|
|
36
|
+
def variables
|
|
37
|
+
vars = {}
|
|
38
|
+
nodes.each_with_index { |node, i| vars[node.var] = [:node, i] if node.var }
|
|
39
|
+
rels.each_with_index { |rel, i| vars[rel.var] = [:rel, i] if rel.var }
|
|
40
|
+
vars
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def to_s = source
|
|
44
|
+
|
|
45
|
+
private
|
|
46
|
+
|
|
47
|
+
def parse
|
|
48
|
+
@nodes << node
|
|
49
|
+
while skip_space.check(/<-|-/)
|
|
50
|
+
@rels << rel
|
|
51
|
+
@nodes << node
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def node
|
|
56
|
+
expect('(')
|
|
57
|
+
var = ident
|
|
58
|
+
labels = nil
|
|
59
|
+
labels = names_list.map(&:camelize) if skip_space.skip(/:/)
|
|
60
|
+
props = skip_space.check(/\{/) ? map : nil
|
|
61
|
+
expect(')')
|
|
62
|
+
Node.new(var: var&.to_sym, labels:, props:)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def rel
|
|
66
|
+
skip_space
|
|
67
|
+
left = @scanner.scan(/<-|-/) || fail!('a relationship')
|
|
68
|
+
var = names = props = nil
|
|
69
|
+
min = max = 1
|
|
70
|
+
if @scanner.skip(/\[/)
|
|
71
|
+
var = ident&.to_sym
|
|
72
|
+
names = names_list.map { it.underscore.to_sym } if skip_space.skip(/:/)
|
|
73
|
+
min, max = length if skip_space.skip(/\*/)
|
|
74
|
+
props = map if skip_space.check(/\{/)
|
|
75
|
+
expect(']')
|
|
76
|
+
end
|
|
77
|
+
right = @scanner.scan(/->|-/) || fail!('the end of a relationship')
|
|
78
|
+
Rel.new(var:, names:, direction: direction_of(left, right), min:, max:, props:)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def direction_of(left, right)
|
|
82
|
+
return fail!('one arrow per relationship') if left == '<-' && right == '->'
|
|
83
|
+
return :in if left == '<-'
|
|
84
|
+
|
|
85
|
+
right == '->' ? :out : :both
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# After *: nothing (1..), N (exactly N), N.. , ..M, N..M.
|
|
89
|
+
def length
|
|
90
|
+
skip_space
|
|
91
|
+
first = @scanner.scan(/\d+/)&.to_i
|
|
92
|
+
return [first || 1, first] unless skip_space.skip(/\.\./)
|
|
93
|
+
|
|
94
|
+
last = skip_space.scan(/\d+/)&.to_i
|
|
95
|
+
[first || 1, last]
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def names_list
|
|
99
|
+
list = [ident || fail!('a name')]
|
|
100
|
+
list << (ident || fail!('a name')) while skip_space.skip(/\|:?/)
|
|
101
|
+
list
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQuery
|
|
4
|
+
# A walk: a start set of nodes and a list of steps, each following some edges one or more hops. It compiles to one
|
|
5
|
+
# WITH RECURSIVE statement and reads like a relation of the nodes the last step reaches:
|
|
6
|
+
#
|
|
7
|
+
# Locale.where(slug: 'seattle').traverse(:contains, depth: 0..).traverse(:has_venue).where(kind: 'bar')
|
|
8
|
+
#
|
|
9
|
+
# Relation methods (where, order, limit, pluck, count, each, ...) go to #to_relation, which needs the last step to
|
|
10
|
+
# reach one model (or name one with to:). For walks that reach several models, use #pairs, #records or
|
|
11
|
+
# #polymorphic. Each query is immutable: steps return a new one.
|
|
12
|
+
class Query
|
|
13
|
+
include Enumerable
|
|
14
|
+
|
|
15
|
+
Step = Data.define(:names, :direction, :min, :max, :labels, :where, :through, :edge_where)
|
|
16
|
+
|
|
17
|
+
attr_reader :start, :steps
|
|
18
|
+
|
|
19
|
+
def initialize(start, steps = [])
|
|
20
|
+
@start = start
|
|
21
|
+
@steps = steps.freeze
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Follows edges named names (a Symbol, an Array, or nil for every edge) from the current nodes.
|
|
25
|
+
#
|
|
26
|
+
# depth: hops, as an Integer or a Range (1 by default; 0.. includes the nodes it starts from; 2..4; 1..).
|
|
27
|
+
# direction: :out (source to target, the default), :in, or :both.
|
|
28
|
+
# to: only arrive at these models (a model or an Array of them).
|
|
29
|
+
# where: only arrive at nodes in this relation (or Array of relations, one per model); a Hash filters the one
|
|
30
|
+
# model the step reaches.
|
|
31
|
+
# through: every node the walk passes through, the last included, must be in this relation (or Array, one per
|
|
32
|
+
# model; nodes of other models pass freely).
|
|
33
|
+
# edge_where: a Hash (or scope Proc) each edge's row must match, for edges kept in tables.
|
|
34
|
+
def traverse(names = nil, depth: 1, direction: :out, to: nil, where: nil, through: nil, edge_where: nil)
|
|
35
|
+
min, max = depth_bounds(depth)
|
|
36
|
+
unless %i[out in both].include?(direction)
|
|
37
|
+
raise ArgumentError, "direction must be :out, :in or :both, not #{direction.inspect}"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
names = names.nil? || names == :* ? nil : Array(names).map(&:to_sym)
|
|
41
|
+
step = Step.new(names:, direction:, min:, max:, labels: list(to)&.map { GraphQuery.type_name(it) },
|
|
42
|
+
where: list(where), through: list(through), edge_where:)
|
|
43
|
+
self.class.new(start, steps + [step])
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def out(names = nil, **) = traverse(names, **, direction: :out)
|
|
47
|
+
def inbound(names = nil, **) = traverse(names, **, direction: :in)
|
|
48
|
+
def both(names = nil, **) = traverse(names, **, direction: :both)
|
|
49
|
+
|
|
50
|
+
# The node models the walk can end on.
|
|
51
|
+
def types = compiler.types.last
|
|
52
|
+
|
|
53
|
+
# The walk as SQL rows (node_type, node_id), plus origin_type and origin_id (the start node each row came from)
|
|
54
|
+
# with origin:, depth (hops in the last step; the fewest, unless path:) with depth:, and path (every node on the
|
|
55
|
+
# way, as 'Type:id' text) with path:.
|
|
56
|
+
def to_sql(origin: false, depth: false, path: false) = Compiler.new(self, origin:, depth:, path:).sql
|
|
57
|
+
|
|
58
|
+
# The nodes of one model the walk reaches, as a relation you can keep chaining.
|
|
59
|
+
def to_relation(model = nil)
|
|
60
|
+
model = resolve_model(model)
|
|
61
|
+
table = model.arel_table
|
|
62
|
+
model.where(table[model.primary_key].in(Arel.sql(ids_sql(model))))
|
|
63
|
+
end
|
|
64
|
+
alias nodes to_relation
|
|
65
|
+
|
|
66
|
+
# The same relation with each node's hop count in the last step selected as graph_depth. Order by it with
|
|
67
|
+
# order(Arel.sql('graph_query_nodes.depth')), which survives pluck.
|
|
68
|
+
def with_depth(model = nil)
|
|
69
|
+
model = resolve_model(model)
|
|
70
|
+
conn = model.connection
|
|
71
|
+
joined = "INNER JOIN (#{to_sql(depth: true)}) graph_query_nodes " \
|
|
72
|
+
"ON graph_query_nodes.node_type = #{conn.quote(model.polymorphic_name)} " \
|
|
73
|
+
"AND graph_query_nodes.node_id = #{model.quoted_table_name}.#{conn.quote_column_name(model.primary_key)}"
|
|
74
|
+
model.joins(joined).select(model.arel_table[Arel.star], Arel.sql('graph_query_nodes.depth AS graph_depth'))
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# [[type, id], ...] for every node reached, whatever its model.
|
|
78
|
+
def pairs = connection.select_rows("SELECT DISTINCT node_type, node_id FROM (#{to_sql}) g")
|
|
79
|
+
|
|
80
|
+
# Every node reached, loaded, whatever its model.
|
|
81
|
+
def records
|
|
82
|
+
pairs.group_by(&:first).flat_map { |type, rows| type.constantize.where(id: rows.map(&:last)).to_a }
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# {start id => [nodes of model it reaches]}, for a dataloader batching many starts in one query.
|
|
86
|
+
def by_origin(model = nil)
|
|
87
|
+
model = resolve_model(model)
|
|
88
|
+
rows = origin_pairs(model)
|
|
89
|
+
found = model.where(model.primary_key => rows.map(&:last).uniq).index_by(&:id)
|
|
90
|
+
rows.group_by(&:first).transform_values { |list| list.filter_map { found[it.last] } }
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# [[start id, reached id], ...] for the reached nodes of one model, unloaded.
|
|
94
|
+
def origin_pairs(model = nil)
|
|
95
|
+
model = resolve_model(model)
|
|
96
|
+
connection.select_rows(<<~SQL.squish)
|
|
97
|
+
SELECT DISTINCT origin_id, node_id FROM (#{to_sql(origin: true)}) g
|
|
98
|
+
WHERE node_type = #{connection.quote(model.polymorphic_name)}
|
|
99
|
+
SQL
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Each path the walk takes, as [[type, id], ...] from the start node to the last one. Paths never repeat a node.
|
|
103
|
+
def paths
|
|
104
|
+
connection.select_values("SELECT path FROM (#{to_sql(path: true)}) g").map do |raw|
|
|
105
|
+
PG::TextDecoder::Array.new.decode(raw).map { it.split(':', 2) }
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Rows of scope whose polymorphic association (name: :target reads target_type/target_id) points at a node the
|
|
110
|
+
# walk reaches: everything linked to anything under a venue, say.
|
|
111
|
+
def polymorphic(scope, name)
|
|
112
|
+
reflection = scope.klass.reflect_on_association(name)
|
|
113
|
+
type_col, id_col = reflection ? [reflection.foreign_type, reflection.foreign_key] : ["#{name}_type", "#{name}_id"]
|
|
114
|
+
table = scope.klass.quoted_table_name
|
|
115
|
+
scope.where(Arel.sql("(#{table}.#{connection.quote_column_name(type_col)}, " \
|
|
116
|
+
"#{table}.#{connection.quote_column_name(id_col)}) " \
|
|
117
|
+
"IN (SELECT node_type, node_id FROM (#{to_sql}) graph_query_nodes)"))
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def each(&) = to_relation.each(&)
|
|
121
|
+
|
|
122
|
+
def respond_to_missing?(name, include_private = false)
|
|
123
|
+
(types.size == 1 && ActiveRecord::Relation.method_defined?(name)) || super
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def method_missing(name, ...)
|
|
127
|
+
return super unless types.size == 1 && ActiveRecord::Relation.method_defined?(name)
|
|
128
|
+
|
|
129
|
+
to_relation.public_send(name, ...)
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def inspect = "#<GraphQuery::Query #{types.join('|')}: #{steps.size} step(s)>"
|
|
133
|
+
|
|
134
|
+
def compiler = @compiler ||= Compiler.new(self)
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
def connection = ActiveRecord::Base.connection
|
|
139
|
+
|
|
140
|
+
def ids_sql(model)
|
|
141
|
+
"SELECT node_id FROM (#{to_sql}) graph_query_nodes WHERE node_type = #{connection.quote(model.polymorphic_name)}"
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def resolve_model(model)
|
|
145
|
+
return GraphQuery.model_for(model) if model
|
|
146
|
+
|
|
147
|
+
return types.first.constantize if types.size == 1
|
|
148
|
+
|
|
149
|
+
raise AmbiguousResult, "this walk reaches #{types.join(', ')}: name one, use to:, or use #pairs / #polymorphic"
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# Array() would load a relation's records.
|
|
153
|
+
def list(value) = value.nil? || value.is_a?(Array) ? value : [value]
|
|
154
|
+
|
|
155
|
+
def depth_bounds(depth)
|
|
156
|
+
case depth
|
|
157
|
+
when Integer then [depth, depth]
|
|
158
|
+
when Range
|
|
159
|
+
min = depth.begin || 0
|
|
160
|
+
max = depth.end && (depth.exclude_end? ? depth.end - 1 : depth.end)
|
|
161
|
+
raise ArgumentError, "depth #{depth} is empty" if min.negative? || (max && max < min)
|
|
162
|
+
|
|
163
|
+
[min, max]
|
|
164
|
+
else raise ArgumentError, "depth must be an Integer or a Range, not #{depth.inspect}"
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'monitor'
|
|
4
|
+
|
|
5
|
+
module GraphQuery
|
|
6
|
+
# Every edge declared so far, by node model name. A model declares its edges when it loads, so before answering
|
|
7
|
+
# which edges leave or reach a node the registry loads that node's model (autoloading in development).
|
|
8
|
+
class Registry
|
|
9
|
+
def initialize
|
|
10
|
+
@edges = {}
|
|
11
|
+
@mutex = Monitor.new
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Adds an edge, or a block that builds one when a query first needs it (associations name models that may not
|
|
15
|
+
# be loaded yet while the declaring model loads). key identifies the declaration, so a reload replaces it.
|
|
16
|
+
def add(edge = nil, key: edge&.key, declared_by: edge&.declared_by, &builder)
|
|
17
|
+
@mutex.synchronize { @edges[key] = edge || Pending.new(declared_by.to_s, builder) }
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
Pending = Struct.new(:declared_by, :builder)
|
|
21
|
+
|
|
22
|
+
# Forget the edges a model declared (when it is declared again, as code reloads).
|
|
23
|
+
def clear(declared_by)
|
|
24
|
+
@mutex.synchronize { @edges.delete_if { |_, edge| edge.declared_by == declared_by.to_s } }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def all
|
|
28
|
+
@mutex.synchronize do
|
|
29
|
+
# Building one edge can load another model, which declares more: build from a snapshot.
|
|
30
|
+
@edges.select { |_, edge| edge.is_a?(Pending) }.each do |key, pending|
|
|
31
|
+
@edges[key] = pending.builder.call if @edges[key].equal?(pending)
|
|
32
|
+
end
|
|
33
|
+
@edges.values
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Edges named any of names (nil: any name) walked in a direction from nodes of these types:
|
|
38
|
+
# [[edge, direction], ...]. Direction :both gives each edge both ways.
|
|
39
|
+
def walkable(types, names, direction)
|
|
40
|
+
types.each { load_model(it) }
|
|
41
|
+
directions = direction == :both ? %i[out in] : [direction]
|
|
42
|
+
directions.flat_map do |dir|
|
|
43
|
+
matching = all.select do |edge|
|
|
44
|
+
(names.nil? || names.include?(edge.name)) && types.include?(dir == :in ? edge.to : edge.from)
|
|
45
|
+
end
|
|
46
|
+
matching.map { [it, dir] }
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def load_model(name) = name.to_s.safe_constantize
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'strscan'
|
|
4
|
+
|
|
5
|
+
module GraphQuery
|
|
6
|
+
# The tokens Pattern and Cypher share: whitespace, names, punctuation and literal values (strings, numbers, booleans,
|
|
7
|
+
# null, lists, maps and $parameters). A class that includes it sets @scanner, @source and @params.
|
|
8
|
+
module Syntax
|
|
9
|
+
IDENT = /[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*/
|
|
10
|
+
NUMBER = /-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?/
|
|
11
|
+
|
|
12
|
+
private
|
|
13
|
+
|
|
14
|
+
def skip_space
|
|
15
|
+
@scanner.skip(%r{(?:\s+|//[^\n]*)+})
|
|
16
|
+
@scanner
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def ident = skip_space.scan(IDENT) || skip_space.scan(/`[^`]+`/)&.delete('`')
|
|
20
|
+
|
|
21
|
+
def expect(token)
|
|
22
|
+
skip_space.skip(Regexp.new(Regexp.escape(token))) || fail!("'#{token}'")
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def keyword?(word) = skip_space.check(/#{word}\b/i)
|
|
26
|
+
|
|
27
|
+
def keyword(word) = skip_space.skip(/#{word}\b/i)
|
|
28
|
+
|
|
29
|
+
def fail!(what)
|
|
30
|
+
raise PatternError, "expected #{what} at #{@scanner.pos} in #{@source.inspect}"
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# A literal or a $parameter.
|
|
34
|
+
def value
|
|
35
|
+
skip_space
|
|
36
|
+
if @scanner.skip(/\$/) then param(ident || fail!('a parameter name'))
|
|
37
|
+
elsif (text = @scanner.scan(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/)) then unquote(text)
|
|
38
|
+
elsif (number = @scanner.scan(NUMBER)) then number.include?('.') || number =~ /e/i ? number.to_f : number.to_i
|
|
39
|
+
elsif @scanner.check(/\[/) then list
|
|
40
|
+
elsif @scanner.check(/\{/) then map
|
|
41
|
+
else constant
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def constant
|
|
46
|
+
word = @scanner.scan(/(?:true|false|null)\b/i) || fail!('a value')
|
|
47
|
+
{ 'true' => true, 'false' => false, 'null' => nil }.fetch(word.downcase)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def param(name)
|
|
51
|
+
key = name.to_sym
|
|
52
|
+
return @params.fetch(key) if @params.key?(key)
|
|
53
|
+
return @params.fetch(name) if @params.key?(name)
|
|
54
|
+
|
|
55
|
+
raise PatternError, "no value given for $#{name}"
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def unquote(text)
|
|
59
|
+
text[1..-2].gsub(/\\(.)/) { { 'n' => "\n", 't' => "\t" }.fetch(::Regexp.last_match(1), ::Regexp.last_match(1)) }
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def list
|
|
63
|
+
expect('[')
|
|
64
|
+
items = []
|
|
65
|
+
until skip_space.skip(/\]/)
|
|
66
|
+
items << value
|
|
67
|
+
skip_space.skip(/,/) || (skip_space.check(/\]/) || fail!("',' or ']'"))
|
|
68
|
+
end
|
|
69
|
+
items
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# {key: value, ...}, as a Hash with Symbol keys.
|
|
73
|
+
def map
|
|
74
|
+
expect('{')
|
|
75
|
+
pairs = {}
|
|
76
|
+
until skip_space.skip(/\}/)
|
|
77
|
+
key = ident || fail!('a property name')
|
|
78
|
+
expect(':')
|
|
79
|
+
pairs[key.to_sym] = value
|
|
80
|
+
skip_space.skip(/,/) || (skip_space.check(/\}/) || fail!("',' or '}'"))
|
|
81
|
+
end
|
|
82
|
+
pairs
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQuery
|
|
4
|
+
# Writes to the graph through the edges models declare, inside one database transaction:
|
|
5
|
+
#
|
|
6
|
+
# GraphQuery.transaction do |graph|
|
|
7
|
+
# hill = graph.create(Locale, name: 'Capitol Hill')
|
|
8
|
+
# graph.link(seattle, :contains, hill) # sets locales.parent_id
|
|
9
|
+
# graph.link(northwest, :contains, hill, via: 'LocaleGrouping', attributes: { role: 'core' })
|
|
10
|
+
# graph.relink(hill, :has_venue, eagle, from: downtown) # moves the venue
|
|
11
|
+
# graph.unlink(seattle, :has_venue, closed_bar)
|
|
12
|
+
# end
|
|
13
|
+
#
|
|
14
|
+
# An edge is written where it is kept: a has_many edge sets the foreign key on the target's row, a belongs_to edge on
|
|
15
|
+
# the source's row, and a join-model edge creates or deletes a join row (with the edge's Hash conditions as its
|
|
16
|
+
# attributes). Rows are saved with save!/destroy!, so validations and callbacks run, and any error rolls every write
|
|
17
|
+
# back. SQL edges can't be written.
|
|
18
|
+
class Transaction
|
|
19
|
+
Change = Data.define(:action, :edge, :from, :to, :record)
|
|
20
|
+
|
|
21
|
+
# What was written, in order.
|
|
22
|
+
attr_reader :changes
|
|
23
|
+
|
|
24
|
+
def initialize
|
|
25
|
+
@changes = []
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Adds the edge name from from to to. Already there: nothing changes. via: names the edge's table model when
|
|
29
|
+
# several edges share the name; attributes: extra columns for a new join row.
|
|
30
|
+
def link(from, name, to, via: nil, attributes: {})
|
|
31
|
+
edge = edge_for(from, name, to, via)
|
|
32
|
+
record = case kind(edge)
|
|
33
|
+
when :target_row then point(row(edge, to), edge.source_column, from, edge)
|
|
34
|
+
when :source_row then point(row(edge, from), edge.target_column, to, edge)
|
|
35
|
+
else join_row(edge, from, to, attributes)
|
|
36
|
+
end
|
|
37
|
+
note(:link, edge, from, to, record)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Removes the edge name from from to to. Not there: nothing changes.
|
|
41
|
+
def unlink(from, name, to, via: nil)
|
|
42
|
+
edge = edge_for(from, name, to, via)
|
|
43
|
+
record = case kind(edge)
|
|
44
|
+
when :target_row then clear(row(edge, to), edge.source_column, from)
|
|
45
|
+
when :source_row then clear(row(edge, from), edge.target_column, to)
|
|
46
|
+
else rows(edge, from, to).each(&:destroy!).first
|
|
47
|
+
end
|
|
48
|
+
note(:unlink, edge, from, to, record)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Moves to from one source to another: unlink from from:, link to new_from.
|
|
52
|
+
def relink(new_from, name, to, from:, via: nil, attributes: {})
|
|
53
|
+
unlink(from, name, to, via:) unless from.nil?
|
|
54
|
+
link(new_from, name, to, via:, attributes:)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Whether the edge name runs from from to to.
|
|
58
|
+
def linked?(from, name, to, via: nil)
|
|
59
|
+
edge = edge_for(from, name, to, via)
|
|
60
|
+
case kind(edge)
|
|
61
|
+
when :target_row then row(edge, to)[edge.source_column] == from.id
|
|
62
|
+
when :source_row then row(edge, from)[edge.target_column] == to.id
|
|
63
|
+
else rows(edge, from, to).exists?
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def create(model, **attributes) = model.create!(**attributes).tap { note(:create, nil, nil, nil, it) }
|
|
68
|
+
|
|
69
|
+
def update(record, **attributes) = record.tap { it.update!(**attributes) }.tap { note(:update, nil, nil, nil, it) }
|
|
70
|
+
|
|
71
|
+
def destroy(record) = record.destroy!.tap { note(:destroy, nil, nil, nil, it) }
|
|
72
|
+
|
|
73
|
+
private
|
|
74
|
+
|
|
75
|
+
def note(action, edge, from, to, record)
|
|
76
|
+
@changes << Change.new(action:, edge:, from:, to:, record:) if record
|
|
77
|
+
record
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# The one edge named name from from's model to to's model (or kept in via's table).
|
|
81
|
+
def edge_for(from, name, to, via)
|
|
82
|
+
from_type = GraphQuery.type_name(from)
|
|
83
|
+
to_type = GraphQuery.type_name(to)
|
|
84
|
+
GraphQuery.registry.load_model(to_type)
|
|
85
|
+
edges = GraphQuery.registry.walkable([from_type], [name.to_sym], :out).map(&:first)
|
|
86
|
+
.select { it.to == to_type && !it.sql }
|
|
87
|
+
edges = edges.select { it.table_model == GraphQuery.type_name(via) } if via
|
|
88
|
+
raise NoEdges, "no writable #{name} edge from #{from_type} to #{to_type}" if edges.empty?
|
|
89
|
+
return edges.first if edges.one?
|
|
90
|
+
|
|
91
|
+
tables = edges.map(&:table_model).join(', ')
|
|
92
|
+
raise AmbiguousResult, "#{name} from #{from_type} to #{to_type} is kept in #{tables}: pass via:"
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# Where the edge's row is: the target's own row (has_many), the source's own row (belongs_to), or a join row.
|
|
96
|
+
def kind(edge)
|
|
97
|
+
key = edge.model.primary_key
|
|
98
|
+
if edge.target_column == key && edge.table_model == edge.to then :target_row
|
|
99
|
+
elsif edge.source_column == key && edge.table_model == edge.from then :source_row
|
|
100
|
+
else :join_row
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# The node's row in the edge's table (the record itself when it is one).
|
|
105
|
+
def row(edge, node)
|
|
106
|
+
model = edge.model
|
|
107
|
+
node.is_a?(model) ? node : model.find(node.id)
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def point(record, column, node, edge)
|
|
111
|
+
record.assign_attributes(hash_conditions(edge))
|
|
112
|
+
record[column] = node.id
|
|
113
|
+
return nil unless record.changed?
|
|
114
|
+
|
|
115
|
+
record.save!
|
|
116
|
+
record
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def clear(record, column, node)
|
|
120
|
+
return nil unless record[column] == node.id
|
|
121
|
+
|
|
122
|
+
record[column] = nil
|
|
123
|
+
record.save!
|
|
124
|
+
record
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def join_row(edge, from, to, attributes)
|
|
128
|
+
return nil if rows(edge, from, to).exists?
|
|
129
|
+
|
|
130
|
+
edge.model.create!(**hash_conditions(edge), **attributes,
|
|
131
|
+
edge.source_column => from.id, edge.target_column => to.id)
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def rows(edge, from, to)
|
|
135
|
+
edge.model.where(edge.source_column => from.id, edge.target_column => to.id).where(hash_conditions(edge))
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def hash_conditions(edge) = edge.conditions.grep(Hash).reduce({}, :merge)
|
|
139
|
+
end
|
|
140
|
+
end
|