sskirby-activerecord 3.2.1
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG.md +6749 -0
- data/MIT-LICENSE +20 -0
- data/README.rdoc +222 -0
- data/examples/associations.png +0 -0
- data/examples/performance.rb +177 -0
- data/examples/simple.rb +14 -0
- data/lib/active_record.rb +147 -0
- data/lib/active_record/aggregations.rb +255 -0
- data/lib/active_record/associations.rb +1604 -0
- data/lib/active_record/associations/alias_tracker.rb +79 -0
- data/lib/active_record/associations/association.rb +239 -0
- data/lib/active_record/associations/association_scope.rb +119 -0
- data/lib/active_record/associations/belongs_to_association.rb +79 -0
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +34 -0
- data/lib/active_record/associations/builder/association.rb +55 -0
- data/lib/active_record/associations/builder/belongs_to.rb +85 -0
- data/lib/active_record/associations/builder/collection_association.rb +75 -0
- data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +57 -0
- data/lib/active_record/associations/builder/has_many.rb +71 -0
- data/lib/active_record/associations/builder/has_one.rb +62 -0
- data/lib/active_record/associations/builder/singular_association.rb +32 -0
- data/lib/active_record/associations/collection_association.rb +574 -0
- data/lib/active_record/associations/collection_proxy.rb +132 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +62 -0
- data/lib/active_record/associations/has_many_association.rb +108 -0
- data/lib/active_record/associations/has_many_through_association.rb +180 -0
- data/lib/active_record/associations/has_one_association.rb +73 -0
- data/lib/active_record/associations/has_one_through_association.rb +36 -0
- data/lib/active_record/associations/join_dependency.rb +214 -0
- data/lib/active_record/associations/join_dependency/join_association.rb +154 -0
- data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
- data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
- data/lib/active_record/associations/join_helper.rb +55 -0
- data/lib/active_record/associations/preloader.rb +177 -0
- data/lib/active_record/associations/preloader/association.rb +127 -0
- data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
- data/lib/active_record/associations/preloader/collection_association.rb +24 -0
- data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
- data/lib/active_record/associations/preloader/has_many.rb +17 -0
- data/lib/active_record/associations/preloader/has_many_through.rb +15 -0
- data/lib/active_record/associations/preloader/has_one.rb +23 -0
- data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
- data/lib/active_record/associations/preloader/singular_association.rb +21 -0
- data/lib/active_record/associations/preloader/through_association.rb +67 -0
- data/lib/active_record/associations/singular_association.rb +64 -0
- data/lib/active_record/associations/through_association.rb +83 -0
- data/lib/active_record/attribute_assignment.rb +221 -0
- data/lib/active_record/attribute_methods.rb +272 -0
- data/lib/active_record/attribute_methods/before_type_cast.rb +31 -0
- data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
- data/lib/active_record/attribute_methods/dirty.rb +101 -0
- data/lib/active_record/attribute_methods/primary_key.rb +114 -0
- data/lib/active_record/attribute_methods/query.rb +39 -0
- data/lib/active_record/attribute_methods/read.rb +135 -0
- data/lib/active_record/attribute_methods/serialization.rb +93 -0
- data/lib/active_record/attribute_methods/time_zone_conversion.rb +62 -0
- data/lib/active_record/attribute_methods/write.rb +69 -0
- data/lib/active_record/autosave_association.rb +422 -0
- data/lib/active_record/base.rb +716 -0
- data/lib/active_record/callbacks.rb +275 -0
- data/lib/active_record/coders/yaml_column.rb +41 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +452 -0
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +188 -0
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +58 -0
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +388 -0
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -0
- data/lib/active_record/connection_adapters/abstract/quoting.rb +115 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +492 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +598 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +296 -0
- data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +653 -0
- data/lib/active_record/connection_adapters/column.rb +270 -0
- data/lib/active_record/connection_adapters/mysql2_adapter.rb +288 -0
- data/lib/active_record/connection_adapters/mysql_adapter.rb +426 -0
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +1261 -0
- data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +55 -0
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +577 -0
- data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
- data/lib/active_record/counter_cache.rb +119 -0
- data/lib/active_record/dynamic_finder_match.rb +56 -0
- data/lib/active_record/dynamic_matchers.rb +79 -0
- data/lib/active_record/dynamic_scope_match.rb +23 -0
- data/lib/active_record/errors.rb +195 -0
- data/lib/active_record/explain.rb +85 -0
- data/lib/active_record/explain_subscriber.rb +21 -0
- data/lib/active_record/fixtures.rb +906 -0
- data/lib/active_record/fixtures/file.rb +65 -0
- data/lib/active_record/identity_map.rb +156 -0
- data/lib/active_record/inheritance.rb +167 -0
- data/lib/active_record/integration.rb +49 -0
- data/lib/active_record/locale/en.yml +40 -0
- data/lib/active_record/locking/optimistic.rb +183 -0
- data/lib/active_record/locking/pessimistic.rb +77 -0
- data/lib/active_record/log_subscriber.rb +68 -0
- data/lib/active_record/migration.rb +765 -0
- data/lib/active_record/migration/command_recorder.rb +105 -0
- data/lib/active_record/model_schema.rb +366 -0
- data/lib/active_record/nested_attributes.rb +469 -0
- data/lib/active_record/observer.rb +121 -0
- data/lib/active_record/persistence.rb +372 -0
- data/lib/active_record/query_cache.rb +74 -0
- data/lib/active_record/querying.rb +58 -0
- data/lib/active_record/railtie.rb +119 -0
- data/lib/active_record/railties/console_sandbox.rb +6 -0
- data/lib/active_record/railties/controller_runtime.rb +49 -0
- data/lib/active_record/railties/databases.rake +620 -0
- data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
- data/lib/active_record/readonly_attributes.rb +26 -0
- data/lib/active_record/reflection.rb +534 -0
- data/lib/active_record/relation.rb +534 -0
- data/lib/active_record/relation/batches.rb +90 -0
- data/lib/active_record/relation/calculations.rb +354 -0
- data/lib/active_record/relation/delegation.rb +49 -0
- data/lib/active_record/relation/finder_methods.rb +398 -0
- data/lib/active_record/relation/predicate_builder.rb +58 -0
- data/lib/active_record/relation/query_methods.rb +417 -0
- data/lib/active_record/relation/spawn_methods.rb +148 -0
- data/lib/active_record/result.rb +34 -0
- data/lib/active_record/sanitization.rb +194 -0
- data/lib/active_record/schema.rb +58 -0
- data/lib/active_record/schema_dumper.rb +204 -0
- data/lib/active_record/scoping.rb +152 -0
- data/lib/active_record/scoping/default.rb +142 -0
- data/lib/active_record/scoping/named.rb +202 -0
- data/lib/active_record/serialization.rb +18 -0
- data/lib/active_record/serializers/xml_serializer.rb +202 -0
- data/lib/active_record/session_store.rb +358 -0
- data/lib/active_record/store.rb +50 -0
- data/lib/active_record/test_case.rb +73 -0
- data/lib/active_record/timestamp.rb +113 -0
- data/lib/active_record/transactions.rb +360 -0
- data/lib/active_record/translation.rb +22 -0
- data/lib/active_record/validations.rb +83 -0
- data/lib/active_record/validations/associated.rb +43 -0
- data/lib/active_record/validations/uniqueness.rb +180 -0
- data/lib/active_record/version.rb +10 -0
- data/lib/rails/generators/active_record.rb +25 -0
- data/lib/rails/generators/active_record/migration.rb +15 -0
- data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
- data/lib/rails/generators/active_record/migration/templates/migration.rb +31 -0
- data/lib/rails/generators/active_record/model/model_generator.rb +43 -0
- data/lib/rails/generators/active_record/model/templates/migration.rb +15 -0
- data/lib/rails/generators/active_record/model/templates/model.rb +7 -0
- data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
- data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
- data/lib/rails/generators/active_record/observer/templates/observer.rb +4 -0
- data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +25 -0
- data/lib/rails/generators/active_record/session_migration/templates/migration.rb +12 -0
- metadata +242 -0
@@ -0,0 +1,398 @@
|
|
1
|
+
require 'active_support/core_ext/object/blank'
|
2
|
+
require 'active_support/core_ext/hash/indifferent_access'
|
3
|
+
|
4
|
+
module ActiveRecord
|
5
|
+
module FinderMethods
|
6
|
+
# Find operates with four different retrieval approaches:
|
7
|
+
#
|
8
|
+
# * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
|
9
|
+
# If no record can be found for all of the listed ids, then RecordNotFound will be raised.
|
10
|
+
# * Find first - This will return the first record matched by the options used. These options can either be specific
|
11
|
+
# conditions or merely an order. If no record can be matched, +nil+ is returned. Use
|
12
|
+
# <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
|
13
|
+
# * Find last - This will return the last record matched by the options used. These options can either be specific
|
14
|
+
# conditions or merely an order. If no record can be matched, +nil+ is returned. Use
|
15
|
+
# <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
|
16
|
+
# * Find all - This will return all the records matched by the options used.
|
17
|
+
# If no records are found, an empty array is returned. Use
|
18
|
+
# <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
|
19
|
+
#
|
20
|
+
# All approaches accept an options hash as their last parameter.
|
21
|
+
#
|
22
|
+
# ==== Options
|
23
|
+
#
|
24
|
+
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>,
|
25
|
+
# or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
|
26
|
+
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
|
27
|
+
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
|
28
|
+
# * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
|
29
|
+
# <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
|
30
|
+
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
|
31
|
+
# * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
|
32
|
+
# it would skip rows 0 through 4.
|
33
|
+
# * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
|
34
|
+
# named associations in the same form used for the <tt>:include</tt> option, which will perform an
|
35
|
+
# <tt>INNER JOIN</tt> on the associated table(s),
|
36
|
+
# or an array containing a mixture of both strings and named associations.
|
37
|
+
# If the value is a string, then the records will be returned read-only since they will
|
38
|
+
# have attributes that do not correspond to the table's columns.
|
39
|
+
# Pass <tt>:readonly => false</tt> to override.
|
40
|
+
# * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
|
41
|
+
# to already defined associations. See eager loading under Associations.
|
42
|
+
# * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
|
43
|
+
# for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
|
44
|
+
# * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
|
45
|
+
# to an alternate table name (or even the name of a database view).
|
46
|
+
# * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
|
47
|
+
# * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
|
48
|
+
# <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
|
49
|
+
#
|
50
|
+
# ==== Examples
|
51
|
+
#
|
52
|
+
# # find by id
|
53
|
+
# Person.find(1) # returns the object for ID = 1
|
54
|
+
# Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
|
55
|
+
# Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
|
56
|
+
# Person.find([1]) # returns an array for the object with ID = 1
|
57
|
+
# Person.where("administrator = 1").order("created_on DESC").find(1)
|
58
|
+
#
|
59
|
+
# Note that returned records may not be in the same order as the ids you
|
60
|
+
# provide since database rows are unordered. Give an explicit <tt>:order</tt>
|
61
|
+
# to ensure the results are sorted.
|
62
|
+
#
|
63
|
+
# ==== Examples
|
64
|
+
#
|
65
|
+
# # find first
|
66
|
+
# Person.first # returns the first object fetched by SELECT * FROM people
|
67
|
+
# Person.where(["user_name = ?", user_name]).first
|
68
|
+
# Person.where(["user_name = :u", { :u => user_name }]).first
|
69
|
+
# Person.order("created_on DESC").offset(5).first
|
70
|
+
#
|
71
|
+
# # find last
|
72
|
+
# Person.last # returns the last object fetched by SELECT * FROM people
|
73
|
+
# Person.where(["user_name = ?", user_name]).last
|
74
|
+
# Person.order("created_on DESC").offset(5).last
|
75
|
+
#
|
76
|
+
# # find all
|
77
|
+
# Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
|
78
|
+
# Person.where(["category IN (?)", categories]).limit(50).all
|
79
|
+
# Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
|
80
|
+
# Person.offset(10).limit(10).all
|
81
|
+
# Person.includes([:account, :friends]).all
|
82
|
+
# Person.group("category").all
|
83
|
+
#
|
84
|
+
# Example for find with a lock: Imagine two concurrent transactions:
|
85
|
+
# each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
|
86
|
+
# in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
|
87
|
+
# transaction has to wait until the first is finished; we get the
|
88
|
+
# expected <tt>person.visits == 4</tt>.
|
89
|
+
#
|
90
|
+
# Person.transaction do
|
91
|
+
# person = Person.lock(true).find(1)
|
92
|
+
# person.visits += 1
|
93
|
+
# person.save!
|
94
|
+
# end
|
95
|
+
def find(*args)
|
96
|
+
return to_a.find { |*block_args| yield(*block_args) } if block_given?
|
97
|
+
|
98
|
+
options = args.extract_options!
|
99
|
+
|
100
|
+
if options.present?
|
101
|
+
apply_finder_options(options).find(*args)
|
102
|
+
else
|
103
|
+
case args.first
|
104
|
+
when :first, :last, :all
|
105
|
+
send(args.first)
|
106
|
+
else
|
107
|
+
find_with_ids(*args)
|
108
|
+
end
|
109
|
+
end
|
110
|
+
end
|
111
|
+
|
112
|
+
# A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
|
113
|
+
# same arguments to this method as you can to <tt>find(:first)</tt>.
|
114
|
+
def first(*args)
|
115
|
+
if args.any?
|
116
|
+
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
|
117
|
+
limit(*args).to_a
|
118
|
+
else
|
119
|
+
apply_finder_options(args.first).first
|
120
|
+
end
|
121
|
+
else
|
122
|
+
find_first
|
123
|
+
end
|
124
|
+
end
|
125
|
+
|
126
|
+
# Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
|
127
|
+
# is found. Note that <tt>first!</tt> accepts no arguments.
|
128
|
+
def first!
|
129
|
+
first or raise RecordNotFound
|
130
|
+
end
|
131
|
+
|
132
|
+
# A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
|
133
|
+
# same arguments to this method as you can to <tt>find(:last)</tt>.
|
134
|
+
def last(*args)
|
135
|
+
if args.any?
|
136
|
+
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
|
137
|
+
if order_values.empty?
|
138
|
+
order("#{primary_key} DESC").limit(*args).reverse
|
139
|
+
else
|
140
|
+
to_a.last(*args)
|
141
|
+
end
|
142
|
+
else
|
143
|
+
apply_finder_options(args.first).last
|
144
|
+
end
|
145
|
+
else
|
146
|
+
find_last
|
147
|
+
end
|
148
|
+
end
|
149
|
+
|
150
|
+
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
|
151
|
+
# is found. Note that <tt>last!</tt> accepts no arguments.
|
152
|
+
def last!
|
153
|
+
last or raise RecordNotFound
|
154
|
+
end
|
155
|
+
|
156
|
+
# A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
|
157
|
+
# same arguments to this method as you can to <tt>find(:all)</tt>.
|
158
|
+
def all(*args)
|
159
|
+
args.any? ? apply_finder_options(args.first).to_a : to_a
|
160
|
+
end
|
161
|
+
|
162
|
+
# Returns true if a record exists in the table that matches the +id+ or
|
163
|
+
# conditions given, or false otherwise. The argument can take five forms:
|
164
|
+
#
|
165
|
+
# * Integer - Finds the record with this primary key.
|
166
|
+
# * String - Finds the record with a primary key corresponding to this
|
167
|
+
# string (such as <tt>'5'</tt>).
|
168
|
+
# * Array - Finds the record that matches these +find+-style conditions
|
169
|
+
# (such as <tt>['color = ?', 'red']</tt>).
|
170
|
+
# * Hash - Finds the record that matches these +find+-style conditions
|
171
|
+
# (such as <tt>{:color => 'red'}</tt>).
|
172
|
+
# * No args - Returns false if the table is empty, true otherwise.
|
173
|
+
#
|
174
|
+
# For more information about specifying conditions as a Hash or Array,
|
175
|
+
# see the Conditions section in the introduction to ActiveRecord::Base.
|
176
|
+
#
|
177
|
+
# Note: You can't pass in a condition as a string (like <tt>name =
|
178
|
+
# 'Jamie'</tt>), since it would be sanitized and then queried against
|
179
|
+
# the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
|
180
|
+
#
|
181
|
+
# ==== Examples
|
182
|
+
# Person.exists?(5)
|
183
|
+
# Person.exists?('5')
|
184
|
+
# Person.exists?(:name => "David")
|
185
|
+
# Person.exists?(['name LIKE ?', "%#{query}%"])
|
186
|
+
# Person.exists?
|
187
|
+
def exists?(id = false)
|
188
|
+
return false if id.nil?
|
189
|
+
|
190
|
+
id = id.id if ActiveRecord::Base === id
|
191
|
+
|
192
|
+
join_dependency = construct_join_dependency_for_association_find
|
193
|
+
relation = construct_relation_for_association_find(join_dependency)
|
194
|
+
relation = relation.except(:select, :order).select("1").limit(1)
|
195
|
+
|
196
|
+
case id
|
197
|
+
when Array, Hash
|
198
|
+
relation = relation.where(id)
|
199
|
+
else
|
200
|
+
relation = relation.where(table[primary_key].eq(id)) if id
|
201
|
+
end
|
202
|
+
|
203
|
+
connection.select_value(relation, "#{name} Exists") ? true : false
|
204
|
+
end
|
205
|
+
|
206
|
+
protected
|
207
|
+
|
208
|
+
def find_with_associations
|
209
|
+
join_dependency = construct_join_dependency_for_association_find
|
210
|
+
relation = construct_relation_for_association_find(join_dependency)
|
211
|
+
rows = connection.select_all(relation, 'SQL', relation.bind_values)
|
212
|
+
join_dependency.instantiate(rows)
|
213
|
+
rescue ThrowResult
|
214
|
+
[]
|
215
|
+
end
|
216
|
+
|
217
|
+
def construct_join_dependency_for_association_find
|
218
|
+
including = (@eager_load_values + @includes_values).uniq
|
219
|
+
ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
|
220
|
+
end
|
221
|
+
|
222
|
+
def construct_relation_for_association_calculations
|
223
|
+
including = (@eager_load_values + @includes_values).uniq
|
224
|
+
join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
|
225
|
+
relation = except(:includes, :eager_load, :preload)
|
226
|
+
apply_join_dependency(relation, join_dependency)
|
227
|
+
end
|
228
|
+
|
229
|
+
def construct_relation_for_association_find(join_dependency)
|
230
|
+
relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
|
231
|
+
apply_join_dependency(relation, join_dependency)
|
232
|
+
end
|
233
|
+
|
234
|
+
def apply_join_dependency(relation, join_dependency)
|
235
|
+
join_dependency.join_associations.each do |association|
|
236
|
+
relation = association.join_relation(relation)
|
237
|
+
end
|
238
|
+
|
239
|
+
limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
|
240
|
+
|
241
|
+
if !limitable_reflections && relation.limit_value
|
242
|
+
limited_id_condition = construct_limited_ids_condition(relation.except(:select))
|
243
|
+
relation = relation.where(limited_id_condition)
|
244
|
+
end
|
245
|
+
|
246
|
+
relation = relation.except(:limit, :offset) unless limitable_reflections
|
247
|
+
|
248
|
+
relation
|
249
|
+
end
|
250
|
+
|
251
|
+
def construct_limited_ids_condition(relation)
|
252
|
+
orders = relation.order_values.map { |val| val.presence }.compact
|
253
|
+
values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
|
254
|
+
|
255
|
+
relation = relation.dup
|
256
|
+
|
257
|
+
ids_array = relation.select(values).collect {|row| row[primary_key]}
|
258
|
+
ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
|
259
|
+
end
|
260
|
+
|
261
|
+
def find_by_attributes(match, attributes, *args)
|
262
|
+
conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
|
263
|
+
result = where(conditions).send(match.finder)
|
264
|
+
|
265
|
+
if match.bang? && result.blank?
|
266
|
+
raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
|
267
|
+
else
|
268
|
+
yield(result) if block_given?
|
269
|
+
result
|
270
|
+
end
|
271
|
+
end
|
272
|
+
|
273
|
+
def find_or_instantiator_by_attributes(match, attributes, *args)
|
274
|
+
options = args.size > 1 && args.last(2).all?{ |a| a.is_a?(Hash) } ? args.extract_options! : {}
|
275
|
+
protected_attributes_for_create, unprotected_attributes_for_create = {}, {}
|
276
|
+
args.each_with_index do |arg, i|
|
277
|
+
if arg.is_a?(Hash)
|
278
|
+
protected_attributes_for_create = args[i].with_indifferent_access
|
279
|
+
else
|
280
|
+
unprotected_attributes_for_create[attributes[i]] = args[i]
|
281
|
+
end
|
282
|
+
end
|
283
|
+
|
284
|
+
conditions = (protected_attributes_for_create.merge(unprotected_attributes_for_create)).slice(*attributes).symbolize_keys
|
285
|
+
|
286
|
+
record = where(conditions).first
|
287
|
+
|
288
|
+
unless record
|
289
|
+
record = @klass.new(protected_attributes_for_create, options) do |r|
|
290
|
+
r.assign_attributes(unprotected_attributes_for_create, :without_protection => true)
|
291
|
+
end
|
292
|
+
yield(record) if block_given?
|
293
|
+
record.save if match.instantiator == :create
|
294
|
+
end
|
295
|
+
|
296
|
+
record
|
297
|
+
end
|
298
|
+
|
299
|
+
def find_with_ids(*ids)
|
300
|
+
return to_a.find { |*block_args| yield(*block_args) } if block_given?
|
301
|
+
|
302
|
+
expects_array = ids.first.kind_of?(Array)
|
303
|
+
return ids.first if expects_array && ids.first.empty?
|
304
|
+
|
305
|
+
ids = ids.flatten.compact.uniq
|
306
|
+
|
307
|
+
case ids.size
|
308
|
+
when 0
|
309
|
+
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
|
310
|
+
when 1
|
311
|
+
result = find_one(ids.first)
|
312
|
+
expects_array ? [ result ] : result
|
313
|
+
else
|
314
|
+
find_some(ids)
|
315
|
+
end
|
316
|
+
end
|
317
|
+
|
318
|
+
def find_one(id)
|
319
|
+
id = id.id if ActiveRecord::Base === id
|
320
|
+
|
321
|
+
if IdentityMap.enabled? && where_values.blank? &&
|
322
|
+
limit_value.blank? && order_values.blank? &&
|
323
|
+
includes_values.blank? && preload_values.blank? &&
|
324
|
+
readonly_value.nil? && joins_values.blank? &&
|
325
|
+
!@klass.locking_enabled? &&
|
326
|
+
record = IdentityMap.get(@klass, id)
|
327
|
+
return record
|
328
|
+
end
|
329
|
+
|
330
|
+
column = columns_hash[primary_key]
|
331
|
+
|
332
|
+
substitute = connection.substitute_at(column, @bind_values.length)
|
333
|
+
relation = where(table[primary_key].eq(substitute))
|
334
|
+
relation.bind_values = [[column, id]]
|
335
|
+
record = relation.first
|
336
|
+
|
337
|
+
unless record
|
338
|
+
conditions = arel.where_sql
|
339
|
+
conditions = " [#{conditions}]" if conditions
|
340
|
+
raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
|
341
|
+
end
|
342
|
+
|
343
|
+
record
|
344
|
+
end
|
345
|
+
|
346
|
+
def find_some(ids)
|
347
|
+
result = where(table[primary_key].in(ids)).all
|
348
|
+
|
349
|
+
expected_size =
|
350
|
+
if @limit_value && ids.size > @limit_value
|
351
|
+
@limit_value
|
352
|
+
else
|
353
|
+
ids.size
|
354
|
+
end
|
355
|
+
|
356
|
+
# 11 ids with limit 3, offset 9 should give 2 results.
|
357
|
+
if @offset_value && (ids.size - @offset_value < expected_size)
|
358
|
+
expected_size = ids.size - @offset_value
|
359
|
+
end
|
360
|
+
|
361
|
+
if result.size == expected_size
|
362
|
+
result
|
363
|
+
else
|
364
|
+
conditions = arel.where_sql
|
365
|
+
conditions = " [#{conditions}]" if conditions
|
366
|
+
|
367
|
+
error = "Couldn't find all #{@klass.name.pluralize} with IDs "
|
368
|
+
error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
|
369
|
+
raise RecordNotFound, error
|
370
|
+
end
|
371
|
+
end
|
372
|
+
|
373
|
+
def find_first
|
374
|
+
if loaded?
|
375
|
+
@records.first
|
376
|
+
else
|
377
|
+
@first ||= limit(1).to_a[0]
|
378
|
+
end
|
379
|
+
end
|
380
|
+
|
381
|
+
def find_last
|
382
|
+
if loaded?
|
383
|
+
@records.last
|
384
|
+
else
|
385
|
+
@last ||=
|
386
|
+
if offset_value || limit_value
|
387
|
+
to_a.last
|
388
|
+
else
|
389
|
+
reverse_order.limit(1).to_a[0]
|
390
|
+
end
|
391
|
+
end
|
392
|
+
end
|
393
|
+
|
394
|
+
def using_limitable_reflections?(reflections)
|
395
|
+
reflections.none? { |r| r.collection? }
|
396
|
+
end
|
397
|
+
end
|
398
|
+
end
|
@@ -0,0 +1,58 @@
|
|
1
|
+
module ActiveRecord
|
2
|
+
class PredicateBuilder # :nodoc:
|
3
|
+
def self.build_from_hash(engine, attributes, default_table)
|
4
|
+
predicates = attributes.map do |column, value|
|
5
|
+
table = default_table
|
6
|
+
|
7
|
+
if value.is_a?(Hash)
|
8
|
+
table = Arel::Table.new(column, engine)
|
9
|
+
build_from_hash(engine, value, table)
|
10
|
+
else
|
11
|
+
column = column.to_s
|
12
|
+
|
13
|
+
if column.include?('.')
|
14
|
+
table_name, column = column.split('.', 2)
|
15
|
+
table = Arel::Table.new(table_name, engine)
|
16
|
+
end
|
17
|
+
|
18
|
+
attribute = table[column.to_sym]
|
19
|
+
|
20
|
+
case value
|
21
|
+
when ActiveRecord::Relation
|
22
|
+
value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty?
|
23
|
+
attribute.in(value.arel.ast)
|
24
|
+
when Array, ActiveRecord::Associations::CollectionProxy
|
25
|
+
values = value.to_a.map {|x| x.is_a?(ActiveRecord::Base) ? x.id : x}
|
26
|
+
ranges, values = values.partition {|v| v.is_a?(Range) || v.is_a?(Arel::Relation)}
|
27
|
+
|
28
|
+
array_predicates = ranges.map {|range| attribute.in(range)}
|
29
|
+
|
30
|
+
if values.include?(nil)
|
31
|
+
values = values.compact
|
32
|
+
if values.empty?
|
33
|
+
array_predicates << attribute.eq(nil)
|
34
|
+
else
|
35
|
+
array_predicates << attribute.in(values.compact).or(attribute.eq(nil))
|
36
|
+
end
|
37
|
+
else
|
38
|
+
array_predicates << attribute.in(values)
|
39
|
+
end
|
40
|
+
|
41
|
+
array_predicates.inject {|composite, predicate| composite.or(predicate)}
|
42
|
+
when Range, Arel::Relation
|
43
|
+
attribute.in(value)
|
44
|
+
when ActiveRecord::Base
|
45
|
+
attribute.eq(value.id)
|
46
|
+
when Class
|
47
|
+
# FIXME: I think we need to deprecate this behavior
|
48
|
+
attribute.eq(value.name)
|
49
|
+
else
|
50
|
+
attribute.eq(value)
|
51
|
+
end
|
52
|
+
end
|
53
|
+
end
|
54
|
+
|
55
|
+
predicates.flatten
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|