activerecord 3.2.22.5 → 5.2.8

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 (275) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +657 -621
  3. data/MIT-LICENSE +2 -2
  4. data/README.rdoc +41 -46
  5. data/examples/performance.rb +55 -42
  6. data/examples/simple.rb +6 -5
  7. data/lib/active_record/aggregations.rb +264 -236
  8. data/lib/active_record/association_relation.rb +40 -0
  9. data/lib/active_record/associations/alias_tracker.rb +47 -42
  10. data/lib/active_record/associations/association.rb +127 -75
  11. data/lib/active_record/associations/association_scope.rb +126 -92
  12. data/lib/active_record/associations/belongs_to_association.rb +78 -27
  13. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +9 -4
  14. data/lib/active_record/associations/builder/association.rb +117 -32
  15. data/lib/active_record/associations/builder/belongs_to.rb +135 -60
  16. data/lib/active_record/associations/builder/collection_association.rb +61 -54
  17. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +120 -42
  18. data/lib/active_record/associations/builder/has_many.rb +10 -64
  19. data/lib/active_record/associations/builder/has_one.rb +19 -51
  20. data/lib/active_record/associations/builder/singular_association.rb +28 -18
  21. data/lib/active_record/associations/collection_association.rb +226 -293
  22. data/lib/active_record/associations/collection_proxy.rb +1067 -69
  23. data/lib/active_record/associations/foreign_association.rb +13 -0
  24. data/lib/active_record/associations/has_many_association.rb +83 -47
  25. data/lib/active_record/associations/has_many_through_association.rb +98 -65
  26. data/lib/active_record/associations/has_one_association.rb +57 -20
  27. data/lib/active_record/associations/has_one_through_association.rb +18 -9
  28. data/lib/active_record/associations/join_dependency/join_association.rb +48 -126
  29. data/lib/active_record/associations/join_dependency/join_base.rb +11 -12
  30. data/lib/active_record/associations/join_dependency/join_part.rb +35 -42
  31. data/lib/active_record/associations/join_dependency.rb +212 -164
  32. data/lib/active_record/associations/preloader/association.rb +95 -89
  33. data/lib/active_record/associations/preloader/through_association.rb +84 -44
  34. data/lib/active_record/associations/preloader.rb +123 -111
  35. data/lib/active_record/associations/singular_association.rb +33 -24
  36. data/lib/active_record/associations/through_association.rb +60 -26
  37. data/lib/active_record/associations.rb +1759 -1506
  38. data/lib/active_record/attribute_assignment.rb +60 -193
  39. data/lib/active_record/attribute_decorators.rb +90 -0
  40. data/lib/active_record/attribute_methods/before_type_cast.rb +55 -8
  41. data/lib/active_record/attribute_methods/dirty.rb +113 -74
  42. data/lib/active_record/attribute_methods/primary_key.rb +106 -77
  43. data/lib/active_record/attribute_methods/query.rb +8 -5
  44. data/lib/active_record/attribute_methods/read.rb +63 -114
  45. data/lib/active_record/attribute_methods/serialization.rb +60 -90
  46. data/lib/active_record/attribute_methods/time_zone_conversion.rb +69 -43
  47. data/lib/active_record/attribute_methods/write.rb +43 -45
  48. data/lib/active_record/attribute_methods.rb +366 -149
  49. data/lib/active_record/attributes.rb +266 -0
  50. data/lib/active_record/autosave_association.rb +312 -225
  51. data/lib/active_record/base.rb +114 -505
  52. data/lib/active_record/callbacks.rb +145 -67
  53. data/lib/active_record/coders/json.rb +15 -0
  54. data/lib/active_record/coders/yaml_column.rb +32 -23
  55. data/lib/active_record/collection_cache_key.rb +53 -0
  56. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +883 -284
  57. data/lib/active_record/connection_adapters/abstract/database_limits.rb +16 -2
  58. data/lib/active_record/connection_adapters/abstract/database_statements.rb +350 -200
  59. data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -27
  60. data/lib/active_record/connection_adapters/abstract/quoting.rb +150 -65
  61. data/lib/active_record/connection_adapters/abstract/savepoints.rb +23 -0
  62. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +146 -0
  63. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +477 -284
  64. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +95 -0
  65. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +1100 -310
  66. data/lib/active_record/connection_adapters/abstract/transaction.rb +283 -0
  67. data/lib/active_record/connection_adapters/abstract_adapter.rb +450 -118
  68. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +657 -446
  69. data/lib/active_record/connection_adapters/column.rb +50 -255
  70. data/lib/active_record/connection_adapters/connection_specification.rb +287 -0
  71. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +33 -0
  72. data/lib/active_record/connection_adapters/mysql/column.rb +27 -0
  73. data/lib/active_record/connection_adapters/mysql/database_statements.rb +140 -0
  74. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +72 -0
  75. data/lib/active_record/connection_adapters/mysql/quoting.rb +44 -0
  76. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +73 -0
  77. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +87 -0
  78. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +80 -0
  79. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +148 -0
  80. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +35 -0
  81. data/lib/active_record/connection_adapters/mysql2_adapter.rb +59 -210
  82. data/lib/active_record/connection_adapters/postgresql/column.rb +44 -0
  83. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +163 -0
  84. data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +44 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +92 -0
  86. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +56 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +15 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +17 -0
  89. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +50 -0
  90. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +23 -0
  91. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +23 -0
  92. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +15 -0
  93. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +21 -0
  94. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +71 -0
  95. data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +15 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +15 -0
  97. data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +45 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +41 -0
  99. data/lib/active_record/connection_adapters/postgresql/oid/oid.rb +15 -0
  100. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +65 -0
  101. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +97 -0
  102. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +18 -0
  103. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +111 -0
  104. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +23 -0
  105. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +28 -0
  106. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +30 -0
  107. data/lib/active_record/connection_adapters/postgresql/oid.rb +34 -0
  108. data/lib/active_record/connection_adapters/postgresql/quoting.rb +168 -0
  109. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +43 -0
  110. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +65 -0
  111. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +206 -0
  112. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +50 -0
  113. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +774 -0
  114. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +39 -0
  115. data/lib/active_record/connection_adapters/postgresql/utils.rb +81 -0
  116. data/lib/active_record/connection_adapters/postgresql_adapter.rb +620 -1080
  117. data/lib/active_record/connection_adapters/schema_cache.rb +85 -36
  118. data/lib/active_record/connection_adapters/sql_type_metadata.rb +34 -0
  119. data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +21 -0
  120. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +67 -0
  121. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +17 -0
  122. data/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +19 -0
  123. data/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb +18 -0
  124. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +106 -0
  125. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +545 -27
  126. data/lib/active_record/connection_adapters/statement_pool.rb +34 -13
  127. data/lib/active_record/connection_handling.rb +145 -0
  128. data/lib/active_record/core.rb +559 -0
  129. data/lib/active_record/counter_cache.rb +200 -105
  130. data/lib/active_record/define_callbacks.rb +22 -0
  131. data/lib/active_record/dynamic_matchers.rb +107 -69
  132. data/lib/active_record/enum.rb +244 -0
  133. data/lib/active_record/errors.rb +245 -60
  134. data/lib/active_record/explain.rb +35 -71
  135. data/lib/active_record/explain_registry.rb +32 -0
  136. data/lib/active_record/explain_subscriber.rb +18 -9
  137. data/lib/active_record/fixture_set/file.rb +82 -0
  138. data/lib/active_record/fixtures.rb +418 -275
  139. data/lib/active_record/gem_version.rb +17 -0
  140. data/lib/active_record/inheritance.rb +209 -100
  141. data/lib/active_record/integration.rb +116 -21
  142. data/lib/active_record/internal_metadata.rb +45 -0
  143. data/lib/active_record/legacy_yaml_adapter.rb +48 -0
  144. data/lib/active_record/locale/en.yml +9 -1
  145. data/lib/active_record/locking/optimistic.rb +107 -94
  146. data/lib/active_record/locking/pessimistic.rb +20 -8
  147. data/lib/active_record/log_subscriber.rb +99 -34
  148. data/lib/active_record/migration/command_recorder.rb +199 -64
  149. data/lib/active_record/migration/compatibility.rb +217 -0
  150. data/lib/active_record/migration/join_table.rb +17 -0
  151. data/lib/active_record/migration.rb +893 -296
  152. data/lib/active_record/model_schema.rb +328 -175
  153. data/lib/active_record/nested_attributes.rb +338 -242
  154. data/lib/active_record/no_touching.rb +58 -0
  155. data/lib/active_record/null_relation.rb +68 -0
  156. data/lib/active_record/persistence.rb +557 -170
  157. data/lib/active_record/query_cache.rb +14 -43
  158. data/lib/active_record/querying.rb +36 -24
  159. data/lib/active_record/railtie.rb +147 -52
  160. data/lib/active_record/railties/console_sandbox.rb +5 -4
  161. data/lib/active_record/railties/controller_runtime.rb +13 -6
  162. data/lib/active_record/railties/databases.rake +206 -488
  163. data/lib/active_record/readonly_attributes.rb +4 -6
  164. data/lib/active_record/reflection.rb +734 -228
  165. data/lib/active_record/relation/batches/batch_enumerator.rb +69 -0
  166. data/lib/active_record/relation/batches.rb +249 -52
  167. data/lib/active_record/relation/calculations.rb +330 -284
  168. data/lib/active_record/relation/delegation.rb +135 -37
  169. data/lib/active_record/relation/finder_methods.rb +450 -287
  170. data/lib/active_record/relation/from_clause.rb +26 -0
  171. data/lib/active_record/relation/merger.rb +193 -0
  172. data/lib/active_record/relation/predicate_builder/array_handler.rb +48 -0
  173. data/lib/active_record/relation/predicate_builder/association_query_value.rb +46 -0
  174. data/lib/active_record/relation/predicate_builder/base_handler.rb +19 -0
  175. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +20 -0
  176. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +56 -0
  177. data/lib/active_record/relation/predicate_builder/range_handler.rb +42 -0
  178. data/lib/active_record/relation/predicate_builder/relation_handler.rb +19 -0
  179. data/lib/active_record/relation/predicate_builder.rb +132 -43
  180. data/lib/active_record/relation/query_attribute.rb +45 -0
  181. data/lib/active_record/relation/query_methods.rb +1037 -221
  182. data/lib/active_record/relation/record_fetch_warning.rb +51 -0
  183. data/lib/active_record/relation/spawn_methods.rb +48 -151
  184. data/lib/active_record/relation/where_clause.rb +186 -0
  185. data/lib/active_record/relation/where_clause_factory.rb +34 -0
  186. data/lib/active_record/relation.rb +451 -359
  187. data/lib/active_record/result.rb +129 -20
  188. data/lib/active_record/runtime_registry.rb +24 -0
  189. data/lib/active_record/sanitization.rb +164 -136
  190. data/lib/active_record/schema.rb +31 -19
  191. data/lib/active_record/schema_dumper.rb +154 -107
  192. data/lib/active_record/schema_migration.rb +56 -0
  193. data/lib/active_record/scoping/default.rb +108 -98
  194. data/lib/active_record/scoping/named.rb +125 -112
  195. data/lib/active_record/scoping.rb +77 -123
  196. data/lib/active_record/secure_token.rb +40 -0
  197. data/lib/active_record/serialization.rb +10 -6
  198. data/lib/active_record/statement_cache.rb +121 -0
  199. data/lib/active_record/store.rb +175 -16
  200. data/lib/active_record/suppressor.rb +61 -0
  201. data/lib/active_record/table_metadata.rb +82 -0
  202. data/lib/active_record/tasks/database_tasks.rb +337 -0
  203. data/lib/active_record/tasks/mysql_database_tasks.rb +115 -0
  204. data/lib/active_record/tasks/postgresql_database_tasks.rb +143 -0
  205. data/lib/active_record/tasks/sqlite_database_tasks.rb +83 -0
  206. data/lib/active_record/timestamp.rb +80 -41
  207. data/lib/active_record/touch_later.rb +64 -0
  208. data/lib/active_record/transactions.rb +240 -119
  209. data/lib/active_record/translation.rb +2 -0
  210. data/lib/active_record/type/adapter_specific_registry.rb +136 -0
  211. data/lib/active_record/type/date.rb +9 -0
  212. data/lib/active_record/type/date_time.rb +9 -0
  213. data/lib/active_record/type/decimal_without_scale.rb +15 -0
  214. data/lib/active_record/type/hash_lookup_type_map.rb +25 -0
  215. data/lib/active_record/type/internal/timezone.rb +17 -0
  216. data/lib/active_record/type/json.rb +30 -0
  217. data/lib/active_record/type/serialized.rb +71 -0
  218. data/lib/active_record/type/text.rb +11 -0
  219. data/lib/active_record/type/time.rb +21 -0
  220. data/lib/active_record/type/type_map.rb +62 -0
  221. data/lib/active_record/type/unsigned_integer.rb +17 -0
  222. data/lib/active_record/type.rb +79 -0
  223. data/lib/active_record/type_caster/connection.rb +33 -0
  224. data/lib/active_record/type_caster/map.rb +23 -0
  225. data/lib/active_record/type_caster.rb +9 -0
  226. data/lib/active_record/validations/absence.rb +25 -0
  227. data/lib/active_record/validations/associated.rb +35 -18
  228. data/lib/active_record/validations/length.rb +26 -0
  229. data/lib/active_record/validations/presence.rb +68 -0
  230. data/lib/active_record/validations/uniqueness.rb +133 -75
  231. data/lib/active_record/validations.rb +53 -43
  232. data/lib/active_record/version.rb +7 -7
  233. data/lib/active_record.rb +89 -57
  234. data/lib/rails/generators/active_record/application_record/application_record_generator.rb +27 -0
  235. data/lib/rails/generators/active_record/application_record/templates/application_record.rb.tt +5 -0
  236. data/lib/rails/generators/active_record/migration/migration_generator.rb +61 -8
  237. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +24 -0
  238. data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +46 -0
  239. data/lib/rails/generators/active_record/migration.rb +28 -8
  240. data/lib/rails/generators/active_record/model/model_generator.rb +23 -22
  241. data/lib/rails/generators/active_record/model/templates/model.rb.tt +13 -0
  242. data/lib/rails/generators/active_record/model/templates/{module.rb → module.rb.tt} +1 -1
  243. data/lib/rails/generators/active_record.rb +10 -16
  244. metadata +141 -62
  245. data/examples/associations.png +0 -0
  246. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +0 -63
  247. data/lib/active_record/associations/join_helper.rb +0 -55
  248. data/lib/active_record/associations/preloader/belongs_to.rb +0 -17
  249. data/lib/active_record/associations/preloader/collection_association.rb +0 -24
  250. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +0 -60
  251. data/lib/active_record/associations/preloader/has_many.rb +0 -17
  252. data/lib/active_record/associations/preloader/has_many_through.rb +0 -15
  253. data/lib/active_record/associations/preloader/has_one.rb +0 -23
  254. data/lib/active_record/associations/preloader/has_one_through.rb +0 -9
  255. data/lib/active_record/associations/preloader/singular_association.rb +0 -21
  256. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +0 -32
  257. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +0 -191
  258. data/lib/active_record/connection_adapters/mysql_adapter.rb +0 -441
  259. data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -583
  260. data/lib/active_record/dynamic_finder_match.rb +0 -68
  261. data/lib/active_record/dynamic_scope_match.rb +0 -23
  262. data/lib/active_record/fixtures/file.rb +0 -65
  263. data/lib/active_record/identity_map.rb +0 -162
  264. data/lib/active_record/observer.rb +0 -121
  265. data/lib/active_record/railties/jdbcmysql_error.rb +0 -16
  266. data/lib/active_record/serializers/xml_serializer.rb +0 -203
  267. data/lib/active_record/session_store.rb +0 -360
  268. data/lib/active_record/test_case.rb +0 -73
  269. data/lib/rails/generators/active_record/migration/templates/migration.rb +0 -34
  270. data/lib/rails/generators/active_record/model/templates/migration.rb +0 -15
  271. data/lib/rails/generators/active_record/model/templates/model.rb +0 -12
  272. data/lib/rails/generators/active_record/observer/observer_generator.rb +0 -15
  273. data/lib/rails/generators/active_record/observer/templates/observer.rb +0 -4
  274. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +0 -25
  275. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +0 -12
