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