This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
/
many_to_many.rb
394 lines (331 loc) · 12 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
module DataMapper
module Associations
module ManyToMany #:nodoc:
class Relationship < Associations::OneToMany::Relationship
OPTIONS = (superclass::OPTIONS + [ :through ]).freeze
##
# 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(relative_target_repository_name)
if child_properties
child_key = properties.values_at(*child_properties)
properties.class.new(child_key).freeze
else
properties.key
end
end
end
alias target_key child_key
# Intermediate association for join model
# relationships
#
# Example: for :bugs association in
#
# class Software::Engineer
# include DataMapper::Resource
#
# has n, :missing_tests
# has n, :bugs, :through => :missing_tests
# end
#
# through is :missing_tests
#
# TODO: document a case when
# through option is a model and
# not an association name
#
# @api semipublic
def through
return @through if explicit_through_relationship?
# 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, target_model, many_to_one_options)
one_to_many = source_model.has(min..max, join_relationship_name, join_model, one_to_many_options)
# initialize the child_key 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 do |relationship|
if relationship.respond_to?(:links)
relationship.links
else
relationship
end
end.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 { |resource| source_key.first.get(resource) }.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 ||= super.merge(:links => links).freeze
end
# TODO: document
# @api private
def inherited_by(model)
relationship = super
if explicit_through_relationship? || target_model?
relationship.instance_variable_set(:@through, through.inherited_by(model))
end
relationship
end
private
# TODO: document
# @api semipublic
def initialize(name, source_model, target_model, options = {})
@through = options.fetch(:through)
super
end
# 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
namespace = join_model_namespace_name.first
relationship_name = Extlib::Inflection.underscore(join_model.name.sub(/\A#{namespace.name}::/, '')).tr('/', '_')
relationship_name.pluralize.to_sym
end
# TODO: document
# @api private
def explicit_through_relationship?
@through != Resource
end
# TODO: document
# @api semipublic
def many_to_one_options
{ :parent_key => target_key.map { |property| property.name } }
end
# TODO: document
# @api semipublic
def one_to_many_options
{ :parent_key => source_key.map { |property| property.name } }
end
# Returns the inverse relationship class
#
# @api private
def inverse_class
self.class
end
# TODO: document
# @api private
def invert
inverse_class.new(inverse_name, parent_model, child_model, inverted_options)
end
# TODO: document
# @api private
def inverted_options
options.only(*OPTIONS - [ :min, :max ]).update(
:child_key => parent_key.map { |property| property.name },
:parent_key => child_key.map { |property| property.name },
:inverse => self
)
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
##
# Remove every Resource in the m:m Collection from the repository
#
# This performs a deletion of each Resource in the Collection from
# the repository and clears the Collection.
#
# @return [TrueClass, FalseClass]
# true if the resources were successfully destroyed
#
# @api public
def destroy
unless intermediaries.destroy
return false
end
super
end
##
# Remove every Resource in the m:m Collection from the repository, bypassing validation
#
# This performs a deletion of each Resource in the Collection from
# the repository and clears the Collection while skipping
# validation.
#
# @return [TrueClass, FalseClass]
# true if the resources were successfully destroyed
#
# @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.relative_target_repository_name_for(source)
model = relationship.target_model
key = model.key(repository_name)
# TODO: handle compound keys
model.all(:repository => repository_name, key.first => map { |resource| resource.key.first }).destroy!
each { |resource| resource.reset }
clear
true
end
private
# TODO: document
# @api private
def _create(safe, attributes)
if last_relationship.respond_to?(:resource_for)
resource = super
if create_intermediary(safe, last_relationship => resource)
resource
end
else
if intermediary = create_intermediary(safe)
super(safe, attributes.merge(last_relationship.inverse => intermediary))
end
end
end
# TODO: document
# @api private
def _update(dirty_attributes)
assert_source_saved 'The source must be saved before mass-updating the collection'
attributes = dirty_attributes.map { |property, value| [ property.name, value ] }.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 { |resource| resource.key.first }).update!(attributes)
end
# TODO: document
# @api private
def _save(safe)
resources = if loaded?
entries
else
head + tail
end
# delete only intermediaries linked to the target orphans
unless @orphans.empty? || intermediaries(@orphans).send(safe ? :destroy : :destroy!)
return false
end
if last_relationship.respond_to?(:resource_for)
super
resources.all? { |resource| create_intermediary(safe, last_relationship => resource) }
else
if intermediary = create_intermediary(safe)
inverse = last_relationship.inverse
resources.map { |resource| inverse.set(resource, intermediary) }
end
super
end
end
# TODO: document
# @api private
def intermediaries(resources = saved)
through = relationship.through
intermediaries = through.loaded?(source) ? through.get!(source) : through.collection_for(source)
intermediaries.all(last_relationship => resources)
end
# TODO: document
# @api private
def saved
select { |resource| resource.saved? }
end
# TODO: document
# @api private
def create_intermediary(safe, attributes = {})
return unless intermediaries.send(safe ? :save : :save!)
intermediary = intermediaries.first(attributes) ||
intermediaries.send(safe ? :create : :create!, attributes)
return intermediary if intermediary.saved?
end
# TODO: document
# @api private
def last_relationship
@last_relationship ||= relationship.links.last
end
# TODO: document
# @api private
def default_attributes
collection_default_attributes
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
end # class Collection
end # module ManyToMany
end # module Associations
end # module DataMapper