@@ -1,57 +1,197 @@
1
- require 'active_support/core_ext/array/wrap'
2
- require 'active_support/core_ext/object/blank'
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record/relation/from_clause"
4
+ require "active_record/relation/query_attribute"
5
+ require "active_record/relation/where_clause"
6
+ require "active_record/relation/where_clause_factory"
7
+ require "active_model/forbidden_attributes_protection"
3
8
 
4
9
  module ActiveRecord
5
10
  module QueryMethods
6
11
  extend ActiveSupport::Concern
7
12
 
8
- attr_accessor :includes_values, :eager_load_values, :preload_values,
9
- :select_values, :group_values, :order_values, :joins_values,
10
- :where_values, :having_values, :bind_values,
11
- :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value,
12
- :from_value, :reordering_value, :reverse_order_value,
13
- :uniq_value
13
+ include ActiveModel::ForbiddenAttributesProtection
14
+
15
+ # WhereChain objects act as placeholder for queries in which #where does not have any parameter.
16
+ # In this case, #where must be chained with #not to return a new relation.
17
+ class WhereChain
18
+ include ActiveModel::ForbiddenAttributesProtection
19
+
20
+ def initialize(scope)
21
+ @scope = scope
22
+ end
23
+
24
+ # Returns a new relation expressing WHERE + NOT condition according to
25
+ # the conditions in the arguments.
26
+ #
27
+ # #not accepts conditions as a string, array, or hash. See QueryMethods#where for
28
+ # more details on each format.
29
+ #
30
+ # User.where.not("name = 'Jon'")
31
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
32
+ #
33
+ # User.where.not(["name = ?", "Jon"])
34
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
35
+ #
36
+ # User.where.not(name: "Jon")
37
+ # # SELECT * FROM users WHERE name != 'Jon'
38
+ #
39
+ # User.where.not(name: nil)
40
+ # # SELECT * FROM users WHERE name IS NOT NULL
41
+ #
42
+ # User.where.not(name: %w(Ko1 Nobu))
43
+ # # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
44
+ #
45
+ # User.where.not(name: "Jon", role: "admin")
46
+ # # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
47
+ def not(opts, *rest)
48
+ opts = sanitize_forbidden_attributes(opts)
49
+
50
+ where_clause = @scope.send(:where_clause_factory).build(opts, rest)
51
+
52
+ @scope.references!(PredicateBuilder.references(opts)) if Hash === opts
53
+ @scope.where_clause += where_clause.invert
54
+ @scope
55
+ end
56
+ end
57
+
58
+ FROZEN_EMPTY_ARRAY = [].freeze
59
+ FROZEN_EMPTY_HASH = {}.freeze
60
+
61
+ Relation::VALUE_METHODS.each do |name|
62
+ method_name = \
63
+ case name
64
+ when *Relation::MULTI_VALUE_METHODS then "#{name}_values"
65
+ when *Relation::SINGLE_VALUE_METHODS then "#{name}_value"
66
+ when *Relation::CLAUSE_METHODS then "#{name}_clause"
67
+ end
68
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
69
+ def #{method_name} # def includes_values
70
+ get_value(#{name.inspect}) # get_value(:includes)
71
+ end # end
72
+
73
+ def #{method_name}=(value) # def includes_values=(value)
74
+ set_value(#{name.inspect}, value) # set_value(:includes, value)
75
+ end # end
76
+ CODE
77
+ end
78
+
79
+ alias extensions extending_values
14
80
 
81
+ # Specify relationships to be included in the result set. For
82
+ # example:
83
+ #
84
+ # users = User.includes(:address)
85
+ # users.each do |user|
86
+ # user.address.city
87
+ # end
88
+ #
89
+ # allows you to access the +address+ attribute of the +User+ model without
90
+ # firing an additional query. This will often result in a
91
+ # performance improvement over a simple join.
92
+ #
93
+ # You can also specify multiple relationships, like this:
94
+ #
95
+ # users = User.includes(:address, :friends)
96
+ #
97
+ # Loading nested relationships is possible using a Hash:
98
+ #
99
+ # users = User.includes(:address, friends: [:address, :followers])
100
+ #
101
+ # === conditions
102
+ #
103
+ # If you want to add conditions to your included models you'll have
104
+ # to explicitly reference them. For example:
105
+ #
106
+ # User.includes(:posts).where('posts.name = ?', 'example')
107
+ #
108
+ # Will throw an error, but this will work:
109
+ #
110
+ # User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
111
+ #
112
+ # Note that #includes works with association names while #references needs
113
+ # the actual table name.
15
114
  def includes(*args)
16
- args.reject! {|a| a.blank? }
115
+ check_if_method_has_arguments!(:includes, args)
116
+ spawn.includes!(*args)
117
+ end
17
118
 
18
- return self if args.empty?
119
+ def includes!(*args) # :nodoc:
120
+ args.reject!(&:blank?)
121
+ args.flatten!
19
122
 
20
- relation = clone
21
- relation.includes_values = (relation.includes_values + args).flatten.uniq
22
- relation
123
+ self.includes_values |= args
124
+ self
23
125
  end
24
126
 
127
+ # Forces eager loading by performing a LEFT OUTER JOIN on +args+:
128
+ #
129
+ # User.eager_load(:posts)
130
+ # # SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
131
+ # # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
132
+ # # "users"."id"
25
133
  def eager_load(*args)
26
- return self if args.blank?
134
+ check_if_method_has_arguments!(:eager_load, args)
135
+ spawn.eager_load!(*args)
136
+ end
27
137
 
28
- relation = clone
29
- relation.eager_load_values += args
30
- relation
138
+ def eager_load!(*args) # :nodoc:
139
+ self.eager_load_values += args
140
+ self
31
141
  end
32
142
 
143
+ # Allows preloading of +args+, in the same way that #includes does:
144
+ #
145
+ # User.preload(:posts)
146
+ # # SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
33
147
  def preload(*args)
34
- return self if args.blank?
148
+ check_if_method_has_arguments!(:preload, args)
149
+ spawn.preload!(*args)
150
+ end
151
+
152
+ def preload!(*args) # :nodoc:
153
+ self.preload_values += args
154
+ self
155
+ end
156
+
157
+ # Use to indicate that the given +table_names+ are referenced by an SQL string,
158
+ # and should therefore be JOINed in any query rather than loaded separately.
159
+ # This method only works in conjunction with #includes.
160
+ # See #includes for more details.
161
+ #
162
+ # User.includes(:posts).where("posts.name = 'foo'")
163
+ # # Doesn't JOIN the posts table, resulting in an error.
164
+ #
165
+ # User.includes(:posts).where("posts.name = 'foo'").references(:posts)
166
+ # # Query now knows the string references posts, so adds a JOIN
167
+ def references(*table_names)
168
+ check_if_method_has_arguments!(:references, table_names)
169
+ spawn.references!(*table_names)
170
+ end
171
+
172
+ def references!(*table_names) # :nodoc:
173
+ table_names.flatten!
174
+ table_names.map!(&:to_s)
35
175
 
36
- relation = clone
37
- relation.preload_values += args
38
- relation
176
+ self.references_values |= table_names
177
+ self
39
178
  end
40
179
 
41
180
  # Works in two unique ways.
42
181
  #
43
- # First: takes a block so it can be used just like Array#select.
182
+ # First: takes a block so it can be used just like <tt>Array#select</tt>.
44
183
  #
45
- # Model.scoped.select { |m| m.field == value }
184
+ # Model.all.select { |m| m.field == value }
46
185
  #
47
186
  # This will build an array of objects from the database for the scope,
48
- # converting them into an array and iterating through them using Array#select.
187
+ # converting them into an array and iterating through them using
188
+ # <tt>Array#select</tt>.
49
189
  #
50
190
  # Second: Modifies the SELECT statement for the query so that only certain
51
191
  # fields are retrieved:
52
192
  #
53
- # >> Model.select(:field)
54
- # => [#<Model field:value>]
193
+ # Model.select(:field)
194
+ # # => [#<Model id: nil, field: "value">]
55
195
  #
56
196
  # Although in the above example it looks as though this method returns an
57
197
  # array, it actually returns a relation object and can have other query
@@ -59,38 +199,105 @@ module ActiveRecord
59
199
  #
60
200
  # The argument to the method can also be an array of fields.
61
201
  #
62
- # >> Model.select([:field, :other_field, :and_one_more])
63
- # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
202
+ # Model.select(:field, :other_field, :and_one_more)
203
+ # # => [#<Model id: nil, field: "value", other_field: "value", and_one_more: "value">]
204
+ #
205
+ # You can also use one or more strings, which will be used unchanged as SELECT fields.
206
+ #
207
+ # Model.select('field AS field_one', 'other_field AS field_two')
208
+ # # => [#<Model id: nil, field: "value", other_field: "value">]
64
209
  #
65
- # Any attributes that do not have fields retrieved by a select
66
- # will raise a ActiveModel::MissingAttributeError when the getter method for that attribute is used:
210
+ # If an alias was specified, it will be accessible from the resulting objects:
67
211
  #
68
- # >> Model.select(:field).first.other_field
69
- # => ActiveModel::MissingAttributeError: missing attribute: other_field
70
- def select(value = Proc.new)
212
+ # Model.select('field AS field_one').first.field_one
213
+ # # => "value"
214
+ #
215
+ # Accessing attributes of an object that do not have fields retrieved by a select
216
+ # except +id+ will throw ActiveModel::MissingAttributeError:
217
+ #
218
+ # Model.select(:field).first.other_field
219
+ # # => ActiveModel::MissingAttributeError: missing attribute: other_field
220
+ def select(*fields)
71
221
  if block_given?
72
- to_a.select {|*block_args| value.call(*block_args) }
73
- else
74
- relation = clone
75
- relation.select_values += Array.wrap(value)
76
- relation
222
+ if fields.any?
223
+ raise ArgumentError, "`select' with block doesn't take arguments."
224
+ end
225
+
226
+ return super()
77
227
  end
228
+
229
+ raise ArgumentError, "Call `select' with at least one field" if fields.empty?
230
+ spawn._select!(*fields)
78
231
  end
79
232
 
233
+ def _select!(*fields) # :nodoc:
234
+ fields.flatten!
235
+ self.select_values += fields
236
+ self
237
+ end
238
+
239
+ # Allows to specify a group attribute:
240
+ #
241
+ # User.group(:name)
242
+ # # SELECT "users".* FROM "users" GROUP BY name
243
+ #
244
+ # Returns an array with distinct records based on the +group+ attribute:
245
+ #
246
+ # User.select([:id, :name])
247
+ # # => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">]
248
+ #
249
+ # User.group(:name)
250
+ # # => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
251
+ #
252
+ # User.group('name AS grouped_name, age')
253
+ # # => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
254
+ #
255
+ # Passing in an array of attributes to group by is also supported.
256
+ #
257
+ # User.select([:id, :first_name]).group(:id, :first_name).first(3)
258
+ # # => [#<User id: 1, first_name: "Bill">, #<User id: 2, first_name: "Earl">, #<User id: 3, first_name: "Beto">]
80
259
  def group(*args)
81
- return self if args.blank?
260
+ check_if_method_has_arguments!(:group, args)
261
+ spawn.group!(*args)
262
+ end
263
+
264
+ def group!(*args) # :nodoc:
265
+ args.flatten!
82
266
 
83
- relation = clone
84
- relation.group_values += args.flatten
85
- relation
267
+ self.group_values += args
268
+ self
86
269
  end
87
270
 
271
+ # Allows to specify an order attribute:
272
+ #
273
+ # User.order(:name)
274
+ # # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
275
+ #
276
+ # User.order(email: :desc)
277
+ # # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
278
+ #
279
+ # User.order(:name, email: :desc)
280
+ # # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
281
+ #
282
+ # User.order('name')
283
+ # # SELECT "users".* FROM "users" ORDER BY name
284
+ #
285
+ # User.order('name DESC')
286
+ # # SELECT "users".* FROM "users" ORDER BY name DESC
287
+ #
288
+ # User.order('name DESC, email')
289
+ # # SELECT "users".* FROM "users" ORDER BY name DESC, email
88
290
  def order(*args)
89
- return self if args.blank?
291
+ check_if_method_has_arguments!(:order, args)
292
+ spawn.order!(*args)
293
+ end
294
+
295
+ # Same as #order but operates on relation in-place instead of copying.
296
+ def order!(*args) # :nodoc:
297
+ preprocess_order_args(args)
90
298
 
91
- relation = clone
92
- relation.order_values += args.flatten
93
- relation
299
+ self.order_values += args
300
+ self
94
301
  end
95
302
 
96
303
  # Replaces any existing order defined on the relation with the specified order.
@@ -102,106 +309,517 @@ module ActiveRecord
102
309
  # User.order('email DESC').reorder('id ASC').order('name ASC')
103
310
  #
104
311
  # generates a query with 'ORDER BY id ASC, name ASC'.
105
- #
106
312
  def reorder(*args)
107
- return self if args.blank?
313
+ check_if_method_has_arguments!(:reorder, args)
314
+ spawn.reorder!(*args)
315
+ end
316
+
317
+ # Same as #reorder but operates on relation in-place instead of copying.
318
+ def reorder!(*args) # :nodoc:
319
+ preprocess_order_args(args)
320
+
321
+ self.reordering_value = true
322
+ self.order_values = args
323
+ self
324
+ end
325
+
326
+ VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
327
+ :limit, :offset, :joins, :left_outer_joins,
328
+ :includes, :from, :readonly, :having])
108
329
 
