sskirby-activerecord 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. data/CHANGELOG.md +6749 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.rdoc +222 -0
  4. data/examples/associations.png +0 -0
  5. data/examples/performance.rb +177 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record.rb +147 -0
  8. data/lib/active_record/aggregations.rb +255 -0
  9. data/lib/active_record/associations.rb +1604 -0
  10. data/lib/active_record/associations/alias_tracker.rb +79 -0
  11. data/lib/active_record/associations/association.rb +239 -0
  12. data/lib/active_record/associations/association_scope.rb +119 -0
  13. data/lib/active_record/associations/belongs_to_association.rb +79 -0
  14. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +34 -0
  15. data/lib/active_record/associations/builder/association.rb +55 -0
  16. data/lib/active_record/associations/builder/belongs_to.rb +85 -0
  17. data/lib/active_record/associations/builder/collection_association.rb +75 -0
  18. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +57 -0
  19. data/lib/active_record/associations/builder/has_many.rb +71 -0
  20. data/lib/active_record/associations/builder/has_one.rb +62 -0
  21. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  22. data/lib/active_record/associations/collection_association.rb +574 -0
  23. data/lib/active_record/associations/collection_proxy.rb +132 -0
  24. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +62 -0
  25. data/lib/active_record/associations/has_many_association.rb +108 -0
  26. data/lib/active_record/associations/has_many_through_association.rb +180 -0
  27. data/lib/active_record/associations/has_one_association.rb +73 -0
  28. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  29. data/lib/active_record/associations/join_dependency.rb +214 -0
  30. data/lib/active_record/associations/join_dependency/join_association.rb +154 -0
  31. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  32. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  33. data/lib/active_record/associations/join_helper.rb +55 -0
  34. data/lib/active_record/associations/preloader.rb +177 -0
  35. data/lib/active_record/associations/preloader/association.rb +127 -0
  36. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  37. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  38. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  39. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  40. data/lib/active_record/associations/preloader/has_many_through.rb +15 -0
  41. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  42. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  43. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  44. data/lib/active_record/associations/preloader/through_association.rb +67 -0
  45. data/lib/active_record/associations/singular_association.rb +64 -0
  46. data/lib/active_record/associations/through_association.rb +83 -0
  47. data/lib/active_record/attribute_assignment.rb +221 -0
  48. data/lib/active_record/attribute_methods.rb +272 -0
  49. data/lib/active_record/attribute_methods/before_type_cast.rb +31 -0
  50. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
  51. data/lib/active_record/attribute_methods/dirty.rb +101 -0
  52. data/lib/active_record/attribute_methods/primary_key.rb +114 -0
  53. data/lib/active_record/attribute_methods/query.rb +39 -0
  54. data/lib/active_record/attribute_methods/read.rb +135 -0
  55. data/lib/active_record/attribute_methods/serialization.rb +93 -0
  56. data/lib/active_record/attribute_methods/time_zone_conversion.rb +62 -0
  57. data/lib/active_record/attribute_methods/write.rb +69 -0
  58. data/lib/active_record/autosave_association.rb +422 -0
  59. data/lib/active_record/base.rb +716 -0
  60. data/lib/active_record/callbacks.rb +275 -0
  61. data/lib/active_record/coders/yaml_column.rb +41 -0
  62. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +452 -0
  63. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +188 -0
  64. data/lib/active_record/connection_adapters/abstract/database_limits.rb +58 -0
  65. data/lib/active_record/connection_adapters/abstract/database_statements.rb +388 -0
  66. data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -0
  67. data/lib/active_record/connection_adapters/abstract/quoting.rb +115 -0
  68. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +492 -0
  69. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +598 -0
  70. data/lib/active_record/connection_adapters/abstract_adapter.rb +296 -0
  71. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +653 -0
  72. data/lib/active_record/connection_adapters/column.rb +270 -0
  73. data/lib/active_record/connection_adapters/mysql2_adapter.rb +288 -0
  74. data/lib/active_record/connection_adapters/mysql_adapter.rb +426 -0
  75. data/lib/active_record/connection_adapters/postgresql_adapter.rb +1261 -0
  76. data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
  77. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +55 -0
  78. data/lib/active_record/connection_adapters/sqlite_adapter.rb +577 -0
  79. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  80. data/lib/active_record/counter_cache.rb +119 -0
  81. data/lib/active_record/dynamic_finder_match.rb +56 -0
  82. data/lib/active_record/dynamic_matchers.rb +79 -0
  83. data/lib/active_record/dynamic_scope_match.rb +23 -0
  84. data/lib/active_record/errors.rb +195 -0
  85. data/lib/active_record/explain.rb +85 -0
  86. data/lib/active_record/explain_subscriber.rb +21 -0
  87. data/lib/active_record/fixtures.rb +906 -0
  88. data/lib/active_record/fixtures/file.rb +65 -0
  89. data/lib/active_record/identity_map.rb +156 -0
  90. data/lib/active_record/inheritance.rb +167 -0
  91. data/lib/active_record/integration.rb +49 -0
  92. data/lib/active_record/locale/en.yml +40 -0
  93. data/lib/active_record/locking/optimistic.rb +183 -0
  94. data/lib/active_record/locking/pessimistic.rb +77 -0
  95. data/lib/active_record/log_subscriber.rb +68 -0
  96. data/lib/active_record/migration.rb +765 -0
  97. data/lib/active_record/migration/command_recorder.rb +105 -0
  98. data/lib/active_record/model_schema.rb +366 -0
  99. data/lib/active_record/nested_attributes.rb +469 -0
  100. data/lib/active_record/observer.rb +121 -0
  101. data/lib/active_record/persistence.rb +372 -0
  102. data/lib/active_record/query_cache.rb +74 -0
  103. data/lib/active_record/querying.rb +58 -0
  104. data/lib/active_record/railtie.rb +119 -0
  105. data/lib/active_record/railties/console_sandbox.rb +6 -0
  106. data/lib/active_record/railties/controller_runtime.rb +49 -0
  107. data/lib/active_record/railties/databases.rake +620 -0
  108. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  109. data/lib/active_record/readonly_attributes.rb +26 -0
  110. data/lib/active_record/reflection.rb +534 -0
  111. data/lib/active_record/relation.rb +534 -0
  112. data/lib/active_record/relation/batches.rb +90 -0
  113. data/lib/active_record/relation/calculations.rb +354 -0
  114. data/lib/active_record/relation/delegation.rb +49 -0
  115. data/lib/active_record/relation/finder_methods.rb +398 -0
  116. data/lib/active_record/relation/predicate_builder.rb +58 -0
  117. data/lib/active_record/relation/query_methods.rb +417 -0
  118. data/lib/active_record/relation/spawn_methods.rb +148 -0
  119. data/lib/active_record/result.rb +34 -0
  120. data/lib/active_record/sanitization.rb +194 -0
  121. data/lib/active_record/schema.rb +58 -0
  122. data/lib/active_record/schema_dumper.rb +204 -0
  123. data/lib/active_record/scoping.rb +152 -0
  124. data/lib/active_record/scoping/default.rb +142 -0
  125. data/lib/active_record/scoping/named.rb +202 -0
  126. data/lib/active_record/serialization.rb +18 -0
  127. data/lib/active_record/serializers/xml_serializer.rb +202 -0
  128. data/lib/active_record/session_store.rb +358 -0
  129. data/lib/active_record/store.rb +50 -0
  130. data/lib/active_record/test_case.rb +73 -0
  131. data/lib/active_record/timestamp.rb +113 -0
  132. data/lib/active_record/transactions.rb +360 -0
  133. data/lib/active_record/translation.rb +22 -0
  134. data/lib/active_record/validations.rb +83 -0
  135. data/lib/active_record/validations/associated.rb +43 -0
  136. data/lib/active_record/validations/uniqueness.rb +180 -0
  137. data/lib/active_record/version.rb +10 -0
  138. data/lib/rails/generators/active_record.rb +25 -0
  139. data/lib/rails/generators/active_record/migration.rb +15 -0
  140. data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
  141. data/lib/rails/generators/active_record/migration/templates/migration.rb +31 -0
  142. data/lib/rails/generators/active_record/model/model_generator.rb +43 -0
  143. data/lib/rails/generators/active_record/model/templates/migration.rb +15 -0
  144. data/lib/rails/generators/active_record/model/templates/model.rb +7 -0
  145. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  146. data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
  147. data/lib/rails/generators/active_record/observer/templates/observer.rb +4 -0
  148. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +25 -0
  149. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +12 -0
  150. metadata +242 -0
