activerecord_csi 2.3.5.p6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- data/CHANGELOG +5858 -0
- data/README +351 -0
- data/RUNNING_UNIT_TESTS +36 -0
- data/Rakefile +270 -0
- data/examples/associations.png +0 -0
- data/examples/performance.rb +162 -0
- data/install.rb +30 -0
- data/lib/active_record/aggregations.rb +261 -0
- data/lib/active_record/association_preload.rb +389 -0
- data/lib/active_record/associations/association_collection.rb +475 -0
- data/lib/active_record/associations/association_proxy.rb +278 -0
- data/lib/active_record/associations/belongs_to_association.rb +76 -0
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +53 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +143 -0
- data/lib/active_record/associations/has_many_association.rb +122 -0
- data/lib/active_record/associations/has_many_through_association.rb +266 -0
- data/lib/active_record/associations/has_one_association.rb +133 -0
- data/lib/active_record/associations/has_one_through_association.rb +37 -0
- data/lib/active_record/associations.rb +2241 -0
- data/lib/active_record/attribute_methods.rb +388 -0
- data/lib/active_record/autosave_association.rb +364 -0
- data/lib/active_record/base.rb +3171 -0
- data/lib/active_record/batches.rb +81 -0
- data/lib/active_record/calculations.rb +311 -0
- data/lib/active_record/callbacks.rb +360 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +371 -0
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +139 -0
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +289 -0
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +94 -0
- data/lib/active_record/connection_adapters/abstract/quoting.rb +69 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +722 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +434 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +241 -0
- data/lib/active_record/connection_adapters/mysql_adapter.rb +630 -0
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +1113 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +34 -0
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +453 -0
- data/lib/active_record/dirty.rb +183 -0
- data/lib/active_record/dynamic_finder_match.rb +41 -0
- data/lib/active_record/dynamic_scope_match.rb +25 -0
- data/lib/active_record/fixtures.rb +996 -0
- data/lib/active_record/i18n_interpolation_deprecation.rb +26 -0
- data/lib/active_record/locale/en.yml +58 -0
- data/lib/active_record/locking/optimistic.rb +148 -0
- data/lib/active_record/locking/pessimistic.rb +55 -0
- data/lib/active_record/migration.rb +566 -0
- data/lib/active_record/named_scope.rb +192 -0
- data/lib/active_record/nested_attributes.rb +392 -0
- data/lib/active_record/observer.rb +197 -0
- data/lib/active_record/query_cache.rb +33 -0
- data/lib/active_record/reflection.rb +320 -0
- data/lib/active_record/schema.rb +51 -0
- data/lib/active_record/schema_dumper.rb +182 -0
- data/lib/active_record/serialization.rb +101 -0
- data/lib/active_record/serializers/json_serializer.rb +91 -0
- data/lib/active_record/serializers/xml_serializer.rb +357 -0
- data/lib/active_record/session_store.rb +326 -0
- data/lib/active_record/test_case.rb +66 -0
- data/lib/active_record/timestamp.rb +71 -0
- data/lib/active_record/transactions.rb +235 -0
- data/lib/active_record/validations.rb +1135 -0
- data/lib/active_record/version.rb +9 -0
- data/lib/active_record.rb +84 -0
- data/lib/activerecord.rb +2 -0
- data/test/assets/example.log +1 -0
- data/test/assets/flowers.jpg +0 -0
- data/test/cases/aaa_create_tables_test.rb +24 -0
- data/test/cases/active_schema_test_mysql.rb +100 -0
- data/test/cases/active_schema_test_postgresql.rb +24 -0
- data/test/cases/adapter_test.rb +145 -0
- data/test/cases/aggregations_test.rb +167 -0
- data/test/cases/ar_schema_test.rb +32 -0
- data/test/cases/associations/belongs_to_associations_test.rb +425 -0
- data/test/cases/associations/callbacks_test.rb +161 -0
- data/test/cases/associations/cascaded_eager_loading_test.rb +131 -0
- data/test/cases/associations/eager_load_includes_full_sti_class_test.rb +36 -0
- data/test/cases/associations/eager_load_nested_include_test.rb +130 -0
- data/test/cases/associations/eager_singularization_test.rb +145 -0
- data/test/cases/associations/eager_test.rb +834 -0
- data/test/cases/associations/extension_test.rb +62 -0
- data/test/cases/associations/habtm_join_table_test.rb +56 -0
- data/test/cases/associations/has_and_belongs_to_many_associations_test.rb +822 -0
- data/test/cases/associations/has_many_associations_test.rb +1134 -0
- data/test/cases/associations/has_many_through_associations_test.rb +346 -0
- data/test/cases/associations/has_one_associations_test.rb +330 -0
- data/test/cases/associations/has_one_through_associations_test.rb +209 -0
- data/test/cases/associations/inner_join_association_test.rb +93 -0
- data/test/cases/associations/join_model_test.rb +712 -0
- data/test/cases/associations_test.rb +262 -0
- data/test/cases/attribute_methods_test.rb +305 -0
- data/test/cases/autosave_association_test.rb +1142 -0
- data/test/cases/base_test.rb +2154 -0
- data/test/cases/batches_test.rb +61 -0
- data/test/cases/binary_test.rb +30 -0
- data/test/cases/calculations_test.rb +348 -0
- data/test/cases/callbacks_observers_test.rb +38 -0
- data/test/cases/callbacks_test.rb +438 -0
- data/test/cases/class_inheritable_attributes_test.rb +32 -0
- data/test/cases/column_alias_test.rb +17 -0
- data/test/cases/column_definition_test.rb +70 -0
- data/test/cases/connection_pool_test.rb +25 -0
- data/test/cases/connection_test_firebird.rb +8 -0
- data/test/cases/connection_test_mysql.rb +64 -0
- data/test/cases/copy_table_test_sqlite.rb +80 -0
- data/test/cases/database_statements_test.rb +12 -0
- data/test/cases/datatype_test_postgresql.rb +204 -0
- data/test/cases/date_time_test.rb +37 -0
- data/test/cases/default_test_firebird.rb +16 -0
- data/test/cases/defaults_test.rb +111 -0
- data/test/cases/deprecated_finder_test.rb +30 -0
- data/test/cases/dirty_test.rb +316 -0
- data/test/cases/finder_respond_to_test.rb +76 -0
- data/test/cases/finder_test.rb +1066 -0
- data/test/cases/fixtures_test.rb +656 -0
- data/test/cases/helper.rb +68 -0
- data/test/cases/i18n_test.rb +46 -0
- data/test/cases/inheritance_test.rb +262 -0
- data/test/cases/invalid_date_test.rb +24 -0
- data/test/cases/json_serialization_test.rb +205 -0
- data/test/cases/lifecycle_test.rb +193 -0
- data/test/cases/locking_test.rb +304 -0
- data/test/cases/method_scoping_test.rb +704 -0
- data/test/cases/migration_test.rb +1523 -0
- data/test/cases/migration_test_firebird.rb +124 -0
- data/test/cases/mixin_test.rb +96 -0
- data/test/cases/modules_test.rb +81 -0
- data/test/cases/multiple_db_test.rb +85 -0
- data/test/cases/named_scope_test.rb +361 -0
- data/test/cases/nested_attributes_test.rb +581 -0
- data/test/cases/pk_test.rb +119 -0
- data/test/cases/pooled_connections_test.rb +103 -0
- data/test/cases/query_cache_test.rb +123 -0
- data/test/cases/readonly_test.rb +107 -0
- data/test/cases/reflection_test.rb +194 -0
- data/test/cases/reload_models_test.rb +22 -0
- data/test/cases/repair_helper.rb +50 -0
- data/test/cases/reserved_word_test_mysql.rb +176 -0
- data/test/cases/sanitize_test.rb +25 -0
- data/test/cases/schema_authorization_test_postgresql.rb +75 -0
- data/test/cases/schema_dumper_test.rb +211 -0
- data/test/cases/schema_test_postgresql.rb +178 -0
- data/test/cases/serialization_test.rb +47 -0
- data/test/cases/synonym_test_oracle.rb +17 -0
- data/test/cases/timestamp_test.rb +75 -0
- data/test/cases/transactions_test.rb +522 -0
- data/test/cases/unconnected_test.rb +32 -0
- data/test/cases/validations_i18n_test.rb +955 -0
- data/test/cases/validations_test.rb +1640 -0
- data/test/cases/xml_serialization_test.rb +240 -0
- data/test/config.rb +5 -0
- data/test/connections/jdbc_jdbcderby/connection.rb +18 -0
- data/test/connections/jdbc_jdbch2/connection.rb +18 -0
- data/test/connections/jdbc_jdbchsqldb/connection.rb +18 -0
- data/test/connections/jdbc_jdbcmysql/connection.rb +26 -0
- data/test/connections/jdbc_jdbcpostgresql/connection.rb +26 -0
- data/test/connections/jdbc_jdbcsqlite3/connection.rb +25 -0
- data/test/connections/native_db2/connection.rb +25 -0
- data/test/connections/native_firebird/connection.rb +26 -0
- data/test/connections/native_frontbase/connection.rb +27 -0
- data/test/connections/native_mysql/connection.rb +25 -0
- data/test/connections/native_openbase/connection.rb +21 -0
- data/test/connections/native_oracle/connection.rb +27 -0
- data/test/connections/native_postgresql/connection.rb +25 -0
- data/test/connections/native_sqlite/connection.rb +25 -0
- data/test/connections/native_sqlite3/connection.rb +25 -0
- data/test/connections/native_sqlite3/in_memory_connection.rb +18 -0
- data/test/connections/native_sybase/connection.rb +23 -0
- data/test/fixtures/accounts.yml +29 -0
- data/test/fixtures/all/developers.yml +0 -0
- data/test/fixtures/all/people.csv +0 -0
- data/test/fixtures/all/tasks.yml +0 -0
- data/test/fixtures/author_addresses.yml +5 -0
- data/test/fixtures/author_favorites.yml +4 -0
- data/test/fixtures/authors.yml +9 -0
- data/test/fixtures/binaries.yml +132 -0
- data/test/fixtures/books.yml +7 -0
- data/test/fixtures/categories/special_categories.yml +9 -0
- data/test/fixtures/categories/subsubdir/arbitrary_filename.yml +4 -0
- data/test/fixtures/categories.yml +14 -0
- data/test/fixtures/categories_ordered.yml +7 -0
- data/test/fixtures/categories_posts.yml +23 -0
- data/test/fixtures/categorizations.yml +17 -0
- data/test/fixtures/clubs.yml +6 -0
- data/test/fixtures/comments.yml +59 -0
- data/test/fixtures/companies.yml +56 -0
- data/test/fixtures/computers.yml +4 -0
- data/test/fixtures/courses.yml +7 -0
- data/test/fixtures/customers.yml +26 -0
- data/test/fixtures/developers.yml +21 -0
- data/test/fixtures/developers_projects.yml +17 -0
- data/test/fixtures/edges.yml +6 -0
- data/test/fixtures/entrants.yml +14 -0
- data/test/fixtures/fixture_database.sqlite3 +0 -0
- data/test/fixtures/fixture_database_2.sqlite3 +0 -0
- data/test/fixtures/fk_test_has_fk.yml +3 -0
- data/test/fixtures/fk_test_has_pk.yml +2 -0
- data/test/fixtures/funny_jokes.yml +10 -0
- data/test/fixtures/items.yml +4 -0
- data/test/fixtures/jobs.yml +7 -0
- data/test/fixtures/legacy_things.yml +3 -0
- data/test/fixtures/mateys.yml +4 -0
- data/test/fixtures/member_types.yml +6 -0
- data/test/fixtures/members.yml +6 -0
- data/test/fixtures/memberships.yml +20 -0
- data/test/fixtures/minimalistics.yml +2 -0
- data/test/fixtures/mixed_case_monkeys.yml +6 -0
- data/test/fixtures/mixins.yml +29 -0
- data/test/fixtures/movies.yml +7 -0
- data/test/fixtures/naked/csv/accounts.csv +1 -0
- data/test/fixtures/naked/yml/accounts.yml +1 -0
- data/test/fixtures/naked/yml/companies.yml +1 -0
- data/test/fixtures/naked/yml/courses.yml +1 -0
- data/test/fixtures/organizations.yml +5 -0
- data/test/fixtures/owners.yml +7 -0
- data/test/fixtures/parrots.yml +27 -0
- data/test/fixtures/parrots_pirates.yml +7 -0
- data/test/fixtures/people.yml +15 -0
- data/test/fixtures/pets.yml +14 -0
- data/test/fixtures/pirates.yml +9 -0
- data/test/fixtures/posts.yml +52 -0
- data/test/fixtures/price_estimates.yml +7 -0
- data/test/fixtures/projects.yml +7 -0
- data/test/fixtures/readers.yml +9 -0
- data/test/fixtures/references.yml +17 -0
- data/test/fixtures/reserved_words/distinct.yml +5 -0
- data/test/fixtures/reserved_words/distincts_selects.yml +11 -0
- data/test/fixtures/reserved_words/group.yml +14 -0
- data/test/fixtures/reserved_words/select.yml +8 -0
- data/test/fixtures/reserved_words/values.yml +7 -0
- data/test/fixtures/ships.yml +5 -0
- data/test/fixtures/sponsors.yml +9 -0
- data/test/fixtures/subscribers.yml +7 -0
- data/test/fixtures/subscriptions.yml +12 -0
- data/test/fixtures/taggings.yml +28 -0
- data/test/fixtures/tags.yml +7 -0
- data/test/fixtures/tasks.yml +7 -0
- data/test/fixtures/topics.yml +42 -0
- data/test/fixtures/toys.yml +4 -0
- data/test/fixtures/treasures.yml +10 -0
- data/test/fixtures/vertices.yml +4 -0
- data/test/fixtures/warehouse-things.yml +3 -0
- data/test/migrations/broken/100_migration_that_raises_exception.rb +10 -0
- data/test/migrations/decimal/1_give_me_big_numbers.rb +15 -0
- data/test/migrations/duplicate/1_people_have_last_names.rb +9 -0
- data/test/migrations/duplicate/2_we_need_reminders.rb +12 -0
- data/test/migrations/duplicate/3_foo.rb +7 -0
- data/test/migrations/duplicate/3_innocent_jointable.rb +12 -0
- data/test/migrations/duplicate_names/20080507052938_chunky.rb +7 -0
- data/test/migrations/duplicate_names/20080507053028_chunky.rb +7 -0
- data/test/migrations/interleaved/pass_1/3_innocent_jointable.rb +12 -0
- data/test/migrations/interleaved/pass_2/1_people_have_last_names.rb +9 -0
- data/test/migrations/interleaved/pass_2/3_innocent_jointable.rb +12 -0
- data/test/migrations/interleaved/pass_3/1_people_have_last_names.rb +9 -0
- data/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb +8 -0
- data/test/migrations/interleaved/pass_3/3_innocent_jointable.rb +12 -0
- data/test/migrations/missing/1000_people_have_middle_names.rb +9 -0
- data/test/migrations/missing/1_people_have_last_names.rb +9 -0
- data/test/migrations/missing/3_we_need_reminders.rb +12 -0
- data/test/migrations/missing/4_innocent_jointable.rb +12 -0
- data/test/migrations/valid/1_people_have_last_names.rb +9 -0
- data/test/migrations/valid/2_we_need_reminders.rb +12 -0
- data/test/migrations/valid/3_innocent_jointable.rb +12 -0
- data/test/models/author.rb +146 -0
- data/test/models/auto_id.rb +4 -0
- data/test/models/binary.rb +2 -0
- data/test/models/bird.rb +3 -0
- data/test/models/book.rb +4 -0
- data/test/models/categorization.rb +5 -0
- data/test/models/category.rb +34 -0
- data/test/models/citation.rb +6 -0
- data/test/models/club.rb +13 -0
- data/test/models/column_name.rb +3 -0
- data/test/models/comment.rb +29 -0
- data/test/models/company.rb +171 -0
- data/test/models/company_in_module.rb +61 -0
- data/test/models/computer.rb +3 -0
- data/test/models/contact.rb +16 -0
- data/test/models/contract.rb +5 -0
- data/test/models/course.rb +3 -0
- data/test/models/customer.rb +73 -0
- data/test/models/default.rb +2 -0
- data/test/models/developer.rb +101 -0
- data/test/models/edge.rb +5 -0
- data/test/models/entrant.rb +3 -0
- data/test/models/essay.rb +3 -0
- data/test/models/event.rb +3 -0
- data/test/models/guid.rb +2 -0
- data/test/models/item.rb +7 -0
- data/test/models/job.rb +5 -0
- data/test/models/joke.rb +3 -0
- data/test/models/keyboard.rb +3 -0
- data/test/models/legacy_thing.rb +3 -0
- data/test/models/matey.rb +4 -0
- data/test/models/member.rb +12 -0
- data/test/models/member_detail.rb +5 -0
- data/test/models/member_type.rb +3 -0
- data/test/models/membership.rb +9 -0
- data/test/models/minimalistic.rb +2 -0
- data/test/models/mixed_case_monkey.rb +3 -0
- data/test/models/movie.rb +5 -0
- data/test/models/order.rb +4 -0
- data/test/models/organization.rb +6 -0
- data/test/models/owner.rb +5 -0
- data/test/models/parrot.rb +16 -0
- data/test/models/person.rb +16 -0
- data/test/models/pet.rb +5 -0
- data/test/models/pirate.rb +70 -0
- data/test/models/post.rb +100 -0
- data/test/models/price_estimate.rb +3 -0
- data/test/models/project.rb +30 -0
- data/test/models/reader.rb +4 -0
- data/test/models/reference.rb +4 -0
- data/test/models/reply.rb +46 -0
- data/test/models/ship.rb +10 -0
- data/test/models/ship_part.rb +5 -0
- data/test/models/sponsor.rb +4 -0
- data/test/models/subject.rb +4 -0
- data/test/models/subscriber.rb +8 -0
- data/test/models/subscription.rb +4 -0
- data/test/models/tag.rb +7 -0
- data/test/models/tagging.rb +10 -0
- data/test/models/task.rb +3 -0
- data/test/models/topic.rb +80 -0
- data/test/models/toy.rb +6 -0
- data/test/models/treasure.rb +8 -0
- data/test/models/vertex.rb +9 -0
- data/test/models/warehouse_thing.rb +5 -0
- data/test/schema/mysql_specific_schema.rb +24 -0
- data/test/schema/postgresql_specific_schema.rb +114 -0
- data/test/schema/schema.rb +493 -0
- data/test/schema/schema2.rb +6 -0
- data/test/schema/sqlite_specific_schema.rb +25 -0
- metadata +420 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
module ActiveRecord
|
|
2
|
+
module Batches # :nodoc:
|
|
3
|
+
def self.included(base)
|
|
4
|
+
base.extend(ClassMethods)
|
|
5
|
+
end
|
|
6
|
+
|
|
7
|
+
# When processing large numbers of records, it's often a good idea to do
|
|
8
|
+
# so in batches to prevent memory ballooning.
|
|
9
|
+
module ClassMethods
|
|
10
|
+
# Yields each record that was found by the find +options+. The find is
|
|
11
|
+
# performed by find_in_batches with a batch size of 1000 (or as
|
|
12
|
+
# specified by the <tt>:batch_size</tt> option).
|
|
13
|
+
#
|
|
14
|
+
# Example:
|
|
15
|
+
#
|
|
16
|
+
# Person.find_each(:conditions => "age > 21") do |person|
|
|
17
|
+
# person.party_all_night!
|
|
18
|
+
# end
|
|
19
|
+
#
|
|
20
|
+
# Note: This method is only intended to use for batch processing of
|
|
21
|
+
# large amounts of records that wouldn't fit in memory all at once. If
|
|
22
|
+
# you just need to loop over less than 1000 records, it's probably
|
|
23
|
+
# better just to use the regular find methods.
|
|
24
|
+
def find_each(options = {})
|
|
25
|
+
find_in_batches(options) do |records|
|
|
26
|
+
records.each { |record| yield record }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
self
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Yields each batch of records that was found by the find +options+ as
|
|
33
|
+
# an array. The size of each batch is set by the <tt>:batch_size</tt>
|
|
34
|
+
# option; the default is 1000.
|
|
35
|
+
#
|
|
36
|
+
# You can control the starting point for the batch processing by
|
|
37
|
+
# supplying the <tt>:start</tt> option. This is especially useful if you
|
|
38
|
+
# want multiple workers dealing with the same processing queue. You can
|
|
39
|
+
# make worker 1 handle all the records between id 0 and 10,000 and
|
|
40
|
+
# worker 2 handle from 10,000 and beyond (by setting the <tt>:start</tt>
|
|
41
|
+
# option on that worker).
|
|
42
|
+
#
|
|
43
|
+
# It's not possible to set the order. That is automatically set to
|
|
44
|
+
# ascending on the primary key ("id ASC") to make the batch ordering
|
|
45
|
+
# work. This also mean that this method only works with integer-based
|
|
46
|
+
# primary keys. You can't set the limit either, that's used to control
|
|
47
|
+
# the the batch sizes.
|
|
48
|
+
#
|
|
49
|
+
# Example:
|
|
50
|
+
#
|
|
51
|
+
# Person.find_in_batches(:conditions => "age > 21") do |group|
|
|
52
|
+
# sleep(50) # Make sure it doesn't get too crowded in there!
|
|
53
|
+
# group.each { |person| person.party_all_night! }
|
|
54
|
+
# end
|
|
55
|
+
def find_in_batches(options = {})
|
|
56
|
+
raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order]
|
|
57
|
+
raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit]
|
|
58
|
+
|
|
59
|
+
start = options.delete(:start).to_i
|
|
60
|
+
batch_size = options.delete(:batch_size) || 1000
|
|
61
|
+
|
|
62
|
+
with_scope(:find => options.merge(:order => batch_order, :limit => batch_size)) do
|
|
63
|
+
records = find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ])
|
|
64
|
+
|
|
65
|
+
while records.any?
|
|
66
|
+
yield records
|
|
67
|
+
|
|
68
|
+
break if records.size < batch_size
|
|
69
|
+
records = find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", records.last.id ])
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
def batch_order
|
|
77
|
+
"#{table_name}.#{primary_key} ASC"
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
module ActiveRecord
|
|
2
|
+
module Calculations #:nodoc:
|
|
3
|
+
CALCULATIONS_OPTIONS = [:conditions, :joins, :order, :select, :group, :having, :distinct, :limit, :offset, :include, :from]
|
|
4
|
+
def self.included(base)
|
|
5
|
+
base.extend(ClassMethods)
|
|
6
|
+
end
|
|
7
|
+
|
|
8
|
+
module ClassMethods
|
|
9
|
+
# Count operates using three different approaches.
|
|
10
|
+
#
|
|
11
|
+
# * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
|
|
12
|
+
# * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
|
|
13
|
+
# * Count using options will find the row count matched by the options used.
|
|
14
|
+
#
|
|
15
|
+
# The third approach, count using options, accepts an option hash as the only parameter. The options are:
|
|
16
|
+
#
|
|
17
|
+
# * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
|
|
18
|
+
# * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
|
|
19
|
+
# or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
|
|
20
|
+
# If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
|
|
21
|
+
# Pass <tt>:readonly => false</tt> to override.
|
|
22
|
+
# * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
|
|
23
|
+
# to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
|
|
24
|
+
# See eager loading under Associations.
|
|
25
|
+
# * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
|
|
26
|
+
# * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
|
|
27
|
+
# * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
|
|
28
|
+
# include the joined columns.
|
|
29
|
+
# * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
|
|
30
|
+
# * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
|
|
31
|
+
# of a database view).
|
|
32
|
+
#
|
|
33
|
+
# Examples for counting all:
|
|
34
|
+
# Person.count # returns the total count of all people
|
|
35
|
+
#
|
|
36
|
+
# Examples for counting by column:
|
|
37
|
+
# Person.count(:age) # returns the total count of all people whose age is present in database
|
|
38
|
+
#
|
|
39
|
+
# Examples for count with options:
|
|
40
|
+
# Person.count(:conditions => "age > 26")
|
|
41
|
+
# Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
|
|
42
|
+
# Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins.
|
|
43
|
+
# Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
|
|
44
|
+
# Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
|
|
45
|
+
#
|
|
46
|
+
# Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
|
|
47
|
+
def count(*args)
|
|
48
|
+
calculate(:count, *construct_count_options_from_args(*args))
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Calculates the average value on a given column. The value is returned as
|
|
52
|
+
# a float, or +nil+ if there's no row. See +calculate+ for examples with
|
|
53
|
+
# options.
|
|
54
|
+
#
|
|
55
|
+
# Person.average('age') # => 35.8
|
|
56
|
+
def average(column_name, options = {})
|
|
57
|
+
calculate(:avg, column_name, options)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Calculates the minimum value on a given column. The value is returned
|
|
61
|
+
# with the same data type of the column, or +nil+ if there's no row. See
|
|
62
|
+
# +calculate+ for examples with options.
|
|
63
|
+
#
|
|
64
|
+
# Person.minimum('age') # => 7
|
|
65
|
+
def minimum(column_name, options = {})
|
|
66
|
+
calculate(:min, column_name, options)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Calculates the maximum value on a given column. The value is returned
|
|
70
|
+
# with the same data type of the column, or +nil+ if there's no row. See
|
|
71
|
+
# +calculate+ for examples with options.
|
|
72
|
+
#
|
|
73
|
+
# Person.maximum('age') # => 93
|
|
74
|
+
def maximum(column_name, options = {})
|
|
75
|
+
calculate(:max, column_name, options)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Calculates the sum of values on a given column. The value is returned
|
|
79
|
+
# with the same data type of the column, 0 if there's no row. See
|
|
80
|
+
# +calculate+ for examples with options.
|
|
81
|
+
#
|
|
82
|
+
# Person.sum('age') # => 4562
|
|
83
|
+
def sum(column_name, options = {})
|
|
84
|
+
calculate(:sum, column_name, options)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
|
|
88
|
+
# Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
|
|
89
|
+
#
|
|
90
|
+
# There are two basic forms of output:
|
|
91
|
+
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else.
|
|
92
|
+
# * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name
|
|
93
|
+
# of a belongs_to association.
|
|
94
|
+
#
|
|
95
|
+
# values = Person.maximum(:age, :group => 'last_name')
|
|
96
|
+
# puts values["Drake"]
|
|
97
|
+
# => 43
|
|
98
|
+
#
|
|
99
|
+
# drake = Family.find_by_last_name('Drake')
|
|
100
|
+
# values = Person.maximum(:age, :group => :family) # Person belongs_to :family
|
|
101
|
+
# puts values[drake]
|
|
102
|
+
# => 43
|
|
103
|
+
#
|
|
104
|
+
# values.each do |family, max_age|
|
|
105
|
+
# ...
|
|
106
|
+
# end
|
|
107
|
+
#
|
|
108
|
+
# Options:
|
|
109
|
+
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
|
|
110
|
+
# * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
|
|
111
|
+
# * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
|
|
112
|
+
# The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
|
|
113
|
+
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
|
|
114
|
+
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
|
|
115
|
+
# * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
|
|
116
|
+
# include the joined columns.
|
|
117
|
+
# * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
|
|
118
|
+
#
|
|
119
|
+
# Examples:
|
|
120
|
+
# Person.calculate(:count, :all) # The same as Person.count
|
|
121
|
+
# Person.average(:age) # SELECT AVG(age) FROM people...
|
|
122
|
+
# Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
|
|
123
|
+
# Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
|
|
124
|
+
# Person.sum("2 * age")
|
|
125
|
+
def calculate(operation, column_name, options = {})
|
|
126
|
+
validate_calculation_options(operation, options)
|
|
127
|
+
column_name = options[:select] if options[:select]
|
|
128
|
+
column_name = '*' if column_name == :all
|
|
129
|
+
column = column_for column_name
|
|
130
|
+
catch :invalid_query do
|
|
131
|
+
if options[:group]
|
|
132
|
+
return execute_grouped_calculation(operation, column_name, column, options)
|
|
133
|
+
else
|
|
134
|
+
return execute_simple_calculation(operation, column_name, column, options)
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
0
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
protected
|
|
141
|
+
def construct_count_options_from_args(*args)
|
|
142
|
+
options = {}
|
|
143
|
+
column_name = :all
|
|
144
|
+
|
|
145
|
+
# We need to handle
|
|
146
|
+
# count()
|
|
147
|
+
# count(:column_name=:all)
|
|
148
|
+
# count(options={})
|
|
149
|
+
# count(column_name=:all, options={})
|
|
150
|
+
case args.size
|
|
151
|
+
when 1
|
|
152
|
+
args[0].is_a?(Hash) ? options = args[0] : column_name = args[0]
|
|
153
|
+
when 2
|
|
154
|
+
column_name, options = args
|
|
155
|
+
else
|
|
156
|
+
raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
|
|
157
|
+
end if args.size > 0
|
|
158
|
+
|
|
159
|
+
[column_name, options]
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def construct_calculation_sql(operation, column_name, options) #:nodoc:
|
|
163
|
+
operation = operation.to_s.downcase
|
|
164
|
+
options = options.symbolize_keys
|
|
165
|
+
|
|
166
|
+
scope = scope(:find)
|
|
167
|
+
merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
|
|
168
|
+
aggregate_alias = column_alias_for(operation, column_name)
|
|
169
|
+
column_name = "#{connection.quote_table_name(table_name)}.#{column_name}" if column_names.include?(column_name.to_s)
|
|
170
|
+
|
|
171
|
+
if operation == 'count'
|
|
172
|
+
if merged_includes.any?
|
|
173
|
+
options[:distinct] = true
|
|
174
|
+
column_name = options[:select] || [connection.quote_table_name(table_name), primary_key] * '.'
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
if options[:distinct]
|
|
178
|
+
use_workaround = !connection.supports_count_distinct?
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
if options[:distinct] && column_name.to_s !~ /\s*DISTINCT\s+/i
|
|
183
|
+
distinct = 'DISTINCT '
|
|
184
|
+
end
|
|
185
|
+
sql = "SELECT #{operation}(#{distinct}#{column_name}) AS #{aggregate_alias}"
|
|
186
|
+
|
|
187
|
+
# A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
|
|
188
|
+
sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
|
|
189
|
+
|
|
190
|
+
sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group]
|
|
191
|
+
if options[:from]
|
|
192
|
+
sql << " FROM #{options[:from]} "
|
|
193
|
+
elsif scope && scope[:from] && !use_workaround
|
|
194
|
+
sql << " FROM #{scope[:from]} "
|
|
195
|
+
else
|
|
196
|
+
sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround
|
|
197
|
+
sql << " FROM #{connection.quote_table_name(table_name)} "
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
joins = ""
|
|
201
|
+
add_joins!(joins, options[:joins], scope)
|
|
202
|
+
|
|
203
|
+
if merged_includes.any?
|
|
204
|
+
join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, joins)
|
|
205
|
+
sql << join_dependency.join_associations.collect{|join| join.association_join }.join
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
sql << joins unless joins.blank?
|
|
209
|
+
|
|
210
|
+
add_conditions!(sql, options[:conditions], scope)
|
|
211
|
+
add_limited_ids_condition!(sql, options, join_dependency) if join_dependency && !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
|
|
212
|
+
|
|
213
|
+
if options[:group]
|
|
214
|
+
group_key = connection.adapter_name == 'FrontBase' ? :group_alias : :group_field
|
|
215
|
+
sql << " GROUP BY #{options[group_key]} "
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
if options[:group] && options[:having]
|
|
219
|
+
having = sanitize_sql_for_conditions(options[:having])
|
|
220
|
+
|
|
221
|
+
# FrontBase requires identifiers in the HAVING clause and chokes on function calls
|
|
222
|
+
if connection.adapter_name == 'FrontBase'
|
|
223
|
+
having.downcase!
|
|
224
|
+
having.gsub!(/#{operation}\s*\(\s*#{column_name}\s*\)/, aggregate_alias)
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
sql << " HAVING #{having} "
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
sql << " ORDER BY #{options[:order]} " if options[:order]
|
|
231
|
+
add_limit!(sql, options, scope)
|
|
232
|
+
sql << ") #{aggregate_alias}_subquery" if use_workaround
|
|
233
|
+
sql
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
def execute_simple_calculation(operation, column_name, column, options) #:nodoc:
|
|
237
|
+
value = connection.select_value(construct_calculation_sql(operation, column_name, options))
|
|
238
|
+
type_cast_calculated_value(value, column, operation)
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
def execute_grouped_calculation(operation, column_name, column, options) #:nodoc:
|
|
242
|
+
group_attr = options[:group].to_s
|
|
243
|
+
association = reflect_on_association(group_attr.to_sym)
|
|
244
|
+
associated = association && association.macro == :belongs_to # only count belongs_to associations
|
|
245
|
+
group_field = associated ? association.primary_key_name : group_attr
|
|
246
|
+
group_alias = column_alias_for(group_field)
|
|
247
|
+
group_column = column_for group_field
|
|
248
|
+
sql = construct_calculation_sql(operation, column_name, options.merge(:group_field => group_field, :group_alias => group_alias))
|
|
249
|
+
calculated_data = connection.select_all(sql)
|
|
250
|
+
aggregate_alias = column_alias_for(operation, column_name)
|
|
251
|
+
|
|
252
|
+
if association
|
|
253
|
+
key_ids = calculated_data.collect { |row| row[group_alias] }
|
|
254
|
+
key_records = association.klass.base_class.find(key_ids)
|
|
255
|
+
key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
calculated_data.inject(ActiveSupport::OrderedHash.new) do |all, row|
|
|
259
|
+
key = type_cast_calculated_value(row[group_alias], group_column)
|
|
260
|
+
key = key_records[key] if associated
|
|
261
|
+
value = row[aggregate_alias]
|
|
262
|
+
all[key] = type_cast_calculated_value(value, column, operation)
|
|
263
|
+
all
|
|
264
|
+
end
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
private
|
|
268
|
+
def validate_calculation_options(operation, options = {})
|
|
269
|
+
options.assert_valid_keys(CALCULATIONS_OPTIONS)
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
# Converts the given keys to the value that the database adapter returns as
|
|
273
|
+
# a usable column name:
|
|
274
|
+
#
|
|
275
|
+
# column_alias_for("users.id") # => "users_id"
|
|
276
|
+
# column_alias_for("sum(id)") # => "sum_id"
|
|
277
|
+
# column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
|
|
278
|
+
# column_alias_for("count(*)") # => "count_all"
|
|
279
|
+
# column_alias_for("count", "id") # => "count_id"
|
|
280
|
+
def column_alias_for(*keys)
|
|
281
|
+
table_name = keys.join(' ')
|
|
282
|
+
table_name.downcase!
|
|
283
|
+
table_name.gsub!(/\*/, 'all')
|
|
284
|
+
table_name.gsub!(/\W+/, ' ')
|
|
285
|
+
table_name.strip!
|
|
286
|
+
table_name.gsub!(/ +/, '_')
|
|
287
|
+
|
|
288
|
+
connection.table_alias_for(table_name)
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
def column_for(field)
|
|
292
|
+
field_name = field.to_s.split('.').last
|
|
293
|
+
columns.detect { |c| c.name.to_s == field_name }
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
def type_cast_calculated_value(value, column, operation = nil)
|
|
297
|
+
operation = operation.to_s.downcase
|
|
298
|
+
case operation
|
|
299
|
+
when 'count' then value.to_i
|
|
300
|
+
when 'sum' then type_cast_using_column(value || '0', column)
|
|
301
|
+
when 'avg' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d
|
|
302
|
+
else type_cast_using_column(value, column)
|
|
303
|
+
end
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
def type_cast_using_column(value, column)
|
|
307
|
+
column ? column.type_cast(value) : value
|
|
308
|
+
end
|
|
309
|
+
end
|
|
310
|
+
end
|
|
311
|
+
end
|