109
- relation = clone
110
- relation.reordering_value = true
111
- relation.order_values = args.flatten
112
- relation
330
+ # Removes an unwanted relation that is already defined on a chain of relations.
331
+ # This is useful when passing around chains of relations and would like to
332
+ # modify the relations without reconstructing the entire chain.
333
+ #
334
+ # User.order('email DESC').unscope(:order) == User.all
335
+ #
336
+ # The method arguments are symbols which correspond to the names of the methods
337
+ # which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
338
+ # The method can also be called with multiple arguments. For example:
339
+ #
340
+ # User.order('email DESC').select('id').where(name: "John")
341
+ # .unscope(:order, :select, :where) == User.all
342
+ #
343
+ # One can additionally pass a hash as an argument to unscope specific +:where+ values.
344
+ # This is done by passing a hash with a single key-value pair. The key should be
345
+ # +:where+ and the value should be the where value to unscope. For example:
346
+ #
347
+ # User.where(name: "John", active: true).unscope(where: :name)
348
+ # == User.where(active: true)
349
+ #
350
+ # This method is similar to #except, but unlike
351
+ # #except, it persists across merges:
352
+ #
353
+ # User.order('email').merge(User.except(:order))
354
+ # == User.order('email')
355
+ #
356
+ # User.order('email').merge(User.unscope(:order))
357
+ # == User.all
358
+ #
359
+ # This means it can be used in association definitions:
360
+ #
361
+ # has_many :comments, -> { unscope(where: :trashed) }
362
+ #
363
+ def unscope(*args)
364
+ check_if_method_has_arguments!(:unscope, args)
365
+ spawn.unscope!(*args)
113
366
  end
