bigrecord 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (104) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README.rdoc +44 -0
  3. data/Rakefile +17 -0
  4. data/VERSION +1 -0
  5. data/doc/bigrecord_specs.rdoc +36 -0
  6. data/doc/getting_started.rdoc +157 -0
  7. data/examples/bigrecord.yml +25 -0
  8. data/generators/bigrecord/bigrecord_generator.rb +17 -0
  9. data/generators/bigrecord/templates/bigrecord.rake +47 -0
  10. data/generators/bigrecord_migration/bigrecord_migration_generator.rb +13 -0
  11. data/generators/bigrecord_migration/templates/migration.rb +9 -0
  12. data/generators/bigrecord_model/bigrecord_model_generator.rb +28 -0
  13. data/generators/bigrecord_model/templates/migration.rb +13 -0
  14. data/generators/bigrecord_model/templates/model.rb +7 -0
  15. data/generators/bigrecord_model/templates/model_spec.rb +12 -0
  16. data/init.rb +9 -0
  17. data/install.rb +22 -0
  18. data/lib/big_record/abstract_base.rb +1088 -0
  19. data/lib/big_record/action_view_extensions.rb +266 -0
  20. data/lib/big_record/ar_associations/association_collection.rb +194 -0
  21. data/lib/big_record/ar_associations/association_proxy.rb +158 -0
  22. data/lib/big_record/ar_associations/belongs_to_association.rb +57 -0
  23. data/lib/big_record/ar_associations/belongs_to_many_association.rb +57 -0
  24. data/lib/big_record/ar_associations/has_and_belongs_to_many_association.rb +164 -0
  25. data/lib/big_record/ar_associations/has_many_association.rb +191 -0
  26. data/lib/big_record/ar_associations/has_one_association.rb +80 -0
  27. data/lib/big_record/ar_associations.rb +1608 -0
  28. data/lib/big_record/ar_reflection.rb +223 -0
  29. data/lib/big_record/attribute_methods.rb +75 -0
  30. data/lib/big_record/base.rb +618 -0
  31. data/lib/big_record/br_associations/association_collection.rb +194 -0
  32. data/lib/big_record/br_associations/association_proxy.rb +153 -0
  33. data/lib/big_record/br_associations/belongs_to_association.rb +52 -0
  34. data/lib/big_record/br_associations/belongs_to_many_association.rb +293 -0
  35. data/lib/big_record/br_associations/cached_item_proxy.rb +194 -0
  36. data/lib/big_record/br_associations/cached_item_proxy_factory.rb +62 -0
  37. data/lib/big_record/br_associations/has_and_belongs_to_many_association.rb +168 -0
  38. data/lib/big_record/br_associations/has_one_association.rb +80 -0
  39. data/lib/big_record/br_associations.rb +978 -0
  40. data/lib/big_record/br_reflection.rb +151 -0
  41. data/lib/big_record/callbacks.rb +367 -0
  42. data/lib/big_record/connection_adapters/abstract/connection_specification.rb +279 -0
  43. data/lib/big_record/connection_adapters/abstract/database_statements.rb +175 -0
  44. data/lib/big_record/connection_adapters/abstract/quoting.rb +58 -0
  45. data/lib/big_record/connection_adapters/abstract_adapter.rb +190 -0
  46. data/lib/big_record/connection_adapters/column.rb +491 -0
  47. data/lib/big_record/connection_adapters/hbase_adapter.rb +432 -0
  48. data/lib/big_record/connection_adapters/view.rb +27 -0
  49. data/lib/big_record/connection_adapters.rb +10 -0
  50. data/lib/big_record/deletion.rb +73 -0
  51. data/lib/big_record/dynamic_schema.rb +92 -0
  52. data/lib/big_record/embedded.rb +71 -0
  53. data/lib/big_record/embedded_associations/association_proxy.rb +148 -0
  54. data/lib/big_record/family_span_columns.rb +89 -0
  55. data/lib/big_record/fixtures.rb +1025 -0
  56. data/lib/big_record/migration.rb +380 -0
  57. data/lib/big_record/routing_ext.rb +65 -0
  58. data/lib/big_record/timestamp.rb +51 -0
  59. data/lib/big_record/validations.rb +830 -0
  60. data/lib/big_record.rb +125 -0
  61. data/lib/bigrecord.rb +1 -0
  62. data/rails/init.rb +9 -0
  63. data/spec/connections/bigrecord.yml +13 -0
  64. data/spec/connections/cassandra/connection.rb +2 -0
  65. data/spec/connections/hbase/connection.rb +2 -0
  66. data/spec/debug.log +281 -0
  67. data/spec/integration/br_associations_spec.rb +80 -0
  68. data/spec/lib/animal.rb +12 -0
  69. data/spec/lib/book.rb +10 -0
  70. data/spec/lib/broken_migrations/duplicate_name/20090706182535_add_animals_table.rb +14 -0
  71. data/spec/lib/broken_migrations/duplicate_name/20090706193019_add_animals_table.rb +9 -0
  72. data/spec/lib/broken_migrations/duplicate_version/20090706190623_add_books_table.rb +9 -0
  73. data/spec/lib/broken_migrations/duplicate_version/20090706190623_add_companies_table.rb +9 -0
  74. data/spec/lib/company.rb +14 -0
  75. data/spec/lib/embedded/web_link.rb +12 -0
  76. data/spec/lib/employee.rb +33 -0
  77. data/spec/lib/migrations/20090706182535_add_animals_table.rb +13 -0
  78. data/spec/lib/migrations/20090706190623_add_books_table.rb +15 -0
  79. data/spec/lib/migrations/20090706193019_add_companies_table.rb +14 -0
  80. data/spec/lib/migrations/20090706194512_add_employees_table.rb +13 -0
  81. data/spec/lib/migrations/20090706195741_add_zoos_table.rb +13 -0
  82. data/spec/lib/novel.rb +5 -0
  83. data/spec/lib/zoo.rb +17 -0
  84. data/spec/spec.opts +4 -0
  85. data/spec/spec_helper.rb +55 -0
  86. data/spec/unit/abstract_base_spec.rb +287 -0
  87. data/spec/unit/adapters/abstract_adapter_spec.rb +56 -0
  88. data/spec/unit/adapters/adapter_shared_spec.rb +51 -0
  89. data/spec/unit/adapters/hbase_adapter_spec.rb +15 -0
  90. data/spec/unit/ar_associations_spec.rb +8 -0
  91. data/spec/unit/base_spec.rb +6 -0
  92. data/spec/unit/br_associations_spec.rb +58 -0
  93. data/spec/unit/embedded_spec.rb +43 -0
  94. data/spec/unit/find_spec.rb +34 -0
  95. data/spec/unit/hash_helper_spec.rb +44 -0
  96. data/spec/unit/migration_spec.rb +144 -0
  97. data/spec/unit/model_spec.rb +315 -0
  98. data/spec/unit/validations_spec.rb +182 -0
  99. data/tasks/bigrecord_tasks.rake +47 -0
  100. data/tasks/data_store.rb +46 -0
  101. data/tasks/gem.rb +22 -0
  102. data/tasks/rdoc.rb +8 -0
  103. data/tasks/spec.rb +34 -0
  104. metadata +189 -0
