activerecord 6.0.0
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of activerecord might be problematic. Click here for more details.
- checksums.yaml +7 -0
- data/CHANGELOG.md +1013 -0
- data/MIT-LICENSE +22 -0
- data/README.rdoc +219 -0
- data/examples/performance.rb +185 -0
- data/examples/simple.rb +15 -0
- data/lib/active_record.rb +195 -0
- data/lib/active_record/aggregations.rb +285 -0
- data/lib/active_record/association_relation.rb +40 -0
- data/lib/active_record/associations.rb +1865 -0
- data/lib/active_record/associations/alias_tracker.rb +81 -0
- data/lib/active_record/associations/association.rb +332 -0
- data/lib/active_record/associations/association_scope.rb +166 -0
- data/lib/active_record/associations/belongs_to_association.rb +124 -0
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +36 -0
- data/lib/active_record/associations/builder/association.rb +136 -0
- data/lib/active_record/associations/builder/belongs_to.rb +130 -0
- data/lib/active_record/associations/builder/collection_association.rb +72 -0
- data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +114 -0
- data/lib/active_record/associations/builder/has_many.rb +19 -0
- data/lib/active_record/associations/builder/has_one.rb +64 -0
- data/lib/active_record/associations/builder/singular_association.rb +44 -0
- data/lib/active_record/associations/collection_association.rb +498 -0
- data/lib/active_record/associations/collection_proxy.rb +1128 -0
- data/lib/active_record/associations/foreign_association.rb +20 -0
- data/lib/active_record/associations/has_many_association.rb +136 -0
- data/lib/active_record/associations/has_many_through_association.rb +220 -0
- data/lib/active_record/associations/has_one_association.rb +118 -0
- data/lib/active_record/associations/has_one_through_association.rb +45 -0
- data/lib/active_record/associations/join_dependency.rb +258 -0
- data/lib/active_record/associations/join_dependency/join_association.rb +80 -0
- data/lib/active_record/associations/join_dependency/join_base.rb +23 -0
- data/lib/active_record/associations/join_dependency/join_part.rb +71 -0
- data/lib/active_record/associations/preloader.rb +201 -0
- data/lib/active_record/associations/preloader/association.rb +133 -0
- data/lib/active_record/associations/preloader/through_association.rb +116 -0
- data/lib/active_record/associations/singular_association.rb +59 -0
- data/lib/active_record/associations/through_association.rb +121 -0
- data/lib/active_record/attribute_assignment.rb +85 -0
- data/lib/active_record/attribute_decorators.rb +90 -0
- data/lib/active_record/attribute_methods.rb +420 -0
- data/lib/active_record/attribute_methods/before_type_cast.rb +81 -0
- data/lib/active_record/attribute_methods/dirty.rb +221 -0
- data/lib/active_record/attribute_methods/primary_key.rb +136 -0
- data/lib/active_record/attribute_methods/query.rb +41 -0
- data/lib/active_record/attribute_methods/read.rb +47 -0
- data/lib/active_record/attribute_methods/serialization.rb +90 -0
- data/lib/active_record/attribute_methods/time_zone_conversion.rb +91 -0
- data/lib/active_record/attribute_methods/write.rb +61 -0
- data/lib/active_record/attributes.rb +279 -0
- data/lib/active_record/autosave_association.rb +508 -0
- data/lib/active_record/base.rb +328 -0
- data/lib/active_record/callbacks.rb +339 -0
- data/lib/active_record/coders/json.rb +15 -0
- data/lib/active_record/coders/yaml_column.rb +50 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +1165 -0
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +85 -0
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +512 -0
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +154 -0
- data/lib/active_record/connection_adapters/abstract/quoting.rb +251 -0
- data/lib/active_record/connection_adapters/abstract/savepoints.rb +23 -0
- data/lib/active_record/connection_adapters/abstract/schema_creation.rb +153 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +713 -0
- data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +93 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +1475 -0
- data/lib/active_record/connection_adapters/abstract/transaction.rb +323 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +761 -0
- data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +821 -0
- data/lib/active_record/connection_adapters/column.rb +95 -0
- data/lib/active_record/connection_adapters/connection_specification.rb +297 -0
- data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +29 -0
- data/lib/active_record/connection_adapters/mysql/column.rb +27 -0
- data/lib/active_record/connection_adapters/mysql/database_statements.rb +200 -0
- data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +72 -0
- data/lib/active_record/connection_adapters/mysql/quoting.rb +81 -0
- data/lib/active_record/connection_adapters/mysql/schema_creation.rb +72 -0
- data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +95 -0
- data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +88 -0
- data/lib/active_record/connection_adapters/mysql/schema_statements.rb +264 -0
- data/lib/active_record/connection_adapters/mysql/type_metadata.rb +31 -0
- data/lib/active_record/connection_adapters/mysql2_adapter.rb +146 -0
- data/lib/active_record/connection_adapters/postgresql/column.rb +30 -0
- data/lib/active_record/connection_adapters/postgresql/database_statements.rb +182 -0
- data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +44 -0
- data/lib/active_record/connection_adapters/postgresql/oid.rb +34 -0
- data/lib/active_record/connection_adapters/postgresql/oid/array.rb +92 -0
- data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +53 -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 +113 -0
- data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +26 -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/quoting.rb +205 -0
- data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +43 -0
- data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +76 -0
- data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +222 -0
- data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +50 -0
- data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +776 -0
- data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +36 -0
- data/lib/active_record/connection_adapters/postgresql/utils.rb +81 -0
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +949 -0
- data/lib/active_record/connection_adapters/schema_cache.rb +141 -0
- data/lib/active_record/connection_adapters/sql_type_metadata.rb +37 -0
- data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +118 -0
- data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +21 -0
- data/lib/active_record/connection_adapters/sqlite3/quoting.rb +103 -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 +137 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +557 -0
- data/lib/active_record/connection_adapters/statement_pool.rb +61 -0
- data/lib/active_record/connection_handling.rb +267 -0
- data/lib/active_record/core.rb +599 -0
- data/lib/active_record/counter_cache.rb +193 -0
- data/lib/active_record/database_configurations.rb +233 -0
- data/lib/active_record/database_configurations/database_config.rb +37 -0
- data/lib/active_record/database_configurations/hash_config.rb +50 -0
- data/lib/active_record/database_configurations/url_config.rb +79 -0
- data/lib/active_record/define_callbacks.rb +22 -0
- data/lib/active_record/dynamic_matchers.rb +122 -0
- data/lib/active_record/enum.rb +274 -0
- data/lib/active_record/errors.rb +388 -0
- data/lib/active_record/explain.rb +50 -0
- data/lib/active_record/explain_registry.rb +32 -0
- data/lib/active_record/explain_subscriber.rb +34 -0
- data/lib/active_record/fixture_set/file.rb +82 -0
- data/lib/active_record/fixture_set/model_metadata.rb +33 -0
- data/lib/active_record/fixture_set/render_context.rb +17 -0
- data/lib/active_record/fixture_set/table_row.rb +153 -0
- data/lib/active_record/fixture_set/table_rows.rb +47 -0
- data/lib/active_record/fixtures.rb +738 -0
- data/lib/active_record/gem_version.rb +17 -0
- data/lib/active_record/inheritance.rb +293 -0
- data/lib/active_record/insert_all.rb +179 -0
- data/lib/active_record/integration.rb +207 -0
- data/lib/active_record/internal_metadata.rb +53 -0
- data/lib/active_record/legacy_yaml_adapter.rb +48 -0
- data/lib/active_record/locale/en.yml +48 -0
- data/lib/active_record/locking/optimistic.rb +197 -0
- data/lib/active_record/locking/pessimistic.rb +89 -0
- data/lib/active_record/log_subscriber.rb +118 -0
- data/lib/active_record/middleware/database_selector.rb +75 -0
- data/lib/active_record/middleware/database_selector/resolver.rb +92 -0
- data/lib/active_record/middleware/database_selector/resolver/session.rb +45 -0
- data/lib/active_record/migration.rb +1397 -0
- data/lib/active_record/migration/command_recorder.rb +284 -0
- data/lib/active_record/migration/compatibility.rb +244 -0
- data/lib/active_record/migration/join_table.rb +17 -0
- data/lib/active_record/model_schema.rb +542 -0
- data/lib/active_record/nested_attributes.rb +600 -0
- data/lib/active_record/no_touching.rb +65 -0
- data/lib/active_record/null_relation.rb +68 -0
- data/lib/active_record/persistence.rb +967 -0
- data/lib/active_record/query_cache.rb +52 -0
- data/lib/active_record/querying.rb +82 -0
- data/lib/active_record/railtie.rb +263 -0
- data/lib/active_record/railties/collection_cache_association_loading.rb +34 -0
- data/lib/active_record/railties/console_sandbox.rb +7 -0
- data/lib/active_record/railties/controller_runtime.rb +51 -0
- data/lib/active_record/railties/databases.rake +527 -0
- data/lib/active_record/readonly_attributes.rb +24 -0
- data/lib/active_record/reflection.rb +1042 -0
- data/lib/active_record/relation.rb +859 -0
- data/lib/active_record/relation/batches.rb +290 -0
- data/lib/active_record/relation/batches/batch_enumerator.rb +69 -0
- data/lib/active_record/relation/calculations.rb +424 -0
- data/lib/active_record/relation/delegation.rb +130 -0
- data/lib/active_record/relation/finder_methods.rb +552 -0
- data/lib/active_record/relation/from_clause.rb +26 -0
- data/lib/active_record/relation/merger.rb +184 -0
- data/lib/active_record/relation/predicate_builder.rb +150 -0
- data/lib/active_record/relation/predicate_builder/array_handler.rb +49 -0
- data/lib/active_record/relation/predicate_builder/association_query_value.rb +43 -0
- data/lib/active_record/relation/predicate_builder/base_handler.rb +18 -0
- data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +19 -0
- data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +53 -0
- data/lib/active_record/relation/predicate_builder/range_handler.rb +22 -0
- data/lib/active_record/relation/predicate_builder/relation_handler.rb +19 -0
- data/lib/active_record/relation/query_attribute.rb +50 -0
- data/lib/active_record/relation/query_methods.rb +1359 -0
- data/lib/active_record/relation/record_fetch_warning.rb +51 -0
- data/lib/active_record/relation/spawn_methods.rb +77 -0
- data/lib/active_record/relation/where_clause.rb +190 -0
- data/lib/active_record/relation/where_clause_factory.rb +33 -0
- data/lib/active_record/result.rb +168 -0
- data/lib/active_record/runtime_registry.rb +24 -0
- data/lib/active_record/sanitization.rb +214 -0
- data/lib/active_record/schema.rb +61 -0
- data/lib/active_record/schema_dumper.rb +270 -0
- data/lib/active_record/schema_migration.rb +60 -0
- data/lib/active_record/scoping.rb +106 -0
- data/lib/active_record/scoping/default.rb +151 -0
- data/lib/active_record/scoping/named.rb +217 -0
- data/lib/active_record/secure_token.rb +40 -0
- data/lib/active_record/serialization.rb +22 -0
- data/lib/active_record/statement_cache.rb +148 -0
- data/lib/active_record/store.rb +290 -0
- data/lib/active_record/suppressor.rb +61 -0
- data/lib/active_record/table_metadata.rb +75 -0
- data/lib/active_record/tasks/database_tasks.rb +506 -0
- data/lib/active_record/tasks/mysql_database_tasks.rb +115 -0
- data/lib/active_record/tasks/postgresql_database_tasks.rb +141 -0
- data/lib/active_record/tasks/sqlite_database_tasks.rb +77 -0
- data/lib/active_record/test_databases.rb +23 -0
- data/lib/active_record/test_fixtures.rb +224 -0
- data/lib/active_record/timestamp.rb +167 -0
- data/lib/active_record/touch_later.rb +66 -0
- data/lib/active_record/transactions.rb +493 -0
- data/lib/active_record/translation.rb +24 -0
- data/lib/active_record/type.rb +78 -0
- data/lib/active_record/type/adapter_specific_registry.rb +129 -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_caster.rb +9 -0
- data/lib/active_record/type_caster/connection.rb +34 -0
- data/lib/active_record/type_caster/map.rb +20 -0
- data/lib/active_record/validations.rb +94 -0
- data/lib/active_record/validations/absence.rb +25 -0
- data/lib/active_record/validations/associated.rb +60 -0
- 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 +226 -0
- data/lib/active_record/version.rb +10 -0
- data/lib/arel.rb +51 -0
- data/lib/arel/alias_predication.rb +9 -0
- data/lib/arel/attributes.rb +22 -0
- data/lib/arel/attributes/attribute.rb +37 -0
- data/lib/arel/collectors/bind.rb +24 -0
- data/lib/arel/collectors/composite.rb +31 -0
- data/lib/arel/collectors/plain_string.rb +20 -0
- data/lib/arel/collectors/sql_string.rb +20 -0
- data/lib/arel/collectors/substitute_binds.rb +28 -0
- data/lib/arel/crud.rb +42 -0
- data/lib/arel/delete_manager.rb +18 -0
- data/lib/arel/errors.rb +9 -0
- data/lib/arel/expressions.rb +29 -0
- data/lib/arel/factory_methods.rb +49 -0
- data/lib/arel/insert_manager.rb +49 -0
- data/lib/arel/math.rb +45 -0
- data/lib/arel/nodes.rb +68 -0
- data/lib/arel/nodes/and.rb +32 -0
- data/lib/arel/nodes/ascending.rb +23 -0
- data/lib/arel/nodes/binary.rb +52 -0
- data/lib/arel/nodes/bind_param.rb +36 -0
- data/lib/arel/nodes/case.rb +55 -0
- data/lib/arel/nodes/casted.rb +50 -0
- data/lib/arel/nodes/comment.rb +29 -0
- data/lib/arel/nodes/count.rb +12 -0
- data/lib/arel/nodes/delete_statement.rb +45 -0
- data/lib/arel/nodes/descending.rb +23 -0
- data/lib/arel/nodes/equality.rb +18 -0
- data/lib/arel/nodes/extract.rb +24 -0
- data/lib/arel/nodes/false.rb +16 -0
- data/lib/arel/nodes/full_outer_join.rb +8 -0
- data/lib/arel/nodes/function.rb +44 -0
- data/lib/arel/nodes/grouping.rb +8 -0
- data/lib/arel/nodes/in.rb +8 -0
- data/lib/arel/nodes/infix_operation.rb +80 -0
- data/lib/arel/nodes/inner_join.rb +8 -0
- data/lib/arel/nodes/insert_statement.rb +37 -0
- data/lib/arel/nodes/join_source.rb +20 -0
- data/lib/arel/nodes/matches.rb +18 -0
- data/lib/arel/nodes/named_function.rb +23 -0
- data/lib/arel/nodes/node.rb +50 -0
- data/lib/arel/nodes/node_expression.rb +13 -0
- data/lib/arel/nodes/outer_join.rb +8 -0
- data/lib/arel/nodes/over.rb +15 -0
- data/lib/arel/nodes/regexp.rb +16 -0
- data/lib/arel/nodes/right_outer_join.rb +8 -0
- data/lib/arel/nodes/select_core.rb +67 -0
- data/lib/arel/nodes/select_statement.rb +41 -0
- data/lib/arel/nodes/sql_literal.rb +16 -0
- data/lib/arel/nodes/string_join.rb +11 -0
- data/lib/arel/nodes/table_alias.rb +27 -0
- data/lib/arel/nodes/terminal.rb +16 -0
- data/lib/arel/nodes/true.rb +16 -0
- data/lib/arel/nodes/unary.rb +45 -0
- data/lib/arel/nodes/unary_operation.rb +20 -0
- data/lib/arel/nodes/unqualified_column.rb +22 -0
- data/lib/arel/nodes/update_statement.rb +41 -0
- data/lib/arel/nodes/values_list.rb +9 -0
- data/lib/arel/nodes/window.rb +126 -0
- data/lib/arel/nodes/with.rb +11 -0
- data/lib/arel/order_predications.rb +13 -0
- data/lib/arel/predications.rb +257 -0
- data/lib/arel/select_manager.rb +271 -0
- data/lib/arel/table.rb +110 -0
- data/lib/arel/tree_manager.rb +72 -0
- data/lib/arel/update_manager.rb +34 -0
- data/lib/arel/visitors.rb +20 -0
- data/lib/arel/visitors/depth_first.rb +204 -0
- data/lib/arel/visitors/dot.rb +297 -0
- data/lib/arel/visitors/ibm_db.rb +34 -0
- data/lib/arel/visitors/informix.rb +62 -0
- data/lib/arel/visitors/mssql.rb +157 -0
- data/lib/arel/visitors/mysql.rb +83 -0
- data/lib/arel/visitors/oracle.rb +159 -0
- data/lib/arel/visitors/oracle12.rb +66 -0
- data/lib/arel/visitors/postgresql.rb +110 -0
- data/lib/arel/visitors/sqlite.rb +39 -0
- data/lib/arel/visitors/to_sql.rb +889 -0
- data/lib/arel/visitors/visitor.rb +46 -0
- data/lib/arel/visitors/where_sql.rb +23 -0
- data/lib/arel/window_predications.rb +9 -0
- data/lib/rails/generators/active_record.rb +19 -0
- 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.rb +48 -0
- data/lib/rails/generators/active_record/migration/migration_generator.rb +75 -0
- 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 +48 -0
- data/lib/rails/generators/active_record/model/model_generator.rb +49 -0
- data/lib/rails/generators/active_record/model/templates/model.rb.tt +22 -0
- data/lib/rails/generators/active_record/model/templates/module.rb.tt +7 -0
- metadata +415 -0
@@ -0,0 +1,859 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
# = Active Record \Relation
|
5
|
+
class Relation
|
6
|
+
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
|
7
|
+
:order, :joins, :left_outer_joins, :references,
|
8
|
+
:extending, :unscope, :optimizer_hints, :annotate]
|
9
|
+
|
10
|
+
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :reordering,
|
11
|
+
:reverse_order, :distinct, :create_with, :skip_query_cache]
|
12
|
+
|
13
|
+
CLAUSE_METHODS = [:where, :having, :from]
|
14
|
+
INVALID_METHODS_FOR_DELETE_ALL = [:distinct, :group, :having]
|
15
|
+
|
16
|
+
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS + CLAUSE_METHODS
|
17
|
+
|
18
|
+
include Enumerable
|
19
|
+
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
|
20
|
+
|
21
|
+
attr_reader :table, :klass, :loaded, :predicate_builder
|
22
|
+
attr_accessor :skip_preloading_value
|
23
|
+
alias :model :klass
|
24
|
+
alias :loaded? :loaded
|
25
|
+
alias :locked? :lock_value
|
26
|
+
|
27
|
+
def initialize(klass, table: klass.arel_table, predicate_builder: klass.predicate_builder, values: {})
|
28
|
+
@klass = klass
|
29
|
+
@table = table
|
30
|
+
@values = values
|
31
|
+
@offsets = {}
|
32
|
+
@loaded = false
|
33
|
+
@predicate_builder = predicate_builder
|
34
|
+
@delegate_to_klass = false
|
35
|
+
end
|
36
|
+
|
37
|
+
def initialize_copy(other)
|
38
|
+
@values = @values.dup
|
39
|
+
reset
|
40
|
+
end
|
41
|
+
|
42
|
+
def arel_attribute(name) # :nodoc:
|
43
|
+
klass.arel_attribute(name, table)
|
44
|
+
end
|
45
|
+
|
46
|
+
def bind_attribute(name, value) # :nodoc:
|
47
|
+
if reflection = klass._reflect_on_association(name)
|
48
|
+
name = reflection.foreign_key
|
49
|
+
value = value.read_attribute(reflection.klass.primary_key) unless value.nil?
|
50
|
+
end
|
51
|
+
|
52
|
+
attr = arel_attribute(name)
|
53
|
+
bind = predicate_builder.build_bind_attribute(attr.name, value)
|
54
|
+
yield attr, bind
|
55
|
+
end
|
56
|
+
|
57
|
+
# Initializes new record from relation while maintaining the current
|
58
|
+
# scope.
|
59
|
+
#
|
60
|
+
# Expects arguments in the same format as {ActiveRecord::Base.new}[rdoc-ref:Core.new].
|
61
|
+
#
|
62
|
+
# users = User.where(name: 'DHH')
|
63
|
+
# user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
|
64
|
+
#
|
65
|
+
# You can also pass a block to new with the new record as argument:
|
66
|
+
#
|
67
|
+
# user = users.new { |user| user.name = 'Oscar' }
|
68
|
+
# user.name # => Oscar
|
69
|
+
def new(attributes = nil, &block)
|
70
|
+
block = _deprecated_scope_block("new", &block)
|
71
|
+
scoping { klass.new(attributes, &block) }
|
72
|
+
end
|
73
|
+
|
74
|
+
alias build new
|
75
|
+
|
76
|
+
# Tries to create a new record with the same scoped attributes
|
77
|
+
# defined in the relation. Returns the initialized object if validation fails.
|
78
|
+
#
|
79
|
+
# Expects arguments in the same format as
|
80
|
+
# {ActiveRecord::Base.create}[rdoc-ref:Persistence::ClassMethods#create].
|
81
|
+
#
|
82
|
+
# ==== Examples
|
83
|
+
#
|
84
|
+
# users = User.where(name: 'Oscar')
|
85
|
+
# users.create # => #<User id: 3, name: "Oscar", ...>
|
86
|
+
#
|
87
|
+
# users.create(name: 'fxn')
|
88
|
+
# users.create # => #<User id: 4, name: "fxn", ...>
|
89
|
+
#
|
90
|
+
# users.create { |user| user.name = 'tenderlove' }
|
91
|
+
# # => #<User id: 5, name: "tenderlove", ...>
|
92
|
+
#
|
93
|
+
# users.create(name: nil) # validation on name
|
94
|
+
# # => #<User id: nil, name: nil, ...>
|
95
|
+
def create(attributes = nil, &block)
|
96
|
+
if attributes.is_a?(Array)
|
97
|
+
attributes.collect { |attr| create(attr, &block) }
|
98
|
+
else
|
99
|
+
block = _deprecated_scope_block("create", &block)
|
100
|
+
scoping { klass.create(attributes, &block) }
|
101
|
+
end
|
102
|
+
end
|
103
|
+
|
104
|
+
# Similar to #create, but calls
|
105
|
+
# {create!}[rdoc-ref:Persistence::ClassMethods#create!]
|
106
|
+
# on the base class. Raises an exception if a validation error occurs.
|
107
|
+
#
|
108
|
+
# Expects arguments in the same format as
|
109
|
+
# {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!].
|
110
|
+
def create!(attributes = nil, &block)
|
111
|
+
if attributes.is_a?(Array)
|
112
|
+
attributes.collect { |attr| create!(attr, &block) }
|
113
|
+
else
|
114
|
+
block = _deprecated_scope_block("create!", &block)
|
115
|
+
scoping { klass.create!(attributes, &block) }
|
116
|
+
end
|
117
|
+
end
|
118
|
+
|
119
|
+
def first_or_create(attributes = nil, &block) # :nodoc:
|
120
|
+
first || create(attributes, &block)
|
121
|
+
end
|
122
|
+
|
123
|
+
def first_or_create!(attributes = nil, &block) # :nodoc:
|
124
|
+
first || create!(attributes, &block)
|
125
|
+
end
|
126
|
+
|
127
|
+
def first_or_initialize(attributes = nil, &block) # :nodoc:
|
128
|
+
first || new(attributes, &block)
|
129
|
+
end
|
130
|
+
|
131
|
+
# Finds the first record with the given attributes, or creates a record
|
132
|
+
# with the attributes if one is not found:
|
133
|
+
#
|
134
|
+
# # Find the first user named "Penélope" or create a new one.
|
135
|
+
# User.find_or_create_by(first_name: 'Penélope')
|
136
|
+
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
|
137
|
+
#
|
138
|
+
# # Find the first user named "Penélope" or create a new one.
|
139
|
+
# # We already have one so the existing record will be returned.
|
140
|
+
# User.find_or_create_by(first_name: 'Penélope')
|
141
|
+
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
|
142
|
+
#
|
143
|
+
# # Find the first user named "Scarlett" or create a new one with
|
144
|
+
# # a particular last name.
|
145
|
+
# User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
|
146
|
+
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
|
147
|
+
#
|
148
|
+
# This method accepts a block, which is passed down to #create. The last example
|
149
|
+
# above can be alternatively written this way:
|
150
|
+
#
|
151
|
+
# # Find the first user named "Scarlett" or create a new one with a
|
152
|
+
# # different last name.
|
153
|
+
# User.find_or_create_by(first_name: 'Scarlett') do |user|
|
154
|
+
# user.last_name = 'Johansson'
|
155
|
+
# end
|
156
|
+
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
|
157
|
+
#
|
158
|
+
# This method always returns a record, but if creation was attempted and
|
159
|
+
# failed due to validation errors it won't be persisted, you get what
|
160
|
+
# #create returns in such situation.
|
161
|
+
#
|
162
|
+
# Please note <b>this method is not atomic</b>, it runs first a SELECT, and if
|
163
|
+
# there are no results an INSERT is attempted. If there are other threads
|
164
|
+
# or processes there is a race condition between both calls and it could
|
165
|
+
# be the case that you end up with two similar records.
|
166
|
+
#
|
167
|
+
# If this might be a problem for your application, please see #create_or_find_by.
|
168
|
+
def find_or_create_by(attributes, &block)
|
169
|
+
find_by(attributes) || create(attributes, &block)
|
170
|
+
end
|
171
|
+
|
172
|
+
# Like #find_or_create_by, but calls
|
173
|
+
# {create!}[rdoc-ref:Persistence::ClassMethods#create!] so an exception
|
174
|
+
# is raised if the created record is invalid.
|
175
|
+
def find_or_create_by!(attributes, &block)
|
176
|
+
find_by(attributes) || create!(attributes, &block)
|
177
|
+
end
|
178
|
+
|
179
|
+
# Attempts to create a record with the given attributes in a table that has a unique constraint
|
180
|
+
# on one or several of its columns. If a row already exists with one or several of these
|
181
|
+
# unique constraints, the exception such an insertion would normally raise is caught,
|
182
|
+
# and the existing record with those attributes is found using #find_by!.
|
183
|
+
#
|
184
|
+
# This is similar to #find_or_create_by, but avoids the problem of stale reads between the SELECT
|
185
|
+
# and the INSERT, as that method needs to first query the table, then attempt to insert a row
|
186
|
+
# if none is found.
|
187
|
+
#
|
188
|
+
# There are several drawbacks to #create_or_find_by, though:
|
189
|
+
#
|
190
|
+
# * The underlying table must have the relevant columns defined with unique constraints.
|
191
|
+
# * A unique constraint violation may be triggered by only one, or at least less than all,
|
192
|
+
# of the given attributes. This means that the subsequent #find_by! may fail to find a
|
193
|
+
# matching record, which will then raise an <tt>ActiveRecord::RecordNotFound</tt> exception,
|
194
|
+
# rather than a record with the given attributes.
|
195
|
+
# * While we avoid the race condition between SELECT -> INSERT from #find_or_create_by,
|
196
|
+
# we actually have another race condition between INSERT -> SELECT, which can be triggered
|
197
|
+
# if a DELETE between those two statements is run by another client. But for most applications,
|
198
|
+
# that's a significantly less likely condition to hit.
|
199
|
+
# * It relies on exception handling to handle control flow, which may be marginally slower.
|
200
|
+
# * The primary key may auto-increment on each create, even if it fails. This can accelerate
|
201
|
+
# the problem of running out of integers, if the underlying table is still stuck on a primary
|
202
|
+
# key of type int (note: All Rails apps since 5.1+ have defaulted to bigint, which is not liable
|
203
|
+
# to this problem).
|
204
|
+
#
|
205
|
+
# This method will return a record if all given attributes are covered by unique constraints
|
206
|
+
# (unless the INSERT -> DELETE -> SELECT race condition is triggered), but if creation was attempted
|
207
|
+
# and failed due to validation errors it won't be persisted, you get what #create returns in
|
208
|
+
# such situation.
|
209
|
+
def create_or_find_by(attributes, &block)
|
210
|
+
transaction(requires_new: true) { create(attributes, &block) }
|
211
|
+
rescue ActiveRecord::RecordNotUnique
|
212
|
+
find_by!(attributes)
|
213
|
+
end
|
214
|
+
|
215
|
+
# Like #create_or_find_by, but calls
|
216
|
+
# {create!}[rdoc-ref:Persistence::ClassMethods#create!] so an exception
|
217
|
+
# is raised if the created record is invalid.
|
218
|
+
def create_or_find_by!(attributes, &block)
|
219
|
+
transaction(requires_new: true) { create!(attributes, &block) }
|
220
|
+
rescue ActiveRecord::RecordNotUnique
|
221
|
+
find_by!(attributes)
|
222
|
+
end
|
223
|
+
|
224
|
+
# Like #find_or_create_by, but calls {new}[rdoc-ref:Core#new]
|
225
|
+
# instead of {create}[rdoc-ref:Persistence::ClassMethods#create].
|
226
|
+
def find_or_initialize_by(attributes, &block)
|
227
|
+
find_by(attributes) || new(attributes, &block)
|
228
|
+
end
|
229
|
+
|
230
|
+
# Runs EXPLAIN on the query or queries triggered by this relation and
|
231
|
+
# returns the result as a string. The string is formatted imitating the
|
232
|
+
# ones printed by the database shell.
|
233
|
+
#
|
234
|
+
# Note that this method actually runs the queries, since the results of some
|
235
|
+
# are needed by the next ones when eager loading is going on.
|
236
|
+
#
|
237
|
+
# Please see further details in the
|
238
|
+
# {Active Record Query Interface guide}[https://guides.rubyonrails.org/active_record_querying.html#running-explain].
|
239
|
+
def explain
|
240
|
+
exec_explain(collecting_queries_for_explain { exec_queries })
|
241
|
+
end
|
242
|
+
|
243
|
+
# Converts relation objects to Array.
|
244
|
+
def to_ary
|
245
|
+
records.dup
|
246
|
+
end
|
247
|
+
alias to_a to_ary
|
248
|
+
|
249
|
+
def records # :nodoc:
|
250
|
+
load
|
251
|
+
@records
|
252
|
+
end
|
253
|
+
|
254
|
+
# Serializes the relation objects Array.
|
255
|
+
def encode_with(coder)
|
256
|
+
coder.represent_seq(nil, records)
|
257
|
+
end
|
258
|
+
|
259
|
+
# Returns size of the records.
|
260
|
+
def size
|
261
|
+
loaded? ? @records.length : count(:all)
|
262
|
+
end
|
263
|
+
|
264
|
+
# Returns true if there are no records.
|
265
|
+
def empty?
|
266
|
+
return @records.empty? if loaded?
|
267
|
+
!exists?
|
268
|
+
end
|
269
|
+
|
270
|
+
# Returns true if there are no records.
|
271
|
+
def none?
|
272
|
+
return super if block_given?
|
273
|
+
empty?
|
274
|
+
end
|
275
|
+
|
276
|
+
# Returns true if there are any records.
|
277
|
+
def any?
|
278
|
+
return super if block_given?
|
279
|
+
!empty?
|
280
|
+
end
|
281
|
+
|
282
|
+
# Returns true if there is exactly one record.
|
283
|
+
def one?
|
284
|
+
return super if block_given?
|
285
|
+
limit_value ? records.one? : size == 1
|
286
|
+
end
|
287
|
+
|
288
|
+
# Returns true if there is more than one record.
|
289
|
+
def many?
|
290
|
+
return super if block_given?
|
291
|
+
limit_value ? records.many? : size > 1
|
292
|
+
end
|
293
|
+
|
294
|
+
# Returns a stable cache key that can be used to identify this query.
|
295
|
+
# The cache key is built with a fingerprint of the SQL query.
|
296
|
+
#
|
297
|
+
# Product.where("name like ?", "%Cosmic Encounter%").cache_key
|
298
|
+
# # => "products/query-1850ab3d302391b85b8693e941286659"
|
299
|
+
#
|
300
|
+
# If ActiveRecord::Base.collection_cache_versioning is turned off, as it was
|
301
|
+
# in Rails 6.0 and earlier, the cache key will also include a version.
|
302
|
+
#
|
303
|
+
# ActiveRecord::Base.collection_cache_versioning = false
|
304
|
+
# Product.where("name like ?", "%Cosmic Encounter%").cache_key
|
305
|
+
# # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000"
|
306
|
+
#
|
307
|
+
# You can also pass a custom timestamp column to fetch the timestamp of the
|
308
|
+
# last updated record.
|
309
|
+
#
|
310
|
+
# Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at)
|
311
|
+
def cache_key(timestamp_column = :updated_at)
|
312
|
+
@cache_keys ||= {}
|
313
|
+
@cache_keys[timestamp_column] ||= klass.collection_cache_key(self, timestamp_column)
|
314
|
+
end
|
315
|
+
|
316
|
+
def compute_cache_key(timestamp_column = :updated_at) # :nodoc:
|
317
|
+
query_signature = ActiveSupport::Digest.hexdigest(to_sql)
|
318
|
+
key = "#{klass.model_name.cache_key}/query-#{query_signature}"
|
319
|
+
|
320
|
+
if cache_version(timestamp_column)
|
321
|
+
key
|
322
|
+
else
|
323
|
+
"#{key}-#{compute_cache_version(timestamp_column)}"
|
324
|
+
end
|
325
|
+
end
|
326
|
+
private :compute_cache_key
|
327
|
+
|
328
|
+
# Returns a cache version that can be used together with the cache key to form
|
329
|
+
# a recyclable caching scheme. The cache version is built with the number of records
|
330
|
+
# matching the query, and the timestamp of the last updated record. When a new record
|
331
|
+
# comes to match the query, or any of the existing records is updated or deleted,
|
332
|
+
# the cache version changes.
|
333
|
+
#
|
334
|
+
# If the collection is loaded, the method will iterate through the records
|
335
|
+
# to generate the timestamp, otherwise it will trigger one SQL query like:
|
336
|
+
#
|
337
|
+
# SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%')
|
338
|
+
def cache_version(timestamp_column = :updated_at)
|
339
|
+
if collection_cache_versioning
|
340
|
+
@cache_versions ||= {}
|
341
|
+
@cache_versions[timestamp_column] ||= compute_cache_version(timestamp_column)
|
342
|
+
end
|
343
|
+
end
|
344
|
+
|
345
|
+
def compute_cache_version(timestamp_column) # :nodoc:
|
346
|
+
if loaded? || distinct_value
|
347
|
+
size = records.size
|
348
|
+
if size > 0
|
349
|
+
timestamp = max_by(×tamp_column)._read_attribute(timestamp_column)
|
350
|
+
end
|
351
|
+
else
|
352
|
+
collection = eager_loading? ? apply_join_dependency : self
|
353
|
+
|
354
|
+
column = connection.visitor.compile(arel_attribute(timestamp_column))
|
355
|
+
select_values = "COUNT(*) AS #{connection.quote_column_name("size")}, MAX(%s) AS timestamp"
|
356
|
+
|
357
|
+
if collection.has_limit_or_offset?
|
358
|
+
query = collection.select("#{column} AS collection_cache_key_timestamp")
|
359
|
+
subquery_alias = "subquery_for_cache_key"
|
360
|
+
subquery_column = "#{subquery_alias}.collection_cache_key_timestamp"
|
361
|
+
arel = query.build_subquery(subquery_alias, select_values % subquery_column)
|
362
|
+
else
|
363
|
+
query = collection.unscope(:order)
|
364
|
+
query.select_values = [select_values % column]
|
365
|
+
arel = query.arel
|
366
|
+
end
|
367
|
+
|
368
|
+
result = connection.select_one(arel, nil)
|
369
|
+
|
370
|
+
if result
|
371
|
+
column_type = klass.type_for_attribute(timestamp_column)
|
372
|
+
timestamp = column_type.deserialize(result["timestamp"])
|
373
|
+
size = result["size"]
|
374
|
+
else
|
375
|
+
timestamp = nil
|
376
|
+
size = 0
|
377
|
+
end
|
378
|
+
end
|
379
|
+
|
380
|
+
if timestamp
|
381
|
+
"#{size}-#{timestamp.utc.to_s(cache_timestamp_format)}"
|
382
|
+
else
|
383
|
+
"#{size}"
|
384
|
+
end
|
385
|
+
end
|
386
|
+
private :compute_cache_version
|
387
|
+
|
388
|
+
# Scope all queries to the current scope.
|
389
|
+
#
|
390
|
+
# Comment.where(post_id: 1).scoping do
|
391
|
+
# Comment.first
|
392
|
+
# end
|
393
|
+
# # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
|
394
|
+
#
|
395
|
+
# Please check unscoped if you want to remove all previous scopes (including
|
396
|
+
# the default_scope) during the execution of a block.
|
397
|
+
def scoping
|
398
|
+
already_in_scope? ? yield : _scoping(self) { yield }
|
399
|
+
end
|
400
|
+
|
401
|
+
def _exec_scope(name, *args, &block) # :nodoc:
|
402
|
+
@delegate_to_klass = true
|
403
|
+
_scoping(_deprecated_spawn(name)) { instance_exec(*args, &block) || self }
|
404
|
+
ensure
|
405
|
+
@delegate_to_klass = false
|
406
|
+
end
|
407
|
+
|
408
|
+
# Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
|
409
|
+
# statement and sends it straight to the database. It does not instantiate the involved models and it does not
|
410
|
+
# trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
|
411
|
+
# Active Record's normal type casting and serialization.
|
412
|
+
#
|
413
|
+
# Note: As Active Record callbacks are not triggered, this method will not automatically update +updated_at+/+updated_on+ columns.
|
414
|
+
#
|
415
|
+
# ==== Parameters
|
416
|
+
#
|
417
|
+
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
|
418
|
+
#
|
419
|
+
# ==== Examples
|
420
|
+
#
|
421
|
+
# # Update all customers with the given attributes
|
422
|
+
# Customer.update_all wants_email: true
|
423
|
+
#
|
424
|
+
# # Update all books with 'Rails' in their title
|
425
|
+
# Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
|
426
|
+
#
|
427
|
+
# # Update all books that match conditions, but limit it to 5 ordered by date
|
428
|
+
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
|
429
|
+
#
|
430
|
+
# # Update all invoices and set the number column to its id value.
|
431
|
+
# Invoice.update_all('number = id')
|
432
|
+
def update_all(updates)
|
433
|
+
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
|
434
|
+
|
435
|
+
if eager_loading?
|
436
|
+
relation = apply_join_dependency
|
437
|
+
return relation.update_all(updates)
|
438
|
+
end
|
439
|
+
|
440
|
+
stmt = Arel::UpdateManager.new
|
441
|
+
stmt.table(arel.join_sources.empty? ? table : arel.source)
|
442
|
+
stmt.key = arel_attribute(primary_key)
|
443
|
+
stmt.take(arel.limit)
|
444
|
+
stmt.offset(arel.offset)
|
445
|
+
stmt.order(*arel.orders)
|
446
|
+
stmt.wheres = arel.constraints
|
447
|
+
|
448
|
+
if updates.is_a?(Hash)
|
449
|
+
if klass.locking_enabled? &&
|
450
|
+
!updates.key?(klass.locking_column) &&
|
451
|
+
!updates.key?(klass.locking_column.to_sym)
|
452
|
+
attr = arel_attribute(klass.locking_column)
|
453
|
+
updates[attr.name] = _increment_attribute(attr)
|
454
|
+
end
|
455
|
+
stmt.set _substitute_values(updates)
|
456
|
+
else
|
457
|
+
stmt.set Arel.sql(klass.sanitize_sql_for_assignment(updates, table.name))
|
458
|
+
end
|
459
|
+
|
460
|
+
@klass.connection.update stmt, "#{@klass} Update All"
|
461
|
+
end
|
462
|
+
|
463
|
+
def update(id = :all, attributes) # :nodoc:
|
464
|
+
if id == :all
|
465
|
+
each { |record| record.update(attributes) }
|
466
|
+
else
|
467
|
+
klass.update(id, attributes)
|
468
|
+
end
|
469
|
+
end
|
470
|
+
|
471
|
+
def update_counters(counters) # :nodoc:
|
472
|
+
touch = counters.delete(:touch)
|
473
|
+
|
474
|
+
updates = {}
|
475
|
+
counters.each do |counter_name, value|
|
476
|
+
attr = arel_attribute(counter_name)
|
477
|
+
updates[attr.name] = _increment_attribute(attr, value)
|
478
|
+
end
|
479
|
+
|
480
|
+
if touch
|
481
|
+
names = touch if touch != true
|
482
|
+
touch_updates = klass.touch_attributes_with_time(*names)
|
483
|
+
updates.merge!(touch_updates) unless touch_updates.empty?
|
484
|
+
end
|
485
|
+
|
486
|
+
update_all updates
|
487
|
+
end
|
488
|
+
|
489
|
+
# Touches all records in the current relation without instantiating records first with the +updated_at+/+updated_on+ attributes
|
490
|
+
# set to the current time or the time specified.
|
491
|
+
# This method can be passed attribute names and an optional time argument.
|
492
|
+
# If attribute names are passed, they are updated along with +updated_at+/+updated_on+ attributes.
|
493
|
+
# If no time argument is passed, the current time is used as default.
|
494
|
+
#
|
495
|
+
# === Examples
|
496
|
+
#
|
497
|
+
# # Touch all records
|
498
|
+
# Person.all.touch_all
|
499
|
+
# # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670'"
|
500
|
+
#
|
501
|
+
# # Touch multiple records with a custom attribute
|
502
|
+
# Person.all.touch_all(:created_at)
|
503
|
+
# # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670', \"created_at\" = '2018-01-04 22:55:23.132670'"
|
504
|
+
#
|
505
|
+
# # Touch multiple records with a specified time
|
506
|
+
# Person.all.touch_all(time: Time.new(2020, 5, 16, 0, 0, 0))
|
507
|
+
# # => "UPDATE \"people\" SET \"updated_at\" = '2020-05-16 00:00:00'"
|
508
|
+
#
|
509
|
+
# # Touch records with scope
|
510
|
+
# Person.where(name: 'David').touch_all
|
511
|
+
# # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670' WHERE \"people\".\"name\" = 'David'"
|
512
|
+
def touch_all(*names, time: nil)
|
513
|
+
update_all klass.touch_attributes_with_time(*names, time: time)
|
514
|
+
end
|
515
|
+
|
516
|
+
# Destroys the records by instantiating each
|
517
|
+
# record and calling its {#destroy}[rdoc-ref:Persistence#destroy] method.
|
518
|
+
# Each object's callbacks are executed (including <tt>:dependent</tt> association options).
|
519
|
+
# Returns the collection of objects that were destroyed; each will be frozen, to
|
520
|
+
# reflect that no changes should be made (since they can't be persisted).
|
521
|
+
#
|
522
|
+
# Note: Instantiation, callback execution, and deletion of each
|
523
|
+
# record can be time consuming when you're removing many records at
|
524
|
+
# once. It generates at least one SQL +DELETE+ query per record (or
|
525
|
+
# possibly more, to enforce your callbacks). If you want to delete many
|
526
|
+
# rows quickly, without concern for their associations or callbacks, use
|
527
|
+
# #delete_all instead.
|
528
|
+
#
|
529
|
+
# ==== Examples
|
530
|
+
#
|
531
|
+
# Person.where(age: 0..18).destroy_all
|
532
|
+
def destroy_all
|
533
|
+
records.each(&:destroy).tap { reset }
|
534
|
+
end
|
535
|
+
|
536
|
+
# Deletes the records without instantiating the records
|
537
|
+
# first, and hence not calling the {#destroy}[rdoc-ref:Persistence#destroy]
|
538
|
+
# method nor invoking callbacks.
|
539
|
+
# This is a single SQL DELETE statement that goes straight to the database, much more
|
540
|
+
# efficient than #destroy_all. Be careful with relations though, in particular
|
541
|
+
# <tt>:dependent</tt> rules defined on associations are not honored. Returns the
|
542
|
+
# number of rows affected.
|
543
|
+
#
|
544
|
+
# Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
|
545
|
+
#
|
546
|
+
# Both calls delete the affected posts all at once with a single DELETE statement.
|
547
|
+
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
|
548
|
+
# +after_destroy+ callbacks, use the #destroy_all method instead.
|
549
|
+
#
|
550
|
+
# If an invalid method is supplied, #delete_all raises an ActiveRecordError:
|
551
|
+
#
|
552
|
+
# Post.distinct.delete_all
|
553
|
+
# # => ActiveRecord::ActiveRecordError: delete_all doesn't support distinct
|
554
|
+
def delete_all
|
555
|
+
invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select do |method|
|
556
|
+
value = @values[method]
|
557
|
+
method == :distinct ? value : value&.any?
|
558
|
+
end
|
559
|
+
if invalid_methods.any?
|
560
|
+
raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
|
561
|
+
end
|
562
|
+
|
563
|
+
if eager_loading?
|
564
|
+
relation = apply_join_dependency
|
565
|
+
return relation.delete_all
|
566
|
+
end
|
567
|
+
|
568
|
+
stmt = Arel::DeleteManager.new
|
569
|
+
stmt.from(arel.join_sources.empty? ? table : arel.source)
|
570
|
+
stmt.key = arel_attribute(primary_key)
|
571
|
+
stmt.take(arel.limit)
|
572
|
+
stmt.offset(arel.offset)
|
573
|
+
stmt.order(*arel.orders)
|
574
|
+
stmt.wheres = arel.constraints
|
575
|
+
|
576
|
+
affected = @klass.connection.delete(stmt, "#{@klass} Destroy")
|
577
|
+
|
578
|
+
reset
|
579
|
+
affected
|
580
|
+
end
|
581
|
+
|
582
|
+
# Finds and destroys all records matching the specified conditions.
|
583
|
+
# This is short-hand for <tt>relation.where(condition).destroy_all</tt>.
|
584
|
+
# Returns the collection of objects that were destroyed.
|
585
|
+
#
|
586
|
+
# If no record is found, returns empty array.
|
587
|
+
#
|
588
|
+
# Person.destroy_by(id: 13)
|
589
|
+
# Person.destroy_by(name: 'Spartacus', rating: 4)
|
590
|
+
# Person.destroy_by("published_at < ?", 2.weeks.ago)
|
591
|
+
def destroy_by(*args)
|
592
|
+
where(*args).destroy_all
|
593
|
+
end
|
594
|
+
|
595
|
+
# Finds and deletes all records matching the specified conditions.
|
596
|
+
# This is short-hand for <tt>relation.where(condition).delete_all</tt>.
|
597
|
+
# Returns the number of rows affected.
|
598
|
+
#
|
599
|
+
# If no record is found, returns <tt>0</tt> as zero rows were affected.
|
600
|
+
#
|
601
|
+
# Person.delete_by(id: 13)
|
602
|
+
# Person.delete_by(name: 'Spartacus', rating: 4)
|
603
|
+
# Person.delete_by("published_at < ?", 2.weeks.ago)
|
604
|
+
def delete_by(*args)
|
605
|
+
where(*args).delete_all
|
606
|
+
end
|
607
|
+
|
608
|
+
# Causes the records to be loaded from the database if they have not
|
609
|
+
# been loaded already. You can use this if for some reason you need
|
610
|
+
# to explicitly load some records before actually using them. The
|
611
|
+
# return value is the relation itself, not the records.
|
612
|
+
#
|
613
|
+
# Post.where(published: true).load # => #<ActiveRecord::Relation>
|
614
|
+
def load(&block)
|
615
|
+
exec_queries(&block) unless loaded?
|
616
|
+
|
617
|
+
self
|
618
|
+
end
|
619
|
+
|
620
|
+
# Forces reloading of relation.
|
621
|
+
def reload
|
622
|
+
reset
|
623
|
+
load
|
624
|
+
end
|
625
|
+
|
626
|
+
def reset
|
627
|
+
@delegate_to_klass = false
|
628
|
+
@_deprecated_scope_source = nil
|
629
|
+
@to_sql = @arel = @loaded = @should_eager_load = nil
|
630
|
+
@records = [].freeze
|
631
|
+
@offsets = {}
|
632
|
+
self
|
633
|
+
end
|
634
|
+
|
635
|
+
# Returns sql statement for the relation.
|
636
|
+
#
|
637
|
+
# User.where(name: 'Oscar').to_sql
|
638
|
+
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
|
639
|
+
def to_sql
|
640
|
+
@to_sql ||= begin
|
641
|
+
if eager_loading?
|
642
|
+
apply_join_dependency do |relation, join_dependency|
|
643
|
+
relation = join_dependency.apply_column_aliases(relation)
|
644
|
+
relation.to_sql
|
645
|
+
end
|
646
|
+
else
|
647
|
+
conn = klass.connection
|
648
|
+
conn.unprepared_statement { conn.to_sql(arel) }
|
649
|
+
end
|
650
|
+
end
|
651
|
+
end
|
652
|
+
|
653
|
+
# Returns a hash of where conditions.
|
654
|
+
#
|
655
|
+
# User.where(name: 'Oscar').where_values_hash
|
656
|
+
# # => {name: "Oscar"}
|
657
|
+
def where_values_hash(relation_table_name = klass.table_name)
|
658
|
+
where_clause.to_h(relation_table_name)
|
659
|
+
end
|
660
|
+
|
661
|
+
def scope_for_create
|
662
|
+
where_values_hash.merge!(create_with_value.stringify_keys)
|
663
|
+
end
|
664
|
+
|
665
|
+
# Returns true if relation needs eager loading.
|
666
|
+
def eager_loading?
|
667
|
+
@should_eager_load ||=
|
668
|
+
eager_load_values.any? ||
|
669
|
+
includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
|
670
|
+
end
|
671
|
+
|
672
|
+
# Joins that are also marked for preloading. In which case we should just eager load them.
|
673
|
+
# Note that this is a naive implementation because we could have strings and symbols which
|
674
|
+
# represent the same association, but that aren't matched by this. Also, we could have
|
675
|
+
# nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
|
676
|
+
def joined_includes_values
|
677
|
+
includes_values & joins_values
|
678
|
+
end
|
679
|
+
|
680
|
+
# Compares two relations for equality.
|
681
|
+
def ==(other)
|
682
|
+
case other
|
683
|
+
when Associations::CollectionProxy, AssociationRelation
|
684
|
+
self == other.records
|
685
|
+
when Relation
|
686
|
+
other.to_sql == to_sql
|
687
|
+
when Array
|
688
|
+
records == other
|
689
|
+
end
|
690
|
+
end
|
691
|
+
|
692
|
+
def pretty_print(q)
|
693
|
+
q.pp(records)
|
694
|
+
end
|
695
|
+
|
696
|
+
# Returns true if relation is blank.
|
697
|
+
def blank?
|
698
|
+
records.blank?
|
699
|
+
end
|
700
|
+
|
701
|
+
def values
|
702
|
+
@values.dup
|
703
|
+
end
|
704
|
+
|
705
|
+
def inspect
|
706
|
+
subject = loaded? ? records : self
|
707
|
+
entries = subject.take([limit_value, 11].compact.min).map!(&:inspect)
|
708
|
+
|
709
|
+
entries[10] = "..." if entries.size == 11
|
710
|
+
|
711
|
+
"#<#{self.class.name} [#{entries.join(', ')}]>"
|
712
|
+
end
|
713
|
+
|
714
|
+
def empty_scope? # :nodoc:
|
715
|
+
@values == klass.unscoped.values
|
716
|
+
end
|
717
|
+
|
718
|
+
def has_limit_or_offset? # :nodoc:
|
719
|
+
limit_value || offset_value
|
720
|
+
end
|
721
|
+
|
722
|
+
def alias_tracker(joins = [], aliases = nil) # :nodoc:
|
723
|
+
joins += [aliases] if aliases
|
724
|
+
ActiveRecord::Associations::AliasTracker.create(connection, table.name, joins)
|
725
|
+
end
|
726
|
+
|
727
|
+
def preload_associations(records) # :nodoc:
|
728
|
+
preload = preload_values
|
729
|
+
preload += includes_values unless eager_loading?
|
730
|
+
preloader = nil
|
731
|
+
preload.each do |associations|
|
732
|
+
preloader ||= build_preloader
|
733
|
+
preloader.preload records, associations
|
734
|
+
end
|
735
|
+
end
|
736
|
+
|
737
|
+
attr_reader :_deprecated_scope_source # :nodoc:
|
738
|
+
|
739
|
+
protected
|
740
|
+
attr_writer :_deprecated_scope_source # :nodoc:
|
741
|
+
|
742
|
+
def load_records(records)
|
743
|
+
@records = records.freeze
|
744
|
+
@loaded = true
|
745
|
+
end
|
746
|
+
|
747
|
+
def null_relation? # :nodoc:
|
748
|
+
is_a?(NullRelation)
|
749
|
+
end
|
750
|
+
|
751
|
+
private
|
752
|
+
def already_in_scope?
|
753
|
+
@delegate_to_klass && begin
|
754
|
+
scope = klass.current_scope(true)
|
755
|
+
scope && !scope._deprecated_scope_source
|
756
|
+
end
|
757
|
+
end
|
758
|
+
|
759
|
+
def _deprecated_spawn(name)
|
760
|
+
spawn.tap { |scope| scope._deprecated_scope_source = name }
|
761
|
+
end
|
762
|
+
|
763
|
+
def _deprecated_scope_block(name, &block)
|
764
|
+
-> record do
|
765
|
+
klass.current_scope = _deprecated_spawn(name)
|
766
|
+
yield record if block_given?
|
767
|
+
end
|
768
|
+
end
|
769
|
+
|
770
|
+
def _scoping(scope)
|
771
|
+
previous, klass.current_scope = klass.current_scope(true), scope
|
772
|
+
yield
|
773
|
+
ensure
|
774
|
+
klass.current_scope = previous
|
775
|
+
end
|
776
|
+
|
777
|
+
def _substitute_values(values)
|
778
|
+
values.map do |name, value|
|
779
|
+
attr = arel_attribute(name)
|
780
|
+
unless Arel.arel_node?(value)
|
781
|
+
type = klass.type_for_attribute(attr.name)
|
782
|
+
value = predicate_builder.build_bind_attribute(attr.name, type.cast(value))
|
783
|
+
end
|
784
|
+
[attr, value]
|
785
|
+
end
|
786
|
+
end
|
787
|
+
|
788
|
+
def _increment_attribute(attribute, value = 1)
|
789
|
+
bind = predicate_builder.build_bind_attribute(attribute.name, value.abs)
|
790
|
+
expr = table.coalesce(Arel::Nodes::UnqualifiedColumn.new(attribute), 0)
|
791
|
+
expr = value < 0 ? expr - bind : expr + bind
|
792
|
+
expr.expr
|
793
|
+
end
|
794
|
+
|
795
|
+
def exec_queries(&block)
|
796
|
+
skip_query_cache_if_necessary do
|
797
|
+
@records =
|
798
|
+
if eager_loading?
|
799
|
+
apply_join_dependency do |relation, join_dependency|
|
800
|
+
if relation.null_relation?
|
801
|
+
[]
|
802
|
+
else
|
803
|
+
relation = join_dependency.apply_column_aliases(relation)
|
804
|
+
rows = connection.select_all(relation.arel, "SQL")
|
805
|
+
join_dependency.instantiate(rows, &block)
|
806
|
+
end.freeze
|
807
|
+
end
|
808
|
+
else
|
809
|
+
klass.find_by_sql(arel, &block).freeze
|
810
|
+
end
|
811
|
+
|
812
|
+
preload_associations(@records) unless skip_preloading_value
|
813
|
+
|
814
|
+
@records.each(&:readonly!) if readonly_value
|
815
|
+
|
816
|
+
@loaded = true
|
817
|
+
@records
|
818
|
+
end
|
819
|
+
end
|
820
|
+
|
821
|
+
def skip_query_cache_if_necessary
|
822
|
+
if skip_query_cache_value
|
823
|
+
uncached do
|
824
|
+
yield
|
825
|
+
end
|
826
|
+
else
|
827
|
+
yield
|
828
|
+
end
|
829
|
+
end
|
830
|
+
|
831
|
+
def build_preloader
|
832
|
+
ActiveRecord::Associations::Preloader.new
|
833
|
+
end
|
834
|
+
|
835
|
+
def references_eager_loaded_tables?
|
836
|
+
joined_tables = arel.join_sources.map do |join|
|
837
|
+
if join.is_a?(Arel::Nodes::StringJoin)
|
838
|
+
tables_in_string(join.left)
|
839
|
+
else
|
840
|
+
[join.left.table_name, join.left.table_alias]
|
841
|
+
end
|
842
|
+
end
|
843
|
+
|
844
|
+
joined_tables += [table.name, table.table_alias]
|
845
|
+
|
846
|
+
# always convert table names to downcase as in Oracle quoted table names are in uppercase
|
847
|
+
joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
|
848
|
+
|
849
|
+
(references_values - joined_tables).any?
|
850
|
+
end
|
851
|
+
|
852
|
+
def tables_in_string(string)
|
853
|
+
return [] if string.blank?
|
854
|
+
# always convert table names to downcase as in Oracle quoted table names are in uppercase
|
855
|
+
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
|
856
|
+
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"]
|
857
|
+
end
|
858
|
+
end
|
859
|
+
end
|