@@ -0,0 +1,534 @@
1
+ # -*- coding: utf-8 -*-
2
+ require 'active_support/core_ext/object/blank'
3
+
4
+ module ActiveRecord
5
+ # = Active Record Relation
6
+ class Relation
7
+ JoinOperation = Struct.new(:relation, :join_class, :on)
8
+ ASSOCIATION_METHODS = [:includes, :eager_load, :preload]
9
+ MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind]
10
+ SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :uniq]
11
+
12
+ include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
13
+
14
+ attr_reader :table, :klass, :loaded
15
+ attr_accessor :extensions, :default_scoped
16
+ alias :loaded? :loaded
17
+ alias :default_scoped? :default_scoped
18
+
19
+ def initialize(klass, table)
20
+ @klass, @table = klass, table
21
+
22
+ @implicit_readonly = nil
23
+ @loaded = false
24
+ @default_scoped = false
25
+
26
+ SINGLE_VALUE_METHODS.each {|v| instance_variable_set(:"@#{v}_value", nil)}
27
+ (ASSOCIATION_METHODS + MULTI_VALUE_METHODS).each {|v| instance_variable_set(:"@#{v}_values", [])}
28
+ @extensions = []
29
+ @create_with_value = {}
30
+ end
31
+
32
+ def insert(values)
33
+ primary_key_value = nil
34
+
35
+ if primary_key && Hash === values
36
+ primary_key_value = values[values.keys.find { |k|
37
+ k.name == primary_key
38
+ }]
39
+
40
+ if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
41
+ primary_key_value = connection.next_sequence_value(klass.sequence_name)
42
+ values[klass.arel_table[klass.primary_key]] = primary_key_value
43
+ end
44
+ end
45
+
46
+ im = arel.create_insert
47
+ im.into @table
48
+
49
+ conn = @klass.connection
50
+
51
+ substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
52
+ binds = substitutes.map do |arel_attr, value|
53
+ [@klass.columns_hash[arel_attr.name], value]
54
+ end
55
+
56
+ substitutes.each_with_index do |tuple, i|
57
+ tuple[1] = conn.substitute_at(binds[i][0], i)
58
+ end
59
+
60
+ if values.empty? # empty insert
61
+ im.values = Arel.sql(connection.empty_insert_statement_value)
62
+ else
63
+ im.insert substitutes
64
+ end
65
+
66
+ conn.insert(
67
+ im,
68
+ 'SQL',
69
+ primary_key,
70
+ primary_key_value,
71
+ nil,
72
+ binds)
73
+ end
74
+
75
+ def new(*args, &block)
76
+ scoping { @klass.new(*args, &block) }
77
+ end
78
+
79
+ def initialize_copy(other)
80
+ reset
81
+ end
82
+
83
+ alias build new
84
+
85
+ def create(*args, &block)
86
+ scoping { @klass.create(*args, &block) }
87
+ end
88
+
89
+ def create!(*args, &block)
90
+ scoping { @klass.create!(*args, &block) }
91
+ end
92
+
93
+ # Tries to load the first record; if it fails, then <tt>create</tt> is called with the same arguments as this method.
94
+ #
95
+ # Expects arguments in the same format as <tt>Base.create</tt>.
96
+ #
97
+ # ==== Examples
98
+ # # Find the first user named Penélope or create a new one.
99
+ # User.where(:first_name => 'Penélope').first_or_create
100
+ # # => <User id: 1, first_name: 'Penélope', last_name: nil>
101
+ #
102
+ # # Find the first user named Penélope or create a new one.
103
+ # # We already have one so the existing record will be returned.
104
+ # User.where(:first_name => 'Penélope').first_or_create
105
+ # # => <User id: 1, first_name: 'Penélope', last_name: nil>
106
+ #
107
+ # # Find the first user named Scarlett or create a new one with a particular last name.
108
+ # User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
109
+ # # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
110
+ #
111
+ # # Find the first user named Scarlett or create a new one with a different last name.
112
+ # # We already have one so the existing record will be returned.
113
+ # User.where(:first_name => 'Scarlett').first_or_create do |user|
114
+ # user.last_name = "O'Hara"
115
+ # end
116
+ # # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
117
+ def first_or_create(attributes = nil, options = {}, &block)
118
+ first || create(attributes, options, &block)
119
+ end
120
+
121
+ # Like <tt>first_or_create</tt> but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
122
+ #
123
+ # Expects arguments in the same format as <tt>Base.create!</tt>.
124
+ def first_or_create!(attributes = nil, options = {}, &block)
125
+ first || create!(attributes, options, &block)
126
+ end
127
+
128
+ # Like <tt>first_or_create</tt> but calls <tt>new</tt> instead of <tt>create</tt>.
129
+ #
130
+ # Expects arguments in the same format as <tt>Base.new</tt>.
131
+ def first_or_initialize(attributes = nil, options = {}, &block)
132
+ first || new(attributes, options, &block)
133
+ end
134
+
135
+ # Runs EXPLAIN on the query or queries triggered by this relation and
136
+ # returns the result as a string. The string is formatted imitating the
137
+ # ones printed by the database shell.
138
+ #
139
+ # Note that this method actually runs the queries, since the results of some
140
+ # are needed by the next ones when eager loading is going on.
141
+ #
142
+ # Please see further details in the
143
+ # {Active Record Query Interface guide}[http://edgeguides.rubyonrails.org/active_record_querying.html#running-explain].
144
+ def explain
145
+ _, queries = collecting_queries_for_explain { exec_queries }
146
+ exec_explain(queries)
147
+ end
148
+
149
+ def to_a
150
+ # We monitor here the entire execution rather than individual SELECTs
151
+ # because from the point of view of the user fetching the records of a
152
+ # relation is a single unit of work. You want to know if this call takes
153
+ # too long, not if the individual queries take too long.
154
+ #
155
+ # It could be the case that none of the queries involved surpass the
156
+ # threshold, and at the same time the sum of them all does. The user
157
+ # should get a query plan logged in that case.
158
+ logging_query_plan do
159
+ exec_queries
160
+ end
161
+ end
162
+
163
+ def exec_queries
164
+ return @records if loaded?
165
+
166
+ default_scoped = with_default_scope
167
+
168
+ if default_scoped.equal?(self)
169
+ @records = if @readonly_value.nil? && !@klass.locking_enabled?
170
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
171
+ else
172
+ IdentityMap.without do
173
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
174
+ end
175
+ end
176
+
177
+ preload = @preload_values
178
+ preload += @includes_values unless eager_loading?
179
+ preload.each do |associations|
180
+ ActiveRecord::Associations::Preloader.new(@records, associations).run
181
+ end
182
+
183
+ # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
184
+ # are JOINS and no explicit SELECT.
185
+ readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
186
+ @records.each { |record| record.readonly! } if readonly
187
+ else
188
+ @records = default_scoped.to_a
189
+ end
190
+
191
+ @loaded = true
192
+ @records
193
+ end
194
+ private :exec_queries
195
+
196
+ def as_json(options = nil) #:nodoc:
197
+ to_a.as_json(options)
198
+ end
199
+
200
+ # Returns size of the records.
201
+ def size
202
+ loaded? ? @records.length : count
203
+ end
204
+
205
+ # Returns true if there are no records.
206
+ def empty?
207
+ return @records.empty? if loaded?
208
+
209
+ c = count
210
+ c.respond_to?(:zero?) ? c.zero? : c.empty?
211
+ end
212
+
213
+ def any?
214
+ if block_given?
215
+ to_a.any? { |*block_args| yield(*block_args) }
216
+ else
217
+ !empty?
218
+ end
219
+ end
220
+
221
+ def many?
222
+ if block_given?
223
+ to_a.many? { |*block_args| yield(*block_args) }
224
+ else
225
+ @limit_value ? to_a.many? : size > 1
226
+ end
227
+ end
228
+
229
+ # Scope all queries to the current scope.
230
+ #
231
+ # ==== Example
232
+ #
233
+ # Comment.where(:post_id => 1).scoping do
234
+ # Comment.first # SELECT * FROM comments WHERE post_id = 1
235
+ # end
236
+ #
237
+ # Please check unscoped if you want to remove all previous scopes (including
238
+ # the default_scope) during the execution of a block.
239
+ def scoping
240
+ @klass.with_scope(self, :overwrite) { yield }
241
+ end
242
+
243
+ # Updates all records with details given if they match a set of conditions supplied, limits and order can
244
+ # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
245
+ # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
246
+ # or validations.
247
+ #
248
+ # ==== Parameters
249
+ #
250
+ # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
251
+ # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
252
+ # See conditions in the intro.
253
+ # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
254
+ #
255
+ # ==== Examples
256
+ #
257
+ # # Update all customers with the given attributes
258
+ # Customer.update_all :wants_email => true
259
+ #
260
+ # # Update all books with 'Rails' in their title
261
+ # Book.update_all "author = 'David'", "title LIKE '%Rails%'"
262
+ #
263
+ # # Update all avatars migrated more than a week ago
264
+ # Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
265
+ #
266
+ # # Update all books that match conditions, but limit it to 5 ordered by date
267
+ # Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
268
+ #
269
+ # # Conditions from the current relation also works
270
+ # Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
271
+ #
272
+ # # The same idea applies to limit and order
273
+ # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
274
+ def update_all(updates, conditions = nil, options = {})
275
+ IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled?
276
+ if conditions || options.present?
277
+ where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
278
+ else
279
+ stmt = Arel::UpdateManager.new(arel.engine)
280
+
281
+ stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
282
+ stmt.table(table)
283
+ stmt.key = table[primary_key]
284
+
285
+ if joins_values.any?
286
+ @klass.connection.join_to_update(stmt, arel)
287
+ else
288
+ stmt.take(arel.limit)
289
+ stmt.order(*arel.orders)
290
+ stmt.wheres = arel.constraints
291
+ end
292
+
293
+ @klass.connection.update stmt, 'SQL', bind_values
294
+ end
295
+ end
296
+
297
+ # Updates an object (or multiple objects) and saves it to the database, if validations pass.
298
+ # The resulting object is returned whether the object was saved successfully to the database or not.
299
+ #
300
+ # ==== Parameters
301
+ #
302
+ # * +id+ - This should be the id or an array of ids to be updated.
303
+ # * +attributes+ - This should be a hash of attributes or an array of hashes.
304
+ #
305
+ # ==== Examples
306
+ #
307
+ # # Updates one record
308
+ # Person.update(15, :user_name => 'Samuel', :group => 'expert')
309
+ #
310
+ # # Updates multiple records
311
+ # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
312
+ # Person.update(people.keys, people.values)
313
+ def update(id, attributes)
314
+ if id.is_a?(Array)
315
+ id.each.with_index.map {|one_id, idx| update(one_id, attributes[idx])}
316
+ else
317
+ object = find(id)
318
+ object.update_attributes(attributes)
319
+ object
320
+ end
321
+ end
322
+
323
+ # Destroys the records matching +conditions+ by instantiating each
324
+ # record and calling its +destroy+ method. Each object's callbacks are
325
+ # executed (including <tt>:dependent</tt> association options and
326
+ # +before_destroy+/+after_destroy+ Observer methods). Returns the
327
+ # collection of objects that were destroyed; each will be frozen, to
328
+ # reflect that no changes should be made (since they can't be
329
+ # persisted).
330
+ #
331
+ # Note: Instantiation, callback execution, and deletion of each
332
+ # record can be time consuming when you're removing many records at
333
+ # once. It generates at least one SQL +DELETE+ query per record (or
334
+ # possibly more, to enforce your callbacks). If you want to delete many
335
+ # rows quickly, without concern for their associations or callbacks, use
336
+ # +delete_all+ instead.
337
+ #
338
+ # ==== Parameters
339
+ #
340
+ # * +conditions+ - A string, array, or hash that specifies which records
341
+ # to destroy. If omitted, all records are destroyed. See the
342
+ # Conditions section in the introduction to ActiveRecord::Base for
343
+ # more information.
344
+ #
345
+ # ==== Examples
346
+ #
347
+ # Person.destroy_all("last_login < '2004-04-04'")
348
+ # Person.destroy_all(:status => "inactive")
349
+ # Person.where(:age => 0..18).destroy_all
350
+ def destroy_all(conditions = nil)
351
+ if conditions
352
+ where(conditions).destroy_all
353
+ else
354
+ to_a.each {|object| object.destroy }.tap { reset }
355
+ end
356
+ end
357
+
358
+ # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
359
+ # therefore all callbacks and filters are fired off before the object is deleted. This method is
360
+ # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
361
+ #
362
+ # This essentially finds the object (or multiple objects) with the given id, creates a new object
363
+ # from the attributes, and then calls destroy on it.
364
+ #
365
+ # ==== Parameters
366
+ #
367
+ # * +id+ - Can be either an Integer or an Array of Integers.
368
+ #
369
+ # ==== Examples
370
+ #
371
+ # # Destroy a single object
372
+ # Todo.destroy(1)
373
+ #
374
+ # # Destroy multiple objects
375
+ # todos = [1,2,3]
376
+ # Todo.destroy(todos)
377
+ def destroy(id)
378
+ if id.is_a?(Array)
379
+ id.map { |one_id| destroy(one_id) }
380
+ else
381
+ find(id).destroy
382
+ end
383
+ end
384
+
385
+ # Deletes the records matching +conditions+ without instantiating the records first, and hence not
386
+ # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
387
+ # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
388
+ # though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
389
+ # the number of rows affected.
390
+ #
391
+ # ==== Parameters
392
+ #
393
+ # * +conditions+ - Conditions are specified the same way as with +find+ method.
394
+ #
395
+ # ==== Example
396
+ #
397
+ # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
398
+ # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
399
+ # Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
400
+ #
401
+ # Both calls delete the affected posts all at once with a single DELETE statement.
402
+ # If you need to destroy dependent associations or call your <tt>before_*</tt> or
403
+ # +after_destroy+ callbacks, use the +destroy_all+ method instead.
404
+ def delete_all(conditions = nil)
405
+ IdentityMap.repository[symbolized_base_class] = {} if IdentityMap.enabled?
406
+ if conditions
407
+ where(conditions).delete_all
408
+ else
409
+ statement = arel.compile_delete
410
+ affected = @klass.connection.delete(statement, 'SQL', bind_values)
411
+
412
+ reset
413
+ affected
414
+ end
415
+ end
416
+
417
+ # Deletes the row with a primary key matching the +id+ argument, using a
418
+ # SQL +DELETE+ statement, and returns the number of rows deleted. Active
419
+ # Record objects are not instantiated, so the object's callbacks are not
420
+ # executed, including any <tt>:dependent</tt> association options or
421
+ # Observer methods.
422
+ #
423
+ # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
424
+ #
425
+ # Note: Although it is often much faster than the alternative,
426
+ # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
427
+ # your application that ensures referential integrity or performs other
428
+ # essential jobs.
429
+ #
430
+ # ==== Examples
431
+ #
432
+ # # Delete a single row
433
+ # Todo.delete(1)
434
+ #
435
+ # # Delete multiple rows
436
+ # Todo.delete([2,3,4])
437
+ def delete(id_or_array)
438
+ IdentityMap.remove_by_id(self.symbolized_base_class, id_or_array) if IdentityMap.enabled?
439
+ where(primary_key => id_or_array).delete_all
440
+ end
441
+
442
+ def reload
443
+ reset
444
+ to_a # force reload
445
+ self
446
+ end
447
+
448
+ def reset
449
+ @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
450
+ @should_eager_load = @join_dependency = nil
451
+ @records = []
452
+ self
453
+ end
454
+
455
+ def to_sql
456
+ @to_sql ||= klass.connection.to_sql(arel)
457
+ end
458
+
459
+ def where_values_hash
460
+ equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
461
+ node.left.relation.name == table_name
462
+ }
463
+
464
+ Hash[equalities.map { |where| [where.left.name, where.right] }]
465
+ end
466
+
467
+ def scope_for_create
468
+ @scope_for_create ||= where_values_hash.merge(create_with_value)
469
+ end
470
+
471
+ def eager_loading?
472
+ @should_eager_load ||=
473
+ @eager_load_values.any? ||
474
+ @includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
475
+ end
476
+
477
+ # Joins that are also marked for preloading. In which case we should just eager load them.
478
+ # Note that this is a naive implementation because we could have strings and symbols which
479
+ # represent the same association, but that aren't matched by this. Also, we could have
480
+ # nested hashes which partially match, e.g. { :a => :b } & { :a => [:b, :c] }
481
+ def joined_includes_values
482
+ @includes_values & @joins_values
483
+ end
484
+
485
+ def ==(other)
486
+ case other
487
+ when Relation
488
+ other.to_sql == to_sql
489
+ when Array
490
+ to_a == other
491
+ end
492
+ end
493
+
494
+ def inspect
495
+ to_a.inspect
496
+ end
497
+
498
+ def with_default_scope #:nodoc:
499
+ if default_scoped? && default_scope = klass.send(:build_default_scope)
500
+ default_scope = default_scope.merge(self)
501
+ default_scope.default_scoped = false
502
+ default_scope
503
+ else
504
+ self
505
+ end
506
+ end
507
+
508
+ private
509
+
510
+ def references_eager_loaded_tables?
511
+ joined_tables = arel.join_sources.map do |join|
512
+ if join.is_a?(Arel::Nodes::StringJoin)
513
+ tables_in_string(join.left)
514
+ else
515
+ [join.left.table_name, join.left.table_alias]
516
+ end
517
+ end
518
+
519
+ joined_tables += [table.name, table.table_alias]
520
+
521
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
522
+ joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
523
+
524
+ (tables_in_string(to_sql) - joined_tables).any?
525
+ end
526
+
527
+ def tables_in_string(string)
528
+ return [] if string.blank?
529
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
530
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
531
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
532
+ end
533
+ end
534
+ end