activerecord 3.0.0 → 4.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 (181) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +2102 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +35 -44
  5. data/examples/performance.rb +110 -100
  6. data/lib/active_record/aggregations.rb +59 -75
  7. data/lib/active_record/associations/alias_tracker.rb +76 -0
  8. data/lib/active_record/associations/association.rb +248 -0
  9. data/lib/active_record/associations/association_scope.rb +135 -0
  10. data/lib/active_record/associations/belongs_to_association.rb +60 -59
  11. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +16 -59
  12. data/lib/active_record/associations/builder/association.rb +108 -0
  13. data/lib/active_record/associations/builder/belongs_to.rb +98 -0
  14. data/lib/active_record/associations/builder/collection_association.rb +89 -0
  15. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +39 -0
  16. data/lib/active_record/associations/builder/has_many.rb +15 -0
  17. data/lib/active_record/associations/builder/has_one.rb +25 -0
  18. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  19. data/lib/active_record/associations/collection_association.rb +608 -0
  20. data/lib/active_record/associations/collection_proxy.rb +986 -0
  21. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +40 -112
  22. data/lib/active_record/associations/has_many_association.rb +83 -76
  23. data/lib/active_record/associations/has_many_through_association.rb +147 -66
  24. data/lib/active_record/associations/has_one_association.rb +67 -108
  25. data/lib/active_record/associations/has_one_through_association.rb +21 -25
  26. data/lib/active_record/associations/join_dependency/join_association.rb +174 -0
  27. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  28. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  29. data/lib/active_record/associations/join_dependency.rb +235 -0
  30. data/lib/active_record/associations/join_helper.rb +45 -0
  31. data/lib/active_record/associations/preloader/association.rb +121 -0
  32. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  33. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  34. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  35. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  36. data/lib/active_record/associations/preloader/has_many_through.rb +19 -0
  37. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  38. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  39. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  40. data/lib/active_record/associations/preloader/through_association.rb +63 -0
  41. data/lib/active_record/associations/preloader.rb +178 -0
  42. data/lib/active_record/associations/singular_association.rb +64 -0
  43. data/lib/active_record/associations/through_association.rb +87 -0
  44. data/lib/active_record/associations.rb +512 -1224
  45. data/lib/active_record/attribute_assignment.rb +201 -0
  46. data/lib/active_record/attribute_methods/before_type_cast.rb +49 -12
  47. data/lib/active_record/attribute_methods/dirty.rb +51 -28
  48. data/lib/active_record/attribute_methods/primary_key.rb +94 -22
  49. data/lib/active_record/attribute_methods/query.rb +5 -4
  50. data/lib/active_record/attribute_methods/read.rb +63 -72
  51. data/lib/active_record/attribute_methods/serialization.rb +162 -0
  52. data/lib/active_record/attribute_methods/time_zone_conversion.rb +39 -41
  53. data/lib/active_record/attribute_methods/write.rb +39 -13
  54. data/lib/active_record/attribute_methods.rb +362 -29
  55. data/lib/active_record/autosave_association.rb +132 -75
  56. data/lib/active_record/base.rb +83 -1627
  57. data/lib/active_record/callbacks.rb +69 -47
  58. data/lib/active_record/coders/yaml_column.rb +38 -0
  59. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +411 -138
  60. data/lib/active_record/connection_adapters/abstract/database_limits.rb +21 -11
  61. data/lib/active_record/connection_adapters/abstract/database_statements.rb +234 -173
  62. data/lib/active_record/connection_adapters/abstract/query_cache.rb +36 -22
  63. data/lib/active_record/connection_adapters/abstract/quoting.rb +82 -25
  64. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +176 -414
  65. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +70 -0
  66. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +562 -232
  67. data/lib/active_record/connection_adapters/abstract/transaction.rb +203 -0
  68. data/lib/active_record/connection_adapters/abstract_adapter.rb +281 -53
  69. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +782 -0
  70. data/lib/active_record/connection_adapters/column.rb +318 -0
  71. data/lib/active_record/connection_adapters/connection_specification.rb +96 -0
  72. data/lib/active_record/connection_adapters/mysql2_adapter.rb +273 -0
  73. data/lib/active_record/connection_adapters/mysql_adapter.rb +365 -450
  74. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +97 -0
  75. data/lib/active_record/connection_adapters/postgresql/cast.rb +152 -0
  76. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +242 -0
  77. data/lib/active_record/connection_adapters/postgresql/oid.rb +366 -0
  78. data/lib/active_record/connection_adapters/postgresql/quoting.rb +171 -0
  79. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  80. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +489 -0
  81. data/lib/active_record/connection_adapters/postgresql_adapter.rb +672 -752
  82. data/lib/active_record/connection_adapters/schema_cache.rb +129 -0
  83. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +588 -17
  84. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  85. data/lib/active_record/connection_handling.rb +98 -0
  86. data/lib/active_record/core.rb +463 -0
  87. data/lib/active_record/counter_cache.rb +108 -101
  88. data/lib/active_record/dynamic_matchers.rb +131 -0
  89. data/lib/active_record/errors.rb +54 -13
  90. data/lib/active_record/explain.rb +38 -0
  91. data/lib/active_record/explain_registry.rb +30 -0
  92. data/lib/active_record/explain_subscriber.rb +29 -0
  93. data/lib/active_record/fixture_set/file.rb +55 -0
  94. data/lib/active_record/fixtures.rb +703 -785
  95. data/lib/active_record/inheritance.rb +200 -0
  96. data/lib/active_record/integration.rb +60 -0
  97. data/lib/active_record/locale/en.yml +8 -1
  98. data/lib/active_record/locking/optimistic.rb +69 -60
  99. data/lib/active_record/locking/pessimistic.rb +34 -12
  100. data/lib/active_record/log_subscriber.rb +40 -6
  101. data/lib/active_record/migration/command_recorder.rb +164 -0
  102. data/lib/active_record/migration/join_table.rb +15 -0
  103. data/lib/active_record/migration.rb +614 -216
  104. data/lib/active_record/model_schema.rb +345 -0
  105. data/lib/active_record/nested_attributes.rb +248 -119
  106. data/lib/active_record/null_relation.rb +65 -0
  107. data/lib/active_record/persistence.rb +275 -57
  108. data/lib/active_record/query_cache.rb +29 -9
  109. data/lib/active_record/querying.rb +62 -0
  110. data/lib/active_record/railtie.rb +135 -21
  111. data/lib/active_record/railties/console_sandbox.rb +5 -0
  112. data/lib/active_record/railties/controller_runtime.rb +17 -5
  113. data/lib/active_record/railties/databases.rake +249 -359
  114. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  115. data/lib/active_record/readonly_attributes.rb +30 -0
  116. data/lib/active_record/reflection.rb +283 -103
  117. data/lib/active_record/relation/batches.rb +38 -34
  118. data/lib/active_record/relation/calculations.rb +252 -139
  119. data/lib/active_record/relation/delegation.rb +125 -0
  120. data/lib/active_record/relation/finder_methods.rb +182 -188
  121. data/lib/active_record/relation/merger.rb +161 -0
  122. data/lib/active_record/relation/predicate_builder.rb +86 -21
  123. data/lib/active_record/relation/query_methods.rb +917 -134
  124. data/lib/active_record/relation/spawn_methods.rb +53 -92
  125. data/lib/active_record/relation.rb +405 -143
  126. data/lib/active_record/result.rb +67 -0
  127. data/lib/active_record/runtime_registry.rb +17 -0
  128. data/lib/active_record/sanitization.rb +168 -0
  129. data/lib/active_record/schema.rb +20 -14
  130. data/lib/active_record/schema_dumper.rb +55 -46
  131. data/lib/active_record/schema_migration.rb +39 -0
  132. data/lib/active_record/scoping/default.rb +146 -0
  133. data/lib/active_record/scoping/named.rb +175 -0
  134. data/lib/active_record/scoping.rb +82 -0
  135. data/lib/active_record/serialization.rb +8 -46
  136. data/lib/active_record/serializers/xml_serializer.rb +21 -68
  137. data/lib/active_record/statement_cache.rb +26 -0
  138. data/lib/active_record/store.rb +156 -0
  139. data/lib/active_record/tasks/database_tasks.rb +203 -0
  140. data/lib/active_record/tasks/firebird_database_tasks.rb +56 -0
  141. data/lib/active_record/tasks/mysql_database_tasks.rb +143 -0
  142. data/lib/active_record/tasks/oracle_database_tasks.rb +45 -0
  143. data/lib/active_record/tasks/postgresql_database_tasks.rb +90 -0
  144. data/lib/active_record/tasks/sqlite_database_tasks.rb +51 -0
  145. data/lib/active_record/tasks/sqlserver_database_tasks.rb +48 -0
  146. data/lib/active_record/test_case.rb +57 -28
  147. data/lib/active_record/timestamp.rb +49 -18
  148. data/lib/active_record/transactions.rb +106 -63
  149. data/lib/active_record/translation.rb +22 -0
  150. data/lib/active_record/validations/associated.rb +25 -24
  151. data/lib/active_record/validations/presence.rb +65 -0
  152. data/lib/active_record/validations/uniqueness.rb +123 -83
  153. data/lib/active_record/validations.rb +29 -29
  154. data/lib/active_record/version.rb +7 -5
  155. data/lib/active_record.rb +83 -34
  156. data/lib/rails/generators/active_record/migration/migration_generator.rb +46 -9
  157. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +19 -0
  158. data/lib/rails/generators/active_record/migration/templates/migration.rb +30 -8
  159. data/lib/rails/generators/active_record/model/model_generator.rb +15 -5
  160. data/lib/rails/generators/active_record/model/templates/model.rb +7 -2
  161. data/lib/rails/generators/active_record/model/templates/module.rb +3 -1
  162. data/lib/rails/generators/active_record.rb +4 -8
  163. metadata +163 -121
  164. data/CHANGELOG +0 -6023
  165. data/examples/associations.png +0 -0
  166. data/lib/active_record/association_preload.rb +0 -403
  167. data/lib/active_record/associations/association_collection.rb +0 -562
  168. data/lib/active_record/associations/association_proxy.rb +0 -295
  169. data/lib/active_record/associations/through_association_scope.rb +0 -154
  170. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +0 -113
  171. data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -401
  172. data/lib/active_record/dynamic_finder_match.rb +0 -53
  173. data/lib/active_record/dynamic_scope_match.rb +0 -32
  174. data/lib/active_record/named_scope.rb +0 -138
  175. data/lib/active_record/observer.rb +0 -140
  176. data/lib/active_record/session_store.rb +0 -340
  177. data/lib/rails/generators/active_record/model/templates/migration.rb +0 -16
  178. data/lib/rails/generators/active_record/observer/observer_generator.rb +0 -15
  179. data/lib/rails/generators/active_record/observer/templates/observer.rb +0 -2
  180. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +0 -24
  181. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +0 -16
