activerecord 1.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 (255) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +2102 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +213 -0
  5. data/examples/performance.rb +172 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record/aggregations.rb +180 -84
  8. data/lib/active_record/associations/alias_tracker.rb +76 -0
  9. data/lib/active_record/associations/association.rb +248 -0
  10. data/lib/active_record/associations/association_scope.rb +135 -0
  11. data/lib/active_record/associations/belongs_to_association.rb +92 -0
  12. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +35 -0
  13. data/lib/active_record/associations/builder/association.rb +108 -0
  14. data/lib/active_record/associations/builder/belongs_to.rb +98 -0
  15. data/lib/active_record/associations/builder/collection_association.rb +89 -0
  16. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +39 -0
  17. data/lib/active_record/associations/builder/has_many.rb +15 -0
  18. data/lib/active_record/associations/builder/has_one.rb +25 -0
  19. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  20. data/lib/active_record/associations/collection_association.rb +608 -0
  21. data/lib/active_record/associations/collection_proxy.rb +986 -0
  22. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +58 -39
  23. data/lib/active_record/associations/has_many_association.rb +116 -85
  24. data/lib/active_record/associations/has_many_through_association.rb +197 -0
  25. data/lib/active_record/associations/has_one_association.rb +102 -0
  26. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  27. data/lib/active_record/associations/join_dependency/join_association.rb +174 -0
  28. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  29. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  30. data/lib/active_record/associations/join_dependency.rb +235 -0
  31. data/lib/active_record/associations/join_helper.rb +45 -0
  32. data/lib/active_record/associations/preloader/association.rb +121 -0
  33. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  34. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  35. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  36. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  37. data/lib/active_record/associations/preloader/has_many_through.rb +19 -0
  38. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  39. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  40. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  41. data/lib/active_record/associations/preloader/through_association.rb +63 -0
  42. data/lib/active_record/associations/preloader.rb +178 -0
  43. data/lib/active_record/associations/singular_association.rb +64 -0
  44. data/lib/active_record/associations/through_association.rb +87 -0
  45. data/lib/active_record/associations.rb +1437 -431
  46. data/lib/active_record/attribute_assignment.rb +201 -0
  47. data/lib/active_record/attribute_methods/before_type_cast.rb +70 -0
  48. data/lib/active_record/attribute_methods/dirty.rb +118 -0
  49. data/lib/active_record/attribute_methods/primary_key.rb +122 -0
  50. data/lib/active_record/attribute_methods/query.rb +40 -0
  51. data/lib/active_record/attribute_methods/read.rb +107 -0
  52. data/lib/active_record/attribute_methods/serialization.rb +162 -0
  53. data/lib/active_record/attribute_methods/time_zone_conversion.rb +59 -0
  54. data/lib/active_record/attribute_methods/write.rb +63 -0
  55. data/lib/active_record/attribute_methods.rb +393 -0
  56. data/lib/active_record/autosave_association.rb +426 -0
  57. data/lib/active_record/base.rb +268 -930
  58. data/lib/active_record/callbacks.rb +203 -230
  59. data/lib/active_record/coders/yaml_column.rb +38 -0
  60. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +638 -0
  61. data/lib/active_record/connection_adapters/abstract/database_limits.rb +67 -0
  62. data/lib/active_record/connection_adapters/abstract/database_statements.rb +390 -0
  63. data/lib/active_record/connection_adapters/abstract/query_cache.rb +95 -0
  64. data/lib/active_record/connection_adapters/abstract/quoting.rb +129 -0
  65. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +501 -0
  66. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +70 -0
  67. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +873 -0
  68. data/lib/active_record/connection_adapters/abstract/transaction.rb +203 -0
  69. data/lib/active_record/connection_adapters/abstract_adapter.rb +389 -275
  70. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +782 -0
  71. data/lib/active_record/connection_adapters/column.rb +318 -0
  72. data/lib/active_record/connection_adapters/connection_specification.rb +96 -0
  73. data/lib/active_record/connection_adapters/mysql2_adapter.rb +273 -0
  74. data/lib/active_record/connection_adapters/mysql_adapter.rb +517 -90
  75. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +97 -0
  76. data/lib/active_record/connection_adapters/postgresql/cast.rb +152 -0
  77. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +242 -0
  78. data/lib/active_record/connection_adapters/postgresql/oid.rb +366 -0
  79. data/lib/active_record/connection_adapters/postgresql/quoting.rb +171 -0
  80. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  81. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +489 -0
  82. data/lib/active_record/connection_adapters/postgresql_adapter.rb +911 -138
  83. data/lib/active_record/connection_adapters/schema_cache.rb +129 -0
  84. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +624 -0
  85. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  86. data/lib/active_record/connection_handling.rb +98 -0
  87. data/lib/active_record/core.rb +463 -0
  88. data/lib/active_record/counter_cache.rb +122 -0
  89. data/lib/active_record/dynamic_matchers.rb +131 -0
  90. data/lib/active_record/errors.rb +213 -0
  91. data/lib/active_record/explain.rb +38 -0
  92. data/lib/active_record/explain_registry.rb +30 -0
  93. data/lib/active_record/explain_subscriber.rb +29 -0
  94. data/lib/active_record/fixture_set/file.rb +55 -0
  95. data/lib/active_record/fixtures.rb +892 -138
  96. data/lib/active_record/inheritance.rb +200 -0
  97. data/lib/active_record/integration.rb +60 -0
  98. data/lib/active_record/locale/en.yml +47 -0
  99. data/lib/active_record/locking/optimistic.rb +181 -0
  100. data/lib/active_record/locking/pessimistic.rb +77 -0
  101. data/lib/active_record/log_subscriber.rb +82 -0
  102. data/lib/active_record/migration/command_recorder.rb +164 -0
  103. data/lib/active_record/migration/join_table.rb +15 -0
  104. data/lib/active_record/migration.rb +1015 -0
  105. data/lib/active_record/model_schema.rb +345 -0
  106. data/lib/active_record/nested_attributes.rb +546 -0
  107. data/lib/active_record/null_relation.rb +65 -0
  108. data/lib/active_record/persistence.rb +509 -0
  109. data/lib/active_record/query_cache.rb +56 -0
  110. data/lib/active_record/querying.rb +62 -0
  111. data/lib/active_record/railtie.rb +205 -0
  112. data/lib/active_record/railties/console_sandbox.rb +5 -0
  113. data/lib/active_record/railties/controller_runtime.rb +50 -0
  114. data/lib/active_record/railties/databases.rake +402 -0
  115. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  116. data/lib/active_record/readonly_attributes.rb +30 -0
  117. data/lib/active_record/reflection.rb +544 -87
  118. data/lib/active_record/relation/batches.rb +93 -0
  119. data/lib/active_record/relation/calculations.rb +399 -0
  120. data/lib/active_record/relation/delegation.rb +125 -0
  121. data/lib/active_record/relation/finder_methods.rb +349 -0
  122. data/lib/active_record/relation/merger.rb +161 -0
  123. data/lib/active_record/relation/predicate_builder.rb +106 -0
  124. data/lib/active_record/relation/query_methods.rb +1044 -0
  125. data/lib/active_record/relation/spawn_methods.rb +73 -0
  126. data/lib/active_record/relation.rb +655 -0
  127. data/lib/active_record/result.rb +67 -0
  128. data/lib/active_record/runtime_registry.rb +17 -0
  129. data/lib/active_record/sanitization.rb +168 -0
  130. data/lib/active_record/schema.rb +65 -0
  131. data/lib/active_record/schema_dumper.rb +204 -0
  132. data/lib/active_record/schema_migration.rb +39 -0
  133. data/lib/active_record/scoping/default.rb +146 -0
  134. data/lib/active_record/scoping/named.rb +175 -0
  135. data/lib/active_record/scoping.rb +82 -0
  136. data/lib/active_record/serialization.rb +22 -0
  137. data/lib/active_record/serializers/xml_serializer.rb +197 -0
  138. data/lib/active_record/statement_cache.rb +26 -0
  139. data/lib/active_record/store.rb +156 -0
  140. data/lib/active_record/tasks/database_tasks.rb +203 -0
  141. data/lib/active_record/tasks/firebird_database_tasks.rb +56 -0
  142. data/lib/active_record/tasks/mysql_database_tasks.rb +143 -0
  143. data/lib/active_record/tasks/oracle_database_tasks.rb +45 -0
  144. data/lib/active_record/tasks/postgresql_database_tasks.rb +90 -0
  145. data/lib/active_record/tasks/sqlite_database_tasks.rb +51 -0
  146. data/lib/active_record/tasks/sqlserver_database_tasks.rb +48 -0
  147. data/lib/active_record/test_case.rb +96 -0
  148. data/lib/active_record/timestamp.rb +119 -0
  149. data/lib/active_record/transactions.rb +366 -69
  150. data/lib/active_record/translation.rb +22 -0
  151. data/lib/active_record/validations/associated.rb +49 -0
  152. data/lib/active_record/validations/presence.rb +65 -0
  153. data/lib/active_record/validations/uniqueness.rb +225 -0
  154. data/lib/active_record/validations.rb +64 -185
  155. data/lib/active_record/version.rb +11 -0
  156. data/lib/active_record.rb +149 -24
  157. data/lib/rails/generators/active_record/migration/migration_generator.rb +62 -0
  158. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +19 -0
  159. data/lib/rails/generators/active_record/migration/templates/migration.rb +39 -0
  160. data/lib/rails/generators/active_record/model/model_generator.rb +48 -0
  161. data/lib/rails/generators/active_record/model/templates/model.rb +10 -0
  162. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  163. data/lib/rails/generators/active_record.rb +23 -0
  164. metadata +261 -161
  165. data/CHANGELOG +0 -581
  166. data/README +0 -361
  167. data/RUNNING_UNIT_TESTS +0 -36
  168. data/dev-utils/eval_debugger.rb +0 -9
  169. data/examples/associations.png +0 -0
  170. data/examples/associations.rb +0 -87
  171. data/examples/shared_setup.rb +0 -15
  172. data/examples/validation.rb +0 -88
  173. data/install.rb +0 -60
  174. data/lib/active_record/associations/association_collection.rb +0 -70
  175. data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -107
  176. data/lib/active_record/deprecated_associations.rb +0 -70
  177. data/lib/active_record/observer.rb +0 -71
  178. data/lib/active_record/support/class_attribute_accessors.rb +0 -43
  179. data/lib/active_record/support/class_inheritable_attributes.rb +0 -37
  180. data/lib/active_record/support/clean_logger.rb +0 -10
  181. data/lib/active_record/support/inflector.rb +0 -70
  182. data/lib/active_record/vendor/mysql.rb +0 -1117
  183. data/lib/active_record/vendor/simple.rb +0 -702
  184. data/lib/active_record/wrappers/yaml_wrapper.rb +0 -15
  185. data/lib/active_record/wrappings.rb +0 -59
  186. data/rakefile +0 -122
  187. data/test/abstract_unit.rb +0 -16
  188. data/test/aggregations_test.rb +0 -34
  189. data/test/all.sh +0 -8
  190. data/test/associations_test.rb +0 -477
  191. data/test/base_test.rb +0 -513
  192. data/test/class_inheritable_attributes_test.rb +0 -33
  193. data/test/connections/native_mysql/connection.rb +0 -24
  194. data/test/connections/native_postgresql/connection.rb +0 -24
  195. data/test/connections/native_sqlite/connection.rb +0 -24
  196. data/test/deprecated_associations_test.rb +0 -336
  197. data/test/finder_test.rb +0 -67
  198. data/test/fixtures/accounts/signals37 +0 -3
  199. data/test/fixtures/accounts/unknown +0 -2
  200. data/test/fixtures/auto_id.rb +0 -4
  201. data/test/fixtures/column_name.rb +0 -3
  202. data/test/fixtures/companies/first_client +0 -6
  203. data/test/fixtures/companies/first_firm +0 -4
  204. data/test/fixtures/companies/second_client +0 -6
  205. data/test/fixtures/company.rb +0 -37
  206. data/test/fixtures/company_in_module.rb +0 -33
  207. data/test/fixtures/course.rb +0 -3
  208. data/test/fixtures/courses/java +0 -2
  209. data/test/fixtures/courses/ruby +0 -2
  210. data/test/fixtures/customer.rb +0 -30
  211. data/test/fixtures/customers/david +0 -6
  212. data/test/fixtures/db_definitions/mysql.sql +0 -96
  213. data/test/fixtures/db_definitions/mysql2.sql +0 -4
  214. data/test/fixtures/db_definitions/postgresql.sql +0 -113
  215. data/test/fixtures/db_definitions/postgresql2.sql +0 -4
  216. data/test/fixtures/db_definitions/sqlite.sql +0 -85
  217. data/test/fixtures/db_definitions/sqlite2.sql +0 -4
  218. data/test/fixtures/default.rb +0 -2
  219. data/test/fixtures/developer.rb +0 -8
  220. data/test/fixtures/developers/david +0 -2
  221. data/test/fixtures/developers/jamis +0 -2
  222. data/test/fixtures/developers_projects/david_action_controller +0 -2
  223. data/test/fixtures/developers_projects/david_active_record +0 -2
  224. data/test/fixtures/developers_projects/jamis_active_record +0 -2
  225. data/test/fixtures/entrant.rb +0 -3
  226. data/test/fixtures/entrants/first +0 -3
  227. data/test/fixtures/entrants/second +0 -3
  228. data/test/fixtures/entrants/third +0 -3
  229. data/test/fixtures/fixture_database.sqlite +0 -0
  230. data/test/fixtures/fixture_database_2.sqlite +0 -0
  231. data/test/fixtures/movie.rb +0 -5
  232. data/test/fixtures/movies/first +0 -2
  233. data/test/fixtures/movies/second +0 -2
  234. data/test/fixtures/project.rb +0 -3
  235. data/test/fixtures/projects/action_controller +0 -2
  236. data/test/fixtures/projects/active_record +0 -2
  237. data/test/fixtures/reply.rb +0 -21
  238. data/test/fixtures/subscriber.rb +0 -5
  239. data/test/fixtures/subscribers/first +0 -2
  240. data/test/fixtures/subscribers/second +0 -2
  241. data/test/fixtures/topic.rb +0 -20
  242. data/test/fixtures/topics/first +0 -9
  243. data/test/fixtures/topics/second +0 -8
  244. data/test/fixtures_test.rb +0 -20
  245. data/test/inflector_test.rb +0 -104
  246. data/test/inheritance_test.rb +0 -125
  247. data/test/lifecycle_test.rb +0 -110
  248. data/test/modules_test.rb +0 -21
  249. data/test/multiple_db_test.rb +0 -46
  250. data/test/pk_test.rb +0 -57
  251. data/test/reflection_test.rb +0 -78
  252. data/test/thread_safety_test.rb +0 -33
  253. data/test/transactions_test.rb +0 -83
  254. data/test/unconnected_test.rb +0 -24
  255. data/test/validations_test.rb +0 -126