@@ -0,0 +1,1608 @@
1
+ require 'big_record/ar_associations/association_proxy'
2
+ require 'big_record/ar_associations/association_collection'
3
+ require 'big_record/ar_associations/belongs_to_association'
4
+ require 'big_record/ar_associations/has_one_association'
5
+ require 'big_record/ar_associations/has_many_association'
6
+ require 'big_record/ar_associations/has_and_belongs_to_many_association'
7
+
8
+ module BigRecord
9
+ class HasManyThroughAssociationNotFoundError < BigRecordError #:nodoc:
10
+ def initialize(owner_class_name, reflection)
11
+ super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
12
+ end
13
+ end
14
+
15
+ class HasManyThroughAssociationPolymorphicError < BigRecordError #:nodoc:
16
+ def initialize(owner_class_name, reflection, source_reflection)
17
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}'.")
18
+ end
19
+ end
20
+
21
+ class HasManyThroughAssociationPointlessSourceTypeError < BigRecordError #:nodoc:
22
+ def initialize(owner_class_name, reflection, source_reflection)
23
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
24
+ end
25
+ end
26
+
27
+ class HasManyThroughSourceAssociationNotFoundError < BigRecordError #:nodoc:
28
+ def initialize(reflection)
29
+ through_reflection = reflection.through_reflection
30
+ source_reflection_names = reflection.source_reflection_names
31
+ source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
32
+ super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence :connector => 'or'} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence :connector => 'or'}?")
33
+ end
34
+ end
35
+
36
+ class HasManyThroughSourceAssociationMacroError < BigRecordError #:nodoc:
37
+ def initialize(reflection)
38
+ through_reflection = reflection.through_reflection
39
+ source_reflection = reflection.source_reflection
40
+ super("Invalid source reflection macro :#{source_reflection.macro}#{" :through" if source_reflection.options[:through]} for has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}. Use :source to specify the source reflection.")
41
+ end
42
+ end
43
+
44
+ class HasManyThroughCantAssociateNewRecords < BigRecordError #:nodoc:
45
+ def initialize(owner, reflection)
46
+ super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
47
+ end
48
+ end
49
+
50
+ class EagerLoadPolymorphicError < BigRecordError #:nodoc:
51
+ def initialize(reflection)
52
+ super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
53
+ end
54
+ end
55
+
56
+ class ReadOnlyAssociation < BigRecordError #:nodoc:
57
+ def initialize(reflection)
58
+ super("Can not add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
59
+ end
60
+ end
61
+
62
+ module ArAssociations # :nodoc:
63
+ def self.included(base)
64
+ base.extend(ClassMethods)
65
+ end
66
+
67
+ # Clears out the association cache
68
+ def clear_association_cache #:nodoc:
69
+ self.class.reflect_on_all_associations.to_a.each do |assoc|
70
+ instance_variable_set "@#{assoc.name}", nil
71
+ end unless self.new_record?
72
+ end
73
+
74
+ # Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like
75
+ # "Project has one Project Manager" or "Project belongs to a Portfolio". Each macro adds a number of methods to the class which are
76
+ # specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby's own attr*
77
+ # methods. Example:
78
+ #
79
+ # class Project < BigRecord::Base
80
+ # belongs_to :portfolio
81
+ # has_one :project_manager
82
+ # has_many :milestones
83
+ # has_and_belongs_to_many :categories
84
+ # end
85
+ #
86
+ # The project class now has the following methods (and more) to ease the traversal and manipulation of its relationships:
87
+ # * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
88
+ # * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
89
+ # * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
90
+ # <tt>Project#milestones.delete(milestone), Project#milestones.find(milestone_id), Project#milestones.find(:all, options),</tt>
91
+ # <tt>Project#milestones.build, Project#milestones.create</tt>
92
+ # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
93
+ # <tt>Project#categories.delete(category1)</tt>
94
+ #
95
+ # == Example
96
+ #
97
+ # link:files/examples/associations.png
98
+ #
99
+ # == Is it belongs_to or has_one?
100
+ #
101
+ # Both express a 1-1 relationship, the difference is mostly where to place the foreign key, which goes on the table for the class
102
+ # saying belongs_to. Example:
103
+ #
104
+ # class User < BigRecord::Base
105
+ # # I reference an account.
106
+ # belongs_to :account
107
+ # end
108
+ #
109
+ # class Account < BigRecord::Base
110
+ # # One user references me.
111
+ # has_one :user
112
+ # end
113
+ #
114
+ # The tables for these classes could look something like:
115
+ #
116
+ # CREATE TABLE users (
117
+ # id int(11) NOT NULL auto_increment,
118
+ # account_id int(11) default NULL,
119
+ # name varchar default NULL,
120
+ # PRIMARY KEY (id)
121
+ # )
122
+ #
123
+ # CREATE TABLE accounts (
124
+ # id int(11) NOT NULL auto_increment,
125
+ # name varchar default NULL,
126
+ # PRIMARY KEY (id)
127
+ # )
128
+ #
129
+ # == Unsaved objects and associations
130
+ #
131
+ # You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
132
+ # aware of, mostly involving the saving of associated objects.
133
+ #
134
+ # === One-to-one associations
135
+ #
136
+ # * Assigning an object to a has_one association automatically saves that object and the object being replaced (if there is one), in
137
+ # order to update their primary keys - except if the parent object is unsaved (new_record? == true).
138
+ # * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
139
+ # is cancelled.
140
+ # * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
141
+ # * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
142
+ # not save the parent either.
143
+ #
144
+ # === Collections
145
+ #
146
+ # * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
147
+ # (the owner of the collection) is not yet stored in the database.
148
+ # * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
149
+ # * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
150
+ # * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
151
+ #
152
+ # === Association callbacks
153
+ #
154
+ # Similiar to the normal callbacks that hook into the lifecycle of an Active Record object, you can also define callbacks that get
155
+ # trigged when you add an object to or removing an object from a association collection. Example:
156
+ #
157
+ # class Project
158
+ # has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
159
+ #
160
+ # def evaluate_velocity(developer)
161
+ # ...
162
+ # end
163
+ # end
164
+ #
165
+ # It's possible to stack callbacks by passing them as an array. Example:
166
+ #
167
+ # class Project
168
+ # has_and_belongs_to_many :developers, :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
169
+ # end
170
+ #
171
+ # Possible callbacks are: before_add, after_add, before_remove and after_remove.
172
+ #
173
+ # Should any of the before_add callbacks throw an exception, the object does not get added to the collection. Same with
174
+ # the before_remove callbacks, if an exception is thrown the object doesn't get removed.
175
+ #
176
+ # === Association extensions
177
+ #
178
+ # The proxy objects that controls the access to associations can be extended through anonymous modules. This is especially
179
+ # beneficial for adding new finders, creators, and other factory-type methods that are only used as part of this association.
180
+ # Example:
181
+ #
182
+ # class Account < BigRecord::Base
183
+ # has_many :people do
184
+ # def find_or_create_by_name(name)
185
+ # first_name, last_name = name.split(" ", 2)
186
+ # find_or_create_by_first_name_and_last_name(first_name, last_name)
187
+ # end
188
+ # end
189
+ # end
190
+ #
191
+ # person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
192
+ # person.first_name # => "David"
193
+ # person.last_name # => "Heinemeier Hansson"
194
+ #
195
+ # If you need to share the same extensions between many associations, you can use a named extension module. Example:
196
+ #
197
+ # module FindOrCreateByNameExtension
198
+ # def find_or_create_by_name(name)
199
+ # first_name, last_name = name.split(" ", 2)
200
+ # find_or_create_by_first_name_and_last_name(first_name, last_name)
201
+ # end
202
+ # end
203
+ #
204
+ # class Account < BigRecord::Base
205
+ # has_many :people, :extend => FindOrCreateByNameExtension
206
+ # end
207
+ #
208
+ # class Company < BigRecord::Base
209
+ # has_many :people, :extend => FindOrCreateByNameExtension
210
+ # end
211
+ #
212
+ # If you need to use multiple named extension modules, you can specify an array of modules with the :extend option.
213
+ # In the case of name conflicts between methods in the modules, methods in modules later in the array supercede
214
+ # those earlier in the array. Example:
215
+ #
216
+ # class Account < BigRecord::Base
217
+ # has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
218
+ # end
219
+ #
220
+ # Some extensions can only be made to work with knowledge of the association proxy's internals.
221
+ # Extensions can access relevant state using accessors on the association proxy:
222
+ #
223
+ # * +proxy_owner+ - Returns the object the association is part of.
224
+ # * +proxy_reflection+ - Returns the reflection object that describes the association.
225
+ # * +proxy_target+ - Returns the associated object for belongs_to and has_one, or the collection of associated objects for has_many and has_and_belongs_to_many.
226
+ #
227
+ # === Association Join Models
228
+ #
229
+ # Has Many associations can be configured with the :through option to use an explicit join model to retrieve the data. This
230
+ # operates similarly to a <tt>has_and_belongs_to_many</tt> association. The advantage is that you're able to add validations,
231
+ # callbacks, and extra attributes on the join model. Consider the following schema:
232
+ #
233
+ # class Author < BigRecord::Base
234
+ # has_many :authorships
235
+ # has_many :books, :through => :authorships
236
+ # end
237
+ #
238
+ # class Authorship < BigRecord::Base
239
+ # belongs_to :author
240
+ # belongs_to :book
241
+ # end
242
+ #
243
+ # @author = Author.find :first
244
+ # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
245
+ # @author.books # selects all books by using the Authorship join model
246
+ #
247
+ # You can also go through a has_many association on the join model:
248
+ #
249
+ # class Firm < BigRecord::Base
250
+ # has_many :clients
251
+ # has_many :invoices, :through => :clients
252
+ # end
253
+ #
254
+ # class Client < BigRecord::Base
255
+ # belongs_to :firm
256
+ # has_many :invoices
257
+ # end
258
+ #
259
+ # class Invoice < BigRecord::Base
260
+ # belongs_to :client
261
+ # end
262
+ #
263
+ # @firm = Firm.find :first
264
+ # @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
265
+ # @firm.invoices # selects all invoices by going through the Client join model.
266
+ #
267
+ # === Polymorphic Associations
268
+ #
269
+ # Polymorphic associations on models are not restricted on what types of models they can be associated with. Rather, they
270
+ # specify an interface that a has_many association must adhere to.
271
+ #
272
+ # class Asset < BigRecord::Base
273
+ # belongs_to :attachable, :polymorphic => true
274
+ # end
275
+ #
276
+ # class Post < BigRecord::Base
277
+ # has_many :assets, :as => :attachable # The <tt>:as</tt> option specifies the polymorphic interface to use.
278
+ # end
279
+ #
280
+ # @asset.attachable = @post
281
+ #
282
+ # This works by using a type column in addition to a foreign key to specify the associated record. In the Asset example, you'd need
283
+ # an attachable_id integer column and an attachable_type string column.
284
+ #
285
+ # Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order
286
+ # for the associations to work as expected, ensure that you store the base model for the STI models in the
287
+ # type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts
288
+ # and member posts that use the posts table for STI. So there will be an additional 'type' column in the posts table.
289
+ #
290
+ # class Asset < BigRecord::Base
291
+ # belongs_to :attachable, :polymorphic => true
292
+ #
293
+ # def attachable_type=(sType)
294
+ # super(sType.to_s.classify.constantize.base_class.to_s)
295
+ # end
296
+ # end
297
+ #
298
+ # class Post < BigRecord::Base
299
+ # # because we store "Post" in attachable_type now :dependent => :destroy will work
300
+ # has_many :assets, :as => :attachable, :dependent => :destroy
301
+ # end
302
+ #
303
+ # class GuestPost < BigRecord::Base
304
+ # end
305
+ #
306
+ # class MemberPost < BigRecord::Base
307
+ # end
308
+ #
309
+ # == Caching
310
+ #
311
+ # All of the methods are built on a simple caching principle that will keep the result of the last query around unless specifically
312
+ # instructed not to. The cache is even shared across methods to make it even cheaper to use the macro-added methods without
313
+ # worrying too much about performance at the first go. Example:
314
+ #
315
+ # project.milestones # fetches milestones from the database
316
+ # project.milestones.size # uses the milestone cache
317
+ # project.milestones.empty? # uses the milestone cache
318
+ # project.milestones(true).size # fetches milestones from the database
319
+ # project.milestones # uses the milestone cache
320
+ #
321
+ # == Eager loading of associations
322
+ #
323
+ # Eager loading is a way to find objects of a certain class and a number of named associations along with it in a single SQL call. This is
324
+ # one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each needs to display their author
325
+ # triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 1. Example:
326
+ #
327
+ # class Post < BigRecord::Base
328
+ # belongs_to :author
329
+ # has_many :comments
330
+ # end
331
+ #
332
+ # Consider the following loop using the class above:
333
+ #
334
+ # for post in Post.find(:all)
335
+ # puts "Post: " + post.title
336
+ # puts "Written by: " + post.author.name
337
+ # puts "Last comment on: " + post.comments.first.created_on
338
+ # end
339
+ #
340
+ # To iterate over these one hundred posts, we'll generate 201 database queries. Let's first just optimize it for retrieving the author:
341
+ #
342
+ # for post in Post.find(:all, :include => :author)
343
+ #
344
+ # This references the name of the belongs_to association that also used the :author symbol, so the find will now weave in a join something
345
+ # like this: LEFT OUTER JOIN authors ON authors.id = posts.author_id. Doing so will cut down the number of queries from 201 to 101.
346
+ #
347
+ # We can improve upon the situation further by referencing both associations in the finder with:
348
+ #
349
+ # for post in Post.find(:all, :include => [ :author, :comments ])
350
+ #
351
+ # That'll add another join along the lines of: LEFT OUTER JOIN comments ON comments.post_id = posts.id. And we'll be down to 1 query.
352
+ # But that shouldn't fool you to think that you can pull out huge amounts of data with no performance penalty just because you've reduced
353
+ # the number of queries. The database still needs to send all the data to Active Record and it still needs to be processed. So it's no
354
+ # catch-all for performance problems, but it's a great way to cut down on the number of queries in a situation as the one described above.
355
+ #
356
+ # Since the eager loading pulls from multiple tables, you'll have to disambiguate any column references in both conditions and orders. So
357
+ # :order => "posts.id DESC" will work while :order => "id DESC" will not. Because eager loading generates the SELECT statement too, the
358
+ # :select option is ignored.
359
+ #
360
+ # You can use eager loading on multiple associations from the same table, but you cannot use those associations in orders and conditions
361
+ # as there is currently not any way to disambiguate them. Eager loading will not pull additional attributes on join tables, so "rich
362
+ # associations" with has_and_belongs_to_many are not a good fit for eager loading.
363
+ #
364
+ # When eager loaded, conditions are interpolated in the context of the model class, not the model instance. Conditions are lazily interpolated
365
+ # before the actual model exists.
366
+ #
367
+ # == Table Aliasing
368
+ #
369
+ # BigRecord uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once,
370
+ # the standard table name is used. The second time, the table is aliased as #{reflection_name}_#{parent_table_name}. Indexes are appended
371
+ # for any more successive uses of the table name.
372
+ #
373
+ # Post.find :all, :include => :comments
374
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ...
375
+ # Post.find :all, :include => :special_comments # STI
376
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... AND comments.type = 'SpecialComment'
377
+ # Post.find :all, :include => [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name
378
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... LEFT OUTER JOIN comments special_comments_posts
379
+ #
380
+ # Acts as tree example:
381
+ #
382
+ # TreeMixin.find :all, :include => :children
383
+ # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
384
+ # TreeMixin.find :all, :include => {:children => :parent} # using cascading eager includes
385
+ # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
386
+ # LEFT OUTER JOIN parents_mixins ...
387
+ # TreeMixin.find :all, :include => {:children => {:parent => :children}}
388
+ # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
389
+ # LEFT OUTER JOIN parents_mixins ...
390
+ # LEFT OUTER JOIN mixins childrens_mixins_2
391
+ #
392
+ # Has and Belongs to Many join tables use the same idea, but add a _join suffix:
393
+ #
394
+ # Post.find :all, :include => :categories
395
+ # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
396
+ # Post.find :all, :include => {:categories => :posts}
397
+ # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
398
+ # LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories
399
+ # Post.find :all, :include => {:categories => {:posts => :categories}}
400
+ # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
401
+ # LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories
402
+ # LEFT OUTER JOIN categories_posts categories_posts_join LEFT OUTER JOIN categories categories_posts
403
+ #
404
+ # If you wish to specify your own custom joins using a :joins option, those table names will take precedence over the eager associations..
405
+ #
406
+ # Post.find :all, :include => :comments, :joins => "inner join comments ..."
407
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments_posts ON ... INNER JOIN comments ...
408
+ # Post.find :all, :include => [:comments, :special_comments], :joins => "inner join comments ..."
409
+ # # => SELECT ... FROM posts LEFT OUTER JOIN comments comments_posts ON ...
410
+ # LEFT OUTER JOIN comments special_comments_posts ...
411
+ # INNER JOIN comments ...
412
+ #
413
+ # Table aliases are automatically truncated according to the maximum length of table identifiers according to the specific database.
414
+ #
415
+ # == Modules
416
+ #
417
+ # By default, associations will look for objects within the current module scope. Consider:
418
+ #
419
+ # module MyApplication
420
+ # module Business
421
+ # class Firm < BigRecord::Base
422
+ # has_many :clients
423
+ # end
424
+ #
425
+ # class Company < BigRecord::Base; end
426
+ # end
427
+ # end
428
+ #
429
+ # When Firm#clients is called, it'll in turn call <tt>MyApplication::Business::Company.find(firm.id)</tt>. If you want to associate
430
+ # with a class in another module scope this can be done by specifying the complete class name, such as:
431
+ #
432
+ # module MyApplication
433
+ # module Business
434
+ # class Firm < BigRecord::Base; end
435
+ # end
436
+ #
437
+ # module Billing
438
+ # class Account < BigRecord::Base
439
+ # belongs_to :firm, :class_name => "MyApplication::Business::Firm"
440
+ # end
441
+ # end
442
+ # end
443
+ #
444
+ # == Type safety with BigRecord::AssociationTypeMismatch
445
+ #
446
+ # If you attempt to assign an object to an association that doesn't match the inferred or specified <tt>:class_name</tt>, you'll
447
+ # get a BigRecord::AssociationTypeMismatch.
448
+ #
449
+ # == Options
450
+ #
451
+ # All of the association macros can be specialized through options which makes more complex cases than the simple and guessable ones
452
+ # possible.
453
+ module ClassMethods
454
+ # Adds the following methods for retrieval and query of collections of associated objects.
455
+ # +collection+ is replaced with the symbol passed as the first argument, so
456
+ # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.
457
+ # * <tt>collection(force_reload = false)</tt> - returns an array of all the associated objects.
458
+ # An empty array is returned if none are found.
459
+ # * <tt>collection<<(object, ...)</tt> - adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
460
+ # * <tt>collection.delete(object, ...)</tt> - removes one or more objects from the collection by setting their foreign keys to NULL.
461
+ # This will also destroy the objects if they're declared as belongs_to and dependent on this model.
462
+ # * <tt>collection=objects</tt> - replaces the collections content by deleting and adding objects as appropriate.
463
+ # * <tt>collection_singular_ids</tt> - returns an array of the associated objects ids
464
+ # * <tt>collection_singular_ids=ids</tt> - replace the collection by the objects identified by the primary keys in +ids+
465
+ # * <tt>collection.clear</tt> - removes every object from the collection. This destroys the associated objects if they
466
+ # are <tt>:dependent</tt>, deletes them directly from the database if they are <tt>:dependent => :delete_all</tt>,
467
+ # and sets their foreign keys to NULL otherwise.
468
+ # * <tt>collection.empty?</tt> - returns true if there are no associated objects.
469
+ # * <tt>collection.size</tt> - returns the number of associated objects.
470
+ # * <tt>collection.find</tt> - finds an associated object according to the same rules as Base.find.
471
+ # * <tt>collection.build(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
472
+ # with +attributes+ and linked to this object through a foreign key but has not yet been saved. *Note:* This only works if an
473
+ # associated object already exists, not if it's nil!
474
+ # * <tt>collection.create(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
475
+ # with +attributes+ and linked to this object through a foreign key and that has already been saved (if it passed the validation).
476
+ # *Note:* This only works if an associated object already exists, not if it's nil!
477
+ #
478
+ # Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
479
+ # * <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => "firm_id = #{id}"</tt>)
480
+ # * <tt>Firm#clients<<</tt>
481
+ # * <tt>Firm#clients.delete</tt>
482
+ # * <tt>Firm#clients=</tt>
483
+ # * <tt>Firm#client_ids</tt>
484
+ # * <tt>Firm#client_ids=</tt>
485
+ # * <tt>Firm#clients.clear</tt>
486
+ # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
487
+ # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
488
+ # * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
489
+ # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
490
+ # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
491
+ # The declaration can also include an options hash to specialize the behavior of the association.
492
+ #
493
+ # Options are:
494
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
495
+ # from the association name. So <tt>has_many :products</tt> will by default be linked to the +Product+ class, but
496
+ # if the real class name is +SpecialProduct+, you'll have to specify it with this option.
497
+ # * <tt>:conditions</tt> - specify the conditions that the associated objects must meet in order to be included as a "WHERE"
498
+ # sql fragment, such as "price > 5 AND name LIKE 'B%'".
499
+ # * <tt>:order</tt> - specify the order in which the associated objects are returned as a "ORDER BY" sql fragment,
500
+ # such as "last_name, first_name DESC"
501
+ # * <tt>:group</tt> - specify the attribute by which the associated objects are returned as a "GROUP BY" sql fragment,
502
+ # such as "category"
503
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
504
+ # of this class in lower-case and "_id" suffixed. So a +Person+ class that makes a has_many association will use "person_id"
505
+ # as the default foreign_key.
506
+ # * <tt>:dependent</tt> - if set to :destroy all the associated objects are destroyed
507
+ # alongside this object by calling their destroy method. If set to :delete_all all associated
508
+ # objects are deleted *without* calling their destroy method. If set to :nullify all associated
509
+ # objects' foreign keys are set to NULL *without* calling their save callbacks.
510
+ # NOTE: :dependent => true is deprecated and has been replaced with :dependent => :destroy.
511
+ # May not be set if :exclusively_dependent is also set.
512
+ # * <tt>:exclusively_dependent</tt> - Deprecated; equivalent to :dependent => :delete_all. If set to true all
513
+ # the associated object are deleted in one SQL statement without having their
514
+ # before_destroy callback run. This should only be used on associations that depend solely on this class and don't need to do any
515
+ # clean-up in before_destroy. The upside is that it's much faster, especially if there's a counter_cache involved.
516
+ # May not be set if :dependent is also set.
517
+ # * <tt>:finder_sql</tt> - specify a complete SQL statement to fetch the association. This is a good way to go for complex
518
+ # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+ is _not_ added.
519
+ # * <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is
520
+ # specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM.
521
+ # * <tt>:extend</tt> - specify a named module for extending the proxy, see "Association extensions".
522
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when the collection is loaded.
523
+ # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
524
+ # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned.
525
+ # * <tt>:offset</tt>: An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
526
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
527
+ # include the joined columns.
528
+ # * <tt>:as</tt>: Specifies a polymorphic interface (See #belongs_to).
529
+ # * <tt>:through</tt>: Specifies a Join Model to perform the query through. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
530
+ # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>
531
+ # or <tt>has_many</tt> association.
532
+ # * <tt>:source</tt>: Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
533
+ # inferred from the association. <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either +:subscribers+ or
534
+ # +:subscriber+ on +Subscription+, unless a +:source+ is given.
535
+ # * <tt>:source_type</tt>: Specifies type of the source association used by <tt>has_many :through</tt> queries where the source association
536
+ # is a polymorphic belongs_to.
537
+ # * <tt>:uniq</tt> - if set to true, duplicates will be omitted from the collection. Useful in conjunction with :through.
538
+ #
539
+ # Option examples:
540
+ # has_many :comments, :order => "posted_on"
541
+ # has_many :comments, :include => :author
542
+ # has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
543
+ # has_many :tracks, :order => "position", :dependent => :destroy
544
+ # has_many :comments, :dependent => :nullify
545
+ # has_many :tags, :as => :taggable
546
+ # has_many :subscribers, :through => :subscriptions, :source => :user
547
+ # has_many :subscribers, :class_name => "Person", :finder_sql =>
548
+ # 'SELECT DISTINCT people.* ' +
549
+ # 'FROM people p, post_subscriptions ps ' +
550
+ # 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
551
+ # 'ORDER BY p.first_name'
552
+ def has_many(association_id, options = {}, &extension)
553
+ reflection = create_has_many_reflection(association_id, options, &extension)
554
+
555
+ configure_dependency_for_has_many(reflection)
556
+
557
+ if options[:through]
558
+ collection_reader_method(reflection, HasManyThroughAssociation)
559
+ else
560
+ add_multiple_associated_save_callbacks(reflection.name)
561
+ add_association_callbacks(reflection.name, reflection.options)
562
+ collection_accessor_methods(reflection, HasManyAssociation)
563
+ end
564
+ end
565
+
566
+ # Adds the following methods for retrieval and query of a single associated object.
567
+ # +association+ is replaced with the symbol passed as the first argument, so
568
+ # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.
569
+ # * <tt>association(force_reload = false)</tt> - returns the associated object. Nil is returned if none is found.
570
+ # * <tt>association=(associate)</tt> - assigns the associate object, extracts the primary key, sets it as the foreign key,
571
+ # and saves the associate object.
572
+ # * <tt>association.nil?</tt> - returns true if there is no associated object.
573
+ # * <tt>build_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
574
+ # with +attributes+ and linked to this object through a foreign key but has not yet been saved. Note: This ONLY works if
575
+ # an association already exists. It will NOT work if the association is nil.
576
+ # * <tt>create_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
577
+ # with +attributes+ and linked to this object through a foreign key and that has already been saved (if it passed the validation).
578
+ #
579
+ # Example: An Account class declares <tt>has_one :beneficiary</tt>, which will add:
580
+ # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>)
581
+ # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
582
+ # * <tt>Account#beneficiary.nil?</tt>
583
+ # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
584
+ # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
585
+ #
586
+ # The declaration can also include an options hash to specialize the behavior of the association.
587
+ #
588
+ # Options are:
589
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
590
+ # from the association name. So <tt>has_one :manager</tt> will by default be linked to the +Manager+ class, but
591
+ # if the real class name is +Person+, you'll have to specify it with this option.
592
+ # * <tt>:conditions</tt> - specify the conditions that the associated object must meet in order to be included as a "WHERE"
593
+ # sql fragment, such as "rank = 5".
594
+ # * <tt>:order</tt> - specify the order from which the associated object will be picked at the top. Specified as
595
+ # an "ORDER BY" sql fragment, such as "last_name, first_name DESC"
596
+ # * <tt>:dependent</tt> - if set to :destroy (or true) the associated object is destroyed when this object is. If set to
597
+ # :delete the associated object is deleted *without* calling its destroy method. If set to :nullify the associated
598
+ # object's foreign key is set to NULL. Also, association is assigned.
599
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
600
+ # of this class in lower-case and "_id" suffixed. So a +Person+ class that makes a has_one association will use "person_id"
601
+ # as the default foreign_key.
602
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when this object is loaded.
603
+ # * <tt>:as</tt>: Specifies a polymorphic interface (See #belongs_to).
604
+ #
605
+ # Option examples:
606
+ # has_one :credit_card, :dependent => :destroy # destroys the associated credit card
607
+ # has_one :credit_card, :dependent => :nullify # updates the associated records foriegn key value to null rather than destroying it
608
+ # has_one :last_comment, :class_name => "Comment", :order => "posted_on"
609
+ # has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
610
+ # has_one :attachment, :as => :attachable
611
+ def has_one(association_id, options = {})
612
+ reflection = create_has_one_reflection(association_id, options)
613
+
614
+ module_eval do
615
+ after_save <<-EOF
616
+ association = instance_variable_get("@#{reflection.name}")
617
+ if !association.nil? && (new_record? || association.new_record? || association["#{reflection.primary_key_name}"] != id)
618
+ association["#{reflection.primary_key_name}"] = id
619
+ association.save(true)
620
+ end
621
+ EOF
622
+ end
623
+
624
+ association_accessor_methods(reflection, HasOneAssociation)
625
+ association_constructor_method(:build, reflection, HasOneAssociation)
626
+ association_constructor_method(:create, reflection, HasOneAssociation)
627
+
628
+ configure_dependency_for_has_one(reflection)
629
+ end
630
+
631
+ # Adds the following methods for retrieval and query for a single associated object that this object holds an id to.
632
+ # +association+ is replaced with the symbol passed as the first argument, so
633
+ # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.
634
+ # * <tt>association(force_reload = false)</tt> - returns the associated object. Nil is returned if none is found.
635
+ # * <tt>association=(associate)</tt> - assigns the associate object, extracts the primary key, and sets it as the foreign key.
636
+ # * <tt>association.nil?</tt> - returns true if there is no associated object.
637
+ # * <tt>build_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
638
+ # with +attributes+ and linked to this object through a foreign key but has not yet been saved.
639
+ # * <tt>create_association(attributes = {})</tt> - returns a new object of the associated type that has been instantiated
640
+ # with +attributes+ and linked to this object through a foreign key and that has already been saved (if it passed the validation).
641
+ #
642
+ # Example: A Post class declares <tt>belongs_to :author</tt>, which will add:
643
+ # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
644
+ # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
645
+ # * <tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)
646
+ # * <tt>Post#author.nil?</tt>
647
+ # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
648
+ # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
649
+ # The declaration can also include an options hash to specialize the behavior of the association.
650
+ #
651
+ # Options are:
652
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
653
+ # from the association name. So <tt>has_one :author</tt> will by default be linked to the +Author+ class, but
654
+ # if the real class name is +Person+, you'll have to specify it with this option.
655
+ # * <tt>:conditions</tt> - specify the conditions that the associated object must meet in order to be included as a "WHERE"
656
+ # sql fragment, such as "authorized = 1".
657
+ # * <tt>:order</tt> - specify the order from which the associated object will be picked at the top. Specified as
658
+ # an "ORDER BY" sql fragment, such as "last_name, first_name DESC"
659
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
660
+ # of the associated class in lower-case and "_id" suffixed. So a +Person+ class that makes a belongs_to association to a
661
+ # +Boss+ class will use "boss_id" as the default foreign_key.
662
+ # * <tt>:counter_cache</tt> - caches the number of belonging objects on the associate class through use of increment_counter
663
+ # and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it's
664
+ # destroyed. This requires that a column named "#{table_name}_count" (such as comments_count for a belonging Comment class)
665
+ # is used on the associate class (such as a Post class). You can also specify a custom counter cache column by given that
666
+ # name instead of a true/false value to this option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
667
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when this object is loaded.
668
+ # * <tt>:polymorphic</tt> - specify this association is a polymorphic association by passing true.
669
+ #
670
+ # Option examples:
671
+ # belongs_to :firm, :foreign_key => "client_of"
672
+ # belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
673
+ # belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
674
+ # :conditions => 'discounts > #{payments_count}'
675
+ # belongs_to :attachable, :polymorphic => true
676
+ def belongs_to(association_id, options = {})
677
+ if options.include?(:class_name) && !options.include?(:foreign_key)
678
+ ::ActiveSupport::Deprecation.warn(
679
+ "The inferred foreign_key name will change in Rails 2.0 to use the association name instead of its class name when they differ. When using :class_name in belongs_to, use the :foreign_key option to explicitly set the key name to avoid problems in the transition.",
680
+ caller)
681
+ end
682
+
683
+ reflection = create_belongs_to_reflection(association_id, options)
684
+
685
+ if reflection.options[:polymorphic]
686
+ association_accessor_methods(reflection, BelongsToPolymorphicAssociation)
687
+
688
+ module_eval do
689
+ before_save <<-EOF
690
+ association = instance_variable_get("@#{reflection.name}")
691
+ if association && association.target
692
+ if association.new_record?
693
+ association.save(true)
694
+ end
695
+
696
+ if association.updated?
697
+ self["#{reflection.primary_key_name}"] = association.id
698
+ self["#{reflection.options[:foreign_type]}"] = association.class.base_class.name.to_s
699
+ end
700
+ end
701
+ EOF
702
+ end
703
+ else
704
+ association_accessor_methods(reflection, BelongsToAssociation)
705
+ association_constructor_method(:build, reflection, BelongsToAssociation)
706
+ association_constructor_method(:create, reflection, BelongsToAssociation)
707
+
708
+ module_eval do
709
+ before_save <<-EOF
710
+ association = instance_variable_get("@#{reflection.name}")
711
+ if !association.nil?
712
+ if association.new_record?
713
+ association.save(true)
714
+ end
715
+
716
+ if association.updated?
717
+ self["#{reflection.primary_key_name}"] = association.id
718
+ end
719
+ end
720
+ EOF
721
+ end
722
+ end
723
+
724
+ if options[:counter_cache]
725
+ cache_column = options[:counter_cache] == true ?
726
+ "#{self.to_s.underscore.pluralize}_count" :
727
+ options[:counter_cache]
728
+
729
+ module_eval(
730
+ "after_create '#{reflection.name}.class.increment_counter(\"#{cache_column}\", #{reflection.primary_key_name})" +
731
+ " unless #{reflection.name}.nil?'"
732
+ )
733
+
734
+ module_eval(
735
+ "before_destroy '#{reflection.name}.class.decrement_counter(\"#{cache_column}\", #{reflection.primary_key_name})" +
736
+ " unless #{reflection.name}.nil?'"
737
+ )
738
+ end
739
+ end
740
+
741
+ # Associates two classes via an intermediate join table. Unless the join table is explicitly specified as
742
+ # an option, it is guessed using the lexical order of the class names. So a join between Developer and Project
743
+ # will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
744
+ # is calculated using the <tt><</tt> operator for <tt>String</tt>. This means that if the strings are of different lengths,
745
+ # and the strings are equal when compared up to the shortest length, then the longer string is considered of higher
746
+ # lexical precedence than the shorter one. For example, one would expect the tables <tt>paper_boxes</tt> and <tt>papers</tt>
747
+ # to generate a join table name of <tt>papers_paper_boxes</tt> because of the length of the name <tt>paper_boxes</tt>,
748
+ # but it in fact generates a join table name of <tt>paper_boxes_papers</tt>. Be aware of this caveat, and use the
749
+ # custom <tt>join_table</tt> option if you need to.
750
+ #
751
+ # Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through
752
+ # has_and_belongs_to_many associations. Records returned from join tables with additional attributes will be marked as
753
+ # ReadOnly (because we can't save changes to the additional attrbutes). It's strongly recommended that you upgrade any
754
+ # associations with attributes to a real join model (see introduction).
755
+ #
756
+ # Adds the following methods for retrieval and query.
757
+ # +collection+ is replaced with the symbol passed as the first argument, so
758
+ # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.
759
+ # * <tt>collection(force_reload = false)</tt> - returns an array of all the associated objects.
760
+ # An empty array is returned if none is found.
761
+ # * <tt>collection<<(object, ...)</tt> - adds one or more objects to the collection by creating associations in the join table
762
+ # (collection.push and collection.concat are aliases to this method).
763
+ # * <tt>collection.push_with_attributes(object, join_attributes)</tt> - adds one to the collection by creating an association in the join table that
764
+ # also holds the attributes from <tt>join_attributes</tt> (should be a hash with the column names as keys). This can be used to have additional
765
+ # attributes on the join, which will be injected into the associated objects when they are retrieved through the collection.
766
+ # (collection.concat_with_attributes is an alias to this method). This method is now deprecated.
767
+ # * <tt>collection.delete(object, ...)</tt> - removes one or more objects from the collection by removing their associations from the join table.
768
+ # This does not destroy the objects.
769
+ # * <tt>collection=objects</tt> - replaces the collections content by deleting and adding objects as appropriate.
770
+ # * <tt>collection_singular_ids</tt> - returns an array of the associated objects ids
771
+ # * <tt>collection_singular_ids=ids</tt> - replace the collection by the objects identified by the primary keys in +ids+
772
+ # * <tt>collection.clear</tt> - removes every object from the collection. This does not destroy the objects.
773
+ # * <tt>collection.empty?</tt> - returns true if there are no associated objects.
774
+ # * <tt>collection.size</tt> - returns the number of associated objects.
775
+ # * <tt>collection.find(id)</tt> - finds an associated object responding to the +id+ and that
776
+ # meets the condition that it has to be associated with this object.
777
+ # * <tt>collection.build(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
778
+ # with +attributes+ and linked to this object through the join table but has not yet been saved.
779
+ # * <tt>collection.create(attributes = {})</tt> - returns a new object of the collection type that has been instantiated
780
+ # with +attributes+ and linked to this object through the join table and that has already been saved (if it passed the validation).
781
+ #
782
+ # Example: An Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
783
+ # * <tt>Developer#projects</tt>
784
+ # * <tt>Developer#projects<<</tt>
785
+ # * <tt>Developer#projects.delete</tt>
786
+ # * <tt>Developer#projects=</tt>
787
+ # * <tt>Developer#project_ids</tt>
788
+ # * <tt>Developer#project_ids=</tt>
789
+ # * <tt>Developer#projects.clear</tt>
790
+ # * <tt>Developer#projects.empty?</tt>
791
+ # * <tt>Developer#projects.size</tt>
792
+ # * <tt>Developer#projects.find(id)</tt>
793
+ # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("project_id" => id)</tt>)
794
+ # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("project_id" => id); c.save; c</tt>)
795
+ # The declaration may include an options hash to specialize the behavior of the association.
796
+ #
797
+ # Options are:
798
+ # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
799
+ # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
800
+ # +Project+ class, but if the real class name is +SuperProject+, you'll have to specify it with this option.
801
+ # * <tt>:join_table</tt> - specify the name of the join table if the default based on lexical order isn't what you want.
802
+ # WARNING: If you're overwriting the table name of either class, the table_name method MUST be declared underneath any
803
+ # has_and_belongs_to_many declaration in order to work.
804
+ # * <tt>:foreign_key</tt> - specify the foreign key used for the association. By default this is guessed to be the name
805
+ # of this class in lower-case and "_id" suffixed. So a +Person+ class that makes a has_and_belongs_to_many association
806
+ # will use "person_id" as the default foreign_key.
807
+ # * <tt>:association_foreign_key</tt> - specify the association foreign key used for the association. By default this is
808
+ # guessed to be the name of the associated class in lower-case and "_id" suffixed. So if the associated class is +Project+,
809
+ # the has_and_belongs_to_many association will use "project_id" as the default association foreign_key.
810
+ # * <tt>:conditions</tt> - specify the conditions that the associated object must meet in order to be included as a "WHERE"
811
+ # sql fragment, such as "authorized = 1".
812
+ # * <tt>:order</tt> - specify the order in which the associated objects are returned as a "ORDER BY" sql fragment, such as "last_name, first_name DESC"
813
+ # * <tt>:uniq</tt> - if set to true, duplicate associated objects will be ignored by accessors and query methods
814
+ # * <tt>:finder_sql</tt> - overwrite the default generated SQL used to fetch the association with a manual one
815
+ # * <tt>:delete_sql</tt> - overwrite the default generated SQL used to remove links between the associated
816
+ # classes with a manual one
817
+ # * <tt>:insert_sql</tt> - overwrite the default generated SQL used to add links between the associated classes
818
+ # with a manual one
819
+ # * <tt>:extend</tt> - anonymous module for extending the proxy, see "Association extensions".
820
+ # * <tt>:include</tt> - specify second-order associations that should be eager loaded when the collection is loaded.
821
+ # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
822
+ # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned.
823
+ # * <tt>:offset</tt>: An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
824
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
825
+ # include the joined columns.
826
+ #
827
+ # Option examples:
828
+ # has_and_belongs_to_many :projects
829
+ # has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
830
+ # has_and_belongs_to_many :nations, :class_name => "Country"
831
+ # has_and_belongs_to_many :categories, :join_table => "prods_cats"
832
+ # has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
833
+ # 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
834
+ def has_and_belongs_to_many(association_id, options = {}, &extension)
835
+ reflection = create_has_and_belongs_to_many_reflection(association_id, options, &extension)
836
+
837
+ add_multiple_associated_save_callbacks(reflection.name)
838
+ collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
839
+
840
+ # Don't use a before_destroy callback since users' before_destroy
841
+ # callbacks will be executed after the association is wiped out.
842
+ old_method = "destroy_without_habtm_shim_for_#{reflection.name}"
843
+ class_eval <<-end_eval
844
+ alias_method :#{old_method}, :destroy_without_callbacks
845
+ def destroy_without_callbacks
846
+ #{reflection.name}.clear
847
+ #{old_method}
848
+ end
849
+ end_eval
850
+
851
+ add_association_callbacks(reflection.name, options)
852
+ end
853
+
854
+ private
855
+ def join_table_name(first_table_name, second_table_name)
856
+ if first_table_name < second_table_name
857
+ join_table = "#{first_table_name}_#{second_table_name}"
858
+ else
859
+ join_table = "#{second_table_name}_#{first_table_name}"
860
+ end
861
+
862
+ table_name_prefix + join_table + table_name_suffix
863
+ end
864
+
865
+ def association_accessor_methods(reflection, association_proxy_class)
866
+ define_method(reflection.name) do |*params|
867
+ force_reload = params.first unless params.empty?
868
+ association = instance_variable_get("@#{reflection.name}")
869
+
870
+ if association.nil? || force_reload
871
+ association = association_proxy_class.new(self, reflection)
872
+ retval = association.reload
873
+ if retval.nil? and association_proxy_class == BelongsToAssociation
874
+ instance_variable_set("@#{reflection.name}", nil)
875
+ return nil
876
+ end
877
+ instance_variable_set("@#{reflection.name}", association)
878
+ end
879
+
880
+ association.target.nil? ? nil : association
881
+ end
882
+
883
+ define_method("#{reflection.name}=") do |new_value|
884
+ association = instance_variable_get("@#{reflection.name}")
885
+ if association.nil?
886
+ association = association_proxy_class.new(self, reflection)
887
+ end
888
+
889
+ association.replace(new_value)
890
+
891
+ unless new_value.nil?
892
+ instance_variable_set("@#{reflection.name}", association)
893
+ else
894
+ instance_variable_set("@#{reflection.name}", nil)
895
+ return nil
896
+ end
897
+
898
+ association
899
+ end
900
+
901
+ define_method("set_#{reflection.name}_target") do |target|
902
+ return if target.nil? and association_proxy_class == BelongsToAssociation
903
+ association = association_proxy_class.new(self, reflection)
904
+ association.target = target
905
+ instance_variable_set("@#{reflection.name}", association)
906
+ end
907
+ end
908
+
909
+ def collection_reader_method(reflection, association_proxy_class)
910
+ define_method(reflection.name) do |*params|
911
+ force_reload = params.first unless params.empty?
912
+ association = instance_variable_get("@#{reflection.name}")
913
+
914
+ unless association.respond_to?(:loaded?)
915
+ association = association_proxy_class.new(self, reflection)
916
+ instance_variable_set("@#{reflection.name}", association)
917
+ end
918
+
919
+ association.reload if force_reload
920
+
921
+ association
922
+ end
923
+ end
924
+
925
+ def collection_accessor_methods(reflection, association_proxy_class)
926
+ collection_reader_method(reflection, association_proxy_class)
927
+
928
+ define_method("#{reflection.name}=") do |new_value|
929
+ # Loads proxy class instance (defined in collection_reader_method) if not already loaded
930
+ association = send(reflection.name)
931
+ association.replace(new_value)
932
+ association
933
+ end
934
+
935
+ define_method("#{reflection.name.to_s.singularize}_ids") do
936
+ send(reflection.name).map(&:id)
937
+ end
938
+
939
+ define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value|
940
+ ids = (new_value || []).reject { |nid| nid.blank? }
941
+ send("#{reflection.name}=", reflection.class_name.constantize.find(ids))
942
+ end
943
+ end
944
+
945
+ def add_multiple_associated_save_callbacks(association_name)
946
+ method_name = "validate_associated_records_for_#{association_name}".to_sym
947
+ define_method(method_name) do
948
+ association = instance_variable_get("@#{association_name}")
949
+ if association.respond_to?(:loaded?)
950
+ if new_record?
951
+ association
952
+ else
953
+ association.select { |record| record.new_record? }
954
+ end.each do |record|
955
+ errors.add "#{association_name}" unless record.valid?
956
+ end
957
+ end
958
+ end
959
+
960
+ validate method_name
961
+ before_save("@new_record_before_save = new_record?; true")
962
+
963
+ after_callback = <<-end_eval
964
+ association = instance_variable_get("@#{association_name}")
965
+
966
+ if association.respond_to?(:loaded?)
967
+ if @new_record_before_save
968
+ records_to_save = association
969
+ else
970
+ records_to_save = association.select { |record| record.new_record? }
971
+ end
972
+ records_to_save.each { |record| association.send(:insert_record, record) }
973
+ association.send(:construct_sql) # reconstruct the SQL queries now that we know the owner's id
974
+ end
975
+ end_eval
976
+
977
+ # Doesn't use after_save as that would save associations added in after_create/after_update twice
978
+ after_create(after_callback)
979
+ after_update(after_callback)
980
+ end
981
+
982
+ def association_constructor_method(constructor, reflection, association_proxy_class)
983
+ define_method("#{constructor}_#{reflection.name}") do |*params|
984
+ attributees = params.first unless params.empty?
985
+ replace_existing = params[1].nil? ? true : params[1]
986
+ association = instance_variable_get("@#{reflection.name}")
987
+
988
+ if association.nil?
989
+ association = association_proxy_class.new(self, reflection)
990
+ instance_variable_set("@#{reflection.name}", association)
991
+ end
992
+
993
+ if association_proxy_class == HasOneAssociation
994
+ association.send(constructor, attributees, replace_existing)
995
+ else
996
+ association.send(constructor, attributees)
997
+ end
998
+ end
999
+ end
1000
+
1001
+ def find_with_associations(options = {})
1002
+ catch :invalid_query do
1003
+ join_dependency = JoinDependency.new(self, merge_includes(scope(:find, :include), options[:include]), options[:joins])
1004
+ rows = select_all_rows(options, join_dependency)
1005
+ return join_dependency.instantiate(rows)
1006
+ end
1007
+ []
1008
+ end
1009
+
1010
+ def configure_dependency_for_has_many(reflection)
1011
+ if reflection.options[:dependent] == true
1012
+ ::ActiveSupport::Deprecation.warn("The :dependent => true option is deprecated and will be removed from Rails 2.0. Please use :dependent => :destroy instead. See http://www.rubyonrails.org/deprecation for details.", caller)
1013
+ end
1014
+
1015
+ if reflection.options[:dependent] && reflection.options[:exclusively_dependent]
1016
+ raise ArgumentError, ':dependent and :exclusively_dependent are mutually exclusive options. You may specify one or the other.'
1017
+ end
1018
+
1019
+ if reflection.options[:exclusively_dependent]
1020
+ reflection.options[:dependent] = :delete_all
1021
+ ::ActiveSupport::Deprecation.warn("The :exclusively_dependent option is deprecated and will be removed from Rails 2.0. Please use :dependent => :delete_all instead. See http://www.rubyonrails.org/deprecation for details.", caller)
1022
+ end
1023
+
1024
+ # See HasManyAssociation#delete_records. Dependent associations
1025
+ # delete children, otherwise foreign key is set to NULL.
1026
+
1027
+ # Add polymorphic type if the :as option is present
1028
+ dependent_conditions = %(#{reflection.primary_key_name} = \#{record.quoted_id})
1029
+ if reflection.options[:as]
1030
+ dependent_conditions += " AND #{reflection.options[:as]}_type = '#{base_class.name}'"
1031
+ end
1032
+
1033
+ case reflection.options[:dependent]
1034
+ when :destroy, true
1035
+ module_eval "before_destroy '#{reflection.name}.each { |o| o.destroy }'"
1036
+ when :delete_all
1037
+ module_eval "before_destroy { |record| #{reflection.class_name}.delete_all(%(#{dependent_conditions})) }"
1038
+ when :nullify
1039
+ module_eval "before_destroy { |record| #{reflection.class_name}.update_all(%(#{reflection.primary_key_name} = NULL), %(#{dependent_conditions})) }"
1040
+ when nil, false
1041
+ # pass
1042
+ else
1043
+ raise ArgumentError, 'The :dependent option expects either :destroy, :delete_all, or :nullify'
1044
+ end
1045
+ end
1046
+
1047
+ def configure_dependency_for_has_one(reflection)
1048
+ case reflection.options[:dependent]
1049
+ when :destroy, true
1050
+ module_eval "before_destroy '#{reflection.name}.destroy unless #{reflection.name}.nil?'"
1051
+ when :delete
1052
+ module_eval "before_destroy '#{reflection.class_name}.delete(#{reflection.name}.id) unless #{reflection.name}.nil?'"
1053
+ when :nullify
1054
+ module_eval "before_destroy '#{reflection.name}.update_attribute(\"#{reflection.primary_key_name}\", nil) unless #{reflection.name}.nil?'"
1055
+ when nil, false
1056
+ # pass
1057
+ else
1058
+ raise ArgumentError, "The :dependent option expects either :destroy, :delete or :nullify."
1059
+ end
1060
+ end
1061
+
1062
+
1063
+ def add_deprecated_api_for_has_many(association_name)
1064
+ deprecated_collection_count_method(association_name)
1065
+ deprecated_add_association_relation(association_name)
1066
+ deprecated_remove_association_relation(association_name)
1067
+ deprecated_has_collection_method(association_name)
1068
+ deprecated_find_in_collection_method(association_name)
1069
+ deprecated_find_all_in_collection_method(association_name)
1070
+ deprecated_collection_create_method(association_name)
1071
+ deprecated_collection_build_method(association_name)
1072
+ end
1073
+
1074
+ def create_has_many_reflection(association_id, options, &extension)
1075
+ options.assert_valid_keys(
1076
+ :class_name, :table_name, :foreign_key,
1077
+ :exclusively_dependent, :dependent,
1078
+ :select, :conditions, :include, :order, :group, :limit, :offset,
1079
+ :as, :through, :source, :source_type,
1080
+ :uniq,
1081
+ :finder_sql, :counter_sql,
1082
+ :before_add, :after_add, :before_remove, :after_remove,
1083
+ :extend
1084
+ )
1085
+
1086
+ options[:extend] = create_extension_module(association_id, extension) if block_given?
1087
+
1088
+ create_reflection(:has_many, association_id, options, self)
1089
+ end
1090
+
1091
+ def create_has_one_reflection(association_id, options)
1092
+ options.assert_valid_keys(
1093
+ :class_name, :foreign_key, :remote, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as
1094
+ )
1095
+
1096
+ create_reflection(:has_one, association_id, options, self)
1097
+ end
1098
+
1099
+ def create_belongs_to_reflection(association_id, options)
1100
+ options.assert_valid_keys(
1101
+ :class_name, :foreign_key, :foreign_type, :remote, :conditions, :order, :include, :dependent,
1102
+ :counter_cache, :extend, :polymorphic
1103
+ )
1104
+
1105
+ reflection = create_reflection(:belongs_to, association_id, options, self)
1106
+
1107
+ if options[:polymorphic]
1108
+ reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
1109
+ end
1110
+
1111
+ reflection
1112
+ end
1113
+
1114
+ def create_has_and_belongs_to_many_reflection(association_id, options, &extension)
1115
+ options.assert_valid_keys(
1116
+ :class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
1117
+ :select, :conditions, :include, :order, :group, :limit, :offset,
1118
+ :uniq,
1119
+ :finder_sql, :delete_sql, :insert_sql,
1120
+ :before_add, :after_add, :before_remove, :after_remove,
1121
+ :extend
1122
+ )
1123
+
1124
+ options[:extend] = create_extension_module(association_id, extension) if block_given?
1125
+
1126
+ reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)
1127
+
1128
+ reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
1129
+
1130
+ reflection
1131
+ end
1132
+
1133
+ def reflect_on_included_associations(associations)
1134
+ [ associations ].flatten.collect { |association| reflect_on_association(association.to_s.intern) }
1135
+ end
1136
+
1137
+ def guard_against_unlimitable_reflections(reflections, options)
1138
+ if (options[:offset] || options[:limit]) && !using_limitable_reflections?(reflections)
1139
+ raise(
1140
+ ConfigurationError,
1141
+ "You can not use offset and limit together with has_many or has_and_belongs_to_many associations"
1142
+ )
1143
+ end
1144
+ end
1145
+
1146
+ def select_all_rows(options, join_dependency)
1147
+ connection.select_all(
1148
+ construct_finder_sql_with_included_associations(options, join_dependency),
1149
+ "#{name} Load Including Associations"
1150
+ )
1151
+ end
1152
+
1153
+ def construct_finder_sql_with_included_associations(options, join_dependency)
1154
+ scope = scope(:find)
1155
+ sql = "SELECT #{column_aliases(join_dependency)} FROM #{(scope && scope[:from]) || options[:from] || table_name} "
1156
+ sql << join_dependency.join_associations.collect{|join| join.association_join }.join
1157
+
1158
+ add_joins!(sql, options, scope)
1159
+ add_conditions!(sql, options[:conditions], scope)
1160
+ add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
1161
+
1162
+ sql << "GROUP BY #{options[:group]} " if options[:group]
1163
+
1164
+ add_order!(sql, options[:order], scope)
1165
+ add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections)
1166
+ add_lock!(sql, options, scope)
1167
+
1168
+ return sanitize_sql(sql)
1169
+ end
1170
+
1171
+ def add_limited_ids_condition!(sql, options, join_dependency)
1172
+ unless (id_list = select_limited_ids_list(options, join_dependency)).empty?
1173
+ sql << "#{condition_word(sql)} #{table_name}.#{primary_key} IN (#{id_list}) "
1174
+ else
1175
+ throw :invalid_query
1176
+ end
1177
+ end
1178
+
1179
+ def select_limited_ids_list(options, join_dependency)
1180
+ connection.select_all(
1181
+ construct_finder_sql_for_association_limiting(options, join_dependency),
1182
+ "#{name} Load IDs For Limited Eager Loading"
1183
+ ).collect { |row| connection.quote(row[primary_key]) }.join(", ")
1184
+ end
1185
+
1186
+ def construct_finder_sql_for_association_limiting(options, join_dependency)
1187
+ scope = scope(:find)
1188
+ is_distinct = include_eager_conditions?(options) || include_eager_order?(options)
1189
+ sql = "SELECT "
1190
+ if is_distinct
1191
+ sql << connection.distinct("#{table_name}.#{primary_key}", options[:order])
1192
+ else
1193
+ sql << primary_key
1194
+ end
1195
+ sql << " FROM #{table_name} "
1196
+
1197
+ if is_distinct
1198
+ sql << join_dependency.join_associations.collect(&:association_join).join
1199
+ add_joins!(sql, options, scope)
1200
+ end
1201
+
1202
+ add_conditions!(sql, options[:conditions], scope)
1203
+ if options[:order]
1204
+ if is_distinct
1205
+ connection.add_order_by_for_association_limiting!(sql, options)
1206
+ else
1207
+ sql << "ORDER BY #{options[:order]}"
1208
+ end
1209
+ end
1210
+ add_limit!(sql, options, scope)
1211
+ return sanitize_sql(sql)
1212
+ end
1213
+
1214
+ # Checks if the conditions reference a table other than the current model table
1215
+ def include_eager_conditions?(options)
1216
+ # look in both sets of conditions
1217
+ conditions = [scope(:find, :conditions), options[:conditions]].inject([]) do |all, cond|
1218
+ case cond
1219
+ when nil then all
1220
+ when Array then all << cond.first
1221
+ else all << cond
1222
+ end
1223
+ end
1224
+ return false unless conditions.any?
1225
+ conditions.join(' ').scan(/([\.\w]+)\.\w+/).flatten.any? do |condition_table_name|
1226
+ condition_table_name != table_name
1227
+ end
1228
+ end
1229
+
1230
+ # Checks if the query order references a table other than the current model's table.
1231
+ def include_eager_order?(options)
1232
+ order = options[:order]
1233
+ return false unless order
1234
+ order.scan(/([\.\w]+)\.\w+/).flatten.any? do |order_table_name|
1235
+ order_table_name != table_name
1236
+ end
1237
+ end
1238
+
1239
+ def using_limitable_reflections?(reflections)
1240
+ reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero?
1241
+ end
1242
+
1243
+ def column_aliases(join_dependency)
1244
+ join_dependency.joins.collect{|join| join.column_names_with_alias.collect{|column_name, aliased_name|
1245
+ "#{join.aliased_table_name}.#{connection.quote_column_name column_name} AS #{aliased_name}"}}.flatten.join(", ")
1246
+ end
1247
+
1248
+ def add_association_callbacks(association_name, options)
1249
+ callbacks = %w(before_add after_add before_remove after_remove)
1250
+ callbacks.each do |callback_name|
1251
+ full_callback_name = "#{callback_name}_for_#{association_name}"
1252
+ defined_callbacks = options[callback_name.to_sym]
1253
+ if options.has_key?(callback_name.to_sym)
1254
+ class_inheritable_reader full_callback_name.to_sym
1255
+ write_inheritable_array(full_callback_name.to_sym, [defined_callbacks].flatten)
1256
+ end
1257
+ end
1258
+ end
1259
+
1260
+ def condition_word(sql)
1261
+ sql =~ /where/i ? " AND " : "WHERE "
1262
+ end
1263
+
1264
+ def create_extension_module(association_id, extension)
1265
+ extension_module_name = "#{self.to_s}#{association_id.to_s.camelize}AssociationExtension"
1266
+
1267
+ silence_warnings do
1268
+ Object.const_set(extension_module_name, Module.new(&extension))
1269
+ end
1270
+
1271
+ extension_module_name.constantize
1272
+ end
1273
+
1274
+ class JoinDependency # :nodoc:
1275
+ attr_reader :joins, :reflections, :table_aliases
1276
+
1277
+ def initialize(base, associations, joins)
1278
+ @joins = [JoinBase.new(base, joins)]
1279
+ @associations = associations
1280
+ @reflections = []
1281
+ @base_records_hash = {}
1282
+ @base_records_in_order = []
1283
+ @table_aliases = Hash.new { |aliases, table| aliases[table] = 0 }
1284
+ @table_aliases[base.table_name] = 1
1285
+ build(associations)
1286
+ end
1287
+
1288
+ def join_associations
1289
+ @joins[1..-1].to_a
1290
+ end
1291
+
1292
+ def join_base
1293
+ @joins[0]
1294
+ end
1295
+
1296
+ def instantiate(rows)
1297
+ rows.each_with_index do |row, i|
1298
+ primary_id = join_base.record_id(row)
1299
+ unless @base_records_hash[primary_id]
1300
+ @base_records_in_order << (@base_records_hash[primary_id] = join_base.instantiate(row))
1301
+ end
1302
+ construct(@base_records_hash[primary_id], @associations, join_associations.dup, row)
1303
+ end
1304
+ return @base_records_in_order
1305
+ end
1306
+
1307
+ def aliased_table_names_for(table_name)
1308
+ joins.select{|join| join.table_name == table_name }.collect{|join| join.aliased_table_name}
1309
+ end
1310
+
1311
+ protected
1312
+ def build(associations, parent = nil)
1313
+ parent ||= @joins.last
1314
+ case associations
1315
+ when Symbol, String
1316
+ reflection = parent.reflections[associations.to_s.intern] or
1317
+ raise ConfigurationError, "Association named '#{ associations }' was not found; perhaps you misspelled it?"
1318
+ @reflections << reflection
1319
+ @joins << JoinAssociation.new(reflection, self, parent)
1320
+ when Array
1321
+ associations.each do |association|
1322
+ build(association, parent)
1323
+ end
1324
+ when Hash
1325
+ associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
1326
+ build(name, parent)
1327
+ build(associations[name])
1328
+ end
1329
+ else
1330
+ raise ConfigurationError, associations.inspect
1331
+ end
1332
+ end
1333
+
1334
+ def construct(parent, associations, joins, row)
1335
+ case associations
1336
+ when Symbol, String
1337
+ while (join = joins.shift).reflection.name.to_s != associations.to_s
1338
+ raise ConfigurationError, "Not Enough Associations" if joins.empty?
1339
+ end
1340
+ construct_association(parent, join, row)
1341
+ when Array
1342
+ associations.each do |association|
1343
+ construct(parent, association, joins, row)
1344
+ end
1345
+ when Hash
1346
+ associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
1347
+ association = construct_association(parent, joins.shift, row)
1348
+ construct(association, associations[name], joins, row) if association
1349
+ end
1350
+ else
1351
+ raise ConfigurationError, associations.inspect
1352
+ end
1353
+ end
1354
+
1355
+ def construct_association(record, join, row)
1356
+ case join.reflection.macro
1357
+ when :has_many, :has_and_belongs_to_many
1358
+ collection = record.send(join.reflection.name)
1359
+ collection.loaded
1360
+
1361
+ return nil if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
1362
+ association = join.instantiate(row)
1363
+ collection.target.push(association) unless collection.target.include?(association)
1364
+ when :has_one
1365
+ return if record.id.to_s != join.parent.record_id(row).to_s
1366
+ association = join.instantiate(row) unless row[join.aliased_primary_key].nil?
1367
+ record.send("set_#{join.reflection.name}_target", association)
1368
+ when :belongs_to
1369
+ return if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
1370
+ association = join.instantiate(row)
1371
+ record.send("set_#{join.reflection.name}_target", association)
1372
+ else
1373
+ raise ConfigurationError, "unknown macro: #{join.reflection.macro}"
1374
+ end
1375
+ return association
1376
+ end
1377
+
1378
+ class JoinBase # :nodoc:
1379
+ attr_reader :active_record, :table_joins
1380
+ delegate :table_name, :column_names, :primary_key, :reflections, :sanitize_sql, :to => :active_record
1381
+
1382
+ def initialize(active_record, joins = nil)
1383
+ @active_record = active_record
1384
+ @cached_record = {}
1385
+ @table_joins = joins
1386
+ end
1387
+
1388
+ def aliased_prefix
1389
+ "t0"
1390
+ end
1391
+
1392
+ def aliased_primary_key
1393
+ "#{ aliased_prefix }_r0"
1394
+ end
1395
+
1396
+ def aliased_table_name
1397
+ active_record.table_name
1398
+ end
1399
+
1400
+ def column_names_with_alias
1401
+ unless @column_names_with_alias
1402
+ @column_names_with_alias = []
1403
+ ([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i|
1404
+ @column_names_with_alias << [column_name, "#{ aliased_prefix }_r#{ i }"]
1405
+ end
1406
+ end
1407
+ return @column_names_with_alias
1408
+ end
1409
+
1410
+ def extract_record(row)
1411
+ column_names_with_alias.inject({}){|record, (cn, an)| record[cn] = row[an]; record}
1412
+ end
1413
+
1414
+ def record_id(row)
1415
+ row[aliased_primary_key]
1416
+ end
1417
+
1418
+ def instantiate(row)
1419
+ @cached_record[record_id(row)] ||= active_record.instantiate(extract_record(row))
1420
+ end
1421
+ end
1422
+
1423
+ class JoinAssociation < JoinBase # :nodoc:
1424
+ attr_reader :reflection, :parent, :aliased_table_name, :aliased_prefix, :aliased_join_table_name, :parent_table_name
1425
+ delegate :options, :klass, :through_reflection, :source_reflection, :to => :reflection
1426
+
1427
+ def initialize(reflection, join_dependency, parent = nil)
1428
+ reflection.check_validity!
1429
+ if reflection.options[:polymorphic]
1430
+ raise EagerLoadPolymorphicError.new(reflection)
1431
+ end
1432
+
1433
+ super(reflection.klass)
1434
+ @parent = parent
1435
+ @reflection = reflection
1436
+ @aliased_prefix = "t#{ join_dependency.joins.size }"
1437
+ @aliased_table_name = table_name #.tr('.', '_') # start with the table name, sub out any .'s
1438
+ @parent_table_name = parent.active_record.table_name
1439
+
1440
+ if !parent.table_joins.blank? && parent.table_joins.to_s.downcase =~ %r{join(\s+\w+)?\s+#{aliased_table_name.downcase}\son}
1441
+ join_dependency.table_aliases[aliased_table_name] += 1
1442
+ end
1443
+
1444
+ unless join_dependency.table_aliases[aliased_table_name].zero?
1445
+ # if the table name has been used, then use an alias
1446
+ @aliased_table_name = active_record.connection.table_alias_for "#{pluralize(reflection.name)}_#{parent_table_name}"
1447
+ table_index = join_dependency.table_aliases[aliased_table_name]
1448
+ join_dependency.table_aliases[aliased_table_name] += 1
1449
+ @aliased_table_name = @aliased_table_name[0..active_record.connection.table_alias_length-3] + "_#{table_index+1}" if table_index > 0
1450
+ else
1451
+ join_dependency.table_aliases[aliased_table_name] += 1
1452
+ end
1453
+
1454
+ if reflection.macro == :has_and_belongs_to_many || (reflection.macro == :has_many && reflection.options[:through])
1455
+ @aliased_join_table_name = reflection.macro == :has_and_belongs_to_many ? reflection.options[:join_table] : reflection.through_reflection.klass.table_name
1456
+ unless join_dependency.table_aliases[aliased_join_table_name].zero?
1457
+ @aliased_join_table_name = active_record.connection.table_alias_for "#{pluralize(reflection.name)}_#{parent_table_name}_join"
1458
+ table_index = join_dependency.table_aliases[aliased_join_table_name]
1459
+ join_dependency.table_aliases[aliased_join_table_name] += 1
1460
+ @aliased_join_table_name = @aliased_join_table_name[0..active_record.connection.table_alias_length-3] + "_#{table_index+1}" if table_index > 0
1461
+ else
1462
+ join_dependency.table_aliases[aliased_join_table_name] += 1
1463
+ end
1464
+ end
1465
+ end
1466
+
1467
+ def association_join
1468
+ join = case reflection.macro
1469
+ when :has_and_belongs_to_many
1470
+ " LEFT OUTER JOIN %s ON %s.%s = %s.%s " % [
1471
+ table_alias_for(options[:join_table], aliased_join_table_name),
1472
+ aliased_join_table_name,
1473
+ options[:foreign_key] || reflection.active_record.to_s.classify.foreign_key,
1474
+ parent.aliased_table_name, reflection.active_record.primary_key] +
1475
+ " LEFT OUTER JOIN %s ON %s.%s = %s.%s " % [
1476
+ table_name_and_alias, aliased_table_name, klass.primary_key,
1477
+ aliased_join_table_name, options[:association_foreign_key] || klass.table_name.classify.foreign_key
1478
+ ]
1479
+ when :has_many, :has_one
1480
+ case
1481
+ when reflection.macro == :has_many && reflection.options[:through]
1482
+ through_conditions = through_reflection.options[:conditions] ? "AND #{interpolate_sql(sanitize_sql(through_reflection.options[:conditions]))}" : ''
1483
+
1484
+ jt_foreign_key = jt_as_extra = jt_source_extra = jt_sti_extra = nil
1485
+ first_key = second_key = as_extra = nil
1486
+
1487
+ if through_reflection.options[:as] # has_many :through against a polymorphic join
1488
+ jt_foreign_key = through_reflection.options[:as].to_s + '_id'
1489
+ jt_as_extra = " AND %s.%s = %s" % [
1490
+ aliased_join_table_name, reflection.active_record.connection.quote_column_name(through_reflection.options[:as].to_s + '_type'),
1491
+ klass.quote_value(parent.active_record.base_class.name)
1492
+ ]
1493
+ else
1494
+ jt_foreign_key = through_reflection.primary_key_name
1495
+ end
1496
+
1497
+ case source_reflection.macro
1498
+ when :has_many
1499
+ if source_reflection.options[:as]
1500
+ first_key = "#{source_reflection.options[:as]}_id"
1501
+ second_key = options[:foreign_key] || primary_key
1502
+ as_extra = " AND %s.%s = %s" % [
1503
+ aliased_table_name, reflection.active_record.connection.quote_column_name("#{source_reflection.options[:as]}_type"),
1504
+ klass.quote_value(source_reflection.active_record.base_class.name)
1505
+ ]
1506
+ else
1507
+ first_key = through_reflection.klass.base_class.to_s.classify.foreign_key
1508
+ second_key = options[:foreign_key] || primary_key
1509
+ end
1510
+
1511
+ unless through_reflection.klass.descends_from_active_record?
1512
+ jt_sti_extra = " AND %s.%s = %s" % [
1513
+ aliased_join_table_name,
1514
+ reflection.active_record.connection.quote_column_name(through_reflection.active_record.inheritance_column),
1515
+ through_reflection.klass.quote_value(through_reflection.klass.name.demodulize)]
1516
+ end
1517
+ when :belongs_to
1518
+ first_key = primary_key
1519
+ if reflection.options[:source_type]
1520
+ second_key = source_reflection.association_foreign_key
1521
+ jt_source_extra = " AND %s.%s = %s" % [
1522
+ aliased_join_table_name, reflection.active_record.connection.quote_column_name(reflection.source_reflection.options[:foreign_type]),
1523
+ klass.quote_value(reflection.options[:source_type])
1524
+ ]
1525
+ else
1526
+ second_key = source_reflection.options[:foreign_key] || klass.to_s.classify.foreign_key
1527
+ end
1528
+ end
1529
+
1530
+ " LEFT OUTER JOIN %s ON (%s.%s = %s.%s%s%s%s) " % [
1531
+ table_alias_for(through_reflection.klass.table_name, aliased_join_table_name),
1532
+ parent.aliased_table_name, reflection.active_record.connection.quote_column_name(parent.primary_key),
1533
+ aliased_join_table_name, reflection.active_record.connection.quote_column_name(jt_foreign_key),
1534
+ jt_as_extra, jt_source_extra, jt_sti_extra
1535
+ ] +
1536
+ " LEFT OUTER JOIN %s ON (%s.%s = %s.%s%s) " % [
1537
+ table_name_and_alias,
1538
+ aliased_table_name, reflection.active_record.connection.quote_column_name(first_key),
1539
+ aliased_join_table_name, reflection.active_record.connection.quote_column_name(second_key),
1540
+ as_extra
1541
+ ]
1542
+
1543
+ when reflection.macro == :has_many && reflection.options[:as]
1544
+ " LEFT OUTER JOIN %s ON %s.%s = %s.%s AND %s.%s = %s" % [
1545
+ table_name_and_alias,
1546
+ aliased_table_name, "#{reflection.options[:as]}_id",
1547
+ parent.aliased_table_name, parent.primary_key,
1548
+ aliased_table_name, "#{reflection.options[:as]}_type",
1549
+ klass.quote_value(parent.active_record.base_class.name)
1550
+ ]
1551
+ when reflection.macro == :has_one && reflection.options[:as]
1552
+ " LEFT OUTER JOIN %s ON %s.%s = %s.%s AND %s.%s = %s " % [
1553
+ table_name_and_alias,
1554
+ aliased_table_name, "#{reflection.options[:as]}_id",
1555
+ parent.aliased_table_name, parent.primary_key,
1556
+ aliased_table_name, "#{reflection.options[:as]}_type",
1557
+ klass.quote_value(reflection.active_record.base_class.name)
1558
+ ]
1559
+ else
1560
+ foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
1561
+ " LEFT OUTER JOIN %s ON %s.%s = %s.%s " % [
1562
+ table_name_and_alias,
1563
+ aliased_table_name, foreign_key,
1564
+ parent.aliased_table_name, parent.primary_key
1565
+ ]
1566
+ end
1567
+ when :belongs_to
1568
+ " LEFT OUTER JOIN %s ON %s.%s = %s.%s " % [
1569
+ table_name_and_alias, aliased_table_name, reflection.klass.primary_key,
1570
+ parent.aliased_table_name, options[:foreign_key] || klass.to_s.foreign_key
1571
+ ]
1572
+ else
1573
+ ""
1574
+ end || ''
1575
+ join << %(AND %s.%s = %s ) % [
1576
+ aliased_table_name,
1577
+ reflection.active_record.connection.quote_column_name(klass.inheritance_column),
1578
+ klass.quote_value(klass.name.demodulize)] unless klass.descends_from_active_record?
1579
+
1580
+ [through_reflection, reflection].each do |ref|
1581
+ join << "AND #{interpolate_sql(sanitize_sql(ref.options[:conditions]))} " if ref && ref.options[:conditions]
1582
+ end
1583
+
1584
+ join
1585
+ end
1586
+
1587
+ protected
1588
+
1589
+ def pluralize(table_name)
1590
+ BigRecord::Base.pluralize_table_names ? table_name.to_s.pluralize : table_name
1591
+ end
1592
+
1593
+ def table_alias_for(table_name, table_alias)
1594
+ "#{table_name} #{table_alias if table_name != table_alias}".strip
1595
+ end
1596
+
1597
+ def table_name_and_alias
1598
+ table_alias_for table_name, @aliased_table_name
1599
+ end
1600
+
1601
+ def interpolate_sql(sql)
1602
+ instance_eval("%@#{sql.gsub('@', '\@')}@")
1603
+ end
1604
+ end
1605
+ end
1606
+ end
1607
+ end
1608
+ end