114
367
 
368
+ def unscope!(*args) # :nodoc:
369
+ args.flatten!
370
+ self.unscope_values += args
371
+
372
+ args.each do |scope|
373
+ case scope
374
+ when Symbol
375
+ scope = :left_outer_joins if scope == :left_joins
376
+ if !VALID_UNSCOPING_VALUES.include?(scope)
377
+ raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
378
+ end
379
+ set_value(scope, DEFAULT_VALUES[scope])
380
+ when Hash
381
+ scope.each do |key, target_value|
382
+ if key != :where
383
+ raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
384
+ end
385
+
386
+ target_values = Array(target_value).map(&:to_s)
387
+ self.where_clause = where_clause.except(*target_values)
388
+ end
389
+ else
390
+ raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
391
+ end
392
+ end
393
+
394
+ self
395
+ end
396
+
397
+ # Performs a joins on +args+. The given symbol(s) should match the name of
398
+ # the association(s).
399
+ #
400
+ # User.joins(:posts)
401
+ # # SELECT "users".*
402
+ # # FROM "users"
403
+ # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
404
+ #
405
+ # Multiple joins:
406
+ #
407
+ # User.joins(:posts, :account)
408
+ # # SELECT "users".*
409
+ # # FROM "users"
410
+ # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
411
+ # # INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id"
412
+ #
413
+ # Nested joins:
414
+ #
415
+ # User.joins(posts: [:comments])
416
+ # # SELECT "users".*
417
+ # # FROM "users"
418
+ # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
419
+ # # INNER JOIN "comments" "comments_posts"
420
+ # # ON "comments_posts"."post_id" = "posts"."id"
421
+ #
422
+ # You can use strings in order to customize your joins:
423
+ #
424
+ # User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
425
+ # # SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
115
426
  def joins(*args)
116
- return self if args.compact.blank?
427
+ check_if_method_has_arguments!(:joins, args)
428
+ spawn.joins!(*args)
429
+ end
430
+
431
+ def joins!(*args) # :nodoc:
432
+ args.compact!
433
+ args.flatten!
434
+ self.joins_values += args
435
+ self
436
+ end
117
437
 
118
- relation = clone
438
+ # Performs a left outer joins on +args+:
439
+ #
440
+ # User.left_outer_joins(:posts)
441
+ # => SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
442
+ #
443
+ def left_outer_joins(*args)
444
+ check_if_method_has_arguments!(__callee__, args)
445
+ spawn.left_outer_joins!(*args)
446
+ end
447
+ alias :left_joins :left_outer_joins
119
448
 
