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