activerecord 1.0.0 → 3.0.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (178) hide show
  1. data/CHANGELOG +5518 -76
  2. data/README.rdoc +222 -0
  3. data/examples/performance.rb +162 -0
  4. data/examples/simple.rb +14 -0
  5. data/lib/active_record/aggregations.rb +192 -80
  6. data/lib/active_record/association_preload.rb +403 -0
  7. data/lib/active_record/associations/association_collection.rb +545 -53
  8. data/lib/active_record/associations/association_proxy.rb +295 -0
  9. data/lib/active_record/associations/belongs_to_association.rb +91 -0
  10. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +78 -0
  11. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +127 -36
  12. data/lib/active_record/associations/has_many_association.rb +108 -84
  13. data/lib/active_record/associations/has_many_through_association.rb +116 -0
  14. data/lib/active_record/associations/has_one_association.rb +143 -0
  15. data/lib/active_record/associations/has_one_through_association.rb +40 -0
  16. data/lib/active_record/associations/through_association_scope.rb +154 -0
  17. data/lib/active_record/associations.rb +2086 -368
  18. data/lib/active_record/attribute_methods/before_type_cast.rb +33 -0
  19. data/lib/active_record/attribute_methods/dirty.rb +95 -0
  20. data/lib/active_record/attribute_methods/primary_key.rb +50 -0
  21. data/lib/active_record/attribute_methods/query.rb +39 -0
  22. data/lib/active_record/attribute_methods/read.rb +116 -0
  23. data/lib/active_record/attribute_methods/time_zone_conversion.rb +61 -0
  24. data/lib/active_record/attribute_methods/write.rb +37 -0
  25. data/lib/active_record/attribute_methods.rb +60 -0
  26. data/lib/active_record/autosave_association.rb +369 -0
  27. data/lib/active_record/base.rb +1603 -721
  28. data/lib/active_record/callbacks.rb +176 -225
  29. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +365 -0
  30. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +113 -0
  31. data/lib/active_record/connection_adapters/abstract/database_limits.rb +57 -0
  32. data/lib/active_record/connection_adapters/abstract/database_statements.rb +329 -0
  33. data/lib/active_record/connection_adapters/abstract/query_cache.rb +81 -0
  34. data/lib/active_record/connection_adapters/abstract/quoting.rb +72 -0
  35. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +739 -0
  36. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +543 -0
  37. data/lib/active_record/connection_adapters/abstract_adapter.rb +165 -279
  38. data/lib/active_record/connection_adapters/mysql_adapter.rb +594 -82
  39. data/lib/active_record/connection_adapters/postgresql_adapter.rb +988 -135
  40. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +53 -0
  41. data/lib/active_record/connection_adapters/sqlite_adapter.rb +365 -71
  42. data/lib/active_record/counter_cache.rb +115 -0
  43. data/lib/active_record/dynamic_finder_match.rb +53 -0
  44. data/lib/active_record/dynamic_scope_match.rb +32 -0
  45. data/lib/active_record/errors.rb +172 -0
  46. data/lib/active_record/fixtures.rb +941 -105
  47. data/lib/active_record/locale/en.yml +40 -0
  48. data/lib/active_record/locking/optimistic.rb +172 -0
  49. data/lib/active_record/locking/pessimistic.rb +55 -0
  50. data/lib/active_record/log_subscriber.rb +48 -0
  51. data/lib/active_record/migration.rb +617 -0
  52. data/lib/active_record/named_scope.rb +138 -0
  53. data/lib/active_record/nested_attributes.rb +417 -0
  54. data/lib/active_record/observer.rb +105 -36
  55. data/lib/active_record/persistence.rb +291 -0
  56. data/lib/active_record/query_cache.rb +36 -0
  57. data/lib/active_record/railtie.rb +91 -0
  58. data/lib/active_record/railties/controller_runtime.rb +38 -0
  59. data/lib/active_record/railties/databases.rake +512 -0
  60. data/lib/active_record/reflection.rb +364 -87
  61. data/lib/active_record/relation/batches.rb +89 -0
  62. data/lib/active_record/relation/calculations.rb +286 -0
  63. data/lib/active_record/relation/finder_methods.rb +355 -0
  64. data/lib/active_record/relation/predicate_builder.rb +41 -0
  65. data/lib/active_record/relation/query_methods.rb +261 -0
  66. data/lib/active_record/relation/spawn_methods.rb +112 -0
  67. data/lib/active_record/relation.rb +393 -0
  68. data/lib/active_record/schema.rb +59 -0
  69. data/lib/active_record/schema_dumper.rb +195 -0
  70. data/lib/active_record/serialization.rb +60 -0
  71. data/lib/active_record/serializers/xml_serializer.rb +244 -0
  72. data/lib/active_record/session_store.rb +340 -0
  73. data/lib/active_record/test_case.rb +67 -0
  74. data/lib/active_record/timestamp.rb +88 -0
  75. data/lib/active_record/transactions.rb +329 -75
  76. data/lib/active_record/validations/associated.rb +48 -0
  77. data/lib/active_record/validations/uniqueness.rb +185 -0
  78. data/lib/active_record/validations.rb +58 -179
  79. data/lib/active_record/version.rb +9 -0
  80. data/lib/active_record.rb +100 -24
  81. data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
  82. data/lib/rails/generators/active_record/migration/templates/migration.rb +17 -0
  83. data/lib/rails/generators/active_record/model/model_generator.rb +38 -0
  84. data/lib/rails/generators/active_record/model/templates/migration.rb +16 -0
  85. data/lib/rails/generators/active_record/model/templates/model.rb +5 -0
  86. data/lib/rails/generators/active_record/model/templates/module.rb +5 -0
  87. data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
  88. data/lib/rails/generators/active_record/observer/templates/observer.rb +2 -0
  89. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +24 -0
  90. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +16 -0
  91. data/lib/rails/generators/active_record.rb +27 -0
  92. metadata +216 -158
  93. data/README +0 -361
  94. data/RUNNING_UNIT_TESTS +0 -36
  95. data/dev-utils/eval_debugger.rb +0 -9
  96. data/examples/associations.rb +0 -87
  97. data/examples/shared_setup.rb +0 -15
  98. data/examples/validation.rb +0 -88
  99. data/install.rb +0 -60
  100. data/lib/active_record/deprecated_associations.rb +0 -70
  101. data/lib/active_record/support/class_attribute_accessors.rb +0 -43
  102. data/lib/active_record/support/class_inheritable_attributes.rb +0 -37
  103. data/lib/active_record/support/clean_logger.rb +0 -10
  104. data/lib/active_record/support/inflector.rb +0 -70
  105. data/lib/active_record/vendor/mysql.rb +0 -1117
  106. data/lib/active_record/vendor/simple.rb +0 -702
  107. data/lib/active_record/wrappers/yaml_wrapper.rb +0 -15
  108. data/lib/active_record/wrappings.rb +0 -59
  109. data/rakefile +0 -122
  110. data/test/abstract_unit.rb +0 -16
  111. data/test/aggregations_test.rb +0 -34
  112. data/test/all.sh +0 -8
  113. data/test/associations_test.rb +0 -477
  114. data/test/base_test.rb +0 -513
  115. data/test/class_inheritable_attributes_test.rb +0 -33
  116. data/test/connections/native_mysql/connection.rb +0 -24
  117. data/test/connections/native_postgresql/connection.rb +0 -24
  118. data/test/connections/native_sqlite/connection.rb +0 -24
  119. data/test/deprecated_associations_test.rb +0 -336
  120. data/test/finder_test.rb +0 -67
  121. data/test/fixtures/accounts/signals37 +0 -3
  122. data/test/fixtures/accounts/unknown +0 -2
  123. data/test/fixtures/auto_id.rb +0 -4
  124. data/test/fixtures/column_name.rb +0 -3
  125. data/test/fixtures/companies/first_client +0 -6
  126. data/test/fixtures/companies/first_firm +0 -4
  127. data/test/fixtures/companies/second_client +0 -6
  128. data/test/fixtures/company.rb +0 -37
  129. data/test/fixtures/company_in_module.rb +0 -33
  130. data/test/fixtures/course.rb +0 -3
  131. data/test/fixtures/courses/java +0 -2
  132. data/test/fixtures/courses/ruby +0 -2
  133. data/test/fixtures/customer.rb +0 -30
  134. data/test/fixtures/customers/david +0 -6
  135. data/test/fixtures/db_definitions/mysql.sql +0 -96
  136. data/test/fixtures/db_definitions/mysql2.sql +0 -4
  137. data/test/fixtures/db_definitions/postgresql.sql +0 -113
  138. data/test/fixtures/db_definitions/postgresql2.sql +0 -4
  139. data/test/fixtures/db_definitions/sqlite.sql +0 -85
  140. data/test/fixtures/db_definitions/sqlite2.sql +0 -4
  141. data/test/fixtures/default.rb +0 -2
  142. data/test/fixtures/developer.rb +0 -8
  143. data/test/fixtures/developers/david +0 -2
  144. data/test/fixtures/developers/jamis +0 -2
  145. data/test/fixtures/developers_projects/david_action_controller +0 -2
  146. data/test/fixtures/developers_projects/david_active_record +0 -2
  147. data/test/fixtures/developers_projects/jamis_active_record +0 -2
  148. data/test/fixtures/entrant.rb +0 -3
  149. data/test/fixtures/entrants/first +0 -3
  150. data/test/fixtures/entrants/second +0 -3
  151. data/test/fixtures/entrants/third +0 -3
  152. data/test/fixtures/fixture_database.sqlite +0 -0
  153. data/test/fixtures/fixture_database_2.sqlite +0 -0
  154. data/test/fixtures/movie.rb +0 -5
  155. data/test/fixtures/movies/first +0 -2
  156. data/test/fixtures/movies/second +0 -2
  157. data/test/fixtures/project.rb +0 -3
  158. data/test/fixtures/projects/action_controller +0 -2
  159. data/test/fixtures/projects/active_record +0 -2
  160. data/test/fixtures/reply.rb +0 -21
  161. data/test/fixtures/subscriber.rb +0 -5
  162. data/test/fixtures/subscribers/first +0 -2
  163. data/test/fixtures/subscribers/second +0 -2
  164. data/test/fixtures/topic.rb +0 -20
  165. data/test/fixtures/topics/first +0 -9
  166. data/test/fixtures/topics/second +0 -8
  167. data/test/fixtures_test.rb +0 -20
  168. data/test/inflector_test.rb +0 -104
  169. data/test/inheritance_test.rb +0 -125
  170. data/test/lifecycle_test.rb +0 -110
  171. data/test/modules_test.rb +0 -21
  172. data/test/multiple_db_test.rb +0 -46
  173. data/test/pk_test.rb +0 -57
  174. data/test/reflection_test.rb +0 -78
  175. data/test/thread_safety_test.rb +0 -33
  176. data/test/transactions_test.rb +0 -83
  177. data/test/unconnected_test.rb +0 -24
  178. data/test/validations_test.rb +0 -126