449
+ def left_outer_joins!(*args) # :nodoc:
450
+ args.compact!
120
451
  args.flatten!
121
- relation.joins_values += args
452
+ self.left_outer_joins_values += args
453
+ self
454
+ end
122
455
 
123
- relation
456
+ # Returns a new relation, which is the result of filtering the current relation
457
+ # according to the conditions in the arguments.
458
+ #
459
+ # #where accepts conditions in one of several formats. In the examples below, the resulting
460
+ # SQL is given as an illustration; the actual query generated may be different depending
461
+ # on the database adapter.
462
+ #
463
+ # === string
464
+ #
465
+ # A single string, without additional arguments, is passed to the query
466
+ # constructor as an SQL fragment, and used in the where clause of the query.
467
+ #
468
+ # Client.where("orders_count = '2'")
469
+ # # SELECT * from clients where orders_count = '2';
470
+ #
471
+ # Note that building your own string from user input may expose your application
472
+ # to injection attacks if not done properly. As an alternative, it is recommended
473
+ # to use one of the following methods.
474
+ #
475
+ # === array
476
+ #
477
+ # If an array is passed, then the first element of the array is treated as a template, and
478
+ # the remaining elements are inserted into the template to generate the condition.
479
+ # Active Record takes care of building the query to avoid injection attacks, and will
480
+ # convert from the ruby type to the database type where needed. Elements are inserted
481
+ # into the string in the order in which they appear.
482
+ #
483
+ # User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
484
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
485
+ #
486
+ # Alternatively, you can use named placeholders in the template, and pass a hash as the
487
+ # second element of the array. The names in the template are replaced with the corresponding
488
+ # values from the hash.
489
+ #
490
+ # User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
491
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
492
+ #
493
+ # This can make for more readable code in complex queries.
494
+ #
495
+ # Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
496
+ # than the previous methods; you are responsible for ensuring that the values in the template
497
+ # are properly quoted. The values are passed to the connector for quoting, but the caller
498
+ # is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
499
+ # the values are inserted using the same escapes as the Ruby core method +Kernel::sprintf+.
500
+ #
501
+ # User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
502
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
503
+ #
504
+ # If #where is called with multiple arguments, these are treated as if they were passed as
505
+ # the elements of a single array.
506
+ #
507
+ # User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
508
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
509
+ #
510
+ # When using strings to specify conditions, you can use any operator available from
511
+ # the database. While this provides the most flexibility, you can also unintentionally introduce
512
+ # dependencies on the underlying database. If your code is intended for general consumption,
513
+ # test with multiple database backends.
514
+ #
515
+ # === hash
516
+ #
517
+ # #where will also accept a hash condition, in which the keys are fields and the values
518
+ # are values to be searched for.
519
+ #
520
+ # Fields can be symbols or strings. Values can be single values, arrays, or ranges.
521
+ #
522
+ # User.where({ name: "Joe", email: "joe@example.com" })
523
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
524
+ #
525
+ # User.where({ name: ["Alice", "Bob"]})
526
+ # # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
527
+ #
528
+ # User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
529
+ # # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
530
+ #
531
+ # In the case of a belongs_to relationship, an association key can be used
532
+ # to specify the model if an ActiveRecord object is used as the value.
533
+ #
534
+ # author = Author.find(1)
535
+ #
536
+ # # The following queries will be equivalent:
537
+ # Post.where(author: author)
538
+ # Post.where(author_id: author)
539
+ #
540
+ # This also works with polymorphic belongs_to relationships:
541
+ #
542
+ # treasure = Treasure.create(name: 'gold coins')
543
+ # treasure.price_estimates << PriceEstimate.create(price: 125)
544
+ #
545
+ # # The following queries will be equivalent:
546
+ # PriceEstimate.where(estimate_of: treasure)
547
+ # PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
548
+ #
549
+ # === Joins
550
+ #
551
+ # If the relation is the result of a join, you may create a condition which uses any of the
552
+ # tables in the join. For string and array conditions, use the table name in the condition.
553
+ #
554
+ # User.joins(:posts).where("posts.created_at < ?", Time.now)
555
+ #
556
+ # For hash conditions, you can either use the table name in the key, or use a sub-hash.
557
+ #
558
+ # User.joins(:posts).where({ "posts.published" => true })
559
+ # User.joins(:posts).where({ posts: { published: true } })
560
+ #
561
+ # === no argument
562
+ #
563
+ # If no argument is passed, #where returns a new instance of WhereChain, that
564
+ # can be chained with #not to return a new relation that negates the where clause.
565
+ #
566
+ # User.where.not(name: "Jon")
567
+ # # SELECT * FROM users WHERE name != 'Jon'
568
+ #
569
+ # See WhereChain for more details on #not.
570
+ #
571
+ # === blank condition
572
+ #
573
+ # If the condition is any blank-ish object, then #where is a no-op and returns
574
+ # the current relation.
575
+ def where(opts = :chain, *rest)
576
+ if :chain == opts
577
+ WhereChain.new(spawn)
578
+ elsif opts.blank?
579
+ self
580
+ else
581
+ spawn.where!(opts, *rest)
582
+ end
583
+ end
584
+
585
+ def where!(opts, *rest) # :nodoc:
586
+ opts = sanitize_forbidden_attributes(opts)
587
+ references!(PredicateBuilder.references(opts)) if Hash === opts
588
+ self.where_clause += where_clause_factory.build(opts, rest)
589
+ self
124
590
  end
125
591
 
126
- def bind(value)
127
- relation = clone
128
- relation.bind_values += [value]
129
- relation
592
+ # Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.
593
+ #
594
+ # Post.where(trashed: true).where(trashed: false)
595
+ # # WHERE `trashed` = 1 AND `trashed` = 0
596
+ #
597
+ # Post.where(trashed: true).rewhere(trashed: false)
598
+ # # WHERE `trashed` = 0
599
+ #
600
+ # Post.where(active: true).where(trashed: true).rewhere(trashed: false)
601
+ # # WHERE `active` = 1 AND `trashed` = 0
602
+ #
603
+ # This is short-hand for <tt>unscope(where: conditions.keys).where(conditions)</tt>.
604
+ # Note that unlike reorder, we're only unscoping the named conditions -- not the entire where statement.
605
+ def rewhere(conditions)
606
+ unscope(where: conditions.keys).where(conditions)
130
607
  end
131
608
 
132
- def where(opts, *rest)
133
- return self if opts.blank?
609
+ # Returns a new relation, which is the logical union of this relation and the one passed as an
610
+ # argument.
611
+ #
612
+ # The two relations must be structurally compatible: they must be scoping the same model, and
613
+ # they must differ only by #where (if no #group has been defined) or #having (if a #group is
614
+ # present). Neither relation may have a #limit, #offset, or #distinct set.
615
+ #
616
+ # Post.where("id = 1").or(Post.where("author_id = 3"))
617
+ # # SELECT `posts`.* FROM `posts` WHERE ((id = 1) OR (author_id = 3))
618
+ #
619
+ def or(other)
620
+ unless other.is_a? Relation
621
+ raise ArgumentError, "You have passed #{other.class.name} object to #or. Pass an ActiveRecord::Relation object instead."
622
+ end
134
623
 
135
- relation = clone
136
- relation.where_values += build_where(opts, rest)
137
- relation
624
+ spawn.or!(other)
138
625
  end
139
626
 
627
+ def or!(other) # :nodoc:
628
+ incompatible_values = structurally_incompatible_values_for_or(other)
629
+
630
+ unless incompatible_values.empty?
631
+ raise ArgumentError, "Relation passed to #or must be structurally compatible. Incompatible values: #{incompatible_values}"
632
+ end
633
+
634
+ self.where_clause = self.where_clause.or(other.where_clause)
635
+ self.having_clause = having_clause.or(other.having_clause)
636
+ self.references_values += other.references_values
637
+
638
+ self
639
+ end
640
+
641
+ # Allows to specify a HAVING clause. Note that you can't use HAVING
642
+ # without also specifying a GROUP clause.
643
+ #
644
+ # Order.having('SUM(price) > 30').group('user_id')
140
645
  def having(opts, *rest)
141
- return self if opts.blank?
646
+ opts.blank? ? self : spawn.having!(opts, *rest)
647
+ end
648
+
649
+ def having!(opts, *rest) # :nodoc:
650
+ opts = sanitize_forbidden_attributes(opts)
651
+ references!(PredicateBuilder.references(opts)) if Hash === opts
142
652
 
