activerecord 3.2.22.5 → 5.2.8
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.
- checksums.yaml +5 -5
- data/CHANGELOG.md +657 -621
- data/MIT-LICENSE +2 -2
- data/README.rdoc +41 -46
- data/examples/performance.rb +55 -42
- data/examples/simple.rb +6 -5
- data/lib/active_record/aggregations.rb +264 -236
- data/lib/active_record/association_relation.rb +40 -0
- data/lib/active_record/associations/alias_tracker.rb +47 -42
- data/lib/active_record/associations/association.rb +127 -75
- data/lib/active_record/associations/association_scope.rb +126 -92
- data/lib/active_record/associations/belongs_to_association.rb +78 -27
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +9 -4
- data/lib/active_record/associations/builder/association.rb +117 -32
- data/lib/active_record/associations/builder/belongs_to.rb +135 -60
- data/lib/active_record/associations/builder/collection_association.rb +61 -54
- data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +120 -42
- data/lib/active_record/associations/builder/has_many.rb +10 -64
- data/lib/active_record/associations/builder/has_one.rb +19 -51
- data/lib/active_record/associations/builder/singular_association.rb +28 -18
- data/lib/active_record/associations/collection_association.rb +226 -293
- data/lib/active_record/associations/collection_proxy.rb +1067 -69
- data/lib/active_record/associations/foreign_association.rb +13 -0
- data/lib/active_record/associations/has_many_association.rb +83 -47
- data/lib/active_record/associations/has_many_through_association.rb +98 -65
- data/lib/active_record/associations/has_one_association.rb +57 -20
- data/lib/active_record/associations/has_one_through_association.rb +18 -9
- data/lib/active_record/associations/join_dependency/join_association.rb +48 -126
- data/lib/active_record/associations/join_dependency/join_base.rb +11 -12
- data/lib/active_record/associations/join_dependency/join_part.rb +35 -42
- data/lib/active_record/associations/join_dependency.rb +212 -164
- data/lib/active_record/associations/preloader/association.rb +95 -89
- data/lib/active_record/associations/preloader/through_association.rb +84 -44
- data/lib/active_record/associations/preloader.rb +123 -111
- data/lib/active_record/associations/singular_association.rb +33 -24
- data/lib/active_record/associations/through_association.rb +60 -26
- data/lib/active_record/associations.rb +1759 -1506
- data/lib/active_record/attribute_assignment.rb +60 -193
- data/lib/active_record/attribute_decorators.rb +90 -0
- data/lib/active_record/attribute_methods/before_type_cast.rb +55 -8
- data/lib/active_record/attribute_methods/dirty.rb +113 -74
- data/lib/active_record/attribute_methods/primary_key.rb +106 -77
- data/lib/active_record/attribute_methods/query.rb +8 -5
- data/lib/active_record/attribute_methods/read.rb +63 -114
- data/lib/active_record/attribute_methods/serialization.rb +60 -90
- data/lib/active_record/attribute_methods/time_zone_conversion.rb +69 -43
- data/lib/active_record/attribute_methods/write.rb +43 -45
- data/lib/active_record/attribute_methods.rb +366 -149
- data/lib/active_record/attributes.rb +266 -0
- data/lib/active_record/autosave_association.rb +312 -225
- data/lib/active_record/base.rb +114 -505
- data/lib/active_record/callbacks.rb +145 -67
- data/lib/active_record/coders/json.rb +15 -0
- data/lib/active_record/coders/yaml_column.rb +32 -23
- data/lib/active_record/collection_cache_key.rb +53 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +883 -284
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +16 -2
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +350 -200
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -27
- data/lib/active_record/connection_adapters/abstract/quoting.rb +150 -65
- data/lib/active_record/connection_adapters/abstract/savepoints.rb +23 -0
- data/lib/active_record/connection_adapters/abstract/schema_creation.rb +146 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +477 -284
- data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +95 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +1100 -310
- data/lib/active_record/connection_adapters/abstract/transaction.rb +283 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +450 -118
- data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +657 -446
- data/lib/active_record/connection_adapters/column.rb +50 -255
- data/lib/active_record/connection_adapters/connection_specification.rb +287 -0
- data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +33 -0
- data/lib/active_record/connection_adapters/mysql/column.rb +27 -0
- data/lib/active_record/connection_adapters/mysql/database_statements.rb +140 -0
- data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +72 -0
- data/lib/active_record/connection_adapters/mysql/quoting.rb +44 -0
- data/lib/active_record/connection_adapters/mysql/schema_creation.rb +73 -0
- data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +87 -0
- data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +80 -0
- data/lib/active_record/connection_adapters/mysql/schema_statements.rb +148 -0
- data/lib/active_record/connection_adapters/mysql/type_metadata.rb +35 -0
- data/lib/active_record/connection_adapters/mysql2_adapter.rb +59 -210
- data/lib/active_record/connection_adapters/postgresql/column.rb +44 -0
- data/lib/active_record/connection_adapters/postgresql/database_statements.rb +163 -0
- data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +44 -0
- data/lib/active_record/connection_adapters/postgresql/oid/array.rb +92 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +56 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +17 -0
- data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +50 -0
- data/lib/active_record/connection_adapters/postgresql/oid/date.rb +23 -0
- data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +23 -0
- data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +21 -0
- data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +71 -0
- data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +45 -0
- data/lib/active_record/connection_adapters/postgresql/oid/money.rb +41 -0
- data/lib/active_record/connection_adapters/postgresql/oid/oid.rb +15 -0
- data/lib/active_record/connection_adapters/postgresql/oid/point.rb +65 -0
- data/lib/active_record/connection_adapters/postgresql/oid/range.rb +97 -0
- data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +18 -0
- data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +111 -0
- data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +23 -0
- data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +28 -0
- data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +30 -0
- data/lib/active_record/connection_adapters/postgresql/oid.rb +34 -0
- data/lib/active_record/connection_adapters/postgresql/quoting.rb +168 -0
- data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +43 -0
- data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +65 -0
- data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +206 -0
- data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +50 -0
- data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +774 -0
- data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +39 -0
- data/lib/active_record/connection_adapters/postgresql/utils.rb +81 -0
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +620 -1080
- data/lib/active_record/connection_adapters/schema_cache.rb +85 -36
- data/lib/active_record/connection_adapters/sql_type_metadata.rb +34 -0
- data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +21 -0
- data/lib/active_record/connection_adapters/sqlite3/quoting.rb +67 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +17 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +19 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb +18 -0
- data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +106 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +545 -27
- data/lib/active_record/connection_adapters/statement_pool.rb +34 -13
- data/lib/active_record/connection_handling.rb +145 -0
- data/lib/active_record/core.rb +559 -0
- data/lib/active_record/counter_cache.rb +200 -105
- data/lib/active_record/define_callbacks.rb +22 -0
- data/lib/active_record/dynamic_matchers.rb +107 -69
- data/lib/active_record/enum.rb +244 -0
- data/lib/active_record/errors.rb +245 -60
- data/lib/active_record/explain.rb +35 -71
- data/lib/active_record/explain_registry.rb +32 -0
- data/lib/active_record/explain_subscriber.rb +18 -9
- data/lib/active_record/fixture_set/file.rb +82 -0
- data/lib/active_record/fixtures.rb +418 -275
- data/lib/active_record/gem_version.rb +17 -0
- data/lib/active_record/inheritance.rb +209 -100
- data/lib/active_record/integration.rb +116 -21
- data/lib/active_record/internal_metadata.rb +45 -0
- data/lib/active_record/legacy_yaml_adapter.rb +48 -0
- data/lib/active_record/locale/en.yml +9 -1
- data/lib/active_record/locking/optimistic.rb +107 -94
- data/lib/active_record/locking/pessimistic.rb +20 -8
- data/lib/active_record/log_subscriber.rb +99 -34
- data/lib/active_record/migration/command_recorder.rb +199 -64
- data/lib/active_record/migration/compatibility.rb +217 -0
- data/lib/active_record/migration/join_table.rb +17 -0
- data/lib/active_record/migration.rb +893 -296
- data/lib/active_record/model_schema.rb +328 -175
- data/lib/active_record/nested_attributes.rb +338 -242
- data/lib/active_record/no_touching.rb +58 -0
- data/lib/active_record/null_relation.rb +68 -0
- data/lib/active_record/persistence.rb +557 -170
- data/lib/active_record/query_cache.rb +14 -43
- data/lib/active_record/querying.rb +36 -24
- data/lib/active_record/railtie.rb +147 -52
- data/lib/active_record/railties/console_sandbox.rb +5 -4
- data/lib/active_record/railties/controller_runtime.rb +13 -6
- data/lib/active_record/railties/databases.rake +206 -488
- data/lib/active_record/readonly_attributes.rb +4 -6
- data/lib/active_record/reflection.rb +734 -228
- data/lib/active_record/relation/batches/batch_enumerator.rb +69 -0
- data/lib/active_record/relation/batches.rb +249 -52
- data/lib/active_record/relation/calculations.rb +330 -284
- data/lib/active_record/relation/delegation.rb +135 -37
- data/lib/active_record/relation/finder_methods.rb +450 -287
- data/lib/active_record/relation/from_clause.rb +26 -0
- data/lib/active_record/relation/merger.rb +193 -0
- data/lib/active_record/relation/predicate_builder/array_handler.rb +48 -0
- data/lib/active_record/relation/predicate_builder/association_query_value.rb +46 -0
- data/lib/active_record/relation/predicate_builder/base_handler.rb +19 -0
- data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +20 -0
- data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +56 -0
- data/lib/active_record/relation/predicate_builder/range_handler.rb +42 -0
- data/lib/active_record/relation/predicate_builder/relation_handler.rb +19 -0
- data/lib/active_record/relation/predicate_builder.rb +132 -43
- data/lib/active_record/relation/query_attribute.rb +45 -0
- data/lib/active_record/relation/query_methods.rb +1037 -221
- data/lib/active_record/relation/record_fetch_warning.rb +51 -0
- data/lib/active_record/relation/spawn_methods.rb +48 -151
- data/lib/active_record/relation/where_clause.rb +186 -0
- data/lib/active_record/relation/where_clause_factory.rb +34 -0
- data/lib/active_record/relation.rb +451 -359
- data/lib/active_record/result.rb +129 -20
- data/lib/active_record/runtime_registry.rb +24 -0
- data/lib/active_record/sanitization.rb +164 -136
- data/lib/active_record/schema.rb +31 -19
- data/lib/active_record/schema_dumper.rb +154 -107
- data/lib/active_record/schema_migration.rb +56 -0
- data/lib/active_record/scoping/default.rb +108 -98
- data/lib/active_record/scoping/named.rb +125 -112
- data/lib/active_record/scoping.rb +77 -123
- data/lib/active_record/secure_token.rb +40 -0
- data/lib/active_record/serialization.rb +10 -6
- data/lib/active_record/statement_cache.rb +121 -0
- data/lib/active_record/store.rb +175 -16
- data/lib/active_record/suppressor.rb +61 -0
- data/lib/active_record/table_metadata.rb +82 -0
- data/lib/active_record/tasks/database_tasks.rb +337 -0
- data/lib/active_record/tasks/mysql_database_tasks.rb +115 -0
- data/lib/active_record/tasks/postgresql_database_tasks.rb +143 -0
- data/lib/active_record/tasks/sqlite_database_tasks.rb +83 -0
- data/lib/active_record/timestamp.rb +80 -41
- data/lib/active_record/touch_later.rb +64 -0
- data/lib/active_record/transactions.rb +240 -119
- data/lib/active_record/translation.rb +2 -0
- data/lib/active_record/type/adapter_specific_registry.rb +136 -0
- data/lib/active_record/type/date.rb +9 -0
- data/lib/active_record/type/date_time.rb +9 -0
- data/lib/active_record/type/decimal_without_scale.rb +15 -0
- data/lib/active_record/type/hash_lookup_type_map.rb +25 -0
- data/lib/active_record/type/internal/timezone.rb +17 -0
- data/lib/active_record/type/json.rb +30 -0
- data/lib/active_record/type/serialized.rb +71 -0
- data/lib/active_record/type/text.rb +11 -0
- data/lib/active_record/type/time.rb +21 -0
- data/lib/active_record/type/type_map.rb +62 -0
- data/lib/active_record/type/unsigned_integer.rb +17 -0
- data/lib/active_record/type.rb +79 -0
- data/lib/active_record/type_caster/connection.rb +33 -0
- data/lib/active_record/type_caster/map.rb +23 -0
- data/lib/active_record/type_caster.rb +9 -0
- data/lib/active_record/validations/absence.rb +25 -0
- data/lib/active_record/validations/associated.rb +35 -18
- data/lib/active_record/validations/length.rb +26 -0
- data/lib/active_record/validations/presence.rb +68 -0
- data/lib/active_record/validations/uniqueness.rb +133 -75
- data/lib/active_record/validations.rb +53 -43
- data/lib/active_record/version.rb +7 -7
- data/lib/active_record.rb +89 -57
- data/lib/rails/generators/active_record/application_record/application_record_generator.rb +27 -0
- data/lib/rails/generators/active_record/application_record/templates/application_record.rb.tt +5 -0
- data/lib/rails/generators/active_record/migration/migration_generator.rb +61 -8
- data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +24 -0
- data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +46 -0
- data/lib/rails/generators/active_record/migration.rb +28 -8
- data/lib/rails/generators/active_record/model/model_generator.rb +23 -22
- data/lib/rails/generators/active_record/model/templates/model.rb.tt +13 -0
- data/lib/rails/generators/active_record/model/templates/{module.rb → module.rb.tt} +1 -1
- data/lib/rails/generators/active_record.rb +10 -16
- metadata +141 -62
- data/examples/associations.png +0 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +0 -63
- data/lib/active_record/associations/join_helper.rb +0 -55
- data/lib/active_record/associations/preloader/belongs_to.rb +0 -17
- data/lib/active_record/associations/preloader/collection_association.rb +0 -24
- data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +0 -60
- data/lib/active_record/associations/preloader/has_many.rb +0 -17
- data/lib/active_record/associations/preloader/has_many_through.rb +0 -15
- data/lib/active_record/associations/preloader/has_one.rb +0 -23
- data/lib/active_record/associations/preloader/has_one_through.rb +0 -9
- data/lib/active_record/associations/preloader/singular_association.rb +0 -21
- data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +0 -32
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +0 -191
- data/lib/active_record/connection_adapters/mysql_adapter.rb +0 -441
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -583
- data/lib/active_record/dynamic_finder_match.rb +0 -68
- data/lib/active_record/dynamic_scope_match.rb +0 -23
- data/lib/active_record/fixtures/file.rb +0 -65
- data/lib/active_record/identity_map.rb +0 -162
- data/lib/active_record/observer.rb +0 -121
- data/lib/active_record/railties/jdbcmysql_error.rb +0 -16
- data/lib/active_record/serializers/xml_serializer.rb +0 -203
- data/lib/active_record/session_store.rb +0 -360
- data/lib/active_record/test_case.rb +0 -73
- data/lib/rails/generators/active_record/migration/templates/migration.rb +0 -34
- data/lib/rails/generators/active_record/model/templates/migration.rb +0 -15
- data/lib/rails/generators/active_record/model/templates/model.rb +0 -12
- data/lib/rails/generators/active_record/observer/observer_generator.rb +0 -15
- data/lib/rails/generators/active_record/observer/templates/observer.rb +0 -4
- data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +0 -25
- data/lib/rails/generators/active_record/session_migration/templates/migration.rb +0 -12
@@ -1,136 +1,180 @@
|
|
1
|
-
#
|
2
|
-
require 'active_support/core_ext/object/blank'
|
1
|
+
# frozen_string_literal: true
|
3
2
|
|
4
3
|
module ActiveRecord
|
5
|
-
# = Active Record Relation
|
4
|
+
# = Active Record \Relation
|
6
5
|
class Relation
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :uniq]
|
6
|
+
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
|
7
|
+
:order, :joins, :left_outer_joins, :references,
|
8
|
+
:extending, :unscope]
|
11
9
|
|
12
|
-
|
10
|
+
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :reordering,
|
11
|
+
:reverse_order, :distinct, :create_with, :skip_query_cache]
|
12
|
+
CLAUSE_METHODS = [:where, :having, :from]
|
13
|
+
INVALID_METHODS_FOR_DELETE_ALL = [:distinct, :group, :having]
|
13
14
|
|
14
|
-
|
15
|
-
attr_accessor :extensions, :default_scoped
|
16
|
-
alias :loaded? :loaded
|
17
|
-
alias :default_scoped? :default_scoped
|
15
|
+
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS + CLAUSE_METHODS
|
18
16
|
|
19
|
-
|
20
|
-
|
17
|
+
include Enumerable
|
18
|
+
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
|
21
19
|
|
22
|
-
|
23
|
-
|
24
|
-
|
20
|
+
attr_reader :table, :klass, :loaded, :predicate_builder
|
21
|
+
alias :model :klass
|
22
|
+
alias :loaded? :loaded
|
23
|
+
alias :locked? :lock_value
|
25
24
|
|
26
|
-
|
27
|
-
|
28
|
-
@
|
29
|
-
@
|
25
|
+
def initialize(klass, table: klass.arel_table, predicate_builder: klass.predicate_builder, values: {})
|
26
|
+
@klass = klass
|
27
|
+
@table = table
|
28
|
+
@values = values
|
29
|
+
@offsets = {}
|
30
|
+
@loaded = false
|
31
|
+
@predicate_builder = predicate_builder
|
32
|
+
@delegate_to_klass = false
|
30
33
|
end
|
31
34
|
|
32
|
-
def
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
primary_key_value = values[values.keys.find { |k|
|
37
|
-
k.name == primary_key
|
38
|
-
}]
|
39
|
-
|
40
|
-
if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
|
41
|
-
primary_key_value = connection.next_sequence_value(klass.sequence_name)
|
42
|
-
values[klass.arel_table[klass.primary_key]] = primary_key_value
|
43
|
-
end
|
44
|
-
end
|
45
|
-
|
46
|
-
im = arel.create_insert
|
47
|
-
im.into @table
|
35
|
+
def initialize_copy(other)
|
36
|
+
@values = @values.dup
|
37
|
+
reset
|
38
|
+
end
|
48
39
|
|
49
|
-
|
40
|
+
def arel_attribute(name) # :nodoc:
|
41
|
+
klass.arel_attribute(name, table)
|
42
|
+
end
|
50
43
|
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
|
44
|
+
# Initializes new record from relation while maintaining the current
|
45
|
+
# scope.
|
46
|
+
#
|
47
|
+
# Expects arguments in the same format as {ActiveRecord::Base.new}[rdoc-ref:Core.new].
|
48
|
+
#
|
49
|
+
# users = User.where(name: 'DHH')
|
50
|
+
# user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
|
51
|
+
#
|
52
|
+
# You can also pass a block to new with the new record as argument:
|
53
|
+
#
|
54
|
+
# user = users.new { |user| user.name = 'Oscar' }
|
55
|
+
# user.name # => Oscar
|
56
|
+
def new(attributes = nil, &block)
|
57
|
+
scoping { klass.new(values_for_create(attributes), &block) }
|
58
|
+
end
|
55
59
|
|
56
|
-
|
57
|
-
tuple[1] = conn.substitute_at(binds[i][0], i)
|
58
|
-
end
|
60
|
+
alias build new
|
59
61
|
|
60
|
-
|
61
|
-
|
62
|
+
# Tries to create a new record with the same scoped attributes
|
63
|
+
# defined in the relation. Returns the initialized object if validation fails.
|
64
|
+
#
|
65
|
+
# Expects arguments in the same format as
|
66
|
+
# {ActiveRecord::Base.create}[rdoc-ref:Persistence::ClassMethods#create].
|
67
|
+
#
|
68
|
+
# ==== Examples
|
69
|
+
#
|
70
|
+
# users = User.where(name: 'Oscar')
|
71
|
+
# users.create # => #<User id: 3, name: "Oscar", ...>
|
72
|
+
#
|
73
|
+
# users.create(name: 'fxn')
|
74
|
+
# users.create # => #<User id: 4, name: "fxn", ...>
|
75
|
+
#
|
76
|
+
# users.create { |user| user.name = 'tenderlove' }
|
77
|
+
# # => #<User id: 5, name: "tenderlove", ...>
|
78
|
+
#
|
79
|
+
# users.create(name: nil) # validation on name
|
80
|
+
# # => #<User id: nil, name: nil, ...>
|
81
|
+
def create(attributes = nil, &block)
|
82
|
+
if attributes.is_a?(Array)
|
83
|
+
attributes.collect { |attr| create(attr, &block) }
|
62
84
|
else
|
63
|
-
|
85
|
+
scoping { klass.create(values_for_create(attributes), &block) }
|
64
86
|
end
|
65
|
-
|
66
|
-
conn.insert(
|
67
|
-
im,
|
68
|
-
'SQL',
|
69
|
-
primary_key,
|
70
|
-
primary_key_value,
|
71
|
-
nil,
|
72
|
-
binds)
|
73
87
|
end
|
74
88
|
|
75
|
-
|
76
|
-
|
89
|
+
# Similar to #create, but calls
|
90
|
+
# {create!}[rdoc-ref:Persistence::ClassMethods#create!]
|
91
|
+
# on the base class. Raises an exception if a validation error occurs.
|
92
|
+
#
|
93
|
+
# Expects arguments in the same format as
|
94
|
+
# {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!].
|
95
|
+
def create!(attributes = nil, &block)
|
96
|
+
if attributes.is_a?(Array)
|
97
|
+
attributes.collect { |attr| create!(attr, &block) }
|
98
|
+
else
|
99
|
+
scoping { klass.create!(values_for_create(attributes), &block) }
|
100
|
+
end
|
77
101
|
end
|
78
102
|
|
79
|
-
def
|
80
|
-
|
81
|
-
reset
|
103
|
+
def first_or_create(attributes = nil, &block) # :nodoc:
|
104
|
+
first || create(attributes, &block)
|
82
105
|
end
|
83
106
|
|
84
|
-
|
85
|
-
|
86
|
-
def create(*args, &block)
|
87
|
-
scoping { @klass.create(*args, &block) }
|
107
|
+
def first_or_create!(attributes = nil, &block) # :nodoc:
|
108
|
+
first || create!(attributes, &block)
|
88
109
|
end
|
89
110
|
|
90
|
-
def
|
91
|
-
|
111
|
+
def first_or_initialize(attributes = nil, &block) # :nodoc:
|
112
|
+
first || new(attributes, &block)
|
92
113
|
end
|
93
114
|
|
94
|
-
#
|
95
|
-
#
|
96
|
-
# Expects arguments in the same format as <tt>Base.create</tt>.
|
115
|
+
# Finds the first record with the given attributes, or creates a record
|
116
|
+
# with the attributes if one is not found:
|
97
117
|
#
|
98
|
-
#
|
99
|
-
#
|
100
|
-
# User
|
101
|
-
# # => <User id: 1, first_name: 'Penélope', last_name: nil>
|
118
|
+
# # Find the first user named "Penélope" or create a new one.
|
119
|
+
# User.find_or_create_by(first_name: 'Penélope')
|
120
|
+
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
|
102
121
|
#
|
103
|
-
# # Find the first user named Penélope or create a new one.
|
122
|
+
# # Find the first user named "Penélope" or create a new one.
|
104
123
|
# # We already have one so the existing record will be returned.
|
105
|
-
# User.
|
106
|
-
# # =>
|
124
|
+
# User.find_or_create_by(first_name: 'Penélope')
|
125
|
+
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
|
107
126
|
#
|
108
|
-
# # Find the first user named Scarlett or create a new one with
|
109
|
-
#
|
110
|
-
#
|
127
|
+
# # Find the first user named "Scarlett" or create a new one with
|
128
|
+
# # a particular last name.
|
129
|
+
# User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
|
130
|
+
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
|
111
131
|
#
|
112
|
-
#
|
113
|
-
#
|
114
|
-
#
|
115
|
-
#
|
132
|
+
# This method accepts a block, which is passed down to #create. The last example
|
133
|
+
# above can be alternatively written this way:
|
134
|
+
#
|
135
|
+
# # Find the first user named "Scarlett" or create a new one with a
|
136
|
+
# # different last name.
|
137
|
+
# User.find_or_create_by(first_name: 'Scarlett') do |user|
|
138
|
+
# user.last_name = 'Johansson'
|
116
139
|
# end
|
117
|
-
# # =>
|
118
|
-
|
119
|
-
|
140
|
+
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
|
141
|
+
#
|
142
|
+
# This method always returns a record, but if creation was attempted and
|
143
|
+
# failed due to validation errors it won't be persisted, you get what
|
144
|
+
# #create returns in such situation.
|
145
|
+
#
|
146
|
+
# Please note *this method is not atomic*, it runs first a SELECT, and if
|
147
|
+
# there are no results an INSERT is attempted. If there are other threads
|
148
|
+
# or processes there is a race condition between both calls and it could
|
149
|
+
# be the case that you end up with two similar records.
|
150
|
+
#
|
151
|
+
# Whether that is a problem or not depends on the logic of the
|
152
|
+
# application, but in the particular case in which rows have a UNIQUE
|
153
|
+
# constraint an exception may be raised, just retry:
|
154
|
+
#
|
155
|
+
# begin
|
156
|
+
# CreditAccount.transaction(requires_new: true) do
|
157
|
+
# CreditAccount.find_or_create_by(user_id: user.id)
|
158
|
+
# end
|
159
|
+
# rescue ActiveRecord::RecordNotUnique
|
160
|
+
# retry
|
161
|
+
# end
|
162
|
+
#
|
163
|
+
def find_or_create_by(attributes, &block)
|
164
|
+
find_by(attributes) || create(attributes, &block)
|
120
165
|
end
|
121
166
|
|
122
|
-
# Like
|
123
|
-
#
|
124
|
-
#
|
125
|
-
def
|
126
|
-
|
167
|
+
# Like #find_or_create_by, but calls
|
168
|
+
# {create!}[rdoc-ref:Persistence::ClassMethods#create!] so an exception
|
169
|
+
# is raised if the created record is invalid.
|
170
|
+
def find_or_create_by!(attributes, &block)
|
171
|
+
find_by(attributes) || create!(attributes, &block)
|
127
172
|
end
|
128
173
|
|
129
|
-
# Like
|
130
|
-
#
|
131
|
-
|
132
|
-
|
133
|
-
first || new(attributes, options, &block)
|
174
|
+
# Like #find_or_create_by, but calls {new}[rdoc-ref:Core#new]
|
175
|
+
# instead of {create}[rdoc-ref:Persistence::ClassMethods#create].
|
176
|
+
def find_or_initialize_by(attributes, &block)
|
177
|
+
find_by(attributes) || new(attributes, &block)
|
134
178
|
end
|
135
179
|
|
136
180
|
# Runs EXPLAIN on the query or queries triggered by this relation and
|
@@ -141,397 +185,445 @@ module ActiveRecord
|
|
141
185
|
# are needed by the next ones when eager loading is going on.
|
142
186
|
#
|
143
187
|
# Please see further details in the
|
144
|
-
# {Active Record Query Interface guide}[http://
|
188
|
+
# {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
|
145
189
|
def explain
|
146
|
-
|
147
|
-
exec_explain(queries)
|
148
|
-
end
|
149
|
-
|
150
|
-
def to_a
|
151
|
-
# We monitor here the entire execution rather than individual SELECTs
|
152
|
-
# because from the point of view of the user fetching the records of a
|
153
|
-
# relation is a single unit of work. You want to know if this call takes
|
154
|
-
# too long, not if the individual queries take too long.
|
155
|
-
#
|
156
|
-
# It could be the case that none of the queries involved surpass the
|
157
|
-
# threshold, and at the same time the sum of them all does. The user
|
158
|
-
# should get a query plan logged in that case.
|
159
|
-
logging_query_plan do
|
160
|
-
exec_queries
|
161
|
-
end
|
190
|
+
exec_explain(collecting_queries_for_explain { exec_queries })
|
162
191
|
end
|
163
192
|
|
164
|
-
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
if default_scoped.equal?(self)
|
170
|
-
@records = if @readonly_value.nil? && !@klass.locking_enabled?
|
171
|
-
eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
|
172
|
-
else
|
173
|
-
IdentityMap.without do
|
174
|
-
eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
|
175
|
-
end
|
176
|
-
end
|
177
|
-
|
178
|
-
preload = @preload_values
|
179
|
-
preload += @includes_values unless eager_loading?
|
180
|
-
preload.each do |associations|
|
181
|
-
ActiveRecord::Associations::Preloader.new(@records, associations).run
|
182
|
-
end
|
183
|
-
|
184
|
-
# @readonly_value is true only if set explicitly. @implicit_readonly is true if there
|
185
|
-
# are JOINS and no explicit SELECT.
|
186
|
-
readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
|
187
|
-
@records.each { |record| record.readonly! } if readonly
|
188
|
-
else
|
189
|
-
@records = default_scoped.to_a
|
190
|
-
end
|
193
|
+
# Converts relation objects to Array.
|
194
|
+
def to_ary
|
195
|
+
records.dup
|
196
|
+
end
|
197
|
+
alias to_a to_ary
|
191
198
|
|
192
|
-
|
199
|
+
def records # :nodoc:
|
200
|
+
load
|
193
201
|
@records
|
194
202
|
end
|
195
|
-
private :exec_queries
|
196
203
|
|
197
|
-
|
198
|
-
|
204
|
+
# Serializes the relation objects Array.
|
205
|
+
def encode_with(coder)
|
206
|
+
coder.represent_seq(nil, records)
|
199
207
|
end
|
200
208
|
|
201
209
|
# Returns size of the records.
|
202
210
|
def size
|
203
|
-
loaded? ? @records.length : count
|
211
|
+
loaded? ? @records.length : count(:all)
|
204
212
|
end
|
205
213
|
|
206
214
|
# Returns true if there are no records.
|
207
215
|
def empty?
|
208
216
|
return @records.empty? if loaded?
|
217
|
+
!exists?
|
218
|
+
end
|
209
219
|
|
210
|
-
|
211
|
-
|
220
|
+
# Returns true if there are no records.
|
221
|
+
def none?
|
222
|
+
return super if block_given?
|
223
|
+
empty?
|
212
224
|
end
|
213
225
|
|
226
|
+
# Returns true if there are any records.
|
214
227
|
def any?
|
215
|
-
if block_given?
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
228
|
+
return super if block_given?
|
229
|
+
!empty?
|
230
|
+
end
|
231
|
+
|
232
|
+
# Returns true if there is exactly one record.
|
233
|
+
def one?
|
234
|
+
return super if block_given?
|
235
|
+
limit_value ? records.one? : size == 1
|
220
236
|
end
|
221
237
|
|
238
|
+
# Returns true if there is more than one record.
|
222
239
|
def many?
|
223
|
-
if block_given?
|
224
|
-
|
225
|
-
else
|
226
|
-
@limit_value ? to_a.many? : size > 1
|
227
|
-
end
|
240
|
+
return super if block_given?
|
241
|
+
limit_value ? records.many? : size > 1
|
228
242
|
end
|
229
243
|
|
230
|
-
#
|
244
|
+
# Returns a cache key that can be used to identify the records fetched by
|
245
|
+
# this query. The cache key is built with a fingerprint of the sql query,
|
246
|
+
# the number of records matched by the query and a timestamp of the last
|
247
|
+
# updated record. When a new record comes to match the query, or any of
|
248
|
+
# the existing records is updated or deleted, the cache key changes.
|
249
|
+
#
|
250
|
+
# Product.where("name like ?", "%Cosmic Encounter%").cache_key
|
251
|
+
# # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000"
|
252
|
+
#
|
253
|
+
# If the collection is loaded, the method will iterate through the records
|
254
|
+
# to generate the timestamp, otherwise it will trigger one SQL query like:
|
231
255
|
#
|
232
|
-
#
|
256
|
+
# SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%')
|
233
257
|
#
|
234
|
-
#
|
235
|
-
#
|
258
|
+
# You can also pass a custom timestamp column to fetch the timestamp of the
|
259
|
+
# last updated record.
|
260
|
+
#
|
261
|
+
# Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at)
|
262
|
+
#
|
263
|
+
# You can customize the strategy to generate the key on a per model basis
|
264
|
+
# overriding ActiveRecord::Base#collection_cache_key.
|
265
|
+
def cache_key(timestamp_column = :updated_at)
|
266
|
+
@cache_keys ||= {}
|
267
|
+
@cache_keys[timestamp_column] ||= @klass.collection_cache_key(self, timestamp_column)
|
268
|
+
end
|
269
|
+
|
270
|
+
# Scope all queries to the current scope.
|
271
|
+
#
|
272
|
+
# Comment.where(post_id: 1).scoping do
|
273
|
+
# Comment.first
|
236
274
|
# end
|
275
|
+
# # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
|
237
276
|
#
|
238
277
|
# Please check unscoped if you want to remove all previous scopes (including
|
239
278
|
# the default_scope) during the execution of a block.
|
240
279
|
def scoping
|
241
|
-
|
280
|
+
previous, klass.current_scope = klass.current_scope(true), self unless @delegate_to_klass
|
281
|
+
yield
|
282
|
+
ensure
|
283
|
+
klass.current_scope = previous unless @delegate_to_klass
|
284
|
+
end
|
285
|
+
|
286
|
+
def _exec_scope(*args, &block) # :nodoc:
|
287
|
+
@delegate_to_klass = true
|
288
|
+
instance_exec(*args, &block) || self
|
289
|
+
ensure
|
290
|
+
@delegate_to_klass = false
|
242
291
|
end
|
243
292
|
|
244
|
-
# Updates all records with details given
|
245
|
-
#
|
246
|
-
#
|
247
|
-
#
|
293
|
+
# Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
|
294
|
+
# statement and sends it straight to the database. It does not instantiate the involved models and it does not
|
295
|
+
# trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
|
296
|
+
# Active Record's normal type casting and serialization.
|
248
297
|
#
|
249
298
|
# ==== Parameters
|
250
299
|
#
|
251
300
|
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
|
252
|
-
# * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
|
253
|
-
# See conditions in the intro.
|
254
|
-
# * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
|
255
301
|
#
|
256
302
|
# ==== Examples
|
257
303
|
#
|
258
304
|
# # Update all customers with the given attributes
|
259
|
-
# Customer.update_all :
|
305
|
+
# Customer.update_all wants_email: true
|
260
306
|
#
|
261
307
|
# # Update all books with 'Rails' in their title
|
262
|
-
# Book.
|
263
|
-
#
|
264
|
-
# # Update all avatars migrated more than a week ago
|
265
|
-
# Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
|
308
|
+
# Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
|
266
309
|
#
|
267
310
|
# # Update all books that match conditions, but limit it to 5 ordered by date
|
268
|
-
# Book.
|
269
|
-
#
|
270
|
-
# # Conditions from the current relation also works
|
271
|
-
# Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
|
311
|
+
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
|
272
312
|
#
|
273
|
-
# #
|
274
|
-
#
|
275
|
-
def update_all(updates
|
276
|
-
|
277
|
-
if conditions || options.present?
|
278
|
-
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
|
279
|
-
else
|
280
|
-
stmt = Arel::UpdateManager.new(arel.engine)
|
313
|
+
# # Update all invoices and set the number column to its id value.
|
314
|
+
# Invoice.update_all('number = id')
|
315
|
+
def update_all(updates)
|
316
|
+
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
|
281
317
|
|
282
|
-
|
283
|
-
|
284
|
-
|
318
|
+
if eager_loading?
|
319
|
+
relation = apply_join_dependency
|
320
|
+
return relation.update_all(updates)
|
321
|
+
end
|
285
322
|
|
286
|
-
|
287
|
-
@klass.connection.join_to_update(stmt, arel)
|
288
|
-
else
|
289
|
-
stmt.take(arel.limit)
|
290
|
-
stmt.order(*arel.orders)
|
291
|
-
stmt.wheres = arel.constraints
|
292
|
-
end
|
323
|
+
stmt = Arel::UpdateManager.new
|
293
324
|
|
294
|
-
|
325
|
+
stmt.set Arel.sql(@klass.sanitize_sql_for_assignment(updates))
|
326
|
+
stmt.table(table)
|
327
|
+
|
328
|
+
if has_join_values? || offset_value
|
329
|
+
@klass.connection.join_to_update(stmt, arel, arel_attribute(primary_key))
|
330
|
+
else
|
331
|
+
stmt.key = arel_attribute(primary_key)
|
332
|
+
stmt.take(arel.limit)
|
333
|
+
stmt.order(*arel.orders)
|
334
|
+
stmt.wheres = arel.constraints
|
295
335
|
end
|
336
|
+
|
337
|
+
@klass.connection.update stmt, "#{@klass} Update All"
|
296
338
|
end
|
297
339
|
|
298
|
-
|
299
|
-
|
300
|
-
|
301
|
-
# ==== Parameters
|
302
|
-
#
|
303
|
-
# * +id+ - This should be the id or an array of ids to be updated.
|
304
|
-
# * +attributes+ - This should be a hash of attributes or an array of hashes.
|
305
|
-
#
|
306
|
-
# ==== Examples
|
307
|
-
#
|
308
|
-
# # Updates one record
|
309
|
-
# Person.update(15, :user_name => 'Samuel', :group => 'expert')
|
310
|
-
#
|
311
|
-
# # Updates multiple records
|
312
|
-
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
|
313
|
-
# Person.update(people.keys, people.values)
|
314
|
-
def update(id, attributes)
|
315
|
-
if id.is_a?(Array)
|
316
|
-
id.each.with_index.map {|one_id, idx| update(one_id, attributes[idx])}
|
340
|
+
def update(id = :all, attributes) # :nodoc:
|
341
|
+
if id == :all
|
342
|
+
each { |record| record.update(attributes) }
|
317
343
|
else
|
318
|
-
|
319
|
-
object.update_attributes(attributes)
|
320
|
-
object
|
344
|
+
klass.update(id, attributes)
|
321
345
|
end
|
322
346
|
end
|
323
347
|
|
324
|
-
# Destroys the records
|
325
|
-
# record and calling its
|
326
|
-
# executed (including <tt>:dependent</tt> association options
|
327
|
-
#
|
328
|
-
#
|
329
|
-
# reflect that no changes should be made (since they can't be
|
330
|
-
# persisted).
|
348
|
+
# Destroys the records by instantiating each
|
349
|
+
# record and calling its {#destroy}[rdoc-ref:Persistence#destroy] method.
|
350
|
+
# Each object's callbacks are executed (including <tt>:dependent</tt> association options).
|
351
|
+
# Returns the collection of objects that were destroyed; each will be frozen, to
|
352
|
+
# reflect that no changes should be made (since they can't be persisted).
|
331
353
|
#
|
332
354
|
# Note: Instantiation, callback execution, and deletion of each
|
333
355
|
# record can be time consuming when you're removing many records at
|
334
356
|
# once. It generates at least one SQL +DELETE+ query per record (or
|
335
357
|
# possibly more, to enforce your callbacks). If you want to delete many
|
336
358
|
# rows quickly, without concern for their associations or callbacks, use
|
337
|
-
#
|
338
|
-
#
|
339
|
-
# ==== Parameters
|
340
|
-
#
|
341
|
-
# * +conditions+ - A string, array, or hash that specifies which records
|
342
|
-
# to destroy. If omitted, all records are destroyed. See the
|
343
|
-
# Conditions section in the introduction to ActiveRecord::Base for
|
344
|
-
# more information.
|
359
|
+
# #delete_all instead.
|
345
360
|
#
|
346
361
|
# ==== Examples
|
347
362
|
#
|
348
|
-
# Person.
|
349
|
-
|
350
|
-
|
351
|
-
def destroy_all(conditions = nil)
|
352
|
-
if conditions
|
353
|
-
where(conditions).destroy_all
|
354
|
-
else
|
355
|
-
to_a.each {|object| object.destroy }.tap { reset }
|
356
|
-
end
|
363
|
+
# Person.where(age: 0..18).destroy_all
|
364
|
+
def destroy_all
|
365
|
+
records.each(&:destroy).tap { reset }
|
357
366
|
end
|
358
367
|
|
359
|
-
#
|
360
|
-
#
|
361
|
-
#
|
362
|
-
#
|
363
|
-
#
|
364
|
-
#
|
368
|
+
# Deletes the records without instantiating the records
|
369
|
+
# first, and hence not calling the {#destroy}[rdoc-ref:Persistence#destroy]
|
370
|
+
# method nor invoking callbacks.
|
371
|
+
# This is a single SQL DELETE statement that goes straight to the database, much more
|
372
|
+
# efficient than #destroy_all. Be careful with relations though, in particular
|
373
|
+
# <tt>:dependent</tt> rules defined on associations are not honored. Returns the
|
374
|
+
# number of rows affected.
|
365
375
|
#
|
366
|
-
#
|
367
|
-
#
|
368
|
-
# * +id+ - Can be either an Integer or an Array of Integers.
|
376
|
+
# Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
|
369
377
|
#
|
370
|
-
#
|
378
|
+
# Both calls delete the affected posts all at once with a single DELETE statement.
|
379
|
+
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
|
380
|
+
# +after_destroy+ callbacks, use the #destroy_all method instead.
|
371
381
|
#
|
372
|
-
#
|
373
|
-
# Todo.destroy(1)
|
382
|
+
# If an invalid method is supplied, #delete_all raises an ActiveRecordError:
|
374
383
|
#
|
375
|
-
#
|
376
|
-
#
|
377
|
-
|
378
|
-
|
379
|
-
|
380
|
-
|
381
|
-
|
382
|
-
|
384
|
+
# Post.distinct.delete_all
|
385
|
+
# # => ActiveRecord::ActiveRecordError: delete_all doesn't support distinct
|
386
|
+
def delete_all
|
387
|
+
invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select do |method|
|
388
|
+
value = get_value(method)
|
389
|
+
SINGLE_VALUE_METHODS.include?(method) ? value : value.any?
|
390
|
+
end
|
391
|
+
if invalid_methods.any?
|
392
|
+
raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
|
383
393
|
end
|
384
|
-
end
|
385
394
|
|
386
|
-
|
387
|
-
|
388
|
-
|
389
|
-
|
390
|
-
# the number of rows affected.
|
391
|
-
#
|
392
|
-
# ==== Parameters
|
393
|
-
#
|
394
|
-
# * +conditions+ - Conditions are specified the same way as with +find+ method.
|
395
|
-
#
|
396
|
-
# ==== Example
|
397
|
-
#
|
398
|
-
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
|
399
|
-
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
|
400
|
-
# Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
|
401
|
-
#
|
402
|
-
# Both calls delete the affected posts all at once with a single DELETE statement.
|
403
|
-
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
|
404
|
-
# +after_destroy+ callbacks, use the +destroy_all+ method instead.
|
405
|
-
def delete_all(conditions = nil)
|
406
|
-
raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value
|
395
|
+
if eager_loading?
|
396
|
+
relation = apply_join_dependency
|
397
|
+
return relation.delete_all
|
398
|
+
end
|
407
399
|
|
408
|
-
|
409
|
-
|
410
|
-
where(conditions).delete_all
|
411
|
-
else
|
412
|
-
statement = arel.compile_delete
|
413
|
-
affected = @klass.connection.delete(statement, 'SQL', bind_values)
|
400
|
+
stmt = Arel::DeleteManager.new
|
401
|
+
stmt.from(table)
|
414
402
|
|
415
|
-
|
416
|
-
|
403
|
+
if has_join_values? || has_limit_or_offset?
|
404
|
+
@klass.connection.join_to_delete(stmt, arel, arel_attribute(primary_key))
|
405
|
+
else
|
406
|
+
stmt.wheres = arel.constraints
|
417
407
|
end
|
408
|
+
|
409
|
+
affected = @klass.connection.delete(stmt, "#{@klass} Destroy")
|
410
|
+
|
411
|
+
reset
|
412
|
+
affected
|
418
413
|
end
|
419
414
|
|
420
|
-
#
|
421
|
-
#
|
422
|
-
#
|
423
|
-
#
|
424
|
-
# Observer methods.
|
415
|
+
# Causes the records to be loaded from the database if they have not
|
416
|
+
# been loaded already. You can use this if for some reason you need
|
417
|
+
# to explicitly load some records before actually using them. The
|
418
|
+
# return value is the relation itself, not the records.
|
425
419
|
#
|
426
|
-
#
|
427
|
-
|
428
|
-
|
429
|
-
|
430
|
-
|
431
|
-
# essential jobs.
|
432
|
-
#
|
433
|
-
# ==== Examples
|
434
|
-
#
|
435
|
-
# # Delete a single row
|
436
|
-
# Todo.delete(1)
|
437
|
-
#
|
438
|
-
# # Delete multiple rows
|
439
|
-
# Todo.delete([2,3,4])
|
440
|
-
def delete(id_or_array)
|
441
|
-
IdentityMap.remove_by_id(self.symbolized_base_class, id_or_array) if IdentityMap.enabled?
|
442
|
-
where(primary_key => id_or_array).delete_all
|
420
|
+
# Post.where(published: true).load # => #<ActiveRecord::Relation>
|
421
|
+
def load(&block)
|
422
|
+
exec_queries(&block) unless loaded?
|
423
|
+
|
424
|
+
self
|
443
425
|
end
|
444
426
|
|
427
|
+
# Forces reloading of relation.
|
445
428
|
def reload
|
446
429
|
reset
|
447
|
-
|
448
|
-
self
|
430
|
+
load
|
449
431
|
end
|
450
432
|
|
451
433
|
def reset
|
452
|
-
@
|
453
|
-
@
|
454
|
-
@records = []
|
434
|
+
@delegate_to_klass = false
|
435
|
+
@to_sql = @arel = @loaded = @should_eager_load = nil
|
436
|
+
@records = [].freeze
|
437
|
+
@offsets = {}
|
455
438
|
self
|
456
439
|
end
|
457
440
|
|
441
|
+
# Returns sql statement for the relation.
|
442
|
+
#
|
443
|
+
# User.where(name: 'Oscar').to_sql
|
444
|
+
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
|
458
445
|
def to_sql
|
459
|
-
@to_sql ||=
|
446
|
+
@to_sql ||= begin
|
447
|
+
if eager_loading?
|
448
|
+
apply_join_dependency do |relation, join_dependency|
|
449
|
+
relation = join_dependency.apply_column_aliases(relation)
|
450
|
+
relation.to_sql
|
451
|
+
end
|
452
|
+
else
|
453
|
+
conn = klass.connection
|
454
|
+
conn.unprepared_statement { conn.to_sql(arel) }
|
455
|
+
end
|
456
|
+
end
|
460
457
|
end
|
461
458
|
|
462
|
-
|
463
|
-
|
464
|
-
|
465
|
-
|
466
|
-
|
467
|
-
|
459
|
+
# Returns a hash of where conditions.
|
460
|
+
#
|
461
|
+
# User.where(name: 'Oscar').where_values_hash
|
462
|
+
# # => {name: "Oscar"}
|
463
|
+
def where_values_hash(relation_table_name = klass.table_name)
|
464
|
+
where_clause.to_h(relation_table_name)
|
468
465
|
end
|
469
466
|
|
470
467
|
def scope_for_create
|
471
|
-
|
468
|
+
where_values_hash.merge!(create_with_value.stringify_keys)
|
472
469
|
end
|
473
470
|
|
471
|
+
# Returns true if relation needs eager loading.
|
474
472
|
def eager_loading?
|
475
473
|
@should_eager_load ||=
|
476
|
-
|
477
|
-
|
474
|
+
eager_load_values.any? ||
|
475
|
+
includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
|
478
476
|
end
|
479
477
|
|
480
478
|
# Joins that are also marked for preloading. In which case we should just eager load them.
|
481
479
|
# Note that this is a naive implementation because we could have strings and symbols which
|
482
480
|
# represent the same association, but that aren't matched by this. Also, we could have
|
483
|
-
# nested hashes which partially match, e.g. { :
|
481
|
+
# nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
|
484
482
|
def joined_includes_values
|
485
|
-
|
483
|
+
includes_values & joins_values
|
486
484
|
end
|
487
485
|
|
486
|
+
# Compares two relations for equality.
|
488
487
|
def ==(other)
|
489
488
|
case other
|
489
|
+
when Associations::CollectionProxy, AssociationRelation
|
490
|
+
self == other.records
|
490
491
|
when Relation
|
491
492
|
other.to_sql == to_sql
|
492
493
|
when Array
|
493
|
-
|
494
|
+
records == other
|
494
495
|
end
|
495
496
|
end
|
496
497
|
|
498
|
+
def pretty_print(q)
|
499
|
+
q.pp(records)
|
500
|
+
end
|
501
|
+
|
502
|
+
# Returns true if relation is blank.
|
503
|
+
def blank?
|
504
|
+
records.blank?
|
505
|
+
end
|
506
|
+
|
507
|
+
def values
|
508
|
+
@values.dup
|
509
|
+
end
|
510
|
+
|
497
511
|
def inspect
|
498
|
-
|
512
|
+
subject = loaded? ? records : self
|
513
|
+
entries = subject.take([limit_value, 11].compact.min).map!(&:inspect)
|
514
|
+
|
515
|
+
entries[10] = "..." if entries.size == 11
|
516
|
+
|
517
|
+
"#<#{self.class.name} [#{entries.join(', ')}]>"
|
499
518
|
end
|
500
519
|
|
501
|
-
def
|
502
|
-
|
503
|
-
default_scope = default_scope.merge(self)
|
504
|
-
default_scope.default_scoped = false
|
505
|
-
default_scope
|
506
|
-
else
|
507
|
-
self
|
508
|
-
end
|
520
|
+
def empty_scope? # :nodoc:
|
521
|
+
@values == klass.unscoped.values
|
509
522
|
end
|
510
523
|
|
524
|
+
def has_limit_or_offset? # :nodoc:
|
525
|
+
limit_value || offset_value
|
526
|
+
end
|
527
|
+
|
528
|
+
def alias_tracker(joins = [], aliases = nil) # :nodoc:
|
529
|
+
joins += [aliases] if aliases
|
530
|
+
ActiveRecord::Associations::AliasTracker.create(connection, table.name, joins)
|
531
|
+
end
|
532
|
+
|
533
|
+
protected
|
534
|
+
|
535
|
+
def load_records(records)
|
536
|
+
@records = records.freeze
|
537
|
+
@loaded = true
|
538
|
+
end
|
539
|
+
|
511
540
|
private
|
512
541
|
|
513
|
-
|
514
|
-
|
515
|
-
|
516
|
-
|
542
|
+
def has_join_values?
|
543
|
+
joins_values.any? || left_outer_joins_values.any?
|
544
|
+
end
|
545
|
+
|
546
|
+
def exec_queries(&block)
|
547
|
+
skip_query_cache_if_necessary do
|
548
|
+
@records =
|
549
|
+
if eager_loading?
|
550
|
+
apply_join_dependency do |relation, join_dependency|
|
551
|
+
if ActiveRecord::NullRelation === relation
|
552
|
+
[]
|
553
|
+
else
|
554
|
+
relation = join_dependency.apply_column_aliases(relation)
|
555
|
+
rows = connection.select_all(relation.arel, "SQL")
|
556
|
+
join_dependency.instantiate(rows, &block)
|
557
|
+
end.freeze
|
558
|
+
end
|
559
|
+
else
|
560
|
+
klass.find_by_sql(arel, &block).freeze
|
561
|
+
end
|
562
|
+
|
563
|
+
preload = preload_values
|
564
|
+
preload += includes_values unless eager_loading?
|
565
|
+
preloader = nil
|
566
|
+
preload.each do |associations|
|
567
|
+
preloader ||= build_preloader
|
568
|
+
preloader.preload @records, associations
|
569
|
+
end
|
570
|
+
|
571
|
+
@records.each(&:readonly!) if readonly_value
|
572
|
+
|
573
|
+
@loaded = true
|
574
|
+
@records
|
575
|
+
end
|
576
|
+
end
|
577
|
+
|
578
|
+
def skip_query_cache_if_necessary
|
579
|
+
if skip_query_cache_value
|
580
|
+
uncached do
|
581
|
+
yield
|
582
|
+
end
|
517
583
|
else
|
518
|
-
|
584
|
+
yield
|
585
|
+
end
|
586
|
+
end
|
587
|
+
|
588
|
+
def build_preloader
|
589
|
+
ActiveRecord::Associations::Preloader.new
|
590
|
+
end
|
591
|
+
|
592
|
+
def references_eager_loaded_tables?
|
593
|
+
joined_tables = arel.join_sources.map do |join|
|
594
|
+
if join.is_a?(Arel::Nodes::StringJoin)
|
595
|
+
tables_in_string(join.left)
|
596
|
+
else
|
597
|
+
[join.left.table_name, join.left.table_alias]
|
598
|
+
end
|
519
599
|
end
|
600
|
+
|
601
|
+
joined_tables += [table.name, table.table_alias]
|
602
|
+
|
603
|
+
# always convert table names to downcase as in Oracle quoted table names are in uppercase
|
604
|
+
joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
|
605
|
+
|
606
|
+
(references_values - joined_tables).any?
|
520
607
|
end
|
521
608
|
|
522
|
-
|
609
|
+
def tables_in_string(string)
|
610
|
+
return [] if string.blank?
|
611
|
+
# always convert table names to downcase as in Oracle quoted table names are in uppercase
|
612
|
+
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
|
613
|
+
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"]
|
614
|
+
end
|
523
615
|
|
524
|
-
|
525
|
-
|
616
|
+
def values_for_create(attributes = nil)
|
617
|
+
result = attributes ? where_values_hash.merge!(attributes) : where_values_hash
|
526
618
|
|
527
|
-
|
528
|
-
|
619
|
+
# NOTE: if there are same keys in both create_with and result, create_with should be used.
|
620
|
+
# This is to make sure nested attributes don't get passed to the klass.new,
|
621
|
+
# while keeping the precedence of the duplicate keys in create_with.
|
622
|
+
create_with_value.stringify_keys.each do |k, v|
|
623
|
+
result[k] = v if result.key?(k)
|
624
|
+
end
|
529
625
|
|
530
|
-
|
531
|
-
|
532
|
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
|
533
|
-
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
|
534
|
-
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
|
535
|
-
end
|
626
|
+
result
|
627
|
+
end
|
536
628
|
end
|
537
629
|
end
|