@@ -0,0 +1,393 @@
1
+ require 'active_support/core_ext/object/blank'
2
+
3
+ module ActiveRecord
4
+ # = Active Record Relation
5
+ class Relation
6
+ JoinOperation = Struct.new(:relation, :join_class, :on)
7
+ ASSOCIATION_METHODS = [:includes, :eager_load, :preload]
8
+ MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having]
9
+ SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :create_with, :from]
10
+
11
+ include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches
12
+
13
+ delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
14
+ delegate :insert, :to => :arel
15
+
16
+ attr_reader :table, :klass, :loaded
17
+ attr_accessor :extensions
18
+ alias :loaded? :loaded
19
+
20
+ def initialize(klass, table)
21
+ @klass, @table = klass, table
22
+
23
+ @implicit_readonly = nil
24
+ @loaded = 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
+ end
30
+
31
+ def new(*args, &block)
32
+ scoping { @klass.new(*args, &block) }
33
+ end
34
+
35
+ def initialize_copy(other)
36
+ reset
37
+ end
38
+
39
+ alias build new
40
+
41
+ def create(*args, &block)
42
+ scoping { @klass.create(*args, &block) }
43
+ end
44
+
45
+ def create!(*args, &block)
46
+ scoping { @klass.create!(*args, &block) }
47
+ end
48
+
49
+ def respond_to?(method, include_private = false)
50
+ return true if arel.respond_to?(method, include_private) || Array.method_defined?(method) || @klass.respond_to?(method, include_private)
51
+
52
+ if match = DynamicFinderMatch.match(method)
53
+ return true if @klass.send(:all_attributes_exists?, match.attribute_names)
54
+ elsif match = DynamicScopeMatch.match(method)
55
+ return true if @klass.send(:all_attributes_exists?, match.attribute_names)
56
+ else
57
+ super
58
+ end
59
+ end
60
+
61
+ def to_a
62
+ return @records if loaded?
63
+
64
+ @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql)
65
+
66
+ preload = @preload_values
67
+ preload += @includes_values unless eager_loading?
68
+ preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
69
+
70
+ # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
71
+ # are JOINS and no explicit SELECT.
72
+ readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
73
+ @records.each { |record| record.readonly! } if readonly
74
+
75
+ @loaded = true
76
+ @records
77
+ end
78
+
79
+ def as_json(options = nil) to_a end #:nodoc:
80
+
81
+ # Returns size of the records.
82
+ def size
83
+ loaded? ? @records.length : count
84
+ end
85
+
86
+ # Returns true if there are no records.
87
+ def empty?
88
+ loaded? ? @records.empty? : count.zero?
89
+ end
90
+
91
+ def any?
92
+ if block_given?
93
+ to_a.any? { |*block_args| yield(*block_args) }
94
+ else
95
+ !empty?
96
+ end
97
+ end
98
+
99
+ def many?
100
+ if block_given?
101
+ to_a.many? { |*block_args| yield(*block_args) }
102
+ else
103
+ @limit_value ? to_a.many? : size > 1
104
+ end
105
+ end
106
+
107
+ # Scope all queries to the current scope.
108
+ #
109
+ # ==== Example
110
+ #
111
+ # Comment.where(:post_id => 1).scoping do
112
+ # Comment.first # SELECT * FROM comments WHERE post_id = 1
113
+ # end
114
+ #
115
+ # Please check unscoped if you want to remove all previous scopes (including
116
+ # the default_scope) during the execution of a block.
117
+ def scoping
118
+ @klass.scoped_methods << self
119
+ begin
120
+ yield
121
+ ensure
122
+ @klass.scoped_methods.pop
123
+ end
124
+ end
125
+
126
+ # Updates all records with details given if they match a set of conditions supplied, limits and order can
127
+ # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
128
+ # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
129
+ # or validations.
130
+ #
131
+ # ==== Parameters
132
+ #
133
+ # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
134
+ # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
135
+ # See conditions in the intro.
136
+ # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
137
+ #
138
+ # ==== Examples
139
+ #
140
+ # # Update all customers with the given attributes
141
+ # Customer.update_all :wants_email => true
142
+ #
143
+ # # Update all books with 'Rails' in their title
144
+ # Book.update_all "author = 'David'", "title LIKE '%Rails%'"
145
+ #
146
+ # # Update all avatars migrated more than a week ago
147
+ # Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
148
+ #
149
+ # # Update all books that match conditions, but limit it to 5 ordered by date
150
+ # Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
151
+ def update_all(updates, conditions = nil, options = {})
152
+ if conditions || options.present?
153
+ where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
154
+ else
155
+ # Apply limit and order only if they're both present
156
+ if @limit_value.present? == @order_values.present?
157
+ arel.update(Arel::SqlLiteral.new(@klass.send(:sanitize_sql_for_assignment, updates)))
158
+ else
159
+ except(:limit, :order).update_all(updates)
160
+ end
161
+ end
162
+ end
163
+
164
+ # Updates an object (or multiple objects) and saves it to the database, if validations pass.
165
+ # The resulting object is returned whether the object was saved successfully to the database or not.
166
+ #
167
+ # ==== Parameters
168
+ #
169
+ # * +id+ - This should be the id or an array of ids to be updated.
170
+ # * +attributes+ - This should be a hash of attributes or an array of hashes.
171
+ #
172
+ # ==== Examples
173
+ #
174
+ # # Updates one record
175
+ # Person.update(15, :user_name => 'Samuel', :group => 'expert')
176
+ #
177
+ # # Updates multiple records
178
+ # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
179
+ # Person.update(people.keys, people.values)
180
+ def update(id, attributes)
181
+ if id.is_a?(Array)
182
+ idx = -1
183
+ id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
184
+ else
185
+ object = find(id)
186
+ object.update_attributes(attributes)
187
+ object
188
+ end
189
+ end
190
+
191
+ # Destroys the records matching +conditions+ by instantiating each
192
+ # record and calling its +destroy+ method. Each object's callbacks are
193
+ # executed (including <tt>:dependent</tt> association options and
194
+ # +before_destroy+/+after_destroy+ Observer methods). Returns the
195
+ # collection of objects that were destroyed; each will be frozen, to
196
+ # reflect that no changes should be made (since they can't be
197
+ # persisted).
198
+ #
199
+ # Note: Instantiation, callback execution, and deletion of each
200
+ # record can be time consuming when you're removing many records at
201
+ # once. It generates at least one SQL +DELETE+ query per record (or
202
+ # possibly more, to enforce your callbacks). If you want to delete many
203
+ # rows quickly, without concern for their associations or callbacks, use
204
+ # +delete_all+ instead.
205
+ #
206
+ # ==== Parameters
207
+ #
208
+ # * +conditions+ - A string, array, or hash that specifies which records
209
+ # to destroy. If omitted, all records are destroyed. See the
210
+ # Conditions section in the introduction to ActiveRecord::Base for
211
+ # more information.
212
+ #
213
+ # ==== Examples
214
+ #
215
+ # Person.destroy_all("last_login < '2004-04-04'")
216
+ # Person.destroy_all(:status => "inactive")
217
+ def destroy_all(conditions = nil)
218
+ if conditions
219
+ where(conditions).destroy_all
220
+ else
221
+ to_a.each {|object| object.destroy }.tap { reset }
222
+ end
223
+ end
224
+
225
+ # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
226
+ # therefore all callbacks and filters are fired off before the object is deleted. This method is
227
+ # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
228
+ #
229
+ # This essentially finds the object (or multiple objects) with the given id, creates a new object
230
+ # from the attributes, and then calls destroy on it.
231
+ #
232
+ # ==== Parameters
233
+ #
234
+ # * +id+ - Can be either an Integer or an Array of Integers.
235
+ #
236
+ # ==== Examples
237
+ #
238
+ # # Destroy a single object
239
+ # Todo.destroy(1)
240
+ #
241
+ # # Destroy multiple objects
242
+ # todos = [1,2,3]
243
+ # Todo.destroy(todos)
244
+ def destroy(id)
245
+ if id.is_a?(Array)
246
+ id.map { |one_id| destroy(one_id) }
247
+ else
248
+ find(id).destroy
249
+ end
250
+ end
251
+
252
+ # Deletes the records matching +conditions+ without instantiating the records first, and hence not
253
+ # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
254
+ # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
255
+ # though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
256
+ # the number of rows affected.
257
+ #
258
+ # ==== Parameters
259
+ #
260
+ # * +conditions+ - Conditions are specified the same way as with +find+ method.
261
+ #
262
+ # ==== Example
263
+ #
264
+ # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
265
+ # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
266
+ #
267
+ # Both calls delete the affected posts all at once with a single DELETE statement.
268
+ # If you need to destroy dependent associations or call your <tt>before_*</tt> or
269
+ # +after_destroy+ callbacks, use the +destroy_all+ method instead.
270
+ def delete_all(conditions = nil)
271
+ conditions ? where(conditions).delete_all : arel.delete.tap { reset }
272
+ end
273
+
274
+ # Deletes the row with a primary key matching the +id+ argument, using a
275
+ # SQL +DELETE+ statement, and returns the number of rows deleted. Active
276
+ # Record objects are not instantiated, so the object's callbacks are not
277
+ # executed, including any <tt>:dependent</tt> association options or
278
+ # Observer methods.
279
+ #
280
+ # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
281
+ #
282
+ # Note: Although it is often much faster than the alternative,
283
+ # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
284
+ # your application that ensures referential integrity or performs other
285
+ # essential jobs.
286
+ #
287
+ # ==== Examples
288
+ #
289
+ # # Delete a single row
290
+ # Todo.delete(1)
291
+ #
292
+ # # Delete multiple rows
293
+ # Todo.delete([2,3,4])
294
+ def delete(id_or_array)
295
+ where(@klass.primary_key => id_or_array).delete_all
296
+ end
297
+
298
+ def reload
299
+ reset
300
+ to_a # force reload
301
+ self
302
+ end
303
+
304
+ def reset
305
+ @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
306
+ @should_eager_load = @join_dependency = nil
307
+ @records = []
308
+ self
309
+ end
310
+
311
+ def primary_key
312
+ @primary_key ||= table[@klass.primary_key]
313
+ end
314
+
315
+ def to_sql
316
+ @to_sql ||= arel.to_sql
317
+ end
318
+
319
+ def where_values_hash
320
+ Hash[@where_values.find_all { |w|
321
+ w.respond_to?(:operator) && w.operator == :==
322
+ }.map { |where|
323
+ [where.operand1.name,
324
+ where.operand2.respond_to?(:value) ?
325
+ where.operand2.value : where.operand2]
326
+ }]
327
+ end
328
+
329
+ def scope_for_create
330
+ @scope_for_create ||= begin
331
+ @create_with_value || where_values_hash
332
+ end
333
+ end
334
+
335
+ def eager_loading?
336
+ @should_eager_load ||= (@eager_load_values.any? || (@includes_values.any? && references_eager_loaded_tables?))
337
+ end
338
+
339
+ def ==(other)
340
+ case other
341
+ when Relation
342
+ other.to_sql == to_sql
343
+ when Array
344
+ to_a == other.to_a
345
+ end
346
+ end
347
+
348
+ def inspect
349
+ to_a.inspect
350
+ end
351
+
352
+ protected
353
+
354
+ def method_missing(method, *args, &block)
355
+ if Array.method_defined?(method)
356
+ to_a.send(method, *args, &block)
357
+ elsif @klass.scopes[method]
358
+ merge(@klass.send(method, *args, &block))
359
+ elsif @klass.respond_to?(method)
360
+ scoping { @klass.send(method, *args, &block) }
361
+ elsif arel.respond_to?(method)
362
+ arel.send(method, *args, &block)
363
+ elsif match = DynamicFinderMatch.match(method)
364
+ attributes = match.attribute_names
365
+ super unless @klass.send(:all_attributes_exists?, attributes)
366
+
367
+ if match.finder?
368
+ find_by_attributes(match, attributes, *args)
369
+ elsif match.instantiator?
370
+ find_or_instantiator_by_attributes(match, attributes, *args, &block)
371
+ end
372
+ else
373
+ super
374
+ end
375
+ end
376
+
377
+ private
378
+
379
+ def references_eager_loaded_tables?
380
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
381
+ joined_tables = (tables_in_string(arel.joins(arel)) + [table.name, table.table_alias]).compact.map{ |t| t.downcase }.uniq
382
+ (tables_in_string(to_sql) - joined_tables).any?
383
+ end
384
+
385
+ def tables_in_string(string)
386
+ return [] if string.blank?
387
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
388
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
389
+ string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
390
+ end
391
+
392
+ end
393
+ end
@@ -0,0 +1,59 @@
1
+ require 'active_support/core_ext/object/blank'
2
+
3
+ module ActiveRecord
4
+ # = Active Record Schema
5
+ #
6
+ # Allows programmers to programmatically define a schema in a portable
7
+ # DSL. This means you can define tables, indexes, etc. without using SQL
8
+ # directly, so your applications can more easily support multiple
9
+ # databases.
10
+ #
11
+ # Usage:
12
+ #
13
+ # ActiveRecord::Schema.define do
14
+ # create_table :authors do |t|
15
+ # t.string :name, :null => false
16
+ # end
17
+ #
18
+ # add_index :authors, :name, :unique
19
+ #
20
+ # create_table :posts do |t|
21
+ # t.integer :author_id, :null => false
22
+ # t.string :subject
23
+ # t.text :body
24
+ # t.boolean :private, :default => false
25
+ # end
26
+ #
27
+ # add_index :posts, :author_id
28
+ # end
29
+ #
30
+ # ActiveRecord::Schema is only supported by database adapters that also
31
+ # support migrations, the two features being very similar.
32
+ class Schema < Migration
33
+ private_class_method :new
34
+
35
+ def self.migrations_path
36
+ ActiveRecord::Migrator.migrations_path
37
+ end
38
+
39
+ # Eval the given block. All methods available to the current connection
40
+ # adapter are available within the block, so you can easily use the
41
+ # database definition DSL to build up your schema (+create_table+,
42
+ # +add_index+, etc.).
43
+ #
44
+ # The +info+ hash is optional, and if given is used to define metadata
45
+ # about the current schema (currently, only the schema's version):
46
+ #
47
+ # ActiveRecord::Schema.define(:version => 20380119000001) do
48
+ # ...
49
+ # end
50
+ def self.define(info={}, &block)
51
+ instance_eval(&block)
52
+
53
+ unless info[:version].blank?
54
+ initialize_schema_migrations_table
55
+ assume_migrated_upto_version(info[:version], migrations_path)
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,195 @@
1
+ require 'stringio'
2
+ require 'active_support/core_ext/big_decimal'
3
+
4
+ module ActiveRecord
5
+ # = Active Record Schema Dumper
6
+ #
7
+ # This class is used to dump the database schema for some connection to some
8
+ # output format (i.e., ActiveRecord::Schema).
9
+ class SchemaDumper #:nodoc:
10
+ private_class_method :new
11
+
12
+ ##
13
+ # :singleton-method:
14
+ # A list of tables which should not be dumped to the schema.
15
+ # Acceptable values are strings as well as regexp.
16
+ # This setting is only used if ActiveRecord::Base.schema_format == :ruby
17
+ cattr_accessor :ignore_tables
18
+ @@ignore_tables = []
19
+
20
+ def self.dump(connection=ActiveRecord::Base.connection, stream=STDOUT)
21
+ new(connection).dump(stream)
22
+ stream
23
+ end
24
+
25
+ def dump(stream)
26
+ header(stream)
27
+ tables(stream)
28
+ trailer(stream)
29
+ stream
30
+ end
31
+
32
+ private
33
+
34
+ def initialize(connection)
35
+ @connection = connection
36
+ @types = @connection.native_database_types
37
+ @version = Migrator::current_version rescue nil
38
+ end
39
+
40
+ def header(stream)
41
+ define_params = @version ? ":version => #{@version}" : ""
42
+
43
+ stream.puts <<HEADER
44
+ # This file is auto-generated from the current state of the database. Instead
45
+ # of editing this file, please use the migrations feature of Active Record to
46
+ # incrementally modify your database, and then regenerate this schema definition.
47
+ #
48
+ # Note that this schema.rb definition is the authoritative source for your
49
+ # database schema. If you need to create the application database on another
50
+ # system, you should be using db:schema:load, not running all the migrations
51
+ # from scratch. The latter is a flawed and unsustainable approach (the more migrations
52
+ # you'll amass, the slower it'll run and the greater likelihood for issues).
53
+ #
54
+ # It's strongly recommended to check this file into your version control system.
55
+
56
+ ActiveRecord::Schema.define(#{define_params}) do
57
+
58
+ HEADER
59
+ end
60
+
61
+ def trailer(stream)
62
+ stream.puts "end"
63
+ end
64
+
65
+ def tables(stream)
66
+ @connection.tables.sort.each do |tbl|
67
+ next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
68
+ case ignored
69
+ when String; tbl == ignored
70
+ when Regexp; tbl =~ ignored
71
+ else
72
+ raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
73
+ end
74
+ end
75
+ table(tbl, stream)
76
+ end
77
+ end
78
+
79
+ def table(table, stream)
80
+ columns = @connection.columns(table)
81
+ begin
82
+ tbl = StringIO.new
83
+
84
+ # first dump primary key column
85
+ if @connection.respond_to?(:pk_and_sequence_for)
86
+ pk, pk_seq = @connection.pk_and_sequence_for(table)
87
+ elsif @connection.respond_to?(:primary_key)
88
+ pk = @connection.primary_key(table)
89
+ end
90
+
91
+ tbl.print " create_table #{table.inspect}"
92
+ if columns.detect { |c| c.name == pk }
93
+ if pk != 'id'
94
+ tbl.print %Q(, :primary_key => "#{pk}")
95
+ end
96
+ else
97
+ tbl.print ", :id => false"
98
+ end
99
+ tbl.print ", :force => true"
100
+ tbl.puts " do |t|"
101
+
102
+ # then dump all non-primary key columns
103
+ column_specs = columns.map do |column|
104
+ raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil?
105
+ next if column.name == pk
106
+ spec = {}
107
+ spec[:name] = column.name.inspect
108
+
109
+ # AR has an optimisation which handles zero-scale decimals as integers. This
110
+ # code ensures that the dumper still dumps the column as a decimal.
111
+ spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) }
112
+ 'decimal'
113
+ else
114
+ column.type.to_s
115
+ end
116
+ spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal'
117
+ spec[:precision] = column.precision.inspect if !column.precision.nil?
118
+ spec[:scale] = column.scale.inspect if !column.scale.nil?
119
+ spec[:null] = 'false' if !column.null
120
+ spec[:default] = default_string(column.default) if column.has_default?
121
+ (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")}
122
+ spec
123
+ end.compact
124
+
125
+ # find all migration keys used in this table
126
+ keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map{ |k| k.keys }.flatten
127
+
128
+ # figure out the lengths for each column based on above keys
129
+ lengths = keys.map{ |key| column_specs.map{ |spec| spec[key] ? spec[key].length + 2 : 0 }.max }
130
+
131
+ # the string we're going to sprintf our values against, with standardized column widths
132
+ format_string = lengths.map{ |len| "%-#{len}s" }
133
+
134
+ # find the max length for the 'type' column, which is special
135
+ type_length = column_specs.map{ |column| column[:type].length }.max
136
+
137
+ # add column type definition to our format string
138
+ format_string.unshift " t.%-#{type_length}s "
139
+
140
+ format_string *= ''
141
+
142
+ column_specs.each do |colspec|
143
+ values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
144
+ values.unshift colspec[:type]
145
+ tbl.print((format_string % values).gsub(/,\s*$/, ''))
146
+ tbl.puts
147
+ end
148
+
149
+ tbl.puts " end"
150
+ tbl.puts
151
+
152
+ indexes(table, tbl)
153
+
154
+ tbl.rewind
155
+ stream.print tbl.read
156
+ rescue => e
157
+ stream.puts "# Could not dump table #{table.inspect} because of following #{e.class}"
158
+ stream.puts "# #{e.message}"
159
+ stream.puts
160
+ end
161
+
162
+ stream
163
+ end
164
+
165
+ def default_string(value)
166
+ case value
167
+ when BigDecimal
168
+ value.to_s
169
+ when Date, DateTime, Time
170
+ "'" + value.to_s(:db) + "'"
171
+ else
172
+ value.inspect
173
+ end
174
+ end
175
+
176
+ def indexes(table, stream)
177
+ if (indexes = @connection.indexes(table)).any?
178
+ add_index_statements = indexes.map do |index|
179
+ statement_parts = [ ('add_index ' + index.table.inspect) ]
180
+ statement_parts << index.columns.inspect
181
+ statement_parts << (':name => ' + index.name.inspect)
182
+ statement_parts << ':unique => true' if index.unique
183
+
184
+ index_lengths = index.lengths.compact if index.lengths.is_a?(Array)
185
+ statement_parts << (':length => ' + Hash[*index.columns.zip(index.lengths).flatten].inspect) if index_lengths.present?
186
+
187
+ ' ' + statement_parts.join(', ')
188
+ end
189
+
190
+ stream.puts add_index_statements.sort.join("\n")
191
+ stream.puts
192
+ end
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,60 @@
1
+ module ActiveRecord #:nodoc:
2
+ # = Active Record Serialization
3
+ module Serialization
4
+ extend ActiveSupport::Concern
5
+ include ActiveModel::Serializers::JSON
6
+
7
+ def serializable_hash(options = nil)
8
+ options ||= {}
9
+
10
+ options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
11
+ options[:except] |= Array.wrap(self.class.inheritance_column)
12
+
13
+ hash = super(options)
14
+
15
+ serializable_add_includes(options) do |association, records, opts|
16
+ hash[association] = records.is_a?(Enumerable) ?
17
+ records.map { |r| r.serializable_hash(opts) } :
18
+ records.serializable_hash(opts)
19
+ end
20
+
21
+ hash
22
+ end
23
+
24
+ private
25
+ # Add associations specified via the <tt>:includes</tt> option.
26
+ #
27
+ # Expects a block that takes as arguments:
28
+ # +association+ - name of the association
29
+ # +records+ - the association record(s) to be serialized
30
+ # +opts+ - options for the association records
31
+ def serializable_add_includes(options = {})
32
+ return unless include_associations = options.delete(:include)
33
+
34
+ base_only_or_except = { :except => options[:except],
35
+ :only => options[:only] }
36
+
37
+ include_has_options = include_associations.is_a?(Hash)
38
+ associations = include_has_options ? include_associations.keys : Array.wrap(include_associations)
39
+
40
+ for association in associations
41
+ records = case self.class.reflect_on_association(association).macro
42
+ when :has_many, :has_and_belongs_to_many
43
+ send(association).to_a
44
+ when :has_one, :belongs_to
45
+ send(association)
46
+ end
47
+
48
+ unless records.nil?
49
+ association_options = include_has_options ? include_associations[association] : base_only_or_except
50
+ opts = options.merge(association_options)
51
+ yield(association, records, opts)
52
+ end
53
+ end
54
+
55
+ options[:include] = include_associations
56
+ end
57
+ end
58
+ end
59
+
60
+ require 'active_record/serializers/xml_serializer'