activerecord 6.0.1
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 +1086 -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 +49 -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 +340 -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 +262 -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 +512 -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 +1175 -0
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +85 -0
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +516 -0
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +155 -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 +772 -0
- data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +830 -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 +202 -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 +184 -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 +953 -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 +120 -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 +561 -0
- data/lib/active_record/connection_adapters/statement_pool.rb +61 -0
- data/lib/active_record/connection_handling.rb +274 -0
- data/lib/active_record/core.rb +603 -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 +88 -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 +545 -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 +860 -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 +561 -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 +1371 -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 +58 -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 +418 -0
@@ -0,0 +1,18 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
class PredicateBuilder
|
5
|
+
class BaseHandler # :nodoc:
|
6
|
+
def initialize(predicate_builder)
|
7
|
+
@predicate_builder = predicate_builder
|
8
|
+
end
|
9
|
+
|
10
|
+
def call(attribute, value)
|
11
|
+
predicate_builder.build(attribute, value.id)
|
12
|
+
end
|
13
|
+
|
14
|
+
private
|
15
|
+
attr_reader :predicate_builder
|
16
|
+
end
|
17
|
+
end
|
18
|
+
end
|
@@ -0,0 +1,19 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
class PredicateBuilder
|
5
|
+
class BasicObjectHandler # :nodoc:
|
6
|
+
def initialize(predicate_builder)
|
7
|
+
@predicate_builder = predicate_builder
|
8
|
+
end
|
9
|
+
|
10
|
+
def call(attribute, value)
|
11
|
+
bind = predicate_builder.build_bind_attribute(attribute.name, value)
|
12
|
+
attribute.eq(bind)
|
13
|
+
end
|
14
|
+
|
15
|
+
private
|
16
|
+
attr_reader :predicate_builder
|
17
|
+
end
|
18
|
+
end
|
19
|
+
end
|
@@ -0,0 +1,53 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
class PredicateBuilder
|
5
|
+
class PolymorphicArrayValue # :nodoc:
|
6
|
+
def initialize(associated_table, values)
|
7
|
+
@associated_table = associated_table
|
8
|
+
@values = values
|
9
|
+
end
|
10
|
+
|
11
|
+
def queries
|
12
|
+
type_to_ids_mapping.map do |type, ids|
|
13
|
+
{
|
14
|
+
associated_table.association_foreign_type.to_s => type,
|
15
|
+
associated_table.association_foreign_key.to_s => ids
|
16
|
+
}
|
17
|
+
end
|
18
|
+
end
|
19
|
+
|
20
|
+
private
|
21
|
+
attr_reader :associated_table, :values
|
22
|
+
|
23
|
+
def type_to_ids_mapping
|
24
|
+
default_hash = Hash.new { |hsh, key| hsh[key] = [] }
|
25
|
+
values.each_with_object(default_hash) do |value, hash|
|
26
|
+
hash[klass(value).polymorphic_name] << convert_to_id(value)
|
27
|
+
end
|
28
|
+
end
|
29
|
+
|
30
|
+
def primary_key(value)
|
31
|
+
associated_table.association_join_primary_key(klass(value))
|
32
|
+
end
|
33
|
+
|
34
|
+
def klass(value)
|
35
|
+
case value
|
36
|
+
when Base
|
37
|
+
value.class
|
38
|
+
when Relation
|
39
|
+
value.klass
|
40
|
+
end
|
41
|
+
end
|
42
|
+
|
43
|
+
def convert_to_id(value)
|
44
|
+
case value
|
45
|
+
when Base
|
46
|
+
value._read_attribute(primary_key(value))
|
47
|
+
when Relation
|
48
|
+
value.select(primary_key(value))
|
49
|
+
end
|
50
|
+
end
|
51
|
+
end
|
52
|
+
end
|
53
|
+
end
|
@@ -0,0 +1,22 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
class PredicateBuilder
|
5
|
+
class RangeHandler # :nodoc:
|
6
|
+
RangeWithBinds = Struct.new(:begin, :end, :exclude_end?)
|
7
|
+
|
8
|
+
def initialize(predicate_builder)
|
9
|
+
@predicate_builder = predicate_builder
|
10
|
+
end
|
11
|
+
|
12
|
+
def call(attribute, value)
|
13
|
+
begin_bind = predicate_builder.build_bind_attribute(attribute.name, value.begin)
|
14
|
+
end_bind = predicate_builder.build_bind_attribute(attribute.name, value.end)
|
15
|
+
attribute.between(RangeWithBinds.new(begin_bind, end_bind, value.exclude_end?))
|
16
|
+
end
|
17
|
+
|
18
|
+
private
|
19
|
+
attr_reader :predicate_builder
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
@@ -0,0 +1,19 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecord
|
4
|
+
class PredicateBuilder
|
5
|
+
class RelationHandler # :nodoc:
|
6
|
+
def call(attribute, value)
|
7
|
+
if value.eager_loading?
|
8
|
+
value = value.send(:apply_join_dependency)
|
9
|
+
end
|
10
|
+
|
11
|
+
if value.select_values.empty?
|
12
|
+
value = value.select(value.arel_attribute(value.klass.primary_key))
|
13
|
+
end
|
14
|
+
|
15
|
+
attribute.in(value.arel)
|
16
|
+
end
|
17
|
+
end
|
18
|
+
end
|
19
|
+
end
|
@@ -0,0 +1,50 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_model/attribute"
|
4
|
+
|
5
|
+
module ActiveRecord
|
6
|
+
class Relation
|
7
|
+
class QueryAttribute < ActiveModel::Attribute # :nodoc:
|
8
|
+
def type_cast(value)
|
9
|
+
value
|
10
|
+
end
|
11
|
+
|
12
|
+
def value_for_database
|
13
|
+
@value_for_database ||= super
|
14
|
+
end
|
15
|
+
|
16
|
+
def with_cast_value(value)
|
17
|
+
QueryAttribute.new(name, value, type)
|
18
|
+
end
|
19
|
+
|
20
|
+
def nil?
|
21
|
+
unless value_before_type_cast.is_a?(StatementCache::Substitute)
|
22
|
+
value_before_type_cast.nil? ||
|
23
|
+
type.respond_to?(:subtype, true) && value_for_database.nil?
|
24
|
+
end
|
25
|
+
rescue ::RangeError
|
26
|
+
end
|
27
|
+
|
28
|
+
def infinite?
|
29
|
+
infinity?(value_before_type_cast) || infinity?(value_for_database)
|
30
|
+
rescue ::RangeError
|
31
|
+
end
|
32
|
+
|
33
|
+
def unboundable?
|
34
|
+
if defined?(@_unboundable)
|
35
|
+
@_unboundable
|
36
|
+
else
|
37
|
+
value_for_database unless value_before_type_cast.is_a?(StatementCache::Substitute)
|
38
|
+
@_unboundable = nil
|
39
|
+
end
|
40
|
+
rescue ::RangeError
|
41
|
+
@_unboundable = type.cast(value_before_type_cast) <=> 0
|
42
|
+
end
|
43
|
+
|
44
|
+
private
|
45
|
+
def infinity?(value)
|
46
|
+
value.respond_to?(:infinite?) && value.infinite?
|
47
|
+
end
|
48
|
+
end
|
49
|
+
end
|
50
|
+
end
|
@@ -0,0 +1,1371 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_record/relation/from_clause"
|
4
|
+
require "active_record/relation/query_attribute"
|
5
|
+
require "active_record/relation/where_clause"
|
6
|
+
require "active_record/relation/where_clause_factory"
|
7
|
+
require "active_model/forbidden_attributes_protection"
|
8
|
+
|
9
|
+
module ActiveRecord
|
10
|
+
module QueryMethods
|
11
|
+
extend ActiveSupport::Concern
|
12
|
+
|
13
|
+
include ActiveModel::ForbiddenAttributesProtection
|
14
|
+
|
15
|
+
# WhereChain objects act as placeholder for queries in which #where does not have any parameter.
|
16
|
+
# In this case, #where must be chained with #not to return a new relation.
|
17
|
+
class WhereChain
|
18
|
+
include ActiveModel::ForbiddenAttributesProtection
|
19
|
+
|
20
|
+
def initialize(scope)
|
21
|
+
@scope = scope
|
22
|
+
end
|
23
|
+
|
24
|
+
# Returns a new relation expressing WHERE + NOT condition according to
|
25
|
+
# the conditions in the arguments.
|
26
|
+
#
|
27
|
+
# #not accepts conditions as a string, array, or hash. See QueryMethods#where for
|
28
|
+
# more details on each format.
|
29
|
+
#
|
30
|
+
# User.where.not("name = 'Jon'")
|
31
|
+
# # SELECT * FROM users WHERE NOT (name = 'Jon')
|
32
|
+
#
|
33
|
+
# User.where.not(["name = ?", "Jon"])
|
34
|
+
# # SELECT * FROM users WHERE NOT (name = 'Jon')
|
35
|
+
#
|
36
|
+
# User.where.not(name: "Jon")
|
37
|
+
# # SELECT * FROM users WHERE name != 'Jon'
|
38
|
+
#
|
39
|
+
# User.where.not(name: nil)
|
40
|
+
# # SELECT * FROM users WHERE name IS NOT NULL
|
41
|
+
#
|
42
|
+
# User.where.not(name: %w(Ko1 Nobu))
|
43
|
+
# # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
|
44
|
+
def not(opts, *rest)
|
45
|
+
opts = sanitize_forbidden_attributes(opts)
|
46
|
+
|
47
|
+
where_clause = @scope.send(:where_clause_factory).build(opts, rest)
|
48
|
+
|
49
|
+
@scope.references!(PredicateBuilder.references(opts)) if Hash === opts
|
50
|
+
|
51
|
+
if not_behaves_as_nor?(opts)
|
52
|
+
ActiveSupport::Deprecation.warn(<<~MSG.squish)
|
53
|
+
NOT conditions will no longer behave as NOR in Rails 6.1.
|
54
|
+
To continue using NOR conditions, NOT each conditions manually
|
55
|
+
(`#{ opts.keys.map { |key| ".where.not(#{key.inspect} => ...)" }.join }`).
|
56
|
+
MSG
|
57
|
+
@scope.where_clause += where_clause.invert(:nor)
|
58
|
+
else
|
59
|
+
@scope.where_clause += where_clause.invert
|
60
|
+
end
|
61
|
+
|
62
|
+
@scope
|
63
|
+
end
|
64
|
+
|
65
|
+
private
|
66
|
+
def not_behaves_as_nor?(opts)
|
67
|
+
opts.is_a?(Hash) && opts.size > 1
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
FROZEN_EMPTY_ARRAY = [].freeze
|
72
|
+
FROZEN_EMPTY_HASH = {}.freeze
|
73
|
+
|
74
|
+
Relation::VALUE_METHODS.each do |name|
|
75
|
+
method_name = \
|
76
|
+
case name
|
77
|
+
when *Relation::MULTI_VALUE_METHODS then "#{name}_values"
|
78
|
+
when *Relation::SINGLE_VALUE_METHODS then "#{name}_value"
|
79
|
+
when *Relation::CLAUSE_METHODS then "#{name}_clause"
|
80
|
+
end
|
81
|
+
class_eval <<-CODE, __FILE__, __LINE__ + 1
|
82
|
+
def #{method_name} # def includes_values
|
83
|
+
default = DEFAULT_VALUES[:#{name}] # default = DEFAULT_VALUES[:includes]
|
84
|
+
@values.fetch(:#{name}, default) # @values.fetch(:includes, default)
|
85
|
+
end # end
|
86
|
+
|
87
|
+
def #{method_name}=(value) # def includes_values=(value)
|
88
|
+
assert_mutability! # assert_mutability!
|
89
|
+
@values[:#{name}] = value # @values[:includes] = value
|
90
|
+
end # end
|
91
|
+
CODE
|
92
|
+
end
|
93
|
+
|
94
|
+
alias extensions extending_values
|
95
|
+
|
96
|
+
# Specify relationships to be included in the result set. For
|
97
|
+
# example:
|
98
|
+
#
|
99
|
+
# users = User.includes(:address)
|
100
|
+
# users.each do |user|
|
101
|
+
# user.address.city
|
102
|
+
# end
|
103
|
+
#
|
104
|
+
# allows you to access the +address+ attribute of the +User+ model without
|
105
|
+
# firing an additional query. This will often result in a
|
106
|
+
# performance improvement over a simple join.
|
107
|
+
#
|
108
|
+
# You can also specify multiple relationships, like this:
|
109
|
+
#
|
110
|
+
# users = User.includes(:address, :friends)
|
111
|
+
#
|
112
|
+
# Loading nested relationships is possible using a Hash:
|
113
|
+
#
|
114
|
+
# users = User.includes(:address, friends: [:address, :followers])
|
115
|
+
#
|
116
|
+
# === conditions
|
117
|
+
#
|
118
|
+
# If you want to add string conditions to your included models, you'll have
|
119
|
+
# to explicitly reference them. For example:
|
120
|
+
#
|
121
|
+
# User.includes(:posts).where('posts.name = ?', 'example')
|
122
|
+
#
|
123
|
+
# Will throw an error, but this will work:
|
124
|
+
#
|
125
|
+
# User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
|
126
|
+
#
|
127
|
+
# Note that #includes works with association names while #references needs
|
128
|
+
# the actual table name.
|
129
|
+
#
|
130
|
+
# If you pass the conditions via hash, you don't need to call #references
|
131
|
+
# explicitly, as #where references the tables for you. For example, this
|
132
|
+
# will work correctly:
|
133
|
+
#
|
134
|
+
# User.includes(:posts).where(posts: { name: 'example' })
|
135
|
+
def includes(*args)
|
136
|
+
check_if_method_has_arguments!(:includes, args)
|
137
|
+
spawn.includes!(*args)
|
138
|
+
end
|
139
|
+
|
140
|
+
def includes!(*args) # :nodoc:
|
141
|
+
args.reject!(&:blank?)
|
142
|
+
args.flatten!
|
143
|
+
|
144
|
+
self.includes_values |= args
|
145
|
+
self
|
146
|
+
end
|
147
|
+
|
148
|
+
# Forces eager loading by performing a LEFT OUTER JOIN on +args+:
|
149
|
+
#
|
150
|
+
# User.eager_load(:posts)
|
151
|
+
# # SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
|
152
|
+
# # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
|
153
|
+
# # "users"."id"
|
154
|
+
def eager_load(*args)
|
155
|
+
check_if_method_has_arguments!(:eager_load, args)
|
156
|
+
spawn.eager_load!(*args)
|
157
|
+
end
|
158
|
+
|
159
|
+
def eager_load!(*args) # :nodoc:
|
160
|
+
self.eager_load_values += args
|
161
|
+
self
|
162
|
+
end
|
163
|
+
|
164
|
+
# Allows preloading of +args+, in the same way that #includes does:
|
165
|
+
#
|
166
|
+
# User.preload(:posts)
|
167
|
+
# # SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
|
168
|
+
def preload(*args)
|
169
|
+
check_if_method_has_arguments!(:preload, args)
|
170
|
+
spawn.preload!(*args)
|
171
|
+
end
|
172
|
+
|
173
|
+
def preload!(*args) # :nodoc:
|
174
|
+
self.preload_values += args
|
175
|
+
self
|
176
|
+
end
|
177
|
+
|
178
|
+
# Extracts a named +association+ from the relation. The named association is first preloaded,
|
179
|
+
# then the individual association records are collected from the relation. Like so:
|
180
|
+
#
|
181
|
+
# account.memberships.extract_associated(:user)
|
182
|
+
# # => Returns collection of User records
|
183
|
+
#
|
184
|
+
# This is short-hand for:
|
185
|
+
#
|
186
|
+
# account.memberships.preload(:user).collect(&:user)
|
187
|
+
def extract_associated(association)
|
188
|
+
preload(association).collect(&association)
|
189
|
+
end
|
190
|
+
|
191
|
+
# Use to indicate that the given +table_names+ are referenced by an SQL string,
|
192
|
+
# and should therefore be JOINed in any query rather than loaded separately.
|
193
|
+
# This method only works in conjunction with #includes.
|
194
|
+
# See #includes for more details.
|
195
|
+
#
|
196
|
+
# User.includes(:posts).where("posts.name = 'foo'")
|
197
|
+
# # Doesn't JOIN the posts table, resulting in an error.
|
198
|
+
#
|
199
|
+
# User.includes(:posts).where("posts.name = 'foo'").references(:posts)
|
200
|
+
# # Query now knows the string references posts, so adds a JOIN
|
201
|
+
def references(*table_names)
|
202
|
+
check_if_method_has_arguments!(:references, table_names)
|
203
|
+
spawn.references!(*table_names)
|
204
|
+
end
|
205
|
+
|
206
|
+
def references!(*table_names) # :nodoc:
|
207
|
+
table_names.flatten!
|
208
|
+
table_names.map!(&:to_s)
|
209
|
+
|
210
|
+
self.references_values |= table_names
|
211
|
+
self
|
212
|
+
end
|
213
|
+
|
214
|
+
# Works in two unique ways.
|
215
|
+
#
|
216
|
+
# First: takes a block so it can be used just like <tt>Array#select</tt>.
|
217
|
+
#
|
218
|
+
# Model.all.select { |m| m.field == value }
|
219
|
+
#
|
220
|
+
# This will build an array of objects from the database for the scope,
|
221
|
+
# converting them into an array and iterating through them using
|
222
|
+
# <tt>Array#select</tt>.
|
223
|
+
#
|
224
|
+
# Second: Modifies the SELECT statement for the query so that only certain
|
225
|
+
# fields are retrieved:
|
226
|
+
#
|
227
|
+
# Model.select(:field)
|
228
|
+
# # => [#<Model id: nil, field: "value">]
|
229
|
+
#
|
230
|
+
# Although in the above example it looks as though this method returns an
|
231
|
+
# array, it actually returns a relation object and can have other query
|
232
|
+
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
|
233
|
+
#
|
234
|
+
# The argument to the method can also be an array of fields.
|
235
|
+
#
|
236
|
+
# Model.select(:field, :other_field, :and_one_more)
|
237
|
+
# # => [#<Model id: nil, field: "value", other_field: "value", and_one_more: "value">]
|
238
|
+
#
|
239
|
+
# You can also use one or more strings, which will be used unchanged as SELECT fields.
|
240
|
+
#
|
241
|
+
# Model.select('field AS field_one', 'other_field AS field_two')
|
242
|
+
# # => [#<Model id: nil, field: "value", other_field: "value">]
|
243
|
+
#
|
244
|
+
# If an alias was specified, it will be accessible from the resulting objects:
|
245
|
+
#
|
246
|
+
# Model.select('field AS field_one').first.field_one
|
247
|
+
# # => "value"
|
248
|
+
#
|
249
|
+
# Accessing attributes of an object that do not have fields retrieved by a select
|
250
|
+
# except +id+ will throw ActiveModel::MissingAttributeError:
|
251
|
+
#
|
252
|
+
# Model.select(:field).first.other_field
|
253
|
+
# # => ActiveModel::MissingAttributeError: missing attribute: other_field
|
254
|
+
def select(*fields)
|
255
|
+
if block_given?
|
256
|
+
if fields.any?
|
257
|
+
raise ArgumentError, "`select' with block doesn't take arguments."
|
258
|
+
end
|
259
|
+
|
260
|
+
return super()
|
261
|
+
end
|
262
|
+
|
263
|
+
raise ArgumentError, "Call `select' with at least one field" if fields.empty?
|
264
|
+
spawn._select!(*fields)
|
265
|
+
end
|
266
|
+
|
267
|
+
def _select!(*fields) # :nodoc:
|
268
|
+
fields.reject!(&:blank?)
|
269
|
+
fields.flatten!
|
270
|
+
self.select_values += fields
|
271
|
+
self
|
272
|
+
end
|
273
|
+
|
274
|
+
# Allows you to change a previously set select statement.
|
275
|
+
#
|
276
|
+
# Post.select(:title, :body)
|
277
|
+
# # SELECT `posts`.`title`, `posts`.`body` FROM `posts`
|
278
|
+
#
|
279
|
+
# Post.select(:title, :body).reselect(:created_at)
|
280
|
+
# # SELECT `posts`.`created_at` FROM `posts`
|
281
|
+
#
|
282
|
+
# This is short-hand for <tt>unscope(:select).select(fields)</tt>.
|
283
|
+
# Note that we're unscoping the entire select statement.
|
284
|
+
def reselect(*args)
|
285
|
+
check_if_method_has_arguments!(:reselect, args)
|
286
|
+
spawn.reselect!(*args)
|
287
|
+
end
|
288
|
+
|
289
|
+
# Same as #reselect but operates on relation in-place instead of copying.
|
290
|
+
def reselect!(*args) # :nodoc:
|
291
|
+
self.select_values = args
|
292
|
+
self
|
293
|
+
end
|
294
|
+
|
295
|
+
# Allows to specify a group attribute:
|
296
|
+
#
|
297
|
+
# User.group(:name)
|
298
|
+
# # SELECT "users".* FROM "users" GROUP BY name
|
299
|
+
#
|
300
|
+
# Returns an array with distinct records based on the +group+ attribute:
|
301
|
+
#
|
302
|
+
# User.select([:id, :name])
|
303
|
+
# # => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">]
|
304
|
+
#
|
305
|
+
# User.group(:name)
|
306
|
+
# # => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
|
307
|
+
#
|
308
|
+
# User.group('name AS grouped_name, age')
|
309
|
+
# # => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
|
310
|
+
#
|
311
|
+
# Passing in an array of attributes to group by is also supported.
|
312
|
+
#
|
313
|
+
# User.select([:id, :first_name]).group(:id, :first_name).first(3)
|
314
|
+
# # => [#<User id: 1, first_name: "Bill">, #<User id: 2, first_name: "Earl">, #<User id: 3, first_name: "Beto">]
|
315
|
+
def group(*args)
|
316
|
+
check_if_method_has_arguments!(:group, args)
|
317
|
+
spawn.group!(*args)
|
318
|
+
end
|
319
|
+
|
320
|
+
def group!(*args) # :nodoc:
|
321
|
+
args.flatten!
|
322
|
+
|
323
|
+
self.group_values += args
|
324
|
+
self
|
325
|
+
end
|
326
|
+
|
327
|
+
# Allows to specify an order attribute:
|
328
|
+
#
|
329
|
+
# User.order(:name)
|
330
|
+
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
|
331
|
+
#
|
332
|
+
# User.order(email: :desc)
|
333
|
+
# # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
|
334
|
+
#
|
335
|
+
# User.order(:name, email: :desc)
|
336
|
+
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
|
337
|
+
#
|
338
|
+
# User.order('name')
|
339
|
+
# # SELECT "users".* FROM "users" ORDER BY name
|
340
|
+
#
|
341
|
+
# User.order('name DESC')
|
342
|
+
# # SELECT "users".* FROM "users" ORDER BY name DESC
|
343
|
+
#
|
344
|
+
# User.order('name DESC, email')
|
345
|
+
# # SELECT "users".* FROM "users" ORDER BY name DESC, email
|
346
|
+
def order(*args)
|
347
|
+
check_if_method_has_arguments!(:order, args)
|
348
|
+
spawn.order!(*args)
|
349
|
+
end
|
350
|
+
|
351
|
+
# Same as #order but operates on relation in-place instead of copying.
|
352
|
+
def order!(*args) # :nodoc:
|
353
|
+
preprocess_order_args(args)
|
354
|
+
|
355
|
+
self.order_values += args
|
356
|
+
self
|
357
|
+
end
|
358
|
+
|
359
|
+
# Replaces any existing order defined on the relation with the specified order.
|
360
|
+
#
|
361
|
+
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
|
362
|
+
#
|
363
|
+
# Subsequent calls to order on the same relation will be appended. For example:
|
364
|
+
#
|
365
|
+
# User.order('email DESC').reorder('id ASC').order('name ASC')
|
366
|
+
#
|
367
|
+
# generates a query with 'ORDER BY id ASC, name ASC'.
|
368
|
+
def reorder(*args)
|
369
|
+
check_if_method_has_arguments!(:reorder, args)
|
370
|
+
spawn.reorder!(*args)
|
371
|
+
end
|
372
|
+
|
373
|
+
# Same as #reorder but operates on relation in-place instead of copying.
|
374
|
+
def reorder!(*args) # :nodoc:
|
375
|
+
preprocess_order_args(args) unless args.all?(&:blank?)
|
376
|
+
|
377
|
+
self.reordering_value = true
|
378
|
+
self.order_values = args
|
379
|
+
self
|
380
|
+
end
|
381
|
+
|
382
|
+
VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
|
383
|
+
:limit, :offset, :joins, :left_outer_joins, :annotate,
|
384
|
+
:includes, :from, :readonly, :having, :optimizer_hints])
|
385
|
+
|
386
|
+
# Removes an unwanted relation that is already defined on a chain of relations.
|
387
|
+
# This is useful when passing around chains of relations and would like to
|
388
|
+
# modify the relations without reconstructing the entire chain.
|
389
|
+
#
|
390
|
+
# User.order('email DESC').unscope(:order) == User.all
|
391
|
+
#
|
392
|
+
# The method arguments are symbols which correspond to the names of the methods
|
393
|
+
# which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
|
394
|
+
# The method can also be called with multiple arguments. For example:
|
395
|
+
#
|
396
|
+
# User.order('email DESC').select('id').where(name: "John")
|
397
|
+
# .unscope(:order, :select, :where) == User.all
|
398
|
+
#
|
399
|
+
# One can additionally pass a hash as an argument to unscope specific +:where+ values.
|
400
|
+
# This is done by passing a hash with a single key-value pair. The key should be
|
401
|
+
# +:where+ and the value should be the where value to unscope. For example:
|
402
|
+
#
|
403
|
+
# User.where(name: "John", active: true).unscope(where: :name)
|
404
|
+
# == User.where(active: true)
|
405
|
+
#
|
406
|
+
# This method is similar to #except, but unlike
|
407
|
+
# #except, it persists across merges:
|
408
|
+
#
|
409
|
+
# User.order('email').merge(User.except(:order))
|
410
|
+
# == User.order('email')
|
411
|
+
#
|
412
|
+
# User.order('email').merge(User.unscope(:order))
|
413
|
+
# == User.all
|
414
|
+
#
|
415
|
+
# This means it can be used in association definitions:
|
416
|
+
#
|
417
|
+
# has_many :comments, -> { unscope(where: :trashed) }
|
418
|
+
#
|
419
|
+
def unscope(*args)
|
420
|
+
check_if_method_has_arguments!(:unscope, args)
|
421
|
+
spawn.unscope!(*args)
|
422
|
+
end
|
423
|
+
|
424
|
+
def unscope!(*args) # :nodoc:
|
425
|
+
args.flatten!
|
426
|
+
self.unscope_values += args
|
427
|
+
|
428
|
+
args.each do |scope|
|
429
|
+
case scope
|
430
|
+
when Symbol
|
431
|
+
scope = :left_outer_joins if scope == :left_joins
|
432
|
+
if !VALID_UNSCOPING_VALUES.include?(scope)
|
433
|
+
raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
|
434
|
+
end
|
435
|
+
assert_mutability!
|
436
|
+
@values[scope] = DEFAULT_VALUES[scope]
|
437
|
+
when Hash
|
438
|
+
scope.each do |key, target_value|
|
439
|
+
if key != :where
|
440
|
+
raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
|
441
|
+
end
|
442
|
+
|
443
|
+
target_values = Array(target_value).map(&:to_s)
|
444
|
+
self.where_clause = where_clause.except(*target_values)
|
445
|
+
end
|
446
|
+
else
|
447
|
+
raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
|
448
|
+
end
|
449
|
+
end
|
450
|
+
|
451
|
+
self
|
452
|
+
end
|
453
|
+
|
454
|
+
# Performs a joins on +args+. The given symbol(s) should match the name of
|
455
|
+
# the association(s).
|
456
|
+
#
|
457
|
+
# User.joins(:posts)
|
458
|
+
# # SELECT "users".*
|
459
|
+
# # FROM "users"
|
460
|
+
# # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
|
461
|
+
#
|
462
|
+
# Multiple joins:
|
463
|
+
#
|
464
|
+
# User.joins(:posts, :account)
|
465
|
+
# # SELECT "users".*
|
466
|
+
# # FROM "users"
|
467
|
+
# # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
|
468
|
+
# # INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id"
|
469
|
+
#
|
470
|
+
# Nested joins:
|
471
|
+
#
|
472
|
+
# User.joins(posts: [:comments])
|
473
|
+
# # SELECT "users".*
|
474
|
+
# # FROM "users"
|
475
|
+
# # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
|
476
|
+
# # INNER JOIN "comments" "comments_posts"
|
477
|
+
# # ON "comments_posts"."post_id" = "posts"."id"
|
478
|
+
#
|
479
|
+
# You can use strings in order to customize your joins:
|
480
|
+
#
|
481
|
+
# User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
|
482
|
+
# # SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
|
483
|
+
def joins(*args)
|
484
|
+
check_if_method_has_arguments!(:joins, args)
|
485
|
+
spawn.joins!(*args)
|
486
|
+
end
|
487
|
+
|
488
|
+
def joins!(*args) # :nodoc:
|
489
|
+
args.compact!
|
490
|
+
args.flatten!
|
491
|
+
self.joins_values += args
|
492
|
+
self
|
493
|
+
end
|
494
|
+
|
495
|
+
# Performs a left outer joins on +args+:
|
496
|
+
#
|
497
|
+
# User.left_outer_joins(:posts)
|
498
|
+
# => SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
|
499
|
+
#
|
500
|
+
def left_outer_joins(*args)
|
501
|
+
check_if_method_has_arguments!(__callee__, args)
|
502
|
+
spawn.left_outer_joins!(*args)
|
503
|
+
end
|
504
|
+
alias :left_joins :left_outer_joins
|
505
|
+
|
506
|
+
def left_outer_joins!(*args) # :nodoc:
|
507
|
+
args.compact!
|
508
|
+
args.flatten!
|
509
|
+
self.left_outer_joins_values += args
|
510
|
+
self
|
511
|
+
end
|
512
|
+
|
513
|
+
# Returns a new relation, which is the result of filtering the current relation
|
514
|
+
# according to the conditions in the arguments.
|
515
|
+
#
|
516
|
+
# #where accepts conditions in one of several formats. In the examples below, the resulting
|
517
|
+
# SQL is given as an illustration; the actual query generated may be different depending
|
518
|
+
# on the database adapter.
|
519
|
+
#
|
520
|
+
# === string
|
521
|
+
#
|
522
|
+
# A single string, without additional arguments, is passed to the query
|
523
|
+
# constructor as an SQL fragment, and used in the where clause of the query.
|
524
|
+
#
|
525
|
+
# Client.where("orders_count = '2'")
|
526
|
+
# # SELECT * from clients where orders_count = '2';
|
527
|
+
#
|
528
|
+
# Note that building your own string from user input may expose your application
|
529
|
+
# to injection attacks if not done properly. As an alternative, it is recommended
|
530
|
+
# to use one of the following methods.
|
531
|
+
#
|
532
|
+
# === array
|
533
|
+
#
|
534
|
+
# If an array is passed, then the first element of the array is treated as a template, and
|
535
|
+
# the remaining elements are inserted into the template to generate the condition.
|
536
|
+
# Active Record takes care of building the query to avoid injection attacks, and will
|
537
|
+
# convert from the ruby type to the database type where needed. Elements are inserted
|
538
|
+
# into the string in the order in which they appear.
|
539
|
+
#
|
540
|
+
# User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
|
541
|
+
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
|
542
|
+
#
|
543
|
+
# Alternatively, you can use named placeholders in the template, and pass a hash as the
|
544
|
+
# second element of the array. The names in the template are replaced with the corresponding
|
545
|
+
# values from the hash.
|
546
|
+
#
|
547
|
+
# User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
|
548
|
+
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
|
549
|
+
#
|
550
|
+
# This can make for more readable code in complex queries.
|
551
|
+
#
|
552
|
+
# Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
|
553
|
+
# than the previous methods; you are responsible for ensuring that the values in the template
|
554
|
+
# are properly quoted. The values are passed to the connector for quoting, but the caller
|
555
|
+
# is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
|
556
|
+
# the values are inserted using the same escapes as the Ruby core method +Kernel::sprintf+.
|
557
|
+
#
|
558
|
+
# User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
|
559
|
+
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
|
560
|
+
#
|
561
|
+
# If #where is called with multiple arguments, these are treated as if they were passed as
|
562
|
+
# the elements of a single array.
|
563
|
+
#
|
564
|
+
# User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
|
565
|
+
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
|
566
|
+
#
|
567
|
+
# When using strings to specify conditions, you can use any operator available from
|
568
|
+
# the database. While this provides the most flexibility, you can also unintentionally introduce
|
569
|
+
# dependencies on the underlying database. If your code is intended for general consumption,
|
570
|
+
# test with multiple database backends.
|
571
|
+
#
|
572
|
+
# === hash
|
573
|
+
#
|
574
|
+
# #where will also accept a hash condition, in which the keys are fields and the values
|
575
|
+
# are values to be searched for.
|
576
|
+
#
|
577
|
+
# Fields can be symbols or strings. Values can be single values, arrays, or ranges.
|
578
|
+
#
|
579
|
+
# User.where({ name: "Joe", email: "joe@example.com" })
|
580
|
+
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
|
581
|
+
#
|
582
|
+
# User.where({ name: ["Alice", "Bob"]})
|
583
|
+
# # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
|
584
|
+
#
|
585
|
+
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
|
586
|
+
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
|
587
|
+
#
|
588
|
+
# In the case of a belongs_to relationship, an association key can be used
|
589
|
+
# to specify the model if an ActiveRecord object is used as the value.
|
590
|
+
#
|
591
|
+
# author = Author.find(1)
|
592
|
+
#
|
593
|
+
# # The following queries will be equivalent:
|
594
|
+
# Post.where(author: author)
|
595
|
+
# Post.where(author_id: author)
|
596
|
+
#
|
597
|
+
# This also works with polymorphic belongs_to relationships:
|
598
|
+
#
|
599
|
+
# treasure = Treasure.create(name: 'gold coins')
|
600
|
+
# treasure.price_estimates << PriceEstimate.create(price: 125)
|
601
|
+
#
|
602
|
+
# # The following queries will be equivalent:
|
603
|
+
# PriceEstimate.where(estimate_of: treasure)
|
604
|
+
# PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
|
605
|
+
#
|
606
|
+
# === Joins
|
607
|
+
#
|
608
|
+
# If the relation is the result of a join, you may create a condition which uses any of the
|
609
|
+
# tables in the join. For string and array conditions, use the table name in the condition.
|
610
|
+
#
|
611
|
+
# User.joins(:posts).where("posts.created_at < ?", Time.now)
|
612
|
+
#
|
613
|
+
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
|
614
|
+
#
|
615
|
+
# User.joins(:posts).where({ "posts.published" => true })
|
616
|
+
# User.joins(:posts).where({ posts: { published: true } })
|
617
|
+
#
|
618
|
+
# === no argument
|
619
|
+
#
|
620
|
+
# If no argument is passed, #where returns a new instance of WhereChain, that
|
621
|
+
# can be chained with #not to return a new relation that negates the where clause.
|
622
|
+
#
|
623
|
+
# User.where.not(name: "Jon")
|
624
|
+
# # SELECT * FROM users WHERE name != 'Jon'
|
625
|
+
#
|
626
|
+
# See WhereChain for more details on #not.
|
627
|
+
#
|
628
|
+
# === blank condition
|
629
|
+
#
|
630
|
+
# If the condition is any blank-ish object, then #where is a no-op and returns
|
631
|
+
# the current relation.
|
632
|
+
def where(opts = :chain, *rest)
|
633
|
+
if :chain == opts
|
634
|
+
WhereChain.new(spawn)
|
635
|
+
elsif opts.blank?
|
636
|
+
self
|
637
|
+
else
|
638
|
+
spawn.where!(opts, *rest)
|
639
|
+
end
|
640
|
+
end
|
641
|
+
|
642
|
+
def where!(opts, *rest) # :nodoc:
|
643
|
+
opts = sanitize_forbidden_attributes(opts)
|
644
|
+
references!(PredicateBuilder.references(opts)) if Hash === opts
|
645
|
+
self.where_clause += where_clause_factory.build(opts, rest)
|
646
|
+
self
|
647
|
+
end
|
648
|
+
|
649
|
+
# Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.
|
650
|
+
#
|
651
|
+
# Post.where(trashed: true).where(trashed: false)
|
652
|
+
# # WHERE `trashed` = 1 AND `trashed` = 0
|
653
|
+
#
|
654
|
+
# Post.where(trashed: true).rewhere(trashed: false)
|
655
|
+
# # WHERE `trashed` = 0
|
656
|
+
#
|
657
|
+
# Post.where(active: true).where(trashed: true).rewhere(trashed: false)
|
658
|
+
# # WHERE `active` = 1 AND `trashed` = 0
|
659
|
+
#
|
660
|
+
# This is short-hand for <tt>unscope(where: conditions.keys).where(conditions)</tt>.
|
661
|
+
# Note that unlike reorder, we're only unscoping the named conditions -- not the entire where statement.
|
662
|
+
def rewhere(conditions)
|
663
|
+
unscope(where: conditions.keys).where(conditions)
|
664
|
+
end
|
665
|
+
|
666
|
+
# Returns a new relation, which is the logical union of this relation and the one passed as an
|
667
|
+
# argument.
|
668
|
+
#
|
669
|
+
# The two relations must be structurally compatible: they must be scoping the same model, and
|
670
|
+
# they must differ only by #where (if no #group has been defined) or #having (if a #group is
|
671
|
+
# present). Neither relation may have a #limit, #offset, or #distinct set.
|
672
|
+
#
|
673
|
+
# Post.where("id = 1").or(Post.where("author_id = 3"))
|
674
|
+
# # SELECT `posts`.* FROM `posts` WHERE ((id = 1) OR (author_id = 3))
|
675
|
+
#
|
676
|
+
def or(other)
|
677
|
+
unless other.is_a? Relation
|
678
|
+
raise ArgumentError, "You have passed #{other.class.name} object to #or. Pass an ActiveRecord::Relation object instead."
|
679
|
+
end
|
680
|
+
|
681
|
+
spawn.or!(other)
|
682
|
+
end
|
683
|
+
|
684
|
+
def or!(other) # :nodoc:
|
685
|
+
incompatible_values = structurally_incompatible_values_for_or(other)
|
686
|
+
|
687
|
+
unless incompatible_values.empty?
|
688
|
+
raise ArgumentError, "Relation passed to #or must be structurally compatible. Incompatible values: #{incompatible_values}"
|
689
|
+
end
|
690
|
+
|
691
|
+
self.where_clause = self.where_clause.or(other.where_clause)
|
692
|
+
self.having_clause = having_clause.or(other.having_clause)
|
693
|
+
self.references_values += other.references_values
|
694
|
+
|
695
|
+
self
|
696
|
+
end
|
697
|
+
|
698
|
+
# Allows to specify a HAVING clause. Note that you can't use HAVING
|
699
|
+
# without also specifying a GROUP clause.
|
700
|
+
#
|
701
|
+
# Order.having('SUM(price) > 30').group('user_id')
|
702
|
+
def having(opts, *rest)
|
703
|
+
opts.blank? ? self : spawn.having!(opts, *rest)
|
704
|
+
end
|
705
|
+
|
706
|
+
def having!(opts, *rest) # :nodoc:
|
707
|
+
opts = sanitize_forbidden_attributes(opts)
|
708
|
+
references!(PredicateBuilder.references(opts)) if Hash === opts
|
709
|
+
|
710
|
+
self.having_clause += having_clause_factory.build(opts, rest)
|
711
|
+
self
|
712
|
+
end
|
713
|
+
|
714
|
+
# Specifies a limit for the number of records to retrieve.
|
715
|
+
#
|
716
|
+
# User.limit(10) # generated SQL has 'LIMIT 10'
|
717
|
+
#
|
718
|
+
# User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
|
719
|
+
def limit(value)
|
720
|
+
spawn.limit!(value)
|
721
|
+
end
|
722
|
+
|
723
|
+
def limit!(value) # :nodoc:
|
724
|
+
self.limit_value = value
|
725
|
+
self
|
726
|
+
end
|
727
|
+
|
728
|
+
# Specifies the number of rows to skip before returning rows.
|
729
|
+
#
|
730
|
+
# User.offset(10) # generated SQL has "OFFSET 10"
|
731
|
+
#
|
732
|
+
# Should be used with order.
|
733
|
+
#
|
734
|
+
# User.offset(10).order("name ASC")
|
735
|
+
def offset(value)
|
736
|
+
spawn.offset!(value)
|
737
|
+
end
|
738
|
+
|
739
|
+
def offset!(value) # :nodoc:
|
740
|
+
self.offset_value = value
|
741
|
+
self
|
742
|
+
end
|
743
|
+
|
744
|
+
# Specifies locking settings (default to +true+). For more information
|
745
|
+
# on locking, please see ActiveRecord::Locking.
|
746
|
+
def lock(locks = true)
|
747
|
+
spawn.lock!(locks)
|
748
|
+
end
|
749
|
+
|
750
|
+
def lock!(locks = true) # :nodoc:
|
751
|
+
case locks
|
752
|
+
when String, TrueClass, NilClass
|
753
|
+
self.lock_value = locks || true
|
754
|
+
else
|
755
|
+
self.lock_value = false
|
756
|
+
end
|
757
|
+
|
758
|
+
self
|
759
|
+
end
|
760
|
+
|
761
|
+
# Returns a chainable relation with zero records.
|
762
|
+
#
|
763
|
+
# The returned relation implements the Null Object pattern. It is an
|
764
|
+
# object with defined null behavior and always returns an empty array of
|
765
|
+
# records without querying the database.
|
766
|
+
#
|
767
|
+
# Any subsequent condition chained to the returned relation will continue
|
768
|
+
# generating an empty relation and will not fire any query to the database.
|
769
|
+
#
|
770
|
+
# Used in cases where a method or scope could return zero records but the
|
771
|
+
# result needs to be chainable.
|
772
|
+
#
|
773
|
+
# For example:
|
774
|
+
#
|
775
|
+
# @posts = current_user.visible_posts.where(name: params[:name])
|
776
|
+
# # the visible_posts method is expected to return a chainable Relation
|
777
|
+
#
|
778
|
+
# def visible_posts
|
779
|
+
# case role
|
780
|
+
# when 'Country Manager'
|
781
|
+
# Post.where(country: country)
|
782
|
+
# when 'Reviewer'
|
783
|
+
# Post.published
|
784
|
+
# when 'Bad User'
|
785
|
+
# Post.none # It can't be chained if [] is returned.
|
786
|
+
# end
|
787
|
+
# end
|
788
|
+
#
|
789
|
+
def none
|
790
|
+
spawn.none!
|
791
|
+
end
|
792
|
+
|
793
|
+
def none! # :nodoc:
|
794
|
+
where!("1=0").extending!(NullRelation)
|
795
|
+
end
|
796
|
+
|
797
|
+
# Sets readonly attributes for the returned relation. If value is
|
798
|
+
# true (default), attempting to update a record will result in an error.
|
799
|
+
#
|
800
|
+
# users = User.readonly
|
801
|
+
# users.first.save
|
802
|
+
# => ActiveRecord::ReadOnlyRecord: User is marked as readonly
|
803
|
+
def readonly(value = true)
|
804
|
+
spawn.readonly!(value)
|
805
|
+
end
|
806
|
+
|
807
|
+
def readonly!(value = true) # :nodoc:
|
808
|
+
self.readonly_value = value
|
809
|
+
self
|
810
|
+
end
|
811
|
+
|
812
|
+
# Sets attributes to be used when creating new records from a
|
813
|
+
# relation object.
|
814
|
+
#
|
815
|
+
# users = User.where(name: 'Oscar')
|
816
|
+
# users.new.name # => 'Oscar'
|
817
|
+
#
|
818
|
+
# users = users.create_with(name: 'DHH')
|
819
|
+
# users.new.name # => 'DHH'
|
820
|
+
#
|
821
|
+
# You can pass +nil+ to #create_with to reset attributes:
|
822
|
+
#
|
823
|
+
# users = users.create_with(nil)
|
824
|
+
# users.new.name # => 'Oscar'
|
825
|
+
def create_with(value)
|
826
|
+
spawn.create_with!(value)
|
827
|
+
end
|
828
|
+
|
829
|
+
def create_with!(value) # :nodoc:
|
830
|
+
if value
|
831
|
+
value = sanitize_forbidden_attributes(value)
|
832
|
+
self.create_with_value = create_with_value.merge(value)
|
833
|
+
else
|
834
|
+
self.create_with_value = FROZEN_EMPTY_HASH
|
835
|
+
end
|
836
|
+
|
837
|
+
self
|
838
|
+
end
|
839
|
+
|
840
|
+
# Specifies table from which the records will be fetched. For example:
|
841
|
+
#
|
842
|
+
# Topic.select('title').from('posts')
|
843
|
+
# # SELECT title FROM posts
|
844
|
+
#
|
845
|
+
# Can accept other relation objects. For example:
|
846
|
+
#
|
847
|
+
# Topic.select('title').from(Topic.approved)
|
848
|
+
# # SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
|
849
|
+
#
|
850
|
+
# Topic.select('a.title').from(Topic.approved, :a)
|
851
|
+
# # SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
|
852
|
+
#
|
853
|
+
def from(value, subquery_name = nil)
|
854
|
+
spawn.from!(value, subquery_name)
|
855
|
+
end
|
856
|
+
|
857
|
+
def from!(value, subquery_name = nil) # :nodoc:
|
858
|
+
self.from_clause = Relation::FromClause.new(value, subquery_name)
|
859
|
+
self
|
860
|
+
end
|
861
|
+
|
862
|
+
# Specifies whether the records should be unique or not. For example:
|
863
|
+
#
|
864
|
+
# User.select(:name)
|
865
|
+
# # Might return two records with the same name
|
866
|
+
#
|
867
|
+
# User.select(:name).distinct
|
868
|
+
# # Returns 1 record per distinct name
|
869
|
+
#
|
870
|
+
# User.select(:name).distinct.distinct(false)
|
871
|
+
# # You can also remove the uniqueness
|
872
|
+
def distinct(value = true)
|
873
|
+
spawn.distinct!(value)
|
874
|
+
end
|
875
|
+
|
876
|
+
# Like #distinct, but modifies relation in place.
|
877
|
+
def distinct!(value = true) # :nodoc:
|
878
|
+
self.distinct_value = value
|
879
|
+
self
|
880
|
+
end
|
881
|
+
|
882
|
+
# Used to extend a scope with additional methods, either through
|
883
|
+
# a module or through a block provided.
|
884
|
+
#
|
885
|
+
# The object returned is a relation, which can be further extended.
|
886
|
+
#
|
887
|
+
# === Using a module
|
888
|
+
#
|
889
|
+
# module Pagination
|
890
|
+
# def page(number)
|
891
|
+
# # pagination code goes here
|
892
|
+
# end
|
893
|
+
# end
|
894
|
+
#
|
895
|
+
# scope = Model.all.extending(Pagination)
|
896
|
+
# scope.page(params[:page])
|
897
|
+
#
|
898
|
+
# You can also pass a list of modules:
|
899
|
+
#
|
900
|
+
# scope = Model.all.extending(Pagination, SomethingElse)
|
901
|
+
#
|
902
|
+
# === Using a block
|
903
|
+
#
|
904
|
+
# scope = Model.all.extending do
|
905
|
+
# def page(number)
|
906
|
+
# # pagination code goes here
|
907
|
+
# end
|
908
|
+
# end
|
909
|
+
# scope.page(params[:page])
|
910
|
+
#
|
911
|
+
# You can also use a block and a module list:
|
912
|
+
#
|
913
|
+
# scope = Model.all.extending(Pagination) do
|
914
|
+
# def per_page(number)
|
915
|
+
# # pagination code goes here
|
916
|
+
# end
|
917
|
+
# end
|
918
|
+
def extending(*modules, &block)
|
919
|
+
if modules.any? || block
|
920
|
+
spawn.extending!(*modules, &block)
|
921
|
+
else
|
922
|
+
self
|
923
|
+
end
|
924
|
+
end
|
925
|
+
|
926
|
+
def extending!(*modules, &block) # :nodoc:
|
927
|
+
modules << Module.new(&block) if block
|
928
|
+
modules.flatten!
|
929
|
+
|
930
|
+
self.extending_values += modules
|
931
|
+
extend(*extending_values) if extending_values.any?
|
932
|
+
|
933
|
+
self
|
934
|
+
end
|
935
|
+
|
936
|
+
# Specify optimizer hints to be used in the SELECT statement.
|
937
|
+
#
|
938
|
+
# Example (for MySQL):
|
939
|
+
#
|
940
|
+
# Topic.optimizer_hints("MAX_EXECUTION_TIME(50000)", "NO_INDEX_MERGE(topics)")
|
941
|
+
# # SELECT /*+ MAX_EXECUTION_TIME(50000) NO_INDEX_MERGE(topics) */ `topics`.* FROM `topics`
|
942
|
+
#
|
943
|
+
# Example (for PostgreSQL with pg_hint_plan):
|
944
|
+
#
|
945
|
+
# Topic.optimizer_hints("SeqScan(topics)", "Parallel(topics 8)")
|
946
|
+
# # SELECT /*+ SeqScan(topics) Parallel(topics 8) */ "topics".* FROM "topics"
|
947
|
+
def optimizer_hints(*args)
|
948
|
+
check_if_method_has_arguments!(:optimizer_hints, args)
|
949
|
+
spawn.optimizer_hints!(*args)
|
950
|
+
end
|
951
|
+
|
952
|
+
def optimizer_hints!(*args) # :nodoc:
|
953
|
+
args.flatten!
|
954
|
+
|
955
|
+
self.optimizer_hints_values |= args
|
956
|
+
self
|
957
|
+
end
|
958
|
+
|
959
|
+
# Reverse the existing order clause on the relation.
|
960
|
+
#
|
961
|
+
# User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
|
962
|
+
def reverse_order
|
963
|
+
spawn.reverse_order!
|
964
|
+
end
|
965
|
+
|
966
|
+
def reverse_order! # :nodoc:
|
967
|
+
orders = order_values.uniq
|
968
|
+
orders.reject!(&:blank?)
|
969
|
+
self.order_values = reverse_sql_order(orders)
|
970
|
+
self
|
971
|
+
end
|
972
|
+
|
973
|
+
def skip_query_cache!(value = true) # :nodoc:
|
974
|
+
self.skip_query_cache_value = value
|
975
|
+
self
|
976
|
+
end
|
977
|
+
|
978
|
+
def skip_preloading! # :nodoc:
|
979
|
+
self.skip_preloading_value = true
|
980
|
+
self
|
981
|
+
end
|
982
|
+
|
983
|
+
# Adds an SQL comment to queries generated from this relation. For example:
|
984
|
+
#
|
985
|
+
# User.annotate("selecting user names").select(:name)
|
986
|
+
# # SELECT "users"."name" FROM "users" /* selecting user names */
|
987
|
+
#
|
988
|
+
# User.annotate("selecting", "user", "names").select(:name)
|
989
|
+
# # SELECT "users"."name" FROM "users" /* selecting */ /* user */ /* names */
|
990
|
+
#
|
991
|
+
# The SQL block comment delimiters, "/*" and "*/", will be added automatically.
|
992
|
+
def annotate(*args)
|
993
|
+
check_if_method_has_arguments!(:annotate, args)
|
994
|
+
spawn.annotate!(*args)
|
995
|
+
end
|
996
|
+
|
997
|
+
# Like #annotate, but modifies relation in place.
|
998
|
+
def annotate!(*args) # :nodoc:
|
999
|
+
self.annotate_values += args
|
1000
|
+
self
|
1001
|
+
end
|
1002
|
+
|
1003
|
+
# Returns the Arel object associated with the relation.
|
1004
|
+
def arel(aliases = nil) # :nodoc:
|
1005
|
+
@arel ||= build_arel(aliases)
|
1006
|
+
end
|
1007
|
+
|
1008
|
+
def construct_join_dependency(associations, join_type) # :nodoc:
|
1009
|
+
ActiveRecord::Associations::JoinDependency.new(
|
1010
|
+
klass, table, associations, join_type
|
1011
|
+
)
|
1012
|
+
end
|
1013
|
+
|
1014
|
+
protected
|
1015
|
+
def build_subquery(subquery_alias, select_value) # :nodoc:
|
1016
|
+
subquery = except(:optimizer_hints).arel.as(subquery_alias)
|
1017
|
+
|
1018
|
+
Arel::SelectManager.new(subquery).project(select_value).tap do |arel|
|
1019
|
+
arel.optimizer_hints(*optimizer_hints_values) unless optimizer_hints_values.empty?
|
1020
|
+
end
|
1021
|
+
end
|
1022
|
+
|
1023
|
+
private
|
1024
|
+
def assert_mutability!
|
1025
|
+
raise ImmutableRelation if @loaded
|
1026
|
+
raise ImmutableRelation if defined?(@arel) && @arel
|
1027
|
+
end
|
1028
|
+
|
1029
|
+
def build_arel(aliases)
|
1030
|
+
arel = Arel::SelectManager.new(table)
|
1031
|
+
|
1032
|
+
if !joins_values.empty?
|
1033
|
+
build_joins(arel, joins_values.flatten, aliases)
|
1034
|
+
elsif !left_outer_joins_values.empty?
|
1035
|
+
build_left_outer_joins(arel, left_outer_joins_values.flatten, aliases)
|
1036
|
+
end
|
1037
|
+
|
1038
|
+
arel.where(where_clause.ast) unless where_clause.empty?
|
1039
|
+
arel.having(having_clause.ast) unless having_clause.empty?
|
1040
|
+
if limit_value
|
1041
|
+
limit_attribute = ActiveModel::Attribute.with_cast_value(
|
1042
|
+
"LIMIT",
|
1043
|
+
connection.sanitize_limit(limit_value),
|
1044
|
+
Type.default_value,
|
1045
|
+
)
|
1046
|
+
arel.take(Arel::Nodes::BindParam.new(limit_attribute))
|
1047
|
+
end
|
1048
|
+
if offset_value
|
1049
|
+
offset_attribute = ActiveModel::Attribute.with_cast_value(
|
1050
|
+
"OFFSET",
|
1051
|
+
offset_value.to_i,
|
1052
|
+
Type.default_value,
|
1053
|
+
)
|
1054
|
+
arel.skip(Arel::Nodes::BindParam.new(offset_attribute))
|
1055
|
+
end
|
1056
|
+
arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty?
|
1057
|
+
|
1058
|
+
build_order(arel)
|
1059
|
+
|
1060
|
+
build_select(arel)
|
1061
|
+
|
1062
|
+
arel.optimizer_hints(*optimizer_hints_values) unless optimizer_hints_values.empty?
|
1063
|
+
arel.distinct(distinct_value)
|
1064
|
+
arel.from(build_from) unless from_clause.empty?
|
1065
|
+
arel.lock(lock_value) if lock_value
|
1066
|
+
arel.comment(*annotate_values) unless annotate_values.empty?
|
1067
|
+
|
1068
|
+
arel
|
1069
|
+
end
|
1070
|
+
|
1071
|
+
def build_from
|
1072
|
+
opts = from_clause.value
|
1073
|
+
name = from_clause.name
|
1074
|
+
case opts
|
1075
|
+
when Relation
|
1076
|
+
if opts.eager_loading?
|
1077
|
+
opts = opts.send(:apply_join_dependency)
|
1078
|
+
end
|
1079
|
+
name ||= "subquery"
|
1080
|
+
opts.arel.as(name.to_s)
|
1081
|
+
else
|
1082
|
+
opts
|
1083
|
+
end
|
1084
|
+
end
|
1085
|
+
|
1086
|
+
def select_association_list(associations)
|
1087
|
+
result = []
|
1088
|
+
associations.each do |association|
|
1089
|
+
case association
|
1090
|
+
when Hash, Symbol, Array
|
1091
|
+
result << association
|
1092
|
+
else
|
1093
|
+
yield if block_given?
|
1094
|
+
end
|
1095
|
+
end
|
1096
|
+
result
|
1097
|
+
end
|
1098
|
+
|
1099
|
+
def valid_association_list(associations)
|
1100
|
+
select_association_list(associations) do
|
1101
|
+
raise ArgumentError, "only Hash, Symbol and Array are allowed"
|
1102
|
+
end
|
1103
|
+
end
|
1104
|
+
|
1105
|
+
def build_left_outer_joins(manager, outer_joins, aliases)
|
1106
|
+
buckets = Hash.new { |h, k| h[k] = [] }
|
1107
|
+
buckets[:association_join] = valid_association_list(outer_joins)
|
1108
|
+
build_join_query(manager, buckets, Arel::Nodes::OuterJoin, aliases)
|
1109
|
+
end
|
1110
|
+
|
1111
|
+
def build_joins(manager, joins, aliases)
|
1112
|
+
buckets = Hash.new { |h, k| h[k] = [] }
|
1113
|
+
|
1114
|
+
unless left_outer_joins_values.empty?
|
1115
|
+
left_joins = valid_association_list(left_outer_joins_values.flatten)
|
1116
|
+
buckets[:stashed_join] << construct_join_dependency(left_joins, Arel::Nodes::OuterJoin)
|
1117
|
+
end
|
1118
|
+
|
1119
|
+
if joins.last.is_a?(ActiveRecord::Associations::JoinDependency)
|
1120
|
+
buckets[:stashed_join] << joins.pop if joins.last.base_klass == klass
|
1121
|
+
end
|
1122
|
+
|
1123
|
+
joins.map! do |join|
|
1124
|
+
if join.is_a?(String)
|
1125
|
+
table.create_string_join(Arel.sql(join.strip)) unless join.blank?
|
1126
|
+
else
|
1127
|
+
join
|
1128
|
+
end
|
1129
|
+
end.delete_if(&:blank?).uniq!
|
1130
|
+
|
1131
|
+
while joins.first.is_a?(Arel::Nodes::Join)
|
1132
|
+
join_node = joins.shift
|
1133
|
+
if join_node.is_a?(Arel::Nodes::StringJoin) && !buckets[:stashed_join].empty?
|
1134
|
+
buckets[:join_node] << join_node
|
1135
|
+
else
|
1136
|
+
buckets[:leading_join] << join_node
|
1137
|
+
end
|
1138
|
+
end
|
1139
|
+
|
1140
|
+
joins.each do |join|
|
1141
|
+
case join
|
1142
|
+
when Hash, Symbol, Array
|
1143
|
+
buckets[:association_join] << join
|
1144
|
+
when ActiveRecord::Associations::JoinDependency
|
1145
|
+
buckets[:stashed_join] << join
|
1146
|
+
when Arel::Nodes::Join
|
1147
|
+
buckets[:join_node] << join
|
1148
|
+
else
|
1149
|
+
raise "unknown class: %s" % join.class.name
|
1150
|
+
end
|
1151
|
+
end
|
1152
|
+
|
1153
|
+
build_join_query(manager, buckets, Arel::Nodes::InnerJoin, aliases)
|
1154
|
+
end
|
1155
|
+
|
1156
|
+
def build_join_query(manager, buckets, join_type, aliases)
|
1157
|
+
association_joins = buckets[:association_join]
|
1158
|
+
stashed_joins = buckets[:stashed_join]
|
1159
|
+
leading_joins = buckets[:leading_join]
|
1160
|
+
join_nodes = buckets[:join_node]
|
1161
|
+
|
1162
|
+
join_sources = manager.join_sources
|
1163
|
+
join_sources.concat(leading_joins) unless leading_joins.empty?
|
1164
|
+
|
1165
|
+
unless association_joins.empty? && stashed_joins.empty?
|
1166
|
+
alias_tracker = alias_tracker(leading_joins + join_nodes, aliases)
|
1167
|
+
join_dependency = construct_join_dependency(association_joins, join_type)
|
1168
|
+
join_sources.concat(join_dependency.join_constraints(stashed_joins, alias_tracker))
|
1169
|
+
end
|
1170
|
+
|
1171
|
+
join_sources.concat(join_nodes) unless join_nodes.empty?
|
1172
|
+
end
|
1173
|
+
|
1174
|
+
def build_select(arel)
|
1175
|
+
if select_values.any?
|
1176
|
+
arel.project(*arel_columns(select_values.uniq))
|
1177
|
+
elsif klass.ignored_columns.any?
|
1178
|
+
arel.project(*klass.column_names.map { |field| arel_attribute(field) })
|
1179
|
+
else
|
1180
|
+
arel.project(table[Arel.star])
|
1181
|
+
end
|
1182
|
+
end
|
1183
|
+
|
1184
|
+
def arel_columns(columns)
|
1185
|
+
columns.flat_map do |field|
|
1186
|
+
case field
|
1187
|
+
when Symbol
|
1188
|
+
arel_column(field.to_s) do |attr_name|
|
1189
|
+
connection.quote_table_name(attr_name)
|
1190
|
+
end
|
1191
|
+
when String
|
1192
|
+
arel_column(field, &:itself)
|
1193
|
+
when Proc
|
1194
|
+
field.call
|
1195
|
+
else
|
1196
|
+
field
|
1197
|
+
end
|
1198
|
+
end
|
1199
|
+
end
|
1200
|
+
|
1201
|
+
def arel_column(field)
|
1202
|
+
field = klass.attribute_aliases[field] || field
|
1203
|
+
from = from_clause.name || from_clause.value
|
1204
|
+
|
1205
|
+
if klass.columns_hash.key?(field) && (!from || table_name_matches?(from))
|
1206
|
+
arel_attribute(field)
|
1207
|
+
else
|
1208
|
+
yield field
|
1209
|
+
end
|
1210
|
+
end
|
1211
|
+
|
1212
|
+
def table_name_matches?(from)
|
1213
|
+
/(?:\A|(?<!FROM)\s)(?:\b#{table.name}\b|#{connection.quote_table_name(table.name)})(?!\.)/i.match?(from.to_s)
|
1214
|
+
end
|
1215
|
+
|
1216
|
+
def reverse_sql_order(order_query)
|
1217
|
+
if order_query.empty?
|
1218
|
+
return [arel_attribute(primary_key).desc] if primary_key
|
1219
|
+
raise IrreversibleOrderError,
|
1220
|
+
"Relation has no current order and table has no primary key to be used as default order"
|
1221
|
+
end
|
1222
|
+
|
1223
|
+
order_query.flat_map do |o|
|
1224
|
+
case o
|
1225
|
+
when Arel::Attribute
|
1226
|
+
o.desc
|
1227
|
+
when Arel::Nodes::Ordering
|
1228
|
+
o.reverse
|
1229
|
+
when String
|
1230
|
+
if does_not_support_reverse?(o)
|
1231
|
+
raise IrreversibleOrderError, "Order #{o.inspect} cannot be reversed automatically"
|
1232
|
+
end
|
1233
|
+
o.split(",").map! do |s|
|
1234
|
+
s.strip!
|
1235
|
+
s.gsub!(/\sasc\Z/i, " DESC") || s.gsub!(/\sdesc\Z/i, " ASC") || (s << " DESC")
|
1236
|
+
end
|
1237
|
+
else
|
1238
|
+
o
|
1239
|
+
end
|
1240
|
+
end
|
1241
|
+
end
|
1242
|
+
|
1243
|
+
def does_not_support_reverse?(order)
|
1244
|
+
# Account for String subclasses like Arel::Nodes::SqlLiteral that
|
1245
|
+
# override methods like #count.
|
1246
|
+
order = String.new(order) unless order.instance_of?(String)
|
1247
|
+
|
1248
|
+
# Uses SQL function with multiple arguments.
|
1249
|
+
(order.include?(",") && order.split(",").find { |section| section.count("(") != section.count(")") }) ||
|
1250
|
+
# Uses "nulls first" like construction.
|
1251
|
+
/\bnulls\s+(?:first|last)\b/i.match?(order)
|
1252
|
+
end
|
1253
|
+
|
1254
|
+
def build_order(arel)
|
1255
|
+
orders = order_values.uniq
|
1256
|
+
orders.reject!(&:blank?)
|
1257
|
+
|
1258
|
+
arel.order(*orders) unless orders.empty?
|
1259
|
+
end
|
1260
|
+
|
1261
|
+
VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC,
|
1262
|
+
"asc", "desc", "ASC", "DESC"].to_set # :nodoc:
|
1263
|
+
|
1264
|
+
def validate_order_args(args)
|
1265
|
+
args.each do |arg|
|
1266
|
+
next unless arg.is_a?(Hash)
|
1267
|
+
arg.each do |_key, value|
|
1268
|
+
unless VALID_DIRECTIONS.include?(value)
|
1269
|
+
raise ArgumentError,
|
1270
|
+
"Direction \"#{value}\" is invalid. Valid directions are: #{VALID_DIRECTIONS.to_a.inspect}"
|
1271
|
+
end
|
1272
|
+
end
|
1273
|
+
end
|
1274
|
+
end
|
1275
|
+
|
1276
|
+
def preprocess_order_args(order_args)
|
1277
|
+
order_args.reject!(&:blank?)
|
1278
|
+
order_args.map! do |arg|
|
1279
|
+
klass.sanitize_sql_for_order(arg)
|
1280
|
+
end
|
1281
|
+
order_args.flatten!
|
1282
|
+
|
1283
|
+
@klass.disallow_raw_sql!(
|
1284
|
+
order_args.flat_map { |a| a.is_a?(Hash) ? a.keys : a },
|
1285
|
+
permit: connection.column_name_with_order_matcher
|
1286
|
+
)
|
1287
|
+
|
1288
|
+
validate_order_args(order_args)
|
1289
|
+
|
1290
|
+
references = order_args.grep(String)
|
1291
|
+
references.map! { |arg| arg =~ /^\W?(\w+)\W?\./ && $1 }.compact!
|
1292
|
+
references!(references) if references.any?
|
1293
|
+
|
1294
|
+
# if a symbol is given we prepend the quoted table name
|
1295
|
+
order_args.map! do |arg|
|
1296
|
+
case arg
|
1297
|
+
when Symbol
|
1298
|
+
order_column(arg.to_s).asc
|
1299
|
+
when Hash
|
1300
|
+
arg.map { |field, dir|
|
1301
|
+
case field
|
1302
|
+
when Arel::Nodes::SqlLiteral
|
1303
|
+
field.send(dir.downcase)
|
1304
|
+
else
|
1305
|
+
order_column(field.to_s).send(dir.downcase)
|
1306
|
+
end
|
1307
|
+
}
|
1308
|
+
else
|
1309
|
+
arg
|
1310
|
+
end
|
1311
|
+
end.flatten!
|
1312
|
+
end
|
1313
|
+
|
1314
|
+
def order_column(field)
|
1315
|
+
arel_column(field) do |attr_name|
|
1316
|
+
if attr_name == "count" && !group_values.empty?
|
1317
|
+
arel_attribute(attr_name)
|
1318
|
+
else
|
1319
|
+
Arel.sql(connection.quote_table_name(attr_name))
|
1320
|
+
end
|
1321
|
+
end
|
1322
|
+
end
|
1323
|
+
|
1324
|
+
# Checks to make sure that the arguments are not blank. Note that if some
|
1325
|
+
# blank-like object were initially passed into the query method, then this
|
1326
|
+
# method will not raise an error.
|
1327
|
+
#
|
1328
|
+
# Example:
|
1329
|
+
#
|
1330
|
+
# Post.references() # raises an error
|
1331
|
+
# Post.references([]) # does not raise an error
|
1332
|
+
#
|
1333
|
+
# This particular method should be called with a method_name and the args
|
1334
|
+
# passed into that method as an input. For example:
|
1335
|
+
#
|
1336
|
+
# def references(*args)
|
1337
|
+
# check_if_method_has_arguments!("references", args)
|
1338
|
+
# ...
|
1339
|
+
# end
|
1340
|
+
def check_if_method_has_arguments!(method_name, args)
|
1341
|
+
if args.blank?
|
1342
|
+
raise ArgumentError, "The method .#{method_name}() must contain arguments."
|
1343
|
+
end
|
1344
|
+
end
|
1345
|
+
|
1346
|
+
STRUCTURAL_OR_METHODS = Relation::VALUE_METHODS - [:extending, :where, :having, :unscope, :references]
|
1347
|
+
def structurally_incompatible_values_for_or(other)
|
1348
|
+
values = other.values
|
1349
|
+
STRUCTURAL_OR_METHODS.reject do |method|
|
1350
|
+
default = DEFAULT_VALUES[method]
|
1351
|
+
@values.fetch(method, default) == values.fetch(method, default)
|
1352
|
+
end
|
1353
|
+
end
|
1354
|
+
|
1355
|
+
def where_clause_factory
|
1356
|
+
@where_clause_factory ||= Relation::WhereClauseFactory.new(klass, predicate_builder)
|
1357
|
+
end
|
1358
|
+
alias having_clause_factory where_clause_factory
|
1359
|
+
|
1360
|
+
DEFAULT_VALUES = {
|
1361
|
+
create_with: FROZEN_EMPTY_HASH,
|
1362
|
+
where: Relation::WhereClause.empty,
|
1363
|
+
having: Relation::WhereClause.empty,
|
1364
|
+
from: Relation::FromClause.empty
|
1365
|
+
}
|
1366
|
+
|
1367
|
+
Relation::MULTI_VALUE_METHODS.each do |value|
|
1368
|
+
DEFAULT_VALUES[value] ||= FROZEN_EMPTY_ARRAY
|
1369
|
+
end
|
1370
|
+
end
|
1371
|
+
end
|