This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
/
many_to_many.rb
352 lines (284 loc) · 11.1 KB
/
many_to_many.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
module DataMapper
module Associations
module ManyToMany #:nodoc:
class Relationship < Associations::OneToMany::Relationship
##
# Returns a set of keys that identify the target model
#
# @return [DataMapper::PropertySet]
# a set of properties that identify the target model
#
# @api semipublic
def child_key
@child_key ||=
begin
properties = target_model.properties(target_repository_name)
child_key = if @child_properties
properties.values_at(*@child_properties)
else
properties.key
end
properties.class.new(child_key).freeze
end
end
alias target_key child_key
# TODO: document
# @api semipublic
def through
return @through if @through != Resource
# habtm relationship traversal is deferred because we want the
# target_model and source_model constants to be defined, so we
# can define the join model within their common namespace
DataMapper.repository(source_repository_name) do
many_to_one = join_model.belongs_to(name.to_s.singularize.to_sym, :model => target_model)
one_to_many = source_model.has(min..max, join_relationship_name(join_model), :model => join_model)
# initialize the child_key on the many to one relationship
# now that the source, join and target models are defined
many_to_one.child_key
@through = one_to_many
end
end
# TODO: document
# @api semipublic
def links
@links ||=
begin
relationships = through.target_model.relationships(source_repository_name)
unless target = relationships[name] || relationships[name.to_s.singular.to_sym]
raise NameError, "Cannot find target relationship #{name} or #{name.to_s.singular} in #{through.target_model} within the #{source_repository_name.inspect} repository"
end
[ through, target ].map { |r| (l = r.links).any? ? l : r }.flatten.freeze
end
end
# TODO: document
# @api private
def source_scope(source)
# TODO: remove this method and inherit from Relationship
target_key = through.target_key
source_key = through.source_key
scope = {}
# TODO: handle compound keys
if (source_values = Array(source).map { |r| source_key.first.get(r) }.compact).any?
scope[target_key.first] = source_values
end
scope
end
# TODO: document
# @api private
def query
# TODO: consider making this a query_for method, so that ManyToMany::Relationship#query only
# returns the query supplied in the definition
@many_to_many_query ||=
begin
# TODO: make sure the proper Query is set up, one that includes all the links
# - make sure that all relationships can be links
# - make sure that each intermediary can be at random repositories
# - make sure that each intermediary can have different conditons that
# scope its results
query = super.dup
# use all links in the query links
query[:links] = links
# TODO: move the logic below inside Query. It should be
# extracting the query conditions from each relationship itself
repository_name = source_repository_name
# merge the conditions from each intermediary into the query
query[:links].each do |relationship|
repository_name = relationship.target_repository_name || repository_name
model = relationship.target_model
# TODO: try to do some of this normalization when
# assigning the Query options to the Relationship
relationship.query.each do |key, value|
# TODO: figure out how to merge Query options from links
if Query::OPTIONS.include?(key)
next # skip for now
end
case key
when Symbol, String
# TODO: turn this into a Query::Path
query[model.properties(repository_name)[key]] = value
when Property
# TODO: turn this into a Query::Path
query[key] = value
when Query::Path
query[key] = value
when Query::Operator
# TODO: if the key.target is a Query::Path, then do not look it up
query[key.class.new(model.properties(repository_name)[key.target], key.operator)] = value
else
raise ArgumentError, "#{key.class} not allowed in relationship query"
end
end
end
query.freeze
end
end
private
# TODO: document
# @api private
def join_model
namespace, name = join_model_namespace_name
if namespace.const_defined?(name)
namespace.const_get(name)
else
model = Model.new do
# all properties added to the anonymous join model are considered a key
def property(name, type, options = {})
options[:key] = true unless options.key?(:key)
options.delete(:index)
super
end
end
namespace.const_set(name, model)
end
end
# TODO: document
# @api private
def join_model_namespace_name
target_parts = target_model.base_model.name.split('::')
source_parts = source_model.base_model.name.split('::')
name = [ target_parts.pop, source_parts.pop ].sort.join
namespace = Object
# find the common namespace between the target_model and source_model
target_parts.zip(source_parts) do |target_part, source_part|
break if target_part != source_part
namespace = namespace.const_get(target_part)
end
return namespace, name
end
# TODO: document
# @api private
def join_relationship_name(model)
namespace = join_model_namespace_name.first
relationship_name = Extlib::Inflection.underscore(model.base_model.name.sub(/\A#{namespace.name}::/, '')).gsub('/', '_')
relationship_name.pluralize.to_sym
end
# TODO: document
# @api private
def inverse
raise NotImplementedError, "#{self.class}#inverse not implemented"
end
# Returns collection class used by this type of
# relationship
#
# @api private
def collection_class
ManyToMany::Collection
end
end # class Relationship
class Collection < Associations::OneToMany::Collection
# TODO: document
# @api public
def create(attributes = {})
if last_relationship.respond_to?(:resource_for)
resource = super
if create_intermediary(last_relationship => resource)
resource
end
else
if intermediary = create_intermediary
super(attributes.merge(last_relationship.inverse => intermediary))
end
end
end
# TODO: document
# @api public
def save
resources = if loaded?
entries
else
head + tail
end
# delete only intermediaries linked to the target orphans
unless intermediaries.all(last_relationship => @orphans).destroy
return false
end
if last_relationship.respond_to?(:resource_for)
super
resources.all? { |r| create_intermediary(last_relationship => r) }
else
if intermediary = create_intermediary
inverse = last_relationship.inverse
resources.map { |r| inverse.set(r, intermediary) }
end
super
end
end
# TODO: document
# @api public
def destroy
unless intermediaries.destroy
return false
end
super
end
# TODO: document
# @api public
def destroy!
unless intermediaries.destroy!
return false
end
if empty?
return true
end
# FIXME: use a subquery to do this more efficiently in the future
repository_name = relationship.target_repository_name
model = relationship.target_model
key = model.key(repository_name)
# TODO: handle compound keys
model.all(:repository => repository_name, key.first => map { |r| r.key.first }).destroy!
each { |r| r.reset }
clear
true
end
private
# TODO: document
# @api private
def _update(dirty_attributes)
attributes = dirty_attributes.map { |p, v| [ p.name, v ] }.to_hash
# FIXME: use a subquery to do this more efficiently in the future,
key = model.key(repository.name)
# TODO: handle compound keys
model.all(:repository => repository_name, key.first => map { |r| r.key.first }).update!(attributes)
end
# TODO: document
# @api private
def intermediaries
through = relationship.through
intermediaries = through.loaded?(source) ? through.get!(source) : through.collection_for(source)
intermediaries.all(last_relationship => self)
end
# TODO: document
# @api private
def create_intermediary(attributes = {})
# create the intermediary record if there isn't one already
if intermediaries.save && (intermediary = intermediaries.first_or_create(attributes)).saved?
intermediary
end
end
# TODO: document
# @api private
def last_relationship
@last_relationship ||= relationship.links.last
end
# TODO: document
# @api private
def relate_resource(resource)
collection_relate_resource(resource)
end
# TODO: document
# @api private
def orphan_resource(resource)
collection_orphan_resource(resource)
end
# TODO: document
# @api private
def delegate_to_relationship(relationship, other_query = nil)
# FIXME: add support for SEL to m:m
query = relationship.query_for(self)
query.update(other_query) if other_query
model.all(query)
end
end # class Collection
end # module ManyToMany
end # module Associations
end # module DataMapper