143
- relation = clone
144
- relation.having_values += build_where(opts, rest)
145
- relation
653
+ self.having_clause += having_clause_factory.build(opts, rest)
654
+ self
146
655
  end
147
656
 
657
+ # Specifies a limit for the number of records to retrieve.
658
+ #
659
+ # User.limit(10) # generated SQL has 'LIMIT 10'
660
+ #
661
+ # User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
148
662
  def limit(value)
149
- relation = clone
150
- relation.limit_value = value
151
- relation
663
+ spawn.limit!(value)
664
+ end
665
+
666
+ def limit!(value) # :nodoc:
667
+ self.limit_value = value
668
+ self
152
669
  end
153
670
 
671
+ # Specifies the number of rows to skip before returning rows.
672
+ #
673
+ # User.offset(10) # generated SQL has "OFFSET 10"
674
+ #
675
+ # Should be used with order.
676
+ #
677
+ # User.offset(10).order("name ASC")
154
678
  def offset(value)
155
- relation = clone
156
- relation.offset_value = value
157
- relation
679
+ spawn.offset!(value)
680
+ end
681
+
682
+ def offset!(value) # :nodoc:
683
+ self.offset_value = value
684
+ self
158
685
  end
159
686
 
687
+ # Specifies locking settings (default to +true+). For more information
688
+ # on locking, please see ActiveRecord::Locking.
160
689
  def lock(locks = true)
161
- relation = clone
690
+ spawn.lock!(locks)
691
+ end
162
692
 
693
+ def lock!(locks = true) # :nodoc:
163
694
  case locks
164
695
  when String, TrueClass, NilClass
165
- relation.lock_value = locks || true
696
+ self.lock_value = locks || true
166
697
  else
167
- relation.lock_value = false
698
+ self.lock_value = false
168
699
  end
169
700
 
170
- relation
701
+ self
702
+ end
703
+
704
+ # Returns a chainable relation with zero records.
705
+ #
706
+ # The returned relation implements the Null Object pattern. It is an
707
+ # object with defined null behavior and always returns an empty array of
708
+ # records without querying the database.
709
+ #
710
+ # Any subsequent condition chained to the returned relation will continue
711
+ # generating an empty relation and will not fire any query to the database.
712
+ #
713
+ # Used in cases where a method or scope could return zero records but the
714
+ # result needs to be chainable.
715
+ #
716
+ # For example:
717
+ #
718
+ # @posts = current_user.visible_posts.where(name: params[:name])
719
+ # # the visible_posts method is expected to return a chainable Relation
720
+ #
721
+ # def visible_posts
722
+ # case role
723
+ # when 'Country Manager'
724
+ # Post.where(country: country)
725
+ # when 'Reviewer'
726
+ # Post.published
727
+ # when 'Bad User'
728
+ # Post.none # It can't be chained if [] is returned.
729
+ # end
730
+ # end
731
+ #
732
+ def none
733
+ spawn.none!
734
+ end
735
+
736
+ def none! # :nodoc:
737
+ where!("1=0").extending!(NullRelation)
171
738
  end
172
739
 
740
+ # Sets readonly attributes for the returned relation. If value is
741
+ # true (default), attempting to update a record will result in an error.
742
+ #
743
+ # users = User.readonly
744
+ # users.first.save
745
+ # => ActiveRecord::ReadOnlyRecord: User is marked as readonly
173
746
  def readonly(value = true)
174
- relation = clone
175
- relation.readonly_value = value
176
- relation
747
+ spawn.readonly!(value)
748
+ end
749
+
750
+ def readonly!(value = true) # :nodoc:
751
+ self.readonly_value = value
752
+ self
177
753
  end
178
754
 
755
+ # Sets attributes to be used when creating new records from a
756
+ # relation object.
757
+ #
758
+ # users = User.where(name: 'Oscar')
759
+ # users.new.name # => 'Oscar'
760
+ #
761
+ # users = users.create_with(name: 'DHH')
762
+ # users.new.name # => 'DHH'
763
+ #
764
+ # You can pass +nil+ to #create_with to reset attributes:
765
+ #
766
+ # users = users.create_with(nil)
767
+ # users.new.name # => 'Oscar'
179
768
  def create_with(value)
180
- relation = clone
181
- relation.create_with_value = value ? create_with_value.merge(value) : {}
182
- relation
769
+ spawn.create_with!(value)
183
770
  end
184
771
 
185
- def from(value)
186
- relation = clone
187
- relation.from_value = value
188
- relation
772
+ def create_with!(value) # :nodoc:
773
+ if value
774
+ value = sanitize_forbidden_attributes(value)
775
+ self.create_with_value = create_with_value.merge(value)
776
+ else
777
+ self.create_with_value = FROZEN_EMPTY_HASH
778
+ end
779
+
780
+ self
781
+ end
782
+
783
+ # Specifies table from which the records will be fetched. For example:
784
+ #
785
+ # Topic.select('title').from('posts')
786
+ # # SELECT title FROM posts
787
+ #
788
+ # Can accept other relation objects. For example:
789
+ #
790
+ # Topic.select('title').from(Topic.approved)
791
+ # # SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
792
+ #
793
+ # Topic.select('a.title').from(Topic.approved, :a)
794
+ # # SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
795
+ #
796
+ def from(value, subquery_name = nil)
797
+ spawn.from!(value, subquery_name)
798
+ end
799
+
800
+ def from!(value, subquery_name = nil) # :nodoc:
801
+ self.from_clause = Relation::FromClause.new(value, subquery_name)
802
+ self
189
803
  end
190
804
 
191
805
  # Specifies whether the records should be unique or not. For example:
192
806
  #
193
807
  # User.select(:name)
194
- # # => Might return two records with the same name
808
+ # # Might return two records with the same name
195
809
  #
196
- # User.select(:name).uniq
197
- # # => Returns 1 record per unique name
810
+ # User.select(:name).distinct
811
+ # # Returns 1 record per distinct name
198
812
  #
199
- # User.select(:name).uniq.uniq(false)
200
- # # => You can also remove the uniqueness
201
- def uniq(value = true)
202
- relation = clone
203
- relation.uniq_value = value
204
- relation
813
+ # User.select(:name).distinct.distinct(false)
814
+ # # You can also remove the uniqueness
815
+ def distinct(value = true)
816
+ spawn.distinct!(value)
817
+ end
818
+
819
+ # Like #distinct, but modifies relation in place.
820
+ def distinct!(value = true) # :nodoc:
821
+ self.distinct_value = value
822
+ self
205
823
  end
206
824
 
207
825
  # Used to extend a scope with additional methods, either through
@@ -217,16 +835,16 @@ module ActiveRecord
217
835
  # end
218
836
  # end
219
837
  #
220
- # scope = Model.scoped.extending(Pagination)
838
+ # scope = Model.all.extending(Pagination)
221
839
  # scope.page(params[:page])
222
840
  #
223
841
  # You can also pass a list of modules:
224
842
  #
225
- # scope = Model.scoped.extending(Pagination, SomethingElse)
843
+ # scope = Model.all.extending(Pagination, SomethingElse)
226
844
  #
227
845
  # === Using a block
228
846
  #
229
- # scope = Model.scoped.extending do
847
+ # scope = Model.all.extending do
230
848
  # def page(number)
231
849
  # # pagination code goes here
232
850
  # end
@@ -235,183 +853,381 @@ module ActiveRecord
235
853
  #
236
854
  # You can also use a block and a module list:
237
855
  #
238
- # scope = Model.scoped.extending(Pagination) do
856
+ # scope = Model.all.extending(Pagination) do
239
857
  # def per_page(number)
240
858
  # # pagination code goes here
241
859
  # end
242
860
  # end
243
- def extending(*modules)
244
- modules << Module.new(&Proc.new) if block_given?
861
+ def extending(*modules, &block)
862
+ if modules.any? || block
863
+ spawn.extending!(*modules, &block)
864
+ else
865
+ self
866
+ end
867
+ end
868
+
869
+ def extending!(*modules, &block) # :nodoc:
870
+ modules << Module.new(&block) if block
871
+ modules.flatten!
245
872
 
246
- return self if modules.empty?
873
+ self.extending_values += modules
874
+ extend(*extending_values) if extending_values.any?
247
875
 
248
- relation = clone
249
- relation.send(:apply_modules, modules.flatten)
250
- relation
876
+ self
251
877
  end
252
878
 
879
+ # Reverse the existing order clause on the relation.
880
+ #
881
+ # User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
253
882
  def reverse_order