@@ -0,0 +1,1044 @@
1
+ require 'active_support/core_ext/array/wrap'
2
+
3
+ module ActiveRecord
4
+ module QueryMethods
5
+ extend ActiveSupport::Concern
6
+
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
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)
113
+ def includes(*args)
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
123
+ end
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"
131
+ def eager_load(*args)
132
+ check_if_method_has_arguments!("eager_load", args)
133
+ spawn.eager_load!(*args)
134
+ end
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)
145
+ def preload(*args)
146
+ check_if_method_has_arguments!("preload", args)
147
+ spawn.preload!(*args)
148
+ end
149
+
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)
215
+ if block_given?
216
+ to_a.select { |*block_args| yield(*block_args) }
217
+ else
218
+ raise ArgumentError, 'Call this with at least one field' if fields.empty?
219
+ spawn.select!(*fields)
220
+ end
221
+ end
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, ...>]
243
+ def group(*args)
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
253
+ end
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
274
+ def order(*args)
275
+ check_if_method_has_arguments!("order", args)
276
+ spawn.order!(*args)
277
+ end
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'.
305
+ def reorder(*args)
306
+ check_if_method_has_arguments!("reorder", args)
307
+ spawn.reorder!(*args)
308
+ end
309
+
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:
356
+ args.flatten!
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
378
+ end
379
+
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)
392
+ end
393
+
394
+ def joins!(*args) # :nodoc:
395
+ self.joins_values += args
396
+ self
397
+ end
398
+
399
+ def bind(value)
400
+ spawn.bind!(value)
401
+ end
402
+
403
+ def bind!(value) # :nodoc:
404
+ self.bind_values += [value]
405
+ self
406
+ end
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+.
595
+ def lock(locks = true)
596
+ spawn.lock!(locks)
597
+ end
598
+
599
+ def lock!(locks = true) # :nodoc:
600
+ case locks
601
+ when String, TrueClass, NilClass
602
+ self.lock_value = locks || true
603
+ else
604
+ self.lock_value = false
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)
645
+ end
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
653
+ def readonly(value = true)
654
+ spawn.readonly!(value)
655
+ end
656
+
657
+ def readonly!(value = true) # :nodoc:
658
+ self.readonly_value = value
659
+ self
660
+ end
661
+
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)
677
+ end
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
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:
773
+ modules << Module.new(&block) if block_given?
774
+
775
+ self.extending_values += modules.flatten
776
+ extend(*extending_values) if extending_values.any?
777
+
778
+ self
779
+ end
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'
784
+ def reverse_order
785
+ spawn.reverse_order!
786
+ end
787
+
788
+ def reverse_order! # :nodoc:
789
+ self.reverse_order_value = !reverse_order_value
790
+ self
791
+ end
792
+
793
+ # Returns the Arel object associated with the relation.
794
+ def arel
795
+ @arel ||= with_default_scope.build_arel
796
+ end
797
+
798
+ # Like #arel, but ignores the default scope of the model.
799
+ def build_arel
800
+ arel = Arel::SelectManager.new(table.engine, table)
801
+
802
+ build_joins(arel, joins_values) unless joins_values.empty?
803
+
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
822
+ end
823
+
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
844
+
845
+ def where_unscoping(target_value)
846
+ target_value_sym = target_value.to_sym
847
+
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
853
+ else
854
+ raise "unscope(where: #{target_value.inspect}) failed: unscoping #{rel.class} is unimplemented."
855
+ end
856
+ end
857
+ end
858
+
859
+ def custom_join_ast(table, joins)
860
+ joins = joins.reject { |join| join.blank? }
861
+
862
+ return [] if joins.empty?
863
+
864
+ @implicit_readonly = true
865
+
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
876
+
877
+ def collapse_wheres(arel, wheres)
878
+ equalities = wheres.grep(Arel::Nodes::Equality)
879
+
880
+ arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
881
+
882
+ (wheres - equalities).each do |where|
883
+ where = Arel.sql(where) if String === where
884
+ arel.where(Arel::Nodes::Grouping.new(where))
885
+ end
886
+ end
887
+
888
+ def build_where(opts, other = [])
889
+ case opts
890
+ when String, Array
891
+ [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
892
+ when Hash
893
+ attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
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)
900
+ else
901
+ [opts]
902
+ end
903
+ end
904
+
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
915
+
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
930
+ end
931
+
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
936
+
937
+ join_list = join_nodes + custom_join_ast(manager, string_joins)
938
+
939
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(
940
+ @klass,
941
+ association_joins,
942
+ join_list
943
+ )
944
+
945
+ join_dependency.graft(*stashed_association_joins)
946
+
947
+ @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
948
+
949
+ # FIXME: refactor this to build an AST
950
+ join_dependency.join_associations.each do |association|
951
+ association.join_to(manager)
952
+ end
953
+
954
+ manager.join_sources.concat join_list
955
+
956
+ manager
957
+ end
958
+
959
+ def build_select(arel, selects)
960
+ unless selects.empty?
961
+ @implicit_readonly = false
962
+ arel.project(*selects)
963
+ else
964
+ arel.project(@klass.arel_table[Arel.star])
965
+ end
966
+ end
967
+
968
+ def reverse_sql_order(order_query)
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
986
+ else
987
+ o
988
+ end
989
+ end
990
+ end
991
+
992
+ def array_of_strings?(o)
993
+ o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
994
+ end
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
1043
+ end
1044
+ end