@@ -1,261 +1,1044 @@
1
1
  require 'active_support/core_ext/array/wrap'
2
- require 'active_support/core_ext/object/blank'
3
2
 
4
3
  module ActiveRecord
5
4
  module QueryMethods
6
5
  extend ActiveSupport::Concern
7
6
 
8
- attr_accessor :includes_values, :eager_load_values, :preload_values,
9
- :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values,
10
- :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, :from_value
7
+ # WhereChain objects act as placeholder for queries in which #where does not have any parameter.
8
+ # In this case, #where must be chained with #not to return a new relation.
9
+ class WhereChain
10
+ def initialize(scope)
11
+ @scope = scope
12
+ end
13
+
14
+ # Returns a new relation expressing WHERE + NOT condition according to
15
+ # the conditions in the arguments.
16
+ #
17
+ # +not+ accepts conditions as a string, array, or hash. See #where for
18
+ # more details on each format.
19
+ #
20
+ # User.where.not("name = 'Jon'")
21
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
22
+ #
23
+ # User.where.not(["name = ?", "Jon"])
24
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
25
+ #
26
+ # User.where.not(name: "Jon")
27
+ # # SELECT * FROM users WHERE name != 'Jon'
28
+ #
29
+ # User.where.not(name: nil)
30
+ # # SELECT * FROM users WHERE name IS NOT NULL
31
+ #
32
+ # User.where.not(name: %w(Ko1 Nobu))
33
+ # # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
34
+ #
35
+ # User.where.not(name: "Jon", role: "admin")
36
+ # # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
37
+ def not(opts, *rest)
38
+ where_value = @scope.send(:build_where, opts, rest).map do |rel|
39
+ case rel
40
+ when Arel::Nodes::In
41
+ Arel::Nodes::NotIn.new(rel.left, rel.right)
42
+ when Arel::Nodes::Equality
43
+ Arel::Nodes::NotEqual.new(rel.left, rel.right)
44
+ when String
45
+ Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
46
+ else
47
+ Arel::Nodes::Not.new(rel)
48
+ end
49
+ end
50
+ @scope.where_values += where_value
51
+ @scope
52
+ end
53
+ end
54
+
55
+ Relation::MULTI_VALUE_METHODS.each do |name|
56
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
57
+ def #{name}_values # def select_values
58
+ @values[:#{name}] || [] # @values[:select] || []
59
+ end # end
60
+ #
61
+ def #{name}_values=(values) # def select_values=(values)
62
+ raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
63
+ @values[:#{name}] = values # @values[:select] = values
64
+ end # end
65
+ CODE
66
+ end
67
+
68
+ (Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
69
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
70
+ def #{name}_value # def readonly_value
71
+ @values[:#{name}] # @values[:readonly]
72
+ end # end
73
+ CODE
74
+ end
75
+
76
+ Relation::SINGLE_VALUE_METHODS.each do |name|
77
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
78
+ def #{name}_value=(value) # def readonly_value=(value)
79
+ raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
80
+ @values[:#{name}] = value # @values[:readonly] = value
81
+ end # end
82
+ CODE
83
+ end
11
84
 
85
+ def create_with_value # :nodoc:
86
+ @values[:create_with] || {}
87
+ end
88
+
89
+ alias extensions extending_values
90
+
91
+ # Specify relationships to be included in the result set. For
92
+ # example:
93
+ #
94
+ # users = User.includes(:address)
95
+ # users.each do |user|
96
+ # user.address.city
97
+ # end
98
+ #
99
+ # allows you to access the +address+ attribute of the +User+ model without
100
+ # firing an additional query. This will often result in a
101
+ # performance improvement over a simple +join+.
102
+ #
103
+ # === conditions
104
+ #
105
+ # If you want to add conditions to your included models you'll have
106
+ # to explicitly reference them. For example:
107
+ #
108
+ # User.includes(:posts).where('posts.name = ?', 'example')
109
+ #
110
+ # Will throw an error, but this will work:
111
+ #
112
+ # User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
12
113
  def includes(*args)
13
- args.reject! { |a| a.blank? }
14
- clone.tap {|r| r.includes_values = (r.includes_values + args).flatten.uniq if args.present? }
114
+ check_if_method_has_arguments!("includes", args)
115
+ spawn.includes!(*args)
116
+ end
117
+
118
+ def includes!(*args) # :nodoc:
119
+ args.reject! {|a| a.blank? }
120
+
121
+ self.includes_values = (includes_values + args).flatten.uniq
122
+ self
15
123
  end
16
124
 
125
+ # Forces eager loading by performing a LEFT OUTER JOIN on +args+:
126
+ #
127
+ # User.eager_load(:posts)
128
+ # => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
129
+ # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
130
+ # "users"."id"
17
131
  def eager_load(*args)
18
- clone.tap {|r| r.eager_load_values += args if args.present? }
132
+ check_if_method_has_arguments!("eager_load", args)
133
+ spawn.eager_load!(*args)
19
134
  end
20
135
 
136
+ def eager_load!(*args) # :nodoc:
137
+ self.eager_load_values += args
138
+ self
139
+ end
140
+
141
+ # Allows preloading of +args+, in the same way that +includes+ does:
142
+ #
143
+ # User.preload(:posts)
144
+ # => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
21
145
  def preload(*args)
22
- clone.tap {|r| r.preload_values += args if args.present? }
146
+ check_if_method_has_arguments!("preload", args)
147
+ spawn.preload!(*args)
23
148
  end
24
149
 
25
- def select(*args)
150
+ def preload!(*args) # :nodoc:
151
+ self.preload_values += args
152
+ self
153
+ end
154
+
155
+ # Used to indicate that an association is referenced by an SQL string, and should
156
+ # therefore be JOINed in any query rather than loaded separately.
157
+ #
158
+ # User.includes(:posts).where("posts.name = 'foo'")
159
+ # # => Doesn't JOIN the posts table, resulting in an error.
160
+ #
161
+ # User.includes(:posts).where("posts.name = 'foo'").references(:posts)
162
+ # # => Query now knows the string references posts, so adds a JOIN
163
+ def references(*args)
164
+ check_if_method_has_arguments!("references", args)
165
+ spawn.references!(*args)
166
+ end
167
+
168
+ def references!(*args) # :nodoc:
169
+ args.flatten!
170
+
171
+ self.references_values = (references_values + args.map!(&:to_s)).uniq
172
+ self
173
+ end
174
+
175
+ # Works in two unique ways.
176
+ #
177
+ # First: takes a block so it can be used just like Array#select.
178
+ #
179
+ # Model.all.select { |m| m.field == value }
180
+ #
181
+ # This will build an array of objects from the database for the scope,
182
+ # converting them into an array and iterating through them using Array#select.
183
+ #
184
+ # Second: Modifies the SELECT statement for the query so that only certain
185
+ # fields are retrieved:
186
+ #
187
+ # Model.select(:field)
188
+ # # => [#<Model field:value>]
189
+ #
190
+ # Although in the above example it looks as though this method returns an
191
+ # array, it actually returns a relation object and can have other query
192
+ # methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
193
+ #
194
+ # The argument to the method can also be an array of fields.
195
+ #
196
+ # Model.select(:field, :other_field, :and_one_more)
197
+ # # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
198
+ #
199
+ # You can also use one or more strings, which will be used unchanged as SELECT fields.
200
+ #
201
+ # Model.select('field AS field_one', 'other_field AS field_two')
202
+ # # => [#<Model field: "value", other_field: "value">]
203
+ #
204
+ # If an alias was specified, it will be accessible from the resulting objects:
205
+ #
206
+ # Model.select('field AS field_one').first.field_one
207
+ # # => "value"
208
+ #
209
+ # Accessing attributes of an object that do not have fields retrieved by a select
210
+ # will throw <tt>ActiveModel::MissingAttributeError</tt>:
211
+ #
212
+ # Model.select(:field).first.other_field
213
+ # # => ActiveModel::MissingAttributeError: missing attribute: other_field
214
+ def select(*fields)
26
215
  if block_given?
27
- to_a.select {|*block_args| yield(*block_args) }
216
+ to_a.select { |*block_args| yield(*block_args) }
28
217
  else
29
- clone.tap {|r| r.select_values += args if args.present? }
218
+ raise ArgumentError, 'Call this with at least one field' if fields.empty?
219
+ spawn.select!(*fields)
30
220
  end
31
221
  end
32
222
 
223
+ def select!(*fields) # :nodoc:
224
+ self.select_values += fields.flatten
225
+ self
226
+ end
227
+
228
+ # Allows to specify a group attribute:
229
+ #
230
+ # User.group(:name)
231
+ # => SELECT "users".* FROM "users" GROUP BY name
232
+ #
233
+ # Returns an array with distinct records based on the +group+ attribute:
234
+ #
235
+ # User.select([:id, :name])
236
+ # => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
237
+ #
238
+ # User.group(:name)
239
+ # => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
240
+ #
241
+ # User.group('name AS grouped_name, age')
242
+ # => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
33
243
  def group(*args)
34
- clone.tap {|r| r.group_values += args.flatten if args.present? }
244
+ check_if_method_has_arguments!("group", args)
245
+ spawn.group!(*args)
246
+ end
247
+
248
+ def group!(*args) # :nodoc:
249
+ args.flatten!
250
+
251
+ self.group_values += args
252
+ self
35
253
  end
36
254
 
255
+ # Allows to specify an order attribute:
256
+ #
257
+ # User.order('name')
258
+ # => SELECT "users".* FROM "users" ORDER BY name
259
+ #
260
+ # User.order('name DESC')
261
+ # => SELECT "users".* FROM "users" ORDER BY name DESC
262
+ #
263
+ # User.order('name DESC, email')
264
+ # => SELECT "users".* FROM "users" ORDER BY name DESC, email
265
+ #
266
+ # User.order(:name)
267
+ # => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
268
+ #
269
+ # User.order(email: :desc)
270
+ # => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
271
+ #
272
+ # User.order(:name, email: :desc)
273
+ # => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
37
274
  def order(*args)
38
- clone.tap {|r| r.order_values += args if args.present? }
275
+ check_if_method_has_arguments!("order", args)
276
+ spawn.order!(*args)
39
277
  end
40
278
 
279
+ def order!(*args) # :nodoc:
280
+ args.flatten!
281
+ validate_order_args args
282
+
283
+ references = args.reject { |arg| Arel::Node === arg }
284
+ references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
285
+ references!(references) if references.any?
286
+
287
+ # if a symbol is given we prepend the quoted table name
288
+ args = args.map { |arg|
289
+ arg.is_a?(Symbol) ? "#{quoted_table_name}.#{arg} ASC" : arg
290
+ }
291
+
292
+ self.order_values = args + self.order_values
293
+ self
294
+ end
295
+
296
+ # Replaces any existing order defined on the relation with the specified order.
297
+ #
298
+ # User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
299
+ #
300
+ # Subsequent calls to order on the same relation will be appended. For example:
301
+ #
302
+ # User.order('email DESC').reorder('id ASC').order('name ASC')
303
+ #
304
+ # generates a query with 'ORDER BY name ASC, id ASC'.
41
305
  def reorder(*args)
42
- clone.tap {|r| r.order_values = args if args.present? }
306
+ check_if_method_has_arguments!("reorder", args)
307
+ spawn.reorder!(*args)
43
308
  end
44
309
 
45
- def joins(*args)
310
+ def reorder!(*args) # :nodoc:
311
+ args.flatten!
312
+ validate_order_args args
313
+
314
+ self.reordering_value = true
315
+ self.order_values = args
316
+ self
317
+ end
318
+
319
+ VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
320
+ :limit, :offset, :joins, :includes, :from,
321
+ :readonly, :having])
322
+
323
+ # Removes an unwanted relation that is already defined on a chain of relations.
324
+ # This is useful when passing around chains of relations and would like to
325
+ # modify the relations without reconstructing the entire chain.
326
+ #
327
+ # User.order('email DESC').unscope(:order) == User.all
328
+ #
329
+ # The method arguments are symbols which correspond to the names of the methods
330
+ # which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
331
+ # The method can also be called with multiple arguments. For example:
332
+ #
333
+ # User.order('email DESC').select('id').where(name: "John")
334
+ # .unscope(:order, :select, :where) == User.all
335
+ #
336
+ # One can additionally pass a hash as an argument to unscope specific :where values.
337
+ # This is done by passing a hash with a single key-value pair. The key should be
338
+ # :where and the value should be the where value to unscope. For example:
339
+ #
340
+ # User.where(name: "John", active: true).unscope(where: :name)
341
+ # == User.where(active: true)
342
+ #
343
+ # Note that this method is more generalized than ActiveRecord::SpawnMethods#except
344
+ # because #except will only affect a particular relation's values. It won't wipe
345
+ # the order, grouping, etc. when that relation is merged. For example:
346
+ #
347
+ # Post.comments.except(:order)
348
+ #
349
+ # will still have an order if it comes from the default_scope on Comment.
350
+ def unscope(*args)
351
+ check_if_method_has_arguments!("unscope", args)
352
+ spawn.unscope!(*args)
353
+ end
354
+
355
+ def unscope!(*args) # :nodoc:
46
356
  args.flatten!
47
- clone.tap {|r| r.joins_values += args if args.present? }
357
+
358
+ args.each do |scope|
359
+ case scope
360
+ when Symbol
361
+ symbol_unscoping(scope)
362
+ when Hash
363
+ scope.each do |key, target_value|
364
+ if key != :where
365
+ raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
366
+ end
367
+
368
+ Array(target_value).each do |val|
369
+ where_unscoping(val)
370
+ end
371
+ end
372
+ else
373
+ raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
374
+ end
375
+ end
376
+
377
+ self
48
378
  end
49
379
 
50
- def where(opts, *rest)
51
- value = build_where(opts, rest)
52
- copy = clone
53
- copy.where_values += Array.wrap(value) if value
54
- copy
380
+ # Performs a joins on +args+:
381
+ #
382
+ # User.joins(:posts)
383
+ # => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
384
+ #
385
+ # You can use strings in order to customize your joins:
386
+ #
387
+ # User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
388
+ # => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
389
+ def joins(*args)
390
+ check_if_method_has_arguments!("joins", args)
391
+ spawn.joins!(*args.compact.flatten)
55
392
  end
56
393
 
57
- def having(*args)
58
- value = build_where(*args)
59
- clone.tap {|r| r.having_values += Array.wrap(value) if value.present? }
394
+ def joins!(*args) # :nodoc:
395
+ self.joins_values += args
396
+ self
60
397
  end
61
398
 
62
- def limit(value = true)
63
- copy = clone
64
- copy.limit_value = value
65
- copy
399
+ def bind(value)
400
+ spawn.bind!(value)
66
401
  end
67
402
 
68
- def offset(value = true)
69
- clone.tap {|r| r.offset_value = value }
403
+ def bind!(value) # :nodoc:
404
+ self.bind_values += [value]
405
+ self
70
406
  end
71
407
 
408
+ # Returns a new relation, which is the result of filtering the current relation
409
+ # according to the conditions in the arguments.
410
+ #
411
+ # #where accepts conditions in one of several formats. In the examples below, the resulting
412
+ # SQL is given as an illustration; the actual query generated may be different depending
413
+ # on the database adapter.
414
+ #
415
+ # === string
416
+ #
417
+ # A single string, without additional arguments, is passed to the query
418
+ # constructor as a SQL fragment, and used in the where clause of the query.
419
+ #
420
+ # Client.where("orders_count = '2'")
421
+ # # SELECT * from clients where orders_count = '2';
422
+ #
423
+ # Note that building your own string from user input may expose your application
424
+ # to injection attacks if not done properly. As an alternative, it is recommended
425
+ # to use one of the following methods.
426
+ #
427
+ # === array
428
+ #
429
+ # If an array is passed, then the first element of the array is treated as a template, and
430
+ # the remaining elements are inserted into the template to generate the condition.
431
+ # Active Record takes care of building the query to avoid injection attacks, and will
432
+ # convert from the ruby type to the database type where needed. Elements are inserted
433
+ # into the string in the order in which they appear.
434
+ #
435
+ # User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
436
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
437
+ #
438
+ # Alternatively, you can use named placeholders in the template, and pass a hash as the
439
+ # second element of the array. The names in the template are replaced with the corresponding
440
+ # values from the hash.
441
+ #
442
+ # User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
443
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
444
+ #
445
+ # This can make for more readable code in complex queries.
446
+ #
447
+ # Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
448
+ # than the previous methods; you are responsible for ensuring that the values in the template
449
+ # are properly quoted. The values are passed to the connector for quoting, but the caller
450
+ # is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
451
+ # the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
452
+ #
453
+ # User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
454
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
455
+ #
456
+ # If #where is called with multiple arguments, these are treated as if they were passed as
457
+ # the elements of a single array.
458
+ #
459
+ # User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
460
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
461
+ #
462
+ # When using strings to specify conditions, you can use any operator available from
463
+ # the database. While this provides the most flexibility, you can also unintentionally introduce
464
+ # dependencies on the underlying database. If your code is intended for general consumption,
465
+ # test with multiple database backends.
466
+ #
467
+ # === hash
468
+ #
469
+ # #where will also accept a hash condition, in which the keys are fields and the values
470
+ # are values to be searched for.
471
+ #
472
+ # Fields can be symbols or strings. Values can be single values, arrays, or ranges.
473
+ #
474
+ # User.where({ name: "Joe", email: "joe@example.com" })
475
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
476
+ #
477
+ # User.where({ name: ["Alice", "Bob"]})
478
+ # # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
479
+ #
480
+ # User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
481
+ # # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
482
+ #
483
+ # In the case of a belongs_to relationship, an association key can be used
484
+ # to specify the model if an ActiveRecord object is used as the value.
485
+ #
486
+ # author = Author.find(1)
487
+ #
488
+ # # The following queries will be equivalent:
489
+ # Post.where(author: author)
490
+ # Post.where(author_id: author)
491
+ #
492
+ # This also works with polymorphic belongs_to relationships:
493
+ #
494
+ # treasure = Treasure.create(name: 'gold coins')
495
+ # treasure.price_estimates << PriceEstimate.create(price: 125)
496
+ #
497
+ # # The following queries will be equivalent:
498
+ # PriceEstimate.where(estimate_of: treasure)
499
+ # PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
500
+ #
501
+ # === Joins
502
+ #
503
+ # If the relation is the result of a join, you may create a condition which uses any of the
504
+ # tables in the join. For string and array conditions, use the table name in the condition.
505
+ #
506
+ # User.joins(:posts).where("posts.created_at < ?", Time.now)
507
+ #
508
+ # For hash conditions, you can either use the table name in the key, or use a sub-hash.
509
+ #
510
+ # User.joins(:posts).where({ "posts.published" => true })
511
+ # User.joins(:posts).where({ posts: { published: true } })
512
+ #
513
+ # === no argument
514
+ #
515
+ # If no argument is passed, #where returns a new instance of WhereChain, that
516
+ # can be chained with #not to return a new relation that negates the where clause.
517
+ #
518
+ # User.where.not(name: "Jon")
519
+ # # SELECT * FROM users WHERE name != 'Jon'
520
+ #
521
+ # See WhereChain for more details on #not.
522
+ #
523
+ # === blank condition
524
+ #
525
+ # If the condition is any blank-ish object, then #where is a no-op and returns
526
+ # the current relation.
527
+ def where(opts = :chain, *rest)
528
+ if opts == :chain
529
+ WhereChain.new(spawn)
530
+ elsif opts.blank?
531
+ self
532
+ else
533
+ spawn.where!(opts, *rest)
534
+ end
535
+ end
536
+
537
+ def where!(opts = :chain, *rest) # :nodoc:
538
+ if opts == :chain
539
+ WhereChain.new(self)
540
+ else
541
+ references!(PredicateBuilder.references(opts)) if Hash === opts
542
+
543
+ self.where_values += build_where(opts, rest)
544
+ self
545
+ end
546
+ end
547
+
548
+ # Allows to specify a HAVING clause. Note that you can't use HAVING
549
+ # without also specifying a GROUP clause.
550
+ #
551
+ # Order.having('SUM(price) > 30').group('user_id')
552
+ def having(opts, *rest)
553
+ opts.blank? ? self : spawn.having!(opts, *rest)
554
+ end
555
+
556
+ def having!(opts, *rest) # :nodoc:
557
+ references!(PredicateBuilder.references(opts)) if Hash === opts
558
+
559
+ self.having_values += build_where(opts, rest)
560
+ self
561
+ end
562
+
563
+ # Specifies a limit for the number of records to retrieve.
564
+ #
565
+ # User.limit(10) # generated SQL has 'LIMIT 10'
566
+ #
567
+ # User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
568
+ def limit(value)
569
+ spawn.limit!(value)
570
+ end
571
+
572
+ def limit!(value) # :nodoc:
573
+ self.limit_value = value
574
+ self
575
+ end
576
+
577
+ # Specifies the number of rows to skip before returning rows.
578
+ #
579
+ # User.offset(10) # generated SQL has "OFFSET 10"
580
+ #
581
+ # Should be used with order.
582
+ #
583
+ # User.offset(10).order("name ASC")
584
+ def offset(value)
585
+ spawn.offset!(value)
586
+ end
587
+
588
+ def offset!(value) # :nodoc:
589
+ self.offset_value = value
590
+ self
591
+ end
592
+
593
+ # Specifies locking settings (default to +true+). For more information
594
+ # on locking, please see +ActiveRecord::Locking+.
72
595
  def lock(locks = true)
596
+ spawn.lock!(locks)
597
+ end
598
+
599
+ def lock!(locks = true) # :nodoc:
73
600
  case locks
74
601
  when String, TrueClass, NilClass
75
- clone.tap {|r| r.lock_value = locks || true }
602
+ self.lock_value = locks || true
76
603
  else
77
- clone.tap {|r| r.lock_value = false }
604
+ self.lock_value = false
78
605
  end
606
+
607
+ self
608
+ end
609
+
610
+ # Returns a chainable relation with zero records, specifically an
611
+ # instance of the <tt>ActiveRecord::NullRelation</tt> class.
612
+ #
613
+ # The returned <tt>ActiveRecord::NullRelation</tt> inherits from Relation and implements the
614
+ # Null Object pattern. It is an object with defined null behavior and always returns an empty
615
+ # array of records without querying the database.
616
+ #
617
+ # Any subsequent condition chained to the returned relation will continue
618
+ # generating an empty relation and will not fire any query to the database.
619
+ #
620
+ # Used in cases where a method or scope could return zero records but the
621
+ # result needs to be chainable.
622
+ #
623
+ # For example:
624
+ #
625
+ # @posts = current_user.visible_posts.where(name: params[:name])
626
+ # # => the visible_posts method is expected to return a chainable Relation
627
+ #
628
+ # def visible_posts
629
+ # case role
630
+ # when 'Country Manager'
631
+ # Post.where(country: country)
632
+ # when 'Reviewer'
633
+ # Post.published
634
+ # when 'Bad User'
635
+ # Post.none # => returning [] instead breaks the previous code
636
+ # end
637
+ # end
638
+ #
639
+ def none
640
+ extending(NullRelation)
641
+ end
642
+
643
+ def none! # :nodoc:
644
+ extending!(NullRelation)
79
645
  end
80
646
 
647
+ # Sets readonly attributes for the returned relation. If value is
648
+ # true (default), attempting to update a record will result in an error.
649
+ #
650
+ # users = User.readonly
651
+ # users.first.save
652
+ # => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
81
653
  def readonly(value = true)
82
- clone.tap {|r| r.readonly_value = value }
654
+ spawn.readonly!(value)
83
655
  end
84
656
 
85
- def create_with(value = true)
86
- clone.tap {|r| r.create_with_value = value }
657
+ def readonly!(value = true) # :nodoc:
658
+ self.readonly_value = value
659
+ self
87
660
  end
88
661
 
89
- def from(value = true)
90
- clone.tap {|r| r.from_value = value }
662
+ # Sets attributes to be used when creating new records from a
663
+ # relation object.
664
+ #
665
+ # users = User.where(name: 'Oscar')
666
+ # users.new.name # => 'Oscar'
667
+ #
668
+ # users = users.create_with(name: 'DHH')
669
+ # users.new.name # => 'DHH'
670
+ #
671
+ # You can pass +nil+ to +create_with+ to reset attributes:
672
+ #
673
+ # users = users.create_with(nil)
674
+ # users.new.name # => 'Oscar'
675
+ def create_with(value)
676
+ spawn.create_with!(value)
91
677
  end
92
678
 
679
+ def create_with!(value) # :nodoc:
680
+ self.create_with_value = value ? create_with_value.merge(value) : {}
681
+ self
682
+ end
683
+
684
+ # Specifies table from which the records will be fetched. For example:
685
+ #
686
+ # Topic.select('title').from('posts')
687
+ # #=> SELECT title FROM posts
688
+ #
689
+ # Can accept other relation objects. For example:
690
+ #
691
+ # Topic.select('title').from(Topic.approved)
692
+ # # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
693
+ #
694
+ # Topic.select('a.title').from(Topic.approved, :a)
695
+ # # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
696
+ #
697
+ def from(value, subquery_name = nil)
698
+ spawn.from!(value, subquery_name)
699
+ end
700
+
701
+ def from!(value, subquery_name = nil) # :nodoc:
702
+ self.from_value = [value, subquery_name]
703
+ self
704
+ end
705
+
706
+ # Specifies whether the records should be unique or not. For example:
707
+ #
708
+ # User.select(:name)
709
+ # # => Might return two records with the same name
710
+ #
711
+ # User.select(:name).distinct
712
+ # # => Returns 1 record per distinct name
713
+ #
714
+ # User.select(:name).distinct.distinct(false)
715
+ # # => You can also remove the uniqueness
716
+ def distinct(value = true)
717
+ spawn.distinct!(value)
718
+ end
719
+ alias uniq distinct
720
+
721
+ # Like #distinct, but modifies relation in place.
722
+ def distinct!(value = true) # :nodoc:
723
+ self.distinct_value = value
724
+ self
725
+ end
726
+ alias uniq! distinct!
727
+
728
+ # Used to extend a scope with additional methods, either through
729
+ # a module or through a block provided.
730
+ #
731
+ # The object returned is a relation, which can be further extended.
732
+ #
733
+ # === Using a module
734
+ #
735
+ # module Pagination
736
+ # def page(number)
737
+ # # pagination code goes here
738
+ # end
739
+ # end
740
+ #
741
+ # scope = Model.all.extending(Pagination)
742
+ # scope.page(params[:page])
743
+ #
744
+ # You can also pass a list of modules:
745
+ #
746
+ # scope = Model.all.extending(Pagination, SomethingElse)
747
+ #
748
+ # === Using a block
749
+ #
750
+ # scope = Model.all.extending do
751
+ # def page(number)
752
+ # # pagination code goes here
753
+ # end
754
+ # end
755
+ # scope.page(params[:page])
756
+ #
757
+ # You can also use a block and a module list:
758
+ #
759
+ # scope = Model.all.extending(Pagination) do
760
+ # def per_page(number)
761
+ # # pagination code goes here
762
+ # end
763
+ # end
93
764
  def extending(*modules, &block)
765
+ if modules.any? || block
766
+ spawn.extending!(*modules, &block)
767
+ else
768
+ self
769
+ end
770
+ end
771
+
772
+ def extending!(*modules, &block) # :nodoc:
94
773
  modules << Module.new(&block) if block_given?
95
- clone.tap {|r| r.send(:apply_modules, *modules) }
774
+
775
+ self.extending_values += modules.flatten
776
+ extend(*extending_values) if extending_values.any?
777
+
778
+ self
96
779
  end
97
780
 
781
+ # Reverse the existing order clause on the relation.
782
+ #
783
+ # User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
98
784
  def reverse_order
99
- order_clause = arel.order_clauses.join(', ')
100
- relation = except(:order)
101
-
102
- order = order_clause.blank? ?
103
- "#{@klass.table_name}.#{@klass.primary_key} DESC" :
104
- reverse_sql_order(order_clause)
785
+ spawn.reverse_order!
786
+ end
105
787
 
106
- relation.order Arel::SqlLiteral.new order
788
+ def reverse_order! # :nodoc:
789
+ self.reverse_order_value = !reverse_order_value
790
+ self
107
791
  end
108
792
 
793
+ # Returns the Arel object associated with the relation.
109
794
  def arel
110
- @arel ||= build_arel
795
+ @arel ||= with_default_scope.build_arel
111
796
  end
112
797
 
113
- def custom_join_sql(*joins)
114
- arel = table
115
- joins.each do |join|
116
- next if join.blank?
798
+ # Like #arel, but ignores the default scope of the model.
799
+ def build_arel
800
+ arel = Arel::SelectManager.new(table.engine, table)
117
801
 
118
- @implicit_readonly = true
802
+ build_joins(arel, joins_values) unless joins_values.empty?
119
803
 
120
- case join
121
- when Hash, Array, Symbol
122
- if array_of_strings?(join)
123
- join_string = join.join(' ')
124
- arel = arel.join(Arel::SqlLiteral.new(join_string))
125
- end
126
- when String
127
- arel = arel.join(Arel::SqlLiteral.new(join))
128
- else
129
- arel = arel.join(join)
130
- end
131
- end
132
- arel.joins(arel)
804
+ collapse_wheres(arel, (where_values - ['']).uniq)
805
+
806
+ arel.having(*having_values.uniq.reject{|h| h.blank?}) unless having_values.empty?
807
+
808
+ arel.take(connection.sanitize_limit(limit_value)) if limit_value
809
+ arel.skip(offset_value.to_i) if offset_value
810
+
811
+ arel.group(*group_values.uniq.reject{|g| g.blank?}) unless group_values.empty?
812
+
813
+ build_order(arel)
814
+
815
+ build_select(arel, select_values.uniq)
816
+
817
+ arel.distinct(distinct_value)
818
+ arel.from(build_from) if from_value
819
+ arel.lock(lock_value) if lock_value
820
+
821
+ arel
133
822
  end
134
823
 
135
- def build_arel
136
- arel = table
824
+ private
825
+
826
+ def symbol_unscoping(scope)
827
+ if !VALID_UNSCOPING_VALUES.include?(scope)
828
+ raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
829
+ end
830
+
831
+ single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
832
+ unscope_code = :"#{scope}_value#{'s' unless single_val_method}="
833
+
834
+ case scope
835
+ when :order
836
+ self.send(:reverse_order_value=, false)
837
+ result = []
838
+ else
839
+ result = [] unless single_val_method
840
+ end
841
+
842
+ self.send(unscope_code, result)
843
+ end
137
844
 
138
- arel = build_joins(arel, @joins_values) unless @joins_values.empty?
845
+ def where_unscoping(target_value)
846
+ target_value_sym = target_value.to_sym
139
847
 
140
- (@where_values - ['']).uniq.each do |where|
141
- case where
142
- when Arel::SqlLiteral
143
- arel = arel.where(where)
848
+ where_values.reject! do |rel|
849
+ case rel
850
+ when Arel::Nodes::In, Arel::Nodes::Equality
851
+ subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
852
+ subrelation.name.to_sym == target_value_sym
144
853
  else
145
- sql = where.is_a?(String) ? where : where.to_sql
146
- arel = arel.where(Arel::SqlLiteral.new("(#{sql})"))
854
+ raise "unscope(where: #{target_value.inspect}) failed: unscoping #{rel.class} is unimplemented."
147
855
  end
148
856
  end
857
+ end
149
858
 
150
- arel = arel.having(*@having_values.uniq.select{|h| h.present?}) unless @having_values.empty?
859
+ def custom_join_ast(table, joins)
860
+ joins = joins.reject { |join| join.blank? }
151
861
 
152
- arel = arel.take(@limit_value) if @limit_value
153
- arel = arel.skip(@offset_value) if @offset_value
862
+ return [] if joins.empty?
154
863
 
155
- arel = arel.group(*@group_values.uniq.select{|g| g.present?}) unless @group_values.empty?
864
+ @implicit_readonly = true
156
865
 
157
- arel = arel.order(*@order_values.uniq.select{|o| o.present?}) unless @order_values.empty?
866
+ joins.map do |join|
867
+ case join
868
+ when Array
869
+ join = Arel.sql(join.join(' ')) if array_of_strings?(join)
870
+ when String
871
+ join = Arel.sql(join)
872
+ end
873
+ table.create_string_join(join)
874
+ end
875
+ end
158
876
 
159
- arel = build_select(arel, @select_values.uniq)
877
+ def collapse_wheres(arel, wheres)
878
+ equalities = wheres.grep(Arel::Nodes::Equality)
160
879
 
161
- arel = arel.from(@from_value) if @from_value
162
- arel = arel.lock(@lock_value) if @lock_value
880
+ arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
163
881
 
164
- arel
882
+ (wheres - equalities).each do |where|
883
+ where = Arel.sql(where) if String === where
884
+ arel.where(Arel::Nodes::Grouping.new(where))
885
+ end
165
886
  end
166
887
 
167
888
  def build_where(opts, other = [])
168
889
  case opts
169
890
  when String, Array
170
- @klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))
891
+ [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
171
892
  when Hash
172
893
  attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
173
- PredicateBuilder.new(table.engine).build_from_hash(attributes, table)
894
+
895
+ attributes.values.grep(ActiveRecord::Relation) do |rel|
896
+ self.bind_values += rel.bind_values
897
+ end
898
+
899
+ PredicateBuilder.build_from_hash(klass, attributes, table)
174
900
  else
175
- opts
901
+ [opts]
176
902
  end
177
903
  end
178
904
 
179
- private
180
-
181
- def build_joins(relation, joins)
182
- joined_associations = []
183
- association_joins = []
184
-
185
- joins = @joins_values.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq
905
+ def build_from
906
+ opts, name = from_value
907
+ case opts
908
+ when Relation
909
+ name ||= 'subquery'
910
+ opts.arel.as(name.to_s)
911
+ else
912
+ opts
913
+ end
914
+ end
186
915
 
187
- joins.each do |join|
188
- association_joins << join if [Hash, Array, Symbol].include?(join.class) && !array_of_strings?(join)
916
+ def build_joins(manager, joins)
917
+ buckets = joins.group_by do |join|
918
+ case join
919
+ when String
920
+ :string_join
921
+ when Hash, Symbol, Array
922
+ :association_join
923
+ when ActiveRecord::Associations::JoinDependency::JoinAssociation
924
+ :stashed_join
925
+ when Arel::Nodes::Join
926
+ :join_node
927
+ else
928
+ raise 'unknown class: %s' % join.class.name
929
+ end
189
930
  end
190
931
 
191
- stashed_association_joins = joins.grep(ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation)
932
+ association_joins = buckets[:association_join] || []
933
+ stashed_association_joins = buckets[:stashed_join] || []
934
+ join_nodes = (buckets[:join_node] || []).uniq
935
+ string_joins = (buckets[:string_join] || []).map { |x| x.strip }.uniq
192
936
 
193
- non_association_joins = (joins - association_joins - stashed_association_joins)
194
- custom_joins = custom_join_sql(*non_association_joins)
937
+ join_list = join_nodes + custom_join_ast(manager, string_joins)
195
938
 
196
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins)
939
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(
940
+ @klass,
941
+ association_joins,
942
+ join_list
943
+ )
197
944
 
198
945
  join_dependency.graft(*stashed_association_joins)
199
946
 
200
947
  @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
201
948
 
202
- to_join = []
203
-
949
+ # FIXME: refactor this to build an AST
204
950
  join_dependency.join_associations.each do |association|
205
- if (association_relation = association.relation).is_a?(Array)
206
- to_join << [association_relation.first, association.join_class, association.association_join.first]
207
- to_join << [association_relation.last, association.join_class, association.association_join.last]
208
- else
209
- to_join << [association_relation, association.join_class, association.association_join]
210
- end
951
+ association.join_to(manager)
211
952
  end
212
953
 
213
- to_join.each do |tj|
214
- unless joined_associations.detect {|ja| ja[0] == tj[0] && ja[1] == tj[1] && ja[2] == tj[2] }
215
- joined_associations << tj
216
- relation = relation.join(tj[0], tj[1]).on(*tj[2])
217
- end
218
- end
954
+ manager.join_sources.concat join_list
219
955
 
220
- relation.join(custom_joins)
956
+ manager
221
957
  end
222
958
 
223
959
  def build_select(arel, selects)
224
960
  unless selects.empty?
225
961
  @implicit_readonly = false
226
- # TODO: fix this ugly hack, we should refactor the callers to get an ARel compatible array.
227
- # Before this change we were passing to ARel the last element only, and ARel is capable of handling an array
228
- if selects.all? {|s| s.is_a?(String) || !s.is_a?(Arel::Expression) } && !(selects.last =~ /^COUNT\(/)
229
- arel.project(*selects)
230
- else
231
- arel.project(selects.last)
232
- end
962
+ arel.project(*selects)
233
963
  else
234
- arel.project(Arel::SqlLiteral.new(@klass.quoted_table_name + '.*'))
964
+ arel.project(@klass.arel_table[Arel.star])
235
965
  end
236
966
  end
237
967
 
238
- def apply_modules(modules)
239
- values = Array.wrap(modules)
240
- @extensions += values if values.present?
241
- values.each {|extension| extend(extension) }
242
- end
243
-
244
968
  def reverse_sql_order(order_query)
245
- order_query.to_s.split(/,/).each { |s|
246
- if s.match(/\s(asc|ASC)$/)
247
- s.gsub!(/\s(asc|ASC)$/, ' DESC')
248
- elsif s.match(/\s(desc|DESC)$/)
249
- s.gsub!(/\s(desc|DESC)$/, ' ASC')
969
+ order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
970
+
971
+ order_query.flat_map do |o|
972
+ case o
973
+ when Arel::Nodes::Ordering
974
+ o.reverse
975
+ when String
976
+ o.to_s.split(',').collect do |s|
977
+ s.strip!
978
+ s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
979
+ end
980
+ when Symbol
981
+ { o => :desc }
982
+ when Hash
983
+ o.each_with_object({}) do |(field, dir), memo|
984
+ memo[field] = (dir == :asc ? :desc : :asc )
985
+ end
250
986
  else
251
- s.concat(' DESC')
987
+ o
252
988
  end
253
- }.join(',')
989
+ end
254
990
  end
255
991
 
256
992
  def array_of_strings?(o)
257
993
  o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
258
994
  end
259
995
 
996
+ def build_order(arel)
997
+ orders = order_values
998
+ orders = reverse_sql_order(orders) if reverse_order_value
999
+
1000
+ orders = orders.uniq.reject(&:blank?).flat_map do |order|
1001
+ case order
1002
+ when Symbol
1003
+ table[order].asc
1004
+ when Hash
1005
+ order.map { |field, dir| table[field].send(dir) }
1006
+ else
1007
+ order
1008
+ end
1009
+ end
1010
+
1011
+ arel.order(*orders) unless orders.empty?
1012
+ end
1013
+
1014
+ def validate_order_args(args)
1015
+ args.select { |a| Hash === a }.each do |h|
1016
+ unless (h.values - [:asc, :desc]).empty?
1017
+ raise ArgumentError, 'Direction should be :asc or :desc'
1018
+ end
1019
+ end
1020
+ end
1021
+
1022
+ # Checks to make sure that the arguments are not blank. Note that if some
1023
+ # blank-like object were initially passed into the query method, then this
1024
+ # method will not raise an error.
1025
+ #
1026
+ # Example:
1027
+ #
1028
+ # Post.references() # => raises an error
1029
+ # Post.references([]) # => does not raise an error
1030
+ #
1031
+ # This particular method should be called with a method_name and the args
1032
+ # passed into that method as an input. For example:
1033
+ #
1034
+ # def references(*args)
1035
+ # check_if_method_has_arguments!("references", args)
1036
+ # ...
1037
+ # end
1038
+ def check_if_method_has_arguments!(method_name, args)
1039
+ if args.blank?
1040
+ raise ArgumentError, "The method .#{method_name}() must contain arguments."
1041
+ end
1042
+ end
260
1043
  end
261
1044
  end