254
- relation = clone
255
- relation.reverse_order_value = !relation.reverse_order_value
256
- relation
883
+ spawn.reverse_order!
257
884
  end
258
885
 
259
- def arel
260
- @arel ||= with_default_scope.build_arel
886
+ def reverse_order! # :nodoc:
887
+ orders = order_values.uniq
888
+ orders.reject!(&:blank?)
889
+ self.order_values = reverse_sql_order(orders)
890
+ self
261
891
  end
262
892
 
263
- def build_arel
264
- arel = table.from table
893
+ def skip_query_cache!(value = true) # :nodoc:
894
+ self.skip_query_cache_value = value
895
+ self
896
+ end
265
897
 
266
- build_joins(arel, @joins_values) unless @joins_values.empty?
898
+ # Returns the Arel object associated with the relation.
899
+ def arel(aliases = nil) # :nodoc:
900
+ @arel ||= build_arel(aliases)
901
+ end
267
902
 
268
- collapse_wheres(arel, (@where_values - ['']).uniq)
903
+ # Returns a relation value with a given name
904
+ def get_value(name) # :nodoc:
905
+ @values.fetch(name, DEFAULT_VALUES[name])
906
+ end
269
907
 
270
- arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?
908
+ protected
271
909
 
272
- arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
273
- arel.skip(@offset_value.to_i) if @offset_value
910
+ # Sets the relation value with the given name
911
+ def set_value(name, value) # :nodoc:
912
+ assert_mutability!
913
+ @values[name] = value
914
+ end
274
915
 
275
- arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty?
916
+ private
276
917
 
277
- order = @order_values
278
- order = reverse_sql_order(order) if @reverse_order_value
279
- arel.order(*order.uniq.reject{|o| o.blank?}) unless order.empty?
918
+ def assert_mutability!
919
+ raise ImmutableRelation if @loaded
920
+ raise ImmutableRelation if defined?(@arel) && @arel
921
+ end
280
922
 
281
- build_select(arel, @select_values.uniq)
923
+ def build_arel(aliases)
924
+ arel = Arel::SelectManager.new(table)
925
+
926
+ aliases = build_joins(arel, joins_values.flatten, aliases) unless joins_values.empty?
927
+ build_left_outer_joins(arel, left_outer_joins_values.flatten, aliases) unless left_outer_joins_values.empty?
928
+
929
+ arel.where(where_clause.ast) unless where_clause.empty?
930
+ arel.having(having_clause.ast) unless having_clause.empty?
931
+ if limit_value
932
+ limit_attribute = ActiveModel::Attribute.with_cast_value(
933
+ "LIMIT".freeze,
934
+ connection.sanitize_limit(limit_value),
935
+ Type.default_value,
936
+ )
937
+ arel.take(Arel::Nodes::BindParam.new(limit_attribute))
938
+ end
939
+ if offset_value
940
+ offset_attribute = ActiveModel::Attribute.with_cast_value(
941
+ "OFFSET".freeze,
942
+ offset_value.to_i,
943
+ Type.default_value,
944
+ )
945
+ arel.skip(Arel::Nodes::BindParam.new(offset_attribute))
946
+ end
947
+ arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty?
282
948
 
283
- arel.distinct(@uniq_value)
284
- arel.from(@from_value) if @from_value
285
- arel.lock(@lock_value) if @lock_value
949
+ build_order(arel)
286
950
 
287
- arel
288
- end
951
+ build_select(arel)
289
952
 
290
- private
953
+ arel.distinct(distinct_value)
954
+ arel.from(build_from) unless from_clause.empty?
955
+ arel.lock(lock_value) if lock_value
291
956
 
292
- def custom_join_ast(table, joins)
293
- joins = joins.reject { |join| join.blank? }
957
+ arel
958
+ end
294
959
 
295
- return [] if joins.empty?
960
+ def build_from
961
+ opts = from_clause.value
962
+ name = from_clause.name
963
+ case opts
964
+ when Relation
965
+ if opts.eager_loading?
966
+ opts = opts.send(:apply_join_dependency)
967
+ end
968
+ name ||= "subquery"
969
+ opts.arel.as(name.to_s)
970
+ else
971
+ opts
972
+ end
973
+ end
296
974
 
297
- @implicit_readonly = true
975
+ def build_left_outer_joins(manager, outer_joins, aliases)
976
+ buckets = outer_joins.group_by do |join|
977
+ case join
978
+ when Hash, Symbol, Array
979
+ :association_join
980
+ when ActiveRecord::Associations::JoinDependency
981
+ :stashed_join
982
+ else
983
+ raise ArgumentError, "only Hash, Symbol and Array are allowed"
984
+ end
985
+ end
298
986
 
299
- joins.map do |join|
300
- case join
301
- when Array
302
- join = Arel.sql(join.join(' ')) if array_of_strings?(join)
303
- when String
304
- join = Arel.sql(join)
987
+ build_join_query(manager, buckets, Arel::Nodes::OuterJoin, aliases)
988
+ end
989
+
990
+ def build_joins(manager, joins, aliases)
991
+ buckets = joins.group_by do |join|
992
+ case join
993
+ when String
994
+ :string_join
995
+ when Hash, Symbol, Array
996
+ :association_join
997
+ when ActiveRecord::Associations::JoinDependency
998
+ :stashed_join
999
+ when Arel::Nodes::Join
1000
+ :join_node
1001
+ else
1002
+ raise "unknown class: %s" % join.class.name
1003
+ end
305
1004
  end
306
- table.create_string_join(join)
1005
+
1006
+ build_join_query(manager, buckets, Arel::Nodes::InnerJoin, aliases)
307
1007
  end
308
- end
309
1008
 
310
- def collapse_wheres(arel, wheres)
311
- equalities = wheres.grep(Arel::Nodes::Equality)
1009
+ def build_join_query(manager, buckets, join_type, aliases)
1010
+ buckets.default = []
1011
+
1012
+ association_joins = buckets[:association_join]
1013
+ stashed_joins = buckets[:stashed_join]
1014
+ join_nodes = buckets[:join_node].uniq
1015
+ string_joins = buckets[:string_join].map(&:strip).uniq
1016
+
1017
+ join_list = join_nodes + convert_join_strings_to_ast(string_joins)
1018
+ alias_tracker = alias_tracker(join_list, aliases)
1019
+
1020
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(
1021
+ klass, table, association_joins
1022
+ )
312
1023
 
313
- arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
1024
+ joins = join_dependency.join_constraints(stashed_joins, join_type, alias_tracker)
1025
+ joins.each { |join| manager.from(join) }
314
1026
 
315
- (wheres - equalities).each do |where|
316
- where = Arel.sql(where) if String === where
317
- arel.where(Arel::Nodes::Grouping.new(where))
1027
+ manager.join_sources.concat(join_list)
1028
+
1029
+ alias_tracker.aliases
318
1030
  end
319
- end
320
1031
 
