activerecord 5.2.3

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