321
- def build_where(opts, other = [])
322
- case opts
323
- when String, Array
324
- [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
325
- when Hash
326
- attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
327
- PredicateBuilder.build_from_hash(table.engine, attributes, table)
328
- else
329
- [opts]
1032
+ def convert_join_strings_to_ast(joins)
1033
+ joins
1034
+ .flatten
1035
+ .reject(&:blank?)
1036
+ .map { |join| table.create_string_join(Arel.sql(join)) }
330
1037
  end
331
- end
332
1038
 
333
- def build_joins(manager, joins)
334
- buckets = joins.group_by do |join|
335
- case join
336
- when String
337
- 'string_join'
338
- when Hash, Symbol, Array
339
- 'association_join'
340
- when ActiveRecord::Associations::JoinDependency::JoinAssociation
341
- 'stashed_join'
342
- when Arel::Nodes::Join
343
- 'join_node'
1039
+ def build_select(arel)
1040
+ if select_values.any?
1041
+ arel.project(*arel_columns(select_values.uniq))
1042
+ elsif klass.ignored_columns.any?
1043
+ arel.project(*klass.column_names.map { |field| arel_attribute(field) })
344
1044
  else
345
- raise 'unknown class: %s' % join.class.name
1045
+ arel.project(table[Arel.star])
346
1046
  end
347
1047
  end
348
1048
 
349
- association_joins = buckets['association_join'] || []
350
- stashed_association_joins = buckets['stashed_join'] || []
351
- join_nodes = (buckets['join_node'] || []).uniq
352
- string_joins = (buckets['string_join'] || []).map { |x|
353
- x.strip
354
- }.uniq
1049
+ def arel_columns(columns)
1050
+ columns.flat_map do |field|
1051
+ case field
1052
+ when Symbol
1053
+ arel_column(field.to_s) do |attr_name|
1054
+ connection.quote_table_name(attr_name)
1055
+ end
1056
+ when String
1057
+ arel_column(field, &:itself)
1058
+ when Proc
1059
+ field.call
1060
+ else
1061
+ field
1062
+ end
1063
+ end
1064
+ end
355
1065
 
356
- join_list = join_nodes + custom_join_ast(manager, string_joins)
1066
+ def arel_column(field)
1067
+ field = klass.attribute_alias(field) if klass.attribute_alias?(field)
1068
+ from = from_clause.name || from_clause.value
357
1069
 
358
- join_dependency = ActiveRecord::Associations::JoinDependency.new(
359
- @klass,
360
- association_joins,
361
- join_list
362
- )
1070
+ if klass.columns_hash.key?(field) && (!from || table_name_matches?(from))
1071
+ arel_attribute(field)
1072
+ else
1073
+ yield field
1074
+ end
1075
+ end
363
1076
 
364
- join_dependency.graft(*stashed_association_joins)
1077
+ def table_name_matches?(from)
1078
+ /(?:\A|(?<!FROM)\s)(?:\b#{table.name}\b|#{connection.quote_table_name(table.name)})(?!\.)/i.match?(from.to_s)
1079
+ end
365
1080
 
366
- @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
1081
+ def reverse_sql_order(order_query)
1082
+ if order_query.empty?
1083
+ return [arel_attribute(primary_key).desc] if primary_key
1084
+ raise IrreversibleOrderError,
1085
+ "Relation has no current order and table has no primary key to be used as default order"
1086
+ end
367
1087
 
368
- # FIXME: refactor this to build an AST
369
- join_dependency.join_associations.each do |association|
370
- association.join_to(manager)
1088
+ order_query.flat_map do |o|
1089
+ case o
1090
+ when Arel::Attribute
1091
+ o.desc
1092
+ when Arel::Nodes::Ordering
1093
+ o.reverse
1094
+ when String
1095
+ if does_not_support_reverse?(o)
1096
+ raise IrreversibleOrderError, "Order #{o.inspect} can not be reversed automatically"
1097
+ end
1098
+ o.split(",").map! do |s|
1099
+ s.strip!
1100
+ s.gsub!(/\sasc\Z/i, " DESC") || s.gsub!(/\sdesc\Z/i, " ASC") || (s << " DESC")
1101
+ end
1102
+ else
1103
+ o
1104
+ end
1105
+ end
371
1106
  end
372
1107
 
373
- manager.join_sources.concat join_list
1108
+ def does_not_support_reverse?(order)
1109
+ # Account for String subclasses like Arel::Nodes::SqlLiteral that
1110
+ # override methods like #count.
1111
+ order = String.new(order) unless order.instance_of?(String)
374
1112
 
375
- manager
376
- end
1113
+ # Uses SQL function with multiple arguments.
1114
+ (order.include?(",") && order.split(",").find { |section| section.count("(") != section.count(")") }) ||
1115
+ # Uses "nulls first" like construction.
1116
+ /nulls (first|last)\Z/i.match?(order)
1117
+ end
377
1118
 
378
- def build_select(arel, selects)
379
- unless selects.empty?
380
- @implicit_readonly = false
381
- arel.project(*selects)
382
- else
383
- arel.project(@klass.arel_table[Arel.star])
1119
+ def build_order(arel)
1120
+ orders = order_values.uniq
1121
+ orders.reject!(&:blank?)
1122
+
1123
+ arel.order(*orders) unless orders.empty?
384
1124
  end
385
- end
386
1125
 
387
- def apply_modules(modules)
388
- unless modules.empty?
389
- @extensions += modules
390
- modules.each {|extension| extend(extension) }
1126
+ VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC,
1127
+ "asc", "desc", "ASC", "DESC"].to_set # :nodoc:
1128
+
1129
+ def validate_order_args(args)
1130
+ args.each do |arg|
1131
+ next unless arg.is_a?(Hash)
1132
+ arg.each do |_key, value|
1133
+ unless VALID_DIRECTIONS.include?(value)
1134
+ raise ArgumentError,
1135
+ "Direction \"#{value}\" is invalid. Valid directions are: #{VALID_DIRECTIONS.to_a.inspect}"
1136
+ end
1137
+ end
1138
+ end
391
1139
  end
392
- end
393
1140
 
394
- def reverse_sql_order(order_query)
395
- order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
1141
+ def preprocess_order_args(order_args)
1142
+ order_args.map! do |arg|
1143
+ klass.sanitize_sql_for_order(arg)
1144
+ end
1145
+ order_args.flatten!
1146
+
1147
+ @klass.enforce_raw_sql_whitelist(
1148
+ order_args.flat_map { |a| a.is_a?(Hash) ? a.keys : a },
1149
+ whitelist: AttributeMethods::ClassMethods::COLUMN_NAME_ORDER_WHITELIST
1150
+ )
1151
+
1152
+ validate_order_args(order_args)
1153
+
1154
+ references = order_args.grep(String)
1155
+ references.map! { |arg| arg =~ /^\W?(\w+)\W?\./ && $1 }.compact!
1156
+ references!(references) if references.any?
1157
+
1158
+ # if a symbol is given we prepend the quoted table name
1159
+ order_args.map! do |arg|
1160
+ case arg
1161
+ when Symbol
1162
+ order_column(arg.to_s).asc
1163
+ when Hash
1164
+ arg.map { |field, dir|
1165
+ case field
1166
+ when Arel::Nodes::SqlLiteral
1167
+ field.send(dir.downcase)
1168
+ else
1169
+ order_column(field.to_s).send(dir.downcase)
1170
+ end
1171
+ }
1172
+ else
1173
+ arg
1174
+ end
1175
+ end.flatten!
1176
+ end
396
1177
 
397
- order_query.map do |o|
398
- case o
399
- when Arel::Nodes::Ordering
400
- o.reverse
401
- when String, Symbol
402
- o.to_s.split(',').collect do |s|
403
- s.strip!
404
- s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
1178
+ def order_column(field)
1179
+ arel_column(field) do |attr_name|
1180
+ if attr_name == "count" && !group_values.empty?
1181
+ arel_attribute(attr_name)
1182
+ else
1183
+ Arel.sql(connection.quote_table_name(attr_name))
405
1184
  end
406
- else
407
- o
408
1185
  end
409
- end.flatten
410
- end
1186
+ end
411
1187
 
412
- def array_of_strings?(o)
413
- o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
414
- end
1188
+ # Checks to make sure that the arguments are not blank. Note that if some
1189
+ # blank-like object were initially passed into the query method, then this
1190
+ # method will not raise an error.
1191
+ #
1192
+ # Example:
1193
+ #
1194
+ # Post.references() # raises an error
1195
+ # Post.references([]) # does not raise an error
1196
+ #
1197
+ # This particular method should be called with a method_name and the args
1198
+ # passed into that method as an input. For example:
1199
+ #
1200
+ # def references(*args)
1201
+ # check_if_method_has_arguments!("references", args)
1202
+ # ...
1203
+ # end
1204
+ def check_if_method_has_arguments!(method_name, args)
1205
+ if args.blank?
1206
+ raise ArgumentError, "The method .#{method_name}() must contain arguments."
1207
+ end
1208
+ end
1209
+
1210
+ STRUCTURAL_OR_METHODS = Relation::VALUE_METHODS - [:extending, :where, :having, :unscope, :references]
1211
+ def structurally_incompatible_values_for_or(other)
1212
+ STRUCTURAL_OR_METHODS.reject do |method|
1213
+ get_value(method) == other.get_value(method)
1214
+ end
1215
+ end
415
1216
 
1217
+ def where_clause_factory
1218
+ @where_clause_factory ||= Relation::WhereClauseFactory.new(klass, predicate_builder)
1219
+ end
1220
+ alias having_clause_factory where_clause_factory
1221
+
1222
+ DEFAULT_VALUES = {
1223
+ create_with: FROZEN_EMPTY_HASH,
1224
+ where: Relation::WhereClause.empty,
1225
+ having: Relation::WhereClause.empty,
1226
+ from: Relation::FromClause.empty
1227
+ }
1228
+
1229
+ Relation::MULTI_VALUE_METHODS.each do |value|
1230
+ DEFAULT_VALUES[value] ||= FROZEN_EMPTY_ARRAY
1231
+ end
416
1232
  end
417
1233
  end