From 2e860b013b2698d5a099b6125fd1a11a1db9a714 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sat, 14 Nov 2026 12:57:07 +0800 Subject: [PATCH 01/81] test: migrate the PostgreSQL test tree onto the directory-owned testsuite --- .github/workflows/test.yml | 32 +- pyproject.toml | 2 +- .../backend/impl/postgres/dialect.py | 6 + .../backend/impl/postgres/transaction.py | 4 + .../activerecord_bulk/test_bulk_create.py | 5 +- .../test_bulk_create_async.py | 2 + tests/benchmark/backend/conftest.py | 2 +- tests/benchmark/relation/conftest.py | 26 +- tests/conftest.py | 191 +---- tests/providers/basic.py | 514 ------------- tests/providers/basic_connection.py | 183 ----- tests/providers/crud_benchmark.py | 189 ----- tests/providers/events.py | 201 ----- tests/providers/fastapi_benchmark.py | 242 ------ tests/providers/fixtures/__init__.py | 14 - tests/providers/fixtures/_common.py | 34 - tests/providers/fixtures/basic.py | 498 ------------- tests/providers/fixtures/events.py | 84 --- tests/providers/fixtures/mixins.py | 134 ---- tests/providers/fixtures/query.py | 385 ---------- tests/providers/mixin_benchmark.py | 15 - tests/providers/mixins.py | 232 ------ tests/providers/partition.py | 381 ---------- tests/providers/pooling.py | 132 ---- tests/providers/query.py | 694 ------------------ tests/providers/query_benchmark.py | 15 - tests/providers/query_connection.py | 169 ----- tests/providers/registry.py | 77 -- tests/providers/relation.py | 459 ------------ tests/providers/scenarios.py | 142 ---- tests/providers/transaction_benchmark.py | 17 - .../feature/backend/SHARDS.md | 130 ++++ .../feature/backend/conftest.py | 192 ++--- .../feature/backend/construct/cli/.gitkeep | 0 .../backend/construct/connection/.gitkeep | 0 .../ddl}/test_auto_increment_ddl.py | 2 +- .../ddl/test_column_definition.py} | 2 +- .../ddl/test_constraint_capabilities.py} | 2 +- .../ddl}/test_create_table_like.py | 2 +- .../ddl/test_database_ddl.py} | 2 +- .../ddl}/test_ddl_source_collection.py | 2 +- .../test_generated_column_capabilities.py | 2 +- .../dialect/test_alter_table_if_exists.py | 14 +- .../test_database_size_introspection.py | 2 +- .../dialect/test_ddl_improvements.py} | 8 +- .../dialect}/test_ddl_protocols.py | 20 +- .../dialect}/test_dialect_function_support.py | 2 +- .../dialect/test_dialect_security.py} | 14 +- .../dialect/test_dql_capabilities.py | 2 +- .../dialect/test_drop_table_cascade.py | 4 +- .../dialect}/test_function_versions.py | 2 +- .../dialect}/test_identifier_quoting.py | 2 +- .../dialect}/test_ilike_support.py | 2 +- .../test_insert_on_conflict_clauses.py | 6 +- .../dialect/test_introspection_parsing.py | 2 +- .../dialect/test_kind_hygiene.py | 2 +- .../dialect/test_materialized_view.py | 2 +- .../dialect/test_materialized_view_docs.py | 4 +- .../test_materialized_view_introspection.py | 2 +- .../dialect/test_object_kind_guards.py | 4 +- .../test_property_graph_query_format.py | 2 +- .../dialect/test_protocol_conformance.py} | 11 +- .../dialect/test_returning_capabilities.py | 2 +- .../dialect/test_schema_support.py | 2 +- .../test_set_operation_and_truncate.py | 2 +- .../dialect/test_status_query_nodes.py | 2 +- .../test_table_storage_introspection.py | 2 +- .../dialect}/test_version_features.py | 2 +- .../feature/backend/construct/errors/.gitkeep | 0 .../{ => construct}/expression/conftest.py | 2 +- .../expression}/test_clause_pair_guard.py | 2 +- .../test_domain_expression_roundtrip.py | 8 +- .../expression}/test_expression_namespace.py | 2 +- .../test_expression_roundtrip_all.py | 4 +- .../expression/test_expression_signatures.py | 2 +- .../test_expressions_transaction.py | 0 .../expression/vector_search_test.py | 2 +- .../expression_roundtrip_harness.py | 2 +- .../functions/test_array_functions.py} | 4 +- .../test_datetime_interval_expressions.py} | 5 +- .../test_extension_type_operations.py | 2 +- .../functions}/test_extensions.py | 2 +- .../functions/test_hstore_functions.py} | 2 +- .../test_math_enhanced_functions.py} | 4 +- .../functions/test_network_functions.py} | 4 +- .../functions/test_pgvector_functions.py} | 2 +- .../functions/test_postgis_functions.py} | 2 +- .../functions/test_range_constructors.py} | 2 +- .../functions}/test_range_functions.py | 2 +- .../functions/test_uuid_functions.py} | 4 +- .../backend/construct/introspection/.gitkeep | 0 .../mixins}/test_address_standardizer.py | 2 +- .../mixins}/test_bloom.py | 2 +- .../mixins}/test_btree_gin.py | 2 +- .../mixins}/test_btree_gist.py | 2 +- .../mixins}/test_citext.py | 2 +- .../mixins}/test_cube.py | 2 +- .../mixins}/test_ddl_alter_config.py | 14 +- .../mixins}/test_extended_statistics.py | 2 +- .../mixins}/test_fuzzystrmatch.py | 2 +- .../mixins}/test_hypopg.py | 2 +- .../mixins}/test_index_pg.py | 4 +- .../mixins}/test_orafce.py | 2 +- .../mixins}/test_pg_cron.py | 2 +- .../mixins}/test_pg_partman.py | 2 +- .../mixins}/test_pg_repack.py | 2 +- .../mixins}/test_pg_stat_statements.py | 2 +- .../mixins}/test_pg_surgery.py | 2 +- .../mixins}/test_pg_walinspect.py | 2 +- .../mixins}/test_pgaudit.py | 2 +- .../mixins}/test_pgcrypto.py | 2 +- .../mixins}/test_pglogical.py | 2 +- .../mixins}/test_policy.py | 2 +- .../mixins}/test_stored_procedure.py | 2 +- .../mixins}/test_table.py | 4 +- .../mixins}/test_tablefunc.py | 2 +- .../mixins}/test_trigger.py | 4 +- .../mixins}/test_uuid_ossp.py | 2 +- .../statements}/partition_syntax_fixtures.py | 2 +- .../statements}/test_ddl_expressions.py | 18 +- .../statements}/test_ddl_objects.py | 10 +- .../statements}/test_expressions.py | 12 +- .../statements}/test_partition_plan.py | 2 +- .../test_partition_syntax_matrix.py | 4 +- .../statements}/test_pg19_copy_repack.py | 2 +- .../test_set_constraints_statement.py | 2 +- .../{ => construct/types}/test_adapters.py | 2 +- .../types}/test_bitstring_types.py | 2 +- .../types/test_column_type_suggestions.py | 2 +- .../types}/test_core_type_mappings.py | 0 .../types/test_data_type_formatting.py | 2 +- .../types}/test_enum_types.py | 2 +- .../types/test_expression_types.py | 4 +- .../types}/test_geometry_types.py | 2 +- .../types}/test_hstore_types.py | 2 +- .../types}/test_jsonpath_types.py | 2 +- .../types}/test_literal_values.py | 2 +- .../types}/test_lsn_types.py | 2 +- .../types}/test_macaddr8_types.py | 2 +- .../types}/test_money_types.py | 2 +- .../types}/test_oid_types.py | 2 +- .../types}/test_pgvector_types.py | 2 +- .../types}/test_postgis_types.py | 2 +- .../types}/test_range_types.py | 2 +- .../types}/test_textsearch_types.py | 2 +- .../types}/test_type_casting.py | 4 +- .../types}/test_type_compatibility.py | 2 +- .../types/test_type_protocol.py} | 6 +- .../types}/test_uuid_type_adapter.py | 2 +- .../types}/test_uuid_values.py | 2 +- .../types}/test_xml_types.py | 2 +- .../{ => core}/examples_compile_test.py | 6 +- .../backend/{ => core}/test_async_support.py | 0 .../cli}/conftest.py | 3 +- .../cli}/example_connections.py | 2 +- .../backend/{ => execute/cli}/test_cli.py | 2 +- .../cli}/test_cli_connection_args.py | 2 +- .../cli}/test_named_connection_cli.py | 4 +- .../cli}/test_resolver.py | 20 +- .../concurrency}/test_advisory_lock.py | 2 +- .../concurrency}/test_concurrency_protocol.py | 6 +- .../test_backend_initialization.py | 2 +- .../{ => execute/connection}/test_config.py | 2 +- .../connection}/test_connection_config.py | 2 +- .../connection}/test_connection_resilience.py | 2 +- .../connection}/test_cursor_pollution.py | 6 +- .../{ => execute/connection}/test_dialect.py | 6 +- .../connection}/test_ssl_connection_params.py | 2 +- .../{ => execute/connection}/test_version.py | 4 +- .../crud}/test_column_mapping_backend.py | 0 .../test_column_mapping_backend_async.py} | 0 .../{ => execute/crud}/test_crud_backend.py | 6 +- .../crud/test_crud_backend_async.py} | 2 +- .../backend/execute/ddl_column/.gitkeep | 0 .../backend/execute/ddl_constraint/.gitkeep | 0 .../backend/execute/ddl_index/.gitkeep | 0 .../ddl_table}/test_schema_namespace.py | 2 +- .../ddl_view}/conftest.py | 3 +- .../test_materialized_view_integration.py | 2 +- .../ddl_view}/test_view_execution.py | 6 +- .../dml_insert}/test_execute_many.py | 2 +- .../test_pg19_copy_repack_integration.py | 2 +- .../dml_update_delete}/test_model_truncate.py | 2 +- .../errors}/test_driver_error_mapping.py | 2 +- .../errors/test_error_taxonomy_contract.py | 2 +- .../errors}/test_execute_error_contract.py | 2 +- .../backend/execute/fulltext_spatial/.gitkeep | 0 .../test_bitstring_functions_integration.py | 0 .../functions/test_seconds_between.py} | 9 +- .../{ => execute}/introspection/conftest.py | 4 +- .../introspection/test_introspection_basic.py | 2 +- .../introspection/test_introspection_cache.py | 2 +- .../test_introspection_cli_capabilities.py | 2 +- .../test_introspection_cli_names.py | 2 +- .../test_introspection_cli_objects.py | 4 +- .../test_introspection_columns.py | 2 +- .../test_introspection_coverage_families.py | 2 +- .../test_introspection_data_profile.py | 2 +- .../test_introspection_default_schema.py | 2 +- .../test_introspection_family_census.py | 0 .../test_introspection_foreign_keys.py | 2 +- .../test_introspection_indexes.py | 4 +- .../test_introspection_profile_source.py | 2 +- .../test_introspection_sequences.py | 2 +- .../test_introspection_tables.py | 2 +- .../test_introspection_triggers.py | 2 +- .../test_introspection_unused_indexes.py | 2 +- .../introspection/test_introspection_views.py | 2 +- .../introspection/test_status_introspector.py | 10 +- .../join}/test_qualified_reference_context.py | 2 +- .../json}/test_json_path_modes.py | 4 +- .../test_partition_advanced_operations.py | 4 +- .../partition}/test_partition_explain.py | 6 +- .../partition}/test_partition_multilevel.py | 6 +- .../partition}/test_partition_operations.py | 10 +- .../test_master_probe_execution.py | 2 +- .../test_dialect_security_integration.py | 2 +- .../test_address_standardizer_integration.py | 0 .../bloom}/test_bloom_integration.py | 0 .../btree_gin}/test_btree_gin_integration.py | 2 +- .../test_btree_gist_integration.py | 2 +- .../citext}/test_citext_integration.py | 2 +- .../extension/cube}/test_cube_integration.py | 2 +- .../extension/ddl}/test_extension_ddl.py | 2 +- .../test_earthdistance_integration.py | 2 +- .../test_fuzzystrmatch_integration.py | 2 +- .../hstore}/test_hstore_integration.py | 2 +- .../hypopg}/test_hypopg_integration.py | 2 +- .../intarray}/test_intarray_integration.py | 2 +- .../ltree}/test_ltree_integration.py | 2 +- .../orafce}/test_orafce_integration.py | 0 .../pg_cron}/test_pg_cron_integration.py | 2 +- .../test_pg_partman_integration.py | 2 +- .../pg_repack}/test_pg_repack_integration.py | 2 +- .../test_pg_stat_statements_integration.py | 2 +- .../test_pg_surgery_integration.py | 2 +- .../pg_trgm}/test_pg_trgm_integration.py | 2 +- .../test_pg_walinspect_integration.py | 2 +- .../pgaudit}/test_pgaudit_integration.py | 2 +- .../pgcrypto}/test_pgcrypto_integration.py | 2 +- .../pglogical}/test_pglogical_integration.py | 2 +- .../pgrouting}/test_pgrouting_integration.py | 0 .../pgvector}/test_pgvector_integration.py | 0 .../postgis}/test_postgis_integration.py | 2 +- .../test_postgis_raster_integration.py | 0 .../tablefunc}/test_tablefunc_integration.py | 2 +- .../uuid_ossp}/test_uuid_ossp_integration.py | 2 +- .../bitstring}/test_bitstring_integration.py | 2 +- .../types/cast}/test_cast_integration.py | 2 +- .../types/enum}/test_enum_integration.py | 0 .../test_extension_type_execution.py | 2 +- .../test_literal_values_integration.py | 2 +- .../types/lsn}/test_lsn_integration.py | 0 .../types/money}/test_money_integration.py | 0 .../test_network_address_integration.py | 0 .../types/oid}/test_oid_integration.py | 0 .../range}/test_range_types_integration.py | 2 +- .../types/xml}/test_xml_integration.py | 0 .../query}/test_backend_explain.py | 2 +- ...est_datetime_interval_explain_examples.py} | 7 +- .../test_property_graph_query_scenarios.py | 2 +- .../test_recursive_cte_graph_traversal.py | 2 +- .../query}/test_row_level_locks.py | 0 .../backend/execute/routine_domain/.gitkeep | 0 .../test_identity_execution.py | 2 +- .../backend/execute/show_admin/.gitkeep | 0 .../test_postgres_transaction_features.py} | 2 +- .../test_transaction_advanced_features.py | 2 +- .../transaction/test_transaction_backend.py | 6 +- .../test_transaction_backend_async.py} | 2 +- .../test_transaction_deferrable.py | 2 +- .../transaction/test_transaction_isolation.py | 2 +- .../test_transaction_mode_effect.py | 2 +- .../transaction/test_transaction_savepoint.py | 2 +- .../feature/basic/bulk_crud/conftest.py | 4 + .../basic/bulk_crud/test_bulk_operations.py | 2 - .../bulk_crud/test_bulk_operations_async.py | 2 + .../feature/basic/conftest.py | 27 +- .../connection/test_active_record_context.py | 2 - .../test_active_record_context_async.py | 2 + .../connection/test_active_record_crud.py | 2 - .../test_active_record_crud_async.py | 2 + .../feature/basic/core/conftest.py | 29 + .../basic/core/test_basic_mapped_models.py | 10 + .../core/test_basic_mapped_models_async.py | 1 + .../feature/basic/crud/conftest.py | 4 + .../basic/crud/test_composite_pk_crud.py | 1 - .../crud/test_composite_pk_crud_async.py | 2 + .../feature/basic/crud/test_crud.py | 2 - .../feature/basic/crud/test_crud_async.py | 2 + .../feature/basic/fields/conftest.py | 4 + .../basic/fields/test_derived_field.py | 365 --------- .../basic/fields/test_derived_field_async.py | 365 --------- .../fields/test_example_basic_fixtures.py | 1 - .../test_example_basic_fixtures_async.py | 2 + .../basic/fields/test_field_column_mapping.py | 2 - .../fields/test_field_column_mapping_async.py | 2 + .../feature/basic/fields/test_fields.py | 2 - .../feature/basic/fields/test_fields_async.py | 2 + .../feature/basic/nopk/conftest.py | 4 + .../feature/basic/nopk/test_keyless_models.py | 1 - .../basic/nopk/test_keyless_models_async.py | 1 + .../feature/basic/readonly/conftest.py | 4 + .../basic/readonly/test_readonly_models.py | 1 - .../readonly/test_readonly_models_async.py | 1 + .../feature/basic/test_basic_mapped_models.py | 20 - .../feature/basic/type_adapter/conftest.py | 4 + .../basic/type_adapter/test_type_adapter.py | 2 - .../type_adapter/test_type_adapter_async.py | 2 + .../feature/basic/validation/conftest.py | 4 + .../test_pydantic_native_validation.py | 2 - .../test_pydantic_native_validation_async.py | 2 + .../basic/validation/test_validation.py | 2 - .../basic/validation/test_validation_async.py | 2 + .../worker/test_connection_management.py | 2 - .../test_connection_management_async.py | 2 + .../basic/worker/test_parallel_crud.py | 2 - .../basic/worker/test_parallel_crud_async.py | 2 + .../worker/test_worker_pool_lifecycle.py | 2 - .../test_worker_pool_lifecycle_async.py | 2 + .../feature/cli/conftest.py | 4 +- .../feature/connection/conftest.py | 167 +---- .../feature/core/conftest.py | 2 + .../feature/{ => core}/test_features.py | 0 .../feature/{ => core}/test_features_async.py | 0 .../feature/events/conftest.py | 9 +- .../feature/events/core/conftest.py | 2 + .../feature/events/core/test_handlers.py | 9 + .../events/core/test_handlers_async.py | 5 + .../feature/events/core/test_lifecycle.py | 9 + .../events/core/test_lifecycle_async.py | 5 + .../feature/events/test_handlers.py | 25 - .../feature/events/test_handlers_async.py | 3 - .../feature/events/test_lifecycle.py | 25 - .../feature/events/test_lifecycle_async.py | 3 - .../feature/interface/test_threadsafe_dict.py | 1 - .../interface/test_threadsafe_dict_async.py | 2 + .../feature/logging/conftest.py | 6 + .../feature/mixins/conftest.py | 9 +- .../feature/mixins/core/conftest.py | 2 + .../{ => core}/test_combined_articles.py | 4 +- .../core/test_combined_articles_async.py | 5 + .../mixins/{ => core}/test_optimistic_lock.py | 4 +- .../mixins/core/test_optimistic_lock_async.py | 5 + .../mixins/{ => core}/test_soft_delete.py | 4 +- .../mixins/core/test_soft_delete_async.py | 5 + .../mixins/{ => core}/test_timestamps.py | 4 +- .../mixins/core/test_timestamps_async.py | 5 + .../mixins/test_combined_articles_async.py | 3 - .../mixins/test_optimistic_lock_async.py | 3 - .../feature/mixins/test_soft_delete_async.py | 3 - .../feature/mixins/test_timestamps_async.py | 3 - .../feature/query/aggregate/conftest.py | 4 + .../aggregate/test_active_query_aggregate.py | 2 - .../test_active_query_aggregate_async.py | 2 + .../query/aggregate/test_aggregate_queries.py | 2 - .../aggregate/test_aggregate_queries_async.py | 2 + .../feature/query/basic/conftest.py | 4 + .../query/basic/test_active_query_basic.py | 2 - .../basic/test_active_query_basic_async.py | 2 + .../feature/query/basic/test_basic.py | 2 - .../feature/query/basic/test_basic_async.py | 2 + .../query/basic/test_composite_pk_query.py | 1 - .../basic/test_composite_pk_query_async.py | 2 + .../query/basic/test_find_one_or_create.py | 1 - .../basic/test_find_one_or_create_async.py | 1 + .../feature/query/collation/conftest.py | 28 + .../feature/query/conftest.py | 1 + .../feature/query/connection/conftest.py | 1 + .../connection/test_active_query_context.py | 2 - .../test_active_query_context_async.py | 2 + .../connection/test_cte_query_context.py | 2 - .../test_cte_query_context_async.py | 2 + .../connection/test_set_operation_context.py | 2 - .../test_set_operation_context_async.py | 2 + .../feature/query/cross_database/conftest.py | 4 + .../test_cross_database_compatibility.py | 2 - ...test_cross_database_compatibility_async.py | 2 + .../feature/query/cte/conftest.py | 4 + .../query/cte/test_composite_pk_cte.py | 1 - .../query/cte/test_composite_pk_cte_async.py | 2 + .../query/cte/test_cte_query_active_query.py | 2 - .../cte/test_cte_query_active_query_async.py | 2 + .../query/cte/test_cte_query_set_operation.py | 2 - .../cte/test_cte_query_set_operation_async.py | 2 + .../feature/query/eager_loading/conftest.py | 4 + .../test_eager_loading_caching.py | 2 - .../test_eager_loading_caching_async.py | 2 + .../test_eager_loading_nested.py | 2 - .../test_eager_loading_nested_async.py | 2 + .../test_eager_loading_with_all.py | 2 - .../test_eager_loading_with_all_async.py | 2 + .../test_eager_loading_with_modifier.py | 2 - .../test_eager_loading_with_modifier_async.py | 2 + .../test_eager_loading_with_one.py | 2 - .../test_eager_loading_with_one_async.py | 2 + .../feature/query/error_handling/conftest.py | 4 + .../error_handling/test_error_handling.py | 2 - .../test_error_handling_async.py | 2 + .../feature/query/joins/conftest.py | 4 + .../query/joins/test_active_query_join.py | 2 - .../joins/test_active_query_join_async.py | 2 + .../feature/query/joins/test_joins.py | 2 - .../feature/query/joins/test_joins_async.py | 2 + .../feature/query/logging/conftest.py | 4 + .../test_logging_data_summarization.py | 2 - .../test_logging_data_summarization_async.py | 2 + .../feature/query/optimization/conftest.py | 4 + .../optimization/test_query_optimization.py | 2 - .../test_query_optimization_async.py | 2 + .../feature/query/range_queries/conftest.py | 4 + .../range_queries/test_active_query_range.py | 2 - .../test_active_query_range_async.py | 2 + .../query/range_queries/test_range_queries.py | 2 - .../range_queries/test_range_queries_async.py | 2 + .../test_range_query_detailed.py | 2 - .../test_range_query_detailed_async.py | 2 + .../feature/query/relations/conftest.py | 4 + .../relations/test_relational_validation.py | 2 - .../test_relational_validation_async.py | 2 + .../query/relations/test_relations_basic.py | 2 - .../relations/test_relations_basic_async.py | 2 + .../feature/query/set_operations/conftest.py | 4 + .../test_active_query_set_operation.py | 2 - .../test_active_query_set_operation_async.py | 2 + .../test_composite_pk_set_operation.py | 1 - .../test_composite_pk_set_operation_async.py | 2 + .../set_operations/test_set_operation.py | 2 - .../test_set_operation_async.py | 2 + .../feature/query/special/conftest.py | 4 + .../special/test_example_query_fixtures.py | 2 - .../test_example_query_fixtures_async.py | 2 + .../query/special/test_special_queries.py | 2 - .../special/test_special_queries_async.py | 2 + .../feature/query/typed_column/conftest.py | 4 + .../query/window_functions/conftest.py | 4 + .../window_functions/test_window_functions.py | 2 - .../test_window_functions_async.py | 2 + .../feature/query/worker/conftest.py | 3 +- .../query/worker/test_parallel_queries.py | 2 - .../worker/test_parallel_queries_async.py | 2 + .../feature/relation/base/conftest.py | 2 + .../feature/relation/boundary/conftest.py | 3 + .../relation/boundary/test_boundary.py | 2 - .../relation/boundary/test_boundary_async.py | 2 + .../feature/relation/cache/conftest.py | 2 + .../relation/cache/test_cache_clearing.py | 2 - .../cache/test_cache_clearing_async.py | 2 + .../feature/relation/conftest.py | 57 +- .../feature/relation/derived/conftest.py | 3 + .../derived/test_derived_field_json.py | 2 - .../derived/test_derived_field_json_async.py | 2 + .../feature/relation/descriptors/conftest.py | 2 + .../descriptors/test_descriptor_compat.py | 1 - .../test_descriptor_compat_async.py | 2 + .../relation/eager_loading/conftest.py | 3 + .../eager_loading/test_with_method.py | 2 - .../eager_loading/test_with_method_async.py | 2 + .../feature/relation/integration/conftest.py | 3 + .../relation/integration/test_integration.py | 2 - .../integration/test_integration_async.py | 2 + .../feature/relation/modifiers/conftest.py | 3 + .../modifiers/test_modifier_behavior.py | 2 - .../modifiers/test_modifier_behavior_async.py | 2 + .../modifiers/test_modifier_warning.py | 2 - .../modifiers/test_modifier_warning_async.py | 2 + .../feature/relation/ordering/conftest.py | 3 + .../ordering/test_has_many_order_by.py | 1 - .../ordering/test_has_many_order_by_async.py | 1 + .../feature/relation/validation/conftest.py | 3 + .../validation/test_path_validation.py | 2 - .../validation/test_path_validation_async.py | 2 + .../relation/validation/test_validator.py | 1 - .../validation/test_validator_async.py | 2 + .../feature/backend/cli/test_cli_blackbox.py | 2 +- tests/support/__init__.py | 2 + tests/support/postgres.py | 131 ++++ 477 files changed, 1199 insertions(+), 6598 deletions(-) create mode 100644 tests/benchmark/activerecord_bulk/test_bulk_create_async.py delete mode 100644 tests/providers/basic.py delete mode 100644 tests/providers/basic_connection.py delete mode 100644 tests/providers/crud_benchmark.py delete mode 100644 tests/providers/events.py delete mode 100644 tests/providers/fastapi_benchmark.py delete mode 100644 tests/providers/fixtures/__init__.py delete mode 100644 tests/providers/fixtures/_common.py delete mode 100644 tests/providers/fixtures/basic.py delete mode 100644 tests/providers/fixtures/events.py delete mode 100644 tests/providers/fixtures/mixins.py delete mode 100644 tests/providers/fixtures/query.py delete mode 100644 tests/providers/mixin_benchmark.py delete mode 100644 tests/providers/mixins.py delete mode 100644 tests/providers/partition.py delete mode 100644 tests/providers/pooling.py delete mode 100644 tests/providers/query.py delete mode 100644 tests/providers/query_benchmark.py delete mode 100644 tests/providers/query_connection.py delete mode 100644 tests/providers/registry.py delete mode 100644 tests/providers/relation.py delete mode 100644 tests/providers/scenarios.py delete mode 100644 tests/providers/transaction_benchmark.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/.gitkeep create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/connection/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/ddl}/test_auto_increment_ddl.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_column_definition.py => construct/ddl/test_column_definition.py} (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_constraint_capabilities.py => construct/ddl/test_constraint_capabilities.py} (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/ddl}/test_create_table_like.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_postgres_database_ddl.py => construct/ddl/test_database_ddl.py} (91%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/ddl}/test_ddl_source_collection.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/ddl}/test_generated_column_capabilities.py (87%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_alter_table_if_exists.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_database_size_introspection.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_postgres_ddl_improvements.py => construct/dialect/test_ddl_improvements.py} (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/dialect}/test_ddl_protocols.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/dialect}/test_dialect_function_support.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_postgres_dialect_security.py => construct/dialect/test_dialect_security.py} (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_dql_capabilities.py (90%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_drop_table_cascade.py (94%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/dialect}/test_function_versions.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/dialect}/test_identifier_quoting.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/dialect}/test_ilike_support.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_insert_on_conflict_clauses.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_introspection_parsing.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_kind_hygiene.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_materialized_view.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_materialized_view_docs.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_materialized_view_introspection.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_object_kind_guards.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_property_graph_query_format.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_postgres_protocol_conformance.py => construct/dialect/test_protocol_conformance.py} (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_returning_capabilities.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_schema_support.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/dialect}/test_set_operation_and_truncate.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_status_query_nodes.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/dialect/test_table_storage_introspection.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/dialect}/test_version_features.py (98%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/errors/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/expression/conftest.py (94%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/expression}/test_clause_pair_guard.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/expression}/test_domain_expression_roundtrip.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/expression}/test_expression_namespace.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/expression}/test_expression_roundtrip_all.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/expression/test_expression_signatures.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/expression/test_expressions_transaction.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/expression/vector_search_test.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/expression_roundtrip_harness.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_array_functions.py => construct/functions/test_array_functions.py} (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_datetime_interval_expressions.py => construct/functions/test_datetime_interval_expressions.py} (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/functions}/test_extension_type_operations.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/functions}/test_extensions.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_hstore_functions.py => construct/functions/test_hstore_functions.py} (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_math_enhanced_functions.py => construct/functions/test_math_enhanced_functions.py} (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_network_functions.py => construct/functions/test_network_functions.py} (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_pgvector_functions.py => construct/functions/test_pgvector_functions.py} (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_postgis_functions.py => construct/functions/test_postgis_functions.py} (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_range_constructors.py => construct/functions/test_range_constructors.py} (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/functions}/test_range_functions.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_uuid_functions.py => construct/functions/test_uuid_functions.py} (93%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/introspection/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_address_standardizer.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_bloom.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_btree_gin.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_btree_gist.py (94%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_citext.py (94%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_cube.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_ddl_alter_config.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_extended_statistics.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_fuzzystrmatch.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_hypopg.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_index_pg.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_orafce.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pg_cron.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pg_partman.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pg_repack.py (91%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pg_stat_statements.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pg_surgery.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pg_walinspect.py (94%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pgaudit.py (88%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pgcrypto.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_pglogical.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_policy.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_stored_procedure.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_table.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_tablefunc.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/mixins}/test_trigger.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => construct/mixins}/test_uuid_ossp.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/partition_syntax_fixtures.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/test_ddl_expressions.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/test_ddl_objects.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/test_expressions.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/test_partition_plan.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/test_partition_syntax_matrix.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/statements}/test_pg19_copy_repack.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{transaction => construct/statements}/test_set_constraints_statement.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/types}/test_adapters.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_bitstring_types.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/types/test_column_type_suggestions.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_core_type_mappings.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/types/test_data_type_formatting.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_enum_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct}/types/test_expression_types.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_geometry_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_hstore_types.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_jsonpath_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_literal_values.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_lsn_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_macaddr8_types.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_money_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_oid_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_pgvector_types.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_postgis_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_range_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_textsearch_types.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_type_casting.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => construct/types}/test_type_compatibility.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{types/test_postgres_type_protocol.py => construct/types/test_type_protocol.py} (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_uuid_type_adapter.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_uuid_values.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => construct/types}/test_xml_types.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => core}/examples_compile_test.py (88%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => core}/test_async_support.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{named_connection => execute/cli}/conftest.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{named_connection => execute/cli}/example_connections.py (92%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/cli}/test_cli.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/cli}/test_cli_connection_args.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{named_connection => execute/cli}/test_named_connection_cli.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{named_connection => execute/cli}/test_resolver.py (92%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/concurrency}/test_advisory_lock.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/concurrency}/test_concurrency_protocol.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_backend_initialization.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_config.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/connection}/test_connection_config.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_connection_resilience.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_cursor_pollution.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_dialect.py (90%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_ssl_connection_params.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/connection}/test_version.py (90%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/crud}/test_column_mapping_backend.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_async_column_mapping_backend.py => execute/crud/test_column_mapping_backend_async.py} (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/crud}/test_crud_backend.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_async_crud_backend.py => execute/crud/test_crud_backend_async.py} (97%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_column/.gitkeep create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_constraint/.gitkeep create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_index/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/ddl_table}/test_schema_namespace.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/ddl_view}/conftest.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/ddl_view}/test_materialized_view_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/ddl_view}/test_view_execution.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/dml_insert}/test_execute_many.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/dml_insert}/test_pg19_copy_repack_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/dml_update_delete}/test_model_truncate.py (93%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/errors}/test_driver_error_mapping.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/errors/test_error_taxonomy_contract.py (77%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/errors}/test_execute_error_contract.py (99%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/fulltext_spatial/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/functions}/test_bitstring_functions_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/test_postgres_seconds_between.py => execute/functions/test_seconds_between.py} (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/conftest.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_basic.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_cache.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_cli_capabilities.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_cli_names.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_cli_objects.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_columns.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_coverage_families.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/introspection}/test_introspection_data_profile.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_default_schema.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_family_census.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_foreign_keys.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_indexes.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/introspection}/test_introspection_profile_source.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_sequences.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_tables.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_triggers.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_unused_indexes.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_introspection_views.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/introspection/test_status_introspector.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/join}/test_qualified_reference_context.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/json}/test_json_path_modes.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/partition}/test_partition_advanced_operations.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/partition}/test_partition_explain.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/partition}/test_partition_multilevel.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/partition}/test_partition_operations.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/postgres/capability_probe}/test_master_probe_execution.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/dialect_security}/test_dialect_security_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/address_standardizer}/test_address_standardizer_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/bloom}/test_bloom_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/btree_gin}/test_btree_gin_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/btree_gist}/test_btree_gist_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/citext}/test_citext_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/cube}/test_cube_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/postgres/extension/ddl}/test_extension_ddl.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/earthdistance}/test_earthdistance_integration.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/fuzzystrmatch}/test_fuzzystrmatch_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/hstore}/test_hstore_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/hypopg}/test_hypopg_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/intarray}/test_intarray_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/ltree}/test_ltree_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/orafce}/test_orafce_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_cron}/test_pg_cron_integration.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_partman}/test_pg_partman_integration.py (96%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_repack}/test_pg_repack_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_stat_statements}/test_pg_stat_statements_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_surgery}/test_pg_surgery_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_trgm}/test_pg_trgm_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pg_walinspect}/test_pg_walinspect_integration.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pgaudit}/test_pgaudit_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pgcrypto}/test_pgcrypto_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pglogical}/test_pglogical_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pgrouting}/test_pgrouting_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/pgvector}/test_pgvector_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/postgis}/test_postgis_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/postgis_raster}/test_postgis_raster_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/tablefunc}/test_tablefunc_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres/extensions => execute/postgres/extension/uuid_ossp}/test_uuid_ossp_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/bitstring}/test_bitstring_integration.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/cast}/test_cast_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/enum}/test_enum_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/extension_types}/test_extension_type_execution.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/literal}/test_literal_values_integration.py (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/lsn}/test_lsn_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/money}/test_money_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/network}/test_network_address_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/oid}/test_oid_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/range}/test_range_types_integration.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/postgres/types/xml}/test_xml_integration.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/query}/test_backend_explain.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{test_postgres_datetime_interval_explain_examples.py => execute/query/test_datetime_interval_explain_examples.py} (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/query}/test_property_graph_query_scenarios.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{postgres => execute/query}/test_recursive_cte_graph_traversal.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/query}/test_row_level_locks.py (100%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/routine_domain/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute/sequence_identity}/test_identity_execution.py (98%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/show_admin/.gitkeep rename tests/rhosocial/activerecord_postgres_test/feature/backend/{transaction/test_transaction_postgres.py => execute/transaction/test_postgres_transaction_features.py} (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/transaction/test_transaction_advanced_features.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/transaction/test_transaction_backend.py (95%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{transaction/test_async_transaction_backend.py => execute/transaction/test_transaction_backend_async.py} (97%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/transaction/test_transaction_deferrable.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/transaction/test_transaction_isolation.py (98%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/transaction/test_transaction_mode_effect.py (99%) rename tests/rhosocial/activerecord_postgres_test/feature/backend/{ => execute}/transaction/test_transaction_savepoint.py (99%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py rename tests/rhosocial/activerecord_postgres_test/feature/{ => core}/test_features.py (100%) rename tests/rhosocial/activerecord_postgres_test/feature/{ => core}/test_features_async.py (100%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py rename tests/rhosocial/activerecord_postgres_test/feature/mixins/{ => core}/test_combined_articles.py (60%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py rename tests/rhosocial/activerecord_postgres_test/feature/mixins/{ => core}/test_optimistic_lock.py (60%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py rename tests/rhosocial/activerecord_postgres_test/feature/mixins/{ => core}/test_soft_delete.py (61%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py rename tests/rhosocial/activerecord_postgres_test/feature/mixins/{ => core}/test_timestamps.py (61%) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py create mode 100644 tests/support/__init__.py create mode 100644 tests/support/postgres.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 449317f5..4f1f5dab 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -63,8 +63,8 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR - name: Install dependencies run: | @@ -122,14 +122,14 @@ jobs: python -m pytest \ --rootdir=. \ --confcutdir=. \ - "$TESTSUITE_DIR/benchmark/crud/test_delete_async.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_delete.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_insert_async.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_insert.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_query_async.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_query.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_update_async.py" \ - "$TESTSUITE_DIR/benchmark/crud/test_update.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_delete_async.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_delete.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_insert_async.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_insert.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_query_async.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_query.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_update_async.py" \ + "$TESTSUITE_DIR/benchmark/crud/core/test_update.py" \ "$TESTSUITE_DIR/benchmark/query" \ "$TESTSUITE_DIR/benchmark/transaction" \ "$TESTSUITE_DIR/benchmark/mixin" \ @@ -278,8 +278,8 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR - name: Install dependencies run: | @@ -385,8 +385,8 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR - name: Install dependencies run: | @@ -488,8 +488,8 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR - name: Install dependencies run: | diff --git a/pyproject.toml b/pyproject.toml index f48098c1..1edd80f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -85,7 +85,7 @@ minversion = "7.0" # an explicit xdist_group is the only thing that serialises a case, and the # worker count is the caller's (-n). The expression directory pins the same # mode for its own runs; see its conftest. -addopts = "-ra -q -p rhosocial.activerecord.testsuite.conftest --dist=loadgroup" +addopts = "-ra -q --dist=loadgroup" asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" testpaths = [ diff --git a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py index aacaf9d5..16d5597c 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py @@ -145,6 +145,7 @@ ILIKESupport, IntrospectionSupport, TransactionControlSupport, + TransactionalDDLSupport, SQLFunctionSupport, DDLTypeSupport, ) @@ -668,6 +669,7 @@ class PostgresDialect( IntrospectionSupport, # Transaction control protocol TransactionControlSupport, + TransactionalDDLSupport, # PostgreSQL-specific protocols PostgresExtensionSupport, PostgresMaterializedViewSupport, @@ -861,6 +863,10 @@ def get_server_version(self) -> Tuple[int, int, int]: """Return the PostgreSQL version this dialect is configured for.""" return self.version + def supports_transactional_ddl(self) -> bool: + """PostgreSQL DDL participates in transactions.""" + return True + def supports_table_function(self) -> bool: """PostgreSQL reads a set-returning function as a row source. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/transaction.py b/src/rhosocial/activerecord/backend/impl/postgres/transaction.py index 701e36d8..7a7e46d9 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/transaction.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/transaction.py @@ -306,3 +306,7 @@ async def rollback(self) -> None: # Clear deferred constraints when outermost transaction rolls back if self._transaction_level == 0: self._deferred_constraints.clear() + + async def supports_savepoint(self) -> bool: + """Async counterpart of the sync capability probe.""" + return self._backend.dialect.supports_savepoint() diff --git a/tests/benchmark/activerecord_bulk/test_bulk_create.py b/tests/benchmark/activerecord_bulk/test_bulk_create.py index 8abfa754..4c1ce6f1 100644 --- a/tests/benchmark/activerecord_bulk/test_bulk_create.py +++ b/tests/benchmark/activerecord_bulk/test_bulk_create.py @@ -1,5 +1,2 @@ # Bridge file for bulk_create benchmark tests from the testsuite. -from rhosocial.activerecord.testsuite.benchmark.crud.test_bulk_create import * # noqa: F401, F403 -from rhosocial.activerecord.testsuite.benchmark.crud.test_bulk_create_async import * # noqa: F403 -from rhosocial.activerecord.testsuite.benchmark.crud.test_bulk_create_async import * # noqa: F401, F403 - +from rhosocial.activerecord.testsuite.benchmark.crud.core.test_bulk_create import * # noqa: F401, F403 diff --git a/tests/benchmark/activerecord_bulk/test_bulk_create_async.py b/tests/benchmark/activerecord_bulk/test_bulk_create_async.py new file mode 100644 index 00000000..5e874a24 --- /dev/null +++ b/tests/benchmark/activerecord_bulk/test_bulk_create_async.py @@ -0,0 +1,2 @@ +from rhosocial.activerecord.testsuite.benchmark.crud.core.test_bulk_create_async import * # noqa: F403 +from rhosocial.activerecord.testsuite.benchmark.crud.core.test_bulk_create_async import * # noqa: F401, F403 diff --git a/tests/benchmark/backend/conftest.py b/tests/benchmark/backend/conftest.py index a8371131..f5beac37 100644 --- a/tests/benchmark/backend/conftest.py +++ b/tests/benchmark/backend/conftest.py @@ -13,7 +13,7 @@ payload_count_for_size, ) -from providers.scenarios import get_enabled_scenarios, get_scenario +from support.postgres import get_enabled_scenarios, get_scenario @dataclass diff --git a/tests/benchmark/relation/conftest.py b/tests/benchmark/relation/conftest.py index cce2ecbd..6076e4a1 100644 --- a/tests/benchmark/relation/conftest.py +++ b/tests/benchmark/relation/conftest.py @@ -7,10 +7,6 @@ source snippets are kept as comments for follow-up external cache design. """ -from rhosocial.activerecord.testsuite.feature.relation.conftest import ( # noqa: F401 - user_post_comment_classes, -) - from dataclasses import dataclass from typing import Any @@ -22,6 +18,28 @@ # Not introduced in this release; keep snippets for follow-up external cache design. # from rhosocial.activerecord.relation.cache_backends import CacheSerializer, RedisCache +from rhosocial.activerecord.testsuite.feature.relation.conftest import ( # noqa: F401 + user_post_comment_classes, +) +from rhosocial.activerecord.testsuite.feature.relation.fixtures import tables + +GROUP_TABLES = ("users", "posts", "comments") + + +def ensure_database(environment): + environment.reset_database() + + +def prepare(environment): + for name in GROUP_TABLES: + environment.execute(tables.RELATION_TABLES[name](environment.dialect)) + + +def teardown(environment): + for name in reversed(GROUP_TABLES): + environment.execute(tables.drop_table(environment.dialect, name)) + + pytestmark = [ pytest.mark.benchmark, pytest.mark.benchmark_relation, diff --git a/tests/conftest.py b/tests/conftest.py index cfd3b1c8..d73453a8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,18 +1,21 @@ # tests/conftest.py -""" -This is the root pytest configuration file for the rhosocial-activerecord-postgres package's test suite. +"""Root configuration for the PostgreSQL backend's test tree. -Its primary responsibility is to configure the environment so that the external -`rhosocial-activerecord-testsuite` can find and use the backend-specific -implementations (Providers) defined within this project. +The backend knows its own classes and how a scenario maps to a connection, so +no declaration table is needed here: the scenario is exposed as a parameterized +pytest fixture that the testsuite environment consumes. """ + import asyncio -import os import selectors import sys import pytest +import support.postgres + +_SCENARIOS = [support.postgres.scenario(name) for name in support.postgres.SCENARIOS] + if sys.platform == "win32": @@ -34,176 +37,10 @@ def pytest_asyncio_loop_factories(config, item): said. Elsewhere the default loop is already selector-based, and the async tests' node ids stay exactly as they were. """ - return { - "selector": lambda: asyncio.SelectorEventLoop(selectors.SelectSelector()) - } - - -# Set the environment variable that the testsuite uses to locate the provider registry. -# The testsuite is a generic package and doesn't know the specific location of the -# provider implementations for this backend (postgres). This environment variable -# acts as a bridge, pointing the testsuite to the correct import path. -# -# `setdefault` is used to ensure that this value is set only if it hasn't been -# set already, allowing for overrides in different environments if needed. -os.environ.setdefault( - 'TESTSUITE_PROVIDER_REGISTRY', - 'providers.registry:provider_registry' -) - -# Early-parse --scenarios from sys.argv and set POSTGRES_ACTIVE_SCENARIOS env var. -# This must happen before providers.scenarios is imported (it filters its -# SCENARIO_MAP at import time). -_argv_scenarios = None -for _i, _arg in enumerate(sys.argv): - if _arg.startswith('--scenarios='): - _argv_scenarios = _arg.split('=', 1)[1] - elif _arg == '--scenarios' and _i + 1 < len(sys.argv): - _argv_scenarios = sys.argv[_i + 1] - -if _argv_scenarios: - os.environ['POSTGRES_ACTIVE_SCENARIOS'] = _argv_scenarios - -# ============================================================================= -# Scenario Parallel Scheduling Plugin -# -# Usage: -# pytest --scenario-parallel -n --dist=loadgroup tests/ -# -# Design: All tests for the same scenario are pinned to the same xdist worker -# (via nodeid @suffix), while tests for different scenarios run in -# parallel. Behavior is unchanged without --scenario-parallel. -# ============================================================================= - - -def _get_scenario_names(): - """Lazy import to avoid side effects during conftest loading.""" - try: - from providers.scenarios import SCENARIO_MAP - return set(SCENARIO_MAP.keys()), list(SCENARIO_MAP.keys()) - except Exception: - return set(), [] - - -def _extract_scenario_from_item(item, scenario_name_set): - """Extract scenario name from item's callspec. - - Returns: - str: scenario name when exactly one scenario param is found - None: no scenario params (not a scenario-parametrized test) - list: multiple distinct scenario names (cross-scenario test) - """ - callspec = getattr(item, 'callspec', None) - if callspec is None: - return None - scenario_values = [ - v for v in callspec.params.values() - if isinstance(v, str) and v in scenario_name_set - ] - if len(scenario_values) == 1: - return scenario_values[0] - if len(scenario_values) >= 2: - return scenario_values # cross-scenario: caller checks isinstance(result, list) - return None - - -def _add_xdist_group_marker(item, group_name): - """Append @group_name suffix to item._nodeid for loadgroup scheduling.""" - suffix = f"@{group_name}" - if suffix not in item.nodeid: - item._nodeid = item.nodeid + suffix - - -def pytest_addoption(parser): - parser.addoption( - '--scenario-parallel', - action='store_true', - default=False, - help='Scenario parallel mode: distribute scenarios across workers, keep each scenario on one worker.', - ) - # The generic --scenarios option is registered by the testsuite conftest - # (loaded via ``addopts``); register it here only when it is not already - # present so the two conftests can coexist. - try: - parser.addoption( - '--scenarios', - default=None, - help='Comma-separated list of scenario names to run (e.g., --scenarios=postgres_16,postgres_17). ' - 'Compatible with pytest -k "" as a native alternative.', - ) - except ValueError: - pass - - -def pytest_configure(config): - config.addinivalue_line( - "markers", - "xdist_group(name): specify the xdist group for a test (provided by pytest-xdist).", - ) - - # Propagate --scenarios to environment variable so that all conftest.py - # instances (which load SCENARIO_MAP independently) can filter consistently. - scenarios_opt = config.getoption('--scenarios', default=None) - if scenarios_opt: - os.environ['POSTGRES_ACTIVE_SCENARIOS'] = scenarios_opt - - -def pytest_collection_modifyitems(config, items): - if not config.getoption('--scenario-parallel', default=False): - return - - scenario_name_set, scenario_name_list = _get_scenario_names() - if not scenario_name_set: - return - - scenario_items = [] - cross_scenario_items = [] - normal_items = [] - - for item in items: - result = _extract_scenario_from_item(item, scenario_name_set) - if isinstance(result, list): - item.add_marker( - pytest.mark.skip( - reason="Cross-scenario test skipped in --scenario-parallel mode. " - "Run without --scenario-parallel for serial execution." - ) - ) - cross_scenario_items.append(item) - elif isinstance(result, str): - _add_xdist_group_marker(item, result) - scenario_items.append(item) - else: - normal_items.append(item) - - def sort_key(item): - result = _extract_scenario_from_item(item, scenario_name_set) - if not isinstance(result, str): - return ('~', 0) - try: - scenario_idx = scenario_name_list.index(result) - except ValueError: - scenario_idx = 0 - base = item.nodeid.split('[')[0] if '[' in item.nodeid else item.nodeid - return (base, scenario_idx) - - first_scenario = scenario_name_list[0] - for item in normal_items: - _add_xdist_group_marker(item, first_scenario) - scenario_items.extend(normal_items) - normal_items = [] - - scenario_items.sort(key=sort_key) - items[:] = scenario_items + normal_items + cross_scenario_items + return {"selector": lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())} - groups: dict = {} - for item in scenario_items: - sn = _extract_scenario_from_item(item, scenario_name_set) - if isinstance(sn, str): - base = item.nodeid.split('[')[0] if '[' in item.nodeid else item.nodeid - groups.setdefault(base, set()).add(sn) - print(f"\n[ScenarioParallel] {len(items)} items: {len(scenario_items)} scenario-param + " - f"{len(normal_items)} normal + {len(cross_scenario_items)} cross-scenario (skipped)") - print(f"[ScenarioParallel] {len(groups)} test methods, {len(scenario_name_list)} scenarios in parallel") - print(f"[ScenarioParallel] Suggested: --dist=loadgroup -n {len(scenario_name_list)}") +@pytest.fixture(scope="session", params=_SCENARIOS, ids=lambda scenario: scenario.name) +def backend_scenario(request): + """Return the scenario the tests run against; its id is the scenario name.""" + return request.param diff --git a/tests/providers/basic.py b/tests/providers/basic.py deleted file mode 100644 index 7547b1f4..00000000 --- a/tests/providers/basic.py +++ /dev/null @@ -1,514 +0,0 @@ -""" -This file provides the concrete implementation of the `IBasicProvider` interface -that is defined in the `rhosocial-activerecord-testsuite` package. - -Its main responsibilities are: -1. Reporting which test scenarios (database configurations) are available. -2. Setting up the database environment for a given test. This includes: - - Getting the correct database configuration for the scenario. - - Configuring the ActiveRecord model with a database connection. - - Dropping any old tables and creating the necessary table schema. -3. Cleaning up any resources after a test runs. -""" -import os -import sys -import logging -from typing import Type, List, Tuple, Optional, Set # noqa: F401 - -logger = logging.getLogger(__name__) - -from rhosocial.activerecord.model import ActiveRecord # noqa: E402 -from rhosocial.activerecord.backend.type_adapter import BaseSQLTypeAdapter # noqa: E402 -from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402 -from rhosocial.activerecord.testsuite.feature.basic.interfaces import IBasicSyncProvider, IBasicAsyncProvider # noqa: E402 -from rhosocial.activerecord.testsuite.core.protocols import WorkerTestProtocol # noqa: E402 - -# Import the fixture selector utility -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -# Expression-based DDL fixtures -from providers.fixtures._common import drop_table # noqa: E402 -from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_TABLE_EXPRESSIONS # noqa: E402 - -# Import base version models (Python 3.8+) -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - User as UserBase, TypeCase as TypeCaseBase, ValidatedFieldUser as ValidatedFieldUserBase, - TypeTestModel as TypeTestModelBase, ValidatedUser as ValidatedUserBase, - TypeAdapterTest as TypeAdapterTestBase, YesOrNoBooleanAdapter, - PydanticValidatedModel as PydanticValidatedModelBase, - MappedUser as MappedUserBase, MappedPost as MappedPostBase, MappedComment as MappedCommentBase, - ColumnMappingModel as ColumnMappingModelBase, MixedAnnotationModel as MixedAnnotationModelBase -) -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - BulkUser as BulkUserBase, AsyncBulkUser as AsyncBulkUserBase -) -# Import async base models -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - AsyncUser as AsyncUserBase, AsyncTypeCase as AsyncTypeCaseBase, - AsyncValidatedUser as AsyncValidatedUserBase, AsyncValidatedFieldUser as AsyncValidatedFieldUserBase, - AsyncTypeTestModel as AsyncTypeTestModelBase, AsyncTypeAdapterTest as AsyncTypeAdapterTestBase, - AsyncPydanticValidatedModel as AsyncPydanticValidatedModelBase, - AsyncMappedUser as AsyncMappedUserBase, AsyncMappedPost as AsyncMappedPostBase, - AsyncMappedComment as AsyncMappedCommentBase, - AsyncColumnMappingModel as AsyncColumnMappingModelBase, AsyncMixedAnnotationModel as AsyncMixedAnnotationModelBase -) - -# Conditionally import Python 3.10+ models -User310 = TypeCase310 = ValidatedFieldUser310 = TypeTestModel310 = ValidatedUser310 = None -TypeAdapterTest310 = PydanticValidatedModel310 = MappedUser310 = MappedPost310 = MappedComment310 = None -ColumnMappingModel310 = MixedAnnotationModel310 = None -AsyncUser310 = AsyncTypeCase310 = AsyncValidatedFieldUser310 = AsyncTypeTestModel310 = None -AsyncValidatedUser310 = AsyncTypeAdapterTest310 = AsyncPydanticValidatedModel310 = AsyncMappedUser310 = AsyncMappedPost310 = None # noqa: E501 -AsyncMappedComment310 = AsyncColumnMappingModel310 = AsyncMixedAnnotationModel310 = None - -if sys.version_info >= (3, 10): - try: - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py310 import ( - User as User310, TypeCase as TypeCase310, ValidatedFieldUser as ValidatedFieldUser310, - TypeTestModel as TypeTestModel310, ValidatedUser as ValidatedUser310, - TypeAdapterTest as TypeAdapterTest310, PydanticValidatedModel as PydanticValidatedModel310, - MappedUser as MappedUser310, MappedPost as MappedPost310, MappedComment as MappedComment310, - ColumnMappingModel as ColumnMappingModel310, MixedAnnotationModel as MixedAnnotationModel310 - ) - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py310 import ( - AsyncUser as AsyncUser310, AsyncTypeCase as AsyncTypeCase310, - AsyncValidatedUser as AsyncValidatedUser310, AsyncValidatedFieldUser as AsyncValidatedFieldUser310, - AsyncTypeTestModel as AsyncTypeTestModel310, AsyncTypeAdapterTest as AsyncTypeAdapterTest310, - AsyncPydanticValidatedModel as AsyncPydanticValidatedModel310, - AsyncMappedUser as AsyncMappedUser310, AsyncMappedPost as AsyncMappedPost310, - AsyncMappedComment as AsyncMappedComment310, - AsyncColumnMappingModel as AsyncColumnMappingModel310, AsyncMixedAnnotationModel as AsyncMixedAnnotationModel310 # noqa: E501 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.10+ fixtures: {e}") - -# Conditionally import Python 3.11+ models -User311 = TypeCase311 = ValidatedFieldUser311 = TypeTestModel311 = ValidatedUser311 = None -TypeAdapterTest311 = PydanticValidatedModel311 = MappedUser311 = MappedPost311 = MappedComment311 = None -ColumnMappingModel311 = MixedAnnotationModel311 = None -AsyncUser311 = AsyncTypeCase311 = AsyncValidatedFieldUser311 = AsyncTypeTestModel311 = None -AsyncValidatedUser311 = AsyncTypeAdapterTest311 = AsyncPydanticValidatedModel311 = AsyncMappedUser311 = AsyncMappedPost311 = None # noqa: E501 -AsyncMappedComment311 = AsyncColumnMappingModel311 = AsyncMixedAnnotationModel311 = None - -if sys.version_info >= (3, 11): - try: - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py311 import ( - User as User311, TypeCase as TypeCase311, ValidatedFieldUser as ValidatedFieldUser311, - TypeTestModel as TypeTestModel311, ValidatedUser as ValidatedUser311, - TypeAdapterTest as TypeAdapterTest311, PydanticValidatedModel as PydanticValidatedModel311, - MappedUser as MappedUser311, MappedPost as MappedPost311, MappedComment as MappedComment311, - ColumnMappingModel as ColumnMappingModel311, MixedAnnotationModel as MixedAnnotationModel311 - ) - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py311 import ( - AsyncUser as AsyncUser311, AsyncTypeCase as AsyncTypeCase311, - AsyncValidatedUser as AsyncValidatedUser311, AsyncValidatedFieldUser as AsyncValidatedFieldUser311, - AsyncTypeTestModel as AsyncTypeTestModel311, AsyncTypeAdapterTest as AsyncTypeAdapterTest311, - AsyncPydanticValidatedModel as AsyncPydanticValidatedModel311, - AsyncMappedUser as AsyncMappedUser311, AsyncMappedPost as AsyncMappedPost311, - AsyncMappedComment as AsyncMappedComment311, - AsyncColumnMappingModel as AsyncColumnMappingModel311, AsyncMixedAnnotationModel as AsyncMixedAnnotationModel311 # noqa: E501 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.11+ fixtures: {e}") - -# Conditionally import Python 3.12+ models -User312 = TypeCase312 = ValidatedFieldUser312 = TypeTestModel312 = ValidatedUser312 = None -TypeAdapterTest312 = PydanticValidatedModel312 = MappedUser312 = MappedPost312 = MappedComment312 = None -ColumnMappingModel312 = MixedAnnotationModel312 = None -AsyncUser312 = AsyncTypeCase312 = AsyncValidatedFieldUser312 = AsyncTypeTestModel312 = None -AsyncValidatedUser312 = AsyncTypeAdapterTest312 = AsyncPydanticValidatedModel312 = AsyncMappedUser312 = AsyncMappedPost312 = None # noqa: E501 -AsyncMappedComment312 = AsyncColumnMappingModel312 = AsyncMixedAnnotationModel312 = None - -if sys.version_info >= (3, 12): - try: - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py312 import ( - User as User312, TypeCase as TypeCase312, ValidatedFieldUser as ValidatedFieldUser312, - TypeTestModel as TypeTestModel312, ValidatedUser as ValidatedUser312, - TypeAdapterTest as TypeAdapterTest312, PydanticValidatedModel as PydanticValidatedModel312, - MappedUser as MappedUser312, MappedPost as MappedPost312, MappedComment as MappedComment312, - ColumnMappingModel as ColumnMappingModel312, MixedAnnotationModel as MixedAnnotationModel312 - ) - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py312 import ( - AsyncUser as AsyncUser312, AsyncTypeCase as AsyncTypeCase312, - AsyncValidatedUser as AsyncValidatedUser312, AsyncValidatedFieldUser as AsyncValidatedFieldUser312, - AsyncTypeTestModel as AsyncTypeTestModel312, AsyncTypeAdapterTest as AsyncTypeAdapterTest312, - AsyncPydanticValidatedModel as AsyncPydanticValidatedModel312, - AsyncMappedUser as AsyncMappedUser312, AsyncMappedPost as AsyncMappedPost312, - AsyncMappedComment as AsyncMappedComment312, - AsyncColumnMappingModel as AsyncColumnMappingModel312, AsyncMixedAnnotationModel as AsyncMixedAnnotationModel312 # noqa: E501 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.12+ fixtures: {e}") - - -# Select appropriate fixture classes based on Python version -def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type: - """Select the most appropriate model class for the current Python version.""" - candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None] - selected = select_fixture(*candidates) - logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}") - return selected - - -# Select sync models -User = _select_model_class(UserBase, User312, User311, User310, "User") -TypeCase = _select_model_class(TypeCaseBase, TypeCase312, TypeCase311, TypeCase310, "TypeCase") -ValidatedFieldUser = _select_model_class(ValidatedFieldUserBase, ValidatedFieldUser312, ValidatedFieldUser311, ValidatedFieldUser310, "ValidatedFieldUser") # noqa: E501 -TypeTestModel = _select_model_class(TypeTestModelBase, TypeTestModel312, TypeTestModel311, TypeTestModel310, "TypeTestModel") # noqa: E501 -ValidatedUser = _select_model_class(ValidatedUserBase, ValidatedUser312, ValidatedUser311, ValidatedUser310, "ValidatedUser") # noqa: E501 -TypeAdapterTest = _select_model_class(TypeAdapterTestBase, TypeAdapterTest312, TypeAdapterTest311, TypeAdapterTest310, "TypeAdapterTest") # noqa: E501 -PydanticValidatedModel = _select_model_class(PydanticValidatedModelBase, PydanticValidatedModel312, PydanticValidatedModel311, PydanticValidatedModel310, "PydanticValidatedModel") # noqa: E501 -MappedUser = _select_model_class(MappedUserBase, MappedUser312, MappedUser311, MappedUser310, "MappedUser") -MappedPost = _select_model_class(MappedPostBase, MappedPost312, MappedPost311, MappedPost310, "MappedPost") -MappedComment = _select_model_class(MappedCommentBase, MappedComment312, MappedComment311, MappedComment310, "MappedComment") # noqa: E501 -ColumnMappingModel = _select_model_class(ColumnMappingModelBase, ColumnMappingModel312, ColumnMappingModel311, ColumnMappingModel310, "ColumnMappingModel") # noqa: E501 -MixedAnnotationModel = _select_model_class(MixedAnnotationModelBase, MixedAnnotationModel312, MixedAnnotationModel311, MixedAnnotationModel310, "MixedAnnotationModel") # noqa: E501 - -# Select async models -AsyncUser = _select_model_class(AsyncUserBase, AsyncUser312, AsyncUser311, AsyncUser310, "AsyncUser") -AsyncTypeCase = _select_model_class(AsyncTypeCaseBase, AsyncTypeCase312, AsyncTypeCase311, AsyncTypeCase310, "AsyncTypeCase") # noqa: E501 -AsyncValidatedFieldUser = _select_model_class(AsyncValidatedFieldUserBase, AsyncValidatedFieldUser312, AsyncValidatedFieldUser311, AsyncValidatedFieldUser310, "AsyncValidatedFieldUser") # noqa: E501 -AsyncTypeTestModel = _select_model_class(AsyncTypeTestModelBase, AsyncTypeTestModel312, AsyncTypeTestModel311, AsyncTypeTestModel310, "AsyncTypeTestModel") # noqa: E501 -AsyncValidatedUser = _select_model_class(AsyncValidatedUserBase, AsyncValidatedUser312, AsyncValidatedUser311, AsyncValidatedUser310, "AsyncValidatedUser") # noqa: E501 -AsyncTypeAdapterTest = _select_model_class(AsyncTypeAdapterTestBase, AsyncTypeAdapterTest312, AsyncTypeAdapterTest311, AsyncTypeAdapterTest310, "AsyncTypeAdapterTest") # noqa: E501 -AsyncPydanticValidatedModel = _select_model_class(AsyncPydanticValidatedModelBase, AsyncPydanticValidatedModel312, AsyncPydanticValidatedModel311, AsyncPydanticValidatedModel310, "AsyncPydanticValidatedModel") # noqa: E501 -AsyncMappedUser = _select_model_class(AsyncMappedUserBase, AsyncMappedUser312, AsyncMappedUser311, AsyncMappedUser310, "AsyncMappedUser") # noqa: E501 -AsyncMappedPost = _select_model_class(AsyncMappedPostBase, AsyncMappedPost312, AsyncMappedPost311, AsyncMappedPost310, "AsyncMappedPost") # noqa: E501 -AsyncMappedComment = _select_model_class(AsyncMappedCommentBase, AsyncMappedComment312, AsyncMappedComment311, AsyncMappedComment310, "AsyncMappedComment") # noqa: E501 -AsyncColumnMappingModel = _select_model_class(AsyncColumnMappingModelBase, AsyncColumnMappingModel312, AsyncColumnMappingModel311, AsyncColumnMappingModel310, "AsyncColumnMappingModel") # noqa: E501 -AsyncMixedAnnotationModel = _select_model_class(AsyncMixedAnnotationModelBase, AsyncMixedAnnotationModel312, AsyncMixedAnnotationModel311, AsyncMixedAnnotationModel310, "AsyncMixedAnnotationModel") # noqa: E501 -BulkUser = BulkUserBase -AsyncBulkUser = AsyncBulkUserBase - -# ...and the scenarios are defined specifically for this backend. -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - - -class BasicProviderBase: - def __init__(self): - self._scenario_db_files = {} - self._created_tables: Set[str] = set() - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def get_yes_no_adapter(self) -> 'BaseSQLTypeAdapter': - return YesOrNoBooleanAdapter() - - def get_dialect(self, scenario_name: str = "default"): - """Return a bare, fully-constructed PostgreSQL dialect instance. - - Used by the ``feature/basic/ddl`` subtopic (expression/dialect - contract). ``(16, 0, 0)`` advertises support for all three - ``IF [NOT] EXISTS`` modifiers (available since PG 9.6). - """ - from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect - - return PostgresDialect(version=(16, 0, 0)) - - def _track_backend(self, backend_instance, collection) -> None: - if backend_instance not in collection: - collection.append(backend_instance) - - def _load_postgres_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "basic", "schema" - ) - schema_path = os.path.join(schema_dir, filename) - with open(schema_path, 'r', encoding='utf-8') as f: - return f.read() - - -class BasicSyncProvider(BasicProviderBase, IBasicSyncProvider, WorkerTestProtocol): - - def __init__(self): - super().__init__() - self._active_backends = [] - - def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - backend_class, config = get_scenario(scenario_name) - model_class.configure(config, backend_class) - backend_instance = model_class.__backend__ - self._track_backend(backend_instance, self._active_backends) - self._reset_table_sync(model_class, table_name) - self._created_tables.add(table_name) - return model_class - - def _reset_table_sync(self, model_class: Type[ActiveRecord], table_name: str) -> None: - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(model_class.__backend__.dialect, table_name).to_sql() - model_class.__backend__.execute(sql, params, options=opts) - except Exception as e: - print(f"Could not drop table {table_name}: {e}") - if fn := BASIC_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(model_class.__backend__.dialect, table_name) - sql, params = create_expr.to_sql() - model_class.__backend__.execute(sql, params, options=opts) - - def _initialize_model_schema(self, model_class: Type[ActiveRecord], table_name: str) -> None: - self._reset_table_sync(model_class, table_name) - - def _setup_multiple_models(self, model_classes: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - if not model_classes: - return tuple() - first_model_class, first_table_name = model_classes[0] - first_model = self._setup_model(first_model_class, scenario_name, first_table_name) - shared_backend = first_model.__backend__ - result = [first_model] - for model_class, table_name in model_classes[1:]: - model_class.__connection_config__ = first_model.__connection_config__ - model_class.__backend_class__ = first_model.__backend_class__ - model_class.__backend__ = shared_backend - self._track_backend(shared_backend, self._active_backends) - self._initialize_model_schema(model_class, table_name) - self._created_tables.add(table_name) - result.append(model_class) - return tuple(result) - - def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(User, scenario_name, "users") - - def setup_type_case_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(TypeCase, scenario_name, "type_cases") - - def setup_type_test_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(TypeTestModel, scenario_name, "type_tests") - - def setup_validated_field_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(ValidatedFieldUser, scenario_name, "validated_field_users") - - def setup_validated_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(ValidatedUser, scenario_name, "validated_users") - - def setup_pydantic_validated_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(PydanticValidatedModel, scenario_name, "pydantic_validated_models") - - def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models([ - (MappedUser, "users"), - (MappedPost, "posts"), - (MappedComment, "comments") - ], scenario_name) - - def setup_mixed_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord_postgres_test.feature.basic.fixtures.models import PostgresMixedAnnotationModel - return self._setup_multiple_models([ - (ColumnMappingModel, "column_mapping_items"), - (PostgresMixedAnnotationModel, "mixed_annotation_items") - ], scenario_name) - - def setup_type_adapter_model_and_schema(self, scenario_name: str = None) -> Type[ActiveRecord]: - if scenario_name is None: - scenario_name = self.get_test_scenarios()[0] if self.get_test_scenarios() else "default" - return self._setup_model(TypeAdapterTest, scenario_name, "type_adapter_tests") - - def setup_bulk_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(BulkUser, scenario_name, "bulk_users") - - def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def setup_order_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def setup_mapped_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def setup_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def setup_product_form_a_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def setup_product_with_proxy_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def setup_product_with_column_and_adapter_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - def get_worker_connection_params(self, scenario_name: str, fixture_type: str = None) -> dict: - from .scenarios import SCENARIO_MAP - is_async = fixture_type and fixture_type.startswith('async_') - backend_class_name = 'AsyncPostgresBackend' if is_async else 'PostgresBackend' - table_name = 'users' - if fixture_type: - base_type = fixture_type.replace('async_', '') - table_map = { - 'user': 'users', - 'type_case': 'type_cases', - 'type_test': 'type_tests', - 'validated_field_user': 'validated_field_users', - 'validated_user': 'validated_users', - 'pydantic_validated_model': 'pydantic_validated_models', - 'type_adapter_test': 'type_adapter_tests', - } - table_name = table_map.get(base_type, 'users') - if scenario_name not in SCENARIO_MAP: - if SCENARIO_MAP: - scenario_name = next(iter(SCENARIO_MAP)) - else: - raise ValueError("No scenarios registered") - config_dict = SCENARIO_MAP[scenario_name] - from .pooling import resolve_database_name - - pooled_db = resolve_database_name(scenario_name) - if pooled_db: - config_dict = {**config_dict, "database": pooled_db} - return { - 'backend_module': 'rhosocial.activerecord.backend.impl.postgres.backend', - 'backend_class_name': backend_class_name, - 'config_class_module': 'rhosocial.activerecord.backend.impl.postgres.config', - 'config_class_name': 'PostgresConnectionConfig', - 'config_kwargs': config_dict, - 'schema_sql': self._load_postgres_schema(f'{table_name}.sql'), - } - - def get_worker_schema_sql(self, scenario_name: str, table_name: str) -> str: - return self._load_postgres_schema(f'{table_name}.sql') - - def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_backends: - try: - for table_name in list(self._created_tables): - try: - backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - backend_instance.disconnect() - except Exception: - pass - self._active_backends.clear() - self._created_tables.clear() - - -class BasicAsyncProvider(BasicProviderBase, IBasicAsyncProvider): - - def __init__(self): - super().__init__() - self._active_async_backends = [] - - async def get_dialect(self, scenario_name: str = "default"): - """Async mirror of ``BasicProviderBase.get_dialect``.""" - return super().get_dialect(scenario_name) - - async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - _, config = get_scenario(scenario_name) - await model_class.configure(config, AsyncPostgresBackend) - backend_instance = model_class.__backend__ - self._track_backend(backend_instance, self._active_async_backends) - await self._reset_table_async(model_class, table_name) - self._created_tables.add(table_name) - return model_class - - async def _reset_table_async(self, model_class: Type[ActiveRecord], table_name: str) -> None: - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(model_class.__backend__.dialect, table_name).to_sql() - await model_class.__backend__.execute(sql, params, options=opts) - except Exception as e: - print(f"Could not drop table {table_name}: {e}") - if fn := BASIC_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(model_class.__backend__.dialect, table_name) - sql, params = create_expr.to_sql() - await model_class.__backend__.execute(sql, params, options=opts) - - async def _initialize_async_model_schema(self, model_class: Type[ActiveRecord], table_name: str) -> None: - await self._reset_table_async(model_class, table_name) - - async def _setup_multiple_models_async(self, model_classes: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - if not model_classes: - return tuple() - first_model_class, first_table_name = model_classes[0] - first_model = await self._setup_async_model(first_model_class, scenario_name, first_table_name) - shared_backend = first_model.__backend__ - result = [first_model] - for model_class, table_name in model_classes[1:]: - model_class.__connection_config__ = first_model.__connection_config__ - model_class.__backend_class__ = first_model.__backend_class__ - model_class.__backend__ = shared_backend - self._track_backend(shared_backend, self._active_async_backends) - await self._initialize_async_model_schema(model_class, table_name) - self._created_tables.add(table_name) - result.append(model_class) - return tuple(result) - - async def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncUser, scenario_name, "users") - - async def setup_type_case_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncTypeCase, scenario_name, "type_cases") - - async def setup_type_test_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncTypeTestModel, scenario_name, "type_tests") - - async def setup_validated_field_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncValidatedFieldUser, scenario_name, "validated_field_users") - - async def setup_validated_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncValidatedUser, scenario_name, "validated_users") - - async def setup_pydantic_validated_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncPydanticValidatedModel, scenario_name, "pydantic_validated_models") - - async def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return await self._setup_multiple_models_async([ - (AsyncMappedUser, "users"), - (AsyncMappedPost, "posts"), - (AsyncMappedComment, "comments") - ], scenario_name) - - async def setup_mixed_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord_postgres_test.feature.basic.fixtures.models import AsyncPostgresMixedAnnotationModel - return await self._setup_multiple_models_async([ - (AsyncColumnMappingModel, "column_mapping_items"), - (AsyncPostgresMixedAnnotationModel, "mixed_annotation_items") - ], scenario_name) - - async def setup_type_adapter_model_and_schema(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncTypeAdapterTest, scenario_name, "type_adapter_tests") - - async def setup_bulk_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncBulkUser, scenario_name, "bulk_users") - - async def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def setup_order_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def setup_mapped_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def setup_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def setup_product_form_a_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def setup_product_with_proxy_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def setup_product_with_column_and_adapter_model(self, scenario_name: str) -> Type[ActiveRecord]: - raise NotImplementedError - - async def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_async_backends: - try: - for table_name in list(self._created_tables): - try: - await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - await backend_instance.disconnect() - except Exception: - pass - self._active_async_backends.clear() - self._created_tables.clear() diff --git a/tests/providers/basic_connection.py b/tests/providers/basic_connection.py deleted file mode 100644 index c57443c5..00000000 --- a/tests/providers/basic_connection.py +++ /dev/null @@ -1,183 +0,0 @@ -# tests/providers/basic_connection.py -""" -Concrete implementation of IBasicConnectionProvider for PostgreSQL backend. - -This provider sets up connection pools and models for testing -ActiveRecord context awareness. -""" -from typing import Type, Tuple, Optional, List - -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord -from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend -from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig # noqa: F401 -from rhosocial.activerecord.connection.pool import BackendPool, AsyncBackendPool, PoolConfig -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType - -from rhosocial.activerecord.testsuite.feature.basic.connection.interfaces import IBasicConnectionProvider -from .scenarios import get_scenario, get_enabled_scenarios - - -class SyncTestUser(ActiveRecord): - """Sync test user model for connection pool tests.""" - @classmethod - def table_name(cls): - return "test_users" - - id: Optional[int] = None - name: str - email: str - - -class AsyncTestUser(AsyncActiveRecord): - """Async test user model for connection pool tests.""" - @classmethod - def table_name(cls): - return "test_users" - - id: Optional[int] = None - name: str - email: str - - -class BasicConnectionProvider(IBasicConnectionProvider): - """ - PostgreSQL backend implementation for basic connection pool context tests. - """ - - def __init__(self): - self._active_backends: List = [] - self._active_async_backends: List = [] - - def get_test_scenarios(self) -> list: - """Returns available test scenarios.""" - return list(get_enabled_scenarios().keys()) - - def _create_test_table(self, backend): - """Create the test_users table.""" - try: - backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL)) - except Exception: - pass - - backend.execute(""" - CREATE TABLE test_users ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL - ) - """, options=ExecutionOptions(stmt_type=StatementType.DDL)) - - async def _create_test_table_async(self, backend): - """Create the test_users table asynchronously.""" - try: - await backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL)) # noqa: E501 - except Exception: - pass - - await backend.execute(""" - CREATE TABLE test_users ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL - ) - """, options=ExecutionOptions(stmt_type=StatementType.DDL)) - - def setup_sync_pool_and_model(self, scenario_name: str) -> Tuple[BackendPool, Type[ActiveRecord]]: - """Setup sync connection pool and model for context tests.""" - _, config = get_scenario(scenario_name) - - # Create connection pool - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: PostgresBackend(connection_config=config) - ) - pool = BackendPool.create(pool_config) - - # Create table - with pool.connection() as backend: - self._create_test_table(backend) - self._active_backends.append(backend) - - # Configure model to use a separate backend (not pool backend) - # This tests that model.backend() returns pool context backend - SyncTestUser.configure(config, PostgresBackend) - self._active_backends.append(SyncTestUser.__backend__) - - return pool, SyncTestUser - - async def setup_async_pool_and_model(self, scenario_name: str) -> Tuple[AsyncBackendPool, Type[AsyncActiveRecord]]: - """Setup async connection pool and model for context tests.""" - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - - _, config = get_scenario(scenario_name) - - # Create connection pool - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: AsyncPostgresBackend(connection_config=config) - ) - - # Create pool - pool = await AsyncBackendPool.create(pool_config) - - # Create table - async with pool.connection() as backend: - await self._create_test_table_async(backend) - self._active_async_backends.append(backend) - - # Configure model - await AsyncTestUser.configure(config, AsyncPostgresBackend) - self._active_async_backends.append(AsyncTestUser.__backend__) - - return pool, AsyncTestUser - - def cleanup_sync(self, scenario_name: str, pool: BackendPool): - """Cleanup after sync tests.""" - try: - pool.close(timeout=1.0, force=True) - except Exception: - pass - - # Disconnect backends - for backend in self._active_backends: - try: - backend.execute("DROP TABLE IF EXISTS test_users CASCADE") - except Exception: - pass - try: - backend.disconnect() - except Exception: - pass - self._active_backends.clear() - - async def cleanup_async(self, scenario_name: str, pool: AsyncBackendPool): - """Cleanup after async tests.""" - try: - await pool.close(timeout=1.0, force=True) - except Exception: - pass - - # Disconnect backends - for backend in self._active_async_backends: - try: - await backend.execute("DROP TABLE IF EXISTS test_users CASCADE") - except Exception: - pass - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() - - def setup_sync_pool_for_crud(self, scenario_name: str) -> Tuple[BackendPool, Type[ActiveRecord]]: - """Setup sync connection pool for CRUD tests.""" - return self.setup_sync_pool_and_model(scenario_name) - - async def setup_async_pool_for_crud(self, scenario_name: str) -> Tuple[AsyncBackendPool, Type[AsyncActiveRecord]]: - """Setup async connection pool for CRUD tests.""" - return await self.setup_async_pool_and_model(scenario_name) diff --git a/tests/providers/crud_benchmark.py b/tests/providers/crud_benchmark.py deleted file mode 100644 index bfc77fdd..00000000 --- a/tests/providers/crud_benchmark.py +++ /dev/null @@ -1,189 +0,0 @@ -"""PostgreSQL provider for CRUD benchmark tests.""" - -import sys -from typing import Type - -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.data import ( - make_user_payloads, - payload_count_for_size, -) -from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models import ( - AsyncBenchmarkUser as AsyncBenchmarkUserBase, - BenchmarkUser as BenchmarkUserBase, -) -from rhosocial.activerecord.testsuite.benchmark.crud.interfaces import CrudBenchmarkContext -from rhosocial.activerecord.testsuite.utils import select_fixture - -from .scenarios import get_enabled_scenarios, get_scenario - -BenchmarkUser310 = AsyncBenchmarkUser310 = None -BenchmarkUser311 = AsyncBenchmarkUser311 = None -BenchmarkUser312 = AsyncBenchmarkUser312 = None - -if sys.version_info >= (3, 10): - from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py310 import ( - AsyncBenchmarkUser as AsyncBenchmarkUser310, - BenchmarkUser as BenchmarkUser310, - ) - -if sys.version_info >= (3, 11): - from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py311 import ( - AsyncBenchmarkUser as AsyncBenchmarkUser311, - BenchmarkUser as BenchmarkUser311, - ) - -if sys.version_info >= (3, 12): - from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py312 import ( - AsyncBenchmarkUser as AsyncBenchmarkUser312, - BenchmarkUser as BenchmarkUser312, - ) - - -BenchmarkUser = select_fixture( - *[ - candidate - for candidate in (BenchmarkUser312, BenchmarkUser311, BenchmarkUser310, BenchmarkUserBase) - if candidate - ] -) -AsyncBenchmarkUser = select_fixture( - *[ - candidate - for candidate in ( - AsyncBenchmarkUser312, - AsyncBenchmarkUser311, - AsyncBenchmarkUser310, - AsyncBenchmarkUserBase, - ) - if candidate - ] -) - - -class CrudBenchmarkProvider: - def __init__(self): - self._active_backends = [] - self._active_async_backends = [] - - def get_benchmark_scenarios(self): - return list(get_enabled_scenarios().keys()) - - def setup_benchmark_sync(self, scenario: str, size: str): - model_class = self._setup_model(BenchmarkUser, scenario) - payloads = make_user_payloads(payload_count_for_size(size)) - record_ids = [] - for payload in payloads: - instance = model_class(**payload) - rows = instance.save() - if rows != 1 or instance.id is None: - raise AssertionError("failed to seed sync CRUD benchmark row") - record_ids.append(instance.id) - return CrudBenchmarkContext( - scenario=scenario, - size=size, - model_class=model_class, - payloads=payloads, - record_ids=record_ids, - backend_namespace="rhosocial.activerecord.backend.impl.postgres", - backend_name="postgres", - ) - - def teardown_benchmark_sync(self, scenario: str, context: CrudBenchmarkContext) -> None: - self._cleanup_sync() - - async def setup_benchmark_async(self, scenario: str, size: str): - model_class = await self._setup_async_model(AsyncBenchmarkUser, scenario) - payloads = make_user_payloads(payload_count_for_size(size)) - record_ids = [] - for payload in payloads: - instance = model_class(**payload) - rows = await instance.save() - if rows != 1 or instance.id is None: - raise AssertionError("failed to seed async CRUD benchmark row") - record_ids.append(instance.id) - return CrudBenchmarkContext( - scenario=scenario, - size=size, - model_class=model_class, - payloads=payloads, - record_ids=record_ids, - backend_namespace="rhosocial.activerecord.backend.impl.postgres", - backend_name="postgres", - ) - - async def teardown_benchmark_async(self, scenario: str, context: CrudBenchmarkContext) -> None: - await self._cleanup_async() - - def _setup_model(self, model_class: Type[ActiveRecord], scenario: str) -> Type[ActiveRecord]: - backend_class, config = get_scenario(scenario) - model_class.configure(config, backend_class) - self._initialize_schema(model_class.__backend__) - if model_class.__backend__ not in self._active_backends: - self._active_backends.append(model_class.__backend__) - return model_class - - async def _setup_async_model( - self, model_class: Type[ActiveRecord], scenario: str - ) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - - _, config = get_scenario(scenario) - await model_class.configure(config, AsyncPostgresBackend) - await self._initialize_schema_async(model_class.__backend__) - if model_class.__backend__ not in self._active_async_backends: - self._active_async_backends.append(model_class.__backend__) - return model_class - - def _initialize_schema(self, backend): - options = ExecutionOptions(stmt_type=StatementType.DDL) - backend.execute("DROP TABLE IF EXISTS benchmark_users", options=options) - backend.execute(self._schema_sql(), options=options) - - async def _initialize_schema_async(self, backend): - options = ExecutionOptions(stmt_type=StatementType.DDL) - await backend.execute("DROP TABLE IF EXISTS benchmark_users", options=options) - await backend.execute(self._schema_sql(), options=options) - - def _schema_sql(self): - return """ -CREATE TABLE benchmark_users ( - id SERIAL PRIMARY KEY, - username VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL, - age INTEGER, - balance DOUBLE PRECISION NOT NULL DEFAULT 0.0, - notes TEXT, - is_active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMP, - updated_at TIMESTAMP -) -""" - - def _cleanup_sync(self): - for backend in self._active_backends: - try: - backend.execute("DROP TABLE IF EXISTS benchmark_users CASCADE") - except Exception: - pass - try: - backend.disconnect() - except Exception: - pass - self._active_backends.clear() - - async def _cleanup_async(self): - for backend in self._active_async_backends: - try: - await backend.execute("DROP TABLE IF EXISTS benchmark_users CASCADE") - except Exception: - pass - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() diff --git a/tests/providers/events.py b/tests/providers/events.py deleted file mode 100644 index f20be52f..00000000 --- a/tests/providers/events.py +++ /dev/null @@ -1,201 +0,0 @@ -""" -This file provides the concrete implementation of the `IEventsProvider` interface -that is defined in the `rhosocial-activerecord-testsuite` package. - -Its main responsibilities are: -1. Reporting which test scenarios (database configurations) are available. -2. Setting up the database environment for a given test. This includes: - - Getting the correct database configuration for the scenario. - - Configuring the ActiveRecord model with a database connection. - - Dropping any old tables and creating the necessary table schema. -3. Cleaning up any resources after a test runs. -""" -import os -import sys -import logging -from typing import Type, List - -from rhosocial.activerecord.model import ActiveRecord - -# Setup logging for fixture selection debugging -logger = logging.getLogger(__name__) - -# Import the fixture selector utility -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -# Import base version models (Python 3.8+) -from rhosocial.activerecord.testsuite.feature.events.fixtures.models import ( # noqa: E402 - EventTestModel as EventTestModelBase, - EventTrackingModel as EventTrackingModelBase, - AsyncEventTestModel as AsyncEventTestModelBase, -) - -# Conditionally import Python 3.10+ models -EventTestModel310 = EventTrackingModel310 = None - -if sys.version_info >= (3, 10): - try: - from rhosocial.activerecord.testsuite.feature.events.fixtures.models_py310 import ( - EventTestModel as EventTestModel310, - EventTrackingModel as EventTrackingModel310 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.10+ fixtures: {e}") - -# Conditionally import Python 3.11+ models -EventTestModel311 = EventTrackingModel311 = None - -if sys.version_info >= (3, 11): - try: - from rhosocial.activerecord.testsuite.feature.events.fixtures.models_py311 import ( - EventTestModel as EventTestModel311, - EventTrackingModel as EventTrackingModel311 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.11+ fixtures: {e}") - -# Conditionally import Python 3.12+ models -EventTestModel312 = EventTrackingModel312 = None - -if sys.version_info >= (3, 12): - try: - from rhosocial.activerecord.testsuite.feature.events.fixtures.models_py312 import ( - EventTestModel as EventTestModel312, - EventTrackingModel as EventTrackingModel312 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.12+ fixtures: {e}") - - -# Select appropriate fixture classes based on Python version -def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type: - """Select the most appropriate model class for the current Python version.""" - candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None] - selected = select_fixture(*candidates) - logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}") - return selected - - -# Select models -EventTestModel = _select_model_class(EventTestModelBase, EventTestModel312, EventTestModel311, EventTestModel310, "EventTestModel") # noqa: E501 -EventTrackingModel = _select_model_class(EventTrackingModelBase, EventTrackingModel312, EventTrackingModel311, EventTrackingModel310, "EventTrackingModel") # noqa: E501 -AsyncEventTestModel = AsyncEventTestModelBase - -from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402 -from rhosocial.activerecord.testsuite.feature.events.interfaces import IEventsSyncProvider, IEventsAsyncProvider # noqa: E402 -# ...and the scenarios are defined specifically for this backend. -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - -# Expression-based DDL fixtures -from .fixtures._common import drop_table # noqa: E402 -from .fixtures.events import TABLE_EXPRESSIONS as EVENTS_TABLE_EXPRESSIONS # noqa: E402 - - -class EventsProviderBase: - def __init__(self): - self._active_backends = [] - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _load_postgres_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "events", "schema" - ) - schema_path = os.path.join(schema_dir, filename) - with open(schema_path, 'r', encoding='utf-8') as f: - return f.read() - - -class EventsSyncProvider(EventsProviderBase, IEventsSyncProvider): - - def __init__(self): - super().__init__() - - def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - backend_class, config = get_scenario(scenario_name) - model_class.configure(config, backend_class) - backend_instance = model_class.__backend__ - if backend_instance not in self._active_backends: - self._active_backends.append(backend_instance) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, table_name).to_sql() - backend_instance.execute(sql, params, options=opts) - except Exception as e: - print(f"Could not drop table {table_name}: {e}") - if fn := EVENTS_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - sql, params = create_expr.to_sql() - backend_instance.execute(sql, params, options=opts) - return model_class - - def setup_event_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(EventTestModel, scenario_name, "event_tests") - - def setup_event_tracking_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(EventTrackingModel, scenario_name, "event_tracking_models") - - def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_backends: - try: - for table_name in ['event_tests', 'event_tracking_models']: - try: - backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - backend_instance.disconnect() - except Exception: - pass - self._active_backends.clear() - - -class EventsAsyncProvider(EventsProviderBase, IEventsAsyncProvider): - - def __init__(self): - super().__init__() - self._active_async_backends = [] - - async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - _, config = get_scenario(scenario_name) - await model_class.configure(config, AsyncPostgresBackend) - backend_instance = model_class.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, table_name).to_sql() - await backend_instance.execute(sql, params, options=opts) - except Exception as e: - print(f"Could not drop table {table_name}: {e}") - if fn := EVENTS_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - sql, params = create_expr.to_sql() - await backend_instance.execute(sql, params, options=opts) - return model_class - - async def setup_event_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncEventTestModel, scenario_name, "event_tests") - - async def setup_event_tracking_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(EventTrackingModel, scenario_name, "event_tracking_models") - - async def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_async_backends: - try: - for table_name in ['event_tests', 'event_tracking_models']: - try: - await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - await backend_instance.disconnect() - except Exception: - pass - self._active_async_backends.clear() diff --git a/tests/providers/fastapi_benchmark.py b/tests/providers/fastapi_benchmark.py deleted file mode 100644 index 3ebdcba6..00000000 --- a/tests/providers/fastapi_benchmark.py +++ /dev/null @@ -1,242 +0,0 @@ -"""PostgreSQL provider for FastAPI benchmark tests.""" - -import sys -from contextlib import asynccontextmanager -from typing import Type - -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.data import ( - make_user_payloads, - payload_count_for_size, -) -from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models import ( - AsyncBenchmarkUser as AsyncBenchmarkUserBase, -) -from rhosocial.activerecord.testsuite.benchmark.fastapi.interfaces import ( - FASTAPI_CONNECTION_STRATEGIES, - FASTAPI_CONTEXT_STRATEGY, - FASTAPI_RUNTIME_CONFIGS, - FastAPIBenchmarkContext, -) -from rhosocial.activerecord.testsuite.utils import select_fixture - -from .scenarios import get_enabled_scenarios, get_scenario - -AsyncBenchmarkUser310 = None -AsyncBenchmarkUser311 = None -AsyncBenchmarkUser312 = None - -if sys.version_info >= (3, 10): - from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py310 import ( - AsyncBenchmarkUser as AsyncBenchmarkUser310, - ) - -if sys.version_info >= (3, 11): - from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py311 import ( - AsyncBenchmarkUser as AsyncBenchmarkUser311, - ) - -if sys.version_info >= (3, 12): - from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py312 import ( - AsyncBenchmarkUser as AsyncBenchmarkUser312, - ) - -AsyncBenchmarkUser = select_fixture( - *[ - candidate - for candidate in ( - AsyncBenchmarkUser312, - AsyncBenchmarkUser311, - AsyncBenchmarkUser310, - AsyncBenchmarkUserBase, - ) - if candidate - ] -) - - -class FastAPIBenchmarkProvider: - def __init__(self): - self._active_async_backends = [] - self._active_async_pools = [] - self._active_clients = [] - - def get_benchmark_scenarios(self): - return list(get_enabled_scenarios().keys()) - - def get_connection_strategies(self): - return FASTAPI_CONNECTION_STRATEGIES - - async def setup_benchmark_async( - self, - scenario: str, - size: str, - connection_strategy: str = "context", - ): - import httpx - from rhosocial.activerecord.testsuite.benchmark.fastapi.app import ( - create_fastapi_benchmark_app, - ) - - model_class, config = await self._setup_async_model(AsyncBenchmarkUser, scenario) - payloads = make_user_payloads(payload_count_for_size(size)) - record_ids = [] - async with model_class.__backend__.context(): - for payload in payloads: - instance = model_class(**payload) - rows = await instance.save() - if rows != 1 or instance.id is None: - raise AssertionError("failed to seed async FastAPI benchmark row") - record_ids.append(instance.id) - - runtime_config = self._fastapi_runtime_config(connection_strategy) - pool = None - pool_config = None - backend_context_factory = self._create_async_context_factory(config) - if connection_strategy != FASTAPI_CONTEXT_STRATEGY: - pool, pool_config = await self._create_async_pool(config, runtime_config) - backend_context_factory = pool.connection - - app = create_fastapi_benchmark_app( - model_class=model_class, - backend_context_factory=backend_context_factory, - backend_name="postgres", - scenario=scenario, - ) - transport = httpx.ASGITransport(app=app) - client = httpx.AsyncClient(transport=transport, base_url="http://testserver") - self._active_clients.append(client) - - return FastAPIBenchmarkContext( - scenario=scenario, - size=size, - app=app, - client=client, - model_class=model_class, - payloads=payloads, - record_ids=record_ids, - backend_namespace="rhosocial.activerecord.backend.impl.postgres", - backend_name="postgres", - connection_strategy=connection_strategy, - concurrency=runtime_config["concurrency"], - repeat=runtime_config["repeat"], - pool_config={ - "min_size": pool_config.min_size, - "max_size": pool_config.max_size, - "connection_mode": pool_config.connection_mode, - } - if pool_config - else None, - pool_connection_mode=pool.connection_mode if pool else None, - pool_stats=pool.get_stats if pool else None, - ) - - async def teardown_benchmark_async( - self, - scenario: str, - context: FastAPIBenchmarkContext, - ) -> None: - await self._cleanup_async() - - async def _setup_async_model( - self, model_class: Type[ActiveRecord], scenario: str - ) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - - _, config = get_scenario(scenario) - await model_class.configure(config, AsyncPostgresBackend) - await self._initialize_schema_async(model_class.__backend__) - if model_class.__backend__ not in self._active_async_backends: - self._active_async_backends.append(model_class.__backend__) - return model_class, config - - async def _initialize_schema_async(self, backend): - options = ExecutionOptions(stmt_type=StatementType.DDL) - await self._drop_benchmark_table(backend, options) - await backend.execute(self._schema_sql(), options=options) - - def _create_async_context_factory(self, config): - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - - @asynccontextmanager - async def context_factory(): - backend = AsyncPostgresBackend(connection_config=config) - async with backend.context(): - yield backend - - return context_factory - - def _fastapi_runtime_config(self, connection_strategy): - try: - return FASTAPI_RUNTIME_CONFIGS[connection_strategy] - except KeyError as exc: - raise ValueError( - f"unsupported FastAPI benchmark connection strategy: {connection_strategy}" - ) from exc - - async def _create_async_pool(self, config, runtime_config): - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - from rhosocial.activerecord.connection.pool import AsyncBackendPool, PoolConfig - - pool_config = PoolConfig( - min_size=runtime_config["pool_min_size"], - max_size=runtime_config["pool_max_size"], - connection_mode="auto", - backend_factory=lambda: AsyncPostgresBackend(connection_config=config), - ) - pool = await AsyncBackendPool.create(pool_config) - self._active_async_pools.append(pool) - return pool, pool_config - - def _schema_sql(self): - return """ -CREATE TABLE benchmark_users ( - id SERIAL PRIMARY KEY, - username VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL, - age INTEGER, - balance DOUBLE PRECISION NOT NULL DEFAULT 0.0, - notes TEXT, - is_active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMP, - updated_at TIMESTAMP -) -""" - - async def _cleanup_async(self): - for client in self._active_clients: - try: - await client.aclose() - except Exception: - pass - self._active_clients.clear() - - for pool in self._active_async_pools: - try: - await pool.close(force=True) - except Exception: - pass - self._active_async_pools.clear() - - for backend in self._active_async_backends: - try: - options = ExecutionOptions(stmt_type=StatementType.DDL) - await self._drop_benchmark_table(backend, options) - except Exception: - pass - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() - - async def _drop_benchmark_table(self, backend, options): - await backend.execute('DROP TABLE IF EXISTS "benchmark_users" CASCADE', options=options) diff --git a/tests/providers/fixtures/__init__.py b/tests/providers/fixtures/__init__.py deleted file mode 100644 index cd640fd9..00000000 --- a/tests/providers/fixtures/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# tests/providers/fixtures/__init__.py -"""PostgreSQL-specific DDL expression fixtures for the testsuite providers. - -Each module in this package exposes a ``TABLE_EXPRESSIONS`` mapping of -table name -> factory callable ``Callable[[DialectLike, str], CreateTableStatement]``. - -The factory functions build :class:`CreateTableStatement` instances that emit -PostgreSQL-compatible DDL (SERIAL / UUID / JSONB / BYTEA / TIMESTAMPTZ / BOOLEAN / -DECIMAL / VARCHAR / TEXT / FK constraints / CHECK / UNIQUE / NOT NULL / DEFAULT). -The pre-existing ``.sql`` schema files under -``tests/rhosocial/activerecord_postgres_test/feature//schema/`` -remain as the authoritative reference for what the expressions here must -produce; they are simply no longer read at runtime by the providers. -""" diff --git a/tests/providers/fixtures/_common.py b/tests/providers/fixtures/_common.py deleted file mode 100644 index 2af3a52b..00000000 --- a/tests/providers/fixtures/_common.py +++ /dev/null @@ -1,34 +0,0 @@ -# tests/providers/fixtures/_common.py -"""Shared helpers for the PostgreSQL DDL expression fixtures. - -Provides the ``drop_table`` helper used by all feature providers. -""" - -from __future__ import annotations - -from typing import Tuple - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, - DropTableStatement, -) -from rhosocial.activerecord.backend.expression.objects import Table - - -def drop_table(dialect, table_name: str) -> DropTableStatement: - """Build a ``DROP TABLE IF EXISTS table_name CASCADE`` expression.""" - return DropTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_exists=True, - ) - - -def create_table_sql(expr: CreateTableStatement) -> Tuple[str, tuple]: - """Generate canonical PostgreSQL DDL for a :class:`CreateTableStatement`. - - For PostgreSQL no post-processing is required (unlike MySQL where storage - option quotes must be stripped). This pass-through wrapper exists so the - call site is the same as the MySQL counterpart. - """ - return expr.to_sql() diff --git a/tests/providers/fixtures/basic.py b/tests/providers/fixtures/basic.py deleted file mode 100644 index f55ce340..00000000 --- a/tests/providers/fixtures/basic.py +++ /dev/null @@ -1,498 +0,0 @@ -# tests/providers/fixtures/basic.py -"""DDL expressions for the ``feature/basic`` table group (PostgreSQL). - -Each factory builds a :class:`CreateTableStatement` whose generated DDL is -semantically equivalent to the reference ``.sql`` schema files under -``tests/rhosocial/activerecord_postgres_test/feature/basic/schema/``. Those -``.sql`` files are kept as the authoritative reference and are no longer -loaded at runtime. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnPrimaryKeyConstraint, - TablePrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, - ForeignKeyConstraint, - TableConstraint, - ReferentialAction, -) -from rhosocial.activerecord.backend.expression.types import ( - ArrayType, - BigIntType, - BooleanType, - DateType, - DecimalType, - DoubleType, - FloatType, - IntegerType, - JsonBType, - SmallIntType, - TextType, - TimeTzType, - TimestampTzType, - VarCharType, - BlobType, - UUIDType, -) -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.impl.postgres.expression import ( - PostgresSerialType, -) - -_CASCADE = ReferentialAction.CASCADE - - -# --------------------------------------------------------------------------- -# basic/users.sql -# --------------------------------------------------------------------------- - -def create_users_table(dialect, table_name: str = "users") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "balance", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/type_cases.sql -# --------------------------------------------------------------------------- - -def create_type_cases_table(dialect, table_name: str = "type_cases") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", UUIDType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "tiny_int", SmallIntType(dialect=dialect)), - ColumnDefinition(dialect, "small_int", SmallIntType(dialect=dialect)), - ColumnDefinition(dialect, "big_int", BigIntType(dialect=dialect)), - ColumnDefinition(dialect, "float_val", FloatType(dialect=dialect)), - ColumnDefinition(dialect, "double_val", DoubleType(dialect=dialect)), - ColumnDefinition(dialect, "decimal_val", DecimalType(precision=10, scale=4, dialect=dialect)), - ColumnDefinition(dialect, "char_val", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "varchar_val", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "text_val", TextType(dialect=dialect)), - ColumnDefinition(dialect, "date_val", DateType(dialect=dialect)), - ColumnDefinition(dialect, "time_val", TimeTzType(dialect=dialect)), - ColumnDefinition(dialect, "timestamp_val", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "blob_val", BlobType(dialect=dialect)), - ColumnDefinition(dialect, "json_val", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "array_val", ArrayType(element_type=IntegerType(dialect=dialect), dialect=dialect)), - ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]), - ], - table_constraints=[ - TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["id"])), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/type_tests.sql -# --------------------------------------------------------------------------- - -def create_type_tests_table(dialect, table_name: str = "type_tests") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", UUIDType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "string_field", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "int_field", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "float_field", FloatType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "decimal_field", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "bool_field", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "datetime_field", TimestampTzType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "json_field", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "nullable_field", VarCharType(length=255, dialect=dialect)), - ], - table_constraints=[ - TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["id"])), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/validated_field_users.sql -# --------------------------------------------------------------------------- - -def create_validated_field_users_table(dialect, table_name: str = "validated_field_users") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "balance", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "credit_score", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 300))]), - ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "active"))]), - ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/validated_users.sql -# --------------------------------------------------------------------------- - -def create_validated_users_table(dialect, table_name: str = "validated_users") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/pydantic_validated_models.sql -# --------------------------------------------------------------------------- - -def create_pydantic_validated_models_table(dialect, table_name: str = "pydantic_validated_models") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "code", VarCharType(length=32, dialect=dialect)), - ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "step_count", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "price", DecimalType(precision=10, scale=2, dialect=dialect)), - ColumnDefinition(dialect, "start_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "end_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "status", VarCharType(length=32, dialect=dialect)), - ColumnDefinition(dialect, "normalized_name", VarCharType(length=50, dialect=dialect)), - ColumnDefinition(dialect, "created_token", VarCharType(length=255, dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/bulk_users.sql -# --------------------------------------------------------------------------- - -def create_bulk_users_table(dialect, table_name: str = "bulk_users") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, ""))]), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/posts.sql -# --------------------------------------------------------------------------- - -def create_posts_table(dialect, table_name: str = "posts") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "author", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect)), - ColumnDefinition(dialect, "published_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "published", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["author"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/comments.sql -# --------------------------------------------------------------------------- - -def create_comments_table(dialect, table_name: str = "comments") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "post_ref", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "author", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "text", TextType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "approved", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["post_ref"], foreign_key_table=Table(dialect, 'posts'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ForeignKeyConstraint(dialect, columns=["author"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/column_mapping_items.sql -# --------------------------------------------------------------------------- - -def create_column_mapping_items_table(dialect, table_name: str = "column_mapping_items") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "item_total", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "remarks", IntegerType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/mixed_annotation_items.sql -# --------------------------------------------------------------------------- - -def create_mixed_annotation_items_table(dialect, table_name: str = "mixed_annotation_items") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "tags", ArrayType(element_type=TextType(dialect=dialect), dialect=dialect)), - ColumnDefinition(dialect, "meta", TextType(dialect=dialect)), - ColumnDefinition(dialect, "description", TextType(dialect=dialect)), - ColumnDefinition(dialect, "status", TextType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# basic/type_adapter_tests.sql -# --------------------------------------------------------------------------- - -def create_type_adapter_tests_table(dialect, table_name: str = "type_adapter_tests") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=True, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "optional_name", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "optional_age", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "last_login", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "is_premium", BooleanType(dialect=dialect)), - ColumnDefinition(dialect, "unsupported_union", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "custom_bool", VarCharType(length=10, dialect=dialect)), - ColumnDefinition(dialect, "optional_custom_bool", VarCharType(length=10, dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# composite_pk/order_items.sql (composite PK) -# --------------------------------------------------------------------------- - -def create_composite_pk_order_items_table(dialect, table_name: str = "order_items") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "order_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "unit_price", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ], - table_constraints=[ - TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["order_id", "product_id"])), - ], - ) - - -# --------------------------------------------------------------------------- -# composite_pk/store_inventory.sql (composite PK, no FK) -# --------------------------------------------------------------------------- - -def create_store_inventory_table(dialect, table_name: str = "store_inventory") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "store_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "batch_id", VarCharType(length=64, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "stock", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ], - table_constraints=[ - TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["store_id", "product_id", "batch_id"])), - ], - ) - - -# --------------------------------------------------------------------------- -# derived_field/orders.sql (single PK) -# --------------------------------------------------------------------------- - -def create_orders_table(dialect, table_name: str = "orders") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "total", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "created_at", TextType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TextType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# derived_field/product.sql (single PK) -# --------------------------------------------------------------------------- - -def create_product_table(dialect, table_name: str = "product") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=True, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", TextType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "price", FloatType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ], - ) - - -TABLE_EXPRESSIONS: Dict[str, Callable] = { - "users": create_users_table, - "type_cases": create_type_cases_table, - "type_tests": create_type_tests_table, - "validated_field_users": create_validated_field_users_table, - "validated_users": create_validated_users_table, - "pydantic_validated_models": create_pydantic_validated_models_table, - "bulk_users": create_bulk_users_table, - "posts": create_posts_table, - "comments": create_comments_table, - "column_mapping_items": create_column_mapping_items_table, - "mixed_annotation_items": create_mixed_annotation_items_table, - "type_adapter_tests": create_type_adapter_tests_table, - "order_items": create_composite_pk_order_items_table, - "store_inventory": create_store_inventory_table, - "orders": create_orders_table, - "product": create_product_table, -} diff --git a/tests/providers/fixtures/events.py b/tests/providers/fixtures/events.py deleted file mode 100644 index 3c3e626a..00000000 --- a/tests/providers/fixtures/events.py +++ /dev/null @@ -1,84 +0,0 @@ -# tests/providers/fixtures/events.py -"""DDL expressions for the ``feature/events`` table group (PostgreSQL). - -Reference: ``tests/rhosocial/activerecord_postgres_test/feature/events/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnNullableConstraint, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, -) -from rhosocial.activerecord.backend.expression.types import ( - IntegerType, - TextType, - TimestampTzType, - VarCharType, -) -from rhosocial.activerecord.backend.impl.postgres.expression import PostgresSerialType -from rhosocial.activerecord.backend.expression.objects import Table - - -# --------------------------------------------------------------------------- -# events/event_tests.sql -# --------------------------------------------------------------------------- - -def create_event_tests_table(dialect, table_name: str = "event_tests") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "draft"))]), - ColumnDefinition(dialect, "revision", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# events/event_tracking_models.sql -# --------------------------------------------------------------------------- - -def create_event_tracking_models_table(dialect, table_name: str = "event_tracking_models") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect)), - ColumnDefinition(dialect, "view_count", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "last_viewed_at", TimestampTzType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ], - ) - - -TABLE_EXPRESSIONS: Dict[str, Callable] = { - "event_tests": create_event_tests_table, - "event_tracking_models": create_event_tracking_models_table, -} diff --git a/tests/providers/fixtures/mixins.py b/tests/providers/fixtures/mixins.py deleted file mode 100644 index c2892334..00000000 --- a/tests/providers/fixtures/mixins.py +++ /dev/null @@ -1,134 +0,0 @@ -# tests/providers/fixtures/mixins.py -"""DDL expressions for the ``feature/mixins`` table group (PostgreSQL). - -Reference: ``tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnNullableConstraint, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, -) -from rhosocial.activerecord.backend.expression.types import ( - BooleanType, - DecimalType, - IntegerType, - TextType, - TimestampTzType, - VarCharType, -) -from rhosocial.activerecord.backend.impl.postgres.expression import PostgresSerialType -from rhosocial.activerecord.backend.expression.objects import Table - - -# --------------------------------------------------------------------------- -# mixins/combined_articles.sql -# --------------------------------------------------------------------------- - -def create_combined_articles_table(dialect, table_name: str = "combined_articles") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect)), - ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "draft"))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "version", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "deleted_at", TimestampTzType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ], - ) - - -# --------------------------------------------------------------------------- -# mixins/tasks.sql -# --------------------------------------------------------------------------- - -def create_tasks_table(dialect, table_name: str = "tasks") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "is_completed", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]), - ColumnDefinition(dialect, "deleted_at", TimestampTzType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ], - ) - - -# --------------------------------------------------------------------------- -# mixins/timestamped_posts.sql -# --------------------------------------------------------------------------- - -def create_timestamped_posts_table(dialect, table_name: str = "timestamped_posts") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# mixins/versioned_products.sql -# --------------------------------------------------------------------------- - -def create_versioned_products_table(dialect, table_name: str = "versioned_products") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "price", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "version", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ], - ) - - -TABLE_EXPRESSIONS: Dict[str, Callable] = { - "combined_articles": create_combined_articles_table, - "tasks": create_tasks_table, - "timestamped_posts": create_timestamped_posts_table, - "versioned_products": create_versioned_products_table, -} diff --git a/tests/providers/fixtures/query.py b/tests/providers/fixtures/query.py deleted file mode 100644 index 25d052cb..00000000 --- a/tests/providers/fixtures/query.py +++ /dev/null @@ -1,385 +0,0 @@ -# tests/providers/fixtures/query.py -"""DDL expressions for the ``feature/query`` table group (PostgreSQL). - -Reference: ``tests/rhosocial/activerecord_postgres_test/feature/query/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnNullableConstraint, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, - ForeignKeyConstraint, - ReferentialAction, -) -from rhosocial.activerecord.backend.expression.types import ( - BooleanType, - DecimalType, - IntegerType, - JsonBType, - TextType, - TimestampTzType, - VarCharType, -) -from rhosocial.activerecord.backend.impl.postgres.expression import PostgresSerialType -from rhosocial.activerecord.backend.expression.objects import Table - -_CASCADE = ReferentialAction.CASCADE - - -# --------------------------------------------------------------------------- -# query/users.sql -# --------------------------------------------------------------------------- - -def create_users_table(dialect, table_name: str = "users") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "balance", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# query/posts.sql -# --------------------------------------------------------------------------- - -def create_posts_table(dialect, table_name: str = "posts") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect)), - ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "published"))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# query/comments.sql -# --------------------------------------------------------------------------- - -def create_comments_table(dialect, table_name: str = "comments") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "post_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "is_hidden", BooleanType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ForeignKeyConstraint(dialect, columns=["post_id"], foreign_key_table=Table(dialect, 'posts'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# query/orders.sql -# --------------------------------------------------------------------------- - -def create_orders_table(dialect, table_name: str = "orders") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "order_number", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "total_amount", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "pending"))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"]), - ], - ) - - -# --------------------------------------------------------------------------- -# query/order_items.sql -# --------------------------------------------------------------------------- - -def create_order_items_table(dialect, table_name: str = "order_items") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "order_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "unit_price", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "subtotal", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["order_id"], foreign_key_table=Table(dialect, 'orders'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# query/profiles.sql -# --------------------------------------------------------------------------- - -def create_profiles_table(dialect, table_name: str = "profiles") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "bio", TextType(dialect=dialect)), - ColumnDefinition(dialect, "avatar_url", VarCharType(length=512, dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"]), - ], - ) - - -# --------------------------------------------------------------------------- -# query/json_users.sql -# --------------------------------------------------------------------------- - -def create_json_users_table(dialect, table_name: str = "json_users") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "settings", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "tags", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "profile", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "roles", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "scores", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "subscription", JsonBType(dialect=dialect)), - ColumnDefinition(dialect, "preferences", JsonBType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# query/nodes.sql (self-referential FK) -# --------------------------------------------------------------------------- - -def create_nodes_table(dialect, table_name: str = "nodes") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "parent_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ColumnDefinition(dialect, "value", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["parent_id"], foreign_key_table=Table(dialect, 'nodes'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# query/searchable_items.sql -# --------------------------------------------------------------------------- - -def create_searchable_items_table(dialect, table_name: str = "searchable_items") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "tags", TextType(dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - ) - - -# --------------------------------------------------------------------------- -# query/extended_orders.sql -# --------------------------------------------------------------------------- - -def create_extended_orders_table(dialect, table_name: str = "extended_orders") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "order_number", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "total_amount", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]), - ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "pending"))]), - ColumnDefinition(dialect, "priority", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "medium"))]), - ColumnDefinition(dialect, "region", VarCharType(length=50, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "default"))]), - ColumnDefinition(dialect, "category", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "product", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "department", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "year", VarCharType(length=10, dialect=dialect)), - ColumnDefinition(dialect, "quarter", VarCharType(length=10, dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -# --------------------------------------------------------------------------- -# query/extended_order_items.sql -# --------------------------------------------------------------------------- - -def create_extended_order_items_table(dialect, table_name: str = "extended_order_items") -> CreateTableStatement: - return CreateTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_not_exists=False, - columns=[ - ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "order_id", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_name", VarCharType(length=255, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "price", DecimalType(precision=10, scale=2, dialect=dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "category", VarCharType(length=255, dialect=dialect)), - ColumnDefinition(dialect, "region", VarCharType(length=50, dialect=dialect)), - ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)), - ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)), - ], - table_constraints=[ - ForeignKeyConstraint(dialect, columns=["order_id"], foreign_key_table=Table(dialect, 'extended_orders'), foreign_key_columns=["id"], - on_delete=_CASCADE), - ], - ) - - -TABLE_EXPRESSIONS: Dict[str, Callable] = { - "users": create_users_table, - "posts": create_posts_table, - "comments": create_comments_table, - "orders": create_orders_table, - "order_items": create_order_items_table, - "profiles": create_profiles_table, - "json_users": create_json_users_table, - "nodes": create_nodes_table, - "searchable_items": create_searchable_items_table, - "extended_orders": create_extended_orders_table, - "extended_order_items": create_extended_order_items_table, -} diff --git a/tests/providers/mixin_benchmark.py b/tests/providers/mixin_benchmark.py deleted file mode 100644 index 0e47555e..00000000 --- a/tests/providers/mixin_benchmark.py +++ /dev/null @@ -1,15 +0,0 @@ -"""PostgreSQL provider for mixin benchmark tests.""" - -from rhosocial.activerecord.testsuite.benchmark.mixin.interfaces import MixinBenchmarkContext - -from .crud_benchmark import CrudBenchmarkProvider - - -class MixinBenchmarkProvider(CrudBenchmarkProvider): - def setup_benchmark_sync(self, scenario: str, size: str): - context = super().setup_benchmark_sync(scenario, size) - return MixinBenchmarkContext(**context.__dict__) - - async def setup_benchmark_async(self, scenario: str, size: str): - context = await super().setup_benchmark_async(scenario, size) - return MixinBenchmarkContext(**context.__dict__) diff --git a/tests/providers/mixins.py b/tests/providers/mixins.py deleted file mode 100644 index 42f844c1..00000000 --- a/tests/providers/mixins.py +++ /dev/null @@ -1,232 +0,0 @@ -""" -This file provides the concrete implementation of the `IMixinsProvider` interface -that is defined in the `rhosocial-activerecord-testsuite` package. - -Its main responsibilities are: -1. Reporting which test scenarios (database configurations) are available. -2. Setting up the database environment for a given test. This includes: - - Getting the correct database configuration for the scenario. - - Configuring the ActiveRecord model with a database connection. - - Dropping any old tables and creating the necessary table schema. -3. Cleaning up any resources after a test runs. -""" -import os -import sys -import logging -from typing import Type, List - -from rhosocial.activerecord.model import ActiveRecord - -# Setup logging for fixture selection debugging -logger = logging.getLogger(__name__) - -# Import the fixture selector utility -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -# Import base version models (Python 3.8+) -from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models import ( # noqa: E402 - TimestampedPost as TimestampedPostBase, - VersionedProduct as VersionedProductBase, - Task as TaskBase, - CombinedArticle as CombinedArticleBase, - AsyncTimestampedPost as AsyncTimestampedPostBase, - AsyncVersionedProduct as AsyncVersionedProductBase, - AsyncTask as AsyncTaskBase, - AsyncCombinedArticle as AsyncCombinedArticleBase, -) - -# Conditionally import Python 3.10+ models -TimestampedPost310 = VersionedProduct310 = Task310 = CombinedArticle310 = None - -if sys.version_info >= (3, 10): - try: - from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models_py310 import ( - TimestampedPost as TimestampedPost310, - VersionedProduct as VersionedProduct310, - Task as Task310, - CombinedArticle as CombinedArticle310 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.10+ fixtures: {e}") - -# Conditionally import Python 3.11+ models -TimestampedPost311 = VersionedProduct311 = Task311 = CombinedArticle311 = None - -if sys.version_info >= (3, 11): - try: - from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models_py311 import ( - TimestampedPost as TimestampedPost311, - VersionedProduct as VersionedProduct311, - Task as Task311, - CombinedArticle as CombinedArticle311 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.11+ fixtures: {e}") - -# Conditionally import Python 3.12+ models -TimestampedPost312 = VersionedProduct312 = Task312 = CombinedArticle312 = None - -if sys.version_info >= (3, 12): - try: - from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models_py312 import ( - TimestampedPost as TimestampedPost312, - VersionedProduct as VersionedProduct312, - Task as Task312, - CombinedArticle as CombinedArticle312 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.12+ fixtures: {e}") - - -# Select appropriate fixture classes based on Python version -def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type: - """Select the most appropriate model class for the current Python version.""" - candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None] - selected = select_fixture(*candidates) - logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}") - return selected - - -# Select models -TimestampedPost = _select_model_class(TimestampedPostBase, TimestampedPost312, TimestampedPost311, TimestampedPost310, "TimestampedPost") # noqa: E501 -VersionedProduct = _select_model_class(VersionedProductBase, VersionedProduct312, VersionedProduct311, VersionedProduct310, "VersionedProduct") # noqa: E501 -Task = _select_model_class(TaskBase, Task312, Task311, Task310, "Task") -CombinedArticle = _select_model_class(CombinedArticleBase, CombinedArticle312, CombinedArticle311, CombinedArticle310, "CombinedArticle") # noqa: E501 - -AsyncTimestampedPost = AsyncTimestampedPostBase -AsyncVersionedProduct = AsyncVersionedProductBase -AsyncTask = AsyncTaskBase -AsyncCombinedArticle = AsyncCombinedArticleBase - -from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402 -from rhosocial.activerecord.testsuite.feature.mixins.interfaces import IMixinsSyncProvider, IMixinsAsyncProvider # noqa: E402 -# ...and the scenarios are defined specifically for this backend. -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - -# Expression-based DDL fixtures -from .fixtures._common import drop_table # noqa: E402 -from .fixtures.mixins import TABLE_EXPRESSIONS as MIXINS_TABLE_EXPRESSIONS # noqa: E402 - - -class MixinsProviderBase: - def __init__(self): - self._active_backends = [] - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _load_postgres_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "mixins", "schema" - ) - schema_path = os.path.join(schema_dir, filename) - with open(schema_path, 'r', encoding='utf-8') as f: - return f.read() - - -class MixinsSyncProvider(MixinsProviderBase, IMixinsSyncProvider): - - def __init__(self): - super().__init__() - - def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - backend_class, config = get_scenario(scenario_name) - model_class.configure(config, backend_class) - backend_instance = model_class.__backend__ - if backend_instance not in self._active_backends: - self._active_backends.append(backend_instance) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, table_name).to_sql() - backend_instance.execute(sql, params, options=opts) - except Exception as e: - print(f"Could not drop table {table_name}: {e}") - if fn := MIXINS_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - sql, params = create_expr.to_sql() - backend_instance.execute(sql, params, options=opts) - return model_class - - def setup_timestamped_post_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(TimestampedPost, scenario_name, "timestamped_posts") - - def setup_versioned_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(VersionedProduct, scenario_name, "versioned_products") - - def setup_task_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(Task, scenario_name, "tasks") - - def setup_combined_article_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(CombinedArticle, scenario_name, "combined_articles") - - def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_backends: - try: - for table_name in ['timestamped_posts', 'versioned_products', 'tasks', - 'combined_articles']: - try: - backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - backend_instance.disconnect() - except Exception: - pass - self._active_backends.clear() - - -class MixinsAsyncProvider(MixinsProviderBase, IMixinsAsyncProvider): - - def __init__(self): - super().__init__() - self._active_async_backends = [] - - async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - _, config = get_scenario(scenario_name) - await model_class.configure(config, AsyncPostgresBackend) - backend_instance = model_class.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, table_name).to_sql() - await backend_instance.execute(sql, params, options=opts) - except Exception as e: - print(f"Could not drop table {table_name}: {e}") - if fn := MIXINS_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - sql, params = create_expr.to_sql() - await backend_instance.execute(sql, params, options=opts) - return model_class - - async def setup_timestamped_post_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncTimestampedPost, scenario_name, "timestamped_posts") - - async def setup_versioned_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncVersionedProduct, scenario_name, "versioned_products") - - async def setup_task_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncTask, scenario_name, "tasks") - - async def setup_combined_article_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncCombinedArticle, scenario_name, "combined_articles") - - async def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_async_backends: - try: - for table_name in ['timestamped_posts', 'versioned_products', 'tasks', - 'combined_articles']: - try: - await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - await backend_instance.disconnect() - except Exception: - pass - self._active_async_backends.clear() diff --git a/tests/providers/partition.py b/tests/providers/partition.py deleted file mode 100644 index 3a630c16..00000000 --- a/tests/providers/partition.py +++ /dev/null @@ -1,381 +0,0 @@ -"""PostgreSQL provider for shared partition testsuite scenarios.""" -from __future__ import annotations - -from datetime import datetime -from decimal import Decimal -from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type - -from rhosocial.activerecord.base.field_proxy import FieldProxy -from rhosocial.activerecord.base import IdentityAttribute -from rhosocial.activerecord.backend.expression import Column -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - CreateTableStatement, - DropTableStatement, - PartitionClause, - PartitionStrategy, - TruncateStatement, - ColumnNotNullConstraint, -) -from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend -from rhosocial.activerecord.backend.impl.postgres.expression import ( - PostgresAttachPartitionStatement, - PostgresColumnDefinition, - PostgresCreatePartitionStatement, - PostgresDetachPartitionStatement, - PostgresPartitionMetadataQueryStatement, -) -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord -from rhosocial.activerecord.testsuite.feature.partition.interfaces import IPartitionProvider - -from rhosocial.activerecord.backend.expression.types import ( - BigIntType, IntegerType, TextType, TimestampType, DecimalType, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnConstraint, -) - -from .scenarios import get_enabled_scenarios, get_scenario -from rhosocial.activerecord.backend.expression.objects import Table - - -class PartitionProvider(IPartitionProvider): - """Concrete partition provider backed by real PostgreSQL scenarios.""" - - TABLE_NAME = "ar_testsuite_partition_events" - PARTITIONS = { - "p2026_01": ("ar_testsuite_partition_events_p2026_01", "2026-01-01", "2026-02-01"), - "p2026_02": ("ar_testsuite_partition_events_p2026_02", "2026-02-01", "2026-03-01"), - "p2026_03": ("ar_testsuite_partition_events_p2026_03", "2026-03-01", "2026-04-01"), - } - - def __init__(self): - self._active_backends = [] - self._active_async_backends = [] - - def get_test_scenarios(self) -> List[str]: - """Return PostgreSQL scenarios configured for real backend tests.""" - return list(get_enabled_scenarios().keys()) - - def get_partition_capabilities(self, scenario_name: str) -> Dict[str, bool]: - backend = self._ensure_backend(scenario_name) - return self._capabilities(backend) - - async def async_get_partition_capabilities(self, scenario_name: str) -> Dict[str, bool]: - backend = await self._ensure_async_backend(scenario_name) - return self._capabilities(backend) - - def setup_range_partitioned_event_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], ...]: - backend = self._ensure_backend(scenario_name) - self._reset_partition_table(backend) - Event = self._event_model(backend) - return (Event,) - - async def setup_async_range_partitioned_event_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], ...]: - backend = await self._ensure_async_backend(scenario_name) - await self._reset_partition_table_async(backend) - Event = self._async_event_model(backend) - return (Event,) - - def add_future_range_partition(self, scenario_name: str) -> None: - backend = self._ensure_backend(scenario_name) - name, from_value, to_value = self.PARTITIONS["p2026_03"] - sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value) - backend.execute(sql, params) - - async def async_add_future_range_partition(self, scenario_name: str) -> None: - backend = await self._ensure_async_backend(scenario_name) - name, from_value, to_value = self.PARTITIONS["p2026_03"] - sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value) - await backend.execute(sql, params) - - def truncate_partition(self, scenario_name: str, partition_key: str) -> None: - backend = self._ensure_backend(scenario_name) - sql, params = self._truncate_partition_sql(backend.dialect, self._partition_name(partition_key)) - backend.execute(sql, params) - - async def async_truncate_partition(self, scenario_name: str, partition_key: str) -> None: - backend = await self._ensure_async_backend(scenario_name) - sql, params = self._truncate_partition_sql(backend.dialect, self._partition_name(partition_key)) - await backend.execute(sql, params) - - def detach_partition(self, scenario_name: str, partition_key: str) -> None: - backend = self._ensure_backend(scenario_name) - sql, params = self._detach_partition_sql(backend.dialect, self._partition_name(partition_key)) - backend.execute(sql, params) - - async def async_detach_partition(self, scenario_name: str, partition_key: str) -> None: - backend = await self._ensure_async_backend(scenario_name) - sql, params = self._detach_partition_sql(backend.dialect, self._partition_name(partition_key)) - await backend.execute(sql, params) - - def attach_partition(self, scenario_name: str, partition_key: str) -> None: - backend = self._ensure_backend(scenario_name) - name, from_value, to_value = self.PARTITIONS[partition_key] - sql, params = self._attach_partition_sql(backend.dialect, name, from_value, to_value) - backend.execute(sql, params) - - async def async_attach_partition(self, scenario_name: str, partition_key: str) -> None: - backend = await self._ensure_async_backend(scenario_name) - name, from_value, to_value = self.PARTITIONS[partition_key] - sql, params = self._attach_partition_sql(backend.dialect, name, from_value, to_value) - await backend.execute(sql, params) - - def get_partition_metadata(self, scenario_name: str) -> Dict[str, Any]: - backend = self._ensure_backend(scenario_name) - return self._metadata(backend) - - async def async_get_partition_metadata(self, scenario_name: str) -> Dict[str, Any]: - backend = await self._ensure_async_backend(scenario_name) - return await self._metadata_async(backend) - - def create_valid_unique_constraint(self, scenario_name: str) -> None: - backend = self._ensure_backend(scenario_name) - backend.execute( - f'CREATE UNIQUE INDEX IF NOT EXISTS "{self.TABLE_NAME}_id_created_at_uq" ' - f'ON "{self.TABLE_NAME}" (id, created_at)' - ) - - async def async_create_valid_unique_constraint(self, scenario_name: str) -> None: - backend = await self._ensure_async_backend(scenario_name) - await backend.execute( - f'CREATE UNIQUE INDEX IF NOT EXISTS "{self.TABLE_NAME}_id_created_at_uq" ' - f'ON "{self.TABLE_NAME}" (id, created_at)' - ) - - def create_invalid_unique_constraint(self, scenario_name: str) -> None: - backend = self._ensure_backend(scenario_name) - backend.execute( - f'CREATE UNIQUE INDEX "{self.TABLE_NAME}_id_only_uq" ' - f'ON "{self.TABLE_NAME}" (id)' - ) - - async def async_create_invalid_unique_constraint(self, scenario_name: str) -> None: - backend = await self._ensure_async_backend(scenario_name) - await backend.execute( - f'CREATE UNIQUE INDEX "{self.TABLE_NAME}_id_only_uq" ' - f'ON "{self.TABLE_NAME}" (id)' - ) - - def cleanup_after_test(self, scenario_name: str) -> None: - """Drop partition test tables and disconnect sync backends.""" - for backend in self._active_backends: - try: - self._drop_partition_tables(backend) - finally: - backend.disconnect() - self._active_backends.clear() - - async def cleanup_after_test_async(self, scenario_name: str) -> None: - """Drop partition test tables and disconnect async backends.""" - for backend in self._active_async_backends: - try: - await self._drop_partition_tables_async(backend) - finally: - await backend.disconnect() - self._active_async_backends.clear() - - def _ensure_backend(self, scenario_name: str): - if self._active_backends: - return self._active_backends[0] - backend_class, config = get_scenario(scenario_name) - backend = backend_class(connection_config=config) - backend.connect() - backend.introspect_and_adapt() - self._active_backends.append(backend) - return backend - - async def _ensure_async_backend(self, scenario_name: str): - if self._active_async_backends: - return self._active_async_backends[0] - _, config = get_scenario(scenario_name) - backend = AsyncPostgresBackend(connection_config=config) - await backend.connect() - await backend.introspect_and_adapt() - self._active_async_backends.append(backend) - return backend - - def _capabilities(self, backend) -> Dict[str, bool]: - dialect = backend.dialect - supports_creation = dialect.supports_partitioned_table_creation() - supports_pg11 = dialect.version >= (11, 0, 0) - return { - "range_partitioning": supports_creation and dialect.supports_range_table_partitioning(), - "add_partition": dialect.supports_add_partition(), - "truncate_partition": dialect.supports_truncate_partition(), - "detach_partition": dialect.supports_detach_partition(), - "attach_partition": dialect.supports_attach_partition(), - "partition_introspection": dialect.supports_partition_metadata_introspection(), - "partition_bounds": dialect.supports_partition_bounds_expression(), - "partitioned_unique_constraint": supports_creation and supports_pg11, - "unique_requires_partition_key": supports_creation and supports_pg11, - } - - def _reset_partition_table(self, backend) -> None: - self._drop_partition_tables(backend) - sql, params = self._create_parent_sql(backend.dialect) - backend.execute(sql, params) - for key in ("p2026_01", "p2026_02"): - name, from_value, to_value = self.PARTITIONS[key] - sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value) - backend.execute(sql, params) - - async def _reset_partition_table_async(self, backend) -> None: - await self._drop_partition_tables_async(backend) - sql, params = self._create_parent_sql(backend.dialect) - await backend.execute(sql, params) - for key in ("p2026_01", "p2026_02"): - name, from_value, to_value = self.PARTITIONS[key] - sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value) - await backend.execute(sql, params) - - def _drop_partition_tables(self, backend) -> None: - for table_name in self._all_table_names(): - sql, params = self._drop_partition_sql(backend.dialect, table_name) - backend.execute(sql, params) - - async def _drop_partition_tables_async(self, backend) -> None: - for table_name in self._all_table_names(): - sql, params = self._drop_partition_sql(backend.dialect, table_name) - await backend.execute(sql, params) - - def _all_table_names(self) -> Tuple[str, ...]: - return tuple(partition[0] for partition in self.PARTITIONS.values()) + (self.TABLE_NAME,) - - def _partition_name(self, partition_key: str) -> str: - return self.PARTITIONS[partition_key][0] - - def _create_parent_sql(self, dialect): - expr = CreateTableStatement( - dialect=dialect, - table=self.TABLE_NAME, - columns=[ - PostgresColumnDefinition(dialect, "id", BigIntType(dialect=dialect), attributes=[IdentityAttribute(generation="BY DEFAULT")]), - ColumnDefinition(dialect, "created_at", TimestampType(dialect=dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "tenant_id", IntegerType(dialect=dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "payload", TextType(dialect=dialect)), - ColumnDefinition(dialect, "amount", DecimalType(precision=12, scale=2, dialect=dialect)), - ], - partition=PartitionClause( - dialect=dialect, - method=PartitionStrategy.RANGE, - keys=[Column(dialect, "created_at")], - ), - ) - return expr.to_sql() - - def _create_range_partition_sql(self, dialect, partition_name: str, from_value: str, to_value: str): - expr = PostgresCreatePartitionStatement( - dialect=dialect, - partition_name=partition_name, - parent_table=self.TABLE_NAME, - partition_type="RANGE", - partition_values={"from": from_value, "to": to_value}, - ) - return expr.to_sql() - - def _detach_partition_sql(self, dialect, partition_name: str): - expr = PostgresDetachPartitionStatement( - dialect=dialect, - partition_name=partition_name, - parent_table=self.TABLE_NAME, - ) - return expr.to_sql() - - def _attach_partition_sql(self, dialect, partition_name: str, from_value: str, to_value: str): - expr = PostgresAttachPartitionStatement( - dialect=dialect, - partition_name=partition_name, - parent_table=self.TABLE_NAME, - partition_type="RANGE", - partition_values={"from": from_value, "to": to_value}, - ) - return expr.to_sql() - - def _truncate_partition_sql(self, dialect, partition_name: str): - expr = TruncateStatement(dialect=dialect, table=Table(dialect, partition_name)) - return expr.to_sql() - - def _drop_partition_sql(self, dialect, table_name: str): - expr = DropTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_exists=True, - cascade=True, - ) - return expr.to_sql() - - def _partition_metadata_sql(self, dialect): - expr = PostgresPartitionMetadataQueryStatement( - dialect=dialect, - parent_table=self.TABLE_NAME, - ) - return expr.to_sql() - - def _event_model(self, backend): - table_name = self.TABLE_NAME - - class PartitionEvent(ActiveRecord): - @classmethod - def table_name(cls): - return table_name - - __backend__ = backend - c: ClassVar[FieldProxy] = FieldProxy() - - id: Optional[int] = None - created_at: datetime - tenant_id: int - payload: Optional[str] = None - amount: Optional[Decimal] = None - - return PartitionEvent - - def _async_event_model(self, backend): - table_name = self.TABLE_NAME - - class AsyncPartitionEvent(AsyncActiveRecord): - @classmethod - def table_name(cls): - return table_name - - __backend__ = backend - c: ClassVar[FieldProxy] = FieldProxy() - - id: Optional[int] = None - created_at: datetime - tenant_id: int - payload: Optional[str] = None - amount: Optional[Decimal] = None - - return AsyncPartitionEvent - - def _metadata(self, backend) -> Dict[str, Any]: - sql, params = self._partition_metadata_sql(backend.dialect) - rows = backend.fetch_all(sql, params) - return self._metadata_dict(rows) - - async def _metadata_async(self, backend) -> Dict[str, Any]: - sql, params = self._partition_metadata_sql(backend.dialect) - rows = await backend.fetch_all(sql, params) - return self._metadata_dict(rows) - - def _metadata_dict(self, rows) -> Dict[str, Any]: - first = rows[0] if rows else None - partition_key = first["partition_key"] if first else "" - return { - "is_partitioned": bool(partition_key), - "strategy": "range" if partition_key.upper().startswith("RANGE") else "unknown", - "key_columns": ["created_at"] if "created_at" in partition_key.lower() else [], - "partitions": [ - {"name": row["name"], "bound": row["bound"]} - for row in rows - if row["name"] is not None - ], - } diff --git a/tests/providers/pooling.py b/tests/providers/pooling.py deleted file mode 100644 index 40186779..00000000 --- a/tests/providers/pooling.py +++ /dev/null @@ -1,132 +0,0 @@ -# tests/providers/pooling.py -"""Database pooling helpers for the PostgreSQL test providers. - -Under parallel (pytest-xdist) runs with a positive pool size the providers -reuse a per-worker pooled database ``{database}_{index}`` on the scenario's -PostgreSQL server instead of the shared scenario ``database`` schema, so -scenario variants of the same test can run concurrently on different workers -without conflicting. The pool name prefix is derived from the scenario's -configured ``database`` (the YAML ``database`` field), so e.g. -``database: test_db`` produces pooled databases ``test_db_0``, ``test_db_1``, -... Serial runs (no ``-n``) keep the previous behaviour: the provider connects -to the scenario's configured ``database``. - -The scenario name selects the server (host/port); the pool index selects the -database name. The two are deliberately unrelated. -""" - -import psycopg - -from rhosocial.activerecord.testsuite.core.pool import ( - pooled_database_name, - register_base_database, - register_pool_reset_handler, -) - -from .scenarios import SCENARIO_MAP, get_scenario_raw - -# Derive each scenario's pooled-database base name from its configured -# ``database`` (YAML ``database`` field). Registered at import time so any -# caller of pooled_database_name() / resolve_database_name() resolves names -# consistent with the scenario configuration. -for _scenario_name, _scenario_config in SCENARIO_MAP.items(): - register_base_database(_scenario_name, _scenario_config["database"]) - - -def resolve_database_name(scenario_name: str): - """ - Return the pooled database name (e.g. ``test_db_3``) used by a test for - the given scenario, or ``None`` when pooling is inactive (callers then fall - back to the scenario's configured database). - """ - return pooled_database_name(scenario_name) - - -def _escape_identifier(name: str) -> str: - """Escape a PostgreSQL identifier for use inside double quotes.""" - return name.replace('"', '""') - - -def _connect_maintenance(config) -> psycopg.Connection: - """Connect to a maintenance database (``postgres`` or the configured one).""" - for dbname in ("postgres", config.database): - try: - return psycopg.connect( - host=config.host, - port=config.port, - dbname=dbname, - user=config.username, - password=config.password, - connect_timeout=10, - autocommit=True, - ) - except psycopg.Error: - continue - return None - - -def _reset_postgres_database(scenario_name: str, db_name: str) -> None: - """Ensure the pooled database exists and is empty on the scenario's server. - - Connects to the server selected by ``scenario_name``, creates the pooled - ``db_name`` database if missing, and drops all leftover non-extension - tables so the test starts from a clean state. Extension-owned tables are - preserved (e.g. PostGIS metadata). Errors are swallowed: a failed reset - must not hide the underlying test failure. - """ - if scenario_name not in SCENARIO_MAP: - return - _, config = get_scenario_raw(scenario_name) - try: - admin_conn = _connect_maintenance(config) - if admin_conn is None: - return - try: - with admin_conn.cursor() as cursor: - cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (db_name,)) - if cursor.fetchone() is None: - cursor.execute(f'CREATE DATABASE "{_escape_identifier(db_name)}"') - finally: - admin_conn.close() - except Exception: - return - - try: - conn = psycopg.connect( - host=config.host, - port=config.port, - dbname=db_name, - user=config.username, - password=config.password, - connect_timeout=10, - autocommit=True, - ) - try: - with conn.cursor() as cursor: - cursor.execute( - """ - SELECT n.nspname, c.relname - FROM pg_class c - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE c.relkind IN ('r', 'p', 'm') - AND n.nspname NOT IN ('pg_catalog', 'information_schema') - AND NOT EXISTS ( - SELECT 1 FROM pg_depend d - JOIN pg_extension e ON d.refobjid = e.oid - WHERE d.classid = 'pg_class'::regclass - AND d.objid = c.oid - AND d.deptype = 'e' - ) - """ - ) - for schema, table in cursor.fetchall(): - cursor.execute( - f'DROP TABLE IF EXISTS "{_escape_identifier(schema)}"."{_escape_identifier(table)}" CASCADE' - ) - finally: - conn.close() - except Exception: - pass - - -register_pool_reset_handler(_reset_postgres_database) diff --git a/tests/providers/query.py b/tests/providers/query.py deleted file mode 100644 index 142790bc..00000000 --- a/tests/providers/query.py +++ /dev/null @@ -1,694 +0,0 @@ -""" -This file provides the concrete implementation of the `IQueryProvider` interface -that is defined in the `rhosocial-activerecord-testsuite` package. - -Its main responsibilities are: -1. Reporting which test scenarios (database configurations) are available. -2. Setting up the database environment for a given test. This includes: - - Getting the correct database configuration for the scenario. - - Configuring the ActiveRecord model with a database connection. - - Dropping any old tables and creating the necessary table schema. -3. Cleaning up any resources (like temporary database files) after a test runs. -""" -import os -import sys -import logging -from typing import Set, Type, List, Tuple - -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord - -# Setup logging for fixture selection debugging -logger = logging.getLogger(__name__) - -# Import the fixture selector utility -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -# Import base version models (Python 3.8+) -from rhosocial.activerecord.testsuite.feature.query.fixtures.models import ( # noqa: E402 - User as UserBase, JsonUser as JsonUserBase, - Order as OrderBase, OrderItem as OrderItemBase, - Post as PostBase, Comment as CommentBase, - Profile as ProfileBase, - MappedUser as MappedUserBase, MappedPost as MappedPostBase, MappedComment as MappedCommentBase -) -from rhosocial.activerecord.testsuite.feature.query.fixtures.cte_models import Node # noqa: E402 -from rhosocial.activerecord.testsuite.feature.query.fixtures.extended_models import ExtendedOrder, ExtendedOrderItem # noqa: E402 - -# Conditionally import Python 3.10+ models -User310 = JsonUser310 = Order310 = OrderItem310 = Post310 = Comment310 = Profile310 = None -MappedUser310 = MappedPost310 = MappedComment310 = None - -if sys.version_info >= (3, 10): - try: - from rhosocial.activerecord.testsuite.feature.query.fixtures.models_py310 import ( - User as User310, JsonUser as JsonUser310, - Order as Order310, OrderItem as OrderItem310, - Post as Post310, Comment as Comment310, - Profile as Profile310, - MappedUser as MappedUser310, MappedPost as MappedPost310, MappedComment as MappedComment310 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.10+ fixtures: {e}") - -# Conditionally import Python 3.11+ models -User311 = JsonUser311 = Order311 = OrderItem311 = Post311 = Comment311 = Profile311 = None -MappedUser311 = MappedPost311 = MappedComment311 = None - -if sys.version_info >= (3, 11): - try: - from rhosocial.activerecord.testsuite.feature.query.fixtures.models_py311 import ( - User as User311, JsonUser as JsonUser311, - Order as Order311, OrderItem as OrderItem311, - Post as Post311, Comment as Comment311, - Profile as Profile311, - MappedUser as MappedUser311, MappedPost as MappedPost311, MappedComment as MappedComment311 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.11+ fixtures: {e}") - -# Conditionally import Python 3.12+ models -User312 = JsonUser312 = Order312 = OrderItem312 = Post312 = Comment312 = Profile312 = None -MappedUser312 = MappedPost312 = MappedComment312 = None - -if sys.version_info >= (3, 12): - try: - from rhosocial.activerecord.testsuite.feature.query.fixtures.models_py312 import ( - User as User312, JsonUser as JsonUser312, - Order as Order312, OrderItem as OrderItem312, - Post as Post312, Comment as Comment312, - Profile as Profile312, - MappedUser as MappedUser312, MappedPost as MappedPost312, MappedComment as MappedComment312 - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.12+ fixtures: {e}") - - -# Select appropriate fixture classes based on Python version -def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type: - """Select the most appropriate model class for the current Python version.""" - candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None] - selected = select_fixture(*candidates) - logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}") - return selected - - -# Select sync models -User = _select_model_class(UserBase, User312, User311, User310, "User") -JsonUser = _select_model_class(JsonUserBase, JsonUser312, JsonUser311, JsonUser310, "JsonUser") -Order = _select_model_class(OrderBase, Order312, Order311, Order310, "Order") -OrderItem = _select_model_class(OrderItemBase, OrderItem312, OrderItem311, OrderItem310, "OrderItem") -Post = _select_model_class(PostBase, Post312, Post311, Post310, "Post") -Comment = _select_model_class(CommentBase, Comment312, Comment311, Comment310, "Comment") -MappedUser = _select_model_class(MappedUserBase, MappedUser312, MappedUser311, MappedUser310, "MappedUser") -MappedPost = _select_model_class(MappedPostBase, MappedPost312, MappedPost311, MappedPost310, "MappedPost") -MappedComment = _select_model_class(MappedCommentBase, MappedComment312, MappedComment311, MappedComment310, "MappedComment") # noqa: E501 -Profile = _select_model_class(ProfileBase, Profile312, Profile311, Profile310, "Profile") - -from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402 -from rhosocial.activerecord.testsuite.feature.query.interfaces import IQuerySyncProvider, IQueryAsyncProvider # noqa: E402 -from rhosocial.activerecord.testsuite.core.protocols import WorkerTestProtocol # noqa: E402 - -# Composite-PK model classes used by setup_order_item_model. -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - OrderItem as CompositeOrderItemBase, - AsyncOrderItem as AsyncCompositeOrderItemBase, -) - -# Expression-based DDL fixtures -from providers.fixtures._common import drop_table # noqa: E402 -from providers.fixtures.query import TABLE_EXPRESSIONS as QUERY_TABLE_EXPRESSIONS # noqa: E402 - -# The scenarios are defined specifically for this backend. -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - - -class QueryProviderBase: - def __init__(self): - self._active_backends = [] - self._created_tables: Set[str] = set() - self._created_schemas: Set[str] = set() - self._mixed_schema_provisioned = False - - def supports_schema(self) -> bool: - """PostgreSQL models named schema namespaces natively.""" - return True - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _provision_cross_schema(self, backend_instance) -> None: - """Create the two cross-schema fixture namespaces, tables and seeds.""" - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - SCHEMA_A, - SCHEMA_B, - ) - - opts = ExecutionOptions(stmt_type=StatementType.DDL) - statements = [] - for schema in (SCHEMA_A, SCHEMA_B): - statements.append(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE') - statements.append(f'CREATE SCHEMA "{schema}"') - statements.append( - f'CREATE TABLE "{SCHEMA_A}".customers ' - f'(id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL)' - ) - statements.append( - f'CREATE TABLE "{SCHEMA_B}".orders ' - f'(id SERIAL PRIMARY KEY, customer_id INTEGER NOT NULL, amount INTEGER NOT NULL)' - ) - for sql in statements: - backend_instance.execute(sql, options=opts) - self._created_schemas.update((SCHEMA_A, SCHEMA_B)) - - def _provision_mixed_schema_sync(self, backend_instance) -> None: - """Provision an identical orders table in SCHEMA_A (default stays untouched).""" - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - SCHEMA_A, - ) - - opts = ExecutionOptions(stmt_type=StatementType.DDL) - statements = [ - f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE', - f'CREATE SCHEMA "{SCHEMA_A}"', - f'CREATE TABLE "{SCHEMA_A}".orders (' - "id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, " - "order_number VARCHAR(255) NOT NULL, " - "total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, " - "status VARCHAR(50) NOT NULL DEFAULT 'pending', " - "created_at TIMESTAMP WITH TIME ZONE, updated_at TIMESTAMP WITH TIME ZONE)", - ] - for sql in statements: - backend_instance.execute(sql, options=opts) - self._mixed_schema_provisioned = True - - async def _provision_mixed_schema_async(self, backend_instance) -> None: - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - SCHEMA_A, - ) - - opts = ExecutionOptions(stmt_type=StatementType.DDL) - statements = [ - f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE', - f'CREATE SCHEMA "{SCHEMA_A}"', - f'CREATE TABLE "{SCHEMA_A}".orders (' - "id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, " - "order_number VARCHAR(255) NOT NULL, " - "total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, " - "status VARCHAR(50) NOT NULL DEFAULT 'pending', " - "created_at TIMESTAMP WITH TIME ZONE, updated_at TIMESTAMP WITH TIME ZONE)", - ] - for sql in statements: - await backend_instance.execute(sql, options=opts) - self._mixed_schema_provisioned = True - - def _track_backend(self, backend_instance, collection): - if backend_instance not in collection: - collection.append(backend_instance) - - def _load_postgres_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "query", "schema" - ) - schema_path = os.path.join(schema_dir, filename) - with open(schema_path, 'r', encoding='utf-8') as f: - return f.read() - - -class QuerySyncProvider(QueryProviderBase, IQuerySyncProvider, WorkerTestProtocol): - - def __init__(self): - super().__init__() - self._active_backends = [] - - def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str, shared_backend=None) -> Type[ActiveRecord]: - backend_class, config = get_scenario(scenario_name) - if shared_backend is None: - model_class.configure(config, backend_class) - else: - model_class.__connection_config__ = config - model_class.__backend_class__ = backend_class - model_class.__backend__ = shared_backend - backend_instance = model_class.__backend__ - self._track_backend(backend_instance, self._active_backends) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, table_name).to_sql() - backend_instance.execute(sql, params, options=opts) - except Exception: - pass - if fn := QUERY_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - sql, params = create_expr.to_sql() - backend_instance.execute(sql, params, options=opts) - self._created_tables.add(table_name) - return model_class - - def _setup_multiple_models(self, models_and_tables: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - result = [] - shared_backend = None - for i, (model_class, table_name) in enumerate(models_and_tables): - if i == 0: - configured_model = self._setup_model(model_class, scenario_name, table_name) - shared_backend = configured_model.__backend__ - else: - configured_model = self._setup_model(model_class, scenario_name, table_name, shared_backend=shared_backend) - result.append(configured_model) - return tuple(result) - - def setup_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - models_and_tables = [ - (User, "users"), - (Order, "orders"), - (OrderItem, "order_items") - ] - return self._setup_multiple_models(models_and_tables, scenario_name) - - def setup_blog_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - models_and_tables = [ - (User, "users"), - (Post, "posts"), - (Comment, "comments") - ] - return self._setup_multiple_models(models_and_tables, scenario_name) - - def setup_json_user_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord.backend.impl.postgres.adapters import PostgresJSONBAdapter - jsonb_adapter = PostgresJSONBAdapter() - json_fields = ["settings", "tags", "profile", "roles", "scores", "subscription", "preferences"] - for field_name in json_fields: - if field_name not in JsonUser.__field_adapters__: - JsonUser.__field_adapters__[field_name] = (jsonb_adapter, str) - models_and_tables = [ - (JsonUser, "json_users"), - ] - return self._setup_multiple_models(models_and_tables, scenario_name) - - def setup_tree_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - models_and_tables = [ - (Node, "nodes"), - ] - return self._setup_multiple_models(models_and_tables, scenario_name) - - def setup_extended_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - models_and_tables = [ - (User, "users"), - (ExtendedOrder, "extended_orders"), - (ExtendedOrderItem, "extended_order_items") - ] - return self._setup_multiple_models(models_and_tables, scenario_name) - - def setup_combined_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - models_and_tables = [ - (User, "users"), - (Order, "orders"), - (OrderItem, "order_items"), - (Post, "posts"), - (Comment, "comments") - ] - return self._setup_multiple_models(models_and_tables, scenario_name) - - def setup_annotated_query_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.annotated_adapter_models import SearchableItem - return self._setup_multiple_models([ - (SearchableItem, "searchable_items"), - ], scenario_name) - - def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models([ - (MappedUser, "users"), - (MappedPost, "posts"), - (MappedComment, "comments") - ], scenario_name) - - def setup_profile_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models([ - (User, "users"), - (Profile, "profiles"), - ], scenario_name) - - def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - """Set up the composite-PK OrderItem model for the query feature tests.""" - from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType - from providers.fixtures._common import drop_table - from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_EXPRS - - backend_class, config = get_scenario(scenario_name) - CompositeOrderItemBase.configure(config, backend_class) - backend_instance = CompositeOrderItemBase.__backend__ - self._track_backend(backend_instance, self._active_backends) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, "order_items").to_sql() - backend_instance.execute(sql, params, options=opts) - except Exception: - pass - if fn := BASIC_EXPRS.get("order_items"): - create_expr = fn(backend_instance.dialect, "order_items") - sql, params = create_expr.to_sql() - backend_instance.execute(sql, params, options=opts) - self._created_tables.add("order_items") - return CompositeOrderItemBase - - def setup_schema_fixtures(self, scenario_name: str): - """Two models in two distinct schemas (see testsuite schema_models).""" - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - SchemaCustomer, - SchemaOrder, - ) - - backend_class, config = get_scenario(scenario_name) - SchemaCustomer.configure(config, backend_class) - SchemaOrder.configure(config, backend_class) - shared_backend = SchemaCustomer.__backend__ - self._track_backend(shared_backend, self._active_backends) - self._provision_cross_schema(shared_backend) - return SchemaCustomer, SchemaOrder - - def setup_mixed_schema_fixtures(self, scenario_name: str): - """(User, Order, MixedSchemaOrder): default users/orders plus orders in SCHEMA_A.""" - from rhosocial.activerecord.testsuite.feature.query.cross_schema.mixed_schema_models import ( - MixedSchemaOrder, - ) - from rhosocial.activerecord.testsuite.feature.query.fixtures.models import Order, User - - user_model = self._setup_model(User, scenario_name, "users") - shared_backend = user_model.__backend__ - order_model = self._setup_model(Order, scenario_name, "orders", shared_backend) - - backend_class, config = get_scenario(scenario_name) - MixedSchemaOrder.__connection_config__ = config - MixedSchemaOrder.__backend_class__ = backend_class - MixedSchemaOrder.__backend__ = shared_backend - self._track_backend(shared_backend, self._active_backends) - self._provision_mixed_schema_sync(shared_backend) - return user_model, order_model, MixedSchemaOrder - - def _get_schema_sql_for_fixture_type(self, fixture_type: str) -> dict: - schemas = {} - if fixture_type == 'order': - tables = ['users', 'orders', 'order_items'] - elif fixture_type == 'blog': - tables = ['users', 'posts', 'comments'] - elif fixture_type == 'user': - tables = ['users'] - elif fixture_type == 'combined': - tables = ['users', 'orders', 'order_items', 'posts', 'comments'] - else: - tables = ['users'] - for table in tables: - schemas[table] = self._load_postgres_schema(f'{table}.sql') - return schemas - - def get_worker_connection_params(self, scenario_name: str, fixture_type: str = 'order') -> dict: - from .scenarios import SCENARIO_MAP - is_async = fixture_type and fixture_type.startswith('async_') - backend_class_name = 'AsyncPostgresBackend' if is_async else 'PostgresBackend' - base_fixture_type = fixture_type.replace('async_', '') if fixture_type else 'order' - schema_sql = self._get_schema_sql_for_fixture_type(base_fixture_type) - if scenario_name not in SCENARIO_MAP: - if SCENARIO_MAP: - scenario_name = next(iter(SCENARIO_MAP)) - else: - raise ValueError("No scenarios registered") - config_dict = SCENARIO_MAP[scenario_name] - from .pooling import resolve_database_name - - pooled_db = resolve_database_name(scenario_name) - if pooled_db: - config_dict = {**config_dict, "database": pooled_db} - return { - 'backend_module': 'rhosocial.activerecord.backend.impl.postgres.backend', - 'backend_class_name': backend_class_name, - 'config_class_module': 'rhosocial.activerecord.backend.impl.postgres.config', - 'config_class_name': 'PostgresConnectionConfig', - 'config_kwargs': config_dict, - 'schema_sql': schema_sql, - } - - def get_worker_schema_sql(self, scenario_name: str, table_name: str) -> str: - return self._load_postgres_schema(f'{table_name}.sql') - - def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_backends: - try: - for table_name in list(self._created_tables): - try: - backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - backend_instance.disconnect() - except Exception: - pass - for schema_name in list(self._created_schemas): - try: - backend_instance.execute(f'DROP SCHEMA IF EXISTS "{schema_name}" CASCADE') - except Exception: - pass - if self._mixed_schema_provisioned: - try: - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - SCHEMA_A, - ) - - backend_instance.execute(f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE') - except Exception: - pass - self._mixed_schema_provisioned = False - self._active_backends.clear() - self._created_tables.clear() - self._created_schemas.clear() - - -class QueryAsyncProvider(QueryProviderBase, IQueryAsyncProvider): - - def __init__(self): - super().__init__() - self._active_async_backends = [] - - async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str, shared_backend=None) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - _, config = get_scenario(scenario_name) - if shared_backend is None: - await model_class.configure(config, AsyncPostgresBackend) - else: - model_class.__connection_config__ = config - model_class.__backend_class__ = AsyncPostgresBackend - model_class.__backend__ = shared_backend - backend_instance = model_class.__backend__ - self._track_backend(backend_instance, self._active_async_backends) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, table_name).to_sql() - await backend_instance.execute(sql, params, options=opts) - except Exception: - pass - if fn := QUERY_TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - sql, params = create_expr.to_sql() - await backend_instance.execute(sql, params, options=opts) - self._created_tables.add(table_name) - return model_class - - async def _setup_multiple_models_async(self, models_and_tables: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - result = [] - shared_backend = None - for i, (model_class, table_name) in enumerate(models_and_tables): - if i == 0: - configured_model = await self._setup_async_model(model_class, scenario_name, table_name) - shared_backend = configured_model.__backend__ - else: - configured_model = await self._setup_async_model(model_class, scenario_name, table_name, shared_backend=shared_backend) - result.append(configured_model) - return tuple(result) - - async def setup_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser, AsyncOrder, AsyncOrderItem - return await self._setup_multiple_models_async([ - (AsyncUser, "users"), - (AsyncOrder, "orders"), - (AsyncOrderItem, "order_items") - ], scenario_name) - - async def setup_blog_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_blog_models import AsyncPost, AsyncComment - return await self._setup_multiple_models_async([ - (AsyncUser, "users"), - (AsyncPost, "posts"), - (AsyncComment, "comments") - ], scenario_name) - - async def setup_json_user_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_json_models import AsyncJsonUser - from rhosocial.activerecord.backend.impl.postgres.adapters import PostgresJSONBAdapter - jsonb_adapter = PostgresJSONBAdapter() - json_fields = ["settings", "tags", "profile", "roles", "scores", "subscription", "preferences"] - for field_name in json_fields: - if field_name not in AsyncJsonUser.__field_adapters__: - AsyncJsonUser.__field_adapters__[field_name] = (jsonb_adapter, str) - return await self._setup_multiple_models_async([ - (AsyncJsonUser, "json_users"), - ], scenario_name) - - async def setup_tree_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_cte_models import AsyncNode - return await self._setup_multiple_models_async([ - (AsyncNode, "nodes"), - ], scenario_name) - - async def setup_extended_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_extended_models import AsyncUser, AsyncExtendedOrder, AsyncExtendedOrderItem - return await self._setup_multiple_models_async([ - (AsyncUser, "users"), - (AsyncExtendedOrder, "extended_orders"), - (AsyncExtendedOrderItem, "extended_order_items") - ], scenario_name) - - async def setup_combined_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser, AsyncOrder, AsyncOrderItem - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_blog_models import AsyncPost, AsyncComment - return await self._setup_multiple_models_async([ - (AsyncUser, "users"), - (AsyncOrder, "orders"), - (AsyncOrderItem, "order_items"), - (AsyncPost, "posts"), - (AsyncComment, "comments") - ], scenario_name) - - async def setup_annotated_query_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_annotated_adapter_models import AsyncSearchableItem - return await self._setup_multiple_models_async([ - (AsyncSearchableItem, "searchable_items"), - ], scenario_name) - - async def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import AsyncMappedUser, AsyncMappedPost, AsyncMappedComment - return await self._setup_multiple_models_async([ - (AsyncMappedUser, "users"), - (AsyncMappedPost, "posts"), - (AsyncMappedComment, "comments") - ], scenario_name) - - async def setup_profile_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser, AsyncProfile - return await self._setup_multiple_models_async([ - (AsyncUser, "users"), - (AsyncProfile, "profiles"), - ], scenario_name) - - async def setup_order_item_model(self, scenario_name: str) -> Type[AsyncActiveRecord]: - """Set up the composite-PK AsyncOrderItem model for the query feature tests.""" - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType - from providers.fixtures._common import drop_table - from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_EXPRS - - _, config = get_scenario(scenario_name) - await AsyncCompositeOrderItemBase.configure(config, AsyncPostgresBackend) - backend_instance = AsyncCompositeOrderItemBase.__backend__ - self._track_backend(backend_instance, self._active_async_backends) - opts = ExecutionOptions(stmt_type=StatementType.DDL) - try: - sql, params = drop_table(backend_instance.dialect, "order_items").to_sql() - await backend_instance.execute(sql, params, options=opts) - except Exception: - pass - if fn := BASIC_EXPRS.get("order_items"): - create_expr = fn(backend_instance.dialect, "order_items") - sql, params = create_expr.to_sql() - await backend_instance.execute(sql, params, options=opts) - self._created_tables.add("order_items") - return AsyncCompositeOrderItemBase - - async def setup_schema_fixtures(self, scenario_name: str): - """Two async models in two distinct schemas.""" - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - AsyncSchemaCustomer, - AsyncSchemaOrder, - ) - - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend - - _, config = get_scenario(scenario_name) - - # Provision DDL through a short-lived synchronous connection. - ddl_backend = PostgresBackend(connection_config=config) - ddl_backend.connect() - try: - self._provision_cross_schema(ddl_backend) - finally: - ddl_backend.disconnect() - - await AsyncSchemaCustomer.configure(config, AsyncPostgresBackend) - await AsyncSchemaOrder.configure(config, AsyncPostgresBackend) - shared_backend = AsyncSchemaCustomer.__backend__ - self._track_backend(shared_backend, self._active_async_backends) - return AsyncSchemaCustomer, AsyncSchemaOrder - - async def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_async_backends: - try: - for table_name in list(self._created_tables): - try: - await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE') - except Exception: - pass - finally: - try: - await backend_instance.disconnect() - except Exception: - pass - for schema_name in list(self._created_schemas): - try: - await backend_instance.execute( - f'DROP SCHEMA IF EXISTS "{schema_name}" CASCADE') - except Exception: - pass - if self._mixed_schema_provisioned: - try: - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - SCHEMA_A, - ) - - await backend_instance.execute(f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE') - except Exception: - pass - self._mixed_schema_provisioned = False - self._active_async_backends.clear() - self._created_tables.clear() - self._created_schemas.clear() - - async def setup_mixed_schema_fixtures(self, scenario_name: str): - """(AsyncUser, AsyncOrder, AsyncMixedSchemaOrder) with orders also in SCHEMA_A.""" - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - from rhosocial.activerecord.testsuite.feature.query.cross_schema.mixed_schema_models import ( - AsyncMixedSchemaOrder, - ) - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import ( - AsyncOrder, - AsyncUser, - ) - - _, config = get_scenario(scenario_name) - user_model = await self._setup_async_model(AsyncUser, scenario_name, "users") - shared_backend = user_model.__backend__ - self._track_backend(shared_backend, self._active_async_backends) - order_model = await self._setup_async_model(AsyncOrder, scenario_name, "orders", shared_backend) - - AsyncMixedSchemaOrder.__connection_config__ = config - AsyncMixedSchemaOrder.__backend_class__ = AsyncPostgresBackend - AsyncMixedSchemaOrder.__backend__ = shared_backend - self._track_backend(shared_backend, self._active_async_backends) - await self._provision_mixed_schema_async(shared_backend) - return AsyncUser, order_model, AsyncMixedSchemaOrder diff --git a/tests/providers/query_benchmark.py b/tests/providers/query_benchmark.py deleted file mode 100644 index cca4f5c6..00000000 --- a/tests/providers/query_benchmark.py +++ /dev/null @@ -1,15 +0,0 @@ -"""PostgreSQL provider for query benchmark tests.""" - -from rhosocial.activerecord.testsuite.benchmark.query.interfaces import QueryBenchmarkContext - -from .crud_benchmark import CrudBenchmarkProvider - - -class QueryBenchmarkProvider(CrudBenchmarkProvider): - def setup_benchmark_sync(self, scenario: str, size: str): - context = super().setup_benchmark_sync(scenario, size) - return QueryBenchmarkContext(**context.__dict__) - - async def setup_benchmark_async(self, scenario: str, size: str): - context = await super().setup_benchmark_async(scenario, size) - return QueryBenchmarkContext(**context.__dict__) diff --git a/tests/providers/query_connection.py b/tests/providers/query_connection.py deleted file mode 100644 index d0c01c3f..00000000 --- a/tests/providers/query_connection.py +++ /dev/null @@ -1,169 +0,0 @@ -# tests/providers/query_connection.py -""" -Concrete implementation of IQueryConnectionProvider for PostgreSQL backend. - -This provider sets up connection pools and models for testing -query classes context awareness (ActiveQuery, CTEQuery, SetOperationQuery). -""" -from typing import Type, Tuple, Optional, List - -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord -from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend -from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig # noqa: F401 -from rhosocial.activerecord.connection.pool import BackendPool, AsyncBackendPool, PoolConfig -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType - -from rhosocial.activerecord.testsuite.feature.query.connection.interfaces import IQueryConnectionProvider -from .scenarios import get_scenario, get_enabled_scenarios - - -class SyncQueryTestUser(ActiveRecord): - """Sync test user model for query connection pool tests.""" - @classmethod - def table_name(cls): - return "test_users" - - id: Optional[int] = None - name: str - email: str - - -class AsyncQueryTestUser(AsyncActiveRecord): - """Async test user model for query connection pool tests.""" - @classmethod - def table_name(cls): - return "test_users" - - id: Optional[int] = None - name: str - email: str - - -class QueryConnectionProvider(IQueryConnectionProvider): - """ - PostgreSQL backend implementation for query connection pool context tests. - """ - - def __init__(self): - self._active_backends: List = [] - self._active_async_backends: List = [] - - def get_test_scenarios(self) -> list: - """Returns available test scenarios.""" - return list(get_enabled_scenarios().keys()) - - def _create_test_table(self, backend): - """Create the test_users table.""" - try: - backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL)) - except Exception: - pass - - backend.execute(""" - CREATE TABLE test_users ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL - ) - """, options=ExecutionOptions(stmt_type=StatementType.DDL)) - - async def _create_test_table_async(self, backend): - """Create the test_users table asynchronously.""" - try: - await backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL)) # noqa: E501 - except Exception: - pass - - await backend.execute(""" - CREATE TABLE test_users ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL - ) - """, options=ExecutionOptions(stmt_type=StatementType.DDL)) - - def setup_sync_pool_and_model(self, scenario_name: str) -> Tuple[BackendPool, Type[ActiveRecord]]: - """Setup sync connection pool and model for query context tests.""" - _, config = get_scenario(scenario_name) - - # Create connection pool - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: PostgresBackend(connection_config=config) - ) - pool = BackendPool.create(pool_config) - - # Create table - with pool.connection() as backend: - self._create_test_table(backend) - self._active_backends.append(backend) - - # Configure model to use a separate backend (not pool backend) - # This tests that model.backend() returns pool context backend - SyncQueryTestUser.configure(config, PostgresBackend) - self._active_backends.append(SyncQueryTestUser.__backend__) - - return pool, SyncQueryTestUser - - async def setup_async_pool_and_model(self, scenario_name: str) -> Tuple[AsyncBackendPool, Type[AsyncActiveRecord]]: - """Setup async connection pool and model for query context tests.""" - from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( - AsyncPostgresBackend, - ) - - _, config = get_scenario(scenario_name) - - # Create connection pool - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: AsyncPostgresBackend(connection_config=config) - ) - - # Create pool - pool = await AsyncBackendPool.create(pool_config) - - # Create table - async with pool.connection() as backend: - await self._create_test_table_async(backend) - self._active_async_backends.append(backend) - - # Configure model - await AsyncQueryTestUser.configure(config, AsyncPostgresBackend) - self._active_async_backends.append(AsyncQueryTestUser.__backend__) - - return pool, AsyncQueryTestUser - - def cleanup_sync(self, scenario_name: str, pool: BackendPool): - """Cleanup after sync tests.""" - pool.close(timeout=1.0) - - # Disconnect backends - for backend in self._active_backends: - try: - backend.execute("DROP TABLE IF EXISTS test_users CASCADE") - except Exception: - pass - try: - backend.disconnect() - except Exception: - pass - self._active_backends.clear() - - async def cleanup_async(self, scenario_name: str, pool: AsyncBackendPool): - """Cleanup after async tests.""" - await pool.close(timeout=1.0) - - # Disconnect backends - for backend in self._active_async_backends: - try: - await backend.execute("DROP TABLE IF EXISTS test_users CASCADE") - except Exception: - pass - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() diff --git a/tests/providers/registry.py b/tests/providers/registry.py deleted file mode 100644 index 2375942b..00000000 --- a/tests/providers/registry.py +++ /dev/null @@ -1,77 +0,0 @@ -# tests/providers/registry.py -""" -Test Provider Registry for postgres Backend - -This module registers the concrete implementations of the test suite provider -interfaces for the postgres backend. -""" -from rhosocial.activerecord.testsuite.core.registry import ProviderRegistry -from rhosocial.activerecord.testsuite.feature.cli.providers import ( - GenericAsyncCLIProvider, - GenericSyncCLIProvider, -) -from .basic import BasicSyncProvider, BasicAsyncProvider -from .events import EventsSyncProvider, EventsAsyncProvider -from .mixins import MixinsSyncProvider, MixinsAsyncProvider -from .query import QuerySyncProvider, QueryAsyncProvider -from .relation import RelationSyncProvider, RelationAsyncProvider -from .basic_connection import BasicConnectionProvider -from .query_connection import QueryConnectionProvider -from .crud_benchmark import CrudBenchmarkProvider -from .fastapi_benchmark import FastAPIBenchmarkProvider -from .mixin_benchmark import MixinBenchmarkProvider -from .query_benchmark import QueryBenchmarkProvider -from .transaction_benchmark import TransactionBenchmarkProvider - -# Importing the pooling module registers the PostgreSQL-specific pool reset -# handler (a side effect of the import), mirroring MySQL's tests/providers/pooling.py. -from . import pooling # noqa: F401 - -# Create a single, global instance of the ProviderRegistry for this backend. -provider_registry = ProviderRegistry() - -# Register the concrete implementations as the providers for the -# interfaces defined in the testsuite. -provider_registry.register("feature.basic.IBasicProvider", BasicSyncProvider) -provider_registry.register("feature.basic.IBasicSyncProvider", BasicSyncProvider) -provider_registry.register("feature.basic.IBasicAsyncProvider", BasicAsyncProvider) - -provider_registry.register("feature.events.IEventsProvider", EventsSyncProvider) -provider_registry.register("feature.events.IEventsSyncProvider", EventsSyncProvider) -provider_registry.register("feature.events.IEventsAsyncProvider", EventsAsyncProvider) - -provider_registry.register("feature.mixins.IMixinsProvider", MixinsSyncProvider) -provider_registry.register("feature.mixins.IMixinsSyncProvider", MixinsSyncProvider) -provider_registry.register("feature.mixins.IMixinsAsyncProvider", MixinsAsyncProvider) - -provider_registry.register("feature.query.IQueryProvider", QuerySyncProvider) -provider_registry.register("feature.query.IQuerySyncProvider", QuerySyncProvider) -provider_registry.register("feature.query.IQueryAsyncProvider", QueryAsyncProvider) - -provider_registry.register("feature.relation.IRelationProvider", RelationSyncProvider) -provider_registry.register("feature.relation.IRelationSyncProvider", RelationSyncProvider) -provider_registry.register("feature.relation.IRelationAsyncProvider", RelationAsyncProvider) - -# Register connection pool context awareness providers -provider_registry.register( - "feature.basic.connection.IBasicConnectionProvider", - BasicConnectionProvider, -) -provider_registry.register( - "feature.query.connection.IQueryConnectionProvider", - QueryConnectionProvider, -) - -# Register benchmark providers. -provider_registry.register("benchmark.crud.ICrudBenchmarkProvider", CrudBenchmarkProvider) -provider_registry.register("benchmark.query.IQueryBenchmarkProvider", QueryBenchmarkProvider) -provider_registry.register( - "benchmark.transaction.ITransactionBenchmarkProvider", - TransactionBenchmarkProvider, -) -provider_registry.register("benchmark.mixin.IMixinBenchmarkProvider", MixinBenchmarkProvider) -provider_registry.register("benchmark.fastapi.IFastAPIBenchmarkProvider", FastAPIBenchmarkProvider) - -# Register CLI providers, assembled from the basic and mixins providers above. -provider_registry.register("feature.cli.ICLISyncProvider", GenericSyncCLIProvider) -provider_registry.register("feature.cli.ICLIAsyncProvider", GenericAsyncCLIProvider) diff --git a/tests/providers/relation.py b/tests/providers/relation.py deleted file mode 100644 index 2ec56c93..00000000 --- a/tests/providers/relation.py +++ /dev/null @@ -1,459 +0,0 @@ -# tests/providers/relation.py -from typing import Dict, List, Tuple, Type, Set - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend -from rhosocial.activerecord.backend.impl.postgres.adapters.json import PostgresJSONBAdapter -from rhosocial.activerecord.testsuite.feature.relation.interfaces import IRelationSyncProvider, IRelationAsyncProvider -from rhosocial.activerecord.testsuite.feature.relation.fixtures.models import ( - Employee, Department, Author, Book, Chapter, Profile, - User, Post, Comment, - AsyncUser, AsyncPost, AsyncComment, - BoundaryOwner, BoundaryProfile, BoundaryPost, - AsyncBoundaryOwner, AsyncBoundaryProfile, AsyncBoundaryPost, -) -from .scenarios import get_enabled_scenarios, get_scenario - - -EMPLOYEE_DEPARTMENT_SCHEMA = """ - DROP TABLE IF EXISTS employees CASCADE; - DROP TABLE IF EXISTS departments CASCADE; - CREATE TABLE departments ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL, - description TEXT DEFAULT '' - ); - CREATE TABLE employees ( - id SERIAL PRIMARY KEY, - username TEXT NOT NULL, - department_id INTEGER NOT NULL - ); -""" - -AUTHOR_BOOK_SCHEMA = """ - DROP TABLE IF EXISTS chapters CASCADE; - DROP TABLE IF EXISTS books CASCADE; - DROP TABLE IF EXISTS profiles CASCADE; - DROP TABLE IF EXISTS authors CASCADE; - CREATE TABLE authors ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL - ); - CREATE TABLE books ( - id SERIAL PRIMARY KEY, - title TEXT NOT NULL, - author_id INTEGER NOT NULL - ); - CREATE TABLE chapters ( - id SERIAL PRIMARY KEY, - title TEXT NOT NULL, - book_id INTEGER NOT NULL - ); - CREATE TABLE profiles ( - id SERIAL PRIMARY KEY, - bio TEXT NOT NULL, - author_id INTEGER NOT NULL - ); -""" - -USER_POST_COMMENT_SCHEMA = """ - DROP TABLE IF EXISTS comments CASCADE; - DROP TABLE IF EXISTS posts CASCADE; - DROP TABLE IF EXISTS users CASCADE; - CREATE TABLE users ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL, - email TEXT, - settings JSONB - ); - CREATE TABLE posts ( - id SERIAL PRIMARY KEY, - title TEXT NOT NULL, - body TEXT NOT NULL, - user_id INTEGER NOT NULL, - view_count INTEGER NOT NULL DEFAULT 0, - metadata JSONB - ); - CREATE TABLE comments ( - id SERIAL PRIMARY KEY, - body TEXT NOT NULL, - post_id INTEGER NOT NULL, - meta JSONB - ); -""" - -RELATION_BOUNDARY_SCHEMA = """ - DROP TABLE IF EXISTS relation_boundary_posts CASCADE; - DROP TABLE IF EXISTS relation_boundary_profiles CASCADE; - DROP TABLE IF EXISTS relation_boundary_owners CASCADE; - CREATE TABLE relation_boundary_owners ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL - ); - CREATE TABLE relation_boundary_profiles ( - id SERIAL PRIMARY KEY, - bio TEXT NOT NULL, - owner_id INTEGER NULL - ); - CREATE TABLE relation_boundary_posts ( - id SERIAL PRIMARY KEY, - title TEXT NOT NULL, - owner_id INTEGER NULL - ); -""" - - -class RelationProviderBase: - def __init__(self): - self._sync_user_post_comment_setup = False - self._async_user_post_comment_setup = False - self._sync_relation_boundary_setup = False - self._async_relation_boundary_setup = False - self._created_tables: Set[str] = set() - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _configure_with_shared_backend(self, model_class, config, backend_class, backend): - model_class.__connection_config__ = config - model_class.__backend_class__ = backend_class - model_class.__backend__ = backend - - def _configure_json_field_adapters(self): - adapter = PostgresJSONBAdapter() - User.__field_adapters__["settings"] = (adapter, str) - Post.__field_adapters__["metadata"] = (adapter, str) - Comment.__field_adapters__["meta"] = (adapter, str) - AsyncUser.__field_adapters__["settings"] = (adapter, str) - AsyncPost.__field_adapters__["metadata"] = (adapter, str) - AsyncComment.__field_adapters__["meta"] = (adapter, str) - - def _reset_setup_state(self): - self._sync_user_post_comment_setup = False - self._async_user_post_comment_setup = False - self._sync_relation_boundary_setup = False - self._async_relation_boundary_setup = False - - -class RelationSyncProvider(RelationProviderBase, IRelationSyncProvider): - - def __init__(self): - super().__init__() - self._active_backends = [] - - def _execute_script(self, backend, sql: str): - for statement in sql.split(";"): - statement = statement.strip() - if statement: - backend.execute(statement) - - def _setup_employee_department(self, scenario_name): - backend_class, config = get_scenario(scenario_name) - Employee.configure(config, backend_class) - backend = Employee.backend() - backend.connect() - backend.introspect_and_adapt() - self._active_backends.append(backend) - self._execute_script(backend, EMPLOYEE_DEPARTMENT_SCHEMA) - self._configure_with_shared_backend(Department, config, backend_class, backend) - return Employee, Department - - def _setup_author_book(self, scenario_name): - backend_class, config = get_scenario(scenario_name) - Author.configure(config, backend_class) - backend = Author.backend() - backend.connect() - backend.introspect_and_adapt() - self._active_backends.append(backend) - self._execute_script(backend, AUTHOR_BOOK_SCHEMA) - self._configure_with_shared_backend(Book, config, backend_class, backend) - self._configure_with_shared_backend(Chapter, config, backend_class, backend) - self._configure_with_shared_backend(Profile, config, backend_class, backend) - return Author, Book, Chapter, Profile - - def _setup_user_post_comment_sync(self, scenario_name): - if not self._sync_user_post_comment_setup: - self._configure_json_field_adapters() - backend_class, config = get_scenario(scenario_name) - User.configure(config, backend_class) - backend = User.backend() - backend.connect() - backend.introspect_and_adapt() - self._active_backends.append(backend) - self._execute_script(backend, USER_POST_COMMENT_SCHEMA) - self._configure_with_shared_backend(Post, config, backend_class, backend) - self._configure_with_shared_backend(Comment, config, backend_class, backend) - self._sync_user_post_comment_setup = True - - def _setup_relation_boundary_sync(self, scenario_name): - if not self._sync_relation_boundary_setup: - backend_class, config = get_scenario(scenario_name) - BoundaryOwner.configure(config, backend_class) - backend = BoundaryOwner.backend() - backend.connect() - backend.introspect_and_adapt() - self._active_backends.append(backend) - self._execute_script(backend, RELATION_BOUNDARY_SCHEMA) - self._configure_with_shared_backend( - BoundaryProfile, config, backend_class, backend, - ) - self._configure_with_shared_backend( - BoundaryPost, config, backend_class, backend, - ) - self._sync_relation_boundary_setup = True - - def setup_employee_department_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_employee_department(scenario_name) - - def setup_author_book_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_author_book(scenario_name) - - def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - self._setup_user_post_comment_sync(scenario_name) - return User - - def setup_post_model(self, scenario_name: str) -> Type[ActiveRecord]: - self._setup_user_post_comment_sync(scenario_name) - return Post - - def setup_comment_model(self, scenario_name: str) -> Type[ActiveRecord]: - self._setup_user_post_comment_sync(scenario_name) - return Comment - - def setup_relation_boundary_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - self._setup_relation_boundary_sync(scenario_name) - return BoundaryOwner, BoundaryProfile, BoundaryPost - - def load_relation_boundary_dataset(self, scenario_name: str, dataset_name: str) -> Dict[str, int]: - self._setup_relation_boundary_sync(scenario_name) - return self._load_relation_boundary_dataset(dataset_name) - - def _load_relation_boundary_dataset(self, dataset_name): - if dataset_name == "null_foreign_key": - profile = BoundaryProfile(bio="No owner", owner_id=None) - profile.save() - return {"profile_id": profile.id} - - if dataset_name == "orphan_foreign_key": - missing_owner_id = 999999 - post = BoundaryPost(title="Orphan post", owner_id=missing_owner_id) - post.save() - return {"post_id": post.id, "missing_owner_id": missing_owner_id} - - if dataset_name == "owner_without_children": - owner = BoundaryOwner(name="Owner without children") - owner.save() - return {"owner_id": owner.id} - - if dataset_name == "multiple_has_one_matches": - owner = BoundaryOwner(name="Owner with duplicate profiles") - owner.save() - first = BoundaryProfile(bio="First profile", owner_id=owner.id) - first.save() - second = BoundaryProfile(bio="Second profile", owner_id=owner.id) - second.save() - return { - "owner_id": owner.id, - "first_profile_id": first.id, - "second_profile_id": second.id, - } - - raise ValueError(f"Unknown relation boundary dataset: {dataset_name}") - - def cleanup_after_test(self, scenario_name: str) -> None: - tables_to_drop = [ - 'employees', 'departments', - 'authors', 'books', 'chapters', 'profiles', - 'users', 'posts', 'comments', - 'relation_boundary_owners', 'relation_boundary_profiles', 'relation_boundary_posts', - ] - for backend in self._active_backends: - try: - for table in tables_to_drop: - try: - backend.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE') - except Exception: - pass - finally: - try: - backend.disconnect() - except Exception: - pass - self._active_backends.clear() - self._reset_setup_state() - - -class RelationAsyncProvider(RelationProviderBase, IRelationAsyncProvider): - - def __init__(self): - super().__init__() - self._active_async_backends = [] - - def _configure_async_model_without_connection(self, model_class, config, backend=None): - if backend is None: - backend = AsyncPostgresBackend(connection_config=config) - model_class.__connection_config__ = config - model_class.__backend_class__ = AsyncPostgresBackend - model_class.__backend__ = backend - return backend - - async def _execute_script_async(self, backend, sql: str): - for statement in sql.split(";"): - statement = statement.strip() - if statement: - await backend.execute(statement) - - async def _setup_employee_department_fixtures_async(self, scenario_name): - _, config = get_scenario(scenario_name) - await Employee.configure(config, AsyncPostgresBackend) - backend = Employee.backend() - await backend.connect() - await backend.introspect_and_adapt() - self._active_async_backends.append(backend) - await self._execute_script_async(backend, EMPLOYEE_DEPARTMENT_SCHEMA) - self._configure_with_shared_backend(Department, config, AsyncPostgresBackend, backend) - return Employee, Department - - async def _setup_author_book_fixtures_async(self, scenario_name): - _, config = get_scenario(scenario_name) - await Author.configure(config, AsyncPostgresBackend) - backend = Author.backend() - await backend.connect() - await backend.introspect_and_adapt() - self._active_async_backends.append(backend) - await self._execute_script_async(backend, AUTHOR_BOOK_SCHEMA) - self._configure_with_shared_backend(Book, config, AsyncPostgresBackend, backend) - self._configure_with_shared_backend(Chapter, config, AsyncPostgresBackend, backend) - self._configure_with_shared_backend(Profile, config, AsyncPostgresBackend, backend) - return Author, Book, Chapter, Profile - - async def _setup_user_post_comment_async(self, scenario_name): - if not self._async_user_post_comment_setup: - self._configure_json_field_adapters() - _, config = get_scenario(scenario_name) - backend = self._configure_async_model_without_connection(AsyncUser, config) - self._configure_async_model_without_connection(AsyncPost, config, backend) - self._configure_async_model_without_connection(AsyncComment, config, backend) - self._active_async_backends.append(backend) - await backend.introspect_and_adapt() - await self._execute_script_async(backend, USER_POST_COMMENT_SCHEMA) - self._async_user_post_comment_setup = True - - async def _setup_relation_boundary_async(self, scenario_name): - if not self._async_relation_boundary_setup: - _, config = get_scenario(scenario_name) - backend = self._configure_async_model_without_connection( - AsyncBoundaryOwner, config, - ) - self._configure_async_model_without_connection( - AsyncBoundaryProfile, config, backend, - ) - self._configure_async_model_without_connection( - AsyncBoundaryPost, config, backend, - ) - self._active_async_backends.append(backend) - await backend.introspect_and_adapt() - await self._execute_script_async(backend, RELATION_BOUNDARY_SCHEMA) - self._async_relation_boundary_setup = True - - async def setup_employee_department_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]: - return await self._setup_employee_department_fixtures_async(scenario_name) - - async def setup_author_book_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return await self._setup_author_book_fixtures_async(scenario_name) - - async def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]: - await self._setup_user_post_comment_async(scenario_name) - return AsyncUser - - async def setup_post_model(self, scenario_name: str) -> Type[ActiveRecord]: - await self._setup_user_post_comment_async(scenario_name) - return AsyncPost - - async def setup_comment_model(self, scenario_name: str) -> Type[ActiveRecord]: - await self._setup_user_post_comment_async(scenario_name) - return AsyncComment - - async def setup_relation_boundary_fixtures( - self, - scenario_name: str, - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - await self._setup_relation_boundary_async(scenario_name) - return AsyncBoundaryOwner, AsyncBoundaryProfile, AsyncBoundaryPost - - async def load_relation_boundary_dataset( - self, - scenario_name: str, - dataset_name: str, - ) -> Dict[str, int]: - await self._setup_relation_boundary_async(scenario_name) - return await self._load_async_relation_boundary_dataset(dataset_name) - - async def _load_async_relation_boundary_dataset(self, dataset_name): - if dataset_name == "null_foreign_key": - profile = AsyncBoundaryProfile(bio="No owner", owner_id=None) - await profile.save() - return {"profile_id": profile.id} - - if dataset_name == "orphan_foreign_key": - missing_owner_id = 999999 - post = AsyncBoundaryPost(title="Orphan post", owner_id=missing_owner_id) - await post.save() - return {"post_id": post.id, "missing_owner_id": missing_owner_id} - - if dataset_name == "owner_without_children": - owner = AsyncBoundaryOwner(name="Owner without children") - await owner.save() - return {"owner_id": owner.id} - - if dataset_name == "multiple_has_one_matches": - owner = AsyncBoundaryOwner(name="Owner with duplicate profiles") - await owner.save() - first = AsyncBoundaryProfile(bio="First profile", owner_id=owner.id) - await first.save() - second = AsyncBoundaryProfile(bio="Second profile", owner_id=owner.id) - await second.save() - return { - "owner_id": owner.id, - "first_profile_id": first.id, - "second_profile_id": second.id, - } - - raise ValueError(f"Unknown relation boundary dataset: {dataset_name}") - - async def cleanup_after_test(self, scenario_name: str): - tables_to_drop = [ - 'employees', 'departments', - 'authors', 'books', 'chapters', 'profiles', - 'users', 'posts', 'comments', - 'relation_boundary_owners', 'relation_boundary_profiles', 'relation_boundary_posts', - ] - for backend in self._active_async_backends: - try: - for table in tables_to_drop: - try: - await backend.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE') - except Exception: - pass - finally: - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() - self._reset_setup_state() diff --git a/tests/providers/scenarios.py b/tests/providers/scenarios.py deleted file mode 100644 index 621b6677..00000000 --- a/tests/providers/scenarios.py +++ /dev/null @@ -1,142 +0,0 @@ -# tests/providers/scenarios.py -"""postgres backend test scenario configuration mapping table""" - -import os -from dataclasses import replace -from typing import Dict, Any, Tuple, Type -from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend -from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig -from rhosocial.activerecord.testsuite.core.pool import pooled_database_name - -# Scenario name -> configuration dictionary mapping table (postgres only) -SCENARIO_MAP: Dict[str, Dict[str, Any]] = {} - - -def register_scenario(name: str, config: Dict[str, Any]): - """Register postgres test scenario""" - SCENARIO_MAP[name] = config - - -def get_scenario_raw(name: str) -> Tuple[Type[PostgresBackend], PostgresConnectionConfig]: - """Return the backend class and connection config for a scenario. - - The config uses the scenario's configured ``database``; no pool override is - applied. Used by the pool reset handler, which must reach the server - regardless of whether a pooled database exists yet. - """ - if name not in SCENARIO_MAP: - # If the specified scenario is not found, use the first available one as a fallback - if SCENARIO_MAP: - name = next(iter(SCENARIO_MAP)) - else: - raise ValueError("No scenarios registered") - - # Unpack the configuration dictionary into the dataclass constructor. - config = PostgresConnectionConfig(**SCENARIO_MAP[name]) - return PostgresBackend, config - - -def get_scenario(name: str) -> Tuple[Type[PostgresBackend], PostgresConnectionConfig]: - """ - Retrieves the backend class and a connection configuration object for a given - scenario name. This is called by the provider to set up the database for a test. - - Under an active database pool the config's ``database`` is replaced by the - worker's pooled database name (``{database}_{index}``) so concurrent workers - never share a schema. Serial runs keep the scenario's configured database. - """ - backend_class, config = get_scenario_raw(name) - pooled_db = pooled_database_name(name) - if pooled_db: - config = replace(config, database=pooled_db) - return backend_class, config - - -def get_enabled_scenarios() -> Dict[str, Any]: - """ - Returns the map of all currently enabled scenarios. The testsuite's conftest - uses this to parameterize the tests, causing them to run for each scenario. - """ - return SCENARIO_MAP - - -def _load_scenarios_from_config(): - """ - Load scenarios from a configuration file with the following priority: - 1. Environment variable specified path (highest priority) - 2. Default path tests/config/postgres_scenarios.yaml (lowest priority) - If no valid configuration file is found, terminate with an error. - """ - try: - import yaml - except ImportError: - raise ImportError("PyYAML is required to load postgres scenario configuration files. Please install it.") # noqa: B904 - - # First, try to load from path specified in environment variable - env_config_path = os.getenv("POSTGRES_SCENARIOS_CONFIG_PATH") - if env_config_path and os.path.exists(env_config_path): - print(f"Loading postgres scenarios from environment-specified path: {env_config_path}") - config_path = env_config_path - else: - # Default path with lowest priority - # Note: The path is relative to this file's location. - config_path = os.path.join(os.path.dirname(__file__), "..", "config", "postgres_scenarios.yaml") - if not os.path.exists(config_path): - raise FileNotFoundError( - "No postgres scenarios configuration file found. " - "Either set POSTGRES_SCENARIOS_CONFIG_PATH environment variable to point to a valid YAML file " - f"or place postgres_scenarios.yaml in the {os.path.dirname(config_path)} directory." - ) - print(f"Loading postgres scenarios from default path: {config_path}") - - try: - with open(config_path, 'r', encoding='utf-8') as f: - config_data = yaml.safe_load(f) - - if 'scenarios' not in config_data: - raise ValueError(f"Configuration file {config_path} does not contain 'scenarios' key") - - for scenario_name, config in config_data['scenarios'].items(): - register_scenario(scenario_name, config) - - _apply_scenario_filter() - - except Exception as e: - raise RuntimeError(f"Failed to load or parse scenario configuration file {config_path}: {e}") # noqa: B904 - - -def _apply_scenario_filter(): - """Filter SCENARIO_MAP based on the active scenarios env var. - - The env var is set either by the --scenarios pytest option in the - testsuite's root conftest (TESTSUITE_ACTIVE_SCENARIOS) or by a backend - local override (POSTGRES_ACTIVE_SCENARIOS). It contains comma-separated - full scenario names (e.g., "postgres_16,postgres_17"). - """ - filter_str = os.getenv("POSTGRES_ACTIVE_SCENARIOS") or os.getenv("TESTSUITE_ACTIVE_SCENARIOS") - if not filter_str: - return - - allowed = set(s.strip() for s in filter_str.split(',') if s.strip()) - if not allowed: - return - - to_remove = [name for name in SCENARIO_MAP if name not in allowed] - for name in to_remove: - del SCENARIO_MAP[name] - - if to_remove: - print(f"Filtered scenarios: kept {list(SCENARIO_MAP.keys())}, " - f"removed {to_remove} (--scenarios={filter_str})") - - -def _register_default_scenarios(): - """ - Registers the scenarios loaded from an external configuration file. - No hardcoded scenarios are registered in the code itself. - """ - _load_scenarios_from_config() - - -# Register default scenarios during initialization -_register_default_scenarios() diff --git a/tests/providers/transaction_benchmark.py b/tests/providers/transaction_benchmark.py deleted file mode 100644 index 3330de2e..00000000 --- a/tests/providers/transaction_benchmark.py +++ /dev/null @@ -1,17 +0,0 @@ -"""PostgreSQL provider for transaction benchmark tests.""" - -from rhosocial.activerecord.testsuite.benchmark.transaction.interfaces import ( - TransactionBenchmarkContext, -) - -from .crud_benchmark import CrudBenchmarkProvider - - -class TransactionBenchmarkProvider(CrudBenchmarkProvider): - def setup_benchmark_sync(self, scenario: str, size: str): - context = super().setup_benchmark_sync(scenario, size) - return TransactionBenchmarkContext(**context.__dict__) - - async def setup_benchmark_async(self, scenario: str, size: str): - context = await super().setup_benchmark_async(scenario, size) - return TransactionBenchmarkContext(**context.__dict__) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md b/tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md new file mode 100644 index 00000000..b5784f2d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md @@ -0,0 +1,130 @@ +# Directory-bound database shards + +Every directory under `execute/` that holds tests declares exactly one +database in its own `conftest.py`: + +```python +from pathlib import Path + +from providers.shards import register + +register(Path(__file__).parent, "test_db_") +``` + +The rules behind the map: + +- **One leaf directory = one database.** A directory that only groups + capabilities (e.g. `execute/postgres/extension/`, `execute/postgres/types/`) + holds no test files and declares no shard; only its leaf subdirectories do. +- Shared, cross-backend features use the fixed numbers `test_db_1` … + `test_db_23`; `test_db_24` is reserved for the backend namespace root + (`execute/postgres/`), and backend-unique leaves start at `test_db_25` with + no upper limit. +- A sharded directory's tests stay on one xdist worker + (`xdist_group("db:")`) and share that database: directories run + serially, different directories run in parallel. Construct tests carry no + group and no database. +- `resolve_database_name()` prefers the directory shard over worker-slot + pooling, so serial runs use the directory's database too. +- Worker-slot pooling uses the `test_db_pool_` base (see + `tests/providers/pooling.py`), so pool slots never collide with + `test_db_` shards. +- All registered shards are created and cleared once per session by the + autouse session fixture in `tests/conftest.py`; they are not dropped at the + end of the session. +- When a leaf is added or moved, update this table and allocate the next free + number. + +## Shared leaves (fixed 1..23) + +| Leaf directory | Database | Test modules | +|---|---|---| +| `execute/connection/` | `test_db_1` | 8 | +| `execute/crud/` | `test_db_2` | 4 | +| `execute/query/` | `test_db_3` | 5 | +| `execute/join/` | `test_db_4` | 1 | +| `execute/transaction/` | `test_db_5` | 8 | +| `execute/ddl_table/` | `test_db_6` | 1 | +| `execute/ddl_column/` | `test_db_7` | 0 (placeholder `.gitkeep`) | +| `execute/ddl_constraint/` | `test_db_8` | 0 (placeholder `.gitkeep`) | +| `execute/ddl_index/` | `test_db_9` | 0 (placeholder `.gitkeep`) | +| `execute/ddl_view/` | `test_db_10` | 2 | +| `execute/dml_insert/` | `test_db_11` | 2 | +| `execute/dml_update_delete/` | `test_db_12` | 1 | +| `execute/json/` | `test_db_13` | 1 | +| `execute/partition/` | `test_db_14` | 4 | +| `execute/introspection/` | `test_db_15` | 19 | +| `execute/errors/` | `test_db_16` | 3 | +| `execute/concurrency/` | `test_db_17` | 2 | +| `execute/cli/` | `test_db_18` | 4 | +| `execute/functions/` | `test_db_19` | 2 | +| `execute/sequence_identity/` | `test_db_20` | 1 | +| `execute/fulltext_spatial/` | `test_db_21` | 0 (placeholder `.gitkeep`; PostgreSQL full-text/spatial extensions live under `execute/postgres/extension/`) | +| `execute/show_admin/` | `test_db_22` | 0 (placeholder `.gitkeep`) | +| `execute/routine_domain/` | `test_db_23` | 0 (placeholder `.gitkeep`) | + +## Backend namespace root + +| Directory | Database | Test modules | +|---|---|---| +| `execute/postgres/` | `test_db_24` | 0 (namespace only; leaf subdirectories carry their own shards) | + +## PostgreSQL-unique leaves (25+) + +### `execute/postgres/extension//` + +| Leaf directory | Database | Test modules | +|---|---|---| +| `execute/postgres/extension/address_standardizer/` | `test_db_25` | 1 | +| `execute/postgres/extension/bloom/` | `test_db_26` | 1 | +| `execute/postgres/extension/btree_gin/` | `test_db_27` | 1 | +| `execute/postgres/extension/btree_gist/` | `test_db_28` | 1 | +| `execute/postgres/extension/citext/` | `test_db_29` | 1 | +| `execute/postgres/extension/cube/` | `test_db_30` | 1 | +| `execute/postgres/extension/fuzzystrmatch/` | `test_db_31` | 1 | +| `execute/postgres/extension/hstore/` | `test_db_32` | 1 | +| `execute/postgres/extension/hypopg/` | `test_db_33` | 1 | +| `execute/postgres/extension/intarray/` | `test_db_34` | 1 | +| `execute/postgres/extension/orafce/` | `test_db_35` | 1 | +| `execute/postgres/extension/pg_cron/` | `test_db_36` | 1 | +| `execute/postgres/extension/pg_partman/` | `test_db_37` | 1 | +| `execute/postgres/extension/pg_repack/` | `test_db_38` | 1 | +| `execute/postgres/extension/pg_stat_statements/` | `test_db_39` | 1 | +| `execute/postgres/extension/pg_surgery/` | `test_db_40` | 1 | +| `execute/postgres/extension/pg_walinspect/` | `test_db_41` | 1 | +| `execute/postgres/extension/pgaudit/` | `test_db_42` | 1 | +| `execute/postgres/extension/pgcrypto/` | `test_db_43` | 1 | +| `execute/postgres/extension/pglogical/` | `test_db_44` | 1 | +| `execute/postgres/extension/tablefunc/` | `test_db_45` | 1 | +| `execute/postgres/extension/uuid_ossp/` | `test_db_46` | 1 | +| `execute/postgres/extension/earthdistance/` | `test_db_47` | 1 | +| `execute/postgres/extension/ltree/` | `test_db_48` | 1 | +| `execute/postgres/extension/pg_trgm/` | `test_db_49` | 1 | +| `execute/postgres/extension/pgrouting/` | `test_db_50` | 1 | +| `execute/postgres/extension/pgvector/` | `test_db_51` | 1 | +| `execute/postgres/extension/postgis/` | `test_db_52` | 1 | +| `execute/postgres/extension/postgis_raster/` | `test_db_53` | 1 | +| `execute/postgres/extension/ddl/` | `test_db_54` | 1 (CREATE/DROP EXTENSION execution) | + +### `execute/postgres/types//` + +| Leaf directory | Database | Test modules | +|---|---|---| +| `execute/postgres/types/bitstring/` | `test_db_55` | 1 | +| `execute/postgres/types/cast/` | `test_db_56` | 1 | +| `execute/postgres/types/enum/` | `test_db_57` | 1 | +| `execute/postgres/types/extension_types/` | `test_db_58` | 1 | +| `execute/postgres/types/literal/` | `test_db_59` | 1 | +| `execute/postgres/types/lsn/` | `test_db_60` | 1 | +| `execute/postgres/types/money/` | `test_db_61` | 1 | +| `execute/postgres/types/network/` | `test_db_62` | 1 | +| `execute/postgres/types/oid/` | `test_db_63` | 1 | +| `execute/postgres/types/range/` | `test_db_64` | 1 | +| `execute/postgres/types/xml/` | `test_db_65` | 1 | + +### Other PostgreSQL-unique leaves + +| Leaf directory | Database | Test modules | +|---|---|---| +| `execute/postgres/dialect_security/` | `test_db_66` | 1 | +| `execute/postgres/capability_probe/` | `test_db_67` | 1 | diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py index 5aa30bc9..a3c80c8b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py @@ -1,110 +1,131 @@ # tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py +"""Fixtures for the backend-owned tests. + +The backend runs these against a real server. The scenario supplies the +connection parameters; the database name is derived from the directory that +owns the test, so two directories never share tables. +""" +import os +from typing import Any, Dict, Tuple, Type + import pytest import pytest_asyncio -import yaml -import os -from typing import Dict, Any, Tuple, Type # noqa: F401 -from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend +import support.postgres + from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend +from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import ( + AsyncPostgresBackend, +) from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig - # --- Scenario Loading Logic --- -SCENARIO_MAP: Dict[str, Dict[str, Any]] = {} +SCENARIO_MAP: Dict[str, Dict[str, Any]] = dict(support.postgres.SCENARIO_MAP) -def register_scenario(name: str, config: Dict[str, Any]): - SCENARIO_MAP[name] = config -def _load_scenarios_from_config(): - """ - Load scenarios from a configuration file. - Uses POSTGRES_SCENARIOS_CONFIG_PATH or a default path. +def _apply_scenario_filter(): + """Filter SCENARIO_MAP based on the active scenarios env var. + + Keeps the backend-feature scenarios consistent with the scenarios active + for the rest of the test run. """ - config_path = None - env_config_path = os.getenv("POSTGRES_SCENARIOS_CONFIG_PATH") - - if env_config_path and os.path.exists(env_config_path): - config_path = env_config_path - else: - # Path is relative to this file's location - default_path = os.path.join(os.path.dirname(__file__), "../../../../config", "postgres_scenarios.yaml") - if os.path.exists(default_path): - config_path = default_path - elif env_config_path: - print(f"Warning: Scenario file specified in POSTGRES_SCENARIOS_CONFIG_PATH not found: {env_config_path}") - return - - if not config_path: - raise FileNotFoundError( - "No PostgreSQL scenarios configuration file found. " - "Set POSTGRES_SCENARIOS_CONFIG_PATH or place postgres_scenarios.yaml in tests/config." - ) + filter_str = os.getenv("POSTGRES_ACTIVE_SCENARIOS") or os.getenv( + "TESTSUITE_ACTIVE_SCENARIOS" + ) + if not filter_str: + return + allowed = set(s.strip() for s in filter_str.split(",") if s.strip()) + if not allowed: + return + for name in [n for n in SCENARIO_MAP if n not in allowed]: + del SCENARIO_MAP[name] + + +_apply_scenario_filter() + + +def get_enabled_scenarios() -> Dict[str, Any]: + return SCENARIO_MAP + + +def get_scenario_names(): + return list(get_enabled_scenarios().keys()) + + +_PREPARED_DATABASES = set() - try: - with open(config_path, 'r', encoding='utf-8') as f: - config_data = yaml.safe_load(f) - if 'scenarios' not in config_data: - raise ValueError(f"Configuration file {config_path} does not contain 'scenarios' key") +def _database_for(request) -> str: + """Derive the logical database the directory owning the test runs in.""" + parts = list(request.node.path.parts) + try: + index = max(i for i, part in enumerate(parts) if part == "backend") + except ValueError: + return "test_backend" + names = [part for part in parts[index + 1 : -1] if part] + return "test_backend" + "".join("_" + name for name in names) - for scenario_name, config in config_data['scenarios'].items(): - if config: # Ensure config is not null or empty - register_scenario(scenario_name, config) - except ImportError: - raise ImportError("PyYAML is required to load scenario configuration files") # noqa: B904 +def _prepare_database(scenario_name: str, database: str) -> None: + """Create the directory's database once per scenario.""" + key = (scenario_name, database) + if key in _PREPARED_DATABASES: + return + support.postgres.scenario(scenario_name).reset_database(database) + _PREPARED_DATABASES.add(key) -_load_scenarios_from_config() -def get_scenario_config(name: str) -> Dict[str, Any]: +def get_scenario( + name: str, database: str = "test_backend" +) -> Tuple[Type[PostgresBackend], PostgresConnectionConfig]: if name not in SCENARIO_MAP: if SCENARIO_MAP: name = next(iter(SCENARIO_MAP)) else: - raise ValueError("No scenarios registered or enabled") - config_dict = SCENARIO_MAP[name].copy() - # Apply the pooled database name so parallel workers never share a schema. - from providers.pooling import resolve_database_name + raise ValueError("No scenarios registered") + _prepare_database(name, database) + return PostgresBackend, support.postgres.scenario(name).make_config(database) + + +def pytest_collection_modifyitems(config, items): + """Pin a backend directory's tests to one worker. + + These directories create and drop tables in the directory's own database, + so two workers must never run tests from the same directory at once. + """ + for item in items: + parts = item.path.parts + if "backend" not in parts: + continue + item.add_marker(pytest.mark.xdist_group("postgres-backend::" + str(item.path.parent))) - pooled_db = resolve_database_name(name) - if pooled_db: - config_dict["database"] = pooled_db - return config_dict # --- Provider Logic for Fixtures --- + class BackendFeatureProvider: def __init__(self): self._backend = None self._async_backend = None - def setup_backend(self, scenario_name: str): - print(f"DEBUG: setup_backend called with scenario_name: {scenario_name}") + def setup_backend(self, scenario_name: str, database: str): if self._backend: return self._backend - config_dict = get_scenario_config(scenario_name) - # Remove 'enabled' keyword as it's not a connection parameter - config_dict.pop('enabled', None) - config = PostgresConnectionConfig(**config_dict) - self._backend = PostgresBackend(connection_config=config) + backend_class, config = get_scenario(scenario_name, database) + self._backend = backend_class(connection_config=config) self._backend.connect() - # Introspect and adapt to detect server version and extensions + # Introspect and adapt to detect server version and extensions. self._backend.introspect_and_adapt() return self._backend - async def setup_async_backend(self, scenario_name: str): - print(f"DEBUG: setup_async_backend called with scenario_name: {scenario_name}") + async def setup_async_backend(self, scenario_name: str, database: str): if self._async_backend: return self._async_backend - config_dict = get_scenario_config(scenario_name) - # Remove 'enabled' keyword as it's not a connection parameter - config_dict.pop('enabled', None) - config = PostgresConnectionConfig(**config_dict) + _, config = get_scenario(scenario_name, database) self._async_backend = AsyncPostgresBackend(connection_config=config) await self._async_backend.connect() - # Introspect and adapt to detect server version and extensions + # Introspect and adapt to detect server version and extensions. await self._async_backend.introspect_and_adapt() return self._async_backend @@ -118,26 +139,26 @@ async def async_cleanup(self): await self._async_backend.disconnect() self._async_backend = None + # --- Fixtures --- -def get_scenario_names(): - return list(SCENARIO_MAP.keys()) @pytest.fixture(scope="function", params=get_scenario_names()) def postgres_backend(request): scenario_name = request.param provider = BackendFeatureProvider() - backend = provider.setup_backend(scenario_name) - backend.scenario_name = scenario_name # Attach for test reference + backend = provider.setup_backend(scenario_name, _database_for(request)) + backend.scenario_name = scenario_name # Attach for test reference yield backend provider.cleanup() + @pytest_asyncio.fixture(scope="function", params=get_scenario_names()) async def async_postgres_backend(request): scenario_name = request.param provider = BackendFeatureProvider() - backend = await provider.setup_async_backend(scenario_name) - backend.scenario_name = scenario_name # Attach for test reference + backend = await provider.setup_async_backend(scenario_name, _database_for(request)) + backend.scenario_name = scenario_name # Attach for test reference yield backend await provider.async_cleanup() @@ -146,38 +167,38 @@ async def async_postgres_backend(request): @pytest.fixture(scope="function") -def postgres_backend_single(): +def postgres_backend_single(request): """Non-parameterized fixture using the first available scenario.""" scenario_names = get_scenario_names() if not scenario_names: pytest.skip("No PostgreSQL scenarios configured") scenario_name = scenario_names[0] provider = BackendFeatureProvider() - backend = provider.setup_backend(scenario_name) + backend = provider.setup_backend(scenario_name, _database_for(request)) backend.scenario_name = scenario_name yield backend provider.cleanup() @pytest_asyncio.fixture(scope="function") -async def async_postgres_backend_single(): +async def async_postgres_backend_single(request): """Non-parameterized async fixture using the first available scenario.""" scenario_names = get_scenario_names() if not scenario_names: pytest.skip("No PostgreSQL scenarios configured") scenario_name = scenario_names[0] provider = BackendFeatureProvider() - backend = await provider.setup_async_backend(scenario_name) + backend = await provider.setup_async_backend(scenario_name, _database_for(request)) backend.scenario_name = scenario_name yield backend await provider.async_cleanup() -# --- Control Backend for Session Modification Tests --- +# --- Class-scoped Backend Fixtures --- @pytest.fixture(scope="class") -def postgres_backend_class(): +def postgres_backend_class(request): """Class-scoped backend fixture for extension integration tests. Uses the first available scenario. Suitable for test classes where @@ -188,21 +209,21 @@ def postgres_backend_class(): pytest.skip("No PostgreSQL scenarios configured") scenario_name = scenario_names[0] provider = BackendFeatureProvider() - backend = provider.setup_backend(scenario_name) + backend = provider.setup_backend(scenario_name, _database_for(request)) backend.scenario_name = scenario_name yield backend provider.cleanup() @pytest_asyncio.fixture(scope="class") -async def async_postgres_backend_class(): +async def async_postgres_backend_class(request): """Class-scoped async backend fixture for extension integration tests.""" scenario_names = get_scenario_names() if not scenario_names: pytest.skip("No PostgreSQL scenarios configured") scenario_name = scenario_names[0] provider = BackendFeatureProvider() - backend = await provider.setup_async_backend(scenario_name) + backend = await provider.setup_async_backend(scenario_name, _database_for(request)) backend.scenario_name = scenario_name yield backend await provider.async_cleanup() @@ -212,7 +233,7 @@ async def async_postgres_backend_class(): @pytest.fixture(scope="function") -def postgres_control_backend(): +def postgres_control_backend(request): """ Dedicated control backend for tests that modify PostgreSQL session settings. @@ -230,13 +251,13 @@ def postgres_control_backend(): pytest.skip("No PostgreSQL scenarios configured") scenario_name = scenario_names[0] provider = BackendFeatureProvider() - backend = provider.setup_backend(scenario_name) + backend = provider.setup_backend(scenario_name, _database_for(request)) yield backend provider.cleanup() @pytest_asyncio.fixture(scope="function") -async def async_postgres_control_backend(): +async def async_postgres_control_backend(request): """ Dedicated async control backend for tests that modify PostgreSQL session settings. @@ -248,7 +269,7 @@ async def async_postgres_control_backend(): pytest.skip("No PostgreSQL scenarios configured") scenario_name = scenario_names[0] provider = BackendFeatureProvider() - backend = await provider.setup_async_backend(scenario_name) + backend = await provider.setup_async_backend(scenario_name, _database_for(request)) yield backend await provider.async_cleanup() @@ -257,6 +278,7 @@ async def async_postgres_control_backend(): def postgres_dialect(): """Fixture providing PostgresDialect instance for testing transaction expressions.""" from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect + return PostgresDialect(version=(15, 0, 0)) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/connection/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/connection/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py index ef195797..f0d9ded5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py """Regression tests for DDL compilation of auto-increment, standard types, boolean defaults, and timestamps. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py index b0bff327..7f69af74 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py """Tests for the PostgreSQL-specific column definition expressions.""" import pytest diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py index 623f812e..271d1995 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py """PostgreSQL constraint capability switches, pinned to live measurements. Every value asserted here was measured against the instances diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py index 068ca3da..9207765e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py """ PostgreSQL CREATE TABLE ... LIKE syntax tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py similarity index 91% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py index f62ec7de..043c82e5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py """Explicit PostgresDialect database DDL capability + rendering tests.""" from rhosocial.activerecord.backend.expression.objects import Database diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py index c1acfe5c..96201752 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py try: from typing import Annotated, Optional diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py similarity index 87% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py index ae0fe338..9cfaa85b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py """Explicit PostgreSQL generated-column capability assertions. The generic ``GeneratedColumnExpression``/formatter already covers these diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py index 008204ef..a5d3d165 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py """Tests for ALTER TABLE IF [NOT] EXISTS qualifier rendering on PostgreSQL. PostgreSQL supports the vendor extensions since 9.6: @@ -30,14 +30,14 @@ def dialect(): return PostgresDialect(version=(15, 0, 0)) -class TestPostgresAlterTableModifierCapabilities: +class TestAlterTableModifierCapabilities: def test_supports_switches(self, dialect): assert dialect.supports_add_column_if_not_exists() is True assert dialect.supports_drop_column_if_exists() is True assert dialect.supports_drop_constraint_if_exists() is True -class TestPostgresAddColumnIfNotExists: +class TestAddColumnIfNotExists: def test_if_not_exists_renders_qualifier(self, dialect): action = AddColumnAction( dialect, @@ -70,7 +70,7 @@ def test_inside_alter_table(self, dialect): assert params == () -class TestPostgresDropColumnIfExists: +class TestDropColumnIfExists: def test_if_exists_renders_qualifier(self, dialect): action = DropColumnAction(dialect, column_name="x", if_exists=True) sql, params = action.to_sql() @@ -85,7 +85,7 @@ def test_none_renders_plain_form(self, dialect): assert params == () -class TestPostgresDropConstraintIfExists: +class TestDropConstraintIfExists: def test_if_exists_renders_qualifier(self, dialect): action = DropTableConstraintAction( dialect, constraint_name="fkey", if_exists=True @@ -110,7 +110,7 @@ def test_none_renders_plain_form(self, dialect): assert params == () -class TestPostgresAlterColumnTypeAndUsing: +class TestAlterColumnTypeAndUsing: """SET DATA TYPE with the PostgreSQL ``USING`` conversion expression. Covered here per plan §6.3: the ALTER COLUMN subclauses added by the @@ -174,7 +174,7 @@ def test_set_data_type_using_rejected_for_other_ops(self, dialect): action.to_sql() -class TestPostgresRenameColumnAndTable: +class TestRenameColumnAndTable: """RENAME COLUMN / RENAME TABLE render through the core actions.""" def test_rename_column(self, dialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py index 5781b756..33ff342a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py """The PostgreSQL database-size query nodes (SQL generation only). ``get_storage_info`` used to spell ``SELECT pg_database_size(%s) as diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py index dda58388..d1fd4a5c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py """Tests for PostgreSQL DDL improvements: capability gating, UnsupportedFeatureError.""" import pytest from unittest.mock import patch, PropertyMock @@ -14,7 +14,7 @@ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError -class TestPostgresViewCapabilityGating: +class TestViewCapabilityGating: """Tests for PostgreSQL VIEW DDL capability gating.""" def test_create_or_replace_view_supported(self): @@ -43,7 +43,7 @@ def test_materialized_view_supported(self): assert PostgresDialect(version=(9, 2, 0)).supports_materialized_view() is False -class TestPostgresColumnCapabilityGating: +class TestColumnCapabilityGating: """Tests for PostgreSQL COLUMN DDL capability gating.""" def test_foreign_key_on_delete_supported(self): @@ -57,7 +57,7 @@ def test_foreign_key_on_update_supported(self): assert dialect.supports_foreign_key_on_update() is True -class TestPostgresSchemaCapabilityGating: +class TestSchemaCapabilityGating: """Tests for PostgreSQL SCHEMA DDL capability gating.""" def test_create_schema_supported(self): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py index aa9e2630..6529b9f7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py """Tests for PostgreSQL DDL protocol feature detection. This module tests the protocol-based feature detection methods: @@ -44,7 +44,7 @@ from rhosocial.activerecord.backend.impl.postgres.protocols.ddl.type import PostgresTypeSupport -class TestPostgresPartitionSupportFeatureDetection: +class TestPartitionSupportFeatureDetection: """Test PostgresPartitionSupport feature detection methods.""" def test_supports_table_partitioning_pg9(self): @@ -188,7 +188,7 @@ def test_supports_partitionwise_aggregate_pg11(self): assert dialect.supports_partitionwise_aggregate() is True -class TestPostgresPartitionMixinDirect: +class TestPartitionMixinDirect: """Test PostgresPartitionMixin partition capability methods directly.""" class _Host: @@ -269,7 +269,7 @@ def test_supports_concurrent_attach_direct(self): assert self._PartitionMixinPg10().supports_concurrent_attach() is False -class TestPostgresIndexSupportFeatureDetection: +class TestIndexSupportFeatureDetection: """Test PostgresIndexSupport feature detection methods.""" def test_supports_safe_hash_index_pg9(self): @@ -353,7 +353,7 @@ def test_supports_spgist_include_pg14(self): assert dialect.supports_spgist_include() is True -class TestPostgresMaterializedViewSupportFeatureDetection: +class TestMaterializedViewSupportFeatureDetection: """Test PostgresMaterializedViewSupport feature detection methods.""" def test_supports_materialized_view_concurrent_refresh_pg93(self): @@ -367,7 +367,7 @@ def test_supports_materialized_view_concurrent_refresh_pg94(self): assert dialect.supports_materialized_view_concurrent_refresh() is True -class TestPostgresVacuumFeatureDetection: +class TestVacuumFeatureDetection: """Test PostgresVacuumMixin feature detection methods.""" def test_supports_parallel_vacuum_pg12(self): @@ -523,7 +523,7 @@ def test_cluster_support_is_runtime_checkable(self): assert isinstance(PostgresDialect(version=(14, 0, 0)), PostgresClusterSupport) -class TestPostgresDomainFeatureDetection: +class TestDomainFeatureDetection: """Test PostgresDomainSupport feature detection methods.""" def test_domain_pg95(self): @@ -541,7 +541,7 @@ def test_domain_support_is_runtime_checkable(self): assert isinstance(PostgresDialect(version=(14, 0, 0)), PostgresDomainSupport) -class TestPostgresCollationDDLFeatureDetection: +class TestCollationDDLFeatureDetection: """Test PostgresCollationDDLSupport feature detection methods.""" def test_collation_ddl_pg95(self): @@ -579,7 +579,7 @@ def test_foreign_table_ddl_support_is_runtime_checkable(self): ) -class TestPostgresRoutineDDLFeatureDetection: +class TestRoutineDDLFeatureDetection: """Test PostgresRoutineDDLSupport feature detection methods.""" def test_routine_ddl_pg95(self): @@ -675,7 +675,7 @@ def test_baseline_19(self): assert d.supports_publication() is True -class TestPostgresTypeDomainProtocols: +class TestTypeDomainProtocols: def test_protocol_derivation_and_runtime_support(self): # Core split the former umbrella protocols into one per statement # expression, so a backend protocol derives from each it restates. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py index 5c57a253..efcce237 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py """ Test SQLFunctionSupport protocol implementation for PostgreSQL dialect. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py index 377d6c46..38a48760 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py """ Tests for PostgreSQL dialect SQL injection security fixes. @@ -264,7 +264,7 @@ def test_exclude_constraint_rejects_raw_where(dialect): dialect.format_table_exclude_constraint(constraint.branch) -class TestPostgresEnumSecurity: +class TestEnumSecurity: """Tests for CREATE TYPE ENUM value escaping (fix for SQL injection risk).""" def test_create_type_enum_values_escaped(self, dialect): @@ -290,7 +290,7 @@ def test_create_type_enum_sql_injection_blocked(self, dialect): assert "AS ENUM" in sql -class TestPostgresStoredProcedureNameSecurity: +class TestStoredProcedureNameSecurity: """Tests for stored procedure names using format_identifier.""" def test_create_procedure_name_quoted(self, dialect): @@ -332,7 +332,7 @@ def test_procedure_with_schema_quoted(self, dialect): assert '"my_procedure"' in sql -class TestPostgresPartialIndexWhereClauseSecurity: +class TestPartialIndexWhereClauseSecurity: """Tests for partial index WHERE clause (ToSQLProtocol support).""" def test_create_index_with_string_where_clause(self, dialect): @@ -392,7 +392,7 @@ def to_sql(self): assert params == ("active",) -class TestPostgresTriggerFunctionNameSecurity: +class TestTriggerFunctionNameSecurity: """Tests for trigger function name using format_identifier.""" def test_trigger_function_name_quoted(self, dialect): @@ -438,7 +438,7 @@ def test_trigger_function_name_special_chars_quoted(self, dialect): assert '"Function With Spaces"' in sql -class TestPostgresExtendedStatisticsNameSecurity: +class TestExtendedStatisticsNameSecurity: """Tests for extended statistics names using format_identifier.""" def test_create_statistics_name_quoted(self, dialect): @@ -643,7 +643,7 @@ def test_hstore_operator_not_double_escaped(): # Try to find the file relative to the repo root import os for candidate in [ - os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..", "..", hstore_path), + os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..", "..", "..", hstore_path), os.path.join(os.getcwd(), hstore_path), ]: candidate = os.path.normpath(candidate) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py similarity index 90% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py index d30a5584..3d681313 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py """PostgreSQL DQL capability tests: WITH TIES (PG13+) and NULLS ordering.""" import pytest diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py similarity index 94% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py index 5ff2a4e5..717f7aa8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py """Tests for DROP TABLE ... CASCADE/RESTRICT rendering on PostgreSQL. PostgreSQL declares full SQL-standard CASCADE/RESTRICT support; the generic @@ -19,7 +19,7 @@ def dialect(): return PostgresDialect(version=(15, 0, 0)) -class TestPostgresDropTableCascade: +class TestDropTableCascade: def test_capability_switches(self, dialect): assert dialect.supports_drop_table_cascade() is True assert dialect.supports_drop_table_restrict() is True diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py index cf3b2623..4ef7e4c5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py """Unit tests for PostgreSQL function version requirements system. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py index 3b51b45a..15ecf612 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py """ Tests for PostgresDialect identifier quoting. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py index fbfd16c5..c91ad67c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py """Tests for ILIKE protocol support in PostgreSQL dialect.""" from rhosocial.activerecord.backend.expression.core import Column from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py index 2b8fb13a..e16fbb9e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py """Tests for PostgreSQL ON CONFLICT clause capability and rendering. Covers: @@ -27,7 +27,7 @@ def dialect(): return PostgresDialect(version=(15, 0, 0)) -class TestPostgresOnConflictCapabilities: +class TestOnConflictCapabilities: """Capability switch tests.""" def test_supports_upsert_pg94(self): @@ -59,7 +59,7 @@ def test_multiple_on_conflict_clauses_rejected(self, dialect): expr.to_sql() -class TestPostgresOnConflictRendering: +class TestOnConflictRendering: """SQL rendering tests for a single ON CONFLICT clause.""" def test_do_nothing(self, dialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py index 190019f9..2683e921 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py """Offline regression tests for the introspection answer shapes. Three defects used to survive because every test that touched them needed a diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py index 7ef6d340..a9fa86a7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py """The PostgreSQL expression package's kinds: what they are and how they are named. The organisation's rule (expression-kinds.md §三, expression-dialect §3 and diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py index 40e0593d..8d709155 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py """PostgreSQL materialized view DDL tests (SQL generation only, no database). Covers the regression matrix documented in diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py index 44e6ee77..60dbc716 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py """Documentation and example consistency for materialized views. Docs that drift from the implementation are a defect: the previous MV @@ -11,7 +11,7 @@ import pytest -PROJECT_ROOT = Path(__file__).resolve().parents[6] +PROJECT_ROOT = Path(__file__).resolve().parents[7] MV_DOC_PAGES = [ PROJECT_ROOT / "docs" / "en_US" / "ddl" / "materialized_view.md", PROJECT_ROOT / "docs" / "zh_CN" / "ddl" / "materialized_view.md", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py index 7e16c977..88828c43 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py """PostgreSQL materialized view introspection tests (SQL generation only). Covers the introspection half of the regression matrix documented in diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py index 69776be6..f10d86e5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py """ A statement handed the wrong kind of catalogue object must refuse, not render. @@ -52,7 +52,7 @@ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError from rhosocial.activerecord.backend.expression import objects as objects_mod -from expression_roundtrip_harness import ( +from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import ( collect_expression_classes, make_instance, ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py index 61a87d5b..f8fe2f73 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py """Tests for fail-closed PostgreSQL graph capability and formatter safeguards. SQL/PGQ was withdrawn in PostgreSQL 19 Beta 4 and shipped in no earlier diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py index 44c78727..d1820a3e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py """ Tests to verify PostgresDialect protocol conformance and protocol non-overlap. @@ -149,6 +149,7 @@ def get_postgres_protocols(): dialect_protocols.PartitionSupport, dialect_protocols.ConstraintSupport, dialect_protocols.TruncateSupport, + dialect_protocols.TransactionalDDLSupport, dialect_protocols.IntrospectionSupport, dialect_protocols.TransactionControlSupport, dialect_protocols.SQLFunctionSupport, @@ -193,7 +194,7 @@ def get_postgres_protocols(): POSTGRES_PROTOCOLS = get_postgres_protocols() -class TestPostgresDialectProtocolConformance: +class TestDialectProtocolConformance: """Assert PostgresDialect implements all protocols it declares to support.""" @pytest.fixture @@ -236,7 +237,7 @@ def get_all_generic_protocols() -> dict: return discovered -class TestPostgresDialectNegativeProtocolConformance: +class TestDialectNegativeProtocolConformance: """Assert PostgresDialect does not implement intentionally-unsupported protocols.""" @pytest.fixture @@ -481,7 +482,7 @@ def test_no_interface_overlap_between_protocols(self): ) -class TestPostgresProtocolDerivation: +class TestProtocolDerivation: """Verify PostgreSQL-specific protocols derive from their generic counterparts. This ensures that backend-specific protocols inherit the standard interface, @@ -528,7 +529,7 @@ def test_dialect_satisfies_generic_protocols_via_derivation(self): ) -class TestPostgresExpressionDialectSeparation: +class TestExpressionDialectSeparation: """Verify PostgreSQL-specific expression classes delegate to dialect for SQL generation. Expression-Dialect separation means expression classes collect parameters diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py index 124ceacb..3d65f102 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py """PostgreSQL RETURNING capability tests (incl. PG17 OLD/NEW references).""" import pytest diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py index cac415fd..d97e3371 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py """Tests for the schema capability declared on the PostgreSQL dialect. Two questions, and they are not the same one. Does the engine *have* schemas -- diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py index b031fd14..2ffc64da 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py """Tests for SetOperation and Truncate protocol support in PostgreSQL dialect.""" import pytest # noqa: F401 from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py index d85209d7..50e5a36d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py """The status-introspection nodes (SQL generation only). The status introspector used to hold the catalog SQL itself: ``execute("SELECT diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py index 192eedd8..659372ff 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py """The per-table storage trio (SQL generation and parsing only). A table's footprint is three numbers PostgreSQL keeps apart: the total, the diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py index db52d62b..4a89d514 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py """PostgreSQL version-specific feature detection tests. This module tests the version-specific feature detection methods diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/errors/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/errors/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py similarity index 94% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py index 52e8d375..34bfe02c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py """The expression tests are parallel by configuration (expression-dialect §12). An expression test builds a tree, renders it through its own dialect and diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py index 41558a21..db22c99c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py """Guard: every clause pair the PostgreSQL dialect consumes is fully spellable. The rule this file enforces (the round's rule 1/2/3/4): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py index 099364e8..d34c7b31 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py """Round-trip contract for ``PostgresCreateDomainExpression``. ``CREATE DOMAIN`` has two mutually exclusive spellings for the same list of @@ -39,7 +39,9 @@ from rhosocial.activerecord.backend.impl.postgres.expression.ddl.domain import ( PostgresCreateDomainExpression, ) -from expression_roundtrip_harness import assert_params_equal +from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import ( + assert_params_equal, +) # Deserialisation resolves a kind through the framework's registry, which ships # core and the built-in backends. A PostgreSQL class is registered by the code @@ -88,7 +90,7 @@ def _round_trip(expr, dialect): return params -class TestPostgresCreateDomainRoundTrip: +class TestCreateDomainRoundTrip: """Both spellings survive the generic get_params() round trip.""" def test_constraints_spelling_round_trips(self, dialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py index 1670cb17..19966e6c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py """Guardrail: every expression must live under the backend's expression namespace. ``BaseExpression`` subclasses render SQL, so they belong in diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py index 47e1f618..15a62486 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py """ Functional serialization coverage: every registered expression class must round-trip losslessly through all three encodings (dict / JSON string / XML). @@ -325,7 +325,7 @@ class name -- ``Literal`` the single exception, naming its fourteen value kinds network as pg_network, range as pg_range, ) -from expression_roundtrip_harness import ( +from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import ( collect_expression_classes, make_instance, register_all, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py index a0f3130b..9aad043c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py """SQL-snapshot tests for format-signature-compliant expression classes. These tests build expressions with a bare ``PostgresDialect`` (no DB diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expressions_transaction.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expressions_transaction.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expressions_transaction.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expressions_transaction.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py index 10cd7eea..83562f76 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py """SQL-snapshot tests for the pgvector similarity-search helpers. These tests build expressions with a bare ``PostgresDialect`` (no DB diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py index ef3bf622..a5397b95 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py """ Expression serialization round-trip / contract test helpers (PostgreSQL-local copy). diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py index 62a802fa..22818741 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py """ Tests for PostgreSQL Array functions. @@ -31,7 +31,7 @@ ) -class TestPostgresArrayFunctions: +class TestArrayFunctions: """Tests for PostgreSQL array functions.""" def test_array_agg(self, postgres_dialect: PostgresDialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_datetime_interval_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_datetime_interval_expressions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py index 7f47f67b..5e504978 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_datetime_interval_expressions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py @@ -1,5 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/ -# test_postgres_datetime_interval_expressions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py """Tests for PostgreSQL datetime interval expressions.""" import pytest @@ -18,7 +17,7 @@ from rhosocial.activerecord.backend.expression.types import IntegerType -class TestPostgresDateTimeIntervalExpressions: +class TestDateTimeIntervalExpressions: @pytest.mark.parametrize( "field", ["year", "month", "day", "hour", "minute", "second"], diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py index 07808478..3041f986 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py """PostgreSQL's own types, and what you can do with them. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py index f68b9bf8..3a0e6d20 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py """Unit tests for PostgreSQL extension mixins and functions. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py index 376c0476..5913bbe6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py """ Tests for PostgreSQL hstore function factories. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py index 64ddbd91..d42f7b13 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py """ Tests for PostgreSQL-specific enhanced math functions. @@ -21,7 +21,7 @@ ) -class TestPostgresMathEnhancedFunctions: +class TestMathEnhancedFunctions: """Tests for PostgreSQL enhanced math functions.""" def test_round__default(self, postgres_dialect: PostgresDialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py index 242d8677..8a8f15d6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py """ Tests for PostgreSQL Network Address functions. @@ -30,7 +30,7 @@ ) -class TestPostgresNetworkFunctions: +class TestNetworkFunctions: """Tests for PostgreSQL network functions.""" def test_inet_client_addr(self, postgres_dialect: PostgresDialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py index 98a41fee..f14f3204 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py """ Tests for PostgreSQL pgvector function factories. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py index 252210ed..e3f3ba83 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py """ Tests for PostgreSQL PostGIS function factories. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py index 6cdba6ae..da170c5b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py """ Tests for PostgreSQL Range Type Constructors. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py index 7915ca51..a8e8f794 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py """Unit tests for PostgreSQL range functions. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py index 754665d9..34818bb1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py """ Tests for PostgreSQL UUID functions. @@ -18,7 +18,7 @@ ) -class TestPostgresUUIDFunctions: +class TestUUIDFunctions: """Tests for PostgreSQL UUID functions.""" def test_uuid_generate_v1(self, postgres_dialect: PostgresDialect): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/introspection/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/introspection/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py index 2f5c93ac..13212842 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py """Unit tests for PostgreSQL address_standardizer extension functions. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py index dd3c8834..f1545bfd 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py """ Unit tests for PostgreSQL bloom extension mixin. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py index be9a93c2..11d34c57 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py """ Unit tests for PostgreSQL btree_gin extension mixin. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py similarity index 94% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py index 49bcebea..bd811c11 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py """ Unit tests for PostgreSQL btree_gist extension mixin. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py similarity index 94% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py index a595453e..81645dab 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py """ Unit tests for PostgreSQL citext extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py index 21e4c4e7..234cd39d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py """ Unit tests for PostgreSQL cube extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_alter_config.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_alter_config.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py index 6a5bd10d..d4619de7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_alter_config.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py """Tests for PostgreSQL DDL expression classes. This module tests the expression-based format methods for DDL operations, @@ -197,7 +197,7 @@ def test_verbose_false_schema(self, dialect): assert sql == 'CLUSTER "app"."orders"' -class TestPostgresAlterColumnUsingExpression: +class TestAlterColumnUsingExpression: """ALTER COLUMN ... SET DATA TYPE ... USING.""" @pytest.fixture @@ -255,7 +255,7 @@ def test_without_using_unaffected(self, dialect): assert sql == 'ALTER COLUMN "price" SET DATA TYPE NUMERIC(10,2)' -class TestPostgresAlterColumnModifierMixin: +class TestAlterColumnModifierMixin: """ADD/DROP COLUMN and DROP CONSTRAINT IF [NOT] EXISTS qualifiers.""" @pytest.fixture @@ -312,7 +312,7 @@ def test_drop_constraint_if_exists_cascade(self, dialect): assert sql == 'DROP CONSTRAINT IF EXISTS "user_email_key" CASCADE' -class TestPostgresConstraintCapabilities: +class TestConstraintCapabilities: """PostgreSQL-only constraint capability switches.""" @pytest.fixture @@ -325,7 +325,7 @@ def test_capabilities(self, dialect): assert dialect.supports_drop_constraint_if_exists() is True -class TestPostgresConstraintDeferral: +class TestConstraintDeferral: """``DEFERRABLE`` / ``INITIALLY`` is not an all-kinds grant. The ``column_constraint`` / ``table_constraint`` grammar figures draw @@ -435,7 +435,7 @@ def test_alter_constraint_enforced_splits_by_kind_and_version(self): action.to_sql() -class TestPostgresTypeDDL: +class TestTypeDDL: """CREATE/DROP TYPE capability switches and formatting.""" @pytest.fixture @@ -478,7 +478,7 @@ def test_drop_type_full(self, dialect): assert sql == 'DROP TYPE IF EXISTS "app"."color" CASCADE' -class TestPostgresConstraintEnforcement: +class TestConstraintEnforcement: def test_capability_versions(self): """The two enforcement probes are grammar gates with no kind in them. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py index cc5eb684..8ec51391 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py """Unit tests for PostgreSQL extended statistics mixin. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py index ba5e9aa4..6107c4f4 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py """ Unit tests for PostgreSQL fuzzystrmatch extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py index 35584d05..067f50c1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py """ Unit tests for PostgreSQL hypopg extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py index afc0b22c..2026a79d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py """Unit tests for PostgreSQL index mixin. Tests for: @@ -994,7 +994,7 @@ def test_alter_statistics_missing_params_raises(self): expr.to_sql() -class TestPostgresIndexMixinDirect: +class TestIndexMixinDirect: """Test PostgresIndexMixin directly (not through PostgresDialect).""" class _Host: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py index 3ecaa115..c0c37cda 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py """ Unit tests for PostgreSQL orafce extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py index 138ff103..da5a53c3 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py """ Unit tests for PostgreSQL pg_cron extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py index 8f393855..ae29e858 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py """ Unit tests for PostgreSQL pg_partman extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py similarity index 91% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py index 43ced5b7..c75c8d96 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py """ Unit tests for PostgreSQL pg_repack extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py index d05c84d4..6ce61437 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py """Unit tests for PostgreSQL pg_stat_statements extension mixin and functions.""" from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py index 26ae704d..fe9fdb24 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py """ Unit tests for PostgreSQL pg_surgery extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py similarity index 94% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py index f2516961..7ecfee56 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py """ Unit tests for PostgreSQL pg_walinspect extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py similarity index 88% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py index 9d1da526..f8eb255e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py """Unit tests for PostgreSQL pgaudit extension mixin.""" from rhosocial.activerecord.backend.impl.postgres.mixins.extensions.pgaudit import PostgresPgauditMixin diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py index b644bf98..6495eaa4 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py """ Unit tests for PostgreSQL pgcrypto extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py index 0a3a13c2..f59cbd7e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py """ Unit tests for PostgreSQL pglogical extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py index e1a65541..606fac4b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py """Unit tests for PostgreSQL Row-Level Security POLICY DDL. Tests cover: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py index a912b91e..bcb541a7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py """Unit tests for PostgreSQL stored procedure mixin. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_table.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_table.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_table.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_table.py index 5d00a29b..ca07fc28 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_table.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_table.py @@ -35,7 +35,7 @@ def test_supports_table_tablespace(self): assert PostgresDialect().supports_table_tablespace() is True -class TestPostgresTableMixinDirect: +class TestTableMixinDirect: """Test PostgresTableMixin directly (not through PostgresDialect).""" class _Host: @@ -75,7 +75,7 @@ def test_supports_table_tablespace_direct(self): assert self._TableMixin().supports_table_tablespace() is True -class TestPostgresTableDDLDeclarations: +class TestTableDDLDeclarations: @staticmethod def _expression(dialect, table="child", *, inherits=None, tablespace=None): return CreateTableStatement( diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py index ec7b9152..1a287e01 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py """ Unit tests for PostgreSQL tablefunc extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py index 5540deb9..c5be9c77 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py """Unit tests for PostgreSQL trigger mixin. Tests for: @@ -284,7 +284,7 @@ def test_drop_trigger_if_exists(self): assert "DROP TRIGGER IF EXISTS" in sql -class TestPostgresTriggerMixinDirect: +class TestTriggerMixinDirect: """Test PostgresTriggerMixin directly (not through PostgresDialect).""" class _Host: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py index 98d0a047..9d501945 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py """ Unit tests for PostgreSQL uuid-ossp extension functions. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py index 92cd37e7..9a8845c1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py """Fixture table for PostgreSQL partition syntax families. Every case is an offline description of one PostgreSQL partitioning shape: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py index ffbc82af..6f0fb85c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py """Tests for PostgreSQL DDL expression classes. This module tests the expression-based format methods for DDL operations, @@ -51,7 +51,7 @@ PostgresExtendedStatisticsMixin, # noqa: F401 ) -class TestPostgresRefreshMaterializedViewExpression: +class TestRefreshMaterializedViewExpression: """Test PostgresRefreshMaterializedViewPgStatement.""" @pytest.fixture @@ -140,7 +140,7 @@ def test_refresh_concurrently_and_no_data(self, dialect): assert params == () -class TestPostgresCommentExpression: +class TestCommentExpression: """Test PostgresCommentOnStatement.""" @pytest.fixture @@ -244,7 +244,7 @@ def test_comment_with_schema(self, dialect): assert params == ("Public users table",) -class TestPostgresPartitionedTableCreation: +class TestPartitionedTableCreation: """Test PostgreSQL CREATE TABLE ... PARTITION BY support.""" @pytest.fixture @@ -500,7 +500,7 @@ def test_child_multi_column_list_partition_clause_rejected(self, dialect): expr.to_sql() -class TestPostgresPartitionValue: +class TestPartitionValue: """Test safe PostgreSQL partition bound value formatting.""" @pytest.fixture @@ -604,7 +604,7 @@ def test_partition_value_requires_pg10(self): PostgresPartitionValue(dialect, 1).to_sql() -class TestPostgresCreatePartitionExpression: +class TestCreatePartitionExpression: """Test PostgresCreatePartitionStatement.""" @pytest.fixture @@ -957,7 +957,7 @@ def test_create_partition_requires_pg10(self): expr.to_sql() -class TestPostgresDetachPartitionExpression: +class TestDetachPartitionExpression: """Test PostgresDetachPartitionStatement.""" @pytest.fixture @@ -1049,7 +1049,7 @@ def test_detach_partition_requires_pg10(self): expr.to_sql() -class TestPostgresAttachPartitionExpression: +class TestAttachPartitionExpression: """Test PostgresAttachPartitionStatement.""" @pytest.fixture @@ -1277,7 +1277,7 @@ def test_attach_partition_requires_pg10(self): expr.to_sql() -class TestPostgresPartitionMetadataExpression: +class TestPartitionMetadataExpression: """Test PostgreSQL partition metadata query expression.""" def test_metadata_query_for_parent(self): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_objects.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_objects.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py index e64fb3e1..a41b6f96 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_objects.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py """Tests for PostgreSQL DDL expression classes. This module tests the expression-based format methods for DDL operations, @@ -107,7 +107,7 @@ _PG_ROUNDTRIP_REGISTRY.register_node(PostgresCompositeTypeDefinition) -class TestPostgresDomainExpression: +class TestDomainExpression: """CREATE / ALTER / DROP DOMAIN.""" @pytest.fixture @@ -337,7 +337,7 @@ def test_drop_domain_flags(self, dialect): expression.to_sql() -class TestPostgresTypeDDLExpressions: +class TestTypeDDLExpressions: @pytest.fixture def dialect(self): return PostgresDialect(version=(14, 0, 0)) @@ -727,7 +727,7 @@ def test_base_subscript_version_boundary(self): assert 'SUBSCRIPT = "box_subscript"' in sql -class TestPostgresCollationDDLExpression: +class TestCollationDDLExpression: """CREATE / DROP COLLATION DDL.""" @pytest.fixture @@ -855,7 +855,7 @@ def test_version_gate_96(self): PostgresDropForeignTableStatement(d, "ft").to_sql() -class TestPostgresRoutineDDLExpression: +class TestRoutineDDLExpression: """CREATE / DROP FUNCTION and AGGREGATE.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py index 9c1fa2d9..218aeda7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py """Tests for PostgreSQL-specific expression classes and format methods. This module tests the expression-based format methods for DDL/DML operations, @@ -20,7 +20,7 @@ ) -class TestPostgresVacuumExpression: +class TestVacuumExpression: """Test PostgresVacuumStatement and format_vacuum_statement.""" @pytest.fixture @@ -95,7 +95,7 @@ def test_vacuum_truncate_excludes_full(self, dialect): expr.to_sql() -class TestPostgresAnalyzeExpression: +class TestAnalyzeExpression: """Test PostgresAnalyzeStatement and format_analyze_statement.""" @pytest.fixture @@ -121,7 +121,7 @@ def test_analyze_with_columns(self, dialect): assert '("id", "name", "email")' in sql -class TestPostgresCreatePartitionExpression: +class TestCreatePartitionExpression: """Test PostgresCreatePartitionStatement and format_create_partition_statement.""" @pytest.fixture @@ -247,7 +247,7 @@ def test_partition_with_tablespace(self, dialect): assert 'TABLESPACE "fast_storage"' in sql -class TestPostgresDetachPartitionExpression: +class TestDetachPartitionExpression: """Test PostgresDetachPartitionStatement and format_detach_partition_statement.""" @pytest.fixture @@ -302,7 +302,7 @@ def test_finalize_requires_concurrently(self, dialect): expr.to_sql() -class TestPostgresAttachPartitionExpression: +class TestAttachPartitionExpression: """Test PostgresAttachPartitionStatement and format_attach_partition_statement.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py index f20971b2..80fb689f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py """Unit tests for PostgreSQL partition plans and maintenance planning. No server is required. Plan generation, naming, DDL rendering and catalog diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py index 1ab7ab7b..bc18c2fe 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py """Offline matrix for PostgreSQL partition syntax families. Each test consumes ``partition_syntax_case`` from @@ -32,7 +32,7 @@ PartitionRetention, PartitionValidator, ) -from partition_syntax_fixtures import ( # noqa: F401 (fixture re-export) +from rhosocial.activerecord_postgres_test.feature.backend.construct.statements.partition_syntax_fixtures import ( # noqa: F401 (fixture re-export) PartitionSyntaxCase, partition_syntax_case as _matrix_case, ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py index 5448b8f0..9e645163 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py """Tests for PostgreSQL COPY and native REPACK expressions and APIs.""" from contextlib import contextmanager diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py index d7f236e7..4caef929 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py """The PostgreSQL ``SET CONSTRAINTS`` statement node (SQL generation only). ``defer_constraint`` used to spell the statement at the call site with an diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py index 92105126..2c032b4d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py """Offline adapter round-trip coverage for the PostgreSQL backend.""" import uuid from decimal import Decimal diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py index 138c63cb..7c242757 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py """ Unit tests for PostgreSQL bit string types. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py index 30de4844..731bb219 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py """PostgreSQL's column-type table, and the one entry it refuses. The protocol's obligation on a backend is three things diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_core_type_mappings.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_core_type_mappings.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_core_type_mappings.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_core_type_mappings.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py index 90e19354..6291775e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py """Pure-function tests for PostgreSQL DataType formatting and parsing. These tests exercise ``PostgresTypeFormatSupportMixin`` (the diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py index 7818c75c..9f3ea826 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py """Unit tests for PostgreSQL ENUM types. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py index 70bbaa5b..1c776605 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py """Tests for PostgreSQL-specific DataType subclasses (pure, no DB). Covers the base classes each PostgreSQL type is anchored to, equality and @@ -36,7 +36,7 @@ ) -class TestPostgresTypesAreAnchoredToCoreConcepts: +class TestTypesAreAnchoredToCoreConcepts: """A backend type that says "I am this concept" must be that concept. Without this, ``isinstance(col.data_type, IntegerType)`` is false for a diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py index 44a7a457..d20bf2cf 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py """ Unit tests for PostgreSQL geometry types. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py index fbe3c3f5..bac6c186 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py """Unit tests for PostgreSQL hstore type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py index 94551e3a..00b5aceb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py """ Unit tests for PostgreSQL jsonpath type support. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py index bef74dd9..ba0f4be9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py """Value literals on PostgreSQL: binding and the three tier-2 spellings. Core collapsed the twelve typed-value classes into one ``Literal`` node diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py index 9865183d..f3832b8b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py """Unit tests for PostgreSQL pg_lsn type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py index f32ab682..cbbe4e92 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py """Unit tests for PostgreSQL MACADDR8 type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py index be49b29a..ad00a6ad 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py """Unit tests for PostgreSQL MONEY type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py index f1bc7d10..b5e9de96 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py """Unit tests for PostgreSQL OID types. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py index 4af6d2e0..ce65a5fe 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py """Unit tests for PostgreSQL pgvector type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py index eb14ce0e..a9bf03e1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py """Unit tests for PostgreSQL PostGIS geometry type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py index 79a4464d..be187cae 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py """ Unit tests for PostgreSQL range types. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py index 9bd78fef..ba4247bf 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py """ Unit tests for PostgreSQL text search types. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py index 54685e9c..3f418509 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py """Unit tests for PostgreSQL type casting functionality. Tests for: @@ -137,7 +137,7 @@ def test_cast_expression_supports_arithmetic(self): assert params == (1.1,) -class TestPostgresDialectFormatCast: +class TestDialectFormatCast: """Tests for PostgreSQL dialect format_cast_expression method.""" def setup_method(self): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py index a784aaf8..dfbe69de 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py """PostgreSQL type compatibility tests. This module tests the extended type compatibility checking diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py index 38188f8d..46ef8de4 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py """Tests for the formalised core DataType protocol conformance. Verifies: @@ -678,7 +678,7 @@ def registry(self): import importlib.util from pathlib import Path - path = Path(__file__).resolve().parent.parent / ( + path = Path(__file__).resolve().parent.parent / "expression" / ( "test_expression_roundtrip_all.py" ) spec = importlib.util.spec_from_file_location("postgres_rt_registry", path) @@ -689,7 +689,7 @@ def registry(self): return registry def test_every_rendered_type_parses_back_coherently(self, dialect, registry): - from expression_roundtrip_harness import ( + from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import ( parse_roundtrip_failures, ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py index 1b2bd676..f540d19d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py """Unit tests for PostgreSQL UUID type adapter. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py index dc8df4ed..9d376518 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py """UUID value expressions on PostgreSQL. PostgreSQL has two routes to a generated UUID — the built-in diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py index 66511538..b376e140 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py """Unit tests for PostgreSQL XML type. Tests for: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py similarity index 88% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py index 837afc53..ac2d13bf 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py """Guard against syntax/API drift in the runnable examples. Every script under ``examples/`` must at least compile. This test runs @@ -9,10 +9,8 @@ import py_compile from pathlib import Path -import pytest - EXAMPLES_ROOT = ( - Path(__file__).resolve().parents[5] + Path(__file__).resolve().parents[6] / "src" / "rhosocial" / "activerecord" / "backend" / "impl" / "postgres" / "examples" ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_async_support.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_support.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_async_support.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py index d0e85429..293158be 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py @@ -1,9 +1,10 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py """ Test fixtures for PostgreSQL named connection tests. """ import types from unittest.mock import MagicMock + import pytest diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py similarity index 92% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py index 029ebd28..1b55ed8e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py """ Example named connections for PostgreSQL testing. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py index 4c685b42..98b6d593 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py """ Tests for PostgreSQL backend CLI. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py index fccee4ec..cb5f50d1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py """Offline tests for ``resolve_connection_config_from_args`` (SSL mapping, etc.).""" import argparse diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_named_connection_cli.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_named_connection_cli.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py index 3ae58da7..85c7be36 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_named_connection_cli.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_cli.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py """ Tests for PostgreSQL CLI parameter resolution. @@ -35,7 +35,7 @@ def __init__( self.connection_params = connection_params or [] -class TestPostgresConnectionConfigPriority: +class TestConnectionConfigPriority: """Test connection config resolution priority for PostgreSQL CLI.""" def test_default_values(self): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py similarity index 92% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py index 8b5f912d..e4a06244 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py """ Tests for PostgreSQL named connection resolver. @@ -27,7 +27,7 @@ from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig -class TestPostgresNamedConnectionResolverUnit: +class TestNamedConnectionResolverUnit: """Unit tests for NamedConnectionResolver with PostgreSQL backend.""" def test_resolve_postgres_config(self): @@ -117,13 +117,13 @@ def prod_db(): assert "prod_db" in names -class TestPostgresNamedConnectionsIntegration: +class TestNamedConnectionsIntegration: """Integration tests using actual example_connections module.""" def test_postgres_18_connection(self): """Test resolving the postgres_18 named connection.""" config = resolve_named_connection( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18", + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18", {}, ) assert isinstance(config, PostgresConnectionConfig) @@ -135,7 +135,7 @@ def test_postgres_18_connection(self): def test_postgres_18_with_custom_database(self): """Test resolving postgres_18 with custom database parameter.""" config = resolve_named_connection( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18", + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18", {"database": "my_app"}, ) assert isinstance(config, PostgresConnectionConfig) @@ -144,7 +144,7 @@ def test_postgres_18_with_custom_database(self): def test_postgres_18_with_pool(self): """Test resolving postgres_18_with_pool named connection.""" config = resolve_named_connection( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18_with_pool", + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18_with_pool", {}, ) assert isinstance(config, PostgresConnectionConfig) @@ -153,7 +153,7 @@ def test_postgres_18_with_pool(self): def test_postgres_18_with_custom_pool_size(self): """Test resolving postgres_18_with_pool with custom pool_size.""" config = resolve_named_connection( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18_with_pool", + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18_with_pool", {"pool_size": "10"}, ) assert isinstance(config, PostgresConnectionConfig) @@ -162,7 +162,7 @@ def test_postgres_18_with_custom_pool_size(self): def test_postgres_18_readonly(self): """Test resolving postgres_18_readonly named connection.""" config = resolve_named_connection( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18_readonly", + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18_readonly", {}, ) assert isinstance(config, PostgresConnectionConfig) @@ -171,7 +171,7 @@ def test_postgres_18_readonly(self): def test_list_example_connections(self): """Test listing connections in example_connections module.""" connections = list_named_connections_in_module( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections" + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections" ) names = [c["name"] for c in connections] assert "postgres_18" in names @@ -181,7 +181,7 @@ def test_list_example_connections(self): def test_describe_postgres_18(self): """Test describing the postgres_18 connection.""" resolver = NamedConnectionResolver( - "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18" + "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18" ).load() info = resolver.describe() assert info["is_class"] is False diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py index 9533d015..4a6d5aa3 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py """ PostgreSQL advisory lock tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py index 64511089..5fa7d124 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py """ Test for ConcurrencyAware protocol implementation in PostgreSQL backend. @@ -10,7 +10,7 @@ from rhosocial.activerecord.backend.protocols import ConcurrencyAware, ConcurrencyHint -class TestPostgresConcurrencyAware: +class TestConcurrencyAware: """Test ConcurrencyAware protocol implementation for PostgreSQL backend.""" def test_postgres_backend_implements_protocol(self, postgres_backend_single): @@ -41,7 +41,7 @@ def test_postgres_concurrency_hint_returns_hint_object(self, postgres_backend_si assert isinstance(hint, ConcurrencyHint) -class TestAsyncPostgresConcurrencyAware: +class TestAsyncConcurrencyAware: """Test ConcurrencyAware protocol implementation for async PostgreSQL backend.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_initialization.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_backend_initialization.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_initialization.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_backend_initialization.py index 8e1db137..a3a0ac9b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_initialization.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_backend_initialization.py @@ -10,7 +10,7 @@ ) -class TestPostgresBackendInitialization: +class TestBackendInitialization: def test_sync_backend_builds_default_config_from_kwargs(self): backend = PostgresBackend(database="app_db", username="app_user", application_name="tests") diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_config.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_config.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_config.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_config.py index defa213f..e764340c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_config.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_config.py @@ -232,7 +232,7 @@ def test_custom_values(self): assert mixin.enable_type_compatibility_warnings is False -class TestPostgresConnectionConfigTypeAdapter: +class TestConnectionConfigTypeAdapter: """Test PostgresConnectionConfig with type adapter settings.""" def test_config_default_type_adapter_settings(self): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py index e1082eaa..78905731 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py """ Unit tests for PostgresConnectionConfig autocommit option. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py index 33580f3b..75ca6e0e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py """ Connection Resilience Tests diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py index c174b2ce..fc04c0f7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py """ PostgreSQL cursor result set pollution tests. @@ -16,7 +16,7 @@ pytestmark = [pytest.mark.feature, pytest.mark.backend] -class TestPostgresCursorPollution: +class TestCursorPollution: """Cursor pollution: sync PostgreSQL backend.""" def test_get_server_version_then_query(self, postgres_backend): @@ -77,7 +77,7 @@ def test_high_frequency_version_query_cycle(self, postgres_backend): logger.info("PostgreSQL high-frequency version query cycle 200 iterations passed") -class TestAsyncPostgresCursorPollution: +class TestAsyncCursorPollution: """Cursor pollution: async PostgreSQL backend.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py similarity index 90% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py index dfcc03dc..e2033b16 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py """ PostgreSQL backend dialect tests using real database connection. @@ -9,7 +9,7 @@ import pytest_asyncio # noqa: F401 -class TestPostgreSQLDialectBackend: +class TestDialect: """Synchronous dialect tests for PostgreSQL backend.""" def test_format_identifier(self, postgres_backend): @@ -32,7 +32,7 @@ def test_quote_parameter(self, postgres_backend): assert "$1" in result_sql -class TestAsyncPostgreSQLDialectBackend: +class TestAsyncDialect: """Asynchronous dialect tests for PostgreSQL backend.""" async def test_async_format_identifier(self, async_postgres_backend): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py index 106db47e..79efb913 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py """Regression tests: SSL/TLS config must actually reach ``psycopg.connect()``. The config exposes libpq keyword names (``sslmode``/``sslcert``/``sslkey``/ diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py similarity index 90% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py index 51adb382..6897c053 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py import pytest import pytest_asyncio # noqa: F401 @@ -6,7 +6,7 @@ from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend -class TestPostgresVersion: +class TestVersion: """Tests for server version retrieval against a live database.""" def test_get_version_parsing(self, postgres_backend: PostgresBackend): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_column_mapping_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_column_mapping_backend.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_column_mapping_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend_async.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_column_mapping_backend.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py index d0d9a702..dd50f2e9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py """ PostgreSQL backend CRUD tests using real database connection. @@ -10,7 +10,7 @@ from decimal import Decimal -class TestPostgreSQLCRUDBackend: +class TestCRUD: """Synchronous CRUD tests for PostgreSQL backend.""" @pytest.fixture @@ -124,7 +124,7 @@ def test_fetch_none(self, postgres_backend, test_table): assert row is None -class TestAsyncPostgreSQLCRUDBackend: +class TestAsyncCRUD: """Asynchronous CRUD tests for PostgreSQL backend.""" @pytest_asyncio.fixture diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py index 6d57f119..30801a47 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py from datetime import datetime import pytest diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_column/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_column/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_constraint/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_constraint/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_index/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_index/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py index 6512bded..af25e9c7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py """ Tests for PostgreSQL schema namespace support. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py index f585d068..32851494 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py """Fixtures for PostgreSQL materialized view integration tests.""" import pytest @@ -142,4 +142,3 @@ def _create(view=None, query=None, **kwargs): return expression return _create - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py index 098c5bfc..10f88fff 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py """PostgreSQL materialized view integration tests (require a live server). Covers the server-behaviour half of the regression matrix documented in diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py index b374f7a7..8fc3d1d1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py """ Tests for PostgreSQL VIEW and MATERIALIZED VIEW functionality with actual database execution. @@ -126,7 +126,7 @@ def postgres_view_backend(postgres_backend): options=ExecutionOptions(stmt_type=StatementType.DDL)) -class TestPostgresViewExecution: +class TestViewExecution: """Tests for CREATE VIEW and DROP VIEW with actual execution.""" def test_create_view_basic(self, postgres_view_backend): @@ -313,7 +313,7 @@ def test_drop_view_cascade(self, postgres_view_backend): assert result is not None -class TestPostgresMaterializedViewExecution: +class TestMaterializedViewExecution: """Tests for CREATE MATERIALIZED VIEW and related operations.""" def test_create_materialized_view_basic(self, postgres_view_backend): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py index bd0a032c..959d1a53 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py """ PostgreSQL execute_many tests for batch operations. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py index f6809037..f97c345d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py """Live PostgreSQL COPY and REPACK integration tests.""" import pytest diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py similarity index 93% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py index f215773e..db6cf264 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py """PostgreSQL rendering tests for model-bound TRUNCATE expressions.""" from rhosocial.activerecord.backend.expression.objects import Table diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py index 650369c4..604ec08d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py """PostgreSQL driver error mapping unit tests. These tests instantiate psycopg exception classes and drive the backend's diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py similarity index 77% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py index 66d3dab7..20f108ac 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py """Run the shared error taxonomy contract against this backend. The testsuite module imports only the core taxonomy, so no PostgreSQL diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py index ec48f4be..42556e77 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py """PostgreSQL execute-phase error contract tests. No PostgreSQL server is required: the tests instantiate unconnected backends diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/fulltext_spatial/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/fulltext_spatial/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_functions_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_functions_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_seconds_between.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_seconds_between.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py index c921f787..488b8c57 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_seconds_between.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py @@ -1,5 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/ -# test_postgres_seconds_between.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py """Signed, fractional seconds between two instants on PostgreSQL. What matters here is what a calendar-component sum gets wrong: the sign, @@ -72,7 +71,7 @@ def _seconds_query(dialect) -> QueryStatement: ) -class TestPostgresSecondsBetweenExpression: +class TestSecondsBetweenExpression: """The SQL PostgreSQL renders for the node.""" def test_columns(self, postgres_dialect): @@ -152,7 +151,7 @@ def test_query_integration(self, postgres_dialect): assert params == () -class TestSyncPostgresSecondsBetweenExecution: +class TestSyncSecondsBetweenExecution: """The value the PostgreSQL spelling actually produces.""" def test_signed_fractional_semantics(self, postgres_backend_single): @@ -172,7 +171,7 @@ def test_signed_fractional_semantics(self, postgres_backend_single): backend.execute(_CLEANUP) -class TestAsyncPostgresSecondsBetweenExecution: +class TestAsyncSecondsBetweenExecution: """The same value asked through the async backend.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py index 11b4e784..fd6fd081 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py """ Pytest fixtures for PostgreSQL introspection tests. @@ -300,4 +300,4 @@ async def async_backend_with_sequence(async_postgres_backend): async_postgres_backend.introspector.clear_cache() await _async_execute_sql_list(async_postgres_backend, _CLEANUP_SEQUENCE_SQL) except Exception: - pass + pass \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py index 7f2ea667..30880ddd 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py """ Tests for basic PostgreSQL introspection functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py index fc529be5..5faa527c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py """ Tests for PostgreSQL introspection caching functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py index c5b91259..a7dbc1f3 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py # noqa: E501 """Offline gates on the introspect types and their capability switches. The CLI advertises one type per catalogue family, and a type is only offered diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py index 2c0e5944..8da12197 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py """Offline tests for what ``NAME`` means to each introspect type. A type either answers for one catalogue object or lists a family. The ones diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py index 282a3b48..3984123b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py """ Black-box CLI tests for the types that answer for a recognised server object: ``views``, ``materialized-views``, ``sequences`` and ``extensions``. @@ -22,7 +22,7 @@ from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend from rhosocial.activerecord.backend.impl.postgres.cli.introspect import INTROSPECT_TYPES from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig -from providers.scenarios import SCENARIO_MAP, get_scenario_raw +from support.postgres import SCENARIO_MAP, get_scenario_raw # The CLI runs its async handler inside ``asyncio.run``, which on Windows # builds the ProactorEventLoop psycopg refuses to work with. That is the diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py index 70aefb5f..e7eb2972 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py """ Tests for PostgreSQL column introspection functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py index 2b6320be..df3a78eb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py # noqa: E501 """Offline tests for the catalogue families added for introspection coverage. The statements are rendered trees and the parsers are pure Python, so diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py index ff857d04..d0e6e09d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py """The data-profile family, measured against a real server. Rendering these statements proves only that they are well-formed. What needs diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py index 922e8a99..0e39cb80 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py """Offline tests for ``default_schema`` config-aware resolution. Both introspection stacks gained config-aware default-schema resolution: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_family_census.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_family_census.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_family_census.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_family_census.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py index 2ffa8430..4400b0e8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py """ Tests for PostgreSQL foreign key introspection functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py index df558dc4..548df2d4 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py """ Tests for PostgreSQL index introspection functionality. @@ -225,7 +225,7 @@ def test_primary_key_detection_in_indexes(self, backend_with_tables): assert pk_indexes[0].name == "users_pkey" -class TestPostgreSQLSpecificIndexTypes: +class TestSpecificIndexTypes: """Tests for PostgreSQL-specific index types.""" def test_unique_index(self, backend_with_tables): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py index 384b556c..0e48b2d4 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py """The provenance of a profile, and the default both twins offer. ``ProfileSource`` is core's closed set for where a profile number came from. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py index e6a369bb..bb7b3190 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py """ Tests for PostgreSQL sequence, materialized view and extension introspection. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py index 2fa48649..d1db167f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py """ Tests for PostgreSQL table introspection functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py index ed0137a7..19874ccb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py """ Tests for PostgreSQL trigger introspection functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py index c16cf586..366c666f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py """Unused-indexes listing: statement shape and live execution. The family reads two catalog relations that answer two different questions: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py index 731bcf23..442cf944 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py """ Tests for PostgreSQL view introspection functionality. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py index a3da7481..1abcb53b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py """ Tests for PostgreSQL status introspector. @@ -28,7 +28,7 @@ ) -class TestPostgreSQLStatusIntrospector: +class TestStatusIntrospector: """Tests for synchronous PostgreSQL status introspector.""" def test_get_overview(self, postgres_backend_single): @@ -253,7 +253,7 @@ def test_status_item_readonly_flag(self, postgres_backend_single): assert port_item.is_readonly is True -class TestPostgreSQLStatusIntrospectorMixin: +class TestStatusIntrospectorMixin: """Tests for PostgreSQLStatusIntrospectorMixin helper methods.""" def test_parse_setting_value_int(self, postgres_backend_single): @@ -358,7 +358,7 @@ def test_security_category_items(self, postgres_backend_single): assert item.category == StatusCategory.SECURITY -class TestAsyncPostgreSQLStatusIntrospector: +class TestAsyncStatusIntrospector: """Tests for asynchronous PostgreSQL status introspector.""" @pytest.mark.asyncio @@ -553,7 +553,7 @@ async def test_status_item_readonly_flag(self, async_postgres_backend_single): assert port_item.is_readonly is True -class TestAsyncPostgreSQLStatusIntrospectorMixin: +class TestAsyncStatusIntrospectorMixin: """Tests for async PostgreSQLStatusIntrospectorMixin helper methods.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py index 396b2c24..b608c421 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py """Column qualifier resolution under JOINs (regression tests). History: the query layer used to force ``alias=alias or table_name`` on every diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py index 16641483..85c1f672 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py """JSON path rendering modes on PostgreSQL. ``format_json_expression`` overrode the core dispatch entry point and ignored @@ -59,7 +59,7 @@ from rhosocial.activerecord.backend.options import ExecutionOptions from rhosocial.activerecord.backend.schema import StatementType -from providers.scenarios import get_enabled_scenarios, get_scenario +from support.postgres import get_enabled_scenarios, get_scenario #: A SELECT, so the backend reads the result set back into ``.data``. DQL = ExecutionOptions(stmt_type=StatementType.DQL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_advanced_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_advanced_operations.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_advanced_operations.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_advanced_operations.py index 7d383f51..f59f655d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_advanced_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_advanced_operations.py @@ -254,7 +254,7 @@ async def async_postgres_range_partition_environment(async_postgres_backend): await _async_drop_advanced_tables(async_postgres_backend) -class TestPostgreSQLAdvancedPartitionOperations: +class TestAdvancedPartitionOperations: """Synchronous advanced PostgreSQL partition behavior tests.""" def test_list_partition_routes_rows_and_reports_metadata(self, postgres_backend): @@ -513,7 +513,7 @@ def test_concurrent_detach_executes_or_reports_environment_limit( assert RANGE_JAN not in {row["name"] for row in metadata} -class TestAsyncPostgreSQLAdvancedPartitionOperations: +class TestAsyncAdvancedPartitionOperations: """Asynchronous advanced PostgreSQL partition behavior tests.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py index 9d4c6824..eaef5872 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py """PostgreSQL EXPLAIN tests for partitioned tables.""" from __future__ import annotations @@ -275,7 +275,7 @@ def _combined_plan_text(result: PostgresExplainResult) -> str: return "\n".join(lines) -class TestPostgresPartitionExplain: +class TestPartitionExplain: """Synchronous EXPLAIN tests for PostgreSQL partition pruning.""" def test_explain_partition_pruning_on_range_predicate( @@ -360,7 +360,7 @@ def test_explain_full_scan_returns_rows( assert len(result.raw_rows) > 0 -class TestAsyncPostgresPartitionExplain: +class TestAsyncPartitionExplain: """Asynchronous EXPLAIN tests for PostgreSQL partition pruning.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py index 72525dfe..3a562a4f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py """Live PostgreSQL tests for multi-level, heterogeneous partitioning. The tree under test is PostgreSQL's own capability, not a lowest-common- @@ -249,7 +249,7 @@ def _assert_primary_key(backend, table, expected_columns): assert column in definition -class TestPostgresPartitionMultilevel: +class TestPartitionMultilevel: """Synchronous live tests for a heterogeneous two-level tree.""" @pytest.fixture @@ -442,7 +442,7 @@ def test_drop_branch_removes_one_branch_and_ensure_rebuilds_it( _assert_tree(rebuilt) -class TestAsyncPostgresPartitionMultilevel: +class TestAsyncPartitionMultilevel: """Asynchronous live tests; method names mirror the sync class.""" @pytest_asyncio.fixture diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py index 1396cd6a..59fe7b09 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py """Real PostgreSQL partition operation tests. These tests execute against the configured PostgreSQL scenarios. They cover @@ -704,7 +704,7 @@ async def async_pg_partman_table(async_postgres_backend_single): await async_postgres_backend_single.execute(sql, params) -class TestPostgreSQLPartitionOperations: +class TestPartitionOperations: """Synchronous real backend tests for common partition operations.""" def test_partition_routing_and_pruning_metadata(self, postgres_backend, partitioned_event_table): @@ -908,7 +908,7 @@ def test_truncate_partition_keeps_partition_available(self, postgres_backend, pa assert count == 1 -class TestAsyncPostgreSQLPartitionOperations: +class TestAsyncPartitionOperations: """Asynchronous real backend tests for common partition operations.""" @pytest.mark.asyncio @@ -1136,7 +1136,7 @@ async def test_truncate_partition_keeps_partition_available( assert count == 1 -class TestPostgreSQLProductionTimePartitionOperations: +class TestProductionTimePartitionOperations: """Synchronous production-style time partition operation scenarios.""" def test_initial_year_partition_uses_microsecond_boundaries( @@ -1373,7 +1373,7 @@ def test_detach_expired_year_partition_for_cold_archive( assert parent_count == 2 -class TestAsyncPostgreSQLProductionTimePartitionOperations: +class TestAsyncProductionTimePartitionOperations: """Asynchronous production-style time partition operation scenarios.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py index 407ac6d0..f3b0e27b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py # noqa: E501 """Execution confirmation for the master probes this backend declares. Rendering is not execution: the probe answers below are confirmed against the diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py index d133a64d..e8e1389b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py # noqa: E501 """ Integration tests for PostgreSQL dialect SQL injection security fixes. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/address_standardizer/test_address_standardizer_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/address_standardizer/test_address_standardizer_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/bloom/test_bloom_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/bloom/test_bloom_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py index 1401b708..e8851daa 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py # noqa: E501 """Integration tests for PostgreSQL btree_gin extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py index af5a59b9..55462e79 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py # noqa: E501 """Integration tests for PostgreSQL btree_gist extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py index 84f71fb4..cef95d1e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py # noqa: E501 """Integration tests for PostgreSQL citext extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py index 95ef700d..25c63938 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py """Integration tests for PostgreSQL cube extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py index 233771af..2a459030 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py """ PostgreSQL extension DDL expression tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py index a965121e..beb14d57 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py # noqa: E501 """Integration tests for the earthdistance extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py index efee69fe..aa223862 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py # noqa: E501 """ Integration tests for PostgreSQL fuzzystrmatch extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py index 788034f4..19bad74c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py # noqa: E501 """Integration tests for PostgreSQL hstore extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py index bdcf4bf9..c6324b48 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py # noqa: E501 """Integration tests for the hypopg extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py index 2c0ca8bd..c25e3750 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py # noqa: E501 """Integration tests for PostgreSQL intarray extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py index 3e74ee20..48bc12be 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py """Integration tests for PostgreSQL ltree extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/orafce/test_orafce_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/orafce/test_orafce_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py index 6ae999c7..ead08c6d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py # noqa: E501 """Integration tests for the pg_cron extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py similarity index 96% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py index f0c36cce..11c8ab04 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py # noqa: E501 """Integration tests for the pg_partman extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py index 38703d16..454a1d67 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py # noqa: E501 """Integration tests for the pg_repack extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py index e9a27ecf..33e83cb9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py # noqa: E501 """Integration tests for PostgreSQL pg_stat_statements extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py index eb4b87fb..c901cf62 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py # noqa: E501 """Integration tests for the pg_surgery extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py index 16a9abf0..a84be203 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py # noqa: E501 """ Integration tests for PostgreSQL pg_trgm extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py index 1a2cb04c..afda6f7d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py # noqa: E501 """Integration tests for the pg_walinspect extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py index e67bcd24..40ef2fc1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py # noqa: E501 """Integration tests for the pgaudit extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py index 53c9a5b6..c8f08914 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py # noqa: E501 """ Integration tests for PostgreSQL pgcrypto extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py index adf62c1c..433b3e18 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py # noqa: E501 """Integration tests for the pglogical extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgrouting_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgrouting/test_pgrouting_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgrouting_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgrouting/test_pgrouting_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgvector_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgvector/test_pgvector_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgvector_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgvector/test_pgvector_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py index cbec0d3d..1a4479e8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py # noqa: E501 """Integration tests for the PostGIS extension. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_raster_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis_raster/test_postgis_raster_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_raster_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis_raster/test_postgis_raster_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py index 504986ba..cb274a4d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py # noqa: E501 """ Integration tests for PostgreSQL tablefunc extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py index e0313475..ccb740c6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py # noqa: E501 """Integration tests for PostgreSQL uuid-ossp extension with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py index 49929f50..5a72d5d8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py # noqa: E501 """ Integration tests for PostgreSQL bit string types with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py index 05bad350..f4ebb6b1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py """Type conversion against a live PostgreSQL, one case per type. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/enum/test_enum_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/enum/test_enum_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py index cc7f349d..58b30326 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py # noqa: E501 """The extension type operations, executed. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py index 71b62791..0256e227 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py # noqa: E501 """Live answers for the tier-2 literal spellings, on the scenario servers. The rendering half of this question lives in diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/money/test_money_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/money/test_money_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_network_address_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_network_address_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/oid/test_oid_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/oid/test_oid_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py index e28bc9e2..b392a9ba 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py # noqa: E501 """ Integration tests for PostgreSQL range types with real database. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/xml/test_xml_integration.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_integration.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/xml/test_xml_integration.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py index 4b37199e..1fafff3c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py """ Integration tests for PostgresBackend.explain() and AsyncPostgresBackend.explain(). diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_datetime_interval_explain_examples.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_datetime_interval_explain_examples.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py index d9b6d345..19fe813b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_datetime_interval_explain_examples.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py @@ -1,5 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/ -# test_postgres_datetime_interval_explain_examples.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py """PostgreSQL EXPLAIN examples for datetime interval expressions and indexes.""" from decimal import Decimal @@ -169,7 +168,7 @@ def _assert_temporal_rows(rows): assert round(float(rows[0]["duration_minutes"])) == 30 -class TestSyncPostgresDateTimeIntervalExplainExamples: +class TestSyncDateTimeIntervalExplainExamples: def test_created_at_range_explain_returns_temporal_plan( self, temporal_indexed_backend ): @@ -244,7 +243,7 @@ def test_datetime_interval_expressions_work_with_indexed_filter( _assert_temporal_rows(query_result.data) -class TestAsyncPostgresDateTimeIntervalExplainExamples: +class TestAsyncDateTimeIntervalExplainExamples: @pytest.mark.asyncio async def test_datetime_range_index_is_available_when_seqscan_disabled( self, async_temporal_indexed_backend diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py index 75d8dc21..1e21cfaa 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py """Capability-gated SQL/PGQ integration scenarios. These scenarios need a live server that actually implements SQL/PGQ. That was diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py index ae05ead1..351f2288 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py """ Recursive CTE graph traversal tests — PGQ quantified path alternative. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_row_level_locks.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_row_level_locks.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_row_level_locks.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_row_level_locks.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/routine_domain/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/routine_domain/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py index 0363b901..87a3523b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py """Execution confirmation for PostgreSQL identity / auto-increment / SERIAL DDL. Rendering is not execution. PostgreSQL 9 renders a well-formed diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/show_admin/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/show_admin/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py index 048e8ae5..7c261d3e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py """ PostgreSQL-specific transaction tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py index a7b03ba5..b34813c6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py """ PostgreSQL advanced transaction feature tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py similarity index 95% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py index 430b1c2d..da33ea45 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py """ PostgreSQL backend transaction tests using real database connection. @@ -10,7 +10,7 @@ from decimal import Decimal -class TestPostgreSQLTransactionBackend: +class TestTransactionBackend: """Synchronous transaction tests for PostgreSQL backend.""" @pytest.fixture @@ -55,7 +55,7 @@ def test_transaction_rollback(self, postgres_backend, test_table): assert len(rows) == 0 -class TestAsyncPostgreSQLTransactionBackend: +class TestAsyncTransactionBackend: """Asynchronous transaction tests for PostgreSQL backend.""" @pytest_asyncio.fixture diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py similarity index 97% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py index 3ac01641..0a4ae460 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py import pytest import pytest_asyncio diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py index 1194d58b..8cc3fdd0 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py """ PostgreSQL transaction deferrable constraint tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py similarity index 98% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py index 4952ecf8..2d4df990 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py """ PostgreSQL transaction isolation level tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py index 6e8d10f2..e4704b4b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py """ PostgreSQL transaction access mode effect tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py similarity index 99% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py index b5dadd57..3a71ec26 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py """ PostgreSQL transaction savepoint tests. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py new file mode 100644 index 00000000..15576b53 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py +"""Use the shared ``basic/bulk_crud`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py index 8e76ce45..1c01ee58 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py @@ -9,5 +9,3 @@ ) from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py index 2a67aa45..86952bcd 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py """Bridge file for async feature.basic.bulk_crud.test_bulk_operations_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py index 1f6cb9a6..ce6d4e5e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py @@ -3,28 +3,9 @@ Pytest configuration for basic feature tests. This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. It overrides ``type_adapter_fixtures`` -so the scenario name is passed to the provider. Without this, the sync provider -always creates the ``type_adapter_tests`` table on the first registered scenario, -which collides with the async provider when both scenarios run in parallel. +available to the tests in this directory. The testsuite fixture definitions +configure each model against the directory's logical database, so no +scenario-specific override is needed here. """ -import pytest - -from rhosocial.activerecord.testsuite.feature.basic.conftest import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.basic.conftest import ( # noqa: F401 - SCENARIO_PARAMS_SYNC, - PROVIDER_KEY_SYNC, -) -from rhosocial.activerecord.testsuite.core.registry import get_provider_registry - - -@pytest.fixture(scope="function", params=SCENARIO_PARAMS_SYNC) -def type_adapter_fixtures(request): - scenario = request.param - provider_registry = get_provider_registry() - provider_class = provider_registry.get_provider(PROVIDER_KEY_SYNC) - provider = provider_class() - model = provider.setup_type_adapter_model_and_schema(scenario) - yield model - provider.cleanup_after_test(scenario) +from rhosocial.activerecord.testsuite.feature.basic.conftest import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py index b5ecbf1d..8f7e8cf3 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py @@ -12,5 +12,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py index 8d360f89..75784cbb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py """Bridge file for async feature.basic.connection.test_active_record_context_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py index c9488510..eb4e162b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py @@ -12,5 +12,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py index a826a9e8..10f67d9c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py """Bridge file for async feature.basic.connection.test_active_record_crud_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py new file mode 100644 index 00000000..99e0c967 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py @@ -0,0 +1,29 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py +"""The mapped-model fixture group this directory owns. + +The directory runs the shared ``basic`` mapped-model tests; the models they +request (``MappedUser``, ``MappedPost``, ``MappedComment``) read and write the +topic's ``users``, ``posts`` and ``comments`` tables, so the group is exactly +those three. +""" + +from rhosocial.activerecord.testsuite.feature.basic.fixtures import tables + +GROUP_TABLES = ("users", "posts", "comments") + + +def ensure_database(environment): + """Create the directory's database, or clear it when it already exists.""" + environment.reset_database() + + +def prepare(environment): + """Create the group's tables before every test.""" + for name in GROUP_TABLES: + environment.execute(tables.BASIC_TABLES[name](environment.dialect)) + + +def teardown(environment): + """Drop the group's tables after every test.""" + for name in reversed(GROUP_TABLES): + environment.execute(tables.drop_table(environment.dialect, name)) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py new file mode 100644 index 00000000..eb892392 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py @@ -0,0 +1,10 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py +""" +This module serves as a bridge to execute the generic basic mapped models tests +defined in the `rhosocial-activerecord-testsuite` package against the PostgreSQL backend. + +The fixtures those cases request (including ``mapped_models_fixtures``) come +from the shared ``basic`` topic conftest inherited from the parent directory. +""" + +from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py new file mode 100644 index 00000000..9fb037a7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py new file mode 100644 index 00000000..030a02ce --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py +"""Use the shared ``basic/crud`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.crud.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py index 1f34b0b8..c47fec31 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py @@ -3,4 +3,3 @@ Bridge file for composite PK CRUD tests from the testsuite. """ from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F403 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py index 5bf67d8f..50aa8f50 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py """Bridge file for async feature.basic.crud.test_composite_pk_crud_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py index ffc5439b..e1402383 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py @@ -28,5 +28,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py index b8ffe646..60742940 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py """Bridge file for async feature.basic.crud.test_crud_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py new file mode 100644 index 00000000..26b980e8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py +"""Use the shared ``basic/fields`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.fields.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py deleted file mode 100644 index 69e0cf80..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py +++ /dev/null @@ -1,365 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/basic/fields/test_derived_field.py -import pytest -from typing import ClassVar, Optional -from typing_extensions import Annotated - -from rhosocial.activerecord.base import DerivedField, UseColumn -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.backend.expression import ( - ArithmeticOperation, - Column, - Literal, -) - - -class TestDerivedFieldDeclaration: - - def test_derived_fields_registered(self, product_class): - assert "discounted_price" in product_class.__derived_fields__ - assert "total_value" in product_class.__derived_fields__ - - def test_descriptor_class_access(self, product_class): - assert isinstance(product_class.discounted_price, DerivedField) - - def test_derived_field_with_static_expression(self, product_class): - """Test DerivedField constructed with a pre-built expression object (non-callable path).""" - dialect = product_class.backend().dialect - static_expr = ArithmeticOperation( - dialect, "mul", Column(dialect, "price"), Literal(dialect, 2) - ) - df = DerivedField(static_expr) - resolved = df.resolve(dialect) - assert resolved is static_expr - - def test_descriptor_instance_default_none(self, product_class): - p = product_class(name="x", price=10.0, quantity=1) - assert p.discounted_price is None - assert p.total_value is None - - def test_derived_field_names_mapping(self, product_class): - names = product_class.__derived_field_names__ - df = product_class.__derived_fields__["discounted_price"] - assert names[id(df)] == "discounted_price" - - -class TestDerivedFieldQuery: - - def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - p.save() - return p - - def test_find_all_derived_true(self, product_class): - self._insert(product_class, "A", 100.0, 5) - results = product_class.find_all(derived=True) - assert len(results) == 1 - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(500.0) - - def test_find_all_derived_list_by_name(self, product_class): - self._insert(product_class, "B", 50.0, 3) - results = product_class.find_all(derived=["total_value"]) - assert len(results) == 1 - assert results[0].total_value == pytest.approx(150.0) - assert results[0].discounted_price is None - - def test_find_all_derived_list_all(self, product_class): - self._insert(product_class, "C", 200.0, 2) - results = product_class.find_all(derived=["discounted_price", "total_value"]) - assert results[0].discounted_price == pytest.approx(180.0) - assert results[0].total_value == pytest.approx(400.0) - - def test_find_one_derived(self, product_class): - p = self._insert(product_class, "D", 80.0, 4) - result = product_class.find_one(p.id, derived=True) - assert result.discounted_price == pytest.approx(72.0) - - def test_find_one_or_fail_derived(self, product_class): - p = self._insert(product_class, "D2", 80.0, 4) - result = product_class.find_one_or_fail(p.id, derived=True) - assert result.discounted_price == pytest.approx(72.0) - assert result.total_value == pytest.approx(320.0) - - def test_find_one_or_fail_derived_list(self, product_class): - p = self._insert(product_class, "D3", 80.0, 4) - result = product_class.find_one_or_fail(p.id, derived=["discounted_price", "total_value"]) - assert result.discounted_price == pytest.approx(72.0) - assert result.total_value == pytest.approx(320.0) - - def test_find_all_derived_false_default(self, product_class): - self._insert(product_class, "E", 60.0, 1) - results = product_class.find_all() - assert results[0].discounted_price is None - assert results[0].total_value is None - - def test_find_all_derived_all(self, product_class): - self._insert(product_class, "F", 100.0, 5) - results = product_class.find_all(derived="all") - assert len(results) == 1 - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(500.0) - - def test_find_one_derived_all(self, product_class): - p = self._insert(product_class, "G", 80.0, 4) - result = product_class.find_one(p.id, derived="all") - assert result.discounted_price == pytest.approx(72.0) - assert result.total_value == pytest.approx(320.0) - - def test_find_one_or_fail_derived_all(self, product_class): - p = self._insert(product_class, "H", 60.0, 3) - result = product_class.find_one_or_fail(p.id, derived="all") - assert result.discounted_price == pytest.approx(54.0) - assert result.total_value == pytest.approx(180.0) - - -class TestDerivedFieldFormA: - """Tests for Form A declaration: ClassVar[DerivedField] = DerivedField(...).""" - - def test_form_a_fields_registered(self, product_form_a_class): - assert "discounted_price" in product_form_a_class.__derived_fields__ - assert "total_value" in product_form_a_class.__derived_fields__ - - def test_form_a_query(self, product_form_a_class): - p = product_form_a_class(name="FA", price=100.0, quantity=3) - p.save() - results = product_form_a_class.find_all(derived=True) - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(300.0) - - def test_form_a_source_id_mapping(self, product_form_a_class): - df = product_form_a_class.__derived_fields__["discounted_price"] - assert df._source_id is not None - assert product_form_a_class.__derived_field_names__[df._source_id] == "discounted_price" - - -class TestDerivedFieldDictForm: - """Tests for derived=dict form.""" - - def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - p.save() - return p - - def test_derived_dict_with_lambda(self, product_class): - self._insert(product_class, "D1", 100.0, 4) - results = product_class.find_all( - derived={ - "my_discount": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.8) - ) - } - ) - assert results[0].__dict__["my_discount"] == pytest.approx(80.0) - - def test_derived_dict_with_derived_field_instance(self, product_class): - self._insert(product_class, "D2", 50.0, 2) - df = product_class.__derived_fields__["total_value"] - results = product_class.find_all( - derived={"tv": df} - ) - assert results[0].__dict__["tv"] == pytest.approx(100.0) - - - def test_derived_dict_with_expression_object(self, product_class): - self._insert(product_class, "D3", 80.0, 5) - dialect = product_class.backend().dialect - expr = ArithmeticOperation( - dialect, "mul", Column(dialect, "price"), Literal(dialect, 0.5) - ) - results = product_class.find_all( - derived={"half_price": expr} - ) - assert results[0].__dict__["half_price"] == pytest.approx(40.0) - - -class TestDerivedFieldLookupByInstance: - """Tests for derived=[DerivedField instance] form.""" - - def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - p.save() - return p - - def test_lookup_by_derived_field_instance(self, product_class): - self._insert(product_class, "L1", 200.0, 1) - df = product_class.__derived_fields__["discounted_price"] - results = product_class.find_all(derived=[df]) - assert results[0].discounted_price == pytest.approx(180.0) - - -class TestExtraDerived: - - def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - p.save() - return p - - def test_extra_derived_basic(self, product_class): - self._insert(product_class, "F", 100.0, 10) - results = product_class.find_all( - extra_derived={ - "triple_price": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 3) - ) - } - ) - assert len(results) == 1 - assert results[0].__dict__["triple_price"] == pytest.approx(300.0) - - def test_extra_derived_conflict_raises(self, product_class): - self._insert(product_class, "G", 50.0, 2) - with pytest.raises(ValueError, match="conflicts with a declared derived field"): - product_class.find_all( - extra_derived={ - "discounted_price": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.5) - ) - } - ) - - def test_derived_and_extra_derived_together(self, product_class): - self._insert(product_class, "H", 40.0, 5) - results = product_class.find_all( - derived=True, - extra_derived={ - "double_qty": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "quantity"), Literal(d, 2) - ) - } - ) - assert results[0].discounted_price == pytest.approx(36.0) - assert results[0].total_value == pytest.approx(200.0) - assert results[0].__dict__["double_qty"] == pytest.approx(10.0) - - -class TestDerivedFieldWithProxy: - """Tests for DerivedField using FieldProxy in expressions.""" - - def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - p.save() - return p - - def test_proxy_derived_query(self, product_with_proxy_class): - self._insert(product_with_proxy_class, "P1", 100.0, 4) - results = product_with_proxy_class.find_all(derived=True) - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(400.0) - - def test_proxy_derived_all_fields(self, product_with_proxy_class): - self._insert(product_with_proxy_class, "P2", 200.0, 3) - results = product_with_proxy_class.find_all( - derived=["discounted_price", "total_value"] - ) - assert results[0].discounted_price == pytest.approx(180.0) - assert results[0].total_value == pytest.approx(600.0) - - def test_proxy_derived_not_in_model_fields(self, product_with_proxy_class): - assert "discounted_price" not in product_with_proxy_class.model_fields - assert "total_value" not in product_with_proxy_class.model_fields - - def test_proxy_derived_not_in_dirty_fields(self, product_with_proxy_class): - self._insert(product_with_proxy_class, "P3", 50.0, 2) - instance = product_with_proxy_class.find_all(derived=True)[0] - instance.__dict__["discounted_price"] = 999.0 - assert "discounted_price" not in instance.dirty_fields - - def test_proxy_derived_read_only(self, product_with_proxy_class): - self._insert(product_with_proxy_class, "P4", 80.0, 1) - instance = product_with_proxy_class.find_all(derived=True)[0] - with pytest.raises(AttributeError): - instance.discounted_price = 123.0 - - def test_proxy_derived_not_saved_to_db(self, product_with_proxy_class): - p = self._insert(product_with_proxy_class, "P5", 60.0, 2) - instance = product_with_proxy_class.find_one(p.id, derived=True) - assert instance.discounted_price == pytest.approx(54.0) - instance.name = "P5_modified" - instance.save() - fresh = product_with_proxy_class.find_one(p.id, derived=True) - assert fresh.name == "P5_modified" - assert fresh.discounted_price == pytest.approx(54.0) - - -class TestDerivedFieldWithUseColumnAndAdapter: - """Tests for DerivedField with UseColumn and UseAdapter annotations.""" - - def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - p.save() - return p - - def test_use_column_alias_in_select(self, product_with_column_and_adapter_class): - """UseColumn controls the SELECT alias; result maps back to Python field name.""" - self._insert(product_with_column_and_adapter_class, "UC1", 100.0, 5) - results = product_with_column_and_adapter_class.find_all(derived=True) - # discounted_price has UseColumn("disc") — alias is "disc" in SQL, - # but the value is accessible via the Python attribute name - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_int == 500 - - def test_use_adapter_from_database(self, product_with_column_and_adapter_class): - """UseAdapter applies from_database conversion on the derived field value.""" - self._insert(product_with_column_and_adapter_class, "UA1", 33.3, 3) - results = product_with_column_and_adapter_class.find_all(derived=["total_int"]) - # 33.3 * 3 = 99.9, adapter rounds to int → 100 - assert results[0].total_int == 100 - assert isinstance(results[0].total_int, int) - - def test_use_column_field_not_in_model_fields(self, product_with_column_and_adapter_class): - assert "discounted_price" not in product_with_column_and_adapter_class.model_fields - assert "total_int" not in product_with_column_and_adapter_class.model_fields - - def test_use_column_column_name_stored(self, product_with_column_and_adapter_class): - df = product_with_column_and_adapter_class.__derived_fields__["discounted_price"] - assert df.column_name == "disc" - - def test_use_adapter_stored(self, product_with_column_and_adapter_class): - df = product_with_column_and_adapter_class.__derived_fields__["total_int"] - assert df.adapter is not None - - def test_use_column_and_adapter_together(self, product_with_column_and_adapter_class): - """Both UseColumn and UseAdapter can coexist on the same derived field.""" - self._insert(product_with_column_and_adapter_class, "CA1", 50.0, 4) - results = product_with_column_and_adapter_class.find_all( - derived=["discounted_price", "total_int"] - ) - assert results[0].discounted_price == pytest.approx(45.0) - assert results[0].total_int == 200 - - -class TestDerivedFieldColumnConflict: - """Tests that column name conflicts between regular and derived fields are detected.""" - - def test_use_column_conflict_raises(self): - """UseColumn on derived field must not duplicate a regular field's column name.""" - with pytest.raises(TypeError, match="conflicts with a regular field's column name"): - class ConflictModel(ActiveRecord): - @classmethod - def table_name(cls): - return "conflict" - - id: Optional[int] = None - discount_rate: Annotated[float, UseColumn("disc")] - discounted: ClassVar[Annotated[float, DerivedField( - lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9) - ), - ), UseColumn("disc")]] - - def test_use_column_no_conflict_different_names(self): - """Different column names should not conflict.""" - class NoConflict(ActiveRecord): - @classmethod - def table_name(cls): - return "no_conflict" - - id: Optional[int] = None - discount_rate: Annotated[float, UseColumn("rate")] - discounted: ClassVar[Annotated[float, DerivedField( - lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9) - ), - ), UseColumn("disc")]] - - assert NoConflict.__derived_fields__["discounted"].column_name == "disc" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py deleted file mode 100644 index 82643fe1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py +++ /dev/null @@ -1,365 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/basic/fields/test_derived_field_async.py -import pytest -from typing import ClassVar, Optional -from typing_extensions import Annotated - -from rhosocial.activerecord.base import DerivedField, UseColumn -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.backend.expression import ( - ArithmeticOperation, - Column, - Literal, -) - - -class TestAsyncDerivedFieldDeclaration: - - async def test_derived_fields_registered(self, async_product_class): - assert "discounted_price" in async_product_class.__derived_fields__ - assert "total_value" in async_product_class.__derived_fields__ - - async def test_descriptor_class_access(self, async_product_class): - assert isinstance(async_product_class.discounted_price, DerivedField) - - async def test_derived_field_with_static_expression(self, async_product_class): - """Test DerivedField constructed with a pre-built expression object (non-callable path).""" - dialect = async_product_class.backend().dialect - static_expr = ArithmeticOperation( - dialect, "mul", Column(dialect, "price"), Literal(dialect, 2) - ) - df = DerivedField(static_expr) - resolved = df.resolve(dialect) - assert resolved is static_expr - - async def test_descriptor_instance_default_none(self, async_product_class): - p = async_product_class(name="x", price=10.0, quantity=1) - assert p.discounted_price is None - assert p.total_value is None - - async def test_derived_field_names_mapping(self, async_product_class): - names = async_product_class.__derived_field_names__ - df = async_product_class.__derived_fields__["discounted_price"] - assert names[id(df)] == "discounted_price" - - -class TestAsyncDerivedFieldQuery: - - async def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - await p.save() - return p - - async def test_find_all_derived_true(self, async_product_class): - await self._insert(async_product_class, "A", 100.0, 5) - results = await async_product_class.find_all(derived=True) - assert len(results) == 1 - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(500.0) - - async def test_find_all_derived_list_by_name(self, async_product_class): - await self._insert(async_product_class, "B", 50.0, 3) - results = await async_product_class.find_all(derived=["total_value"]) - assert len(results) == 1 - assert results[0].total_value == pytest.approx(150.0) - assert results[0].discounted_price is None - - async def test_find_all_derived_list_all(self, async_product_class): - await self._insert(async_product_class, "C", 200.0, 2) - results = await async_product_class.find_all(derived=["discounted_price", "total_value"]) - assert results[0].discounted_price == pytest.approx(180.0) - assert results[0].total_value == pytest.approx(400.0) - - async def test_find_one_derived(self, async_product_class): - p = await self._insert(async_product_class, "D", 80.0, 4) - result = await async_product_class.find_one(p.id, derived=True) - assert result.discounted_price == pytest.approx(72.0) - - async def test_find_one_or_fail_derived(self, async_product_class): - p = await self._insert(async_product_class, "D2", 80.0, 4) - result = await async_product_class.find_one_or_fail(p.id, derived=True) - assert result.discounted_price == pytest.approx(72.0) - assert result.total_value == pytest.approx(320.0) - - async def test_find_one_or_fail_derived_list(self, async_product_class): - p = await self._insert(async_product_class, "D3", 80.0, 4) - result = await async_product_class.find_one_or_fail(p.id, derived=["discounted_price", "total_value"]) - assert result.discounted_price == pytest.approx(72.0) - assert result.total_value == pytest.approx(320.0) - - async def test_find_all_derived_false_default(self, async_product_class): - await self._insert(async_product_class, "E", 60.0, 1) - results = await async_product_class.find_all() - assert results[0].discounted_price is None - assert results[0].total_value is None - - async def test_find_all_derived_all(self, async_product_class): - await self._insert(async_product_class, "F", 100.0, 5) - results = await async_product_class.find_all(derived="all") - assert len(results) == 1 - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(500.0) - - async def test_find_one_derived_all(self, async_product_class): - p = await self._insert(async_product_class, "G", 80.0, 4) - result = await async_product_class.find_one(p.id, derived="all") - assert result.discounted_price == pytest.approx(72.0) - assert result.total_value == pytest.approx(320.0) - - async def test_find_one_or_fail_derived_all(self, async_product_class): - p = await self._insert(async_product_class, "H", 60.0, 3) - result = await async_product_class.find_one_or_fail(p.id, derived="all") - assert result.discounted_price == pytest.approx(54.0) - assert result.total_value == pytest.approx(180.0) - - -class TestAsyncDerivedFieldFormA: - """Tests for Form A declaration: ClassVar[DerivedField] = DerivedField(...).""" - - async def test_form_a_fields_registered(self, async_product_form_a_class): - assert "discounted_price" in async_product_form_a_class.__derived_fields__ - assert "total_value" in async_product_form_a_class.__derived_fields__ - - async def test_form_a_query(self, async_product_form_a_class): - p = async_product_form_a_class(name="FA", price=100.0, quantity=3) - await p.save() - results = await async_product_form_a_class.find_all(derived=True) - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(300.0) - - async def test_form_a_source_id_mapping(self, async_product_form_a_class): - df = async_product_form_a_class.__derived_fields__["discounted_price"] - assert df._source_id is not None - assert async_product_form_a_class.__derived_field_names__[df._source_id] == "discounted_price" - - -class TestAsyncDerivedFieldDictForm: - """Tests for derived=dict form.""" - - async def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - await p.save() - return p - - async def test_derived_dict_with_lambda(self, async_product_class): - await self._insert(async_product_class, "D1", 100.0, 4) - results = await async_product_class.find_all( - derived={ - "my_discount": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.8) - ) - } - ) - assert results[0].__dict__["my_discount"] == pytest.approx(80.0) - - async def test_derived_dict_with_derived_field_instance(self, async_product_class): - await self._insert(async_product_class, "D2", 50.0, 2) - df = async_product_class.__derived_fields__["total_value"] - results = await async_product_class.find_all( - derived={"tv": df} - ) - assert results[0].__dict__["tv"] == pytest.approx(100.0) - - - async def test_derived_dict_with_expression_object(self, async_product_class): - await self._insert(async_product_class, "D3", 80.0, 5) - dialect = async_product_class.backend().dialect - expr = ArithmeticOperation( - dialect, "mul", Column(dialect, "price"), Literal(dialect, 0.5) - ) - results = await async_product_class.find_all( - derived={"half_price": expr} - ) - assert results[0].__dict__["half_price"] == pytest.approx(40.0) - - -class TestAsyncDerivedFieldLookupByInstance: - """Tests for derived=[DerivedField instance] form.""" - - async def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - await p.save() - return p - - async def test_lookup_by_derived_field_instance(self, async_product_class): - await self._insert(async_product_class, "L1", 200.0, 1) - df = async_product_class.__derived_fields__["discounted_price"] - results = await async_product_class.find_all(derived=[df]) - assert results[0].discounted_price == pytest.approx(180.0) - - -class TestAsyncExtraDerived: - - async def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - await p.save() - return p - - async def test_extra_derived_basic(self, async_product_class): - await self._insert(async_product_class, "F", 100.0, 10) - results = await async_product_class.find_all( - extra_derived={ - "triple_price": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 3) - ) - } - ) - assert len(results) == 1 - assert results[0].__dict__["triple_price"] == pytest.approx(300.0) - - async def test_extra_derived_conflict_raises(self, async_product_class): - await self._insert(async_product_class, "G", 50.0, 2) - with pytest.raises(ValueError, match="conflicts with a declared derived field"): - await async_product_class.find_all( - extra_derived={ - "discounted_price": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.5) - ) - } - ) - - async def test_derived_and_extra_derived_together(self, async_product_class): - await self._insert(async_product_class, "H", 40.0, 5) - results = await async_product_class.find_all( - derived=True, - extra_derived={ - "double_qty": lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "quantity"), Literal(d, 2) - ) - } - ) - assert results[0].discounted_price == pytest.approx(36.0) - assert results[0].total_value == pytest.approx(200.0) - assert results[0].__dict__["double_qty"] == pytest.approx(10.0) - - -class TestAsyncDerivedFieldWithProxy: - """Tests for DerivedField using FieldProxy in expressions.""" - - async def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - await p.save() - return p - - async def test_proxy_derived_query(self, async_product_with_proxy_class): - await self._insert(async_product_with_proxy_class, "P1", 100.0, 4) - results = await async_product_with_proxy_class.find_all(derived=True) - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_value == pytest.approx(400.0) - - async def test_proxy_derived_all_fields(self, async_product_with_proxy_class): - await self._insert(async_product_with_proxy_class, "P2", 200.0, 3) - results = await async_product_with_proxy_class.find_all( - derived=["discounted_price", "total_value"] - ) - assert results[0].discounted_price == pytest.approx(180.0) - assert results[0].total_value == pytest.approx(600.0) - - async def test_proxy_derived_not_in_model_fields(self, async_product_with_proxy_class): - assert "discounted_price" not in async_product_with_proxy_class.model_fields - assert "total_value" not in async_product_with_proxy_class.model_fields - - async def test_proxy_derived_not_in_dirty_fields(self, async_product_with_proxy_class): - await self._insert(async_product_with_proxy_class, "P3", 50.0, 2) - instance = (await async_product_with_proxy_class.find_all(derived=True))[0] - instance.__dict__["discounted_price"] = 999.0 - assert "discounted_price" not in instance.dirty_fields - - async def test_proxy_derived_read_only(self, async_product_with_proxy_class): - await self._insert(async_product_with_proxy_class, "P4", 80.0, 1) - instance = (await async_product_with_proxy_class.find_all(derived=True))[0] - with pytest.raises(AttributeError): - instance.discounted_price = 123.0 - - async def test_proxy_derived_not_saved_to_db(self, async_product_with_proxy_class): - p = await self._insert(async_product_with_proxy_class, "P5", 60.0, 2) - instance = await async_product_with_proxy_class.find_one(p.id, derived=True) - assert instance.discounted_price == pytest.approx(54.0) - instance.name = "P5_modified" - await instance.save() - fresh = await async_product_with_proxy_class.find_one(p.id, derived=True) - assert fresh.name == "P5_modified" - assert fresh.discounted_price == pytest.approx(54.0) - - -class TestAsyncDerivedFieldWithUseColumnAndAdapter: - """Tests for DerivedField with UseColumn and UseAdapter annotations.""" - - async def _insert(self, Model, name, price, quantity): - p = Model(name=name, price=price, quantity=quantity) - await p.save() - return p - - async def test_use_column_alias_in_select(self, async_product_with_column_and_adapter_class): - """UseColumn controls the SELECT alias; result maps back to Python field name.""" - await self._insert(async_product_with_column_and_adapter_class, "UC1", 100.0, 5) - results = await async_product_with_column_and_adapter_class.find_all(derived=True) - # discounted_price has UseColumn("disc") — alias is "disc" in SQL, - # but the value is accessible via the Python attribute name - assert results[0].discounted_price == pytest.approx(90.0) - assert results[0].total_int == 500 - - async def test_use_adapter_from_database(self, async_product_with_column_and_adapter_class): - """UseAdapter applies from_database conversion on the derived field value.""" - await self._insert(async_product_with_column_and_adapter_class, "UA1", 33.3, 3) - results = await async_product_with_column_and_adapter_class.find_all(derived=["total_int"]) - # 33.3 * 3 = 99.9, adapter rounds to int → 100 - assert results[0].total_int == 100 - assert isinstance(results[0].total_int, int) - - async def test_use_column_field_not_in_model_fields(self, async_product_with_column_and_adapter_class): - assert "discounted_price" not in async_product_with_column_and_adapter_class.model_fields - assert "total_int" not in async_product_with_column_and_adapter_class.model_fields - - async def test_use_column_column_name_stored(self, async_product_with_column_and_adapter_class): - df = async_product_with_column_and_adapter_class.__derived_fields__["discounted_price"] - assert df.column_name == "disc" - - async def test_use_adapter_stored(self, async_product_with_column_and_adapter_class): - df = async_product_with_column_and_adapter_class.__derived_fields__["total_int"] - assert df.adapter is not None - - async def test_use_column_and_adapter_together(self, async_product_with_column_and_adapter_class): - """Both UseColumn and UseAdapter can coexist on the same derived field.""" - await self._insert(async_product_with_column_and_adapter_class, "CA1", 50.0, 4) - results = await async_product_with_column_and_adapter_class.find_all( - derived=["discounted_price", "total_int"] - ) - assert results[0].discounted_price == pytest.approx(45.0) - assert results[0].total_int == 200 - - -class TestAsyncDerivedFieldColumnConflict: - """Tests that column name conflicts between regular and derived fields are detected.""" - - async def test_use_column_conflict_raises(self): - """UseColumn on derived field must not duplicate a regular field's column name.""" - with pytest.raises(TypeError, match="conflicts with a regular field's column name"): - class ConflictModel(ActiveRecord): - @classmethod - def table_name(cls): - return "conflict" - - id: Optional[int] = None - discount_rate: Annotated[float, UseColumn("disc")] - discounted: ClassVar[Annotated[float, DerivedField( - lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9) - ), - ), UseColumn("disc")]] - - async def test_use_column_no_conflict_different_names(self): - """Different column names should not conflict.""" - class NoConflict(ActiveRecord): - @classmethod - def table_name(cls): - return "no_conflict" - - id: Optional[int] = None - discount_rate: Annotated[float, UseColumn("rate")] - discounted: ClassVar[Annotated[float, DerivedField( - lambda d: ArithmeticOperation( - dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9) - ), - ), UseColumn("disc")]] - - assert NoConflict.__derived_fields__["discounted"].column_name == "disc" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py index a35d9746..2bb1a933 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py @@ -3,4 +3,3 @@ Bridge file for example basic fixtures tests from the testsuite. """ from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py index cef55fc3..60d8d3e9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py """Bridge file for async feature.basic.fields.test_example_basic_fixtures_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py index 87b920c3..360f1ed6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py @@ -21,5 +21,3 @@ # The test classes contain the actual test cases. from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py index d46911b2..27561fb7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py """Bridge file for async feature.basic.fields.test_field_column_mapping_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py index 13b13fb8..4e26c104 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py @@ -21,5 +21,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py index 2dace749..c3c18ffe 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py """Bridge file for async feature.basic.fields.test_fields_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py new file mode 100644 index 00000000..b31eb03a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py +"""Use the shared ``basic/nopk`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.nopk.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py index ec0a3c2a..2abc20b6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py @@ -1,4 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py """Bridge file for the testsuite keyless model contract (sync and async).""" from rhosocial.activerecord.testsuite.feature.basic.nopk.test_keyless_models import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.nopk.test_keyless_models_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py new file mode 100644 index 00000000..002d1a36 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.nopk.test_keyless_models_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py new file mode 100644 index 00000000..fefb63b6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py +"""Use the shared ``basic/readonly`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.readonly.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py index f9b39047..a8f07aea 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py @@ -1,4 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py """Bridge file for the testsuite read-only model contract (sync and async).""" from rhosocial.activerecord.testsuite.feature.basic.readonly.test_readonly_models import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.readonly.test_readonly_models_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py new file mode 100644 index 00000000..bc6ebf7a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.readonly.test_readonly_models_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py deleted file mode 100644 index 6601e6ad..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py +++ /dev/null @@ -1,20 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py -""" -This module serves as a bridge to execute the generic basic mapped models tests -defined in the `rhosocial-activerecord-testsuite` package against the PostgreSQL backend. - -The tests are dynamically parametrized with PostgreSQL-specific fixtures. -""" - -# IMPORTANT: -# The following imports are essential for the test suite to discover and run the tests. -# The fixtures are defined in the `conftest.py` of the testsuite and are implemented -# by the provider in the current backend (`tests/providers/basic.py`). - -# The `basic_model_fixtures` is a fixture that provides the necessary setup for the tests. -from rhosocial.activerecord.testsuite.feature.basic.conftest import mapped_models_fixtures # noqa: F401 - -# The `TestBasicMappedModels` class contains the actual test cases. -from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py new file mode 100644 index 00000000..07a37fb2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py +"""Use the shared ``basic/type_adapter`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.type_adapter.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py index d6108e4f..db332eac 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py @@ -14,5 +14,3 @@ # Import all tests from the generic testsuite file. from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py index 533df4fa..7294139e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py """Bridge file for async feature.basic.type_adapter.test_type_adapter_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py new file mode 100644 index 00000000..af0b63da --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py +"""Use the shared ``basic/validation`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.validation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py index 03fc5eeb..a136f7f1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py @@ -14,5 +14,3 @@ ) from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py index 1b5019de..62465994 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py """Bridge file for async feature.basic.validation.test_pydantic_native_validation_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py index 2c2cd094..41de15ba 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py @@ -21,5 +21,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py index df784d78..9b25cb87 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py """Bridge file for async feature.basic.validation.test_validation_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py index a5150e06..4486e093 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py @@ -8,5 +8,3 @@ user_class_for_worker, # noqa: F401 ) from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py index 3340c392..48a29cea 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py """Bridge file for async feature.basic.worker.test_connection_management_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py index 287d0828..c75a4e8c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py @@ -9,5 +9,3 @@ async_user_class_for_worker, # noqa: F401 ) from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py index 62eedf04..dce3b9dc 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py """Bridge file for async feature.basic.worker.test_parallel_crud_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py index 7df4d9df..53d0a0d0 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py @@ -8,5 +8,3 @@ user_class_for_worker, # noqa: F401 ) from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py index 15ccdd00..67029291 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py """Bridge file for async feature.basic.worker.test_worker_pool_lifecycle_async tests.""" from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py index 0cc3dba5..f9f2379d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py @@ -1 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.cli.conftest import * # noqa: F403 +# tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py +"""Use the shared ``cli`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.cli.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py index 540b149e..3195053a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py @@ -1,138 +1,69 @@ # tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py +"""Pytest configuration for the connection pool tests. + +The directory owns its logical database the same way every migrated directory +does: it declares the lifecycle here and takes the scenario and configuration +from the testsuite ``environment``, so running against several scenarios gets +one pool per scenario instead of a first-scenario guess. The concurrency tables +are created and dropped by the table fixtures themselves, so ``prepare`` and +``teardown`` have no group to manage. """ -Pytest configuration for connection pool tests. -This module provides fixtures for testing connection pools with PostgreSQL backends. -""" - -import os -from typing import Dict, Any, Generator +from typing import Generator import pytest import pytest_asyncio -import yaml -from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend -from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend -from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig from rhosocial.activerecord.connection.pool import ( - PoolConfig, - BackendPool, AsyncBackendPool, + BackendPool, + PoolConfig, ) -# --- Scenario Loading Logic --- - -SCENARIO_MAP: Dict[str, Dict[str, Any]] = {} - - -def register_scenario(name: str, config: Dict[str, Any]): - SCENARIO_MAP[name] = config - - -def _load_scenarios_from_config(): - """Load scenarios from a configuration file.""" - config_path = None - env_config_path = os.getenv("POSTGRES_SCENARIOS_CONFIG_PATH") - - if env_config_path and os.path.exists(env_config_path): - config_path = env_config_path - else: - default_path = os.path.join( - os.path.dirname(__file__), - "../../../../config", - "postgres_scenarios.yaml" - ) - if os.path.exists(default_path): - config_path = default_path - elif env_config_path: - print(f"Warning: Scenario file specified in POSTGRES_SCENARIOS_CONFIG_PATH not found: {env_config_path}") - return - - if not config_path: - raise FileNotFoundError( - "No PostgreSQL scenarios configuration file found. " - "Set POSTGRES_SCENARIOS_CONFIG_PATH or place postgres_scenarios.yaml in tests/config." - ) - - try: - with open(config_path, 'r', encoding='utf-8') as f: - config_data = yaml.safe_load(f) - - if 'scenarios' not in config_data: - raise ValueError(f"Configuration file {config_path} does not contain 'scenarios' key") +def ensure_database(environment): + """Create the directory's database, or clear it when it already exists.""" + environment.reset_database() - for scenario_name, config in config_data['scenarios'].items(): - if config: - register_scenario(scenario_name, config) - except ImportError: - raise ImportError("PyYAML is required to load scenario configuration files") # noqa: B904 +def prepare(environment): + """No group tables: each table fixture creates what it needs.""" -_load_scenarios_from_config() +def teardown(environment): + """No group tables: each table fixture drops what it created.""" -def get_scenario_config(name: str) -> Dict[str, Any]: - if name not in SCENARIO_MAP: - if SCENARIO_MAP: - name = next(iter(SCENARIO_MAP)) - else: - raise ValueError("No scenarios registered or enabled") - config_dict = SCENARIO_MAP[name].copy() - # Apply the pooled database name so parallel workers never share a schema. - from providers.pooling import resolve_database_name - - pooled_db = resolve_database_name(name) - if pooled_db: - config_dict["database"] = pooled_db - return config_dict +def _backend_factory(environment): + """Return a factory producing sync backends for this environment.""" + config = environment.make_config() + def factory(): + return environment.scenario.backend_class(connection_config=config) -def get_scenario_names(): - return list(SCENARIO_MAP.keys()) + return factory -# --- Pool Fixtures --- +def _async_backend_factory(environment): + """Return a factory producing async backends for this environment.""" + config = environment.make_config() -def create_postgres_backend_factory(config_dict: Dict[str, Any]): - """Create a factory function that produces PostgresBackend instances.""" def factory(): - config = PostgresConnectionConfig(**config_dict) - backend = PostgresBackend(connection_config=config) - backend.connect() - return backend - return factory + return environment.scenario.async_backend_class(connection_config=config) - -def create_async_postgres_backend_factory(config_dict: Dict[str, Any]): - """Create a factory function that produces AsyncPostgresBackend instances.""" - def factory(): - config = PostgresConnectionConfig(**config_dict) - backend = AsyncPostgresBackend(connection_config=config) - # Note: connect() will be called by the pool when needed - return backend return factory @pytest.fixture(scope="function") -def postgres_pool() -> Generator[BackendPool, None, None]: +def postgres_pool(environment) -> Generator[BackendPool, None, None]: """Create a BackendPool with PostgreSQL backends for testing.""" - scenario_names = get_scenario_names() - if not scenario_names: - pytest.skip("No PostgreSQL scenarios configured") - - config_dict = get_scenario_config(scenario_names[0]) - config_dict.pop('enabled', None) - pool_config = PoolConfig( min_size=1, max_size=5, timeout=30.0, validate_on_borrow=True, validation_query="SELECT 1", - backend_factory=create_postgres_backend_factory(config_dict), + backend_factory=_backend_factory(environment), ) pool = BackendPool.create(pool_config) @@ -141,22 +72,15 @@ def postgres_pool() -> Generator[BackendPool, None, None]: @pytest_asyncio.fixture(scope="function") -async def async_postgres_pool() -> AsyncBackendPool: +async def async_postgres_pool(environment) -> AsyncBackendPool: """Create an AsyncBackendPool with PostgreSQL backends for testing.""" - scenario_names = get_scenario_names() - if not scenario_names: - pytest.skip("No PostgreSQL scenarios configured") - - config_dict = get_scenario_config(scenario_names[0]) - config_dict.pop('enabled', None) - pool_config = PoolConfig( min_size=1, max_size=5, timeout=30.0, validate_on_borrow=True, validation_query="SELECT 1", - backend_factory=create_async_postgres_backend_factory(config_dict), + backend_factory=_async_backend_factory(environment), ) pool = await AsyncBackendPool.create(pool_config) @@ -165,21 +89,14 @@ async def async_postgres_pool() -> AsyncBackendPool: @pytest.fixture(scope="function") -def postgres_pool_large() -> Generator[BackendPool, None, None]: +def postgres_pool_large(environment) -> Generator[BackendPool, None, None]: """Create a larger BackendPool for stress testing.""" - scenario_names = get_scenario_names() - if not scenario_names: - pytest.skip("No PostgreSQL scenarios configured") - - config_dict = get_scenario_config(scenario_names[0]) - config_dict.pop('enabled', None) - pool_config = PoolConfig( min_size=2, max_size=10, timeout=60.0, validate_on_borrow=False, # Faster for stress tests - backend_factory=create_postgres_backend_factory(config_dict), + backend_factory=_backend_factory(environment), ) pool = BackendPool.create(pool_config) @@ -188,21 +105,14 @@ def postgres_pool_large() -> Generator[BackendPool, None, None]: @pytest_asyncio.fixture(scope="function") -async def async_postgres_pool_large() -> AsyncBackendPool: +async def async_postgres_pool_large(environment) -> AsyncBackendPool: """Create a larger AsyncBackendPool for stress testing.""" - scenario_names = get_scenario_names() - if not scenario_names: - pytest.skip("No PostgreSQL scenarios configured") - - config_dict = get_scenario_config(scenario_names[0]) - config_dict.pop('enabled', None) - pool_config = PoolConfig( min_size=2, max_size=10, timeout=60.0, validate_on_borrow=False, - backend_factory=create_async_postgres_backend_factory(config_dict), + backend_factory=_async_backend_factory(environment), ) pool = await AsyncBackendPool.create(pool_config) @@ -212,6 +122,7 @@ async def async_postgres_pool_large() -> AsyncBackendPool: # --- Table Setup Fixtures --- + @pytest.fixture(scope="function") def postgres_pool_with_tables(postgres_pool: BackendPool) -> Generator[BackendPool, None, None]: """Create a pool with test tables initialized.""" @@ -244,7 +155,9 @@ def postgres_pool_with_tables(postgres_pool: BackendPool) -> Generator[BackendPo @pytest_asyncio.fixture(scope="function") -async def async_postgres_pool_with_tables(async_postgres_pool: AsyncBackendPool) -> AsyncBackendPool: +async def async_postgres_pool_with_tables( + async_postgres_pool: AsyncBackendPool, +) -> AsyncBackendPool: """Create an async pool with test tables initialized.""" async with async_postgres_pool.connection() as backend: await backend.execute("DROP TABLE IF EXISTS concurrent_test_users") diff --git a/tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py new file mode 100644 index 00000000..bb848484 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py +from rhosocial.activerecord_postgres_test.feature.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/test_features.py b/tests/rhosocial/activerecord_postgres_test/feature/core/test_features.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/test_features.py rename to tests/rhosocial/activerecord_postgres_test/feature/core/test_features.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/test_features_async.py b/tests/rhosocial/activerecord_postgres_test/feature/core/test_features_async.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/test_features_async.py rename to tests/rhosocial/activerecord_postgres_test/feature/core/test_features_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py index 412a154d..ef1b83db 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py @@ -1,8 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py -""" -Pytest configuration for events feature tests. - -This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. -""" -from rhosocial.activerecord.testsuite.feature.events.conftest import * # noqa: F403 +"""Use the shared ``events`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.events.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py new file mode 100644 index 00000000..3b1a4e11 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py +from rhosocial.activerecord_postgres_test.feature.events.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py new file mode 100644 index 00000000..e86f1d11 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py +""" +Event Handler Test Module for PostgreSQL backend. + +This module imports and runs the shared tests from the testsuite package, +ensuring PostgreSQL backend compatibility. +""" +# Import shared tests from testsuite package +from rhosocial.activerecord.testsuite.feature.events.core.test_handlers import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py new file mode 100644 index 00000000..742aed66 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py @@ -0,0 +1,5 @@ +# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py +"""Bridge file for async feature.events.test_handlers_async tests.""" +from rhosocial.activerecord.testsuite.feature.events.core.test_handlers_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.events.core.test_handlers_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py new file mode 100644 index 00000000..177f2eff --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py +""" +Event Lifecycle Test Module for PostgreSQL backend. + +This module imports and runs the shared tests from the testsuite package, +ensuring PostgreSQL backend compatibility. +""" +# Import shared tests from testsuite package +from rhosocial.activerecord.testsuite.feature.events.core.test_lifecycle import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py new file mode 100644 index 00000000..57dd58fd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py @@ -0,0 +1,5 @@ +# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py +"""Bridge file for async feature.events.test_lifecycle_async tests.""" +from rhosocial.activerecord.testsuite.feature.events.core.test_lifecycle_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.events.core.test_lifecycle_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py deleted file mode 100644 index 5964c8ba..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py +++ /dev/null @@ -1,25 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py -""" -Event Handler Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# IMPORTANT: These imports are essential for pytest to work correctly. -# Even though they may be flagged as "unused" by some IDEs or linters, -# they must not be removed. They are the mechanism by which pytest discovers -# the fixtures and the tests from the external testsuite package. - -# Although the root conftest.py sets up the environment, explicitly importing -# the fixtures here makes the dependency clear and can help with test discovery -# in some IDEs. These fixtures are defined in the testsuite package and are -# parameterized to run against the scenarios defined in `providers/scenarios.py`. -from rhosocial.activerecord.testsuite.feature.events.conftest import ( - event_model, # noqa: F401 - event_tracking_model, # Assuming event_tracking_model is also needed here # noqa: F401 -) - -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.events.test_handlers import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.events.test_handlers_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py deleted file mode 100644 index 6b946f79..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py -"""Bridge file for async feature.events.test_handlers_async tests.""" -from rhosocial.activerecord.testsuite.feature.events.test_handlers_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py deleted file mode 100644 index 43bb6d83..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py +++ /dev/null @@ -1,25 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py -""" -Event Lifecycle Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# IMPORTANT: These imports are essential for pytest to work correctly. -# Even though they may be flagged as "unused" by some IDEs or linters, -# they must not be removed. They are the mechanism by which pytest discovers -# the fixtures and the tests from the external testsuite package. - -# Although the root conftest.py sets up the environment, explicitly importing -# the fixtures here makes the dependency clear and can help with test discovery -# in some IDEs. These fixtures are defined in the testsuite package and are -# parameterized to run against the scenarios defined in `providers/scenarios.py`. -from rhosocial.activerecord.testsuite.feature.events.conftest import ( - event_model, # noqa: F401 - event_tracking_model, # Assuming event_tracking_model is also needed here # noqa: F401 -) - -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.events.test_lifecycle import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.events.test_lifecycle_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py deleted file mode 100644 index 94312c2a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py -"""Bridge file for async feature.events.test_lifecycle_async tests.""" -from rhosocial.activerecord.testsuite.feature.events.test_lifecycle_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py index 48cf1235..3f90b13c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py @@ -4,4 +4,3 @@ """ from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py index b5e43962..67ade74a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py """Bridge file for async feature.interface.test_threadsafe_dict_async tests.""" from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py new file mode 100644 index 00000000..396228d5 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py @@ -0,0 +1,6 @@ +# tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py +"""The logging tests are unit-level: this directory needs no database tables. + +The shared suite has no ``logging`` fixture group, so there is nothing to +import and no ``prepare`` / ``teardown`` group to declare. +""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py index afd426f8..d9eca998 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py @@ -1,8 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py -""" -Pytest configuration for mixins feature tests. - -This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. -""" -from rhosocial.activerecord.testsuite.feature.mixins.conftest import * # noqa: F403 +"""Use the shared ``mixins`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.mixins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py new file mode 100644 index 00000000..07abdf52 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py +from rhosocial.activerecord_postgres_test.feature.mixins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py similarity index 60% rename from tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py rename to tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py index c0c81379..e0869313 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py @@ -6,6 +6,4 @@ ensuring PostgreSQL backend compatibility. """ # Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles_async import * # noqa: F403 - +from rhosocial.activerecord.testsuite.feature.mixins.core.test_combined_articles import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py new file mode 100644 index 00000000..217b278f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py @@ -0,0 +1,5 @@ +# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py +"""Bridge file for async feature.mixins.test_combined_articles_async tests.""" +from rhosocial.activerecord.testsuite.feature.mixins.core.test_combined_articles_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.mixins.core.test_combined_articles_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py similarity index 60% rename from tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py rename to tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py index be5611e5..31e34947 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py @@ -6,6 +6,4 @@ ensuring PostgreSQL backend compatibility. """ # Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock_async import * # noqa: F403 - +from rhosocial.activerecord.testsuite.feature.mixins.core.test_optimistic_lock import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py new file mode 100644 index 00000000..b9bcab2c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py @@ -0,0 +1,5 @@ +# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py +"""Bridge file for async feature.mixins.test_optimistic_lock_async tests.""" +from rhosocial.activerecord.testsuite.feature.mixins.core.test_optimistic_lock_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.mixins.core.test_optimistic_lock_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py similarity index 61% rename from tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py rename to tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py index 40a34336..878c9f64 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py @@ -6,6 +6,4 @@ ensuring PostgreSQL backend compatibility. """ # Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete_async import * # noqa: F403 - +from rhosocial.activerecord.testsuite.feature.mixins.core.test_soft_delete import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py new file mode 100644 index 00000000..eea2b5f0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py @@ -0,0 +1,5 @@ +# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py +"""Bridge file for async feature.mixins.test_soft_delete_async tests.""" +from rhosocial.activerecord.testsuite.feature.mixins.core.test_soft_delete_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.mixins.core.test_soft_delete_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py similarity index 61% rename from tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py rename to tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py index 64344372..54ce289f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py @@ -6,6 +6,4 @@ ensuring PostgreSQL backend compatibility. """ # Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps_async import * # noqa: F403 - +from rhosocial.activerecord.testsuite.feature.mixins.core.test_timestamps import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py new file mode 100644 index 00000000..391975e0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py @@ -0,0 +1,5 @@ +# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py +"""Bridge file for async feature.mixins.test_timestamps_async tests.""" +from rhosocial.activerecord.testsuite.feature.mixins.core.test_timestamps_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.mixins.core.test_timestamps_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py deleted file mode 100644 index 1dc7d5c5..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py -"""Bridge file for async feature.mixins.test_combined_articles_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py deleted file mode 100644 index 4c233401..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py -"""Bridge file for async feature.mixins.test_optimistic_lock_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py deleted file mode 100644 index 14371fd5..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py -"""Bridge file for async feature.mixins.test_soft_delete_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py deleted file mode 100644 index 0260c373..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py -"""Bridge file for async feature.mixins.test_timestamps_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py new file mode 100644 index 00000000..8052c239 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py +"""Use the shared ``query/aggregate`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.aggregate.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py index deae3685..cfa86988 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py index c3568677..f94de7ef 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py """Bridge file for async feature.query.aggregate.test_active_query_aggregate_async tests.""" from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py index 525ba49a..5a3795ff 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py index df180f44..7825cf5f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py """Bridge file for async feature.query.aggregate.test_aggregate_queries_async tests.""" from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py new file mode 100644 index 00000000..198ceb3a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py +"""Use the shared ``query/basic`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.basic.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py index 9baba06b..ca58d537 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py index 4bc013b4..ff034351 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py """Bridge file for async feature.query.basic.test_active_query_basic_async tests.""" from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py index e2f69cef..5ec2f7cb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.basic.test_basic import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py index 55d0570f..5681ff04 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py """Bridge file for async feature.query.basic.test_basic_async tests.""" from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py index 20bd64fb..6e648edb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py @@ -3,4 +3,3 @@ Bridge file for composite PK query tests from the testsuite. """ from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F403 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py index a4d65b87..9e26bffa 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py """Bridge file for async feature.query.basic.test_composite_pk_query_async tests.""" from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py index cc8fd3a4..da021fed 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py @@ -1,4 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py """Bridge file for the testsuite natural-key find_one_or_create contract.""" from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py new file mode 100644 index 00000000..c2288e00 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py new file mode 100644 index 00000000..644b2aa3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py @@ -0,0 +1,28 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py +"""The PostgreSQL-only collation test set. + +These tests are backend-specific, so the fixture group lives here rather than +in the shared suite; the tables still come from the topic's declarations. +""" + +from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403 +from rhosocial.activerecord.testsuite.feature.query.fixtures import tables + +GROUP_TABLES = ("searchable_items",) + + +def ensure_database(environment): + """Create the directory's database, or clear it when it already exists.""" + environment.reset_database() + + +def prepare(environment): + """Create the group's tables before every test.""" + for name in GROUP_TABLES: + environment.execute(tables.QUERY_TABLES[name](environment.dialect)) + + +def teardown(environment): + """Drop the group's tables after every test.""" + for name in reversed(GROUP_TABLES): + environment.execute(tables.drop_table(environment.dialect, name)) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py index 070acde9..14b936c8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py @@ -5,4 +5,5 @@ This file imports fixtures from the corresponding testsuite, making them available to the tests in this directory. """ + from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py index e3dcb692..c4aeddfa 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py @@ -5,4 +5,5 @@ This file imports fixtures from the corresponding testsuite, making them available to the tests in this directory. """ + from rhosocial.activerecord.testsuite.feature.query.connection.conftest import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py index 9fb3d2f7..403c1a9e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py @@ -12,5 +12,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py index cd8c61c6..2baf43bd 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py """Bridge file for async feature.query.connection.test_active_query_context_async tests.""" from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py index 0b1e6153..1483e319 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py @@ -12,5 +12,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py index e8b21313..6ca0c306 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py """Bridge file for async feature.query.connection.test_cte_query_context_async tests.""" from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py index ef0d192a..f6acecbf 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py @@ -12,5 +12,3 @@ # Import shared tests from testsuite package from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py index 9bc0e34e..f6ff9fcc 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py """Bridge file for async feature.query.connection.test_set_operation_context_async tests.""" from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py new file mode 100644 index 00000000..3525f4ab --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py +"""Use the shared ``query/cross_database`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.cross_database.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py index b234b681..e16f8d99 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py index 1c8d2108..6a15e862 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py """Bridge file for async feature.query.cross_database.test_cross_database_compatibility_async tests.""" from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py new file mode 100644 index 00000000..ec7963a1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py +"""Use the shared ``query/cte`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.cte.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py index 986a6c4a..b9788d0b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py @@ -3,4 +3,3 @@ Bridge file for composite PK CTE tests from the testsuite. """ from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F403 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py index 46972049..c141ba98 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py """Bridge file for async feature.query.cte.test_composite_pk_cte_async tests.""" from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py index 6298688f..b31607d1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py index 3429c45a..b8e6d01e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py """Bridge file for async feature.query.cte.test_cte_query_active_query_async tests.""" from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py index 686d8fc6..db6792dc 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py index 4bf171be..9540b625 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py """Bridge file for async feature.query.cte.test_cte_query_set_operation_async tests.""" from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py new file mode 100644 index 00000000..a111c21f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py +"""Use the shared ``query/eager_loading`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py index a7c1e676..f3a2492d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py @@ -3,5 +3,3 @@ Bridge file for eager loading caching tests. """ from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching import * # noqa: F401, F403 -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py index f946bcec..3d5f8dd9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py """Bridge file for async feature.query.eager_loading.test_eager_loading_caching_async tests.""" from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py index 09efb41a..60725f0d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py @@ -3,5 +3,3 @@ Bridge file for eager loading nested tests. """ from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested import * # noqa: F401, F403 -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py index b7921aa6..9434e847 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py """Bridge file for async feature.query.eager_loading.test_eager_loading_nested_async tests.""" from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py index 7571dafa..5e6d5fc6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py @@ -3,5 +3,3 @@ Bridge file for eager loading with_all tests. """ from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all import * # noqa: F401, F403 -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py index 197ae5d6..88855189 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py """Bridge file for async feature.query.eager_loading.test_eager_loading_with_all_async tests.""" from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py index c55cb6f8..82549640 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py @@ -3,5 +3,3 @@ Bridge file for eager loading with_modifier tests. """ from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier import * # noqa: F401, F403 -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py index c558e117..858cbae5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py """Bridge file for async feature.query.eager_loading.test_eager_loading_with_modifier_async tests.""" from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py index 8dc3de43..ac1e62aa 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py @@ -3,5 +3,3 @@ Bridge file for eager loading with_one tests. """ from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one import * # noqa: F401, F403 -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py index 1ad43fb7..b08bd846 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py """Bridge file for async feature.query.eager_loading.test_eager_loading_with_one_async tests.""" from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py new file mode 100644 index 00000000..5e73b65c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py +"""Use the shared ``query/error_handling`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.error_handling.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py index 88f48f2c..8cf006ff 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py index ef91b73c..d4ff165a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py """Bridge file for async feature.query.error_handling.test_error_handling_async tests.""" from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py new file mode 100644 index 00000000..d1681c38 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py +"""Use the shared ``query/joins`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.joins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py index 90eb3a08..823372d6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py index 63a0b532..d1308c9d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py """Bridge file for async feature.query.joins.test_active_query_join_async tests.""" from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py index a775027d..320a5614 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.joins.test_joins import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py index f5710f45..2e02d0eb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py """Bridge file for async feature.query.joins.test_joins_async tests.""" from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py new file mode 100644 index 00000000..ac93f80b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py +"""Use the shared ``query/logging`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.logging.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py index 5087c2ed..b476a587 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py index 1f9e0aa4..cec8f64c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py """Bridge file for async feature.query.logging.test_logging_data_summarization_async tests.""" from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py new file mode 100644 index 00000000..02b5a48e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py +"""Use the shared ``query/optimization`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.optimization.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py index 115d70f0..8d4a466d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py index 9688b94b..bb913603 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py """Bridge file for async feature.query.optimization.test_query_optimization_async tests.""" from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py new file mode 100644 index 00000000..3b3fc04d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py +"""Use the shared ``query/range_queries`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.range_queries.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py index 8498bb08..047ce64f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py index 667a3718..35514496 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py """Bridge file for async feature.query.range_queries.test_active_query_range_async tests.""" from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py index fb8bc85e..6d9837f6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py index c6ef096e..50208650 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py """Bridge file for async feature.query.range_queries.test_range_queries_async tests.""" from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py index ef05c44b..1faa60ec 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py index df8937fe..b937526b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py """Bridge file for async feature.query.range_queries.test_range_query_detailed_async tests.""" from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py new file mode 100644 index 00000000..288b571d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py +"""Use the shared ``query/relations`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.relations.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py index abd6a3f4..c699fc31 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py index 9276ed3a..e12e565f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py """Bridge file for async feature.query.relations.test_relational_validation_async tests.""" from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py index 7a2a089e..86c4d037 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py index 6ff408c0..ba498765 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py """Bridge file for async feature.query.relations.test_relations_basic_async tests.""" from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py new file mode 100644 index 00000000..7bc9a220 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py +"""Use the shared ``query/set_operations`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.set_operations.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py index d3981b53..c2f04d67 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py index 97e7fa6f..a71251a5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py """Bridge file for async feature.query.set_operations.test_active_query_set_operation_async tests.""" from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py index 8cf2e58c..3d3034e9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py @@ -3,4 +3,3 @@ Bridge file for composite PK set operation tests from the testsuite. """ from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F403 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py index fe46fbee..f77a1f16 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py """Bridge file for async feature.query.set_operations.test_composite_pk_set_operation_async tests.""" from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py index a23ca1b3..9bec2b6b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py index 20f605cb..46389c84 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py """Bridge file for async feature.query.set_operations.test_set_operation_async tests.""" from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py new file mode 100644 index 00000000..84fb89fb --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py +"""Use the shared ``query/special`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.special.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py index 162cb400..79e54062 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py index aa20fa09..bcc2fcfe 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py """Bridge file for async feature.query.special.test_example_query_fixtures_async tests.""" from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py index eb4efe6f..e15c2d89 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py index 4bba9f80..acb874d3 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py """Bridge file for async feature.query.special.test_special_queries_async tests.""" from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py new file mode 100644 index 00000000..dc7b8d76 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py +"""Use the shared ``query/typed_column`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.typed_column.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py new file mode 100644 index 00000000..1d6ccb99 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py +"""Use the shared ``query/window_functions`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.query.window_functions.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py index 54ee5de3..225b1ea2 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py @@ -6,5 +6,3 @@ discoverable by pytest in this project's test run. """ from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py index f69a0000..f025e662 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py """Bridge file for async feature.query.window_functions.test_window_functions_async tests.""" from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py index e9cd5de9..25979d9d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py @@ -5,4 +5,5 @@ This file imports fixtures from the corresponding testsuite, making them available to the tests in this directory. """ -from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * # noqa: F403 \ No newline at end of file + +from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py index f7927c07..7bfe5ecb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py @@ -9,5 +9,3 @@ async_order_fixtures_for_worker, # noqa: F401 ) from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py index 326c49d9..f2953770 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py """Bridge file for async feature.query.worker.test_parallel_queries_async tests.""" from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py new file mode 100644 index 00000000..5237cde3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py +"""No directory-specific fixtures: the relation topic conftest supplies them.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py new file mode 100644 index 00000000..a73bbce5 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py +"""Use the shared ``relation/boundary`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.boundary.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py index 0efbbf89..c806b2e5 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py index 591af194..8b71c8fc 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py new file mode 100644 index 00000000..61a6dd6a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py +"""No directory-specific fixtures: the relation topic conftest supplies them.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py index ae990e84..1550776b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py index e5e95b6a..84796d5e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py """Bridge file for async feature.relation.cache.test_cache_clearing_async tests.""" from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py index 77f688a5..529950d2 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py @@ -1,56 +1,7 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py -""" -Pytest configuration for relation feature tests. +"""Fixtures for the relation feature tests. -This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. +The topic conftest supplies the fixtures and the minimal test set for this +directory's database. """ -from rhosocial.activerecord.testsuite.feature.relation.conftest import * # noqa: F403 - -import pytest_asyncio - - -@pytest_asyncio.fixture(scope="function") -async def async_user_class(async_user_post_comment_classes): - user, _, _ = async_user_post_comment_classes - return user - - -@pytest_asyncio.fixture(scope="function") -async def async_post_class(async_user_post_comment_classes): - _, post, _ = async_user_post_comment_classes - return post - - -@pytest_asyncio.fixture(scope="function") -async def async_comment_class(async_user_post_comment_classes): - _, _, comment = async_user_post_comment_classes - return comment - - -@pytest_asyncio.fixture(scope="function", params=SCENARIO_PARAMS_ASYNC) # noqa: F405 -async def async_user_post_comment_classes(request): - from rhosocial.activerecord.testsuite.core.registry import get_provider_registry - - scenario = request.param - provider_registry = get_provider_registry() - provider_class = provider_registry.get_provider(PROVIDER_KEY_ASYNC) # noqa: F405 - provider = provider_class() - user = await provider.setup_user_model(scenario) - post = await provider.setup_post_model(scenario) - comment = await provider.setup_comment_model(scenario) - yield user, post, comment - await provider.cleanup_after_test(scenario) - - -@pytest_asyncio.fixture(scope="function", params=SCENARIO_PARAMS_ASYNC) # noqa: F405 -async def async_relation_boundary_context(request): - from rhosocial.activerecord.testsuite.core.registry import get_provider_registry - - scenario = request.param - provider_registry = get_provider_registry() - provider_class = provider_registry.get_provider(PROVIDER_KEY_ASYNC) # noqa: F405 - provider = provider_class() - owner, profile, post = await provider.setup_relation_boundary_fixtures(scenario) - yield provider, scenario, owner, profile, post - await provider.cleanup_after_test(scenario) +from rhosocial.activerecord.testsuite.feature.relation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py new file mode 100644 index 00000000..f2f51c07 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py +"""Use the shared ``relation/derived`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.derived.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py index a9d9b50b..bcf8f56e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py index 0bf8a6d2..15148306 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py new file mode 100644 index 00000000..a58eb73b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py +"""No directory-specific fixtures: the relation topic conftest supplies them.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py index 09df177d..7da186bb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py @@ -1,4 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/test_descriptor_compat.py from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py index 53052583..02d2f7ec 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py """Bridge file for async feature.relation.descriptors.test_descriptor_compat_async tests.""" from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py new file mode 100644 index 00000000..f5789fd7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py +"""Use the shared ``relation/eager_loading`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py index a1ce8686..134b3e91 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py index a2c28563..c372ff6a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py new file mode 100644 index 00000000..0df66180 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py +"""Use the shared ``relation/integration`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.integration.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py index eb3e57d4..b8dfb5ec 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py index ef9b2e02..cfd025f4 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py new file mode 100644 index 00000000..3e5c64a7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py +"""Use the shared ``relation/modifiers`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.modifiers.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py index 8fc621f3..6e7b8df1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py index 797fa5e3..b350149b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py index 2b7b7bc8..4bb16f70 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py index 6e884253..d94f9909 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py new file mode 100644 index 00000000..9176c11d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py +"""Use the shared ``relation/ordering`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.ordering.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py index c3ba5e03..ad2b38cb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py @@ -1,4 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py """Bridge file for the testsuite ordered HasMany contract (sync and async).""" from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py new file mode 100644 index 00000000..53182b04 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py new file mode 100644 index 00000000..e53e8def --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py +"""Use the shared ``relation/validation`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.relation.validation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py index b2b0a150..7232b1d9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py index b492478f..52e84cba 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py @@ -1 +1,3 @@ from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F401,F403 + +from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py index 47df6d4e..e9b4b8e8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py @@ -1,4 +1,3 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/test_validator.py from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py index 799baf9f..f8d4daeb 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py """Bridge file for async feature.relation.validation.test_validator_async tests.""" from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F401, F403 + +from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py b/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py index 210f89ad..2405a988 100644 --- a/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py +++ b/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py @@ -8,7 +8,7 @@ import pytest from rhosocial.activerecord.backend.impl.postgres.__main__ import main -from providers.scenarios import get_scenario_raw +from support.postgres import get_scenario_raw import socket COMMANDS = [ diff --git a/tests/support/__init__.py b/tests/support/__init__.py new file mode 100644 index 00000000..3ad07961 --- /dev/null +++ b/tests/support/__init__.py @@ -0,0 +1,2 @@ +# tests/support/__init__.py +"""Backend declarations and test helpers that are not fixtures.""" diff --git a/tests/support/postgres.py b/tests/support/postgres.py new file mode 100644 index 00000000..5d91b735 --- /dev/null +++ b/tests/support/postgres.py @@ -0,0 +1,131 @@ +# tests/support/postgres.py +"""The PostgreSQL backend's test scenarios. + +The scenario file holds server connection parameters only; the logical database +name comes from the test directory and is injected here. PostgreSQL is a +server backend, so a scenario maps to one database on one server. + +Maintenance work (dropping and creating databases, server-level checks) runs on +the ``postgres`` database every PostgreSQL instance ships with, because a +connection cannot drop the database it is currently using. +""" + +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict + +import yaml + +from rhosocial.activerecord.backend.impl.postgres.backend import ( + AsyncPostgresBackend, + PostgresBackend, +) +from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType + +CONFIG_PATH = Path( + os.environ.get("POSTGRES_SCENARIOS_CONFIG_PATH") + or Path(__file__).resolve().parents[1] / "config" / "postgres_scenarios.yaml" +) + +# The scenario file describes a server, never a database: the logical name is +# derived from the test directory. A ``database`` key, if present, is dropped. +# ``enabled`` is a scenario toggle, not a connection parameter. +SERVER_ONLY_KEYS = ("database", "enabled") + +# The database every PostgreSQL server has, used for server-level connections. +MAINTENANCE_DATABASE = "postgres" + +DDL_OPTIONS = ExecutionOptions(stmt_type=StatementType.DDL) + + +def _load_scenarios(path: Path = CONFIG_PATH) -> Dict[str, Dict[str, Any]]: + """Load one server-parameter dict per scenario from the YAML file.""" + with open(path, "r", encoding="utf-8") as file: + data = yaml.safe_load(file) or {} + entries = data.get("scenarios") + if not entries: + raise ValueError(f"{path} defines no scenarios") + return { + name: {key: value for key, value in entry.items() if key not in SERVER_ONLY_KEYS} + for name, entry in entries.items() + } + + +SCENARIO_MAP = _load_scenarios() +SCENARIOS = tuple(SCENARIO_MAP) + + +def _identifier(name: str) -> str: + """Quote a PostgreSQL identifier (database names come from the testsuite).""" + return '"' + name.replace('"', '""') + '"' + + +@dataclass(frozen=True) +class PostgresScenario: + """One PostgreSQL test scenario: a server plus the backend classes.""" + + name: str + server: Dict[str, Any] + backend_class: Any = PostgresBackend + async_backend_class: Any = AsyncPostgresBackend + maintenance_database: str = "postgres" + + def make_config(self, database: str) -> PostgresConnectionConfig: + """Return the connection configuration for this database on this server.""" + return PostgresConnectionConfig(**self.server, database=database) + + def reset_database(self, database: str) -> None: + """Drop and recreate ``database`` on this scenario's server.""" + backend = self.backend_class( + connection_config=PostgresConnectionConfig(**self.server, database=MAINTENANCE_DATABASE) + ) + backend.connect() + try: + backend.execute( + f"DROP DATABASE IF EXISTS {_identifier(database)}", + (), + options=DDL_OPTIONS, + ) + backend.execute( + f"CREATE DATABASE {_identifier(database)}", + (), + options=DDL_OPTIONS, + ) + finally: + backend.disconnect() + + +def scenario(name: str) -> PostgresScenario: + """Return the scenario called ``name``.""" + try: + server = SCENARIO_MAP[name] + except KeyError: + raise KeyError(f"Unknown PostgreSQL scenario: {name}") from None + return PostgresScenario(name, server) + + +def get_enabled_scenarios(): + """Return the scenarios this backend enables, as a name -> server map.""" + return {name: dict(server) for name, server in SCENARIO_MAP.items()} + + +def get_scenario(name: str): + """Return ``(backend_class, config)`` for a benchmark database.""" + current = scenario(name) + current.reset_database("test_benchmark") + return current.backend_class, current.make_config("test_benchmark") + + +def get_scenario_raw(name: str): + """Return ``(backend_class, config)`` for a server-level connection. + + Falls back to the first configured scenario when CI enables only one. + """ + resolved = name if name in SCENARIO_MAP else next(iter(SCENARIO_MAP), None) + if resolved is None: + raise KeyError("No %s scenario configured" % name) + current = scenario(resolved) + return current.backend_class, current.make_config(MAINTENANCE_DATABASE) From 772f743440da11c7d5ed5ffaaa9674119bed76dc Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 03:08:00 +0800 Subject: [PATCH 02/81] feat(postgres)!: directory-owned fixtures and expression DDL - basic/core, query/collation and connection now own their databases (session database_config/database) and build their tables per test from dialect-only definition classes; no raw SQL remains in those directories - the connection pool tables moved into pool_definitions.py (SERIAL preserved) - the neutral-adapter work and the benchmark relation fixture are included --- .../impl/postgres/adapters/__init__.py | 15 + .../backend/impl/postgres/adapters/base.py | 57 +- .../backend/impl/postgres/adapters/json.py | 51 +- .../backend/impl/postgres/adapters/neutral.py | 699 ++++++++++++++++++ .../backend/impl/postgres/backend/base.py | 68 +- tests/benchmark/relation/conftest.py | 56 +- .../feature/adapters/conftest.py | 4 + .../feature/adapters/test_json_codec.py | 3 + .../feature/adapters/test_neutral_types.py | 3 + .../adapters/test_neutral_types_async.py | 3 + .../backend/adapters/native/conftest.py | 98 +++ .../backend/adapters/native/helpers.py | 70 ++ .../native/schema/extension_types.sql | 17 + .../adapters/native/schema/native_types.sql | 91 +++ .../adapters/native/test_native_arrays.py | 105 +++ .../native/test_native_bit_strings.py | 128 ++++ .../adapters/native/test_native_extensions.py | 169 +++++ .../adapters/native/test_native_full_text.py | 110 +++ .../adapters/native/test_native_geometric.py | 183 +++++ .../adapters/native/test_native_json_xml.py | 157 ++++ .../adapters/native/test_native_network.py | 169 +++++ .../adapters/native/test_native_ranges.py | 283 +++++++ .../adapters/native/test_native_remaining.py | 89 +++ .../native/test_native_wrapped_scalars.py | 242 ++++++ .../backend/adapters/test_json_adapters.py | 175 +++++ .../backend/adapters/test_neutral_adapters.py | 363 +++++++++ .../backend/core/test_get_type_adapters.py | 56 ++ .../feature/basic/core/conftest.py | 68 +- .../feature/connection/conftest.py | 153 ++-- .../feature/connection/pool_definitions.py | 146 ++++ .../feature/query/collation/conftest.py | 76 +- 31 files changed, 3748 insertions(+), 159 deletions(-) create mode 100644 src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py index 94afacfe..02cec9a4 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py @@ -87,6 +87,15 @@ # hstore types from .hstore import PostgresHstoreAdapter +# Neutral value adapters (core driver-independent types) +from .neutral import ( + PostgresNeutralBitStringAdapter, + PostgresNeutralGeometryAdapter, + PostgresNeutralMacAddressAdapter, + PostgresNeutralRangeAdapter, + PostgresNeutralVectorAdapter, +) + __all__ = [ # Basic types "PostgresListAdapter", @@ -126,4 +135,10 @@ "PostgresPostGISAdapter", # hstore types "PostgresHstoreAdapter", + # Neutral value adapters + "PostgresNeutralBitStringAdapter", + "PostgresNeutralGeometryAdapter", + "PostgresNeutralMacAddressAdapter", + "PostgresNeutralRangeAdapter", + "PostgresNeutralVectorAdapter", ] diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py index 27e10db3..fde3313e 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py @@ -7,7 +7,7 @@ import json from enum import Enum as PythonEnum -from typing import Any, Dict, List, Type, Union, Optional, Set, get_args, get_origin # noqa: F401 +from typing import Any, Callable, Dict, List, Type, Union, Optional, Set, get_args, get_origin # noqa: F401 from psycopg.types.json import Jsonb @@ -114,14 +114,48 @@ class PostgresJSONBAdapter(BaseSQLTypeAdapter): Note: psycopg automatically serializes/deserializes JSON, so dict <-> JSON. When reading from DB, psycopg returns dict. When target type is str, we need to serialize back to JSON string. + + The optional ``default`` and ``object_hook`` mirror their ``json.dumps`` / + ``json.loads`` namesakes: + + - ``default`` is forwarded to psycopg's dumper through the per-value + ``Jsonb(value, dumps)`` hook, so it is applied when psycopg serialises + the value (psycopg's global ``dumps`` is replaced, not bypassed). + - ``object_hook`` is applied with ``json.loads``. psycopg has already + decoded a JSONB column to ``dict``/``list`` by the time the adapter sees + it, so the already-decoded value is re-encoded and decoded again to run + the hook over every object, exactly as ``json.loads`` would. """ - def __init__(self): + def __init__( + self, + default: Optional[Callable[[Any], Any]] = None, + object_hook: Optional[Callable[[dict], Any]] = None, + ): super().__init__() + self.default = default + self.object_hook = object_hook self.register_type(dict, Jsonb) + def _dumps(self, value: Any) -> str: + """Serialise for psycopg, applying the configured ``default``.""" + return json.dumps(value, default=self.default) + + def _wrap(self, value: Any) -> Jsonb: + """Build the psycopg wrapper, wiring ``default`` into the dumper.""" + if self.default is None: + # Keep psycopg's default dumps function untouched. + return Jsonb(value) + return Jsonb(value, self._dumps) + + def _apply_object_hook(self, value: Any) -> Any: + """Run ``object_hook`` over an already-decoded JSON value.""" + if self.object_hook is None: + return value + return json.loads(json.dumps(value, default=self.default), object_hook=self.object_hook) + def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: - return Jsonb(value) + return self._wrap(value) def _do_from_database( self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None @@ -131,15 +165,16 @@ def _do_from_database( # but model fields may be defined as Optional[str] type if target_type is str: if isinstance(value, (dict, list)): - return json.dumps(value, ensure_ascii=False) + return json.dumps(value, ensure_ascii=False, default=self.default) return value - # For dict/list target types, return as-is + # For dict/list target types, return the decoded value (running the + # hook if one was configured against the already-decoded document) if isinstance(value, dict): - return value + return self._apply_object_hook(value) if isinstance(value, list): - return value + return self._apply_object_hook(value) # In case it's a string representation - return json.loads(value) + return json.loads(value, object_hook=self.object_hook) def to_database_batch( self, values: List[Any], target_type: Type, options: Optional[Dict[str, Any]] = None @@ -150,7 +185,7 @@ def to_database_batch( if value is None: result.append(None) else: - result.append(Jsonb(value)) + result.append(self._wrap(value)) return result def from_database_batch( @@ -163,11 +198,11 @@ def from_database_batch( result.append(None) elif target_type is str: if isinstance(value, (dict, list)): - result.append(json.dumps(value, ensure_ascii=False)) + result.append(json.dumps(value, ensure_ascii=False, default=self.default)) else: result.append(value) else: - result.append(value) + result.append(self._apply_object_hook(value)) return result diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py index db179ec9..af03c9be 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py @@ -16,7 +16,7 @@ """ import json -from typing import Any, Dict, List, Optional, Set, Type, Union, get_args, get_origin # noqa: F401 +from typing import Any, Callable, Dict, List, Optional, Set, Type, Union, get_args, get_origin # noqa: F401 from psycopg.types.json import Jsonb @@ -32,14 +32,48 @@ class PostgresJSONBAdapter(BaseSQLTypeAdapter): Note: psycopg automatically serializes/deserializes JSON, so dict <-> JSON. When reading from DB, psycopg returns dict. When target type is str, we need to serialize back to JSON string. + + The optional ``default`` and ``object_hook`` mirror their ``json.dumps`` / + ``json.loads`` namesakes: + + - ``default`` is forwarded to psycopg's dumper through the per-value + ``Jsonb(value, dumps)`` hook, so it is applied when psycopg serialises + the value (psycopg's global ``dumps`` is replaced, not bypassed). + - ``object_hook`` is applied with ``json.loads``. psycopg has already + decoded a JSONB column to ``dict``/``list`` by the time the adapter sees + it, so the already-decoded value is re-encoded and decoded again to run + the hook over every object, exactly as ``json.loads`` would. """ - def __init__(self): + def __init__( + self, + default: Optional[Callable[[Any], Any]] = None, + object_hook: Optional[Callable[[dict], Any]] = None, + ): super().__init__() + self.default = default + self.object_hook = object_hook self.register_type(dict, Jsonb) + def _dumps(self, value: Any) -> str: + """Serialise for psycopg, applying the configured ``default``.""" + return json.dumps(value, default=self.default) + + def _wrap(self, value: Any) -> Jsonb: + """Build the psycopg wrapper, wiring ``default`` into the dumper.""" + if self.default is None: + # Keep psycopg's default dumps function untouched. + return Jsonb(value) + return Jsonb(value, self._dumps) + + def _apply_object_hook(self, value: Any) -> Any: + """Run ``object_hook`` over an already-decoded JSON value.""" + if self.object_hook is None: + return value + return json.loads(json.dumps(value, default=self.default), object_hook=self.object_hook) + def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: - return Jsonb(value) + return self._wrap(value) def _do_from_database( self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None @@ -49,15 +83,16 @@ def _do_from_database( # but model fields may be defined as Optional[str] type if target_type is str: if isinstance(value, (dict, list)): - return json.dumps(value, ensure_ascii=False) + return json.dumps(value, ensure_ascii=False, default=self.default) return value - # For dict/list target types, return as-is + # For dict/list target types, return the decoded value (running the + # hook if one was configured against the already-decoded document) if isinstance(value, dict): - return value + return self._apply_object_hook(value) if isinstance(value, list): - return value + return self._apply_object_hook(value) # In case it's a string representation - return json.loads(value) + return json.loads(value, object_hook=self.object_hook) class PostgresJsonPathAdapter: diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py new file mode 100644 index 00000000..30a5d8ae --- /dev/null +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py @@ -0,0 +1,699 @@ +# src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py +"""PostgreSQL value adapters for the core neutral types. + +The adapters in this module speak the driver-independent types from +``rhosocial.activerecord.backend.adapters`` only: :class:`Geometry`, +:class:`Vector`, :class:`BitString`, :class:`Range`, :class:`Multirange`, and +:class:`MacAddress`. They are deliberately separate from the backend-native +adapters already exported by this package (``PostgresPostGISAdapter``, +``PostgresVectorAdapter``, ``PostgresBitStringAdapter``, ``PostgresRangeAdapter``, +``PostgresMacaddrAdapter``), whose Python surface is the PostgreSQL wrapper +types (``PostgresGeometry``, ``PostgresVector`` ...). Keeping both lets an +existing application keep its wrapper types while a new application can opt +into the neutral ones. + +Wire formats: + +- geometry / geography: plain WKT, or ``SRID=n;WKT`` (EWKT) when the geometry + carries an SRID. Both types accept that text form, so one adapter serves + both. EWKB hex output is not decoded: select ``ST_AsEWKT``/``ST_AsText`` + when reading. +- pgvector ``vector``: ``[v1,v2,...]``. +- ``bit`` / ``varbit``: the binary digits accepted by the bit input function. + ``options={"literal": True}`` produces the SQL literal form ``B'1010'``, + which is an expression rather than a bind parameter. +- range / multirange: the PostgreSQL range literal produced by + ``to_postgres_literal()`` (bare numeric bounds, double-quoted text/temporal + bounds). +- ``macaddr`` / ``macaddr8``: the canonical lowercase colon-separated form. +""" + +from __future__ import annotations + +import math +import re +from datetime import date, datetime, time +from decimal import Decimal, InvalidOperation +from typing import Any, Dict, List, Optional, Tuple, Type + +from rhosocial.activerecord.backend.adapters import ( + BitString, + BitStringAdapterBase, + Geometry, + GeometryAdapterBase, + MacAddress, + MacAddressAdapterBase, + Multirange, + Range, + RangeAdapterBase, + Vector, + VectorAdapterBase, +) + +from ..type_values.bit_string import PostgresBitString +from ..type_values.network_address import PostgresMacaddr, PostgresMacaddr8 +from ..type_values.pgvector import PostgresVector +from ..type_values.postgis import PostgresGeometry +from ..type_values.range import PostgresMultirange, PostgresRange + +_HEX_TEXT_RE = re.compile(r"^(?:0[xX])?[0-9A-Fa-f]+$") +_INT_TEXT_RE = re.compile(r"^[+-]?\d+$") +_NUMBER_TEXT_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$") +_NON_FINITE_NAMES = { + "nan": float("nan"), + "infinity": float("inf"), + "+infinity": float("inf"), + "inf": float("inf"), + "-infinity": float("-inf"), + "-inf": float("-inf"), +} + +#: SQL range type names mapped onto the neutral range element labels. +_RANGE_TYPE_LABELS = { + "int4range": "int", + "int8range": "int", + "numrange": "decimal", + "tsrange": "datetime", + "tstzrange": "datetime", + "daterange": "date", + "timerange": "time", + "timetzrange": "time", +} +#: Labels the neutral range decoder knows how to turn into Python values. +_RANGE_ELEMENT_LABELS = frozenset(("int", "float", "decimal", "datetime", "date", "time", "str")) +_ELEMENT_TYPE_ALIASES = { + "integer": "int", + "bigint": "int", + "smallint": "int", + "numeric": "decimal", + "number": "decimal", + "double": "float", + "double precision": "float", + "real": "float", + "timestamp": "datetime", + "timestamptz": "datetime", + "timestamp with time zone": "datetime", + "timestamp without time zone": "datetime", + "date": "date", + "time": "time", + "timetz": "time", + "text": "str", + "varchar": "str", + "character varying": "str", +} + + +# --- Geometry -------------------------------------------------------------- + + +def _looks_like_ewkb_hex(text: str) -> bool: + """Return whether ``text`` is PostGIS's default hex EWKB output.""" + return bool(_HEX_TEXT_RE.match(text)) and len(text) >= 10 + + +class PostgresNeutralGeometryAdapter(GeometryAdapterBase): + """Encode neutral geometries as WKT/EWKT for ``geometry``/``geography``. + + The wire format is text because both PostGIS types accept EWKT text and + psycopg binds text parameters without a driver-specific wrapper. On read, + WKT, EWKT and the backend wrapper :class:`PostgresGeometry` are accepted. + Hex EWKB output is rejected with an explicit message: requesting + ``ST_AsEWKT`` or ``ST_AsText`` is the caller's responsibility, and silently + guessing at the binary encoding would be worse than failing. + + ``options``: + + - ``srid``: overrides the geometry's own SRID in the emitted EWKT prefix. + """ + + def __init__(self) -> None: + super().__init__() + self.register_type(Geometry, str) + + def _encode(self, geometry: Geometry, target_type: Type, options: Dict[str, Any]) -> str: + if target_type is not str: + raise TypeError("PostgreSQL geometry/geography binds as text; target_type must be str") + + srid = options.get("srid", geometry.srid) + if srid is not None: + srid = int(srid) + return "SRID={};{}".format(srid, geometry.to_wkt()) + return geometry.to_wkt() + + def _decode(self, value: Any, options: Dict[str, Any]) -> Geometry: + if isinstance(value, Geometry) and type(value) is not Geometry: + return value + if isinstance(value, PostgresGeometry): + return Geometry.from_wkt(value.wkt, srid=value.srid) + if isinstance(value, str): + text = value.strip() + if _looks_like_ewkb_hex(text): + raise ValueError( + "PostGIS returned hex EWKB, which this adapter does not decode; " + "select ST_AsEWKT or ST_AsText instead" + ) + return Geometry.from_wkt(text) + raise TypeError( + "PostgreSQL geometry/geography must decode from WKT/EWKT text or " + "PostgresGeometry, got {}".format(type(value).__name__) + ) + + +# --- Vector ---------------------------------------------------------------- + + +def _format_vector_component(value: Any) -> str: + """Render one component in the pgvector text form.""" + if isinstance(value, float) and not math.isfinite(value): + if math.isnan(value): + return "NaN" + return "Infinity" if value > 0 else "-Infinity" + return repr(value) + + +def _parse_vector_text(text: str) -> Vector: + """Parse the pgvector ``[v1,v2,...]`` text form into a neutral vector.""" + stripped = text.strip() + if not stripped.startswith("[") or not stripped.endswith("]"): + raise ValueError("pgvector text must look like [v1,v2,...]") + inner = stripped[1:-1].strip() + if not inner: + raise ValueError("pgvector text must contain at least one component") + + values: List[float] = [] + allow_non_finite = False + for part in inner.split(","): + token = part.strip() + if not token: + raise ValueError("pgvector text contains an empty component") + lower = token.lower() + if lower in _NON_FINITE_NAMES: + values.append(_NON_FINITE_NAMES[lower]) + allow_non_finite = True + continue + try: + number = float(token) + except ValueError: + raise ValueError("invalid pgvector component: {!r}".format(token)) from None + if not math.isfinite(number): + allow_non_finite = True + values.append(number) + + return Vector(tuple(values), allow_non_finite=allow_non_finite) + + +class PostgresNeutralVectorAdapter(VectorAdapterBase): + """Encode neutral vectors as pgvector text. + + The text form ``[v1,v2,...]`` is accepted by the ``vector`` type's input + function, so it is bindable as a plain string parameter. + ``halfvec``/``sparsevec`` are not served: they have different wire formats + and are still gaps in the backend's coverage. + """ + + def __init__(self) -> None: + super().__init__() + self.register_type(Vector, str) + + def _encode(self, vector: Vector, target_type: Type, options: Optional[Dict[str, Any]]) -> str: + if target_type is not str: + raise TypeError("pgvector binds as text; target_type must be str") + return "[{}]".format(",".join(_format_vector_component(v) for v in vector.values)) + + def _decode(self, value: Any, options: Optional[Dict[str, Any]]) -> Vector: + if isinstance(value, Vector): + return value + if isinstance(value, PostgresVector): + return Vector(tuple(value.values)) + if isinstance(value, str): + return _parse_vector_text(value) + if isinstance(value, (list, tuple)): + return Vector.from_json_value(list(value)) + raise TypeError( + "pgvector must decode from text, a sequence, or PostgresVector, got " + "{}".format(type(value).__name__) + ) + + +# --- Bit string ------------------------------------------------------------ + + +def _declared_bit_length(options: Optional[Dict[str, Any]]) -> Optional[int]: + """Read the column's declared bit length from the adapter options.""" + if not options: + return None + for key in ("bit_length", "length"): + raw = options.get(key) + if raw is None: + continue + if isinstance(raw, bool) or not isinstance(raw, int): + raise ValueError("{} must be int, got {}".format(key, type(raw).__name__)) + if raw < 1: + raise ValueError("{} must be at least 1, got {}".format(key, raw)) + return raw + return None + + +def _parse_bit_text(text: str) -> str: + """Return the binary digits of a bit string value.""" + stripped = text.strip() + if len(stripped) >= 3 and stripped[0] in ("B", "b") and stripped[1] == "'": + if not stripped.endswith("'"): + raise ValueError("unterminated B'...' bit string") + stripped = stripped[2:-1] + if not stripped: + raise ValueError("bit string text must not be empty") + if any(char not in "01" for char in stripped): + raise ValueError("bit string text may only contain '0' and '1'") + return stripped + + +class PostgresNeutralBitStringAdapter(BitStringAdapterBase): + """Encode neutral bit strings for PostgreSQL ``bit``/``varbit``. + + The default encoding is the bare binary digits (``"1010"``), which the + bit input function accepts for a text-bound parameter. A literal + ``B'1010'`` is SQL syntax, not a bind parameter, so it is only produced + when ``options={"literal": True}`` is requested explicitly. + + Reading recovers the declared length from ``options["bit_length"]`` (or + ``options["length"]``) when the column is fixed-width; otherwise the + length is taken from the returned text. A shorter text is right-padded + with zeros to the declared length, matching ``bit(n)`` casting rules. + """ + + def __init__(self) -> None: + super().__init__() + self.register_type(BitString, str) + + def _encode(self, bits: BitString, target_type: Type, options: Optional[Dict[str, Any]]) -> str: + if target_type is not str: + raise TypeError("PostgreSQL bit/varbit binds as text; target_type must be str") + text = bits.to_bits() + if options and options.get("literal"): + return "B'{}'".format(text) + return text + + def _decode(self, value: Any, options: Optional[Dict[str, Any]]) -> BitString: + if isinstance(value, BitString): + return value + declared = _declared_bit_length(options) + + if isinstance(value, PostgresBitString): + text = value.bits + if declared is None and value.length is not None: + declared = value.length + elif isinstance(value, str): + text = _parse_bit_text(value) + elif isinstance(value, (bytes, bytearray)): + raw = bytes(value) + if not raw: + raise ValueError("bit string bytes must not be empty") + return BitString.from_bytes(raw, declared) + elif isinstance(value, int) and not isinstance(value, bool): + length = declared + if length is None: + length = max(1, value.bit_length()) + return BitString.from_int(value, length) + else: + raise TypeError( + "PostgreSQL bit/varbit must decode from text, bytes, int, or " + "PostgresBitString, got {}".format(type(value).__name__) + ) + + if declared is not None: + if len(text) > declared: + raise ValueError( + "bit string text has {} bits, more than the declared {}".format( + len(text), declared + ) + ) + text = text + "0" * (declared - len(text)) + return BitString.from_bits(text) + + +# --- Range / multirange ---------------------------------------------------- + + +def _element_label(options: Optional[Dict[str, Any]]) -> Optional[str]: + """Resolve the neutral range element label from adapter options.""" + if not options: + return None + for key in ("element_type", "range_type", "subtype"): + raw = options.get(key) + if raw is None: + continue + if not isinstance(raw, str): + raise ValueError("{} must be str, got {}".format(key, type(raw).__name__)) + name = raw.strip().lower() + if name in _RANGE_TYPE_LABELS: + return _RANGE_TYPE_LABELS[name] + label = _ELEMENT_TYPE_ALIASES.get(name, name) + if label not in _RANGE_ELEMENT_LABELS: + raise ValueError( + "unsupported range element type hint {!r}; known labels are {}".format( + raw, ", ".join(sorted(_RANGE_ELEMENT_LABELS)) + ) + ) + return label + return None + + +def _split_range_parts(text: str, separator: str = ",") -> List[str]: + """Split a range/multirange body on top-level separators. + + Brackets nest and quoted bounds shield commas, backslashes and brackets. + PostgreSQL quotes a bound that contains whitespace, a bracket, a comma, + a double quote or a backslash, and escapes ``"``/``\\`` with a backslash. + Doubled quotes are also accepted, as some callers spell them that way. + """ + parts: List[str] = [] + buffer: List[str] = [] + in_quote = False + depth = 0 + index = 0 + while index < len(text): + char = text[index] + if in_quote: + if char == "\\" and index + 1 < len(text): + buffer.append(char) + buffer.append(text[index + 1]) + index += 2 + continue + if char == '"': + if index + 1 < len(text) and text[index + 1] == '"': + buffer.append('""') + index += 2 + continue + in_quote = False + buffer.append(char) + index += 1 + continue + + if char == '"': + in_quote = True + buffer.append(char) + elif char in "([{": + depth += 1 + buffer.append(char) + elif char in ")]}": + if depth == 0: + raise ValueError("unbalanced closing bracket in range literal") + depth -= 1 + buffer.append(char) + elif char == separator and depth == 0: + parts.append("".join(buffer)) + buffer = [] + else: + buffer.append(char) + index += 1 + + if in_quote: + raise ValueError("unterminated quoted range bound") + if depth != 0: + raise ValueError("unbalanced brackets in range literal") + parts.append("".join(buffer)) + return parts + + +def _unquote_bound(text: str) -> Tuple[str, bool]: + """Return the raw bound text and whether it was quoted.""" + text = text.strip() + if not text.startswith('"'): + return text, False + if len(text) < 2 or not text.endswith('"'): + raise ValueError("unterminated quoted range bound") + + characters: List[str] = [] + index = 1 + end = len(text) - 1 + while index < end: + char = text[index] + if char == "\\": + if index + 1 >= end: + raise ValueError("dangling escape in quoted range bound") + characters.append(text[index + 1]) + index += 2 + continue + if char == '"': + if index + 1 < end and text[index + 1] == '"': + characters.append('"') + index += 2 + continue + raise ValueError("unescaped quote inside a quoted range bound") + characters.append(char) + index += 1 + return "".join(characters), True + + +def _parse_element(text: str, label: Optional[str]) -> Any: + """Convert one bound token to its Python value.""" + if label == "datetime": + try: + return datetime.fromisoformat(text) + except ValueError: + raise ValueError("invalid datetime range bound: {!r}".format(text)) from None + if label == "date": + try: + return date.fromisoformat(text) + except ValueError: + raise ValueError("invalid date range bound: {!r}".format(text)) from None + if label == "time": + try: + return time.fromisoformat(text) + except ValueError: + raise ValueError("invalid time range bound: {!r}".format(text)) from None + if label == "int": + if not _INT_TEXT_RE.match(text): + raise ValueError("invalid integer range bound: {!r}".format(text)) + return int(text) + if label == "decimal": + try: + return Decimal(text) + except (InvalidOperation, ValueError): + raise ValueError("invalid decimal range bound: {!r}".format(text)) from None + if label == "float": + try: + return float(text) + except ValueError: + raise ValueError("invalid float range bound: {!r}".format(text)) from None + if label == "str": + return text + + # No label: infer the narrowest lossless type from the token. + lower = text.lower() + if lower in _NON_FINITE_NAMES: + return _NON_FINITE_NAMES[lower] + if _INT_TEXT_RE.match(text): + return int(text) + if _NUMBER_TEXT_RE.match(text): + try: + return Decimal(text) + except InvalidOperation: + return text + return text + + +def _parse_range_literal(text: str, options: Optional[Dict[str, Any]]) -> Range: + """Parse one PostgreSQL range literal into a neutral range.""" + stripped = text.strip() + if not stripped: + raise ValueError("range literal is empty") + if stripped.lower() == "empty": + return Range(None, None, "[)", True) + if len(stripped) < 2: + raise ValueError("range literal is too short: {!r}".format(stripped)) + + lower_bracket = stripped[0] + upper_bracket = stripped[-1] + if lower_bracket not in "[(": + raise ValueError("invalid lower bound bracket: {!r}".format(lower_bracket)) + if upper_bracket not in "])": + raise ValueError("invalid upper bound bracket: {!r}".format(upper_bracket)) + + body = stripped[1:-1] + parts = _split_range_parts(body) + if len(parts) != 2: + raise ValueError( + "range literal must have exactly one bound separator, got {}".format(len(parts)) + ) + + label = _element_label(options) + lower_text, _ = _unquote_bound(parts[0]) + upper_text, _ = _unquote_bound(parts[1]) + + lower = _parse_element(lower_text, label) if lower_text else None + upper = _parse_element(upper_text, label) if upper_text else None + + # PostgreSQL canonical output uses '(' for an infinite bound: normalize + # so an input such as '[,5]' does not produce a non-canonical neutral value. + if lower is None: + lower_bracket = "(" + if upper is None: + upper_bracket = ")" + + return Range(lower, upper, lower_bracket + upper_bracket, False) + + +def _parse_multirange_literal(text: str, options: Optional[Dict[str, Any]]) -> Multirange: + """Parse one PostgreSQL multirange literal into a neutral multirange.""" + stripped = text.strip() + if not stripped.startswith("{") or not stripped.endswith("}"): + raise ValueError("multirange literal must be enclosed in braces: {!r}".format(stripped)) + body = stripped[1:-1] + if not body.strip(): + return Multirange(()) + pieces = [piece for piece in _split_range_parts(body) if piece.strip()] + return Multirange(tuple(_parse_range_literal(piece, options) for piece in pieces)) + + +def _neutral_range_from_parts( + lower: Any, upper: Any, lower_inc: bool, upper_inc: bool, empty: bool +) -> Range: + """Build a neutral range from a backend range's parts.""" + if empty: + return Range(None, None, "[)", True) + lower_bracket = "[" if (lower is not None and lower_inc) else "(" + upper_bracket = "]" if (upper is not None and upper_inc) else ")" + return Range(lower, upper, lower_bracket + upper_bracket, False) + + +def _is_range_like(value: Any) -> bool: + """Return whether ``value`` looks like a driver/backend range object.""" + return all(hasattr(value, name) for name in ("lower", "upper", "bounds")) + + +def _decode_range_like(value: Any) -> Range: + """Convert a psycopg-like range object into a neutral range.""" + empty = bool(getattr(value, "isempty", False) or getattr(value, "empty", False)) + bounds = getattr(value, "bounds", "[)") or "[)" + return _neutral_range_from_parts( + getattr(value, "lower", None), + getattr(value, "upper", None), + bounds[0] == "[", + len(bounds) > 1 and bounds[1] == "]", + empty, + ) + + +class PostgresNeutralRangeAdapter(RangeAdapterBase): + """Encode and decode neutral ``Range``/``Multirange`` values. + + Writes delegate wholly to the neutral literal renderers + (``to_postgres_literal``), which now produce PostgreSQL's native range + syntax: numeric bounds are bare and text/temporal bounds are double-quoted + with ``"``/``\\`` escaped. Reads accept the PostgreSQL literal text, the + backend wrappers ``PostgresRange`` / ``PostgresMultirange``, psycopg's + range objects, and sequences of psycopg-like ranges. + + Text parsing cannot recover an element type by itself. Unquoted numbers + become ``int``/``Decimal`` and quoted bounds stay ``str`` unless the caller + passes ``options={"element_type": "date", ...}`` or + ``options={"range_type": "daterange"}``. Without that hint, a quoted + ``"2024-01-01"`` remains a string; this is a documented limitation of + parsing PostgreSQL's text output, not a silent conversion. + """ + + def __init__(self) -> None: + super().__init__() + self.register_type(Range, str) + self.register_type(Multirange, str) + + def _encode(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]]) -> str: + if target_type is not str: + raise TypeError("PostgreSQL range/multirange binds as text; target_type must be str") + return value.to_postgres_literal() + + def _decode(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]]) -> Any: + if isinstance(value, (Range, Multirange)): + return value + if isinstance(value, PostgresRange): + return _neutral_range_from_parts( + value.lower, value.upper, value.lower_inc, value.upper_inc, value.is_empty + ) + if isinstance(value, PostgresMultirange): + return Multirange( + tuple( + _neutral_range_from_parts( + item.lower, + item.upper, + item.lower_inc, + item.upper_inc, + item.is_empty, + ) + for item in value.ranges + ) + ) + if _is_range_like(value): + return _decode_range_like(value) + if isinstance(value, (list, tuple)): + if not value: + return Multirange(()) + if all(_is_range_like(item) for item in value): + return Multirange(tuple(_decode_range_like(item) for item in value)) + raise TypeError("a sequence of ranges must contain range objects") + if isinstance(value, str): + text = value.strip() + if text.startswith("{"): + return _parse_multirange_literal(text, options) + return _parse_range_literal(text, options) + raise TypeError( + "PostgreSQL range/multirange must decode from text, a backend/driver " + "range, or a sequence of ranges, got {}".format(type(value).__name__) + ) + + +# --- MAC address ----------------------------------------------------------- + + +def _canonical_mac(mac: MacAddress) -> str: + return ":".join("{:02x}".format(octet) for octet in mac.octets) + + +class PostgresNeutralMacAddressAdapter(MacAddressAdapterBase): + """Encode neutral MAC addresses as canonical ``macaddr``/``macaddr8`` text. + + PostgreSQL accepts the lowercase colon-separated form for both types. + ``options={"eui64": True}`` (or ``{"version": 8}``) expands a 6-octet + address into the EUI-64 form (inserting ``ff:fe`` after the third octet) + before writing it to a ``macaddr8`` column; without that option the + canonical 6-octet text is emitted and the server performs its own + ``macaddr8`` conversion. + """ + + def __init__(self) -> None: + super().__init__() + self.register_type(MacAddress, str) + + def _encode(self, mac: MacAddress, target_type: Type, options: Optional[Dict[str, Any]]) -> str: + if target_type is not str: + raise TypeError("PostgreSQL macaddr binds as text; target_type must be str") + options = options or {} + eui64 = options.get("eui64", False) + if "version" in options: + eui64 = eui64 or int(options["version"]) >= 8 + if eui64 and len(mac.octets) == 6: + octets = mac.octets[:3] + b"\xff\xfe" + mac.octets[3:] + return ":".join("{:02x}".format(octet) for octet in octets) + return _canonical_mac(mac) + + def _decode(self, value: Any, options: Optional[Dict[str, Any]]) -> MacAddress: + if isinstance(value, MacAddress): + return value + if isinstance(value, (PostgresMacaddr, PostgresMacaddr8)): + return MacAddress.parse(str(value)) + if isinstance(value, (str, bytes, bytearray)): + return MacAddress.parse(value) + raise TypeError( + "PostgreSQL macaddr must decode from text, bytes, or a backend MAC " + "wrapper, got {}".format(type(value).__name__) + ) + + +__all__ = [ + "PostgresNeutralBitStringAdapter", + "PostgresNeutralGeometryAdapter", + "PostgresNeutralMacAddressAdapter", + "PostgresNeutralRangeAdapter", + "PostgresNeutralVectorAdapter", +] diff --git a/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py b/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py index 56ae2ca3..4b579579 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py @@ -5,7 +5,7 @@ containing methods that are shared between sync and async backends. """ -from typing import Dict, Optional, Tuple, Type, TYPE_CHECKING +from typing import Dict, List, Optional, Tuple, Type, TYPE_CHECKING import logging from psycopg.errors import ( @@ -275,6 +275,11 @@ def _register_postgres_adapters(self): PostgresEnumAdapter, PostgresRangeAdapter, PostgresMultirangeAdapter, + PostgresNeutralBitStringAdapter, + PostgresNeutralGeometryAdapter, + PostgresNeutralMacAddressAdapter, + PostgresNeutralRangeAdapter, + PostgresNeutralVectorAdapter, ) from ..adapters.geometric import PostgresGeometryAdapter from ..adapters.monetary import PostgresMoneyAdapter @@ -317,6 +322,21 @@ def _register_postgres_adapters(self): adapter, py_type, db_type, allow_override=True ) + # Neutral value adapters are keyed by the core neutral Python types + # (Geometry, Vector, ...), so they never collide with the backend + # wrapper adapters above and are always available to the catalogue. + neutral_adapters = [ + PostgresNeutralGeometryAdapter(), + PostgresNeutralVectorAdapter(), + PostgresNeutralBitStringAdapter(), + PostgresNeutralRangeAdapter(), + PostgresNeutralMacAddressAdapter(), + ] + for adapter in neutral_adapters: + for py_type, db_types in adapter.supported_types.items(): + for db_type in db_types: + self.adapter_registry.register(adapter, py_type, db_type, allow_override=True) + # Register Range adapters based on configuration range_mode = getattr(self.config, "range_adapter_mode", RangeAdapterMode.NATIVE) if range_mode in (RangeAdapterMode.CUSTOM, RangeAdapterMode.BOTH): @@ -340,6 +360,25 @@ def _register_postgres_adapters(self): self.log(logging.DEBUG, "Registered PostgreSQL-specific type adapters") + def get_type_adapters(self) -> List["SQLTypeAdapter"]: + """Return the adapter instances this backend provides. + + This is a plain inventory: it says which adapters exist for this backend. + It carries no suggestion/default/priority semantics; the caller decides. + + The inventory is deduplicated by adapter class (module + qualname) and + sorted by ``(module, qualname)``, so the order is deterministic and a + fresh list is returned on every call. + """ + adapters: List["SQLTypeAdapter"] = list(self.adapter_registry.get_all_adapters().values()) + + unique: Dict[Tuple[str, str], "SQLTypeAdapter"] = {} + for adapter in adapters: + adapter_class = type(adapter) + unique.setdefault((adapter_class.__module__, adapter_class.__qualname__), adapter) + + return [unique[key] for key in sorted(unique)] + def _is_connection_error(self, error: Exception) -> bool: """Check if an error indicates a connection loss. @@ -439,7 +478,7 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple["SQLTypeAdapter", mapping conflicts with the base string handling. Users must explicitly specify adapters for these types when needed. """ - suggestions: Dict[Type, Tuple["SQLTypeAdapter", Type]] = {} + base = super().get_default_adapter_suggestions() # Define a list of desired Python type to DB driver type mappings. # This list reflects types seen in test fixtures and common usage, @@ -461,6 +500,14 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple["SQLTypeAdapter", # Import PostgreSQL-specific types from ..type_values.range import PostgresRange, PostgresMultirange from ..type_values.geometric import Point, Line, LineSegment, Box, Path, Polygon, Circle + from rhosocial.activerecord.backend.adapters.bitstring import BitString + from rhosocial.activerecord.backend.adapters.geometry import Geometry + from rhosocial.activerecord.backend.adapters.network import MacAddress + from rhosocial.activerecord.backend.adapters.range import Multirange, Range + from rhosocial.activerecord.backend.adapters.vector import Vector + from rhosocial.activerecord.backend.base.type_adaption import ( + merge_adapter_suggestions, + ) from ..type_values.text_search import PostgresTsVector, PostgresTsQuery from ..type_values.monetary import PostgresMoney from ..type_values.network_address import PostgresMacaddr, PostgresMacaddr8 @@ -541,18 +588,23 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple["SQLTypeAdapter", (CID, int), # Command identifier # === PostgreSQL Tuple Identifier === (TID, str), # Tuple identifier (block number, offset) + # === Neutral families (text/wire forms in this backend's adapters) === + (Geometry, str), # WKT/EWKT text (covers the seven concrete shapes) + (Vector, str), # pgvector text input, e.g. ``[1.0,2.0]`` + (BitString, str), # ``bit``/``varbit`` binary-digit text + (Range, str), # PostgreSQL range literal + (Multirange, str), # PostgreSQL multirange literal + (MacAddress, str), # canonical lowercase colon text # Note: PostgresXML and PostgresBitString are NOT included here # because they both map to str, which conflicts with base string handling. # Users must explicitly specify adapters for these types. ] - # Iterate through the defined mappings and retrieve adapters from the registry. + suggestions = merge_adapter_suggestions(base, type_mappings, self.adapter_registry) + + # Report any mapping this backend's registry cannot satisfy. for py_type, db_type in type_mappings: - adapter = self.adapter_registry.get_adapter(py_type, db_type) - if adapter: - suggestions[py_type] = (adapter, db_type) - else: - # Log a debug message if a specific adapter is expected but not found. + if py_type not in suggestions: self.log( logging.DEBUG, f"No adapter found for ({py_type.__name__}, {db_type.__name__}). " diff --git a/tests/benchmark/relation/conftest.py b/tests/benchmark/relation/conftest.py index 6076e4a1..5cb5bf53 100644 --- a/tests/benchmark/relation/conftest.py +++ b/tests/benchmark/relation/conftest.py @@ -7,6 +7,15 @@ source snippets are kept as comments for follow-up external cache design. """ +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.testsuite.feature.relation.fixtures.definitions import ( + CommentDefinition, + PostDefinition, + UserDefinition, +) + + from dataclasses import dataclass from typing import Any @@ -21,23 +30,13 @@ from rhosocial.activerecord.testsuite.feature.relation.conftest import ( # noqa: F401 user_post_comment_classes, ) -from rhosocial.activerecord.testsuite.feature.relation.fixtures import tables -GROUP_TABLES = ("users", "posts", "comments") -def ensure_database(environment): - environment.reset_database() -def prepare(environment): - for name in GROUP_TABLES: - environment.execute(tables.RELATION_TABLES[name](environment.dialect)) -def teardown(environment): - for name in reversed(GROUP_TABLES): - environment.execute(tables.drop_table(environment.dialect, name)) pytestmark = [ @@ -174,3 +173,40 @@ def relation_benchmark_env(cache_scenario, _raw_models): ) finally: InstanceCache.set_backend(original_backend) + +DDL = ExecutionOptions(stmt_type=StatementType.DDL) +DEFINITIONS = (UserDefinition, PostDefinition, CommentDefinition) + + +@pytest.fixture(scope="session") +def database_config(backend_scenario): + """The scenario, its connection configuration, and the database name.""" + name = "test_benchmark_relation" + return backend_scenario, backend_scenario.make_config(name), name + + +@pytest.fixture(scope="session") +def database(database_config): + """The benchmark directory's database, prepared once.""" + scenario, config, name = database_config + scenario.reset_database(name) + backend = scenario.backend_class(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + yield backend + backend.disconnect() + + +@pytest.fixture(scope="module", autouse=True) +def schema(database): + """Create the relation tables once per module. + + Benchmarks measure query cost, not per-test isolation, so the exception to + the per-test drop+create rule applies here. + """ + fixtures = [definition(database.dialect) for definition in DEFINITIONS] + for fixture in fixtures: + database.execute(*fixture.create_table.to_sql(), options=DDL) + yield + for fixture in reversed(fixtures): + database.execute(*fixture.drop_table.to_sql(), options=DDL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py new file mode 100644 index 00000000..f28fe7b2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py + +"""Use the shared ``feature/adapters`` directory contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py new file mode 100644 index 00000000..c79f4a67 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py +"""Bridge file: runs the shared testsuite neutral-type contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.test_json_codec import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py new file mode 100644 index 00000000..b9fa5525 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py +"""Bridge file: runs the shared testsuite neutral-type contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py new file mode 100644 index 00000000..51ef35f3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py +"""Bridge file: runs the shared testsuite neutral-type contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py new file mode 100644 index 00000000..1e2a57e3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -0,0 +1,98 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +"""Fixtures for the PostgreSQL native type tests. + +The directory owns one logical database (``test_backend_adapters_native``), +so a test class opens one connection and creates its tables once. Each module +declares the tables it needs in ``TABLES``; only those ``CREATE TABLE`` +statements are executed from ``schema/native_types.sql``. That keeps a +targeted run inside the remote-latency budget and keeps the statements shared +between modules in one visible place. + +Extension tables live in ``schema/extension_types.sql`` and are only created +by a class fixture that has already established the extension exists. +""" + +import re +from pathlib import Path + +import pytest + +SCHEMA_DIR = Path(__file__).parent / "schema" +BUILTIN_SCHEMA = SCHEMA_DIR / "native_types.sql" +EXTENSION_SCHEMA = SCHEMA_DIR / "extension_types.sql" + + +def _statements(path): + """Return the non-empty statements of a small SQL script.""" + text = path.read_text(encoding="utf-8") + text = re.sub(r"--[^\n]*", "", text) + return [part.strip() for part in text.split(";") if part.strip()] + + +def _create_tables(backend, path, names): + """Execute only the ``CREATE TABLE`` statements whose table is in ``names``.""" + for statement in _statements(path): + for name in names: + pattern = r"CREATE TABLE\s+(?:IF NOT EXISTS\s+)?{}\s*\(".format( + re.escape(name) + ) + if re.search(pattern, statement, re.IGNORECASE): + backend.execute(statement) + break + + +def _require_extension(backend, name): + """Skip with the exact missing extension name when the server lacks it.""" + if backend.dialect.is_extension_installed(name): + return + available = "yes" if backend.dialect.is_extension_available(name) else "no" + pytest.skip( + "extension '{}' is not installed (pg_extension); " + "pg_available_extensions says available: {}".format(name, available) + ) + + +@pytest.fixture(scope="class") +def native_backend(postgres_backend_class, request): + """The class's backend, with the class's built-in tables created.""" + backend = postgres_backend_class + names = tuple(getattr(request.cls, "TABLES", ())) + if names: + _create_tables(backend, BUILTIN_SCHEMA, names) + return backend + + +@pytest.fixture(scope="class") +def postgis_backend(postgres_backend_class): + """Backend with the PostGIS table; skips when PostGIS is absent.""" + backend = postgres_backend_class + _require_extension(backend, "postgis") + _create_tables(backend, EXTENSION_SCHEMA, ("native_ext_postgis",)) + return backend + + +@pytest.fixture(scope="class") +def vector_backend(postgres_backend_class): + """Backend with the pgvector table; skips when pgvector is absent.""" + backend = postgres_backend_class + _require_extension(backend, "vector") + _create_tables(backend, EXTENSION_SCHEMA, ("native_ext_pgvector",)) + return backend + + +@pytest.fixture(scope="class") +def hstore_backend(postgres_backend_class): + """Backend with hstore installed and its table created. + + hstore is a contrib extension, so it can be created when the server lists + it in ``pg_available_extensions``; the skip only happens when neither is + true. + """ + from rhosocial.activerecord_postgres_test.feature.backend.utils import ( + ensure_extension_installed, + ) + + backend = postgres_backend_class + ensure_extension_installed(backend, "hstore") + _create_tables(backend, EXTENSION_SCHEMA, ("native_ext_hstore",)) + return backend diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py new file mode 100644 index 00000000..8f7be9a5 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py @@ -0,0 +1,70 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py +"""Small SQL helpers shared by the native type test modules.""" + +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType + +#: INSERT ... RETURNING must ask for result processing explicitly: a DML +#: statement does not run the result pipeline by default. +RETURNING_OPTIONS = ExecutionOptions( + stmt_type=StatementType.DML, + process_result_set=True, +) + + +def insert_row(backend, table, values, casts=None): + """Insert one row and return its ``id``. + + ``values`` keeps its insertion order, so callers can line the columns up + with the SQL they assert against. ``casts`` maps a column name to the + PostgreSQL cast appended to its placeholder, for the few types whose text + form is the only unambiguous input (``xid``, ``bit(n)``, ...). + """ + casts = casts or {} + columns = ", ".join(values) + placeholders = ", ".join( + "%s" + ("::" + casts[name] if name in casts else "") for name in values + ) + sql = "INSERT INTO {} ({}) VALUES ({}) RETURNING id".format( + table, columns, placeholders + ) + result = backend.execute(sql, tuple(values.values()), options=RETURNING_OPTIONS) + return result.data[0]["id"] + + +def insert_sql(backend, sql): + """Run a native ``INSERT ... RETURNING id`` and return the new row id. + + Used by the S3 cases, which deliberately bypass the adapter. + """ + result = backend.execute(sql, options=RETURNING_OPTIONS) + return result.data[0]["id"] + + +def read_raw(backend, table, column, row_id, expression=None): + """Read the server's own text for one column of one row.""" + if expression is None: + expression = "{}::text".format(column) + row = backend.fetch_one( + "SELECT {} AS raw FROM {} WHERE id = %s".format(expression, table), + (row_id,), + ) + return row["raw"] + + +def read_value(backend, table, column, row_id): + """Read the driver-decoded value for one column of one row.""" + row = backend.fetch_one( + "SELECT {} AS value FROM {} WHERE id = %s".format(column, table), + (row_id,), + ) + return row["value"] + + +def update_cell(backend, table, column, row_id, value, cast=None): + """Write one column, optionally through an explicit PostgreSQL cast.""" + suffix = "" if cast is None else "::" + cast + backend.execute( + "UPDATE {} SET {} = %s{} WHERE id = %s".format(table, column, suffix), + (value, row_id), + ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql new file mode 100644 index 00000000..b21de2de --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql @@ -0,0 +1,17 @@ +-- tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql +-- Need per database the grouped statement; create extension before running this. +CREATE TABLE IF NOT EXISTS native_ext_postgis ( + id serial PRIMARY KEY, + geom geometry(Point, 4326), + geog geography(Point, 4326) +); + +CREATE TABLE IF NOT EXISTS native_ext_pgvector ( + id serial PRIMARY KEY, + embedding vector(3) +); + +CREATE TABLE IF NOT EXISTS native_ext_hstore ( + id serial PRIMARY KEY, + attrs hstore +); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql new file mode 100644 index 00000000..0e6ab99e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql @@ -0,0 +1,91 @@ +-- tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql +-- Built-in PostgreSQL types only: every statement is safe on a stock server. +-- Tables are grouped by family; a module enables only the tables it names. + +CREATE TABLE IF NOT EXISTS native_wrapped_scalars ( + id serial PRIMARY KEY, + amount money, + oid_value oid, + regclass_value regclass, + regtype_value regtype, + regproc_value regproc, + regconfig_value regconfig, + regnamespace_value regnamespace, + xid_value xid, + xid8_value xid8, + cid_value cid, + tid_value tid, + lsn_value pg_lsn +); + +CREATE TABLE IF NOT EXISTS native_network ( + id serial PRIMARY KEY, + inet_value inet, + cidr_value cidr, + mac_value macaddr, + mac8_value macaddr8 +); + +CREATE TABLE IF NOT EXISTS native_bits ( + id serial PRIMARY KEY, + fixed_bits bit(8), + var_bits varbit, + five_bits bit(5) +); + +CREATE TABLE IF NOT EXISTS native_full_text ( + id serial PRIMARY KEY, + vector_value tsvector, + query_value tsquery +); + +CREATE TABLE IF NOT EXISTS native_geometric ( + id serial PRIMARY KEY, + point_value point, + line_value line, + lseg_value lseg, + box_value box, + path_value path, + polygon_value polygon, + circle_value circle +); + +CREATE TABLE IF NOT EXISTS native_arrays ( + id serial PRIMARY KEY, + ints int[], + texts text[] +); + +CREATE TABLE IF NOT EXISTS native_ranges ( + id serial PRIMARY KEY, + i4 int4range, + i8 int8range, + num numrange, + ts tsrange, + tstz tstzrange, + dt daterange +); + +CREATE TABLE IF NOT EXISTS native_multiranges ( + id serial PRIMARY KEY, + i4 int4multirange, + i8 int8multirange, + num nummultirange, + ts tsmultirange, + tstz tstzmultirange, + dt datemultirange +); + +CREATE TABLE IF NOT EXISTS native_json_xml ( + id serial PRIMARY KEY, + payload_json json, + payload_jsonb jsonb, + path_value jsonpath, + doc xml +); + +CREATE TABLE IF NOT EXISTS native_remaining ( + id serial PRIMARY KEY, + payload bytea, + span interval +); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py new file mode 100644 index 00000000..974c6729 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py @@ -0,0 +1,105 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py +"""Native tests for PostgreSQL ``T[]`` arrays. + +The registered suggestion for ``list`` must stay the native +``PostgresListAdapter`` (list -> list), never the JSON text adapter. Arrays +are asserted three ways: the server's ``{...}`` text, the driver's decoded +list, and a native ``{1,2}`` literal written without the adapter. +""" + +import pytest + +from rhosocial.activerecord.backend.errors import DatabaseError +from rhosocial.activerecord.backend.impl.postgres.adapters.base import ( + PostgresListAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.json import ( + PostgresJSONBAdapter, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + read_value, + update_cell, +) + +TABLE = "native_arrays" + +ARRAY = PostgresListAdapter() + + +class TestArrays: + TABLES = (TABLE,) + + def test_native_int_and_text_arrays_round_trip(self, native_backend): + """S1/S2: bound lists stay lists and their server text is ``{...}``.""" + backend = native_backend + ints = [1, 2, 3] + texts = ["a", "b"] + row_id = insert_row( + backend, + TABLE, + { + "ints": ARRAY.to_database(ints, list), + "texts": ARRAY.to_database(texts, list), + }, + {"ints": "int[]", "texts": "text[]"}, + ) + + assert read_raw(backend, TABLE, "ints", row_id) == "{1,2,3}" + assert read_raw(backend, TABLE, "texts", row_id) == "{a,b}" + assert read_value(backend, TABLE, "ints", row_id) == ints + assert read_value(backend, TABLE, "texts", row_id) == texts + + assert ARRAY.from_database(read_value(backend, TABLE, "ints", row_id), list) == ints + assert ARRAY.from_database(read_value(backend, TABLE, "texts", row_id), list) == texts + + update_cell( + backend, TABLE, "ints", row_id, + ARRAY.to_database(ARRAY.from_database(ints, list), list), "int[]", + ) + assert read_raw(backend, TABLE, "ints", row_id) == "{1,2,3}" + + def test_empty_list_is_distinct_from_null(self, native_backend): + """An empty list stores ``{}``, while NULL remains NULL.""" + backend = native_backend + empty_row = insert_row( + backend, TABLE, {"ints": ARRAY.to_database([], list)}, {"ints": "int[]"} + ) + null_row = insert_row(backend, TABLE, {"ints": None}, {"ints": "int[]"}) + + assert read_raw(backend, TABLE, "ints", empty_row) == "{}" + assert read_value(backend, TABLE, "ints", empty_row) == [] + assert read_value(backend, TABLE, "ints", null_row) is None + + def test_native_array_literal_reads_back_as_a_list(self, native_backend): + """S3: postgres-written ``{4,5}`` and ``{x,y}`` are plain lists.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (ints, texts) VALUES " + "('{{4,5}}'::int[], '{{x,y}}'::text[]) RETURNING id".format(TABLE), + ) + assert read_raw(backend, TABLE, "ints", row_id) == "{4,5}" + assert read_raw(backend, TABLE, "texts", row_id) == "{x,y}" + assert read_value(backend, TABLE, "ints", row_id) == [4, 5] + assert read_value(backend, TABLE, "texts", row_id) == ["x", "y"] + assert ARRAY.from_database([4, 5], list) == [4, 5] + + def test_array_suggestion_is_native_and_not_json(self, native_backend): + """J9 guard: ``list`` resolves to the array adapter, not JSON text.""" + suggestions = native_backend.get_default_adapter_suggestions() + adapter, target = suggestions[list] + assert target is list + assert isinstance(adapter, PostgresListAdapter) + assert not isinstance(adapter, PostgresJSONBAdapter) + # The write-side value is handed to psycopg unchanged. + assert adapter.to_database([1, 2], list) == [1, 2] + + def test_wrong_element_type_is_rejected_by_the_server(self, native_backend): + """The array's element type is enforced by PostgreSQL.""" + with pytest.raises(DatabaseError): + native_backend.execute( + "SELECT %s::int[]", (ARRAY.to_database(["not-an-int"], list),) + ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py new file mode 100644 index 00000000..1f4293a8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py @@ -0,0 +1,128 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py +"""Native tests for PostgreSQL ``bit(n)`` and ``varbit``. + +The neutral ``BitString`` adapter binds the bare binary digits; ``bit(n)`` +right-pads them exactly as PostgreSQL does. The wrapper +``PostgresBitStringAdapter`` emits the SQL literal ``B'1010'`` instead, which +is used inline for the wrapper path. The bit length is asserted separately +from the bytes. +""" + +import pytest + +from rhosocial.activerecord.backend.adapters import BitString +from rhosocial.activerecord.backend.errors import TypeConversionError +from rhosocial.activerecord.backend.impl.postgres.adapters.bit_string import ( + PostgresBitStringAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import ( + PostgresNeutralBitStringAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + PostgresBitString, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + update_cell, +) + +TABLE = "native_bits" + +WRAPPER = PostgresBitStringAdapter() +NEUTRAL = PostgresNeutralBitStringAdapter() + + +class TestBitStrings: + TABLES = (TABLE,) + + def test_bit8_pads_on_the_right_and_stays_stable(self, native_backend): + """S2: a short input into bit(8) is padded, and re-writing is a no-op.""" + backend = native_backend + value = BitString.from_bits("1010") + bound = NEUTRAL.to_database(value, str) + assert bound == "1010" + + row_id = insert_row(backend, TABLE, {"fixed_bits": bound}, {"fixed_bits": "bit(8)"}) + raw = read_raw(backend, TABLE, "fixed_bits", row_id) + assert raw == "10100000" + + decoded = NEUTRAL.from_database(raw, BitString) + assert decoded.to_bits() == "10100000" + assert decoded.bit_length == 8 + + update_cell( + backend, TABLE, "fixed_bits", row_id, + NEUTRAL.to_database(decoded, str), "bit(8)", + ) + assert read_raw(backend, TABLE, "fixed_bits", row_id) == raw + + def test_varbit_preserves_non_byte_aligned_lengths(self, native_backend): + """S1/S2: five bits stay five bits in both varbit and bit(5).""" + backend = native_backend + value = BitString.from_bits("10101") + row_id = insert_row( + backend, + TABLE, + { + "var_bits": NEUTRAL.to_database(value, str), + "five_bits": NEUTRAL.to_database(value, str), + }, + {"var_bits": "varbit", "five_bits": "bit(5)"}, + ) + + assert read_raw(backend, TABLE, "var_bits", row_id) == "10101" + assert read_raw(backend, TABLE, "five_bits", row_id) == "10101" + + decoded = NEUTRAL.from_database("10101", BitString) + assert decoded == value + assert decoded.bit_length == 5 + + update_cell(backend, TABLE, "var_bits", row_id, "10101", "varbit") + assert read_raw(backend, TABLE, "var_bits", row_id) == "10101" + + def test_declared_length_option_pads_external_text(self): + """S1: an explicit bit length restores the leading zeros in text.""" + padded = NEUTRAL.from_database("1010", BitString, {"bit_length": 8}) + assert padded.to_bits() == "10100000" + assert padded.bit_length == 8 + + def test_wrapper_adapter_emits_an_sql_literal(self, native_backend): + """The wrapper adapter's wire form is ``B'...'``, used inline.""" + backend = native_backend + value = PostgresBitString("1010") + literal = WRAPPER.to_database(value, str) + assert literal == "B'1010'" + + row_id = insert_sql( + backend, + "INSERT INTO {} (five_bits) VALUES ({}::bit(5)) RETURNING id".format( + TABLE, literal + ), + ) + raw = read_raw(backend, TABLE, "five_bits", row_id) + assert raw == "10100" + decoded = WRAPPER.from_database(raw, PostgresBitString) + assert decoded == PostgresBitString("10100") + + def test_external_bit_literal_is_accepted(self, native_backend): + """S3: ``B'101'`` written by native SQL reads back as three bits.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (var_bits) VALUES (B'101'::varbit) RETURNING id".format( + TABLE + ), + ) + raw = read_raw(backend, TABLE, "var_bits", row_id) + assert raw == "101" + decoded = NEUTRAL.from_database(raw, BitString) + assert decoded == BitString.from_bits("101") + assert decoded.bit_length == 3 + + def test_invalid_bit_text_is_wrapped(self): + """Non-binary text is rejected by the adapter, not passed to the driver.""" + for text in ("102", "", "B'101"): + with pytest.raises(TypeConversionError): + NEUTRAL.from_database(text, BitString) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py new file mode 100644 index 00000000..9fc5cca8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py @@ -0,0 +1,169 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py +"""Native tests for extension-provided types. + +The extension existence is established before any table is created, so a +server without the extension reports a skip naming exactly that extension. +On the shared test server only ``hstore`` is available; ``postgis`` and +``pgvector`` are listed in ``pg_available_extensions`` as absent and their +classes skip accordingly. +""" + +import pytest + +from rhosocial.activerecord.backend.adapters import Geometry, Vector +from rhosocial.activerecord.backend.errors import DatabaseError, TypeConversionError +from rhosocial.activerecord.backend.impl.postgres.adapters.hstore import ( + PostgresHstoreAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import ( + PostgresNeutralGeometryAdapter, + PostgresNeutralVectorAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + PostgresHstore, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + update_cell, +) + +POSTGIS_TABLE = "native_ext_postgis" +VECTOR_TABLE = "native_ext_pgvector" +HSTORE_TABLE = "native_ext_hstore" + +GEOMETRY = PostgresNeutralGeometryAdapter() +VECTOR = PostgresNeutralVectorAdapter() +HSTORE = PostgresHstoreAdapter() + + +class TestPostgis: + """PostGIS geometry/geography; skipped when the extension is absent.""" + + def test_geometry_ewkt_round_trip_and_srid(self, postgis_backend): + backend = postgis_backend + value = Geometry.from_wkt("POINT (1 2)", srid=4326) + bound = GEOMETRY.to_database(value, str) + assert bound == "SRID=4326;POINT (1.0 2.0)" + + row_id = insert_row( + backend, POSTGIS_TABLE, {"geom": bound}, {"geom": "geometry"} + ) + ewkt = read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_AsEWKT(geom)") + assert ewkt.startswith("SRID=4326;POINT") + assert read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_SRID(geom)") == 4326 + + decoded = GEOMETRY.from_database(ewkt, Geometry) + assert decoded.srid == 4326 + assert decoded.to_wkt().startswith("POINT") + + update_cell(backend, POSTGIS_TABLE, "geom", row_id, ewkt, "geometry") + assert read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_AsEWKT(geom)") == ewkt + + def test_geography_keeps_its_default_srid(self, postgis_backend): + backend = postgis_backend + value = Geometry.from_wkt("POINT (1 2)", srid=4326) + bound = GEOMETRY.to_database(value, str) + row_id = insert_row( + backend, POSTGIS_TABLE, {"geog": bound}, {"geog": "geography"} + ) + assert read_raw(backend, POSTGIS_TABLE, "geog", row_id, "ST_SRID(geog)") == 4326 + ewkt = read_raw(backend, POSTGIS_TABLE, "geog", row_id, "ST_AsEWKT(geog)") + assert ewkt.startswith("SRID=4326;POINT") + assert GEOMETRY.from_database(ewkt, Geometry).srid == 4326 + + def test_default_geometry_text_is_hex_ewkb_and_rejected(self, postgis_backend): + """PostGIS's default output is EWKB hex; the adapter refuses to guess.""" + backend = postgis_backend + row_id = insert_row( + backend, + POSTGIS_TABLE, + {"geom": GEOMETRY.to_database(Geometry.from_wkt("POINT (1 2)", srid=4326), str)}, + {"geom": "geometry"}, + ) + hex_ewkb = read_raw(backend, POSTGIS_TABLE, "geom", row_id, "geom::text") + assert hex_ewkb[:2].lower() == "01" + with pytest.raises(TypeConversionError) as excinfo: + GEOMETRY.from_database(hex_ewkb, Geometry) + assert "EWKB" in str(excinfo.value) + + def test_external_ewkt_literal_reads_back(self, postgis_backend): + backend = postgis_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (geom) VALUES " + "(ST_GeomFromEWKT('SRID=4326;POINT(1 2)')) RETURNING id".format( + POSTGIS_TABLE + ), + ) + ewkt = read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_AsEWKT(geom)") + assert ewkt == "SRID=4326;POINT(1 2)" + assert GEOMETRY.from_database(ewkt, Geometry).srid == 4326 + + +class TestPgVector: + """pgvector ``vector``; skipped when the extension is absent.""" + + def test_vector_text_round_trip(self, vector_backend): + backend = vector_backend + value = Vector((1.0, 2.0, 3.0)) + bound = VECTOR.to_database(value, str) + assert bound == "[1.0,2.0,3.0]" + + row_id = insert_row( + backend, VECTOR_TABLE, {"embedding": bound}, {"embedding": "vector(3)"} + ) + raw = read_raw(backend, VECTOR_TABLE, "embedding", row_id) + assert raw == "[1,2,3]" + assert read_raw( + backend, VECTOR_TABLE, "embedding", row_id, "vector_dims(embedding)" + ) == 3 + assert VECTOR.from_database(raw, Vector) == value + + update_cell( + backend, VECTOR_TABLE, "embedding", row_id, + VECTOR.to_database(VECTOR.from_database(raw, Vector), str), "vector(3)", + ) + assert read_raw(backend, VECTOR_TABLE, "embedding", row_id) == raw + + def test_vector_dimension_mismatch_is_rejected(self, vector_backend): + backend = vector_backend + with pytest.raises(DatabaseError): + backend.execute( + "SELECT %s::vector(3)", (VECTOR.to_database(Vector((1.0, 2.0)), str),) + ) + + +class TestHstore: + """hstore key/value pairs; installed from contrib when available.""" + + def test_hstore_dict_round_trip_and_raw_text(self, hstore_backend): + backend = hstore_backend + value = {"a": "1", "b": "2"} + bound = HSTORE.to_database(value, str) + assert bound == '"a"=>"1", "b"=>"2"' + + row_id = insert_row( + backend, HSTORE_TABLE, {"attrs": bound}, {"attrs": "hstore"} + ) + raw = read_raw(backend, HSTORE_TABLE, "attrs", row_id) + assert raw == '"a"=>"1", "b"=>"2"' + decoded = HSTORE.from_database(raw, PostgresHstore) + assert decoded.data == value + + update_cell(backend, HSTORE_TABLE, "attrs", row_id, raw, "hstore") + assert read_raw(backend, HSTORE_TABLE, "attrs", row_id) == raw + + def test_external_hstore_literal_including_null(self, hstore_backend): + backend = hstore_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (attrs) VALUES ('a=>1, b=>NULL'::hstore) RETURNING id".format( + HSTORE_TABLE + ), + ) + raw = read_raw(backend, HSTORE_TABLE, "attrs", row_id) + assert raw == '"a"=>"1", "b"=>NULL' + decoded = HSTORE.from_database(raw, PostgresHstore) + assert decoded.data == {"a": "1", "b": None} diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py new file mode 100644 index 00000000..b6862a44 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py @@ -0,0 +1,110 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py +"""Native tests for PostgreSQL ``tsvector`` and ``tsquery``. + +Both types are asserted through ``col::text``, which is PostgreSQL's own +lexeme serialisation, and then decoded with the backend wrappers. A second +write must reproduce the same text (S2), and native literals written by SQL +must read back (S3). +""" + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.adapters.text_search import ( + PostgresTsQueryAdapter, + PostgresTsVectorAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + PostgresTsQuery, + PostgresTsVector, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + update_cell, +) + +TABLE = "native_full_text" + +TSVECTOR = PostgresTsVectorAdapter() +TSQUERY = PostgresTsQueryAdapter() + + +class TestFullText: + TABLES = (TABLE,) + + def test_tsvector_keeps_positions_and_weights(self, native_backend): + """S1/S2: sorted lexemes with positions/weights survive a rewrite.""" + backend = native_backend + value = PostgresTsVector.from_string("'hello':1A 'world':2B") + bound = TSVECTOR.to_database(value, str) + assert bound == "'hello':1A 'world':2B" + + row_id = insert_row( + backend, TABLE, {"vector_value": bound}, {"vector_value": "tsvector"} + ) + raw = read_raw(backend, TABLE, "vector_value", row_id) + assert raw == "'hello':1A 'world':2B" + + decoded = TSVECTOR.from_database(raw, PostgresTsVector) + assert decoded == value + assert decoded.get_positions("hello") == [(1, "A")] + + update_cell( + backend, TABLE, "vector_value", row_id, + TSVECTOR.to_database(decoded, str), "tsvector", + ) + assert read_raw(backend, TABLE, "vector_value", row_id) == raw + + def test_tsquery_keeps_boolean_structure(self, native_backend): + """S1/S2: the AND structure and its text stay stable.""" + backend = native_backend + value = PostgresTsQuery.parse("hello & world") + bound = TSQUERY.to_database(value, str) + assert bound == "'hello' & 'world'" + + row_id = insert_row( + backend, TABLE, {"query_value": bound}, {"query_value": "tsquery"} + ) + raw = read_raw(backend, TABLE, "query_value", row_id) + assert raw == "'hello' & 'world'" + + decoded = TSQUERY.from_database(raw, PostgresTsQuery) + assert decoded == value + + update_cell( + backend, TABLE, "query_value", row_id, + TSQUERY.to_database(decoded, str), "tsquery", + ) + assert read_raw(backend, TABLE, "query_value", row_id) == raw + + def test_external_full_text_literals_are_parsed(self, native_backend): + """S3: native text forms produced by SQL read back as wrappers.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (vector_value, query_value) VALUES " + "(to_tsvector('simple', 'cat dog'), " + "to_tsquery('simple', 'cat & dog')) RETURNING id".format(TABLE), + ) + + raw_vector = read_raw(backend, TABLE, "vector_value", row_id) + raw_query = read_raw(backend, TABLE, "query_value", row_id) + assert raw_vector == "'cat':1 'dog':2" + assert raw_query == "'cat' & 'dog'" + + vector = TSVECTOR.from_database(raw_vector, PostgresTsVector) + query = TSQUERY.from_database(raw_query, PostgresTsQuery) + assert vector.get_lexemes() == ["cat", "dog"] + assert vector.get_positions("dog") == [(2, None)] + assert query == PostgresTsQuery.parse("cat & dog") + + def test_invalid_tsquery_text_raises_value_error(self): + """The legacy wrapper adapter raises ValueError, not TypeConversionError. + + The family-based adapters wrap failures, but ``PostgresTsQueryAdapter`` + predates that base class and surfaces the parser's ValueError directly. + Recording it here keeps the contract explicit instead of guessing. + """ + with pytest.raises(ValueError): + TSQUERY.from_database("hello &", PostgresTsQuery) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py new file mode 100644 index 00000000..da80fcec --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py @@ -0,0 +1,183 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py +"""Native tests for PostgreSQL's built-in geometric types. + +The seven wrapper types are checked together: each column is read through +``col::text`` in one SELECT, which is the server's canonical geometric text +(and which drops trailing ``.0`` components). Decoding happens with the +wrapper's own target class; re-writing server text must not change it. +""" + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.adapters.geometric import ( + PostgresGeometryAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + Box, + Circle, + Line, + LineSegment, + Path, + Point, + Polygon, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + update_cell, +) + +TABLE = "native_geometric" + +WRAPPER = PostgresGeometryAdapter() + +_RAW_COLUMNS = ( + "point_value", + "line_value", + "lseg_value", + "box_value", + "path_value", + "polygon_value", + "circle_value", +) + + +class TestGeometric: + TABLES = (TABLE,) + + def test_seven_shapes_round_trip_and_raw_text(self, native_backend): + """S1: all seven shapes decode, and their text has the documented form.""" + backend = native_backend + values = { + "point_value": WRAPPER.to_database(Point(1.5, 2.5), str), + "line_value": WRAPPER.to_database(Line(1.0, -1.0, 0.0), str), + "lseg_value": WRAPPER.to_database( + LineSegment(Point(0.0, 0.0), Point(1.5, 1.5)), str + ), + "box_value": WRAPPER.to_database( + Box(Point(1.5, 1.5), Point(0.0, 0.0)), str + ), + "path_value": WRAPPER.to_database( + Path([Point(0.5, 0.0), Point(1.5, 1.0), Point(2.5, 0.0)]), str + ), + "polygon_value": WRAPPER.to_database( + Polygon( + [ + Point(0.5, 0.5), + Point(10.5, 0.5), + Point(10.5, 10.5), + Point(0.5, 0.5), + ] + ), + str, + ), + "circle_value": WRAPPER.to_database(Circle(Point(1.5, 2.5), 3.5), str), + } + casts = {name: name[: -len("_value")] for name in values} + row_id = insert_row(backend, TABLE, values, casts) + + select = ", ".join( + "{}::text AS {}".format(name, name) for name in _RAW_COLUMNS + ) + row = backend.fetch_one( + "SELECT {} FROM {} WHERE id = %s".format(select, TABLE), (row_id,) + ) + assert row["point_value"] == "(1.5,2.5)" + assert row["line_value"] == "{1,-1,0}" + assert row["lseg_value"] == "[(0,0),(1.5,1.5)]" + assert row["box_value"] == "(1.5,1.5),(0,0)" + assert row["path_value"] == "[(0.5,0),(1.5,1),(2.5,0)]" + assert row["polygon_value"] == ( + "((0.5,0.5),(10.5,0.5),(10.5,10.5),(0.5,0.5))" + ) + assert row["circle_value"] == "<(1.5,2.5),3.5>" + + assert WRAPPER.from_database(row["point_value"], Point) == Point(1.5, 2.5) + assert WRAPPER.from_database(row["line_value"], Line) == Line(1.0, -1.0, 0.0) + assert WRAPPER.from_database(row["lseg_value"], LineSegment) == LineSegment( + Point(0.0, 0.0), Point(1.5, 1.5) + ) + assert WRAPPER.from_database(row["box_value"], Box) == Box( + Point(1.5, 1.5), Point(0.0, 0.0) + ) + assert WRAPPER.from_database(row["path_value"], Path) == Path( + [Point(0.5, 0.0), Point(1.5, 1.0), Point(2.5, 0.0)] + ) + assert WRAPPER.from_database(row["polygon_value"], Polygon) == Polygon( + [ + Point(0.5, 0.5), + Point(10.5, 0.5), + Point(10.5, 10.5), + Point(0.5, 0.5), + ] + ) + assert WRAPPER.from_database(row["circle_value"], Circle) == Circle( + Point(1.5, 2.5), 3.5 + ) + + def test_open_and_closed_paths_keep_their_brackets(self, native_backend): + """The path's bracket form is data, not formatting.""" + backend = native_backend + open_value = Path([Point(0.5, 0.0), Point(1.5, 1.0)], is_closed=False) + closed_value = Path([Point(0.5, 0.0), Point(1.5, 1.0)], is_closed=True) + + open_row = insert_row( + backend, + TABLE, + {"path_value": WRAPPER.to_database(open_value, str)}, + {"path_value": "path"}, + ) + closed_row = insert_row( + backend, + TABLE, + {"path_value": WRAPPER.to_database(closed_value, str)}, + {"path_value": "path"}, + ) + assert read_raw(backend, TABLE, "path_value", open_row) == "[(0.5,0),(1.5,1)]" + assert read_raw(backend, TABLE, "path_value", closed_row) == "((0.5,0),(1.5,1))" + assert WRAPPER.from_database( + read_raw(backend, TABLE, "path_value", closed_row), Path + ).is_closed + + def test_rewriting_server_text_does_not_drift(self, native_backend): + """S2: the server canonical text is stable across a write/read/write.""" + backend = native_backend + value = Box(Point(1.5, 1.5), Point(0.0, 0.0)) + row_id = insert_row( + backend, + TABLE, + {"box_value": WRAPPER.to_database(value, str)}, + {"box_value": "box"}, + ) + raw = read_raw(backend, TABLE, "box_value", row_id) + decoded = WRAPPER.from_database(raw, Box) + assert decoded == value + + update_cell( + backend, TABLE, "box_value", row_id, + WRAPPER.to_database(decoded, str), "box", + ) + assert read_raw(backend, TABLE, "box_value", row_id) == raw + + def test_external_geometric_literals_are_parsed(self, native_backend): + """S3: native SQL literals read back through the wrapper adapter.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (point_value, circle_value, polygon_value) VALUES " + "('(1,2)'::point, '<(1,2),3>'::circle, " + "'((0,0),(1,0),(1,1),(0,0))'::polygon) RETURNING id".format(TABLE), + ) + assert read_raw(backend, TABLE, "point_value", row_id) == "(1,2)" + assert read_raw(backend, TABLE, "circle_value", row_id) == "<(1,2),3>" + assert read_raw(backend, TABLE, "polygon_value", row_id) == ( + "((0,0),(1,0),(1,1),(0,0))" + ) + assert WRAPPER.from_database("(1,2)", Point) == Point(1.0, 2.0) + assert WRAPPER.from_database("<(1,2),3>", Circle) == Circle(Point(1.0, 2.0), 3.0) + + def test_malformed_geometric_text_raises(self): + """The legacy wrapper adapter surfaces malformed text as ValueError.""" + with pytest.raises(ValueError): + WRAPPER.from_database("(1)", Point) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py new file mode 100644 index 00000000..82fdb9d1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py @@ -0,0 +1,157 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py +"""Native tests for PostgreSQL ``json``/``jsonb``/``jsonpath`` and ``xml``. + +psycopg decodes ``json`` and ``jsonb`` to ``dict``/``list`` before the +adapter sees them, so ``from_database`` must pass the decoded document +through instead of calling ``json.loads`` again. ``jsonpath`` and ``xml`` +have text wire forms and are asserted through ``col::text``. +""" + +import json + +import pytest + +from rhosocial.activerecord.backend.errors import DatabaseError +from rhosocial.activerecord.backend.impl.postgres.adapters.base import ( + PostgresJSONBAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.json import ( + PostgresJsonPathAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.xml import ( + PostgresXMLAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + PostgresJsonPath, + PostgresXML, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + read_value, + update_cell, +) + +TABLE = "native_json_xml" + +JSON_ADAPTER = PostgresJSONBAdapter() +JSONPATH = PostgresJsonPathAdapter() +XML = PostgresXMLAdapter() + + +class TestJsonXml: + TABLES = (TABLE,) + + def test_json_and_jsonb_pass_decoded_documents_through(self, native_backend): + """S1: psycopg returns dicts, and the adapter does not re-decode them.""" + backend = native_backend + value = {"a": 1, "b": [1, 2]} + bound = JSON_ADAPTER.to_database(value, dict) + row_id = insert_row( + backend, + TABLE, + {"payload_json": bound, "payload_jsonb": bound}, + {"payload_json": "json", "payload_jsonb": "jsonb"}, + ) + + # Both forms are serialised by the same dumper; jsonb canonicalises + # the whitespace, json keeps the dumped compact shape. + assert read_raw(backend, TABLE, "payload_json", row_id) == '{"a": 1, "b": [1, 2]}' + assert read_raw(backend, TABLE, "payload_jsonb", row_id) == '{"a": 1, "b": [1, 2]}' + + for column in ("payload_json", "payload_jsonb"): + driver_value = read_value(backend, TABLE, column, row_id) + assert isinstance(driver_value, dict) + assert driver_value == value + assert JSON_ADAPTER.from_database(driver_value, dict) == value + + update_cell(backend, TABLE, "payload_jsonb", row_id, bound, "jsonb") + assert read_raw(backend, TABLE, "payload_jsonb", row_id) == ( + '{"a": 1, "b": [1, 2]}' + ) + + def test_jsonpath_canonicalises_the_path_text(self, native_backend): + """S1/S2: ``$.a`` is stored as ``$."a"`` and remains stable.""" + backend = native_backend + value = PostgresJsonPath("$.a") + bound = JSONPATH.to_database(value, str) + assert bound == "$.a" + + row_id = insert_row( + backend, TABLE, {"path_value": bound}, {"path_value": "jsonpath"} + ) + raw = read_raw(backend, TABLE, "path_value", row_id) + assert raw == '$."a"' + decoded = JSONPATH.from_database(raw, PostgresJsonPath) + assert decoded == PostgresJsonPath('$."a"') + assert JSONPATH.to_database(decoded, str) == raw + + update_cell(backend, TABLE, "path_value", row_id, raw, "jsonpath") + assert read_raw(backend, TABLE, "path_value", row_id) == raw + + def test_xml_text_round_trips(self, native_backend): + """S1/S2: XML content is preserved verbatim and remains stable.""" + backend = native_backend + value = PostgresXML("1") + bound = XML.to_database(value, str) + row_id = insert_row(backend, TABLE, {"doc": bound}, {"doc": "xml"}) + raw = read_raw(backend, TABLE, "doc", row_id) + assert raw == "1" + assert XML.from_database(raw, PostgresXML) == value + + update_cell(backend, TABLE, "doc", row_id, raw, "xml") + assert read_raw(backend, TABLE, "doc", row_id) == raw + + def test_external_json_jsonpath_and_xml_literals(self, native_backend): + """S3: native SQL text is decoded into the same Python shapes.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (payload_json, payload_jsonb, path_value, doc) VALUES " + "('{{\"k\": \"v\"}}'::json, '{{\"k\":\"v\"}}'::jsonb, " + "'$.a'::jsonpath, '1'::xml) RETURNING id".format(TABLE), + ) + + assert read_raw(backend, TABLE, "payload_json", row_id) == '{"k": "v"}' + assert read_raw(backend, TABLE, "payload_jsonb", row_id) == '{"k": "v"}' + assert read_raw(backend, TABLE, "path_value", row_id) == '$."a"' + assert read_raw(backend, TABLE, "doc", row_id) == "1" + + for column in ("payload_json", "payload_jsonb"): + driver_value = read_value(backend, TABLE, column, row_id) + assert driver_value == {"k": "v"} + assert JSON_ADAPTER.from_database(driver_value, dict) == {"k": "v"} + + assert JSONPATH.from_database('$."a"', PostgresJsonPath) == PostgresJsonPath( + '$."a"' + ) + assert XML.from_database("1", PostgresXML) == PostgresXML( + "1" + ) + + def test_malformed_xml_is_rejected_by_the_server(self, native_backend): + """PostgreSQL validates XML on input.""" + with pytest.raises(DatabaseError): + native_backend.execute("SELECT %s::xml", ("",)) + + def test_jsonpath_requires_a_root_marker(self): + """The adapter rejects a path that is not rooted at ``$``.""" + with pytest.raises(ValueError): + JSONPATH.to_database("a", str) + with pytest.raises(ValueError): + JSONPATH.from_database("a", PostgresJsonPath) + + def test_json_document_is_never_double_encoded(self, native_backend): + """S2 guard: a dict read back stays a dict, not a JSON string.""" + backend = native_backend + value = {"nested": {"n": 1}} + bound = JSON_ADAPTER.to_database(value, dict) + row_id = insert_row( + backend, TABLE, {"payload_jsonb": bound}, {"payload_jsonb": "jsonb"} + ) + driver_value = read_value(backend, TABLE, "payload_jsonb", row_id) + decoded = JSON_ADAPTER.from_database(driver_value, dict) + assert decoded == value + assert not isinstance(decoded, str) + assert json.dumps(decoded, sort_keys=True) == json.dumps(value, sort_keys=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py new file mode 100644 index 00000000..47b6ad10 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py @@ -0,0 +1,169 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py +"""Native tests for PostgreSQL network address types. + +``inet``/``cidr`` use ``ipaddress`` objects, with ``host()`` and ``col::text`` +as the authoritative server expressions. ``macaddr``/``macaddr8`` must +normalise uppercase, hyphenated and compact input to the lowercase +colon-separated form. +""" + +import ipaddress + +import pytest + +from rhosocial.activerecord.backend.errors import DatabaseError +from rhosocial.activerecord.backend.impl.postgres.adapters.network_address import ( + PostgresMacaddr8Adapter, + PostgresMacaddrAdapter, + PostgresNetworkAddressAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + PostgresMacaddr, + PostgresMacaddr8, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + read_value, + update_cell, +) + +TABLE = "native_network" + +NETWORK = PostgresNetworkAddressAdapter() +MACADDR = PostgresMacaddrAdapter() +MACADDR8 = PostgresMacaddr8Adapter() + + +class TestNetwork: + TABLES = (TABLE,) + + def test_inet_address_and_interface_read_back(self, native_backend): + """S1/S2: host and netmask survive, and ``host()`` strips the mask.""" + backend = native_backend + values = { + "inet_value": NETWORK.to_database(ipaddress.ip_address("192.168.1.5"), str), + } + row_id = insert_row(backend, TABLE, values, {"inet_value": "inet"}) + + assert read_raw(backend, TABLE, "inet_value", row_id) == "192.168.1.5/32" + assert read_raw(backend, TABLE, "inet_value", row_id, "host(inet_value)") == ( + "192.168.1.5" + ) + decoded = NETWORK.from_database( + read_value(backend, TABLE, "inet_value", row_id), str + ) + assert decoded == ipaddress.ip_address("192.168.1.5") + + update_cell(backend, TABLE, "inet_value", row_id, "192.168.1.5/32", "inet") + assert read_raw(backend, TABLE, "inet_value", row_id) == "192.168.1.5/32" + + # An interface keeps the host bits and the mask together. + interface = ipaddress.ip_interface("192.168.1.5/24") + row_id = insert_row( + backend, + TABLE, + {"inet_value": NETWORK.to_database(interface, str)}, + {"inet_value": "inet"}, + ) + assert read_raw(backend, TABLE, "inet_value", row_id) == "192.168.1.5/24" + assert read_raw(backend, TABLE, "inet_value", row_id, "host(inet_value)") == ( + "192.168.1.5" + ) + assert read_raw(backend, TABLE, "inet_value", row_id, "network(inet_value)::text") == ( + "192.168.1.0/24" + ) + decoded = NETWORK.from_database( + read_value(backend, TABLE, "inet_value", row_id), str + ) + assert decoded == interface + + def test_cidr_network_is_returned_as_a_network_object(self, native_backend): + """S1/S2: cidr binds as text and psycopg returns an IPv4Network.""" + backend = native_backend + network = ipaddress.ip_network("192.168.1.0/24") + row_id = insert_row( + backend, + TABLE, + {"cidr_value": NETWORK.to_database(network, str)}, + {"cidr_value": "cidr"}, + ) + + assert read_raw(backend, TABLE, "cidr_value", row_id) == "192.168.1.0/24" + driver_value = read_value(backend, TABLE, "cidr_value", row_id) + assert isinstance(driver_value, ipaddress.IPv4Network) + assert NETWORK.from_database(driver_value, str) == network + + update_cell(backend, TABLE, "cidr_value", row_id, "192.168.1.0/24", "cidr") + assert read_raw(backend, TABLE, "cidr_value", row_id) == "192.168.1.0/24" + + def test_macaddr_normalises_uppercase_and_hyphenated_input(self, native_backend): + """S1/S2: the adapter and the server agree on the canonical form.""" + backend = native_backend + value = PostgresMacaddr("08-00-2B-01-02-03") + assert MACADDR.to_database(value, str) == "08:00:2b:01:02:03" + + row_id = insert_row( + backend, + TABLE, + {"mac_value": MACADDR.to_database(value, str)}, + {"mac_value": "macaddr"}, + ) + raw = read_raw(backend, TABLE, "mac_value", row_id) + assert raw == "08:00:2b:01:02:03" + decoded = MACADDR.from_database(raw, PostgresMacaddr) + assert decoded == value + assert MACADDR.to_database(decoded, str) == raw + + update_cell(backend, TABLE, "mac_value", row_id, raw, "macaddr") + assert read_raw(backend, TABLE, "mac_value", row_id) == raw + + def test_macaddr8_expands_a_six_octet_address(self, native_backend): + """S1/S2: an EUI-48 input becomes the EUI-64 ``ff:fe`` form.""" + backend = native_backend + value = PostgresMacaddr8("08002B010203") + assert MACADDR8.to_database(value, str) == "08:00:2b:ff:fe:01:02:03" + + row_id = insert_row( + backend, + TABLE, + {"mac8_value": MACADDR8.to_database(value, str)}, + {"mac8_value": "macaddr8"}, + ) + raw = read_raw(backend, TABLE, "mac8_value", row_id) + assert raw == "08:00:2b:ff:fe:01:02:03" + decoded = MACADDR8.from_database(raw, PostgresMacaddr8) + assert decoded == value + assert MACADDR8.to_database(decoded, str) == raw + + def test_external_network_literals_are_parsed(self, native_backend): + """S3: native SQL text is accepted without an adapter write.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (inet_value, mac_value) VALUES " + "('10.0.0.1'::inet, '08002B010203'::macaddr) RETURNING id".format(TABLE), + ) + + assert read_raw(backend, TABLE, "inet_value", row_id) == "10.0.0.1/32" + assert read_raw(backend, TABLE, "mac_value", row_id) == "08:00:2b:01:02:03" + # Plain text carries the /32 mask, so the adapter's fallback decodes a + # /32 network rather than a bare host; the driver path above returns + # IPv4Address because psycopg already narrowed it. This is the + # documented limitation of parsing external inet text without a hint. + external = NETWORK.from_database("10.0.0.1/32", str) + assert isinstance(external, ipaddress.IPv4Network) + assert str(external) == "10.0.0.1/32" + assert MACADDR.from_database( + "08:00:2b:01:02:03", PostgresMacaddr + ) == PostgresMacaddr("08:00:2b:01:02:03") + + def test_invalid_values_are_rejected(self, native_backend): + """Invalid input fails before SQL or at the server, never silently.""" + with pytest.raises(ValueError): + PostgresMacaddr("08:00:2b:01:02") + with pytest.raises(ValueError): + PostgresMacaddr("08:00:2b:01:02:zz") + with pytest.raises(DatabaseError): + native_backend.execute("SELECT %s::inet", ("not-an-address",)) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py new file mode 100644 index 00000000..f790a2a6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py @@ -0,0 +1,283 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py +"""Native tests for PostgreSQL range and multirange types. + +Discrete ranges are normalised by the server (``[1,3]`` becomes ``[1,4)``), +so the assertions compare canonical values rather than the input object. +Text parsing cannot recover an element type on its own: without an +``element_type``/``range_type`` hint, a quoted ``"2024-01-01"`` stays a +``str``. That limitation is asserted explicitly, and the hinted form is +asserted next to it. +""" + +from datetime import date, datetime, timezone +from decimal import Decimal + +import pytest + +from rhosocial.activerecord.backend.adapters import Multirange, Range +from rhosocial.activerecord.backend.errors import TypeConversionError +from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import ( + PostgresNeutralRangeAdapter, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + update_cell, +) + +RANGE_TABLE = "native_ranges" +MULTIRANGE_TABLE = "native_multiranges" + +RANGE = PostgresNeutralRangeAdapter() + + +def _require_multirange(backend): + version = backend.get_server_version() + if version < (14, 0, 0): + pytest.skip( + "multirange requires PostgreSQL 14+, server is {}".format( + ".".join(str(part) for part in version) + ) + ) + + +def _read_range_columns(backend, table, row_id, columns): + select = ", ".join("{}::text AS {}".format(name, name) for name in columns) + return backend.fetch_one( + "SELECT {} FROM {} WHERE id = %s".format(select, table), (row_id,) + ) + + +class TestRanges: + TABLES = (RANGE_TABLE, MULTIRANGE_TABLE) + + def test_six_range_types_bind_and_read_canonically(self, native_backend): + """S1: all six range types store and print their canonical text.""" + backend = native_backend + backend.execute("SET TIME ZONE 'UTC'") + values = { + "i4": RANGE.to_database(Range(1, 3, "[]"), str), + "i8": RANGE.to_database(Range(2**40, 2**40 + 10, "[)"), str), + "num": RANGE.to_database(Range(Decimal("1.5"), Decimal("2.5"), "(]"), str), + "ts": RANGE.to_database( + Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0), "[)"), + str, + ), + "tstz": RANGE.to_database( + Range( + datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc), + datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc), + "[)", + ), + str, + ), + "dt": RANGE.to_database( + Range(date(2024, 1, 1), date(2024, 1, 2), "[)"), str + ), + } + casts = { + "i4": "int4range", + "i8": "int8range", + "num": "numrange", + "ts": "tsrange", + "tstz": "tstzrange", + "dt": "daterange", + } + row_id = insert_row(backend, RANGE_TABLE, values, casts) + row = _read_range_columns(backend, RANGE_TABLE, row_id, values) + + assert row["i4"] == "[1,4)" + assert row["i8"] == "[1099511627776,1099511627786)" + assert row["num"] == "(1.5,2.5]" + assert row["ts"] == '["2024-01-01 12:00:00","2024-01-02 12:00:00")' + assert row["tstz"] == '["2024-01-01 12:00:00+00","2024-01-02 12:00:00+00")' + assert row["dt"] == "[2024-01-01,2024-01-02)" + + assert RANGE.from_database(row["i4"], Range, {"range_type": "int4range"}) == ( + Range(1, 4, "[)") + ) + assert RANGE.from_database(row["i8"], Range, {"range_type": "int8range"}) == ( + Range(2**40, 2**40 + 10, "[)") + ) + assert RANGE.from_database(row["num"], Range, {"element_type": "decimal"}) == ( + Range(Decimal("1.5"), Decimal("2.5"), "(]") + ) + assert RANGE.from_database(row["ts"], Range, {"element_type": "datetime"}) == ( + Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0), "[)") + ) + assert RANGE.from_database(row["tstz"], Range, {"range_type": "tstzrange"}) == ( + Range( + datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc), + datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc), + "[)", + ) + ) + assert RANGE.from_database(row["dt"], Range, {"range_type": "daterange"}) == ( + Range(date(2024, 1, 1), date(2024, 1, 2), "[)") + ) + + def test_without_an_element_hint_quoted_bounds_stay_strings(self, native_backend): + """The documented limitation: text alone cannot infer date/datetime.""" + backend = native_backend + backend.execute("SET TIME ZONE 'UTC'") + values = {"dt": RANGE.to_database(Range(date(2024, 1, 1), date(2024, 1, 2)), str)} + row_id = insert_row(backend, RANGE_TABLE, values, {"dt": "daterange"}) + raw = read_raw(backend, RANGE_TABLE, "dt", row_id) + + unhinted = RANGE.from_database(raw, Range) + assert unhinted.lower == "2024-01-01" + assert isinstance(unhinted.lower, str) + assert isinstance(unhinted.upper, str) + + hinted = RANGE.from_database(raw, Range, {"element_type": "date"}) + assert hinted.lower == date(2024, 1, 1) + assert hinted.upper == date(2024, 1, 2) + + by_range_type = RANGE.from_database(raw, Range, {"range_type": "daterange"}) + assert by_range_type == hinted + + def test_empty_and_unbounded_ranges_are_normalised(self, native_backend): + """S2: empty stays empty; ``,5]`` canonicalises to ``(,6)``.""" + backend = native_backend + backend.execute("SET TIME ZONE 'UTC'") + empty_row = insert_row( + backend, + RANGE_TABLE, + {"i4": RANGE.to_database(Range(empty=True), str)}, + {"i4": "int4range"}, + ) + assert read_raw(backend, RANGE_TABLE, "i4", empty_row) == "empty" + empty = RANGE.from_database("empty", Range) + assert empty == Range(empty=True) + assert RANGE.to_database(empty, str) == "empty" + + unbounded = Range(None, 5, "(]") + row_id = insert_row( + backend, + RANGE_TABLE, + {"i4": RANGE.to_database(unbounded, str)}, + {"i4": "int4range"}, + ) + raw = read_raw(backend, RANGE_TABLE, "i4", row_id) + assert raw == "(,6)" + decoded = RANGE.from_database(raw, Range, {"range_type": "int4range"}) + assert decoded == Range(None, 6, "()") + + update_cell( + backend, RANGE_TABLE, "i4", row_id, + RANGE.to_database(decoded, str), "int4range", + ) + assert read_raw(backend, RANGE_TABLE, "i4", row_id) == "(,6)" + + def test_six_multirange_types_round_trip(self, native_backend): + """S1: all six multirange types keep their canonical segment list.""" + backend = native_backend + _require_multirange(backend) + backend.execute("SET TIME ZONE 'UTC'") + values = { + "i4": RANGE.to_database(Multirange((Range(1, 5), Range(10, 15))), str), + "i8": RANGE.to_database(Multirange((Range(2**40, 2**40 + 5),)), str), + "num": RANGE.to_database( + Multirange((Range(Decimal("1.5"), Decimal("2.5")),)), str + ), + "ts": RANGE.to_database( + Multirange( + (Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0)),) + ), + str, + ), + "tstz": RANGE.to_database( + Multirange( + ( + Range( + datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc), + datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc), + ), + ) + ), + str, + ), + "dt": RANGE.to_database( + Multirange((Range(date(2024, 1, 1), date(2024, 1, 2)),)), str + ), + } + casts = { + "i4": "int4multirange", + "i8": "int8multirange", + "num": "nummultirange", + "ts": "tsmultirange", + "tstz": "tstzmultirange", + "dt": "datemultirange", + } + row_id = insert_row(backend, MULTIRANGE_TABLE, values, casts) + row = _read_range_columns(backend, MULTIRANGE_TABLE, row_id, values) + + assert row["i4"] == "{[1,5),[10,15)}" + assert row["i8"] == "{[1099511627776,1099511627781)}" + assert row["num"] == "{[1.5,2.5)}" + assert row["ts"] == '{["2024-01-01 12:00:00","2024-01-02 12:00:00")}' + assert row["tstz"] == '{["2024-01-01 12:00:00+00","2024-01-02 12:00:00+00")}' + assert row["dt"] == "{[2024-01-01,2024-01-02)}" + + assert RANGE.from_database(row["i4"], Multirange, {"range_type": "int4range"}) == ( + Multirange((Range(1, 5), Range(10, 15))) + ) + assert RANGE.from_database(row["num"], Multirange, {"element_type": "decimal"}) == ( + Multirange((Range(Decimal("1.5"), Decimal("2.5")),)) + ) + assert RANGE.from_database(row["dt"], Multirange, {"range_type": "daterange"}) == ( + Multirange((Range(date(2024, 1, 1), date(2024, 1, 2)),)) + ) + + def test_multirange_merges_overlap_and_sorts(self, native_backend): + """S2: unsorted/touching input becomes one sorted canonical list.""" + backend = native_backend + _require_multirange(backend) + value = Multirange((Range(20, 25), Range(1, 5), Range(5, 10))) + assert RANGE.to_database(value, str) == "{[1,10),[20,25)}" + + row_id = insert_row( + backend, + MULTIRANGE_TABLE, + {"i4": RANGE.to_database(value, str)}, + {"i4": "int4multirange"}, + ) + raw = read_raw(backend, MULTIRANGE_TABLE, "i4", row_id) + assert raw == "{[1,10),[20,25)}" + decoded = RANGE.from_database(raw, Multirange, {"range_type": "int4range"}) + assert decoded == Multirange((Range(1, 10), Range(20, 25))) + + def test_external_range_and_multirange_literals(self, native_backend): + """S3: native SQL range literals read back as neutral values.""" + backend = native_backend + _require_multirange(backend) + backend.execute("SET TIME ZONE 'UTC'") + row_id = insert_sql( + backend, + "INSERT INTO {} (i4, dt) VALUES " + "('[1,10)'::int4range, '[2024-01-01,2024-01-02)'::daterange) " + "RETURNING id".format(RANGE_TABLE), + ) + multi_id = insert_sql( + backend, + "INSERT INTO {} (i4) VALUES " + "('{{[1,5),[10,15)}}'::int4multirange) RETURNING id".format( + MULTIRANGE_TABLE + ), + ) + + assert read_raw(backend, RANGE_TABLE, "i4", row_id) == "[1,10)" + assert read_raw(backend, RANGE_TABLE, "dt", row_id) == "[2024-01-01,2024-01-02)" + assert RANGE.from_database("[1,10)", Range, {"range_type": "int4range"}) == ( + Range(1, 10, "[)") + ) + assert read_raw(backend, MULTIRANGE_TABLE, "i4", multi_id) == "{[1,5),[10,15)}" + assert RANGE.from_database( + "{[1,5),[10,15)}", Multirange, {"range_type": "int4range"} + ) == Multirange((Range(1, 5), Range(10, 15))) + + def test_unknown_element_hint_is_wrapped(self): + """A hint the adapter does not know is a conversion error.""" + with pytest.raises(TypeConversionError): + RANGE.from_database("[1,2)", Range, {"element_type": "uuid"}) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py new file mode 100644 index 00000000..8a11ce5f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py @@ -0,0 +1,89 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py +"""Native tests for ``bytea`` and ``interval``: the two pending gaps. + +Neither type has an adapter registered by this backend: ``bytes`` and +``timedelta`` are absent from ``get_default_adapter_suggestions()`` and from +the adapter registry. psycopg still round-trips both natively, so the tests +pin that pass-through and record the missing adapter as a Phase 3b gap +instead of inventing an adapter here. +""" + +from datetime import timedelta + +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + read_value, + update_cell, +) + +TABLE = "native_remaining" + + +def _adapter_keys(backend, py_type): + return [ + key + for key in backend.adapter_registry.get_all_adapters() + if key[0] is py_type + ] + + +class TestRemainingTypes: + TABLES = (TABLE,) + + def test_bytea_has_no_adapter_and_passes_through(self, native_backend): + """Gap: bytes has no adapter; psycopg binds and returns it unchanged.""" + backend = native_backend + suggestions = backend.get_default_adapter_suggestions() + assert suggestions.get(bytes) is None + assert _adapter_keys(backend, bytes) == [] + + value = b"\x00\x01\xff" + row_id = insert_row(backend, TABLE, {"payload": value}, {"payload": "bytea"}) + assert read_raw(backend, TABLE, "payload", row_id) == "\\x0001ff" + assert read_value(backend, TABLE, "payload", row_id) == value + + update_cell(backend, TABLE, "payload", row_id, value, "bytea") + assert read_value(backend, TABLE, "payload", row_id) == value + + def test_bytea_external_hex_literal_reads_back(self, native_backend): + """S3: the server's own hex form decodes to the same bytes.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (payload) VALUES ('\\x0001ff'::bytea) RETURNING id".format( + TABLE + ), + ) + assert read_raw(backend, TABLE, "payload", row_id) == "\\x0001ff" + assert read_value(backend, TABLE, "payload", row_id) == b"\x00\x01\xff" + + def test_interval_has_no_adapter_and_passes_through(self, native_backend): + """Gap: timedelta has no adapter; the driver handles interval natively.""" + backend = native_backend + suggestions = backend.get_default_adapter_suggestions() + assert suggestions.get(timedelta) is None + assert _adapter_keys(backend, timedelta) == [] + + value = timedelta(days=1, seconds=7384) + row_id = insert_row(backend, TABLE, {"span": value}, {"span": "interval"}) + assert read_raw(backend, TABLE, "span", row_id) == "1 day 02:03:04" + assert read_value(backend, TABLE, "span", row_id) == value + + update_cell(backend, TABLE, "span", row_id, read_value(backend, TABLE, "span", row_id), "interval") + assert read_raw(backend, TABLE, "span", row_id) == "1 day 02:03:04" + + def test_interval_external_literal_reads_back(self, native_backend): + """S3: a server-written interval text decodes to a timedelta.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (span) VALUES ('1 day 02:03:04'::interval) RETURNING id".format( + TABLE + ), + ) + assert read_raw(backend, TABLE, "span", row_id) == "1 day 02:03:04" + assert read_value(backend, TABLE, "span", row_id) == timedelta( + days=1, seconds=7384 + ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py new file mode 100644 index 00000000..0c490eaa --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py @@ -0,0 +1,242 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py +"""Native tests for PostgreSQL's wrapped scalar types. + +``money``, ``oid``, the ``reg*`` family, ``xid``/``xid8``/``cid``, ``tid`` and +``pg_lsn`` all have a wrapper class and an adapter in this backend. Reads +assert the server's own text (``col::text`` or ``col::numeric`` for money, so +the locale-formatted money output is never the truth), not the adapter's +re-serialisation. +""" + +from decimal import Decimal + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.adapters.monetary import ( + PostgresMoneyAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.object_identifier import ( + PostgresOidAdapter, + PostgresTidAdapter, + PostgresXidAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.pg_lsn import ( + PostgresLsnAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + CID, + OID, + TID, + XID, + XID8, + PostgresLsn, + PostgresMoney, + RegClass, + RegConfig, + RegNamespace, + RegProc, + RegType, +) +from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import ( + insert_row, + insert_sql, + read_raw, + update_cell, +) + +TABLE = "native_wrapped_scalars" + +MONEY = PostgresMoneyAdapter() +OID_ADAPTER = PostgresOidAdapter() +XID_ADAPTER = PostgresXidAdapter() +TID_ADAPTER = PostgresTidAdapter() +LSN_ADAPTER = PostgresLsnAdapter() + + +class TestWrappedScalars: + TABLES = (TABLE,) + + # --- S1, without a server ------------------------------------------------- + + def test_every_wrapper_round_trips_at_the_adapter_level(self): + """S1: to_database then from_database returns the same semantic value.""" + cases = [ + (MONEY, PostgresMoney(Decimal("1234.56")), PostgresMoney), + (OID_ADAPTER, OID(16384), OID), + (OID_ADAPTER, RegClass("pg_class"), RegClass), + (OID_ADAPTER, RegType("integer"), RegType), + (OID_ADAPTER, RegProc("now"), RegProc), + (OID_ADAPTER, RegConfig("english"), RegConfig), + (OID_ADAPTER, RegNamespace("public"), RegNamespace), + (XID_ADAPTER, XID(42), XID), + (XID_ADAPTER, XID8(42), XID8), + (XID_ADAPTER, CID(7), CID), + (TID_ADAPTER, TID(3, 5), TID), + (LSN_ADAPTER, PostgresLsn.from_string("16/B374D848"), PostgresLsn), + ] + for adapter, value, target in cases: + database_value = adapter.to_database(value, str) + decoded = adapter.from_database(database_value, target) + assert decoded == value + assert adapter.to_database(decoded, str) == database_value + + # --- money ---------------------------------------------------------------- + + def test_money_records_numeric_truth_and_stays_stable(self, native_backend): + """S2: the numeric column value survives a read/rewrite unchanged.""" + backend = native_backend + value = PostgresMoney(Decimal("1234.56")) + bound = MONEY.to_database(value, str) + assert bound == "1234.56" + + row_id = insert_row(backend, TABLE, {"amount": bound}, {"amount": "money"}) + numeric = read_raw(backend, TABLE, "amount", row_id, "amount::numeric::text") + assert numeric == "1234.56" + + # The raw money text is locale formatted; the adapter must parse it. + raw_text = read_raw(backend, TABLE, "amount", row_id) + assert raw_text.startswith("$") + decoded = MONEY.from_database(raw_text, PostgresMoney) + assert decoded.amount == Decimal("1234.56") + + # Writing the decoded value again must not change the stored amount. + update_cell(backend, TABLE, "amount", row_id, MONEY.to_database(decoded, str), "money") + assert read_raw(backend, TABLE, "amount", row_id, "amount::numeric::text") == numeric + + # --- oid and the reg* family ---------------------------------------------- + + def test_oid_and_registry_names_read_back_as_wrappers(self, native_backend): + """S1/S2: reg* columns resolve names and the adapters rebuild wrappers.""" + backend = native_backend + values = { + "oid_value": OID_ADAPTER.to_database(OID(16384), int), + "regclass_value": OID_ADAPTER.to_database(RegClass("pg_class"), str), + "regtype_value": OID_ADAPTER.to_database(RegType("integer"), str), + "regproc_value": OID_ADAPTER.to_database(RegProc("now"), str), + "regconfig_value": OID_ADAPTER.to_database(RegConfig("english"), str), + "regnamespace_value": OID_ADAPTER.to_database(RegNamespace("public"), str), + } + casts = { + "oid_value": "oid", + "regclass_value": "regclass", + "regtype_value": "regtype", + "regproc_value": "regproc", + "regconfig_value": "regconfig", + "regnamespace_value": "regnamespace", + } + row_id = insert_row(backend, TABLE, values, casts) + + assert read_raw(backend, TABLE, "oid_value", row_id) == "16384" + assert read_raw(backend, TABLE, "regclass_value", row_id) == "pg_class" + assert read_raw(backend, TABLE, "regtype_value", row_id) == "integer" + assert read_raw(backend, TABLE, "regproc_value", row_id) == "now" + assert read_raw(backend, TABLE, "regconfig_value", row_id) == "english" + assert read_raw(backend, TABLE, "regnamespace_value", row_id) == "public" + + assert OID_ADAPTER.from_database("16384", OID) == OID(16384) + assert OID_ADAPTER.from_database("pg_class", RegClass) == RegClass("pg_class") + assert OID_ADAPTER.from_database("integer", RegType) == RegType("integer") + assert OID_ADAPTER.from_database("now", RegProc) == RegProc("now") + assert OID_ADAPTER.from_database("english", RegConfig) == RegConfig("english") + assert OID_ADAPTER.from_database("public", RegNamespace) == RegNamespace("public") + + # S2: rewrite the canonical text the adapter produces. + update_cell( + backend, TABLE, "regclass_value", row_id, + OID_ADAPTER.to_database(RegClass("pg_class"), str), "regclass", + ) + assert read_raw(backend, TABLE, "regclass_value", row_id) == "pg_class" + + # --- transaction and command identifiers ---------------------------------- + + def test_xid_xid8_and_cid_keep_their_decimal_text(self, native_backend): + """S1/S2: xid/xid8/cid bind as integer, but the server text is decimal.""" + backend = native_backend + values = { + "xid_value": XID_ADAPTER.to_database(XID(42), int), + "xid8_value": XID_ADAPTER.to_database(XID8(42), int), + "cid_value": XID_ADAPTER.to_database(CID(7), int), + } + casts = { + "xid_value": "text::xid", + "xid8_value": "text::xid8", + "cid_value": "text::cid", + } + row_id = insert_row(backend, TABLE, values, casts) + + assert read_raw(backend, TABLE, "xid_value", row_id) == "42" + assert read_raw(backend, TABLE, "xid8_value", row_id) == "42" + assert read_raw(backend, TABLE, "cid_value", row_id) == "7" + + assert XID_ADAPTER.from_database("42", XID) == XID(42) + assert XID_ADAPTER.from_database("42", XID8) == XID8(42) + assert XID_ADAPTER.from_database("7", CID) == CID(7) + + update_cell( + backend, TABLE, "xid_value", row_id, + XID_ADAPTER.to_database(XID(42), int), "text::xid", + ) + assert read_raw(backend, TABLE, "xid_value", row_id) == "42" + + # --- tid and pg_lsn ------------------------------------------------------- + + def test_tid_and_lsn_use_their_native_text_forms(self, native_backend): + """S1/S2: tid prints as ``(block,offset)`` and pg_lsn as ``HI/LO``.""" + backend = native_backend + xid_bits = LSN_ADAPTER.to_database( + PostgresLsn.from_string("16/b374d848"), str + ) + assert xid_bits == "16/B374D848" # the adapter canonicalises to upper case + values = { + "tid_value": TID_ADAPTER.to_database(TID(3, 5), str), + "lsn_value": xid_bits, + } + casts = {"tid_value": "tid", "lsn_value": "pg_lsn"} + row_id = insert_row(backend, TABLE, values, casts) + + assert read_raw(backend, TABLE, "tid_value", row_id) == "(3,5)" + assert read_raw(backend, TABLE, "lsn_value", row_id) == "16/B374D848" + + assert TID_ADAPTER.from_database("(3,5)", TID) == TID(3, 5) + assert LSN_ADAPTER.from_database("16/B374D848", PostgresLsn) == ( + PostgresLsn.from_string("16/B374D848") + ) + + update_cell( + backend, TABLE, "lsn_value", row_id, + LSN_ADAPTER.to_database( + LSN_ADAPTER.from_database("16/B374D848", PostgresLsn), str + ), "pg_lsn", + ) + assert read_raw(backend, TABLE, "lsn_value", row_id) == "16/B374D848" + + # --- S3, external literals ------------------------------------------------ + + def test_external_money_oid_and_regclass_literals_are_parsed(self, native_backend): + """S3: values written by native SQL (no adapter) read back correctly.""" + backend = native_backend + row_id = insert_sql( + backend, + "INSERT INTO {} (amount, oid_value, regclass_value) " + "VALUES ('9876.54'::money, 20000::oid, 'pg_class'::regclass) " + "RETURNING id".format(TABLE), + ) + + assert read_raw(backend, TABLE, "amount", row_id, "amount::numeric::text") == "9876.54" + assert read_raw(backend, TABLE, "oid_value", row_id) == "20000" + assert read_raw(backend, TABLE, "regclass_value", row_id) == "pg_class" + + money = MONEY.from_database(read_raw(backend, TABLE, "amount", row_id), PostgresMoney) + assert money.amount == Decimal("9876.54") + assert OID_ADAPTER.from_database("20000", OID) == OID(20000) + + # --- invalid input -------------------------------------------------------- + + def test_out_of_range_and_malformed_wrappers_raise(self): + """The adapter rejects values PostgreSQL could never store.""" + with pytest.raises(ValueError): + OID_ADAPTER.to_database(4294967296, int) + with pytest.raises(ValueError): + TID_ADAPTER.to_database((0, 70000), str) + with pytest.raises(ValueError): + LSN_ADAPTER.to_database("not-an-lsn", str) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py new file mode 100644 index 00000000..10eaae54 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py @@ -0,0 +1,175 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py +"""Database-free coverage for the JSON/JSONB adapter hooks. + +Both definitions of ``PostgresJSONBAdapter`` are exercised: the one exported +by ``adapters`` (and registered on the backend) and the copy in +``adapters.json`` that offline tests import. +""" + +import json +from decimal import Decimal + +import pytest +from psycopg.types.json import Jsonb, JsonbDumper + +from rhosocial.activerecord.backend.impl.postgres.adapters.base import ( + PostgresJSONBAdapter as BaseJSONBAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.adapters.json import ( + PostgresJSONBAdapter as JsonModuleJSONBAdapter, +) + +ADAPTER_CLASSES = [ + pytest.param(BaseJSONBAdapter, id="adapters.base"), + pytest.param(JsonModuleJSONBAdapter, id="adapters.json"), +] + + +class _Tagged: + """Marker returned by the sample object hook.""" + + def __init__(self, type_name, payload): + self.type_name = type_name + self.payload = payload + + +def _object_hook(mapping): + if "__type__" in mapping: + return _Tagged(mapping["__type__"], mapping.get("payload")) + return mapping + + +def _dumped_json(wrapper): + """Run the value through psycopg's own JSONB dumper, without a database.""" + return json.loads(JsonbDumper(Jsonb).dump(wrapper)) + + +@pytest.mark.parametrize("adapter_cls", ADAPTER_CLASSES) +class TestJSONBNoHooks: + def test_constructor_defaults(self, adapter_cls): + adapter = adapter_cls() + assert adapter.default is None + assert adapter.object_hook is None + + def test_supported_types_unchanged(self, adapter_cls): + adapter = adapter_cls() + assert adapter.supported_types == {dict: {Jsonb}} + + def test_to_database_returns_jsonb(self, adapter_cls): + adapter = adapter_cls() + result = adapter.to_database({"k": 1, "v": [2, 3]}, dict) + assert isinstance(result, Jsonb) + assert result.obj == {"k": 1, "v": [2, 3]} + assert _dumped_json(result) == {"k": 1, "v": [2, 3]} + + def test_to_database_none(self, adapter_cls): + assert adapter_cls().to_database(None, dict) is None + + def test_from_database_dict_and_list_passthrough(self, adapter_cls): + adapter = adapter_cls() + payload = {"a": 1, "nested": {"b": 2}} + decoded_list = [1, "two", {"three": 3}] + assert adapter.from_database(payload, dict) == payload + assert adapter.from_database(decoded_list, list) == decoded_list + + def test_from_database_string_is_parsed(self, adapter_cls): + adapter = adapter_cls() + assert adapter.from_database('{"a": 1}', dict) == {"a": 1} + assert adapter.from_database("[1, 2, 3]", list) == [1, 2, 3] + + def test_from_database_str_target_keeps_json_text(self, adapter_cls): + adapter = adapter_cls() + payload = {"title": "\u4e2d\u6587"} + assert adapter.from_database(payload, str) == json.dumps(payload, ensure_ascii=False) + assert adapter.from_database("raw text", str) == "raw text" + + def test_unserialisable_value_raises_without_default(self, adapter_cls): + adapter = adapter_cls() + wrapper = adapter.to_database({"amount": Decimal("1.5")}, dict) + with pytest.raises(TypeError): + JsonbDumper(Jsonb).dump(wrapper) + + +@pytest.mark.parametrize("adapter_cls", ADAPTER_CLASSES) +class TestJSONBDefaultHook: + def test_default_is_applied_by_the_dumper(self, adapter_cls): + adapter = adapter_cls(default=str) + wrapper = adapter.to_database({"amount": Decimal("1.5")}, dict) + payload = _dumped_json(wrapper) + assert payload == {"amount": "1.5"} + + def test_default_is_wired_into_the_jsonb_wrapper(self, adapter_cls): + adapter = adapter_cls(default=lambda value: "") + wrapper = adapter.to_database({"when": object()}, dict) + assert wrapper.dumps is not None + assert _dumped_json(wrapper) == {"when": ""} + + def test_default_none_uses_psycopg_global_dumps(self, adapter_cls): + adapter = adapter_cls() + wrapper = adapter.to_database({"a": 1}, dict) + assert wrapper.dumps is None + + def test_default_applies_to_str_target_serialisation(self, adapter_cls): + adapter = adapter_cls(default=str) + # psycopg already decoded the value; serialising back to str must + # route through the same ``default`` instead of raising. + assert adapter.from_database({"amount": Decimal("1.5")}, str) == '{"amount": "1.5"}' + + def test_default_applies_to_batch(self, adapter_cls): + adapter = adapter_cls(default=str) + wrappers = adapter.to_database_batch([{"amount": Decimal("2.5")}, None], dict) + assert wrappers[1] is None + assert _dumped_json(wrappers[0]) == {"amount": "2.5"} + + +@pytest.mark.parametrize("adapter_cls", ADAPTER_CLASSES) +class TestJSONBObjectHook: + def test_hook_runs_over_already_decoded_dict(self, adapter_cls): + """psycopg decodes JSONB before the adapter; the hook still applies.""" + adapter = adapter_cls(object_hook=_object_hook) + decoded = adapter.from_database({"__type__": "user", "payload": {"name": "ann"}}, dict) + assert isinstance(decoded, _Tagged) + assert decoded.type_name == "user" + assert decoded.payload == {"name": "ann"} + + def test_hook_runs_over_nested_objects(self, adapter_cls): + adapter = adapter_cls(object_hook=_object_hook) + decoded = adapter.from_database( + {"outer": {"__type__": "inner", "payload": 1}, "plain": 2}, dict + ) + assert decoded["plain"] == 2 + assert isinstance(decoded["outer"], _Tagged) + assert decoded["outer"].payload == 1 + + def test_hook_runs_over_decoded_list(self, adapter_cls): + adapter = adapter_cls(object_hook=_object_hook) + decoded = adapter.from_database([{"__type__": "a", "payload": 1}, {"b": 2}], list) + assert isinstance(decoded[0], _Tagged) + assert decoded[1] == {"b": 2} + + def test_hook_runs_over_json_string(self, adapter_cls): + adapter = adapter_cls(object_hook=_object_hook) + decoded = adapter.from_database('{"__type__": "user", "payload": {"name": "ann"}}', dict) + assert isinstance(decoded, _Tagged) + assert decoded.payload == {"name": "ann"} + + def test_hook_is_not_applied_for_str_target(self, adapter_cls): + adapter = adapter_cls(object_hook=_object_hook) + assert adapter.from_database({"__type__": "user"}, str) == '{"__type__": "user"}' + + def test_plain_decode_without_hook_matches_dict(self, adapter_cls): + adapter = adapter_cls() + assert adapter.from_database({"__type__": "user"}, dict) == {"__type__": "user"} + + def test_default_and_object_hook_together(self, adapter_cls): + adapter = adapter_cls(default=str, object_hook=_object_hook) + wrapper = adapter.to_database({"__type__": "user", "amount": Decimal("1.5")}, dict) + assert _dumped_json(wrapper) == {"__type__": "user", "amount": "1.5"} + decoded = adapter.from_database({"__type__": "user", "payload": 1}, dict) + assert isinstance(decoded, _Tagged) + + def test_batch_from_database_applies_hook(self, adapter_cls): + adapter = adapter_cls(object_hook=_object_hook) + decoded = adapter.from_database_batch([{"__type__": "user", "payload": 1}, None], dict) + assert isinstance(decoded[0], _Tagged) + assert decoded[1] is None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py new file mode 100644 index 00000000..90ca893c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py @@ -0,0 +1,363 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py +"""DB-free contract tests for the PostgreSQL neutral value adapters. + +Every adapter here works on values only: no connection is opened and no server +is needed. What is pinned is the wire form (WKT/EWKT, pgvector text, bit text, +range literals and MAC text), the read path from the wrapper types and psycopg +objects, the ``TypeConversionError`` wrapping, and the catalogue inventory. +""" + +import math +from datetime import date, datetime, time, timezone +from decimal import Decimal + +import pytest + +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + GeometryCollection, + LineString, + MacAddress, + Multirange, + Point, + Polygon, + Range, + Vector, +) +from rhosocial.activerecord.backend.errors import TypeConversionError +from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import ( + PostgresNeutralBitStringAdapter, + PostgresNeutralGeometryAdapter, + PostgresNeutralMacAddressAdapter, + PostgresNeutralRangeAdapter, + PostgresNeutralVectorAdapter, +) +from rhosocial.activerecord.backend.impl.postgres.backend import ( + AsyncPostgresBackend, + PostgresBackend, +) +from rhosocial.activerecord.backend.impl.postgres.type_values import ( + PostgresBitString, + PostgresGeometry, + PostgresMacaddr, + PostgresMacaddr8, + PostgresMultirange, + PostgresRange, + PostgresVector, +) + +_NEUTRAL_CLASSES = ( + PostgresNeutralBitStringAdapter, + PostgresNeutralGeometryAdapter, + PostgresNeutralMacAddressAdapter, + PostgresNeutralRangeAdapter, + PostgresNeutralVectorAdapter, +) + + +@pytest.fixture(params=[PostgresBackend, AsyncPostgresBackend]) +def backend(request): + """A constructed backend: neither branch opens a connection.""" + return request.param(database="neutral_adapter_unit") + + +def _class_key(adapter): + adapter_class = type(adapter) + return (adapter_class.__module__, adapter_class.__qualname__) + + +class TestInventory: + def test_every_neutral_adapter_is_in_the_catalogue(self, backend): + names = {type(adapter).__name__ for adapter in backend.get_type_adapters()} + for adapter_class in _NEUTRAL_CLASSES: + assert adapter_class.__name__ in names + + def test_neutral_classes_appear_once(self, backend): + keys = [_class_key(adapter) for adapter in backend.get_type_adapters()] + assert len(keys) == len(set(keys)) + + def test_inventory_is_deterministic(self, backend): + first = [_class_key(adapter) for adapter in backend.get_type_adapters()] + second = [_class_key(adapter) for adapter in backend.get_type_adapters()] + assert first == second + assert first == sorted(first) + + +class TestGeometryAdapter: + def test_point_round_trip_without_srid(self): + adapter = PostgresNeutralGeometryAdapter() + point = Point(1, 2) + text = adapter.to_database(point, str) + assert text == "POINT (1.0 2.0)" + assert adapter.from_database(text, Geometry) == point + + def test_point_round_trip_with_ewkt_srid(self): + adapter = PostgresNeutralGeometryAdapter() + point = Point(1, 2, srid=4326) + text = adapter.to_database(point, str) + assert text == "SRID=4326;POINT (1.0 2.0)" + decoded = adapter.from_database(text, Geometry) + assert decoded == point + assert decoded.srid == 4326 + + def test_srid_option_overrides_the_geometry(self): + adapter = PostgresNeutralGeometryAdapter() + assert adapter.to_database(Point(1, 2), str, {"srid": 3857}).startswith("SRID=3857;") + + def test_polygon_and_collection_round_trip(self): + adapter = PostgresNeutralGeometryAdapter() + polygon = Polygon((((0, 0), (10, 0), (10, 10), (0, 0)),), srid=4326) + assert adapter.from_database(adapter.to_database(polygon, str), Geometry) == polygon + collection = GeometryCollection((Point(1, 2), LineString(((0, 0), (1, 1))))) + assert adapter.from_database(adapter.to_database(collection, str), Geometry) == collection + + def test_decodes_the_backend_wrapper(self): + adapter = PostgresNeutralGeometryAdapter() + wrapper = PostgresGeometry.point(1.0, 2.0, srid=4326) + decoded = adapter.from_database(wrapper, Geometry) + assert decoded == Point(1.0, 2.0, srid=4326) + + def test_hex_ewkb_is_rejected_instead_of_guessed(self): + adapter = PostgresNeutralGeometryAdapter() + with pytest.raises(TypeConversionError) as excinfo: + adapter.from_database("0101000020E6100000000000000000F03F", Geometry) + assert "EWKB" in str(excinfo.value) + + def test_wrong_target_type_is_wrapped(self): + adapter = PostgresNeutralGeometryAdapter() + with pytest.raises(TypeConversionError) as excinfo: + adapter.to_database(Point(1, 2), bytes) + assert "Cannot convert Point to Geometry" in str(excinfo.value) + + def test_invalid_wkt_is_wrapped(self): + adapter = PostgresNeutralGeometryAdapter() + with pytest.raises(TypeConversionError): + adapter.to_database("POINT (1 2", str) + + +class TestVectorAdapter: + def test_text_round_trip(self): + adapter = PostgresNeutralVectorAdapter() + vector = Vector((1, 2.5, -3)) + assert adapter.to_database(vector, str) == "[1,2.5,-3]" + assert adapter.from_database("[1,2.5,-3]", Vector) == vector + + def test_decodes_a_plain_sequence_and_the_wrapper(self): + adapter = PostgresNeutralVectorAdapter() + assert adapter.from_database([1.0, 2.0], Vector) == Vector((1.0, 2.0)) + assert adapter.from_database(PostgresVector([1.0, 2.0]), Vector) == Vector((1.0, 2.0)) + + def test_non_finite_components_use_the_pgvector_spellings(self): + adapter = PostgresNeutralVectorAdapter() + infinite = Vector((float("inf"), float("-inf")), allow_non_finite=True) + assert adapter.to_database(infinite, str) == "[Infinity,-Infinity]" + assert adapter.from_database("[Infinity,-Infinity]", Vector) == infinite + + nan_vector = Vector((float("nan"),), allow_non_finite=True) + assert adapter.to_database(nan_vector, str) == "[NaN]" + decoded = adapter.from_database("[NaN]", Vector) + assert len(decoded.values) == 1 + assert math.isnan(decoded.values[0]) + + def test_malformed_text_is_wrapped(self): + adapter = PostgresNeutralVectorAdapter() + for value in ("1,2", "[]", "[1,]", "[a]"): + with pytest.raises(TypeConversionError): + adapter.from_database(value, Vector) + + def test_wrong_target_type_is_wrapped(self): + adapter = PostgresNeutralVectorAdapter() + with pytest.raises(TypeConversionError): + adapter.to_database(Vector((1.0,)), list) + + +class TestBitStringAdapter: + def test_text_round_trip(self): + adapter = PostgresNeutralBitStringAdapter() + bits = BitString.from_bits("1010") + assert adapter.to_database(bits, str) == "1010" + assert adapter.from_database("1010", BitString) == bits + + def test_literal_option_emits_sql_literal(self): + adapter = PostgresNeutralBitStringAdapter() + assert adapter.to_database(BitString.from_bits("1010"), str, {"literal": True}) == ( + "B'1010'" + ) + + def test_declared_length_pads_on_the_right(self): + adapter = PostgresNeutralBitStringAdapter() + decoded = adapter.from_database("1010", BitString, {"length": 8}) + assert decoded.to_bits() == "10100000" + assert decoded.bit_length == 8 + + def test_declared_length_rejects_longer_text(self): + adapter = PostgresNeutralBitStringAdapter() + with pytest.raises(TypeConversionError): + adapter.from_database("10101", BitString, {"length": 4}) + + def test_bytes_and_wrapper_decode(self): + adapter = PostgresNeutralBitStringAdapter() + assert adapter.from_database(b"\xa0", BitString, {"bit_length": 4}) == ( + BitString.from_bits("1010") + ) + assert adapter.from_database(PostgresBitString("1010"), BitString) == ( + BitString.from_bits("1010") + ) + + def test_invalid_text_is_wrapped(self): + adapter = PostgresNeutralBitStringAdapter() + for value in ("102", "", "B'101'"[:-1]): + with pytest.raises(TypeConversionError): + adapter.from_database(value, BitString) + + +class TestRangeAdapter: + def test_numeric_range_round_trip(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(1, 10, "[)") + assert adapter.to_database(value, str) == "[1,10)" + assert adapter.from_database("[1,10)", Range) == value + + def test_unbounded_bounds_are_normalized(self): + adapter = PostgresNeutralRangeAdapter() + decoded = adapter.from_database("(,5)", Range) + assert decoded == Range(None, 5, "()") + assert adapter.to_database(decoded, str) == "(,5)" + # A missing bound is forced to '('; the present upper bound keeps ']'. + assert adapter.from_database("[,5]", Range) == Range(None, 5, "(]") + + def test_decimal_bounds_keep_their_precision(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(Decimal("1.5"), Decimal("2.5"), "(]") + assert adapter.to_database(value, str) == "(1.5,2.5]" + assert adapter.from_database("(1.5,2.5]", Range) == value + + def test_quoted_text_bounds_use_postgres_quoting(self): + adapter = PostgresNeutralRangeAdapter() + value = Range("a b", "c", "[)") + assert adapter.to_database(value, str) == '["a b","c")' + assert adapter.from_database('["a b","c")', Range) == value + + def test_quote_and_backslash_escapes_round_trip(self): + adapter = PostgresNeutralRangeAdapter() + value = Range('a"b\\c', "z", "[)") + text = adapter.to_database(value, str) + assert text == '["a\\"b\\\\c","z")' + assert adapter.from_database(text, Range) == value + + def test_date_bounds_need_an_element_type_hint(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(date(2024, 1, 1), date(2024, 12, 31), "[)") + text = adapter.to_database(value, str) + assert text == '["2024-01-01","2024-12-31")' + decoded = adapter.from_database(text, Range, {"range_type": "daterange"}) + assert decoded == value + + def test_datetime_bounds_need_an_element_type_hint(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0), "[)") + text = adapter.to_database(value, str) + assert adapter.from_database(text, Range, {"element_type": "datetime"}) == value + + def test_timestamp_with_timezone_bounds_need_a_hint(self): + adapter = PostgresNeutralRangeAdapter() + value = Range( + datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc), + datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc), + "[)", + ) + text = adapter.to_database(value, str) + assert adapter.from_database(text, Range, {"range_type": "tstzrange"}) == value + + def test_time_bounds_need_a_hint(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(time(9, 0), time(17, 30), "[)") + text = adapter.to_database(value, str) + assert adapter.from_database(text, Range, {"element_type": "time"}) == value + + def test_quoted_bounds_without_a_hint_stay_strings(self): + adapter = PostgresNeutralRangeAdapter() + decoded = adapter.from_database('["2024-01-01","2024-01-02")', Range) + assert decoded.lower == "2024-01-01" + assert isinstance(decoded.lower, str) + + def test_a_bad_hint_value_is_wrapped(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError): + adapter.from_database('["not-a-date","2024-01-02")', Range, {"element_type": "date"}) + + def test_an_unknown_hint_label_is_wrapped(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError): + adapter.from_database("[1,2)", Range, {"element_type": "uuid"}) + + def test_empty_range(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(empty=True) + assert adapter.to_database(value, str) == "empty" + assert adapter.from_database("empty", Range) == value + + def test_multirange_round_trip(self): + adapter = PostgresNeutralRangeAdapter() + value = Multirange((Range(1, 5), Range(10, 15))) + assert adapter.to_database(value, str) == "{[1,5),[10,15)}" + assert adapter.from_database("{[1,5),[10,15)}", Multirange) == value + assert adapter.from_database("{}", Multirange) == Multirange(()) + + def test_decodes_the_backend_wrappers(self): + adapter = PostgresNeutralRangeAdapter() + wrapper = PostgresRange(1, 10, lower_inc=True, upper_inc=False) + assert adapter.from_database(wrapper, Range) == Range(1, 10, "[)") + multi = PostgresMultirange([wrapper, PostgresRange(20, 30)]) + assert adapter.from_database(multi, Multirange) == Multirange((Range(1, 10), Range(20, 30))) + + def test_decodes_psycopg_range_objects(self): + psycopg_range = pytest.importorskip("psycopg.types.range") + adapter = PostgresNeutralRangeAdapter() + value = psycopg_range.Range(1, 5, "[)") + assert adapter.from_database(value, Range) == Range(1, 5, "[)") + assert adapter.from_database([value, psycopg_range.Range(10, 15, "[)")], Multirange) == ( + Multirange((Range(1, 5), Range(10, 15))) + ) + + def test_malformed_literals_are_wrapped(self): + adapter = PostgresNeutralRangeAdapter() + for value in ("1,2", "[1,2", "[1,2,3)", "[a,b", "{[1,2)"): + with pytest.raises(TypeConversionError): + adapter.from_database(value, Range) + + def test_target_type_mismatch_is_wrapped(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError): + adapter.from_database("[1,2)", Multirange) + + +class TestMacAddressAdapter: + def test_canonical_text_round_trip(self): + adapter = PostgresNeutralMacAddressAdapter() + mac = MacAddress.parse("08:00:2B:01:02:03") + assert adapter.to_database(mac, str) == "08:00:2b:01:02:03" + assert adapter.from_database("08:00:2b:01:02:03", MacAddress) == mac + + def test_eui64_option_expands_six_octets(self): + adapter = PostgresNeutralMacAddressAdapter() + mac = MacAddress.parse("08:00:2b:01:02:03") + assert adapter.to_database(mac, str, {"eui64": True}) == ("08:00:2b:ff:fe:01:02:03") + assert adapter.to_database(mac, str, {"version": 8}) == ("08:00:2b:ff:fe:01:02:03") + + def test_decodes_bytes_and_backend_wrappers(self): + adapter = PostgresNeutralMacAddressAdapter() + expected = MacAddress.parse("08:00:2b:01:02:03") + assert adapter.from_database(b"\x08\x00\x2b\x01\x02\x03", MacAddress) == expected + assert adapter.from_database(PostgresMacaddr("08:00:2b:01:02:03"), MacAddress) == (expected) + assert adapter.from_database( + PostgresMacaddr8("08:00:2b:ff:fe:01:02:03"), MacAddress + ) == MacAddress.parse("08:00:2b:ff:fe:01:02:03") + + def test_invalid_input_is_wrapped(self): + adapter = PostgresNeutralMacAddressAdapter() + with pytest.raises(TypeConversionError): + adapter.from_database("08:00:2b:01:02", MacAddress) + with pytest.raises(TypeConversionError): + adapter.to_database(MacAddress.parse("08:00:2b:01:02:03"), int) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py new file mode 100644 index 00000000..192ce075 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py @@ -0,0 +1,56 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py +"""The backend's adapter inventory is a catalogue, not a recommendation. + +PostgreSQL-specific adapters are registered during construction and never need +a server, so the whole file runs without a database. What is pinned here is the +shape of ``get_type_adapters()``: it implements the core protocol, it lists +classes once each, and it answers in the same order every time. +""" + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.backend import ( + AsyncPostgresBackend, + PostgresBackend, +) +from rhosocial.activerecord.backend.type_adapter import TypeAdapterCatalogProtocol + + +def _backend_class_key(adapter): + adapter_class = type(adapter) + return (adapter_class.__module__, adapter_class.__qualname__) + + +@pytest.fixture(params=[PostgresBackend, AsyncPostgresBackend]) +def backend(request): + """A constructed backend: neither branch opens a connection.""" + return request.param(database="adapter_inventory_unit") + + +class TestGetTypeAdapters: + def test_implements_the_catalogue_protocol(self, backend): + assert isinstance(backend, TypeAdapterCatalogProtocol) + + def test_inventory_is_not_empty(self, backend): + assert backend.get_type_adapters() + + def test_each_adapter_class_appears_once(self, backend): + keys = [_backend_class_key(adapter) for adapter in backend.get_type_adapters()] + assert len(keys) == len(set(keys)) + + def test_order_is_deterministic_and_sorted_by_class(self, backend): + first = [_backend_class_key(adapter) for adapter in backend.get_type_adapters()] + second = [_backend_class_key(adapter) for adapter in backend.get_type_adapters()] + assert first == second + assert first == sorted(first) + + def test_a_new_list_is_returned_on_each_call(self, backend): + first = backend.get_type_adapters() + second = backend.get_type_adapters() + assert first is not second + assert first == second + + def test_default_adapter_suggestions_are_still_provided(self, backend): + suggestions = backend.get_default_adapter_suggestions() + assert isinstance(suggestions, dict) + assert suggestions diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py index 99e0c967..ab5763da 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py @@ -1,29 +1,65 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py -"""The mapped-model fixture group this directory owns. +"""L2 backend fixtures for the mapped-model basic tests. The directory runs the shared ``basic`` mapped-model tests; the models they request (``MappedUser``, ``MappedPost``, ``MappedComment``) read and write the -topic's ``users``, ``posts`` and ``comments`` tables, so the group is exactly -those three. +topic's ``users``, ``posts`` and ``comments`` tables, so the schema group is +exactly those three definitions. + +- ``database``: one database per directory (session scope, emptied at start); +- ``schema``: those three tables, dropped and recreated for every test + (function scope), so each test starts from empty tables. """ -from rhosocial.activerecord.testsuite.feature.basic.fixtures import tables +from pathlib import Path + +import pytest + +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( + CommentDefinition, + PostDefinition, + UserDefinition, +) + +DDL = ExecutionOptions(stmt_type=StatementType.DDL) + +DEFINITIONS = (UserDefinition, PostDefinition, CommentDefinition) + -GROUP_TABLES = ("users", "posts", "comments") +def _database_name() -> str: + """Database name from this directory's namespace (below ``feature``).""" + parts = Path(__file__).parent.parts + start = parts.index("feature") + 1 + return "test_" + "_".join(parts[start:]) -def ensure_database(environment): - """Create the directory's database, or clear it when it already exists.""" - environment.reset_database() +@pytest.fixture(scope="session") +def database_config(backend_scenario): + """The scenario, its connection configuration, and the database name.""" + name = _database_name() + return backend_scenario, backend_scenario.make_config(name), name -def prepare(environment): - """Create the group's tables before every test.""" - for name in GROUP_TABLES: - environment.execute(tables.BASIC_TABLES[name](environment.dialect)) +@pytest.fixture(scope="session") +def database(database_config): + """The directory's database, prepared once and left for later files.""" + scenario, config, name = database_config + scenario.reset_database(name) + backend = scenario.backend_class(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + yield backend + backend.disconnect() -def teardown(environment): - """Drop the group's tables after every test.""" - for name in reversed(GROUP_TABLES): - environment.execute(tables.drop_table(environment.dialect, name)) +@pytest.fixture(scope="function", autouse=True) +def schema(database): + """Drop and recreate the tables this directory uses, before every test.""" + fixtures = [definition(database.dialect) for definition in DEFINITIONS] + for fixture in fixtures: + database.execute(*fixture.create_table.to_sql(), options=DDL) + yield + for fixture in reversed(fixtures): + database.execute(*fixture.drop_table.to_sql(), options=DDL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py index 3195053a..e57892a9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py @@ -1,69 +1,68 @@ # tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py -"""Pytest configuration for the connection pool tests. - -The directory owns its logical database the same way every migrated directory -does: it declares the lifecycle here and takes the scenario and configuration -from the testsuite ``environment``, so running against several scenarios gets -one pool per scenario instead of a first-scenario guess. The concurrency tables -are created and dropped by the table fixtures themselves, so ``prepare`` and -``teardown`` have no group to manage. +"""L2 backend fixtures for the connection-pool tests. + +The pool fixtures own their connections: each creates the directory's database +for the scenario it runs under and hands out PostgreSQL backends from it. The +concurrency tables are created and dropped by the table fixtures through that +pool, from the definitions in ``pool_definitions.py``. + +``database_config`` declares the directory's identity (scenario, configuration +and database name). It exists for the xdist grouping contract: a scenario's +tests for one directory stay on one worker, while different scenarios are +different databases and may run in parallel. """ +from functools import partial +from pathlib import Path from typing import Generator import pytest import pytest_asyncio +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType from rhosocial.activerecord.connection.pool import ( AsyncBackendPool, BackendPool, PoolConfig, ) +from pool_definitions import ( + AsyncConcurrentTestPostsDefinition, + AsyncConcurrentTestUsersDefinition, + ConcurrentTestPostsDefinition, + ConcurrentTestUsersDefinition, +) -def ensure_database(environment): - """Create the directory's database, or clear it when it already exists.""" - environment.reset_database() - - -def prepare(environment): - """No group tables: each table fixture creates what it needs.""" - - -def teardown(environment): - """No group tables: each table fixture drops what it created.""" - - -def _backend_factory(environment): - """Return a factory producing sync backends for this environment.""" - config = environment.make_config() - - def factory(): - return environment.scenario.backend_class(connection_config=config) - - return factory +DDL = ExecutionOptions(stmt_type=StatementType.DDL) -def _async_backend_factory(environment): - """Return a factory producing async backends for this environment.""" - config = environment.make_config() +def _database_name() -> str: + """Database name from this directory's namespace (below ``feature``).""" + parts = Path(__file__).parent.parts + start = parts.index("feature") + 1 + return "test_" + "_".join(parts[start:]) - def factory(): - return environment.scenario.async_backend_class(connection_config=config) - return factory +@pytest.fixture(scope="session") +def database_config(backend_scenario): + """The scenario, its connection configuration, and the directory database name.""" + name = _database_name() + return backend_scenario, backend_scenario.make_config(name), name @pytest.fixture(scope="function") -def postgres_pool(environment) -> Generator[BackendPool, None, None]: +def postgres_pool(database_config) -> Generator[BackendPool, None, None]: """Create a BackendPool with PostgreSQL backends for testing.""" + scenario, config, name = database_config + scenario.reset_database(name) pool_config = PoolConfig( min_size=1, max_size=5, timeout=30.0, validate_on_borrow=True, validation_query="SELECT 1", - backend_factory=_backend_factory(environment), + backend_factory=partial(scenario.backend_class, connection_config=config), ) pool = BackendPool.create(pool_config) @@ -72,15 +71,17 @@ def postgres_pool(environment) -> Generator[BackendPool, None, None]: @pytest_asyncio.fixture(scope="function") -async def async_postgres_pool(environment) -> AsyncBackendPool: +async def async_postgres_pool(database_config) -> AsyncBackendPool: """Create an AsyncBackendPool with PostgreSQL backends for testing.""" + scenario, config, name = database_config + scenario.reset_database(name) pool_config = PoolConfig( min_size=1, max_size=5, timeout=30.0, validate_on_borrow=True, validation_query="SELECT 1", - backend_factory=_async_backend_factory(environment), + backend_factory=partial(scenario.async_backend_class, connection_config=config), ) pool = await AsyncBackendPool.create(pool_config) @@ -89,14 +90,16 @@ async def async_postgres_pool(environment) -> AsyncBackendPool: @pytest.fixture(scope="function") -def postgres_pool_large(environment) -> Generator[BackendPool, None, None]: +def postgres_pool_large(database_config) -> Generator[BackendPool, None, None]: """Create a larger BackendPool for stress testing.""" + scenario, config, name = database_config + scenario.reset_database(name) pool_config = PoolConfig( min_size=2, max_size=10, timeout=60.0, validate_on_borrow=False, # Faster for stress tests - backend_factory=_backend_factory(environment), + backend_factory=partial(scenario.backend_class, connection_config=config), ) pool = BackendPool.create(pool_config) @@ -105,14 +108,16 @@ def postgres_pool_large(environment) -> Generator[BackendPool, None, None]: @pytest_asyncio.fixture(scope="function") -async def async_postgres_pool_large(environment) -> AsyncBackendPool: +async def async_postgres_pool_large(database_config) -> AsyncBackendPool: """Create a larger AsyncBackendPool for stress testing.""" + scenario, config, name = database_config + scenario.reset_database(name) pool_config = PoolConfig( min_size=2, max_size=10, timeout=60.0, validate_on_borrow=False, - backend_factory=_async_backend_factory(environment), + backend_factory=partial(scenario.async_backend_class, connection_config=config), ) pool = await AsyncBackendPool.create(pool_config) @@ -126,32 +131,21 @@ async def async_postgres_pool_large(environment) -> AsyncBackendPool: @pytest.fixture(scope="function") def postgres_pool_with_tables(postgres_pool: BackendPool) -> Generator[BackendPool, None, None]: """Create a pool with test tables initialized.""" + definitions = ( + ConcurrentTestPostsDefinition, + ConcurrentTestUsersDefinition, + ) with postgres_pool.connection() as backend: - backend.execute("DROP TABLE IF EXISTS concurrent_test_users") - backend.execute("DROP TABLE IF EXISTS concurrent_test_posts") - backend.execute(""" - CREATE TABLE concurrent_test_users ( - id SERIAL PRIMARY KEY, - thread_id INTEGER, - name VARCHAR(255), - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ) - """) - backend.execute(""" - CREATE TABLE concurrent_test_posts ( - id SERIAL PRIMARY KEY, - thread_id INTEGER, - user_id INTEGER, - title VARCHAR(255), - content TEXT - ) - """) + fixtures = [definition(backend.dialect) for definition in definitions] + for fixture in fixtures: + backend.execute(*fixture.drop_table.to_sql(), options=DDL) + backend.execute(*fixture.create_table.to_sql(), options=DDL) yield postgres_pool with postgres_pool.connection() as backend: - backend.execute("DROP TABLE IF EXISTS concurrent_test_posts") - backend.execute("DROP TABLE IF EXISTS concurrent_test_users") + for fixture in reversed(fixtures): + backend.execute(*fixture.drop_table.to_sql(), options=DDL) @pytest_asyncio.fixture(scope="function") @@ -159,29 +153,18 @@ async def async_postgres_pool_with_tables( async_postgres_pool: AsyncBackendPool, ) -> AsyncBackendPool: """Create an async pool with test tables initialized.""" + definitions = ( + AsyncConcurrentTestPostsDefinition, + AsyncConcurrentTestUsersDefinition, + ) async with async_postgres_pool.connection() as backend: - await backend.execute("DROP TABLE IF EXISTS concurrent_test_users") - await backend.execute("DROP TABLE IF EXISTS concurrent_test_posts") - await backend.execute(""" - CREATE TABLE concurrent_test_users ( - id SERIAL PRIMARY KEY, - task_id INTEGER, - name VARCHAR(255), - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ) - """) - await backend.execute(""" - CREATE TABLE concurrent_test_posts ( - id SERIAL PRIMARY KEY, - task_id INTEGER, - user_id INTEGER, - title VARCHAR(255), - content TEXT - ) - """) + fixtures = [definition(backend.dialect) for definition in definitions] + for fixture in fixtures: + await backend.execute(*fixture.drop_table.to_sql(), options=DDL) + await backend.execute(*fixture.create_table.to_sql(), options=DDL) yield async_postgres_pool async with async_postgres_pool.connection() as backend: - await backend.execute("DROP TABLE IF EXISTS concurrent_test_posts") - await backend.execute("DROP TABLE IF EXISTS concurrent_test_users") + for fixture in reversed(fixtures): + await backend.execute(*fixture.drop_table.to_sql(), options=DDL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py new file mode 100644 index 00000000..9af82d67 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py @@ -0,0 +1,146 @@ +# tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py +"""The connection-pool tests' own tables. + +The concurrent tests create and drop these tables through the pool itself, so +their DDL belongs here rather than in the conftest or in a test body: a +definition class receives only a ``dialect`` and knows nothing about backends, +databases, connection pools or execution. + +The sync and async test sets each use their own pair of tables, and the only +difference between the two pairs is the column naming the worker +(``thread_id`` for threads, ``task_id`` for asyncio tasks). + +The primary keys are declared with PostgreSQL's own ``SERIAL`` type class, so +the DDL the tables get is the same ``SERIAL PRIMARY KEY`` the inline SQL used to +spell; no SQL text is written here. +""" + +from rhosocial.activerecord.backend.expression import ( + ColumnConstraint as Constraint, + ColumnDefinition as Column, + CreateTableStatement as CreateTable, + DropTableStatement as DropTable, + current_timestamp, +) +from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.statements import ( + ColumnDefaultConstraint as Default, + ColumnPrimaryKeyConstraint as PrimaryKey, +) +from rhosocial.activerecord.backend.expression.types import ( + IntegerType as Int, + TextType as Text, + TimestampType, + VarCharType as VarChar, +) +from rhosocial.activerecord.backend.impl.postgres.expression.types import ( + PostgresSerialType, +) +from rhosocial.activerecord.testsuite.core.fixture_types import supports_drop_if_exists + + +class Definition: + """Base class for the pool tests' table definitions.""" + + table_name = "" + + def __init__(self, dialect): + self.dialect = dialect + self.create_table = CreateTable( + self.dialect, + table=Table(self.dialect, self.table_name), + columns=self.columns(), + ) + self.drop_table = DropTable( + self.dialect, + table=Table(self.dialect, self.table_name), + if_exists=supports_drop_if_exists(self.dialect), + ) + + def columns(self): + raise NotImplementedError + + def column(self, name, sql_type, constraints=None): + return Column(self.dialect, name, sql_type, constraints=constraints or []) + + def auto_pk(self, name="id"): + return self.column( + name, + PostgresSerialType(self.dialect), + [ + Constraint( + self.dialect, + branch=PrimaryKey(self.dialect), + ) + ], + ) + + def created_at(self, name="created_at"): + return self.column( + name, + TimestampType(self.dialect), + [ + Constraint( + self.dialect, + branch=Default(self.dialect, current_timestamp(self.dialect)), + ) + ], + ) + + +class ConcurrentTestUsersDefinition(Definition): + """The synchronized users table.""" + + table_name = "concurrent_test_users" + + def columns(self): + return [ + self.auto_pk(), + self.column("thread_id", Int(self.dialect)), + self.column("name", VarChar(self.dialect, 255)), + self.created_at(), + ] + + +class ConcurrentTestPostsDefinition(Definition): + """The synchronized posts table.""" + + table_name = "concurrent_test_posts" + + def columns(self): + return [ + self.auto_pk(), + self.column("thread_id", Int(self.dialect)), + self.column("user_id", Int(self.dialect)), + self.column("title", VarChar(self.dialect, 255)), + self.column("content", Text(self.dialect)), + ] + + +class AsyncConcurrentTestUsersDefinition(Definition): + """The asyncio users table.""" + + table_name = "concurrent_test_users" + + def columns(self): + return [ + self.auto_pk(), + self.column("task_id", Int(self.dialect)), + self.column("name", VarChar(self.dialect, 255)), + self.created_at(), + ] + + +class AsyncConcurrentTestPostsDefinition(Definition): + """The asyncio posts table.""" + + table_name = "concurrent_test_posts" + + def columns(self): + return [ + self.auto_pk(), + self.column("task_id", Int(self.dialect)), + self.column("user_id", Int(self.dialect)), + self.column("title", VarChar(self.dialect, 255)), + self.column("content", Text(self.dialect)), + ] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py index 644b2aa3..a27485b1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py @@ -1,28 +1,62 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py -"""The PostgreSQL-only collation test set. +"""L2 backend fixtures for the PostgreSQL-only collation test set. These tests are backend-specific, so the fixture group lives here rather than -in the shared suite; the tables still come from the topic's declarations. -""" - -from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403 -from rhosocial.activerecord.testsuite.feature.query.fixtures import tables - -GROUP_TABLES = ("searchable_items",) - - -def ensure_database(environment): - """Create the directory's database, or clear it when it already exists.""" - environment.reset_database() +in the shared suite; the table definition still comes from the query topic. +- ``database``: one database per directory (session scope, emptied at start); +- ``schema``: the ``searchable_items`` table, dropped and recreated for every + test (function scope), so each test starts from an empty table. +""" -def prepare(environment): - """Create the group's tables before every test.""" - for name in GROUP_TABLES: - environment.execute(tables.QUERY_TABLES[name](environment.dialect)) +from pathlib import Path +import pytest -def teardown(environment): - """Drop the group's tables after every test.""" - for name in reversed(GROUP_TABLES): - environment.execute(tables.drop_table(environment.dialect, name)) +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403 +from rhosocial.activerecord.testsuite.feature.query.fixtures.definitions import ( + SearchableItemsDefinition, +) + +DDL = ExecutionOptions(stmt_type=StatementType.DDL) + +DEFINITIONS = (SearchableItemsDefinition,) + + +def _database_name() -> str: + """Database name from this directory's namespace (below ``feature``).""" + parts = Path(__file__).parent.parts + start = parts.index("feature") + 1 + return "test_" + "_".join(parts[start:]) + + +@pytest.fixture(scope="session") +def database_config(backend_scenario): + """The scenario, its connection configuration, and the database name.""" + name = _database_name() + return backend_scenario, backend_scenario.make_config(name), name + + +@pytest.fixture(scope="session") +def database(database_config): + """The directory's database, prepared once and left for later files.""" + scenario, config, name = database_config + scenario.reset_database(name) + backend = scenario.backend_class(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + yield backend + backend.disconnect() + + +@pytest.fixture(scope="function", autouse=True) +def schema(database): + """Drop and recreate the table this directory uses, before every test.""" + fixtures = [definition(database.dialect) for definition in DEFINITIONS] + for fixture in fixtures: + database.execute(*fixture.create_table.to_sql(), options=DDL) + yield + for fixture in reversed(fixtures): + database.execute(*fixture.drop_table.to_sql(), options=DDL) From 5c5882aed1228a0fed4bc36205f2635a47186ccb Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 04:05:30 +0800 Subject: [PATCH 03/81] fix(native): skip multirange tables/tests before PostgreSQL 14 int4multirange does not exist on servers older than 14, so the ranges fixture could not create its table. The class now skips with the server version named; no type substitution is made. --- .../feature/backend/adapters/native/conftest.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index 1e2a57e3..ed7cf793 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -52,11 +52,24 @@ def _require_extension(backend, name): ) +def _supports_multirange(backend) -> bool: + """PostgreSQL 14 added the multirange types; older servers refuse the DDL.""" + version = getattr(backend.dialect, "version", None) + if version is None: + return True + return tuple(version)[:2] >= (14,) + + @pytest.fixture(scope="class") def native_backend(postgres_backend_class, request): """The class's backend, with the class's built-in tables created.""" backend = postgres_backend_class names = tuple(getattr(request.cls, "TABLES", ())) + if "native_ranges" in names and not _supports_multirange(backend): + pytest.skip( + "PostgreSQL before 14 has no multirange types " + f"(server {backend.dialect.version})" + ) if names: _create_tables(backend, BUILTIN_SCHEMA, names) return backend From 43fd18d9d2ecf04e420c6e787e8a41d0c76f8c68 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 12:29:41 +0800 Subject: [PATCH 04/81] fix(native): name the minimum server version per native table int4multirange needs PostgreSQL 14 and xid8 needs 13, so the wrapped-scalars and multirange tables cannot be created on older servers. Each table now carries its minimum version and the class is skipped with the server version in the reason instead of failing in fixture setup. --- .../backend/adapters/native/conftest.py | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index ed7cf793..1c0decf6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -52,12 +52,13 @@ def _require_extension(backend, name): ) -def _supports_multirange(backend) -> bool: - """PostgreSQL 14 added the multirange types; older servers refuse the DDL.""" - version = getattr(backend.dialect, "version", None) - if version is None: - return True - return tuple(version)[:2] >= (14,) +#: Tables whose DDL uses types a server may not have. The value is the +#: minimum server version; below it the class is skipped with the reason. +_TABLE_MIN_VERSION = { + "native_ranges": (14,), # int4multirange is PostgreSQL 14+ + "native_multiranges": (14,), + "native_wrapped_scalars": (13,), # xid8 is PostgreSQL 13+ +} @pytest.fixture(scope="class") @@ -65,11 +66,16 @@ def native_backend(postgres_backend_class, request): """The class's backend, with the class's built-in tables created.""" backend = postgres_backend_class names = tuple(getattr(request.cls, "TABLES", ())) - if "native_ranges" in names and not _supports_multirange(backend): - pytest.skip( - "PostgreSQL before 14 has no multirange types " - f"(server {backend.dialect.version})" - ) + server = tuple(getattr(backend.dialect, "version", None) or ()) + for name in names: + minimum = _TABLE_MIN_VERSION.get(name) + if minimum and server[: len(minimum)] < minimum: + pytest.skip( + "PostgreSQL {} lacks the column types of {} " + "(needs >= {})".format( + ".".join(str(p) for p in server) or "?", name, minimum[0] + ) + ) if names: _create_tables(backend, BUILTIN_SCHEMA, names) return backend From 09f54acebb0f98aa6351cf6fc82769039a7918f3 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 12:43:31 +0800 Subject: [PATCH 05/81] fix(native): ask the dialect's type support switches (corrects 43fd18d) The native fixture decides whether its table can be created by asking the dialect's own switches (supports_multirange_type, supports_xid8_type) instead of comparing server versions in the test; the skip reason names the switch that answered. Corrects the hand-written version table in 43fd18d. --- .../backend/adapters/native/conftest.py | 27 +++++++++---------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index 1c0decf6..f5691a4d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -52,13 +52,14 @@ def _require_extension(backend, name): ) -#: Tables whose DDL uses types a server may not have. The value is the -#: minimum server version; below it the class is skipped with the reason. -_TABLE_MIN_VERSION = { - "native_ranges": (14,), # int4multirange is PostgreSQL 14+ - "native_multiranges": (14,), - "native_wrapped_scalars": (13,), # xid8 is PostgreSQL 13+ -} +#: The dialect's own support switches for the column types these native tables +#: need. The conftest never inspects a server version itself: it asks the +#: dialect, and the dialect answers per version and per capability. +_TABLE_TYPE_SWITCHES = ( + ("native_ranges", "supports_multirange_type", "multirange"), + ("native_multiranges", "supports_multirange_type", "multirange"), + ("native_wrapped_scalars", "supports_xid8_type", "xid8"), +) @pytest.fixture(scope="class") @@ -66,15 +67,11 @@ def native_backend(postgres_backend_class, request): """The class's backend, with the class's built-in tables created.""" backend = postgres_backend_class names = tuple(getattr(request.cls, "TABLES", ())) - server = tuple(getattr(backend.dialect, "version", None) or ()) - for name in names: - minimum = _TABLE_MIN_VERSION.get(name) - if minimum and server[: len(minimum)] < minimum: + for table, probe, concept in _TABLE_TYPE_SWITCHES: + if table in names and not getattr(backend.dialect, probe)(): pytest.skip( - "PostgreSQL {} lacks the column types of {} " - "(needs >= {})".format( - ".".join(str(p) for p in server) or "?", name, minimum[0] - ) + f"this dialect does not support {concept} " + f"({probe} is False)" ) if names: _create_tables(backend, BUILTIN_SCHEMA, names) From 1719fdf59f45f8b8ec0e7d5f0aa84589430a39f9 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 17:26:33 +0800 Subject: [PATCH 06/81] fix(postgres): decide every skip by the dialect's probes, not by version tuples Six test files compared get_server_version() with a hard-coded floor to decide whether to run. They now ask the dialect's own support switches: - macaddr8 -> supports_data_type_postgres_macaddr8 (existed, >= 10) - pg_lsn -> supports_data_type_postgres_pg_lsn, gated at 9.4 (the probe was an always-true stub, which made the lsn test's skip unreachable) - pg_lsn addition (14) -> new supports_pg_lsn_addition probe - bit_count (14) -> new supports_bit_count probe - partitioned-table primary key (11) -> new supports_partitioned_table_primary_key probe, plus its protocol declaration - multirange family in native_ranges -> supports_multirange() No assertion was weakened; the only behavioural difference is that 'no' now comes from the dialect instead of from a number the test wrote down. --- .../impl/postgres/mixins/ddl/partition.py | 13 +++++++++++++ .../backend/impl/postgres/mixins/function.py | 10 ++++++++++ .../impl/postgres/mixins/types/data_type.py | 9 +++++++++ .../mixins/types/data_type_formatting.py | 9 ++++++++- .../impl/postgres/protocols/ddl/partition.py | 11 +++++++++++ .../impl/postgres/protocols/types/data_type.py | 10 ++++++++++ .../adapters/native/test_native_ranges.py | 9 ++------- .../test_bitstring_functions_integration.py | 16 ++++++---------- .../partition/test_partition_explain.py | 8 +++++--- .../partition/test_partition_operations.py | 14 ++++++++++---- .../postgres/types/lsn/test_lsn_integration.py | 18 +++++++++--------- .../test_network_address_integration.py | 4 ++-- .../range/test_range_types_integration.py | 15 +++++++-------- 13 files changed, 102 insertions(+), 44 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py index b6530102..f724892b 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py @@ -63,6 +63,19 @@ def supports_partitioned_table_creation(self) -> bool: """ return self.supports_table_partitioning() + def supports_partitioned_table_primary_key(self) -> bool: + """Check if a partitioned parent table can declare a primary key. + + PostgreSQL 10 refused a PRIMARY KEY on a partitioned table unless + it included the partition key, so a parent declared with one fails + on 10 and works from 11 on -- a parent partitioned by created_at + with PRIMARY KEY (id, created_at) is the shape callers rely on. + + Returns: + True if PostgreSQL version >= 11. + """ + return self.version_at_least((11, 0, 0)) + def supports_range_table_partitioning(self) -> bool: """Check if RANGE table partitioning is supported. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py index c280cccd..8b947810 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py @@ -101,3 +101,13 @@ def _check_function_support(self, func_name: str) -> "FunctionSupportInfo": return FunctionSupportInfo(supported=False, reason="extension_version_insufficient") return FunctionSupportInfo(supported=True) + + def supports_bit_count(self) -> bool: + """Whether bit_count(bit) is supported. + + Native function, PostgreSQL 14+. The bit-string function tables of + the 9.5 through 13 documentation carry no bit_count entry; it first + appears in 14. + https://www.postgresql.org/docs/current/functions-bitstring.html + """ + return self.version_at_least((14, 0, 0)) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py index d3aaafa0..f54b49b4 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py @@ -88,6 +88,15 @@ def supports_xid8_type(self) -> bool: """ return self.version_at_least((13, 0, 0)) + def supports_pg_lsn_addition(self) -> bool: + """Whether a pg_lsn value can be added to a numeric byte count. + + Native feature, PostgreSQL 14+. The pg_lsn subtraction operator + predates it; only 14 introduced ``pg_lsn + numeric``. + https://www.postgresql.org/docs/current/datatype-pg-lsn.html#DATATYPE-PG-LSN + """ + return self.version_at_least((14, 0, 0)) + def format_create_range_type( self, expr: CreateTypeStatement, diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py index d0c9e56f..19277e03 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py @@ -812,7 +812,14 @@ def supports_data_type_postgres_tid(self) -> bool: return True def supports_data_type_postgres_pg_lsn(self) -> bool: - return True + """pg_lsn arrived in PostgreSQL 9.4. + + An unconditional True told every server it could have a pg_lsn + column, and a 9.3 server found out by executing the DDL ('type + "pg_lsn" does not exist'). The type is documented from 9.4 on: + https://www.postgresql.org/docs/9.4/datatype-pg-lsn.html + """ + return self.version_at_least((9, 4, 0)) def supports_data_type_postgres_hstore(self) -> bool: return True diff --git a/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py b/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py index e152392b..b32ed78e 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py @@ -33,6 +33,7 @@ class PostgresPartitionSupport(PartitionSupport, Protocol): - Concurrent DETACH (PG 14+) - Partition bounds expression (PG 12+) - Partitionwise join/aggregate (PG 11+) + - Primary key on a partitioned table (PG 11+) Official Documentation: - Partitioning: https://www.postgresql.org/docs/current/ddl-partitioning.html @@ -43,6 +44,7 @@ class PostgresPartitionSupport(PartitionSupport, Protocol): - HASH partitioning: PostgreSQL 11+ - DEFAULT partition: PostgreSQL 11+ - Row movement: PostgreSQL 11+ + - Primary key on a partitioned table: PostgreSQL 11+ - Concurrent DETACH: PostgreSQL 14+ - Partition bounds expression: PostgreSQL 12+ - Partitionwise join: PostgreSQL 11+ @@ -73,6 +75,15 @@ def supports_partition_key_update(self) -> bool: """ ... + def supports_partitioned_table_primary_key(self) -> bool: + """Whether a partitioned parent table can declare a primary key. + + Native feature, PostgreSQL 11+. + PostgreSQL 10 refuses a PRIMARY KEY on a partitioned table unless it + includes the partition key, so the constraint arrives with 11. + """ + ... + def supports_concurrent_detach(self) -> bool: """Whether CONCURRENTLY DETACH PARTITION is supported. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py b/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py index 75dc1797..76ec879a 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py @@ -21,6 +21,7 @@ class PostgresDataTypeSupport(Protocol): - Numeric Infinity (PG 14+) - Nondeterministic ICU collation (PG 12+) - xid8 type (PG 13+) + - pg_lsn addition (PG 14+) Official Documentation: - Multirange: https://www.postgresql.org/docs/current/rangetypes.html @@ -37,6 +38,7 @@ class PostgresDataTypeSupport(Protocol): - Multirange: PostgreSQL 14+ - JSONB subscript: PostgreSQL 14+ - Numeric Infinity: PostgreSQL 14+ + - pg_lsn addition: PostgreSQL 14+ """ def supports_multirange_type(self) -> bool: @@ -95,6 +97,14 @@ def supports_xid8_type(self) -> bool: """ ... + def supports_pg_lsn_addition(self) -> bool: + """Whether a pg_lsn value can be added to a numeric byte count. + + Native feature, PostgreSQL 14+. + Enables ``pg_lsn + numeric`` arithmetic. + """ + ... + def format_create_range_type(self, expr) -> Tuple[str, tuple]: """Format CREATE TYPE AS RANGE statement from expression object. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py index f790a2a6..f38c200a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py @@ -33,13 +33,8 @@ def _require_multirange(backend): - version = backend.get_server_version() - if version < (14, 0, 0): - pytest.skip( - "multirange requires PostgreSQL 14+, server is {}".format( - ".".join(str(part) for part in version) - ) - ) + if not backend.dialect.supports_multirange(): + pytest.skip("multirange requires PostgreSQL 14+ per supports_multirange") def _read_range_columns(backend, table, row_id, columns): diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py index 610588ed..9f85f270 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py @@ -159,8 +159,8 @@ def test_bit_set_bit_executes(self, postgres_backend): def test_bit_count_executes_on_postgres_14_plus(self, postgres_backend): """Test bit_count(bit) function on PostgreSQL 14+.""" - if postgres_backend.get_server_version() < (14, 0, 0): - pytest.skip("bit_count requires PostgreSQL 14+") + if not postgres_backend.dialect.supports_bit_count(): + pytest.skip("bit_count requires PostgreSQL 14+ per supports_bit_count") expr = bit_count(postgres_backend.dialect, _bit(postgres_backend.dialect, "101011")) result = _execute_expression(postgres_backend, expr) @@ -169,12 +169,8 @@ def test_bit_count_executes_on_postgres_14_plus(self, postgres_backend): def test_bit_count_skips_before_postgres_14(self, postgres_backend): """Test bit_count version gate for PostgreSQL versions before 14.""" - version = postgres_backend.get_server_version() - if version >= (14, 0, 0): - assert version >= (14, 0, 0) - return - - pytest.skip("bit_count requires PostgreSQL 14+") + if not postgres_backend.dialect.supports_bit_count(): + pytest.skip("bit_count requires PostgreSQL 14+ per supports_bit_count") class TestAsyncBitStringFunctionsIntegration: @@ -209,8 +205,8 @@ async def test_async_bit_get_bit_executes(self, async_postgres_backend): @pytest.mark.asyncio async def test_async_bit_count_executes_on_postgres_14_plus(self, async_postgres_backend): """Test async bit_count(bit) function on PostgreSQL 14+.""" - if await async_postgres_backend.get_server_version() < (14, 0, 0): - pytest.skip("bit_count requires PostgreSQL 14+") + if not async_postgres_backend.dialect.supports_bit_count(): + pytest.skip("bit_count requires PostgreSQL 14+ per supports_bit_count") expr = bit_count( async_postgres_backend.dialect, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py index eaef5872..ae8b0e28 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py @@ -237,9 +237,11 @@ def _extract_relation_names(result: PostgresExplainResult) -> list[str]: def _assert_range_partition_support(dialect): if not dialect.supports_partitioned_table_creation(): pytest.skip("PostgreSQL scenario does not support declarative partitioning") - version = dialect.get_server_version() - if version and version[0] < 11: - pytest.skip("PostgreSQL 10 does not support primary keys on partitioned tables") + if not dialect.supports_partitioned_table_primary_key(): + pytest.skip( + "PostgreSQL 10 does not support primary keys on partitioned tables " + "(supports_partitioned_table_primary_key)" + ) @pytest.fixture diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py index 59fe7b09..d54e0627 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py @@ -421,8 +421,11 @@ def _create_production_partitioned_table(backend, partitions): dialect = backend.dialect if not dialect.supports_partitioned_table_creation(): pytest.skip("PostgreSQL scenario does not support declarative partitioning") - if backend.get_server_version() < (11, 0, 0): - pytest.skip("production partition primary key scenario requires PostgreSQL 11+") + if not dialect.supports_partitioned_table_primary_key(): + pytest.skip( + "production partition primary key scenario requires PostgreSQL 11+ " + "(supports_partitioned_table_primary_key)" + ) for table_name in PRODUCTION_PARTITION_TABLES: backend.execute(*_drop_table_sql(dialect, table_name)) backend.execute(*_create_production_parent_sql(dialect)) @@ -443,8 +446,11 @@ async def _async_create_production_partitioned_table(backend, partitions): dialect = backend.dialect if not dialect.supports_partitioned_table_creation(): pytest.skip("PostgreSQL scenario does not support declarative partitioning") - if await backend.get_server_version() < (11, 0, 0): - pytest.skip("production partition primary key scenario requires PostgreSQL 11+") + if not dialect.supports_partitioned_table_primary_key(): + pytest.skip( + "production partition primary key scenario requires PostgreSQL 11+ " + "(supports_partitioned_table_primary_key)" + ) for table_name in PRODUCTION_PARTITION_TABLES: await backend.execute(*_drop_table_sql(dialect, table_name)) await backend.execute(*_create_production_parent_sql(dialect)) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py index 7311d209..22021339 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py @@ -20,13 +20,13 @@ def _requires_pg_lsn(backend): - if backend.get_server_version() < (9, 4, 0): - pytest.skip("pg_lsn requires PostgreSQL 9.4+") + if not backend.dialect.supports_data_type_postgres_pg_lsn(): + pytest.skip("pg_lsn requires PostgreSQL 9.4+ per supports_data_type_postgres_pg_lsn") -async def _requires_pg_lsn_async(backend): - if await backend.get_server_version() < (9, 4, 0): - pytest.skip("pg_lsn requires PostgreSQL 9.4+") +def _requires_pg_lsn_async(backend): + if not backend.dialect.supports_data_type_postgres_pg_lsn(): + pytest.skip("pg_lsn requires PostgreSQL 9.4+ per supports_data_type_postgres_pg_lsn") def _lsn_literal(value): @@ -124,8 +124,8 @@ def test_lsn_subtraction_executes(self, postgres_backend): def test_lsn_addition_executes(self, postgres_backend): """Add bytes to a pg_lsn value and verify PostgreSQL returns the new LSN.""" - if postgres_backend.get_server_version() < (14, 0, 0): - pytest.skip("pg_lsn addition requires PostgreSQL 14+") + if not postgres_backend.dialect.supports_pg_lsn_addition(): + pytest.skip("pg_lsn addition requires PostgreSQL 14+ per supports_pg_lsn_addition") result = postgres_backend.fetch_one(""" SELECT ('16/B374D848'::pg_lsn + 1)::text AS lsn_value """) @@ -144,7 +144,7 @@ class TestAsyncLsnIntegration: @pytest_asyncio.fixture async def async_lsn_test_table(self, async_postgres_backend): """Create a table containing a pg_lsn column for async tests.""" - await _requires_pg_lsn_async(async_postgres_backend) + _requires_pg_lsn_async(async_postgres_backend) await async_postgres_backend.execute(f"DROP TABLE IF EXISTS {ASYNC_LSN_TABLE}") await async_postgres_backend.execute(f""" CREATE TABLE {ASYNC_LSN_TABLE} ( @@ -188,7 +188,7 @@ async def test_async_lsn_null_round_trip( @pytest.mark.asyncio async def test_async_lsn_subtraction_executes(self, async_postgres_backend): """Subtract pg_lsn values asynchronously and verify PostgreSQL byte distance.""" - await _requires_pg_lsn_async(async_postgres_backend) + _requires_pg_lsn_async(async_postgres_backend) result = await async_postgres_backend.fetch_one(""" SELECT '16/B374D849'::pg_lsn - '16/B374D848'::pg_lsn AS distance """) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py index 553888f9..a1526e87 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py @@ -132,8 +132,8 @@ def test_insert_and_select_macaddr_value(self, postgres_backend, network_test_ta def test_insert_and_select_macaddr8_value(self, postgres_backend, network_test_table): """Insert a MACADDR8 value and verify PostgreSQL returns canonical text.""" - if postgres_backend.get_server_version() < (10, 0, 0): - pytest.skip("macaddr8 requires PostgreSQL 10+") + if not postgres_backend.dialect.supports_data_type_postgres_macaddr8(): + pytest.skip("macaddr8 requires PostgreSQL 10+ per supports_data_type_postgres_macaddr8") literal = _macaddr8_literal(PostgresMacaddr8("08:00:2b:01:02:03:04:05")) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py index b392a9ba..9c9ca09c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py @@ -345,14 +345,13 @@ def test_multirange_version_check(self, postgres_backend): """Test multirange version detection via protocol.""" dialect = postgres_backend.dialect - # Check version-based support - version = postgres_backend.get_server_version() - if version >= (14, 0, 0): - assert dialect.supports_multirange() is True - assert dialect.supports_multirange_constructor() is True - else: - assert dialect.supports_multirange() is False - assert dialect.supports_multirange_constructor() is False + # Multirange is one capability: the types, their constructor and the aggregate + # all arrived together in PostgreSQL 14, so every probe the dialect + # exposes for the concept has to give one answer. + supports = dialect.supports_multirange() + assert dialect.supports_multirange_constructor() is supports + assert dialect.supports_multirange_agg() is supports + assert dialect.supports_data_type_postgres_int4multirange() is supports def test_range_types_available(self, postgres_backend): """Test that numeric range types are available.""" From 7a96346a50f5194eef80840c66cbdf584ab192ec Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 18:42:14 +0800 Subject: [PATCH 07/81] ci(postgres): pin the 3.8/3.9 matrix entries to ubuntu-22.04 ubuntu-latest moved to 24.04, where actions/setup-python can no longer find Python 3.8/3.9, so those jobs failed at the setup step before any test ran. The core repository already solves this by pinning the old interpreter rows to ubuntu-22.04 while the rest ride ubuntu-latest; this applies the same pattern here. --- .github/workflows/test.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4f1f5dab..6942dd79 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -330,21 +330,21 @@ jobs: test: name: Python ${{ matrix.python-version }} / postgres ${{ matrix.postgres-version }} - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: include: - - { python-version: '3.8', postgres-version: '9' } - - { python-version: '3.8', postgres-version: '10' } - - { python-version: '3.9', postgres-version: '11' } - - { python-version: '3.10', postgres-version: '12' } - - { python-version: '3.11', postgres-version: '13' } - - { python-version: '3.12', postgres-version: '14' } - - { python-version: '3.13', postgres-version: '15' } - - { python-version: '3.13', postgres-version: '16' } - - { python-version: '3.14', postgres-version: '17' } - - { python-version: '3.14', postgres-version: '18' } + - { python-version: '3.8', postgres-version: '9', os: ubuntu-22.04 } + - { python-version: '3.8', postgres-version: '10', os: ubuntu-22.04 } + - { python-version: '3.9', postgres-version: '11', os: ubuntu-22.04 } + - { python-version: '3.10', postgres-version: '12', os: ubuntu-latest } + - { python-version: '3.11', postgres-version: '13', os: ubuntu-latest } + - { python-version: '3.12', postgres-version: '14', os: ubuntu-latest } + - { python-version: '3.13', postgres-version: '15', os: ubuntu-latest } + - { python-version: '3.13', postgres-version: '16', os: ubuntu-latest } + - { python-version: '3.14', postgres-version: '17', os: ubuntu-latest } + - { python-version: '3.14', postgres-version: '18', os: ubuntu-latest } services: postgres: From 2897e00476612559ed7201a1e05e5f7acc7372f4 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 20:09:53 +0800 Subject: [PATCH 08/81] fix(postgres): register jsonpath in the native table switches native_json_xml carries a jsonpath column, which PostgreSQL 12 introduced. The directory already asks the dialect for its type switches, but this table was missing from the list, so PG 10 and PG 11 failed while creating the table (jsonpath does not exist) instead of skipping the family. The probe (supports_data_type_postgres_jsonpath) already existed and answers >= 12; only the conftest entry was missing. --- .../feature/backend/adapters/native/conftest.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index f5691a4d..6495cd9e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -59,6 +59,7 @@ def _require_extension(backend, name): ("native_ranges", "supports_multirange_type", "multirange"), ("native_multiranges", "supports_multirange_type", "multirange"), ("native_wrapped_scalars", "supports_xid8_type", "xid8"), + ("native_json_xml", "supports_data_type_postgres_jsonpath", "jsonpath"), ) From f63741f02cc0bc88027355ca923a25b992149c60 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 21:48:46 +0800 Subject: [PATCH 09/81] feat(postgres): an auto-increment column is a SERIAL type, on every version A declaration says "the database assigns this integer". PostgreSQL's spelling of that is SERIAL -- a pseudo-type whose backing sequence supplies the value -- and it predates the SQL-standard identity clause. Its observable behaviour on INSERT is the one the request asks about, so it is the single spelling used from 9 through 19, which also removes the version boundary that used to make PostgreSQL 9 refuse the request. What changed: * `is_auto_increment=True` on a PRIMARY KEY compiles to SMALLSERIAL / SERIAL / BIGSERIAL by the column's width, instead of a GENERATED ... AS IDENTITY clause; the constraint contributes no clause of its own any more; * a width SERIAL does not have is refused by name rather than approximated (an auto-increment text column has no PostgreSQL spelling); * `supports_database_assigned_integer_column()` answers True while `supports_auto_increment_column()` stays False, which is the point of the two probes: the capability exists, the MySQL token does not; * the SERIAL type probe now documents the three differences from AUTO_INCREMENT, including the one that is not operationally equivalent (an explicit larger key raises the MySQL counter to max + 1 and leaves a sequence untouched). Explicit `IdentityClause` remains available to a caller that asks for the SQL-standard form. Verified: 11 DDL tests (including all three widths, a refused text column cycle and the explicit SERIAL path) and 18 sequence/identity execution tests pass; an unbound ColumnDefinition renders SERIAL under an adapted PostgreSQL 9 dialect. --- .../impl/postgres/mixins/auto_increment.py | 24 +++++- .../backend/impl/postgres/mixins/ddl_table.py | 75 +++++++++++++----- .../mixins/types/data_type_formatting.py | 22 ++++++ .../construct/ddl/test_auto_increment_ddl.py | 79 +++++++++++++------ 4 files changed, 153 insertions(+), 47 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py index ff55830c..9877fc1c 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py @@ -21,8 +21,26 @@ def supports_auto_increment_column(self) -> bool: Always ``False``: ``AUTO_INCREMENT`` is MySQL / MariaDB syntax and is absent from the PostgreSQL grammar. The server-generated-value - mechanisms PostgreSQL does have are the SQL-standard identity clause - (:class:`~...mixins.identity_column.PostgresIdentityColumnMixin`) and - the ``SERIAL`` type family. + mechanisms PostgreSQL does have are the ``SERIAL`` type family + (:meth:`supports_database_assigned_integer_column` answers yes through + it) and the SQL-standard identity clause + (:class:`~...mixins.identity_column.PostgresIdentityColumnMixin`). """ return False + + def supports_database_assigned_integer_column(self) -> bool: + """Whether an integer column's value comes from the database. + + ``True``: SERIAL is a pseudo-type that carries the value, and its + observable behaviour is the one a declaration asks about -- omit the + value on INSERT and the database supplies it, and the row can return + it. The spelling is not ``AUTO_INCREMENT`` (that probe stays ``False``), + which is why the capability and the mechanism are separate questions. + + Not guaranteed: the MySQL counter behaviour. Inserting an explicit + value larger than the sequence's current one raises MySQL's counter to + ``max + 1``; a SERIAL column leaves its sequence untouched, so a later + generated value may collide. Any test mixing explicit keys with + generated ones must be scoped to the mechanism that behaves that way. + """ + return True diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py index c44ff5b9..26f967f7 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py @@ -1,14 +1,54 @@ # src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py import re -from typing import Any, List, Tuple +from typing import Any, Dict, List, Tuple from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.expression.statements.ddl_table import ColumnPrimaryKeyConstraint, IdentityClause +from rhosocial.activerecord.backend.expression.statements.ddl_table import ColumnPrimaryKeyConstraint +from rhosocial.activerecord.backend.expression.types import ( + BigIntType, + IntegerType, + SmallIntType, +) + +#: An auto-increment column is a SERIAL pseudo-type, not a clause. +#: +#: PostgreSQL spells "the database assigns this integer" as a *type* whose +#: backing sequence does the work. SERIAL has existed far longer than the +#: SQL-standard identity clause, and its observable behaviour -- an omitted +#: value is supplied and returned -- is what the declaration asks for, so it +#: is the one spelling this dialect uses. The mapping covers exactly the three +#: integer widths SERIAL has; anything else is refused rather than approximated. +SERIAL_TYPES: Dict[type, str] = { + SmallIntType: "SMALLSERIAL", + IntegerType: "SERIAL", + BigIntType: "BIGSERIAL", +} class PostgresTableMixin: """PostgreSQL table extended features implementation.""" + def _serial_type_sql(self, data_type: Any) -> str: + """The SERIAL pseudo-type for an auto-increment integer column. + + Refuses a column outside the three widths SERIAL has rather than + approximating one: an auto-increment text column has no PostgreSQL + spelling, and silently choosing a type would decide for the caller. + """ + for core_type, spelling in SERIAL_TYPES.items(): + if isinstance(data_type, core_type): + return spelling + from rhosocial.activerecord.backend.dialect.exceptions import ( + UnsupportedFeatureError, + ) + + raise UnsupportedFeatureError( + self.name, + "AUTO_INCREMENT column", + "SERIAL covers smallint, integer and bigint; " + f"{type(data_type).__name__} is none of them", + ) + def supports_if_not_exists_table(self) -> bool: """CREATE TABLE IF NOT EXISTS is supported since PostgreSQL 9.5+.""" return self.version_at_least((9, 5, 0)) @@ -203,7 +243,15 @@ def format_column_definition(self, col_def) -> Tuple[str, tuple]: ) all_params: List[Any] = [] - type_sql, _ = col_def.data_type.to_sql() + is_serial = any( + isinstance(constraint.branch, ColumnPrimaryKeyConstraint) + and constraint.branch.is_auto_increment + for constraint in col_def.constraints + ) + if is_serial: + type_sql = self._serial_type_sql(col_def.data_type) + else: + type_sql, _ = col_def.data_type.to_sql() if not re.fullmatch(r"[A-Za-z0-9_\s(),\[\]]+", type_sql): raise ValueError( f"Invalid data type '{type_sql}': " @@ -215,27 +263,14 @@ def format_column_definition(self, col_def) -> Tuple[str, tuple]: attr_sql, attr_params = self.format_column_attributes(col_def) col_sql += attr_sql all_params.extend(attr_params) - auto_identity_added = False for constraint in col_def.constraints: + # The auto-increment request was answered by the type above; it + # contributes no clause of its own. if ( - not auto_identity_added - and isinstance(constraint.branch, ColumnPrimaryKeyConstraint) + isinstance(constraint.branch, ColumnPrimaryKeyConstraint) and constraint.branch.is_auto_increment ): - # An auto-increment constraint on PostgreSQL is the standard - # identity clause in its default generation mode. Routing it - # through the gated formatter keeps the version boundary in - # one place: PostgreSQL 9 refuses here instead of rendering - # a GENERATED clause its server rejects, and no silent - # fallback to SERIAL is attempted. The flag lives on the - # PRIMARY KEY branch since the two-level split, so it is read - # there rather than probed off the clause. - identity_sql, identity_params = self.format_identity_clause( - IdentityClause(self, "BY DEFAULT") - ) - col_sql += identity_sql - all_params.extend(identity_params) - auto_identity_added = True + continue suffix, params = self.format_column_constraint(constraint) col_sql += suffix all_params.extend(params) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py index 19277e03..88cc20da 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py @@ -679,6 +679,28 @@ def supports_data_type_postgres_smallserial(self) -> bool: return True def supports_data_type_postgres_serial(self) -> bool: + """Whether ``SERIAL`` exists, which is every PostgreSQL version. + + SERIAL is the PostgreSQL spelling of "the database assigns this + integer", and it is a *pseudo-type*, not a column attribute: writing + ``id SERIAL`` creates an integer column with a default drawn from a + sequence the engine creates and owns. ``AUTO_INCREMENT`` is the MySQL + spelling of the same observable behaviour and differs in three ways: + + * it is a column attribute, so the type stays ``INT`` and the marker + rides beside it; ``SERIAL`` replaces the type; + * it is a per-table counter, while ``SERIAL`` is backed by a sequence + object (visible in the catalogue, droppable, shareable); + * inserting an explicit value larger than the current one raises the + MySQL counter to ``max + 1``, while a ``SERIAL`` column leaves its + sequence untouched -- the one place where the two are not + operationally equivalent. + + PostgreSQL also accepts the SQL-standard identity clause from 10 on + (``supports_identity_column``), which is a third spelling of the same + capability; ``supports_database_assigned_integer_column`` is the + capability-level answer. + """ return True def supports_data_type_postgres_bigserial(self) -> bool: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py index f0d9ded5..2ba22424 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py @@ -3,17 +3,18 @@ boolean defaults, and timestamps. Covers bugs found in rbac cross-backend testing: -- is_auto_increment=True on PRIMARY_KEY must produce GENERATED BY DEFAULT - AS IDENTITY (was missing — caused INSERT id=NULL NOT NULL violation). +- is_auto_increment=True on PRIMARY_KEY must produce a SERIAL type (was + missing — caused INSERT id=NULL NOT NULL violation). - format_create_table_statement must return a string for all types. - BooleanType with DEFAULT True must be accepted. - TimestampType must map to TIMESTAMP. -The auto-increment constraint compiles to the SQL-standard identity clause, so -it is version-gated: PostgreSQL 9 must refuse it rather than render a -``GENERATED`` clause its server rejects, and the refusal must name the feature -instead of falling back to ``SERIAL`` (the SERIAL type family stays available -for users who ask for it explicitly). +An auto-increment constraint compiles to the ``SERIAL`` pseudo-type on every +version: SERIAL predates the identity clause, its observable behaviour is the +one the constraint asks for, and one spelling keeps 9 through 19 identical. +The SQL-standard identity clause remains available to a caller that asks for +it explicitly (``IdentityClause``); it is simply not what an auto-increment +request means. """ import pytest @@ -70,8 +71,8 @@ class TestAutoIncrementDDL: def test_auto_increment_in_ddl(self, dialect): sql, _ = _build_table(dialect).to_sql() - assert "GENERATED BY DEFAULT AS IDENTITY" in sql.upper(), \ - f"auto-increment missing: {sql}" + assert "SERIAL" in sql.upper(), f"auto-increment missing: {sql}" + assert "GENERATED" not in sql.upper(), f"unexpected identity clause: {sql}" def test_all_standard_types_compile(self, dialect): sql, params = _build_table(dialect).to_sql() @@ -103,28 +104,58 @@ def test_timestamp_type(self, dialect): assert "TIMESTAMP" in sql.upper() -class TestAutoIncrementVersionGate: - """The constraint compiles to an identity clause, so it carries the gate.""" +class TestAutoIncrementIsSerial: + """An auto-increment request is a SERIAL type, on every version.""" @pytest.mark.parametrize( - "version", [(10, 0, 0), (14, 0, 0), (18, 0, 0)], ids=lambda v: str(v) + "version", [(9, 6, 0), (10, 0, 0), (14, 0, 0), (18, 0, 0)], ids=lambda v: str(v) ) - def test_identity_clause_rendered_from_pg10(self, version): + def test_serial_on_every_version(self, version): sql, _ = _build_table(PostgresDialect(version=version)).to_sql() - assert "GENERATED BY DEFAULT AS IDENTITY" in sql.upper() + assert "SERIAL" in sql.upper() + assert "GENERATED" not in sql.upper() + + def test_integer_widths_map_to_their_serial(self): + dialect = PostgresDialect(version=(16, 0, 0)) + from rhosocial.activerecord.backend.expression.types import ( + BigIntType, + SmallIntType, + ) - def test_refused_on_pg9(self): - """PostgreSQL 9 has no identity columns: refuse, do not fall back.""" - with pytest.raises(UnsupportedFeatureError, match="IDENTITY column"): - _build_table(PostgresDialect(version=(9, 6, 0))).to_sql() + for core_type, expected in ( + (SmallIntType, "SMALLSERIAL"), + (BigIntType, "BIGSERIAL"), + ): + expr = CreateTableStatement( + dialect=dialect, + table=Table(dialect, "serial_tbl"), + columns=[ + ColumnDefinition( + dialect, "id", core_type(dialect=dialect), constraints=_pk(dialect) + ) + ], + ) + sql, _ = expr.to_sql() + assert expected in sql.upper(), sql + + def test_non_integer_auto_increment_is_refused(self): + """SERIAL has three widths; anything else is refused, not approximated.""" + dialect = PostgresDialect(version=(16, 0, 0)) + expr = CreateTableStatement( + dialect=dialect, + table=Table(dialect, "bad_tbl"), + columns=[ + ColumnDefinition( + dialect, "id", TextType(dialect=dialect), constraints=_pk(dialect) + ) + ], + ) + with pytest.raises(UnsupportedFeatureError, match="AUTO_INCREMENT column"): + expr.to_sql() - def test_refusal_is_not_a_serial_rewrite(self): - """The refused request must not be silently rewritten to a SERIAL type.""" + def test_serial_type_still_spellable_explicitly(self): + """A caller that asks for SERIAL by type keeps that path.""" dialect = PostgresDialect(version=(9, 6, 0)) - with pytest.raises(UnsupportedFeatureError): - _build_table(dialect).to_sql() - # A user who wants SERIAL asks for the type explicitly, and that path - # is version-independent. from rhosocial.activerecord.backend.impl.postgres.expression.types import ( PostgresSerialType, ) From 332253e8694a25a268f35e10da1bf5804b68b1b8 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 22:21:05 +0800 Subject: [PATCH 10/81] fix(postgres): put the capability probe on the dialect and register it The capability probe was declared in `PostgresAutoIncrementMixin`, whose protocol (`PostgresAutoIncrementSupport`) restates it method for method, so the reverse-coverage test rightly flagged a method the protocol does not declare. Probe-only capabilities follow the `TransactionalDDLSupport` pattern instead: the protocol declares it and the dialect answers it. The method therefore moves to `PostgresDialect`, next to the other probe-only answers, and the generic `DatabaseAssignedColumnSupport` joins the protocol list the conformance test classifies. Verified: 575 tests across the dialect conformance and auto-increment DDL files pass. --- .../backend/impl/postgres/dialect.py | 17 +++++++++++++ .../impl/postgres/mixins/auto_increment.py | 25 +++---------------- .../dialect/test_protocol_conformance.py | 1 + 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py index 16d5597c..8c674bea 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py @@ -867,6 +867,23 @@ def supports_transactional_ddl(self) -> bool: """PostgreSQL DDL participates in transactions.""" return True + def supports_database_assigned_integer_column(self) -> bool: + """Whether an integer column's value comes from the database. + + ``True``: SERIAL is a pseudo-type whose backing sequence supplies the + value, and its observable behaviour is the one a declaration asks + about -- omit the value on INSERT, the database supplies it, and the + row can return it. The spelling is not ``AUTO_INCREMENT`` + (``supports_auto_increment_column`` stays ``False``), which is why the + capability and the mechanism are separate questions. + + Not guaranteed: the MySQL counter behaviour. Inserting an explicit + value larger than the sequence's current one raises MySQL's counter to + ``max + 1``; a SERIAL column leaves its sequence untouched, so a later + generated value may collide. + """ + return True + def supports_table_function(self) -> bool: """PostgreSQL reads a set-returning function as a row source. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py index 9877fc1c..3f8d06d0 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py @@ -21,26 +21,9 @@ def supports_auto_increment_column(self) -> bool: Always ``False``: ``AUTO_INCREMENT`` is MySQL / MariaDB syntax and is absent from the PostgreSQL grammar. The server-generated-value - mechanisms PostgreSQL does have are the ``SERIAL`` type family - (:meth:`supports_database_assigned_integer_column` answers yes through - it) and the SQL-standard identity clause - (:class:`~...mixins.identity_column.PostgresIdentityColumnMixin`). + mechanism PostgreSQL does have is the ``SERIAL`` type family; the + capability-level answer lives on the dialect + (``PostgresDialect.supports_database_assigned_integer_column``), which + is what a declaration asks for. """ return False - - def supports_database_assigned_integer_column(self) -> bool: - """Whether an integer column's value comes from the database. - - ``True``: SERIAL is a pseudo-type that carries the value, and its - observable behaviour is the one a declaration asks about -- omit the - value on INSERT and the database supplies it, and the row can return - it. The spelling is not ``AUTO_INCREMENT`` (that probe stays ``False``), - which is why the capability and the mechanism are separate questions. - - Not guaranteed: the MySQL counter behaviour. Inserting an explicit - value larger than the sequence's current one raises MySQL's counter to - ``max + 1``; a SERIAL column leaves its sequence untouched, so a later - generated value may collide. Any test mixing explicit keys with - generated ones must be scoped to the mechanism that behaves that way. - """ - return True diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py index d1820a3e..4974452f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py @@ -159,6 +159,7 @@ def get_postgres_protocols(): dialect_protocols.GraphTableSupport, dialect_protocols.ILIKESupport, dialect_protocols.AutoIncrementColumnSupport, + dialect_protocols.DatabaseAssignedColumnSupport, dialect_protocols.IdentityColumnSupport, dialect_protocols.GeneratedColumnSupport, # The column-type table: `PostgresColumnTypeMixin` answers From cacda5a985e36445c55115dabb26ce3b22635ac8 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 22:34:26 +0800 Subject: [PATCH 11/81] ci: give each interpreter the runner that carries it One runner for every row was wrong in both directions: ubuntu-latest no longer carries Python 3.8/3.9, and the newest interpreters belong on the newest image, not on the same one as the middle band. The matrix now states the mapping per row, and runs-on reads it: * 3.8 / 3.9 -> ubuntu-22.04 (the only image that still has them) * 3.10 - 3.13 -> ubuntu-24.04 * 3.14 / 3.15, free-threaded included -> ubuntu-26.04 --- .github/workflows/test.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6942dd79..d274916a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -221,7 +221,7 @@ jobs: test-python-315: name: Python ${{ matrix.python-version }}${{ matrix.freethreaded && 't' || '' }} / postgres ${{ matrix.postgres-version }} - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} permissions: contents: read strategy: @@ -236,7 +236,7 @@ jobs: # psycopg does not support free-threaded builds -- tracked as # psycopg/psycopg#1095 -- so the GIL leg is the only one this backend # has, on 3.15 as on every other interpreter. - - { python-version: '3.15', postgres-version: '18', freethreaded: false } + - { python-version: '3.15', postgres-version: '18', freethreaded: false, os: ubuntu-26.04 } services: postgres: @@ -338,13 +338,13 @@ jobs: - { python-version: '3.8', postgres-version: '9', os: ubuntu-22.04 } - { python-version: '3.8', postgres-version: '10', os: ubuntu-22.04 } - { python-version: '3.9', postgres-version: '11', os: ubuntu-22.04 } - - { python-version: '3.10', postgres-version: '12', os: ubuntu-latest } - - { python-version: '3.11', postgres-version: '13', os: ubuntu-latest } - - { python-version: '3.12', postgres-version: '14', os: ubuntu-latest } - - { python-version: '3.13', postgres-version: '15', os: ubuntu-latest } - - { python-version: '3.13', postgres-version: '16', os: ubuntu-latest } - - { python-version: '3.14', postgres-version: '17', os: ubuntu-latest } - - { python-version: '3.14', postgres-version: '18', os: ubuntu-latest } + - { python-version: '3.10', postgres-version: '12', os: ubuntu-24.04 } + - { python-version: '3.11', postgres-version: '13', os: ubuntu-24.04 } + - { python-version: '3.12', postgres-version: '14', os: ubuntu-24.04 } + - { python-version: '3.13', postgres-version: '15', os: ubuntu-24.04 } + - { python-version: '3.13', postgres-version: '16', os: ubuntu-24.04 } + - { python-version: '3.14', postgres-version: '17', os: ubuntu-26.04 } + - { python-version: '3.14', postgres-version: '18', os: ubuntu-26.04 } services: postgres: From 241b1975d1c74a78a6e775c546ba6f1721996e53 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sun, 15 Nov 2026 23:45:46 +0800 Subject: [PATCH 12/81] test(postgres): an auto-increment column is accepted on every version The test branched on `supports_identity_column()` and expected `NOT_RENDERED` below PostgreSQL 10. That was true while the flag routed through the identity clause; it now renders a SERIAL type, which exists on every version, so the server accepts the declaration regardless of the identity probe. Verified against PostgreSQL 18 locally; the PostgreSQL 9 row is what this changes, and its job is the one that failed. --- .../sequence_identity/test_identity_execution.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py index 87a3523b..83dc6590 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py @@ -234,17 +234,17 @@ def test_no_cycle_is_executable(self, postgres_backend): assert outcome is ExecutionOutcome.NOT_RENDERED def test_auto_increment_constraint_matches_the_declaration(self, postgres_backend): - """The legacy is_auto_increment flag routes through the identity gate.""" + """The auto-increment flag renders a SERIAL type, accepted on every version.""" dialect = postgres_backend.dialect outcome = _confirm( postgres_backend, _auto_increment_table(dialect, "test_identity_exec_legacy"), "test_identity_exec_legacy", ) - if dialect.supports_identity_column(): - assert outcome is ExecutionOutcome.ACCEPTED - else: - assert outcome is ExecutionOutcome.NOT_RENDERED + # Unlike an identity clause, SERIAL predates the standard and exists on + # every version, so the server accepts the declaration whether or not it + # has ``supports_identity_column``. + assert outcome is ExecutionOutcome.ACCEPTED class TestSerialTypeExecution: From b90368d0155458c41f75b883ed1eba1fba663874 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Mon, 16 Nov 2026 00:08:57 +0800 Subject: [PATCH 13/81] fix(postgres): register macaddr8 in the native table switches `native_network` carries a `macaddr8` column, which PostgreSQL 10 introduced. The directory already asks the dialect for its type switches, but this table was missing from the list, so PostgreSQL 9 failed while creating the table (`type "macaddr8" does not exist`) instead of skipping the family. The probe (`supports_data_type_postgres_macaddr8`) already answered >= 10; only the conftest entry was missing, the same way `jsonpath` was. Verified locally: the native network file, 6 passed on PostgreSQL 18. --- .../feature/backend/adapters/native/conftest.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index 6495cd9e..1e9b95cf 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -60,6 +60,7 @@ def _require_extension(backend, name): ("native_multiranges", "supports_multirange_type", "multirange"), ("native_wrapped_scalars", "supports_xid8_type", "xid8"), ("native_json_xml", "supports_data_type_postgres_jsonpath", "jsonpath"), + ("native_network", "supports_data_type_postgres_macaddr8", "macaddr8"), ) From ddfe985031c3e664d09020efeb737459c8c1f276 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Mon, 16 Nov 2026 05:37:25 +0800 Subject: [PATCH 14/81] test(postgres): move the composite-PK bridge to basic/crud_composite_pk The shared suite keeps the composite-key contract in its own directory now; the bridge follows the module. No test content changes. --- .../feature/basic/crud/test_composite_pk_crud.py | 5 ----- .../feature/basic/crud/test_composite_pk_crud_async.py | 5 ----- .../feature/basic/crud_composite_pk/conftest.py | 3 +++ .../basic/crud_composite_pk/test_composite_pk_crud.py | 3 +++ .../basic/crud_composite_pk/test_composite_pk_crud_async.py | 3 +++ 5 files changed, 9 insertions(+), 10 deletions(-) delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py deleted file mode 100644 index c47fec31..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py -""" -Bridge file for composite PK CRUD tests from the testsuite. -""" -from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py deleted file mode 100644 index 50aa8f50..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py -"""Bridge file for async feature.basic.crud.test_composite_pk_crud_async tests.""" -from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py new file mode 100644 index 00000000..8aa92784 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py +"""Use the shared ``basic/crud_composite_pk`` test set.""" +from rhosocial.activerecord.testsuite.feature.basic.crud_composite_pk.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py new file mode 100644 index 00000000..a8c1157a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py +"""Bridge file: runs the shared ``basic/crud_composite_pk`` sync tests.""" +from rhosocial.activerecord.testsuite.feature.basic.crud_composite_pk.test_composite_pk_crud import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py new file mode 100644 index 00000000..1632ef70 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py +"""Bridge file: runs the shared ``basic/crud_composite_pk`` async tests.""" +from rhosocial.activerecord.testsuite.feature.basic.crud_composite_pk.test_composite_pk_crud_async import * # noqa: F401,F403 From 9cab974b069e2d8e58be46f7c02ffb7c903fe46e Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Mon, 16 Nov 2026 05:54:59 +0800 Subject: [PATCH 15/81] test(postgres): import the shared fixture vocabulary from its new home ``testsuite.fixture_types`` (and, for this backend, ``database_name``) moved out of the ``testsuite.core`` package; the test helpers import them from their new location. No test behaviour changes. --- .../feature/connection/pool_definitions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py index 9af82d67..4c8a684a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py @@ -36,7 +36,7 @@ from rhosocial.activerecord.backend.impl.postgres.expression.types import ( PostgresSerialType, ) -from rhosocial.activerecord.testsuite.core.fixture_types import supports_drop_if_exists +from rhosocial.activerecord.testsuite.fixture_types import supports_drop_if_exists class Definition: From 758ac732366011e68db289c9dd64926f800720b6 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Mon, 16 Nov 2026 14:38:39 +0800 Subject: [PATCH 16/81] fix(postgres): accept the conversion keyword the core passes on read Core's FieldAdapterMixin now calls adapter.from_database(value, target, original_type=) so an adapter can tell '' from NULL for fields that admit None. The public contract carries **kwargs for exactly this, and the adapters that inherit BaseSQLTypeAdapter already tolerate it; the standalone postgres adapters declared the narrow signature and raised TypeError the first time a model field was read back. Every standalone from_database now takes **kwargs, matching the MySQL adapters. --- .../backend/impl/postgres/adapters/bit_string.py | 2 +- .../backend/impl/postgres/adapters/geometric.py | 4 +++- .../backend/impl/postgres/adapters/json.py | 2 +- .../backend/impl/postgres/adapters/monetary.py | 2 +- .../impl/postgres/adapters/network_address.py | 10 +++++++--- .../impl/postgres/adapters/object_identifier.py | 12 +++++++++--- .../backend/impl/postgres/adapters/pg_lsn.py | 2 +- .../backend/impl/postgres/adapters/pgvector.py | 2 +- .../backend/impl/postgres/adapters/postgis.py | 2 +- .../backend/impl/postgres/adapters/range.py | 4 ++-- .../backend/impl/postgres/adapters/text_search.py | 4 ++-- .../backend/impl/postgres/adapters/uuid.py | 2 +- .../backend/impl/postgres/adapters/xml.py | 2 +- 13 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py index 49a38bc6..00e78331 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py @@ -68,7 +68,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to bit string") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresBitString]: """Convert PostgreSQL bit string to Python object. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py index 8c7f4abf..496ce46b 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py @@ -95,7 +95,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to geometric type") - def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: + def from_database( + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs + ) -> Any: """Convert PostgreSQL geometric value to Python object. Args: diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py index af03c9be..530173d6 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py @@ -175,7 +175,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to jsonpath") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresJsonPath]: """Convert PostgreSQL jsonpath value to Python. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py index 3044b67f..89fe7564 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py @@ -87,7 +87,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to MONEY") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresMoney]: """Convert PostgreSQL MONEY value to Python. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py index ef8db097..1f1e6217 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py @@ -51,7 +51,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, return None return str(value) - def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: + def from_database( + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs + ) -> Any: if value is None: return None try: @@ -123,7 +125,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to MACADDR") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresMacaddr]: """Convert PostgreSQL MACADDR to Python object. @@ -206,7 +208,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to MACADDR8") - def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: + def from_database( + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs + ) -> Any: """Convert PostgreSQL MACADDR8 to Python object. Args: diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py index 37954ac1..4f3159be 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py @@ -133,7 +133,9 @@ def to_database( raise TypeError(f"Cannot convert {type(value).__name__} to OID type") - def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: + def from_database( + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs + ) -> Any: """Convert PostgreSQL OID value to Python object. Args: @@ -229,7 +231,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to transaction ID type") - def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: + def from_database( + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs + ) -> Any: """Convert PostgreSQL transaction ID to Python object. Args: @@ -314,7 +318,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to TID") - def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: + def from_database( + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs + ) -> Any: """Convert PostgreSQL tid to Python object. Args: diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py index a317eb3c..07bf1cde 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py @@ -63,7 +63,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to pg_lsn") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresLsn]: """Convert PostgreSQL pg_lsn to Python object. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py index 2887793a..818e7181 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py @@ -68,7 +68,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, def from_database( self, value: Any, target_type: Type, - options: Optional[Dict[str, Any]] = None + options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresVector]: """Convert PostgreSQL vector to Python object. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py index 59aeed28..5b970c01 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py @@ -62,7 +62,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, def from_database( self, value: Any, target_type: Type, - options: Optional[Dict[str, Any]] = None + options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresGeometry]: """Convert PostgreSQL geometry/geography to Python object. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py index 8a8c583c..c12c905f 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py @@ -83,7 +83,7 @@ def to_database( raise TypeError(f"Cannot convert {type(value).__name__} to range") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresRange]: """Convert PostgreSQL range value to PostgresRange object.""" if value is None: @@ -164,7 +164,7 @@ def to_database( raise TypeError(f"Cannot convert {type(value).__name__} to multirange") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresMultirange]: """Convert from PostgreSQL multirange value.""" if value is None: diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py index 776b2126..2f8c96d7 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py @@ -89,7 +89,7 @@ def to_database( raise TypeError(f"Cannot convert {type(value).__name__} to tsvector") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresTsVector]: """Convert PostgreSQL tsvector value to PostgresTsVector object. @@ -170,7 +170,7 @@ def to_database( raise TypeError(f"Cannot convert {type(value).__name__} to tsquery") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresTsQuery]: """Convert PostgreSQL tsquery value to PostgresTsQuery object. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py index e44ccb9e..2f680619 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py @@ -69,7 +69,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, def from_database( self, value: Any, target_type: Type, - options: Optional[Dict[str, Any]] = None + options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[uuid.UUID]: """Convert PostgreSQL uuid to Python object. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py index 8b05fee6..c6a0906f 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py @@ -83,7 +83,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, raise TypeError(f"Cannot convert {type(value).__name__} to XML") def from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None + self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[PostgresXML]: """Convert PostgreSQL XML value to Python. From 9f117fc0ae7712ae68f6698c83cf564f59fb3054 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 00:53:44 +0800 Subject: [PATCH 17/81] feat(postgres): register the backend's own value-type adapters Six adapters existed but were never registered: XML, jsonpath, bit string, PostGIS, pgvector and hstore. Each keys on its own wrapper type (PostgresXML, PostgresJsonPath, PostgresBitString, PostgresGeometry, PostgresVector, PostgresHstore), so registering them cannot shadow a core Python type -- the note claiming a str->str conflict described an older shape of these adapters and is gone. The hstore adapter also accepts a plain dict; that pair is deliberately not registered, because (dict, str) would take every dict in the backend away from the JSON adapter. Coverage of a backend's own types does not displace the core ones. --- .../backend/impl/postgres/backend/base.py | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py b/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py index 4b579579..4e3707a7 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py @@ -260,13 +260,18 @@ def _register_postgres_adapters(self): - BOTH: Register both adapters, with custom taking precedence - multirange_adapter_mode: Same for Multirange types (PG 14+ only) - Note: The following adapters are NOT registered by default due to str->str - type mapping conflicts with existing string handling: - - PostgresXMLAdapter: XML type - - PostgresBitStringAdapter: bit/varbit types - - PostgresJsonPathAdapter: jsonpath type - - Users should specify these explicitly when working with such columns. + Note: every backend-named value type this package defines has its + adapter registered here. Those adapters key on their own wrapper + types (``PostgresXML``, ``PostgresJsonPath``, ``PostgresBitString``, + ``PostgresGeometry``, ``PostgresVector``, ``PostgresHstore``) rather + than on ``str``, so registering them cannot shadow the core string + handling -- an earlier note here described an older shape of these + adapters and no longer applies. + + ``PostgresHstoreAdapter`` is registered for its own type only. It also + accepts a plain ``dict``, but ``(dict, str)`` in this registry would + take every dict in the backend away from the JSON adapter, and a + backend covers its own types without displacing the core ones. """ from ..adapters import ( PostgresListAdapter, @@ -288,6 +293,13 @@ def _register_postgres_adapters(self): from ..adapters.uuid import PostgresUUIDAdapter from ..adapters.pg_lsn import PostgresLsnAdapter from ..adapters.text_search import PostgresTsVectorAdapter, PostgresTsQueryAdapter + from ..adapters.xml import PostgresXMLAdapter + from ..adapters.json import PostgresJsonPathAdapter + from ..adapters.bit_string import PostgresBitStringAdapter + from ..adapters.hstore import PostgresHstoreAdapter + from ..adapters.postgis import PostgresPostGISAdapter + from ..adapters.pgvector import PostgresVectorAdapter + from ..type_values.hstore import PostgresHstore from ..config import RangeAdapterMode pg_adapters = [ @@ -310,9 +322,13 @@ def _register_postgres_adapters(self): # PostgresJsonPathAdapter it claims no str->str mapping, so it # cannot shadow the default string handling. PostgresUUIDAdapter(), - # PostgresJsonPathAdapter(), # Not registered: str->str conflict - # PostgresXMLAdapter is NOT registered by default - # due to str->str type pair conflict + # The backend's own value types: each keys on its wrapper type, + # so none of them can shadow a core Python type. + PostgresXMLAdapter(), + PostgresJsonPathAdapter(), + PostgresBitStringAdapter(), + PostgresPostGISAdapter(), + PostgresVectorAdapter(), ] for adapter in pg_adapters: @@ -322,6 +338,13 @@ def _register_postgres_adapters(self): adapter, py_type, db_type, allow_override=True ) + # hstore is registered for its own type only: the adapter also accepts + # a plain ``dict`` as a convenience, and that pair would displace the + # JSON adapter for every dict in this backend. + self.adapter_registry.register( + PostgresHstoreAdapter(), PostgresHstore, str, allow_override=True + ) + # Neutral value adapters are keyed by the core neutral Python types # (Geometry, Vector, ...), so they never collide with the backend # wrapper adapters above and are always available to the catalogue. From affec31757797c63347d9a43326a67a9d1bacd02 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 01:10:51 +0800 Subject: [PATCH 18/81] fix(postgres): drop two duplicate adapter classes and read psycopg multiranges PostgresNetworkAddressAdapter existed twice; the live one is in network_address.py (the package exports it), so base.py's copy was unreachable and its batch methods had never run. PostgresJSONBAdapter existed twice as well: base.py's carries the batch overrides and is the one the package exports, while json.py's was a shorter copy that only the tests imported. json.py now re-exports base.py's class, so one implementation answers to the name. PostgresMultirangeAdapter imported Multirange from psycopg.types.range, where psycopg 3.2+ no longer keeps it; the ImportError was swallowed and a native multirange value could never be read. The import now points at psycopg.types.multirange. Tests cover the two batch paths, the psycopg Range/Multirange read paths, the tuple/bounds refusals and the enum option guards. The adapter package's coverage rises from 87% to 91%; base.py 75% -> 100%, range.py 78% -> 98%. --- .../backend/impl/postgres/adapters/base.py | 83 ------------------- .../backend/impl/postgres/adapters/json.py | 76 +---------------- .../backend/impl/postgres/adapters/range.py | 7 +- .../backend/construct/types/test_adapters.py | 83 ++++++++++++++++++- 4 files changed, 90 insertions(+), 159 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py index fde3313e..ff5f60be 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py @@ -206,89 +206,6 @@ def from_database_batch( return result -class PostgresNetworkAddressAdapter(BaseSQLTypeAdapter): - """ - Adapts Python ipaddress objects to PostgreSQL network types. - """ - - def __init__(self): - super().__init__() - try: - import ipaddress - self.register_type(ipaddress.IPv4Address, str) - self.register_type(ipaddress.IPv6Address, str) - self.register_type(ipaddress.IPv4Network, str) - self.register_type(ipaddress.IPv6Network, str) - except ImportError: - pass - - def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: - return str(value) - - def _do_from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: - try: - import ipaddress - return ipaddress.ip_address(value) - except (ImportError, ValueError): - try: - import ipaddress - return ipaddress.ip_network(value) - except (ImportError, ValueError): - return value - - def to_database_batch( - self, values: List[Any], target_type: Type, options: Optional[Dict[str, Any]] = None - ) -> List[Any]: - """Optimized batch network address conversion. - - Converts all values to strings in a single pass. - - Args: - values: List of values to convert - target_type: Target type - options: Optional conversion options - - Returns: - List of string representations - """ - result = [] - for value in values: - if value is None: - result.append(None) - else: - result.append(str(value)) - return result - - def from_database_batch( - self, values: List[Any], target_type: Type, options: Optional[Dict[str, Any]] = None - ) -> List[Any]: - """Optimized batch network address parsing from database. - - Args: - values: List of string values from database - target_type: Target Python type - options: Optional conversion options - - Returns: - List of ipaddress objects or strings - """ - import ipaddress - - result = [] - for value in values: - if value is None: - result.append(None) - else: - try: - result.append(ipaddress.ip_address(value)) - except (ImportError, ValueError): - try: - result.append(ipaddress.ip_network(value)) - except (ImportError, ValueError): - result.append(value) - return result - - class PostgresEnumAdapter(BaseSQLTypeAdapter): """PostgreSQL ENUM type adapter. diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py index 530173d6..ace59714 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py @@ -15,84 +15,12 @@ storage format. jsonb is generally preferred for query purposes. """ -import json from typing import Any, Callable, Dict, List, Optional, Set, Type, Union, get_args, get_origin # noqa: F401 -from psycopg.types.json import Jsonb - -from rhosocial.activerecord.backend.type_adapter import BaseSQLTypeAdapter - from ..type_values.json import PostgresJsonPath - -class PostgresJSONBAdapter(BaseSQLTypeAdapter): - """ - Adapts Python dict to PostgreSQL JSONB and vice-versa. - - Note: psycopg automatically serializes/deserializes JSON, so dict <-> JSON. - When reading from DB, psycopg returns dict. When target type is str, - we need to serialize back to JSON string. - - The optional ``default`` and ``object_hook`` mirror their ``json.dumps`` / - ``json.loads`` namesakes: - - - ``default`` is forwarded to psycopg's dumper through the per-value - ``Jsonb(value, dumps)`` hook, so it is applied when psycopg serialises - the value (psycopg's global ``dumps`` is replaced, not bypassed). - - ``object_hook`` is applied with ``json.loads``. psycopg has already - decoded a JSONB column to ``dict``/``list`` by the time the adapter sees - it, so the already-decoded value is re-encoded and decoded again to run - the hook over every object, exactly as ``json.loads`` would. - """ - - def __init__( - self, - default: Optional[Callable[[Any], Any]] = None, - object_hook: Optional[Callable[[dict], Any]] = None, - ): - super().__init__() - self.default = default - self.object_hook = object_hook - self.register_type(dict, Jsonb) - - def _dumps(self, value: Any) -> str: - """Serialise for psycopg, applying the configured ``default``.""" - return json.dumps(value, default=self.default) - - def _wrap(self, value: Any) -> Jsonb: - """Build the psycopg wrapper, wiring ``default`` into the dumper.""" - if self.default is None: - # Keep psycopg's default dumps function untouched. - return Jsonb(value) - return Jsonb(value, self._dumps) - - def _apply_object_hook(self, value: Any) -> Any: - """Run ``object_hook`` over an already-decoded JSON value.""" - if self.object_hook is None: - return value - return json.loads(json.dumps(value, default=self.default), object_hook=self.object_hook) - - def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any: - return self._wrap(value) - - def _do_from_database( - self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None - ) -> Union[dict, list, str]: - # For string target type, serialize dict/list back to JSON string - # This is needed because psycopg auto-deserializes JSON to dict, - # but model fields may be defined as Optional[str] type - if target_type is str: - if isinstance(value, (dict, list)): - return json.dumps(value, ensure_ascii=False, default=self.default) - return value - # For dict/list target types, return the decoded value (running the - # hook if one was configured against the already-decoded document) - if isinstance(value, dict): - return self._apply_object_hook(value) - if isinstance(value, list): - return self._apply_object_hook(value) - # In case it's a string representation - return json.loads(value, object_hook=self.object_hook) +# One implementation: the class lives in ``base`` beside the list adapter. +from .base import PostgresJSONBAdapter # noqa: F401 (re-exported public name) class PostgresJsonPathAdapter: diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py index c12c905f..c2636c8b 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py @@ -177,7 +177,12 @@ def from_database( return PostgresMultirange.from_postgres_string(value) try: - from psycopg.types.range import Multirange + # psycopg 3.2+ keeps the multirange type beside the range one, in + # ``psycopg.types.multirange``. Importing it from + # ``psycopg.types.range`` silently failed (the ``ImportError`` below + # swallowed it), so a native multirange value never reached this + # branch. + from psycopg.types.multirange import Multirange if isinstance(value, Multirange): ranges = [ diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py index 2c032b4d..dcb18e85 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py @@ -225,4 +225,85 @@ def test_roundtrip(self, vec): v = [1.0, 2.5, 3.0] s = vec.to_database(v, str) assert isinstance(s, str) - assert vec.from_database(s, list) == v \ No newline at end of file + assert vec.from_database(s, list) == v +class TestRangeAdapterRefusals: + """The custom range adapters' refusals, and the psycopg values they read. + + These are the ``PostgresRange`` / ``PostgresMultirange`` wrapper adapters + (the ones a CUSTOM/BOTH range mode registers), not the neutral ones: their + wire form is PostgreSQL's literal, and their read path accepts psycopg's + native objects so a native-mode result can still be consumed. + """ + + def test_a_tuple_with_invalid_bounds_is_refused(self, range_a): + with pytest.raises(ValueError, match="Invalid bounds specification"): + range_a.to_database((1, 2, "(("), str) + + def test_a_tuple_must_carry_two_or_three_elements(self, range_a): + with pytest.raises(ValueError, match="2 or 3 elements"): + range_a.to_database((1,), str) + + def test_a_string_without_brackets_is_refused(self, range_a): + with pytest.raises(ValueError, match="Invalid range string format"): + range_a.to_database("1,2", str) + + def test_a_value_that_is_no_range_is_refused_on_write(self, range_a): + with pytest.raises(TypeError, match="Cannot convert"): + range_a.to_database({"lower": 1}, str) + + def test_a_psycopg_range_is_read(self, range_a): + from psycopg.types.range import Range as PsycopgRange + + converted = range_a.from_database(PsycopgRange(1, 3, "[)"), str) + + assert converted.to_postgres_string() == "[1,3)" + + def test_a_value_that_is_no_range_is_refused_on_read(self, range_a): + with pytest.raises(TypeError, match="Cannot convert"): + range_a.from_database({"lower": 1}, str) + + def test_a_multirange_literal_is_carried_through(self, multi_range): + assert multi_range.to_database("{[(1,3)]}", str) == "{[(1,3)]}" + + def test_a_multirange_refuses_an_unknown_value_on_write(self, multi_range): + with pytest.raises(TypeError, match="Cannot convert"): + multi_range.to_database({"a": 1}, str) + + def test_a_psycopg_multirange_is_read(self, multi_range): + from psycopg.types.multirange import Multirange as PsycopgMultirange + from psycopg.types.range import Range as PsycopgRange + + converted = multi_range.from_database(PsycopgMultirange([PsycopgRange(1, 3, "[)")]), str) + + assert len(converted.ranges) == 1 + assert converted.ranges[0].to_postgres_string() == "[1,3)" + + def test_a_multirange_refuses_a_value_it_cannot_read(self, multi_range): + with pytest.raises(TypeError, match="Cannot convert"): + multi_range.from_database({"a": 1}, str) + + +class TestJSONBBatchPaths: + """The JSONB batch override: a text target re-serialises, everything else + is handed back decoded (with the object hook applied if one is configured).""" + + def test_a_text_target_re_serialises_documents(self, jsonb): + assert jsonb.from_database_batch([{"a": 1}, [1], "raw"], str) == [ + '{"a": 1}', + "[1]", + "raw", + ] + + def test_absent_values_stay_absent_and_documents_decode(self, jsonb): + assert jsonb.from_database_batch([None, {"a": 1}], dict) == [None, {"a": 1}] + + +class TestEnumAdapterOptionGuards: + """``enum_type`` / ``enum_class`` are declarations supplied by the field; + anything that is not the declared shape is ignored rather than trusted.""" + + def test_a_non_postgres_enum_type_does_not_validate(self, enum_a): + assert enum_a.to_database("ACTIVE", str, {"enum_type": object()}) == "ACTIVE" + + def test_a_non_enum_class_does_not_rebuild(self, enum_a): + assert enum_a.from_database("ACTIVE", str, {"enum_class": object}) == "ACTIVE" From 4bb300115f90dc1f143486598e6b803169cc56a8 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 01:12:55 +0800 Subject: [PATCH 19/81] test(postgres): cover the network address adapters' batch and refusal paths Both directions in bulk, the absent values, the MAC bytes input, and the named refusals for an unsupported type. network_address.py rises from 81% to 97%; what is left is the two ImportError branches that no environment reaches. --- .../backend/construct/types/test_adapters.py | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py index dcb18e85..851d7a0d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py @@ -307,3 +307,43 @@ def test_a_non_postgres_enum_type_does_not_validate(self, enum_a): def test_a_non_enum_class_does_not_rebuild(self, enum_a): assert enum_a.from_database("ACTIVE", str, {"enum_class": object}) == "ACTIVE" + +class TestNetworkAddressBatches: + """Both directions in bulk, including the absent values.""" + + def test_batch_write_and_read(self, net_addr): + assert net_addr.to_database_batch(["192.168.1.1", None], str) == ["192.168.1.1", None] + + parsed = net_addr.from_database_batch(["192.168.1.1", None], str) + assert str(parsed[0]) == "192.168.1.1" + assert parsed[1] is None + + def test_scalar_absence(self, net_addr): + assert net_addr.from_database(None, str) is None + + +class TestMacaddrRefusals: + """``MACADDR`` accepts text, bytes and the wrapper; everything else is + named in the refusal.""" + + def test_absence_passes_through(self, mac): + assert mac.to_database(None, str) is None + assert mac.from_database(None, str) is None + + def test_bytes_are_accepted_on_write(self, mac): + assert mac.to_database(b"\x08\x00\x2b\x01\x02\x03", str) == "08:00:2b:01:02:03" + + def test_an_unsupported_write_type_is_named(self, mac): + with pytest.raises(TypeError, match="Cannot convert"): + mac.to_database(42, str) + + def test_an_unsupported_read_type_is_named(self, mac): + with pytest.raises(TypeError, match="Cannot convert"): + mac.from_database(42, str) + + def test_both_batch_directions(self, mac): + text = "08:00:2b:01:02:03" + assert mac.to_database_batch([text, None], str) == [text, None] + + parsed = mac.from_database_batch([text], str) + assert str(parsed[0]) == text From 8cb372b7958b14db93c3c9505320add7de81c678 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 01:21:17 +0800 Subject: [PATCH 20/81] test(postgres): cover the neutral adapters' remaining branches Per family: the pass-through of an already-neutral value, the named refusal of a wrong shape, the option guards (declared bit length, literal spelling, element-type hints), and the range literal parser's own error contract (brackets, quotes, truncated and empty literals, the normalised infinite bound). neutral.py rises from 83% to 95% and the adapter package to 96%. The two branches left -- a dangling escape and an unescaped quote inside a quoted bound -- are unreachable through the literal path, because the splitter rejects both shapes before the unquoting step runs. --- .../backend/adapters/test_neutral_adapters.py | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py index 90ca893c..4f5306f7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py @@ -361,3 +361,175 @@ def test_invalid_input_is_wrapped(self): adapter.from_database("08:00:2b:01:02", MacAddress) with pytest.raises(TypeConversionError): adapter.to_database(MacAddress.parse("08:00:2b:01:02:03"), int) + + +# --------------------------------------------------------------------------- +# Remaining branches: pass-throughs, per-family refusals, option guards, and +# the literal parser's own error contract. +# --------------------------------------------------------------------------- + + +class TestGeometryRemainingBranches: + def test_a_concrete_geometry_is_carried_through(self): + adapter = PostgresNeutralGeometryAdapter() + value = Point(1, 2) + assert adapter.from_database(value, Geometry) is value + + def test_a_non_geometry_value_is_named(self): + adapter = PostgresNeutralGeometryAdapter() + with pytest.raises(TypeConversionError, match="must decode from WKT/EWKT text"): + adapter.from_database(42, Geometry) + + def test_hex_ewkb_output_is_refused_with_the_right_advice(self): + """PostGIS's default output is hex EWKB; the adapter asks for WKT + instead of pretending to decode it.""" + adapter = PostgresNeutralGeometryAdapter() + with pytest.raises(TypeConversionError, match="hex EWKB"): + adapter.from_database("0101000020E6100000", Geometry) + + +class TestVectorRemainingBranches: + def test_a_neutral_vector_is_carried_through(self): + adapter = PostgresNeutralVectorAdapter() + value = Vector((1.0, 2.0)) + assert adapter.from_database(value, Vector) is value + + def test_a_non_vector_value_is_named(self): + adapter = PostgresNeutralVectorAdapter() + with pytest.raises(TypeConversionError, match="pgvector must decode from text"): + adapter.from_database(object(), Vector) + + def test_a_non_finite_component_in_text_is_permitted(self): + adapter = PostgresNeutralVectorAdapter() + parsed = adapter.from_database("[nan,1.0]", Vector) + assert parsed.allow_non_finite is True + + +class TestBitStringRemainingBranches: + def test_a_neutral_bit_string_is_carried_through(self): + adapter = PostgresNeutralBitStringAdapter() + value = BitString.from_bits("101") + assert adapter.from_database(value, BitString) is value + + def test_a_wrapper_without_a_declared_length_keeps_its_own(self): + adapter = PostgresNeutralBitStringAdapter() + bits = adapter.from_database(PostgresBitString("101", length=3), BitString) + assert bits.to_bits() == "101" + + def test_empty_bytes_are_refused(self): + adapter = PostgresNeutralBitStringAdapter() + with pytest.raises(TypeConversionError, match="bytes must not be empty"): + adapter.from_database(b"", BitString) + + def test_an_integer_is_read_as_bits(self): + adapter = PostgresNeutralBitStringAdapter() + assert adapter.from_database(5, BitString).to_bits() == "101" + + def test_a_non_bit_value_is_named(self): + adapter = PostgresNeutralBitStringAdapter() + with pytest.raises(TypeConversionError, match="must decode from text, bytes, int"): + adapter.from_database(1.5, BitString) + + def test_a_declared_length_must_be_a_positive_integer(self): + adapter = PostgresNeutralBitStringAdapter() + with pytest.raises(TypeConversionError, match=r"must be int, got bool"): + adapter.from_database("101", BitString, {"bit_length": True}) + with pytest.raises(TypeConversionError, match="must be at least 1"): + adapter.from_database("101", BitString, {"bit_length": 0}) + + def test_a_literal_spelling_is_read_and_written(self): + adapter = PostgresNeutralBitStringAdapter() + assert adapter.from_database("B'101'", BitString).to_bits() == "101" + assert adapter.to_database(BitString.from_bits("101"), str, {"literal": True}) == "B'101'" + + def test_the_wire_form_is_text_only(self): + adapter = PostgresNeutralBitStringAdapter() + with pytest.raises(TypeConversionError, match="target_type must be str"): + adapter.to_database(BitString.from_bits("101"), bytes) + + +class TestRangeRemainingBranches: + def test_a_neutral_range_is_carried_through(self): + adapter = PostgresNeutralRangeAdapter() + value = Range(1, 2, "[)") + assert adapter.from_database(value, Range) is value + + def test_an_empty_sequence_is_an_empty_multirange(self): + adapter = PostgresNeutralRangeAdapter() + assert adapter.from_database([], Multirange) == Multirange(()) + + def test_a_sequence_of_non_ranges_is_refused(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError, match="must contain range objects"): + adapter.from_database([{"a": 1}], Multirange) + + def test_a_non_range_value_is_named(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError, match="must decode from text, a backend/driver"): + adapter.from_database(42, Range) + + def test_the_wire_form_is_text_only(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError, match="target_type must be str"): + adapter.to_database(Range(1, 2, "[)"), bytes) + + def test_an_element_hint_must_be_text(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError, match="must be str"): + adapter.from_database("[1,2]", Range, {"element_type": 1}) + + def test_an_unknown_element_hint_is_named(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError, match="unsupported range element type hint"): + adapter.from_database("[1,2]", Range, {"element_type": "bogus"}) + + def test_a_malformed_bound_of_each_label_is_named(self): + adapter = PostgresNeutralRangeAdapter() + for label in ("date", "time", "datetime", "int", "decimal", "float"): + with pytest.raises(TypeConversionError, match="invalid .* range bound"): + adapter.from_database('["x","y"]', Range, {"element_type": label}) + + def test_a_non_finite_bound_is_read_as_its_float(self): + adapter = PostgresNeutralRangeAdapter() + parsed = adapter.from_database("[nan,1]", Range) + assert math.isnan(parsed.lower) + + def test_bracket_and_quote_errors_are_named(self): + adapter = PostgresNeutralRangeAdapter() + for text, reason in ( + ("[1)]", "unbalanced closing bracket"), + ("[(1,2]", "unbalanced brackets"), + ('["abc]', "unterminated quoted range bound"), + ): + with pytest.raises(TypeConversionError, match=reason): + adapter.from_database(text, Range) + + def test_an_empty_and_a_truncated_literal_are_named(self): + adapter = PostgresNeutralRangeAdapter() + with pytest.raises(TypeConversionError, match="range literal is empty"): + adapter.from_database("", Range) + with pytest.raises(TypeConversionError, match="range literal is too short"): + adapter.from_database("[", Range) + + def test_an_infinite_bound_is_normalised_to_the_exclusive_bracket(self): + adapter = PostgresNeutralRangeAdapter() + parsed = adapter.from_database("[,]", Range) + assert parsed.lower is None and parsed.upper is None + assert parsed.bounds == "()" + + +class TestMacAddressRemainingBranches: + def test_a_neutral_mac_is_carried_through(self): + adapter = PostgresNeutralMacAddressAdapter() + value = MacAddress.parse("08:00:2b:01:02:03") + assert adapter.from_database(value, MacAddress) is value + + def test_the_backend_wrapper_is_read(self): + adapter = PostgresNeutralMacAddressAdapter() + parsed = adapter.from_database(PostgresMacaddr("08:00:2b:01:02:03"), MacAddress) + assert str(parsed) == "08:00:2b:01:02:03" + + def test_a_non_mac_value_is_named(self): + adapter = PostgresNeutralMacAddressAdapter() + with pytest.raises(TypeConversionError, match="must decode from text, bytes, or a backend MAC"): + adapter.from_database(42, MacAddress) From d9d348930b728f28c81ff06b8662e991c5464a83 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 02:41:42 +0800 Subject: [PATCH 21/81] feat(postgres): answer the data-type suggestions and rename the substitute hook suggested_data_types now carries PostgreSQL's own answer for every framework-modelled Python type: TEXT for text (one unbounded tier), JSONB for a document, native arrays for the sequence entries, TIMESTAMP(3) by default, and the server's GEOMETRY/VARBIT/MACADDR words for three complex families. Vector, Range and Multirange name the text carrier their neutral adapters already write, because a bare annotation does not say the dimension or the element type; the field that wants the native type declares it with UseSqlType. The old substitution table keeps its meaning under the name the replan gives it, substitute_data_types. --- .../backend/impl/postgres/dialect.py | 4 + .../backend/impl/postgres/mixins/__init__.py | 2 + .../impl/postgres/mixins/column_type.py | 54 +++++++-- .../postgres/mixins/data_type_suggestions.py | 114 ++++++++++++++++++ .../mixins/types/data_type_formatting.py | 2 +- .../construct/types/test_type_protocol.py | 22 ++-- 6 files changed, 175 insertions(+), 23 deletions(-) create mode 100644 src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py diff --git a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py index 8c674bea..a3a918c8 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py @@ -171,6 +171,7 @@ PostgresLogicalReplicationMixin, PostgresParallelQueryMixin, PostgresColumnTypeMixin, + PostgresDataTypeSuggestionsMixin, # Per-feature mixins PostgresCTEMixin, PostgresWindowMixin, @@ -523,6 +524,9 @@ class PostgresDialect( PostgresVacuumMixin, PostgresCopyMixin, PostgresQueryOptimizationMixin, + # Suggested data types: the DDL half of the same answer. Ahead of the + # mixin that withholds the table, so this dialect's answers win. + PostgresDataTypeSuggestionsMixin, PostgresDataTypeMixin, PostgresLogicalReplicationMixin, PostgresParallelQueryMixin, diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py index de2fcc3c..d813594a 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py @@ -98,6 +98,7 @@ from .query_optimization import PostgresQueryOptimizationMixin from .data_type import PostgresDataTypeMixin from .column_type import PostgresColumnTypeMixin +from .data_type_suggestions import PostgresDataTypeSuggestionsMixin from .logical_replication import PostgresLogicalReplicationMixin from .parallel_query import PostgresParallelQueryMixin from .property_graph_query import PostgresPropertyGraphQueryMixin @@ -219,6 +220,7 @@ "PostgresQueryOptimizationMixin", "PostgresDataTypeMixin", "PostgresColumnTypeMixin", + "PostgresDataTypeSuggestionsMixin", "PostgresLogicalReplicationMixin", "PostgresParallelQueryMixin", "PostgresPropertyGraphQueryMixin", diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py index 2ec98ffc..88904942 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py @@ -10,10 +10,17 @@ Every answer below is written out rather than inherited from a core-side table, because a backend that owns its answer should be readable without a -second file. The eighteen entries are the protocol's closed list, all of them -answered, and exactly one of them is refused: ``datetime.timedelta``, which +second file. The twenty-four entries are the protocol's closed list, all of +them answered, and seven of them are refused: ``datetime.timedelta``, which this server can spell as ``interval`` but which no core column class can -answer for -- see the entry's own comment. +answer for, and the six complex families -- geometry, vector, bit string, +range, multirange and MAC address -- whose column classes core does not have +yet. The DDL half of the six families *is* answered, in ``data_type_suggestions.py``: +this backend spells ``GEOMETRY`` / ``VARBIT`` / ``MACADDR`` for three of them +and refuses the three whose parameters a bare annotation does not carry. A +refused column class costs operations (``Model.c.`` reports the gap); +a refused storage entry costs the table itself, which is why the two halves +answer separately. **What the answers are measured against.** The live probes in ``.claude/plan/2026-10-08/suggested-mappings.md`` §8 (≈90 server instances @@ -51,6 +58,15 @@ import uuid from typing import Any, Dict, Optional, Type +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, +) + from rhosocial.activerecord.backend.dialect.mixins import ColumnTypeMixin from rhosocial.activerecord.backend.expression.column_types import ( ArrayColumn, @@ -65,7 +81,7 @@ UUIDColumn, ) -#: All eighteen protocol entries, in the protocol's reading order. Commented +#: All twenty-four protocol entries, in the protocol's reading order. Commented #: per group because the reasons are the content: the answer is a claim about #: this server, and a claim without its evidence is decoration. POSTGRES_COLUMN_TYPES: Dict[Any, Optional[Type[ColumnBase]]] = { @@ -159,11 +175,22 @@ # class would put storage into the operation layer, which is the split # this protocol exists to keep. enum.Enum: StringColumn, + # -- Complex families ------------------------------------------------ + # core has no column class for these yet, so they are refused rather than + # answered with a class that does not exist. Their storage is answered in + # ``data_type_suggestions.py``, which is the half this backend does own. When core + # grows the family classes, these six entries are where they go. + Geometry: None, + Vector: None, + BitString: None, + Range: None, + Multirange: None, + MacAddress: None, } class PostgresColumnTypeMixin(ColumnTypeMixin): - """The full common-Python-type → column-class table for PostgreSQL. + """The full framework-modelled-Python-type → column-class table for PostgreSQL. Composed into :class:`~rhosocial.activerecord.backend.impl.postgres.dialect.PostgresDialect` ahead of this backend's own mixins. Nothing else in the list can answer for @@ -178,12 +205,17 @@ class PostgresColumnTypeMixin(ColumnTypeMixin): operations, and it is pinned by the backend's own test file rather than left to drift. - **One entry is refused.** ``datetime.timedelta`` answers ``None`` because - PostgreSQL's native ``interval`` has no core column class -- the gap this - backend used to hide by naming ``NumericColumn`` and accepting that - ``sqrt(interval '1 day')`` would be offered and would fail on the server. - A refusal that reaches the model layer as a resolution error is the honest - version of that gap, and the entry's comment says what closes it. + **Seven entries are refused.** ``datetime.timedelta`` answers ``None`` + because PostgreSQL's native ``interval`` has no core column class -- the + gap this backend used to hide by naming ``NumericColumn`` and accepting + that ``sqrt(interval '1 day')`` would be offered and would fail on the + server. A refusal that reaches the model layer as a resolution error is + the honest version of that gap, and the entry's comment says what closes + it. The other six are the complex families, refused for the mirror-image + reason: the operations would have to be written against a core column + class that does not exist yet. Their storage is answered -- ``GEOMETRY``, + ``VARBIT`` and ``MACADDR`` here -- so a bare model builds the table and + only the field accessor reports the gap. The table has no version branch because nothing in it moves with the version: the one thing that does (``jsonb`` becoming available in 9.4) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py new file mode 100644 index 00000000..4c538cd4 --- /dev/null +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py @@ -0,0 +1,114 @@ +# src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py +"""PostgreSQL's **suggested data types**: what a bare field is declared as here. + +The DDL half of the type answer, separate from :mod:`.column_type` for the +reason that file already states: a column class says what a value can *do*, +this says what a column *is*. + +Three things about this server shape the answers: + +* **text is one tier, and it is unbounded.** PostgreSQL's ``TEXT`` has no size + cap (``TOAST`` moves large values out of the row automatically), so a declared + capacity is satisfied rather than rounded: ``TextType(length=N)``, ``JsonType`` + and ``XmlType`` all spend the same ``TEXT``/``XML`` word here. +* **a JSON document's natural home here is ``JSONB``.** The column table's own + comment explains why the operation surface is one class either way; this is + where the storage choice is made, and it is ``JSONB`` (indexable, and the only + one of the two with an equality operator). +* **arrays are native.** ``dict``'s container siblings get real arrays, and the + element width is the shared default: a Python list is ``TEXT[]`` unless the + field declares otherwise. + +Three families carry a parameter a bare annotation does not say: ``Vector`` +needs a dimension, and ``Range`` / ``Multirange`` need an element type (the +element decides the spelling, ``int4range`` / ``numrange`` / ``daterange``). +A suggestion may not invent either, so it names the **text carrier** their +neutral adapters already write -- pgvector's ``[1,2,3]`` and the range literal +``[1,2)`` -- and a bare field round-trips. The field that wants the server's +native type declares it with ``UseSqlType``; the alternative, answering +``None``, would take the table away from the caller, which is not what a +suggestion is for. + +Each call returns a **fresh dict** whose values are this module's read-only +templates; the derivation binds a dialect on a copy of the single entry it uses. +""" +from __future__ import annotations + +import datetime +import decimal +import enum +import uuid +from typing import Any, Dict, Optional + +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, +) +from rhosocial.activerecord.backend.expression.types import ( + ArrayType, + BlobType, + BooleanType, + DateType, + DecimalType, + DoubleType, + IntegerType, + IntervalType, + JsonBType, + TextType, + TimeType, + TimestampType, + UUIDType, + VarCharType, +) +from rhosocial.activerecord.backend.impl.postgres.expression.types import ( + PostgresGeometryType, + PostgresMacAddrType, + PostgresVarBitType, +) + +#: PostgreSQL's suggested declaration per framework-modelled Python type. +POSTGRES_DATA_TYPE_SUGGESTIONS: Dict[Any, Optional[Any]] = { + bool: BooleanType(), + int: IntegerType(), + float: DoubleType(), + decimal.Decimal: DecimalType(), + str: TextType(), + bytes: BlobType(), + bytearray: BlobType(), + datetime.date: DateType(), + datetime.time: TimeType(), + datetime.datetime: TimestampType(precision=3), + datetime.timedelta: IntervalType(), + uuid.UUID: UUIDType(), + dict: JsonBType(), + list: ArrayType(element_type=VarCharType(length=255)), + tuple: ArrayType(element_type=VarCharType(length=255)), + set: ArrayType(element_type=VarCharType(length=255)), + frozenset: ArrayType(element_type=VarCharType(length=255)), + enum.Enum: VarCharType(length=255), + # -- Complex families ------------------------------------------------ + # GEOMETRY untyped: point/line/polygon are the *shape* a value carries, and + # the column decides the shape and SRID it accepts. + Geometry: PostgresGeometryType(), + # No dimension to declare here; the neutral adapter's text is the carrier. + Vector: TextType(), + BitString: PostgresVarBitType(), + # The element type is the column's decision; the literal text round-trips. + Range: TextType(), + Multirange: TextType(), + MacAddress: PostgresMacAddrType(), +} + + +class PostgresDataTypeSuggestionsMixin: + """PostgreSQL's answer to "what declaration does a bare field get here".""" + + def suggested_data_types(self) -> Dict[Any, Optional[Any]]: + return dict(POSTGRES_DATA_TYPE_SUGGESTIONS) + + +__all__ = ["POSTGRES_DATA_TYPE_SUGGESTIONS", "PostgresDataTypeSuggestionsMixin"] diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py index 88cc20da..ce666d77 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py @@ -996,7 +996,7 @@ def format_data_type_postgres_enum(self, data_type) -> Tuple[str, tuple]: def supports_data_type_postgres_enum(self) -> bool: return True - def suggested_data_types(self) -> dict: + def substitute_data_types(self) -> dict: """Cross-backend type-consistency suggestion map. PostgreSQL renders every core type it supports through its own diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py index 46ef8de4..2a754de1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py @@ -4,7 +4,7 @@ Verifies: - format family == supports family (1:1 correspondence) - supports_data_types() includes postgres_* + core entries -- suggested_data_types(): values are DataType classes; keys disjoint from supported +- substitute_data_types(): values are DataType classes; keys disjoint from supported - dialect_options forwarding and equality """ @@ -201,32 +201,32 @@ def test_supports_data_types_values_are_data_type_classes(dialect): # --------------------------------------------------------------------------- -# W4: suggested_data_types() +# W4: substitute_data_types() # --------------------------------------------------------------------------- -def test_suggested_data_types_returns_dict(dialect): - result = dialect.suggested_data_types() +def test_substitute_data_types_returns_dict(dialect): + result = dialect.substitute_data_types() assert isinstance(result, dict) -def test_suggested_data_types_values_are_classes(dialect): - result = dialect.suggested_data_types() +def test_substitute_data_types_values_are_classes(dialect): + result = dialect.substitute_data_types() for name, cls in result.items(): assert isinstance(cls, type), ( - f"suggested_data_types()[{name!r}] is not a class: {cls!r}" + f"substitute_data_types()[{name!r}] is not a class: {cls!r}" ) assert issubclass(cls, DataType), ( - f"suggested_data_types()[{name!r}] = {cls.__name__} is not a DataType subclass" + f"substitute_data_types()[{name!r}] = {cls.__name__} is not a DataType subclass" ) -def test_suggested_data_types_keys_disjoint_from_supported(dialect): +def test_substitute_data_types_keys_disjoint_from_supported(dialect): supported = set(dialect.supports_data_types().keys()) - suggested = set(dialect.suggested_data_types().keys()) + suggested = set(dialect.substitute_data_types().keys()) overlap = supported & suggested assert not overlap, ( - f"suggested_data_types() keys overlap with supports_data_types(): {overlap}" + f"substitute_data_types() keys overlap with supports_data_types(): {overlap}" ) From fa735f9e1ed1df13b364932a6b2751b821a3f452 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 03:18:39 +0800 Subject: [PATCH 22/81] feat(postgres): declare the backend's own value classes in the extra table Thirty-seven value classes the framework does not model now have a declaration: the server's geometric family, its text-search and jsonpath types, the object identifiers (OID, the reg* aliases, XID/XID8/CID/TID), money, hstore, XML, LSN, the PostGIS and pgvector wrappers, and the MAC variants. Entries whose native spelling needs a parameter the annotation does not carry (a vector's dimension, a range's subtype) name the text their adapters write. A bare field annotated with one of these used to fail as 'declares no SQL type' even though the adapter and the type class both existed; this is the table the derivation falls back to for them. --- .../postgres/mixins/data_type_suggestions.py | 146 +++++++++++++++++- 1 file changed, 145 insertions(+), 1 deletion(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py index 4c538cd4..0028a547 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py @@ -60,14 +60,98 @@ JsonBType, TextType, TimeType, + XmlType, TimestampType, UUIDType, VarCharType, ) from rhosocial.activerecord.backend.impl.postgres.expression.types import ( + PostgresBoxType, + PostgresCIDType, + PostgresCircleType, PostgresGeometryType, + PostgresHstoreType, + PostgresJsonPathType, + PostgresLineSegmentType, + PostgresLineType, + PostgresMacAddr8Type, PostgresMacAddrType, + PostgresMoneyType, + PostgresOIDType, + PostgresPathType, + PostgresPointType, + PostgresPolygonType, + PostgresRegClassType, + PostgresRegTypeType, + PostgresTIDType, + PostgresTSQueryType, + PostgresTSVectorType, PostgresVarBitType, + PostgresXID8Type, + PostgresXIDType, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.bit_string import ( + PostgresBitString, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.geometric import ( + Box, + Circle, + Line, + LineSegment, + Path, + Point, + Polygon, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.hstore import ( + PostgresHstore, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.json import ( + PostgresJsonPath, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.monetary import ( + PostgresMoney, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.network_address import ( + PostgresMacaddr, + PostgresMacaddr8, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.object_identifier import ( + CID, + OID, + TID, + XID, + XID8, + RegClass, + RegCollation, + RegConfig, + RegDictionary, + RegNamespace, + RegOper, + RegOperator, + RegProc, + RegProcedure, + RegRole, + RegType, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.pg_lsn import ( + PostgresLsn, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.pgvector import ( + PostgresVector, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.postgis import ( + PostgresGeometry, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.range import ( + PostgresMultirange, + PostgresRange, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.text_search import ( + PostgresTsQuery, + PostgresTsVector, +) +from rhosocial.activerecord.backend.impl.postgres.type_values.xml import ( + PostgresXML, ) #: PostgreSQL's suggested declaration per framework-modelled Python type. @@ -104,11 +188,71 @@ } +#: Declarations for PostgreSQL's **own** value classes -- the types the +#: framework does not model. A field annotated with one of these is a Python +#: type no portable reader knows, so the backend has to say what it stores. +#: Entries whose native spelling needs a parameter (a vector's dimension, a +#: range's subtype) name the text carrier their adapters write; the rest name +#: the server's own type. +POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS: Dict[Any, Optional[Any]] = { + # Bit string, text search, jsonpath and the PostGIS wrapper. + PostgresBitString: PostgresVarBitType(), + PostgresGeometry: PostgresGeometryType(), + PostgresTsVector: PostgresTSVectorType(), + PostgresTsQuery: PostgresTSQueryType(), + PostgresJsonPath: PostgresJsonPathType(), + # The server's own geometric family. + Point: PostgresPointType(), + Line: PostgresLineType(), + LineSegment: PostgresLineSegmentType(), + Box: PostgresBoxType(), + Path: PostgresPathType(), + Polygon: PostgresPolygonType(), + Circle: PostgresCircleType(), + # Network, money, hstore, xml and LSN. + PostgresMacaddr: PostgresMacAddrType(), + PostgresMacaddr8: PostgresMacAddr8Type(), + PostgresMoney: PostgresMoneyType(), + PostgresHstore: PostgresHstoreType(), + PostgresXML: XmlType(), + PostgresLsn: TextType(), + # Object identifiers: the wrapped ones have their own declaration; the + # registry names are OID aliases and are carried as text. + OID: PostgresOIDType(), + RegClass: PostgresRegClassType(), + RegType: PostgresRegTypeType(), + RegProc: TextType(), + RegProcedure: TextType(), + RegOper: TextType(), + RegOperator: TextType(), + RegConfig: TextType(), + RegDictionary: TextType(), + RegNamespace: TextType(), + RegRole: TextType(), + RegCollation: TextType(), + XID: PostgresXIDType(), + XID8: PostgresXID8Type(), + CID: PostgresCIDType(), + TID: PostgresTIDType(), + # Parameter-carrying wrappers: the text their adapters write. + PostgresVector: TextType(), + PostgresRange: TextType(), + PostgresMultirange: TextType(), +} + + class PostgresDataTypeSuggestionsMixin: """PostgreSQL's answer to "what declaration does a bare field get here".""" def suggested_data_types(self) -> Dict[Any, Optional[Any]]: return dict(POSTGRES_DATA_TYPE_SUGGESTIONS) + def suggested_extra_data_types(self) -> Dict[Any, Optional[Any]]: + return dict(POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS) + -__all__ = ["POSTGRES_DATA_TYPE_SUGGESTIONS", "PostgresDataTypeSuggestionsMixin"] +__all__ = [ + "POSTGRES_DATA_TYPE_SUGGESTIONS", + "POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS", + "PostgresDataTypeSuggestionsMixin", +] From 6d64888f99167eff2d3ea37918edc6e19ae28383 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 03:24:54 +0800 Subject: [PATCH 23/81] test(postgres): run the shared suggested-data-type contract The table behind a bare field's declaration now has a shared contract: every framework-modelled type is answered with a renderable declaration and nothing answers None, the backend's own value classes are disjoint from that list and render too, and each call returns a fresh dict. It runs against this backend's dialect through the usual thin bridge. --- .../feature/basic/ddl/test_data_type_suggestion_contract.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py new file mode 100644 index 00000000..36894b94 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py @@ -0,0 +1,4 @@ +# tests/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py +"""Thin bridge that runs the shared suggested-data-type contract here.""" + +from rhosocial.activerecord.testsuite.feature.basic.ddl.test_data_type_suggestion_contract import * # noqa: F403 From 8b4b7b4c3ffb31ddd8635ee7610b6ef5c832b748 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 03:27:43 +0800 Subject: [PATCH 24/81] fix(postgres): keep the range wrappers out of the extra table The new adapter-existence contract caught two entries that had no adapter on a default backend: PostgresRange and PostgresMultirange are adapted only in the CUSTOM/BOTH range modes, so suggesting a declaration for them built a column nothing could write. The wrappers are dropped from the table and the reason is written down where the entry used to be. The contract itself is added beside the adapter inventory: every extra value class must have an adapter registered, because a suggestion the adapter cannot carry is worse than a refusal. --- .../postgres/mixins/data_type_suggestions.py | 8 +++++--- .../backend/core/test_get_type_adapters.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py index 0028a547..57b3809b 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py @@ -234,10 +234,12 @@ XID8: PostgresXID8Type(), CID: PostgresCIDType(), TID: PostgresTIDType(), - # Parameter-carrying wrappers: the text their adapters write. + # Parameter-carrying wrapper: the text its adapter writes. PostgresVector: TextType(), - PostgresRange: TextType(), - PostgresMultirange: TextType(), + # `PostgresRange` / `PostgresMultirange` are deliberately absent: their + # adapters are registered only in the CUSTOM/BOTH range modes, so a default + # backend has no adapter for those value classes. A suggestion without an + # adapter builds a column nothing can write. } diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py index 192ce075..88c80550 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py @@ -54,3 +54,21 @@ def test_default_adapter_suggestions_are_still_provided(self, backend): suggestions = backend.get_default_adapter_suggestions() assert isinstance(suggestions, dict) assert suggestions + +def test_every_extra_value_class_has_an_adapter(backend): + """An extra suggestion is only usable if the value can also be adapted. + + The suggestion table says what column a bare field is declared as; the + adapter registry says whether that field can be written and read back. An + entry without an adapter would build a column nothing can carry a value + into, which is worse than refusing the type outright. + """ + extras = backend.dialect.suggested_extra_data_types() + registered = {py for (py, _db) in backend.adapter_registry.get_all_adapters()} + + missing = [entry.__name__ for entry in extras if entry not in registered] + assert missing == [], ( + f"{type(backend).__name__} suggests a declaration for {missing} but has no " + f"adapter registered for those value classes" + ) + From ae64fbad698b73f7bdbd5128288d58cc2c3bf483 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:18:48 +0800 Subject: [PATCH 25/81] feat(postgres): answer all twenty-four column entries, with no refusal The six families core now models -- geometry, vector, bit string, range, multirange, MAC address -- get a class in this backend's table instead of a hole. Their classes promise only the column surface (alias, null tests, casting, collation), which every backend can execute on whatever storage it picks, so the answer costs no false promise. A duration now answers IntervalColumn rather than NumericColumn: a span is not a number of its own family, and the class promises no arithmetic. The per-entry answers and their reasons were updated together with the table; the protocol conformance file's "eighteen" wording now says twenty-four. --- .../impl/postgres/mixins/column_type.py | 105 ++++++++++-------- .../dialect/test_protocol_conformance.py | 2 +- .../types/test_column_type_suggestions.py | 95 ++++++++++------ 3 files changed, 117 insertions(+), 85 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py index 88904942..727c6728 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py @@ -11,16 +11,14 @@ Every answer below is written out rather than inherited from a core-side table, because a backend that owns its answer should be readable without a second file. The twenty-four entries are the protocol's closed list, all of -them answered, and seven of them are refused: ``datetime.timedelta``, which -this server can spell as ``interval`` but which no core column class can -answer for, and the six complex families -- geometry, vector, bit string, -range, multirange and MAC address -- whose column classes core does not have -yet. The DDL half of the six families *is* answered, in ``data_type_suggestions.py``: -this backend spells ``GEOMETRY`` / ``VARBIT`` / ``MACADDR`` for three of them -and refuses the three whose parameters a bare annotation does not carry. A -refused column class costs operations (``Model.c.`` reports the gap); -a refused storage entry costs the table itself, which is why the two halves -answer separately. +them answered: ``datetime.timedelta`` names ``IntervalColumn``, and the six +complex families -- geometry, vector, bit string, range, multirange and MAC +address -- name the core classes, which promise only the surface every column +has. The DDL half of the six families is answered separately, in +``data_type_suggestions.py``: this backend spells ``GEOMETRY`` / ``VARBIT`` / +``MACADDR`` for three of them and refuses the three whose parameters a bare +annotation does not carry. A column class and a storage entry answer +separately, and neither one's answer implies the other's. **What the answers are measured against.** The live probes in ``.claude/plan/2026-10-08/suggested-mappings.md`` §8 (≈90 server instances @@ -71,14 +69,21 @@ from rhosocial.activerecord.backend.expression.column_types import ( ArrayColumn, BinaryColumn, + BitStringColumn, BooleanColumn, ColumnBase, - TimestampColumn, + GeometryColumn, IntegerColumn, + IntervalColumn, JSONColumn, + MacAddressColumn, + MultirangeColumn, NumericColumn, + RangeColumn, StringColumn, + TimestampColumn, UUIDColumn, + VectorColumn, ) #: All twenty-four protocol entries, in the protocol's reading order. Commented @@ -116,23 +121,18 @@ datetime.date: TimestampColumn, datetime.time: TimestampColumn, datetime.datetime: TimestampColumn, - # THE ONE DELIBERATE `None`. PostgreSQL has a real `interval` type -- §1 - # spells it `INTERVAL` where eight backends have no answer at all -- and no - # core column class answers for it (`IntervalColumn` is a core gap, - # secondary-gaps 附录 D ①). `interval` is not a number: the server answers - # `justify_hours`, `EXTRACT(... FROM interval)` and field qualifiers for - # it, and refuses `sqrt(interval '1 day')` outright, so naming a number - # class here would hand the caller operations the engine cannot execute. - # `None` is the protocol's last resort and this is its last resort: the - # value is carried (psycopg binds and reads back a `timedelta`), and the - # storage is spelled by the `DataType` layer - # (`format_data_type_interval`), but the *operations* have no class to - # name. A field declared `timedelta` fails to resolve with a message - # naming the fix -- declare one explicitly with - # `UseColumnType(SomeColumn)`. When core grows an `IntervalColumn`, this - # entry is where it goes (pinned by - # `test_the_interval_entry_is_refused_until_core_grows_an_interval_column`). - datetime.timedelta: None, + # PostgreSQL has a real `interval` type -- §1 spells it `INTERVAL` where + # eight backends have no answer at all -- and it is not a number: + # `justify_hours`, `EXTRACT(... FROM interval)` and the field qualifiers + # operate on it, while `sqrt(interval '1 day')` is refused outright. So + # `IntervalColumn` names the value and offers no arithmetic; the numeric + # operations stay with numbers. The storage is spelled by the `DataType` + # layer (`format_data_type_interval`). + # + # The backend's own interval operations (`justify_hours`, field extraction) + # belong to a PostgreSQL-named subclass; the core class states only the + # surface every column has. + datetime.timedelta: IntervalColumn, # -- Value families -------------------------------------------------- uuid.UUID: UUIDColumn, # `dict` → the JSON column class, on both `json` and `jsonb`. §12's @@ -176,16 +176,19 @@ # this protocol exists to keep. enum.Enum: StringColumn, # -- Complex families ------------------------------------------------ - # core has no column class for these yet, so they are refused rather than - # answered with a class that does not exist. Their storage is answered in - # ``data_type_suggestions.py``, which is the half this backend does own. When core - # grows the family classes, these six entries are where they go. - Geometry: None, - Vector: None, - BitString: None, - Range: None, - Multirange: None, - MacAddress: None, + # The six families now have core column classes. Those classes promise + # only the surface every column has -- alias, null tests, casting and + # collation -- because no distance, containment, overlap, bitwise or + # similarity operation is spelled the same way on every backend. The + # PostgreSQL operations live on backend-named subclasses (PostGIS is an + # extension, not the core server), which is where the richer spelling + # belongs. The storage stays answered in `data_type_suggestions.py`. + Geometry: GeometryColumn, + Vector: VectorColumn, + BitString: BitStringColumn, + Range: RangeColumn, + Multirange: MultirangeColumn, + MacAddress: MacAddressColumn, } @@ -205,17 +208,21 @@ class PostgresColumnTypeMixin(ColumnTypeMixin): operations, and it is pinned by the backend's own test file rather than left to drift. - **Seven entries are refused.** ``datetime.timedelta`` answers ``None`` - because PostgreSQL's native ``interval`` has no core column class -- the - gap this backend used to hide by naming ``NumericColumn`` and accepting - that ``sqrt(interval '1 day')`` would be offered and would fail on the - server. A refusal that reaches the model layer as a resolution error is - the honest version of that gap, and the entry's comment says what closes - it. The other six are the complex families, refused for the mirror-image - reason: the operations would have to be written against a core column - class that does not exist yet. Their storage is answered -- ``GEOMETRY``, - ``VARBIT`` and ``MACADDR`` here -- so a bare model builds the table and - only the field accessor reports the gap. + **No entry is refused.** ``datetime.timedelta`` used to answer ``None`` + because PostgreSQL's native ``interval`` had no core column class; core + now has ``IntervalColumn``, so the value is named and the arithmetic it + does not promise stays where it belongs. The six complex families used to + answer ``None`` for the mirror-image reason -- no core class existed -- + and now name their core classes, which promise only the surface every + column has. Their storage is answered here too -- ``GEOMETRY``, + ``VARBIT`` and ``MACADDR`` -- so a bare model builds the table and a + field resolves. + + **A backend-named class is where richer operations go.** PostGIS + functions, range ``@>`` operators and `justify_hours` are each this + server's own; they belong to a subclass such as + ``PostgresGeometryColumn(GeometryColumn)`` in the extra table, not to + the core class that every backend derives from. The table has no version branch because nothing in it moves with the version: the one thing that does (``jsonb`` becoming available in 9.4) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py index 4974452f..1183cb5c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py @@ -163,7 +163,7 @@ def get_postgres_protocols(): dialect_protocols.IdentityColumnSupport, dialect_protocols.GeneratedColumnSupport, # The column-type table: `PostgresColumnTypeMixin` answers - # `suggested_column_types()` for all eighteen common Python types and + # `suggested_column_types()` for all twenty-four Python types and # `suggested_extra_column_types()` with nothing of its own, and the # dialect composes the mixin. The table is the model layer's source for # which column class a field's annotation resolves to, so PostgreSQL diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py index 731bb219..8e41812f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py @@ -1,18 +1,19 @@ # tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py -"""PostgreSQL's column-type table, and the one entry it refuses. +"""PostgreSQL's column-type table, and where its own operations live. The protocol's obligation on a backend is three things (``backend/dialect/mixins/column_type.py``, the contract list in ``testsuite/feature/query/typed_column/column_helpers.COMMON_TYPES``): -1. **Answer every entry.** All eighteen of the closed list, none of them +1. **Answer every entry.** All twenty-four of the closed list, none of them silently absent. A hole is a lie told to the model layer. 2. **Say so where this backend differs.** Here: native arrays for the four sequence entries, where seven backends carry a JSON document. 3. **Refuse only what it truly cannot express** -- with ``None``, which reaches - the caller as a resolution error rather than as a silent pick. Here: the one - entry, ``datetime.timedelta``, whose native ``interval`` this server carries - but whose operations no core column class names. + the caller as a resolution error rather than as a silent pick. Here: + nothing. ``timedelta`` names ``IntervalColumn`` and the six complex families + name their core classes, all of which promise only the surface every column + has. No database is needed for any of it: the question is which class an annotation resolves to, and the dialect already knows the server version. @@ -106,7 +107,7 @@ def test_the_table_has_no_entry_beyond_the_protocol(dialect): def test_the_backend_declares_no_extra_python_types(dialect): - """The framework's eighteen are the whole of what PostgreSQL answers for. + """The framework's twenty-four are the whole of what PostgreSQL answers for. Its *server* types beyond them (``interval``, ``xml``, the multirange family) are reached through their ``DataType`` spelling, not through a @@ -225,41 +226,65 @@ class Mood(enum.Enum): assert resolve(dialect, Mood) is StringColumn -def test_the_interval_entry_is_refused_until_core_grows_an_interval_column(dialect): - """**The one deliberate refusal**, and the reasons it is not ``None``'s - opposite either. +def test_the_interval_entry_names_the_core_interval_class(dialect): + """A duration is a duration, not a number of its own family. PostgreSQL has a real ``interval`` type where eight backends have no answer - at all (the protocol's own survey, §1), so there is no "this backend cannot - carry a duration" story here: psycopg binds a ``timedelta`` and reads one - back, and the ``DataType`` layer spells the storage - (``format_data_type_interval``). What no core column class offers is the - *operation* surface -- ``justify_hours``, ``EXTRACT(... FROM interval)``, - the field qualifiers -- and naming a number class would offer - transcendentals the server refuses: ``sqrt(interval '1 day')`` is an error. - - ``NumericColumn`` was the answer the last version of this table gave, and - it was a *declared* over-claim kept visible only because ``FloatColumn`` - and ``DecimalColumn`` existed to differ from. With the numeric family merged - into one class that visibility is gone, so the honest answer under the - rebuilt protocol is ``None``: the gap reaches the model layer as a - resolution error naming the way out, instead of as a number class that - cannot keep its promise. - - When core grows an ``IntervalColumn``, this entry is where it goes -- so - this test fails then, on purpose. + at all (the protocol's own survey, §1): psycopg binds a ``timedelta`` and + reads one back, and the ``DataType`` layer spells the storage + (``format_data_type_interval``). + + The class matters because ``interval`` refuses the numeric operations -- + ``sqrt(interval '1 day')`` is an error -- and offers operations of its own + (``justify_hours``, ``EXTRACT(... FROM interval)``, field qualifiers). + ``IntervalColumn`` names the value without claiming either side: the + numeric surface is not offered, and PostgreSQL's own operations belong to + a PostgreSQL-named subclass. """ - assert dialect.suggested_column_types()[datetime.timedelta] is None + from rhosocial.activerecord.backend.expression.column_types import IntervalColumn + from rhosocial.activerecord.backend.impl.dummy.column_type import DUMMY_COLUMN_TYPES - with pytest.raises(ColumnTypeResolutionError) as excinfo: - resolve(dialect, datetime.timedelta) - assert "UseColumnType" in str(excinfo.value) + assert dialect.suggested_column_types()[datetime.timedelta] is IntervalColumn + assert resolve(dialect, datetime.timedelta) is IntervalColumn + # Both dialects now answer it, so there is no gap left to refuse. + assert DUMMY_COLUMN_TYPES[datetime.timedelta] is IntervalColumn - # The refusal is this table's, not the framework's: the generic numeric - # answer is what the portable baseline would have said. - from rhosocial.activerecord.backend.impl.dummy.column_type import DUMMY_COLUMN_TYPES - assert DUMMY_COLUMN_TYPES[datetime.timedelta] is NumericColumn +def test_the_complex_families_name_the_core_column_classes(dialect): + """Six families, one answer each -- and no operation beyond the column surface. + + The classes carry alias, null tests, casting and collation only. PostGIS, + the range operators and bit arithmetic are this server's own spellings and + belong to backend-named subclasses, which the extra table will carry. + """ + from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, + ) + from rhosocial.activerecord.backend.expression.column_types import ( + BitStringColumn, + GeometryColumn, + MacAddressColumn, + MultirangeColumn, + RangeColumn, + VectorColumn, + ) + + expected = { + Geometry: GeometryColumn, + Vector: VectorColumn, + BitString: BitStringColumn, + Range: RangeColumn, + Multirange: MultirangeColumn, + MacAddress: MacAddressColumn, + } + for entry, klass in expected.items(): + assert dialect.suggested_column_types()[entry] is klass + assert resolve(dialect, entry) is klass # --------------------------------------------------------------------------- From 88e6d33efa2017b9972d082fb20a155523763177 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:26:31 +0800 Subject: [PATCH 26/81] feat(postgres): name the server's own column classes and answer the extras table Twelve PostgreSQL-named column classes (geometry, vector, range, multirange, bit string, text search, jsonpath, hstore, xml, macaddr, money, identifiers, lsn) give this server's values a home for its own operations and a name a field can pass to UseColumnType. POSTGRES_EXTRA_COLUMN_TYPES keys 35 of them by the value class they answer for, mirroring the extra data-type table. PostgresRange/PostgresMultirange stay out for the reason recorded there: their adapters only register in the CUSTOM/BOTH range modes, so a default backend cannot write the value. The classes exist and can be declared explicitly once the adapter is in place. The extras table is disjoint from the twenty-four common entries, every answer builds and renders, and a field annotated with Point resolves to the PostgreSQL geometry class without a declaration. --- .../backend/impl/postgres/column_types.py | 174 ++++++++++++++++++ .../impl/postgres/mixins/column_type.py | 117 +++++++++++- .../types/test_column_type_suggestions.py | 70 ++++++- 3 files changed, 353 insertions(+), 8 deletions(-) create mode 100644 src/rhosocial/activerecord/backend/impl/postgres/column_types.py diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py new file mode 100644 index 00000000..3c92397b --- /dev/null +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -0,0 +1,174 @@ +# src/rhosocial/activerecord/backend/impl/postgres/column_types.py +"""PostgreSQL's own column classes. + +A column class is an *operation surface*: it says what a value held in a column +can be asked to do. Core narrows by the Python type (``str`` -> StringColumn, +``dict`` -> JSONColumn), and those classes deliberately promise only what every +backend can execute. PostgreSQL carries value families the framework does not +have a core class for -- text search, ``jsonpath``, hstore, LSN, the object +identifiers -- and richer spellings for the ones it does (PostGIS, the range +operators, ``macaddr``). + +This module is where those names live, so a model can choose one explicitly:: + + Annotated[Point, UseColumnType(PostgresGeometryColumn())] + +Each class inherits the core class that already carries the right operation +floor (``PostgresGeometryColumn(GeometryColumn)``), or ``ColumnBase`` when the +family has no core class at all (text search, hstore, LSN). The server's own +operations -- ``ST_Distance``, ``@>``, ``justify_hours`` -- are added here as +they are measured; until then the class states the same floor the core class +does, which is the honest minimum rather than a promise the server refuses. + +``POSTGRES_EXTRA_COLUMN_TYPES`` in :mod:`.mixins.column_type` keys these by the +value class they answer for, so a field annotated with one of PostgreSQL's own +value types resolves without a declaration. +""" + +from rhosocial.activerecord.backend.expression.column_types import ( + BitStringColumn, + ColumnBase, + GeometryColumn, + IntegerColumn, + MacAddressColumn, + MultirangeColumn, + NumericColumn, + RangeColumn, + VectorColumn, + XMLColumn, +) + + +class PostgresGeometryColumn(GeometryColumn): + """A column holding a PostgreSQL geometric value (point, line, box, ...). + + Seven server geometric types and the PostGIS ``geometry`` wrapper share one + operation surface here. ``ST_Distance`` and the overlap operators are the + server's own spellings and are added to this class as they are measured. + """ + + +class PostgresVectorColumn(VectorColumn): + """A column holding a pgvector value. + + The ``<->`` / ``<=>`` / ``<#>`` distance operators belong here; the core + class states only the shared column surface until they are measured. + """ + + +class PostgresRangeColumn(RangeColumn): + """A column holding a native PostgreSQL range (``int4range``, ...). + + ``@>`` / ``<@`` / ``&&`` and ``lower()`` / ``upper()`` are PostgreSQL's own; + they are added here as the range family is completed. + """ + + +class PostgresMultirangeColumn(MultirangeColumn): + """A column holding a native PostgreSQL multirange.""" + + +class PostgresBitStringColumn(BitStringColumn): + """A column holding ``bit`` / ``varbit``. + + PostgreSQL spells exclusive-or ``#`` where MySQL spells it ``^``, so the + bitwise family lives on this class rather than on the shared one. + """ + + +class PostgresTextSearchColumn(ColumnBase): + """A column holding ``tsvector`` or ``tsquery``. + + ``to_tsvector`` / ``to_tsquery`` / ``@@`` are PostgreSQL's; no core class + models a text-search value, so this class starts from the column surface. + """ + + @property + def format_method(self) -> str: + """The dialect formatting method that renders this column.""" + return "format_column" + + +class PostgresJsonPathColumn(ColumnBase): + """A column holding ``jsonpath``. + + The type has no core counterpart: it is a path expression, not a document, + so it neither navigates like JSON nor compares like text. + """ + + @property + def format_method(self) -> str: + """The dialect formatting method that renders this column.""" + return "format_column" + + +class PostgresHstoreColumn(ColumnBase): + """A column holding ``hstore``: a key/value map. + + The ``->`` accessor and the ``@>`` containment operator belong here; the + class starts from the column surface. + """ + + @property + def format_method(self) -> str: + """The dialect formatting method that renders this column.""" + return "format_column" + + +class PostgresXmlColumn(XMLColumn): + """A column holding PostgreSQL ``xml``. + + Inherits the core XML surface: casting and null tests, but no comparison -- + ``xml = xml`` is refused by this server too. + """ + + +class PostgresMacAddressColumn(MacAddressColumn): + """A column holding ``macaddr`` or ``macaddr8``.""" + + +class PostgresMoneyColumn(NumericColumn): + """A column holding ``money``. + + It inherits the numeric surface, which is what the server gives it, and the + currency/locale facts stay with the DDL layer. + """ + + +class PostgresIdentifierColumn(IntegerColumn): + """A column holding an object identifier (``oid``, ``regclass``, ``xid``, ...). + + The registry names are OID aliases, so they carry the whole-number surface + while the spelling of the declaration is the DDL layer's job. + """ + + +class PostgresLsnColumn(ColumnBase): + """A column holding ``pg_lsn``: a log sequence number. + + The type compares and subtracts like a number, but it is a position in the + write-ahead log rather than a value to compute with, so no core numeric + surface is claimed here. + """ + + @property + def format_method(self) -> str: + """The dialect formatting method that renders this column.""" + return "format_column" + + +__all__ = [ + "PostgresGeometryColumn", + "PostgresVectorColumn", + "PostgresRangeColumn", + "PostgresMultirangeColumn", + "PostgresBitStringColumn", + "PostgresTextSearchColumn", + "PostgresJsonPathColumn", + "PostgresHstoreColumn", + "PostgresXmlColumn", + "PostgresMacAddressColumn", + "PostgresMoneyColumn", + "PostgresIdentifierColumn", + "PostgresLsnColumn", +] diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py index 727c6728..aef4062d 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py @@ -85,6 +85,56 @@ UUIDColumn, VectorColumn, ) +from ..column_types import ( + PostgresBitStringColumn, + PostgresGeometryColumn, + PostgresHstoreColumn, + PostgresIdentifierColumn, + PostgresJsonPathColumn, + PostgresLsnColumn, + PostgresMacAddressColumn, + PostgresMoneyColumn, + PostgresTextSearchColumn, + PostgresVectorColumn, + PostgresXmlColumn, +) +from ..type_values import ( + Box, + Circle, + CID, + Line, + LineSegment, + OID, + Path, + Point, + Polygon, + PostgresBitString, + PostgresGeometry, + PostgresHstore, + PostgresJsonPath, + PostgresLsn, + PostgresMacaddr, + PostgresMacaddr8, + PostgresMoney, + PostgresTsQuery, + PostgresTsVector, + PostgresVector, + PostgresXML, + RegClass, + RegCollation, + RegConfig, + RegDictionary, + RegNamespace, + RegOper, + RegOperator, + RegProc, + RegProcedure, + RegRole, + RegType, + TID, + XID, + XID8, +) #: All twenty-four protocol entries, in the protocol's reading order. Commented #: per group because the reasons are the content: the answer is a claim about @@ -192,6 +242,58 @@ } +#: PostgreSQL's own value classes -> the column class a bare field gets. +#: +#: The protocol's second table, and the backend-owned half: a Python type this +#: server models and the framework does not. The keys mirror +#: ``POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS``, with one deliberate omission -- +#: ``PostgresRange`` / ``PostgresMultirange`` -- for the reason recorded there: +#: their adapters register only in the CUSTOM/BOTH range modes, so a default +#: backend has no adapter for the value and a suggestion would build a column +#: nothing can write. The column classes exist (``PostgresRangeColumn`` and +#: ``PostgresMultirangeColumn``) and a field can name them explicitly with +#: ``UseColumnType`` once its adapter is in place. +POSTGRES_EXTRA_COLUMN_TYPES: Dict[Any, Type[ColumnBase]] = { + PostgresBitString: PostgresBitStringColumn, + PostgresGeometry: PostgresGeometryColumn, + Point: PostgresGeometryColumn, + Line: PostgresGeometryColumn, + LineSegment: PostgresGeometryColumn, + Box: PostgresGeometryColumn, + Path: PostgresGeometryColumn, + Polygon: PostgresGeometryColumn, + Circle: PostgresGeometryColumn, + PostgresTsVector: PostgresTextSearchColumn, + PostgresTsQuery: PostgresTextSearchColumn, + PostgresJsonPath: PostgresJsonPathColumn, + PostgresHstore: PostgresHstoreColumn, + PostgresMacaddr: PostgresMacAddressColumn, + PostgresMacaddr8: PostgresMacAddressColumn, + PostgresMoney: PostgresMoneyColumn, + PostgresXML: PostgresXmlColumn, + PostgresLsn: PostgresLsnColumn, + PostgresVector: PostgresVectorColumn, + # Object identifiers: the registry names are OID aliases, so they share the + # whole-number surface and the DDL spelling differs per name. + OID: PostgresIdentifierColumn, + RegClass: PostgresIdentifierColumn, + RegType: PostgresIdentifierColumn, + RegProc: PostgresIdentifierColumn, + RegProcedure: PostgresIdentifierColumn, + RegOper: PostgresIdentifierColumn, + RegOperator: PostgresIdentifierColumn, + RegConfig: PostgresIdentifierColumn, + RegDictionary: PostgresIdentifierColumn, + RegNamespace: PostgresIdentifierColumn, + RegRole: PostgresIdentifierColumn, + RegCollation: PostgresIdentifierColumn, + XID: PostgresIdentifierColumn, + XID8: PostgresIdentifierColumn, + CID: PostgresIdentifierColumn, + TID: PostgresIdentifierColumn, +} + + class PostgresColumnTypeMixin(ColumnTypeMixin): """The full framework-modelled-Python-type → column-class table for PostgreSQL. @@ -232,5 +334,18 @@ class PostgresColumnTypeMixin(ColumnTypeMixin): def suggested_column_types(self) -> Dict[Any, Optional[Type[ColumnBase]]]: return dict(POSTGRES_COLUMN_TYPES) + def suggested_extra_column_types(self) -> Dict[Any, Type[ColumnBase]]: + """This server's own value classes -> their column classes. + + A field annotated with a PostgreSQL value class (``Point``, ``PostgresXML``, + ``PostgresMoney``) resolves without a declaration. The range wrappers are + absent on purpose -- see :data:`POSTGRES_EXTRA_COLUMN_TYPES`. + """ + return dict(POSTGRES_EXTRA_COLUMN_TYPES) + -__all__ = ["POSTGRES_COLUMN_TYPES", "PostgresColumnTypeMixin"] +__all__ = [ + "POSTGRES_COLUMN_TYPES", + "POSTGRES_EXTRA_COLUMN_TYPES", + "PostgresColumnTypeMixin", +] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py index 8e41812f..43d0a735 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py @@ -106,15 +106,37 @@ def test_the_table_has_no_entry_beyond_the_protocol(dialect): assert extra == set() -def test_the_backend_declares_no_extra_python_types(dialect): - """The framework's twenty-four are the whole of what PostgreSQL answers for. +def test_the_backend_declares_its_own_python_types_separately(dialect): + """The framework's twenty-four stay in their own table. - Its *server* types beyond them (``interval``, ``xml``, the multirange - family) are reached through their ``DataType`` spelling, not through a - Python-annotation entry of their own: annotating a field with an - unregistered custom class is what ``UseColumnType`` is for. + PostgreSQL models value classes beyond them (``Point``, ``PostgresXML``, + ``PostgresMoney``, the object identifiers), and the protocol reports those + through ``suggested_extra_column_types()`` so "the framework has an answer" + stays distinguishable from "this backend has one of its own". """ - assert dialect.suggested_extra_column_types() == {} + extra = dialect.suggested_extra_column_types() + assert set(extra) - set(COMMON_TYPES) == set(extra) + assert extra + + +def test_every_extra_entry_answers_with_a_column_class(dialect): + """The same two-state rule as the common table: a class, never a hole.""" + from rhosocial.activerecord.backend.expression.column_types import ColumnBase + + extra = dialect.suggested_extra_column_types() + for entry, column_class in extra.items(): + assert isinstance(column_class, type), entry + assert issubclass(column_class, ColumnBase), entry + + +def test_every_extra_class_builds_and_renders(dialect): + """An extras cell is only real if the column it names can be built.""" + from rhosocial.activerecord.backend.expression.column_types import ColumnBase + + for column_class in dialect.suggested_extra_column_types().values(): + column = column_class(dialect, "c") + assert isinstance(column, ColumnBase) + assert column.to_sql() == ('"c"', ()) def test_the_table_agrees_with_the_module_level_constant(dialect): @@ -287,6 +309,40 @@ def test_the_complex_families_name_the_core_column_classes(dialect): assert resolve(dialect, entry) is klass +def test_the_complex_families_are_named_by_this_backend(dialect): + """PostGIS, range and vector spellings belong to PostgreSQL-named classes. + + The core classes stay the shared floor; the names that carry this server's + own operations live in ``impl.postgres.column_types`` and are reachable + with ``UseColumnType``. + """ + from rhosocial.activerecord.backend.impl.postgres import column_types as pg + + for column_class in dialect.suggested_extra_column_types().values(): + assert column_class.__module__ == pg.__name__ + assert column_class.__name__.startswith("Postgres") + + +def test_a_postgres_named_class_is_usable_through_use_column_type(dialect): + """A field can declare the stronger surface explicitly. + + ``Point`` on its own resolves to the column class the extras table records; + a ``UseColumnType`` declaration overrides that with any class whose values + the same annotation can hold. + """ + from rhosocial.activerecord.base.fields import UseColumnType + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresGeometryColumn, + ) + from rhosocial.activerecord.backend.impl.postgres.type_values import Point + + assert resolve(dialect, Point) is PostgresGeometryColumn + assert ( + resolve_column_class(dialect, Point, UseColumnType(PostgresGeometryColumn)) + is PostgresGeometryColumn + ) + + # --------------------------------------------------------------------------- # 3. Normalisation: the protocol's rules, on this backend # --------------------------------------------------------------------------- From 9c800aa1c1d75d89467de84149d2c5e46d260c64 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:29:10 +0800 Subject: [PATCH 27/81] test(backend): run the typed-column protocol contract in this CI The shared file now covers the extras table as well -- class answers, disjoint keys, constructibility and a fresh copy -- so this backend reports a malformed or overlapping extras entry as its own failure rather than leaving it to a later query. --- .../feature/query/typed_column/test_protocol_guarantees.py | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py new file mode 100644 index 00000000..7b73fe82 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_protocol_guarantees import * # noqa: F401,F403 From 9fcdab5c25fb44a38448203e9fa73a2532604991 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:44:21 +0800 Subject: [PATCH 28/81] feat(postgres): give the geometric column classes their built-in operators distance_to (<->) is offered on every geometry value; contains (@>), contained_by (<@) and overlaps (&&) live on PostgresAreaGeometryColumn, because a point has no @> -- a live probe against 18.6 refused it. The extras table now keys box, polygon and circle to the narrower class so a Point field cannot offer an operator the server would refuse. Render assertions plus a live round-trip on postgres-18 (point distance, and contains/contained_by/overlaps on a polygon) both pass. --- .../backend/impl/postgres/column_types.py | 44 ++++++++++ .../impl/postgres/mixins/column_type.py | 8 +- .../construct/types/test_column_operations.py | 81 +++++++++++++++++++ 3 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 3c92397b..97f6c529 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -25,6 +25,8 @@ value types resolves without a declaration. """ +from typing import TYPE_CHECKING + from rhosocial.activerecord.backend.expression.column_types import ( BitStringColumn, ColumnBase, @@ -38,6 +40,9 @@ XMLColumn, ) +if TYPE_CHECKING: # pragma: no cover + from rhosocial.activerecord.backend.expression.operators import BinaryExpression + class PostgresGeometryColumn(GeometryColumn): """A column holding a PostgreSQL geometric value (point, line, box, ...). @@ -47,6 +52,44 @@ class PostgresGeometryColumn(GeometryColumn): server's own spellings and are added to this class as they are measured. """ + def distance_to(self, other) -> "BinaryExpression": + """``col <-> other``: the distance between two geometric values. + + ``<->`` is the one geometric operator every native geometric type + answers (point, line, lseg, box, path, polygon, circle), so it is safe + on this shared class. + """ + from .functions.geometric import geometry_distance + + return geometry_distance(self._dialect, self, other) + + +class PostgresAreaGeometryColumn(PostgresGeometryColumn): + """A geometry column whose value can contain and overlap another value. + + ``@>`` / ``<@`` / ``&&`` exist for boxes, polygons and circles, not for + points, lines or segments. Keeping them on this narrower class means a + ``Point`` field cannot offer an operator the server would refuse. + """ + + def contains(self, other) -> "BinaryExpression": + """``col @> other``: whether this geometry contains the other.""" + from .functions.geometric import geometry_contains + + return geometry_contains(self._dialect, self, other) + + def contained_by(self, other) -> "BinaryExpression": + """``col <@ other``: whether this geometry is contained by the other.""" + from .functions.geometric import geometry_contained_by + + return geometry_contained_by(self._dialect, self, other) + + def overlaps(self, other) -> "BinaryExpression": + """``col && other``: whether the two geometries overlap.""" + from .functions.geometric import geometry_overlaps + + return geometry_overlaps(self._dialect, self, other) + class PostgresVectorColumn(VectorColumn): """A column holding a pgvector value. @@ -159,6 +202,7 @@ def format_method(self) -> str: __all__ = [ "PostgresGeometryColumn", + "PostgresAreaGeometryColumn", "PostgresVectorColumn", "PostgresRangeColumn", "PostgresMultirangeColumn", diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py index aef4062d..c5e66794 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py @@ -86,6 +86,7 @@ VectorColumn, ) from ..column_types import ( + PostgresAreaGeometryColumn, PostgresBitStringColumn, PostgresGeometryColumn, PostgresHstoreColumn, @@ -259,10 +260,11 @@ Point: PostgresGeometryColumn, Line: PostgresGeometryColumn, LineSegment: PostgresGeometryColumn, - Box: PostgresGeometryColumn, Path: PostgresGeometryColumn, - Polygon: PostgresGeometryColumn, - Circle: PostgresGeometryColumn, + # @> / <@ / && exist for these three, not for the line-like types. + Box: PostgresAreaGeometryColumn, + Polygon: PostgresAreaGeometryColumn, + Circle: PostgresAreaGeometryColumn, PostgresTsVector: PostgresTextSearchColumn, PostgresTsQuery: PostgresTextSearchColumn, PostgresJsonPath: PostgresJsonPathColumn, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py new file mode 100644 index 00000000..b0897d3c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -0,0 +1,81 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +"""The server-specific operations on PostgreSQL's own column classes. + +Each operation is a thin façade over a function/operator node this backend +already has. These tests assert the SQL it renders: adding an operation is a +deliberate edit here, not a name that quietly promises more than the server +can execute. Live round-trips are done against the configured scenarios; the +render assertions are the part that needs no server. +""" + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresAreaGeometryColumn, + PostgresGeometryColumn, +) +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect + + +@pytest.fixture +def dialect(): + return PostgresDialect(version=(16, 0, 0)) + + +@pytest.fixture +def geometry(dialect): + return PostgresGeometryColumn(dialect, "g") + + +# --------------------------------------------------------------------------- +# Geometry: PostgreSQL's built-in geometric operators (no extension needed) +# --------------------------------------------------------------------------- + + +def test_distance_is_available_on_every_geometry(geometry): + """``<->`` answers on point, line, lseg, box, path, polygon and circle.""" + expr = geometry.distance_to("(1,1)") + assert expr.to_sql() == ('"g" <-> %s', ("(1,1)",)) + + +@pytest.mark.parametrize( + "method, operator", + [ + ("contains", "@>"), + ("contained_by", "<@"), + ("overlaps", "&&"), + ], +) +def test_area_geometry_operators_against_a_literal(dialect, method, operator): + column = PostgresAreaGeometryColumn(dialect, "g") + expr = getattr(column, method)("(1,1)") + assert expr.to_sql() == (f'"g" {operator} %s', ("(1,1)",)) + + +@pytest.mark.parametrize( + "method, operator", + [ + ("distance_to", "<->"), + ("contains", "@>"), + ("contained_by", "<@"), + ("overlaps", "&&"), + ], +) +def test_geometry_operators_against_a_column(geometry, dialect, method, operator): + if method == "distance_to": + source, other = geometry, PostgresGeometryColumn(dialect, "h") + else: + source = PostgresAreaGeometryColumn(dialect, "g") + other = PostgresAreaGeometryColumn(dialect, "h") + expr = getattr(source, method)(other) + assert expr.to_sql() == (f'"g" {operator} "h"', ()) + + +def test_the_area_operators_are_not_offered_on_a_point(dialect): + """A point has no ``@>``; resolving Point must not hand out a false one.""" + from rhosocial.activerecord.backend.impl.postgres.type_values import Box, Point + + assert dialect.suggested_extra_column_types()[Point] is PostgresGeometryColumn + assert dialect.suggested_extra_column_types()[Box] is PostgresAreaGeometryColumn + assert not hasattr(PostgresGeometryColumn(dialect, "p"), "contains") + assert hasattr(PostgresAreaGeometryColumn(dialect, "b"), "contains") From be598fd1613b6ab979c9d25676655c7c6b0485be Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:46:05 +0800 Subject: [PATCH 29/81] feat(postgres): give the bit-string column class its bitwise operators MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bit_and/bit_or/bit_xor (#, not ^), bit_not, BIT_LENGTH (not the generic LENGTH), BIT_COUNT and the two shifts are thin façades over the existing bit_string functions. Render assertions plus a live round-trip on postgres-18.6 pass. --- .../backend/impl/postgres/column_types.py | 54 ++++++++++++++++++- .../construct/types/test_column_operations.py | 38 +++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 97f6c529..605cc4f4 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -41,7 +41,11 @@ ) if TYPE_CHECKING: # pragma: no cover - from rhosocial.activerecord.backend.expression.operators import BinaryExpression + from rhosocial.activerecord.backend.expression.operators import ( + BinaryExpression, + UnaryExpression, + ) + from rhosocial.activerecord.backend.expression.functions import FunctionCall class PostgresGeometryColumn(GeometryColumn): @@ -118,6 +122,54 @@ class PostgresBitStringColumn(BitStringColumn): bitwise family lives on this class rather than on the shared one. """ + def bit_and(self, other) -> "BinaryExpression": + """``col & other``.""" + from .functions.bit_string import bit_and + + return bit_and(self._dialect, self, other) + + def bit_or(self, other) -> "BinaryExpression": + """``col | other``.""" + from .functions.bit_string import bit_or + + return bit_or(self._dialect, self, other) + + def bit_xor(self, other) -> "BinaryExpression": + """``col # other`` -- PostgreSQL's spelling of bitwise XOR.""" + from .functions.bit_string import bit_xor + + return bit_xor(self._dialect, self, other) + + def bit_not(self) -> "UnaryExpression": + """``~ col``.""" + from .functions.bit_string import bit_not + + return bit_not(self._dialect, self) + + def bit_length(self) -> "FunctionCall": + """``BIT_LENGTH(col)``, not the generic ``LENGTH``.""" + from .functions.bit_string import bit_length_func + + return bit_length_func(self._dialect, self) + + def bit_count(self) -> "FunctionCall": + """``BIT_COUNT(col)``: the number of set bits.""" + from .functions.bit_string import bit_count + + return bit_count(self._dialect, self) + + def shift_left(self, n: int) -> "BinaryExpression": + """``col << n``.""" + from .functions.bit_string import bit_shift_left + + return bit_shift_left(self._dialect, self, n) + + def shift_right(self, n: int) -> "BinaryExpression": + """``col >> n``.""" + from .functions.bit_string import bit_shift_right + + return bit_shift_right(self._dialect, self, n) + class PostgresTextSearchColumn(ColumnBase): """A column holding ``tsvector`` or ``tsquery``. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index b0897d3c..2b64e350 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -79,3 +79,41 @@ def test_the_area_operators_are_not_offered_on_a_point(dialect): assert dialect.suggested_extra_column_types()[Box] is PostgresAreaGeometryColumn assert not hasattr(PostgresGeometryColumn(dialect, "p"), "contains") assert hasattr(PostgresAreaGeometryColumn(dialect, "b"), "contains") + + +# --------------------------------------------------------------------------- +# Bit strings: built-in bitwise operators and length/count functions +# --------------------------------------------------------------------------- + + +@pytest.fixture +def bits(dialect): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresBitStringColumn, + ) + + return PostgresBitStringColumn(dialect, "b") + + +@pytest.mark.parametrize( + "method, operator", + [("bit_and", "&"), ("bit_or", "|"), ("bit_xor", "#")], +) +def test_bitwise_binary_operators(bits, dialect, method, operator): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresBitStringColumn, + ) + + expr = getattr(bits, method)(PostgresBitStringColumn(dialect, "h")) + assert expr.to_sql() == (f'"b" {operator} "h"', ()) + + +def test_bitwise_not_and_length(bits): + assert bits.bit_not().to_sql() == ('~ "b"', ()) + assert bits.bit_length().to_sql() == ('BIT_LENGTH("b")', ()) + assert bits.bit_count().to_sql() == ('BIT_COUNT("b")', ()) + + +@pytest.mark.parametrize("method, operator", [("shift_left", "<<"), ("shift_right", ">>")]) +def test_bitwise_shifts(bits, method, operator): + assert getattr(bits, method)(2).to_sql() == (f'"b" {operator} %s', (2,)) From dddc0502ed2f44109592edac40873ae4e73e8c2e Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:49:09 +0800 Subject: [PATCH 30/81] feat(postgres): give the range column class its operators and functions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit contains/contained_by/overlaps and is_empty/lower/upper are thin façades over functions/range.py, each gated on supports_range_operators() or supports_range_functions(). A 9.1 dialect now fails loudly by capability name instead of rendering an operator the server would refuse. Render assertions and gates pass; a live int4range round-trip on postgres-18.6 returns the expected answers for all six operations. --- .../backend/impl/postgres/column_types.py | 59 +++++++++++++++++++ .../construct/types/test_column_operations.py | 56 ++++++++++++++++++ 2 files changed, 115 insertions(+) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 605cc4f4..1a7218d1 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -27,6 +27,7 @@ from typing import TYPE_CHECKING +from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError from rhosocial.activerecord.backend.expression.column_types import ( BitStringColumn, ColumnBase, @@ -48,6 +49,22 @@ from rhosocial.activerecord.backend.expression.functions import FunctionCall +def _require(dialect, switch: str) -> None: + """Fail loudly, and by name, when the server does not answer a capability. + + A column method must never render an operator the server has no switch + for: that would produce SQL which fails on the first query, with the error + pointing at the column instead of at the missing capability. + """ + answer = getattr(dialect, switch, None) + if answer is None or not answer(): + raise UnsupportedFeatureError( + type(dialect).__name__, + switch, + f"this operation needs the {switch}() capability", + ) + + class PostgresGeometryColumn(GeometryColumn): """A column holding a PostgreSQL geometric value (point, line, box, ...). @@ -110,6 +127,48 @@ class PostgresRangeColumn(RangeColumn): they are added here as the range family is completed. """ + def contains(self, other) -> "BinaryExpression": + """``col @> other``: does the range contain the element or range?""" + _require(self._dialect, "supports_range_operators") + from .functions.range import range_contains + + return range_contains(self._dialect, self, other) + + def contained_by(self, other) -> "BinaryExpression": + """``col <@ other``.""" + _require(self._dialect, "supports_range_operators") + from .functions.range import range_contained_by + + return range_contained_by(self._dialect, self, other) + + def overlaps(self, other) -> "BinaryExpression": + """``col && other``.""" + _require(self._dialect, "supports_range_operators") + from .functions.range import range_overlaps + + return range_overlaps(self._dialect, self, other) + + def is_empty(self) -> "FunctionCall": + """``ISEMPTY(col)``.""" + _require(self._dialect, "supports_range_functions") + from .functions.range import range_is_empty + + return range_is_empty(self._dialect, self) + + def lower(self) -> "FunctionCall": + """``LOWER(col)``.""" + _require(self._dialect, "supports_range_functions") + from .functions.range import range_lower + + return range_lower(self._dialect, self) + + def upper(self) -> "FunctionCall": + """``UPPER(col)``.""" + _require(self._dialect, "supports_range_functions") + from .functions.range import range_upper + + return range_upper(self._dialect, self) + class PostgresMultirangeColumn(MultirangeColumn): """A column holding a native PostgreSQL multirange.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index 2b64e350..acf5c6d7 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -117,3 +117,59 @@ def test_bitwise_not_and_length(bits): @pytest.mark.parametrize("method, operator", [("shift_left", "<<"), ("shift_right", ">>")]) def test_bitwise_shifts(bits, method, operator): assert getattr(bits, method)(2).to_sql() == (f'"b" {operator} %s', (2,)) + + +# --------------------------------------------------------------------------- +# Ranges: native operators and functions, gated on the range capability +# --------------------------------------------------------------------------- + + +@pytest.fixture +def ranges(dialect): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresRangeColumn, + ) + + return PostgresRangeColumn(dialect, "r") + + +@pytest.mark.parametrize( + "method, operator", + [("contains", "@>"), ("contained_by", "<@"), ("overlaps", "&&")], +) +def test_range_operators(ranges, method, operator): + assert getattr(ranges, method)(5).to_sql() == (f'"r" {operator} %s', (5,)) + + +@pytest.mark.parametrize( + "method, sql", + [("is_empty", 'ISEMPTY("r")'), ("lower", 'LOWER("r")'), ("upper", 'UPPER("r")')], +) +def test_range_functions(ranges, method, sql): + assert getattr(ranges, method)().to_sql() == (sql, ()) + + +@pytest.mark.parametrize("method", ["contains", "contained_by", "overlaps"]) +def test_range_operators_fail_on_a_server_without_them(method): + from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresRangeColumn, + ) + + old = PostgresDialect(version=(9, 1, 0)) + column = PostgresRangeColumn(old, "r") + with pytest.raises(UnsupportedFeatureError, match="supports_range_operators"): + getattr(column, method)(5) + + +@pytest.mark.parametrize("method", ["is_empty", "lower", "upper"]) +def test_range_functions_fail_on_a_server_without_them(method): + from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresRangeColumn, + ) + + old = PostgresDialect(version=(9, 1, 0)) + column = PostgresRangeColumn(old, "r") + with pytest.raises(UnsupportedFeatureError, match="supports_range_functions"): + getattr(column, method)() From a9b77189065a5efa32cdb43e0735137cfeec38ad Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:50:31 +0800 Subject: [PATCH 31/81] feat(postgres): give the multirange column class its operators contains/contained_by/overlaps wrap functions/range.py's multirange_* nodes, gated on supports_multirange() so a pre-14 dialect fails by capability name. Render assertions and a live int4multirange round-trip on postgres-18.6 pass. --- .../backend/impl/postgres/column_types.py | 21 +++++++++++ .../construct/types/test_column_operations.py | 35 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 1a7218d1..887e09d8 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -173,6 +173,27 @@ def upper(self) -> "FunctionCall": class PostgresMultirangeColumn(MultirangeColumn): """A column holding a native PostgreSQL multirange.""" + def contains(self, other) -> "BinaryExpression": + """``col @> other``.""" + _require(self._dialect, "supports_multirange") + from .functions.range import multirange_contains + + return multirange_contains(self._dialect, self, other) + + def contained_by(self, other) -> "BinaryExpression": + """``col <@ other``.""" + _require(self._dialect, "supports_multirange") + from .functions.range import multirange_is_contained_by + + return multirange_is_contained_by(self._dialect, self, other) + + def overlaps(self, other) -> "BinaryExpression": + """``col && other``.""" + _require(self._dialect, "supports_multirange") + from .functions.range import multirange_overlaps + + return multirange_overlaps(self._dialect, self, other) + class PostgresBitStringColumn(BitStringColumn): """A column holding ``bit`` / ``varbit``. diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index acf5c6d7..98b398f9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -173,3 +173,38 @@ def test_range_functions_fail_on_a_server_without_them(method): column = PostgresRangeColumn(old, "r") with pytest.raises(UnsupportedFeatureError, match="supports_range_functions"): getattr(column, method)() + + +# --------------------------------------------------------------------------- +# Multiranges: the same operators on a native multirange column +# --------------------------------------------------------------------------- + + +@pytest.fixture +def multiranges(dialect): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresMultirangeColumn, + ) + + return PostgresMultirangeColumn(dialect, "m") + + +@pytest.mark.parametrize( + "method, operator", + [("contains", "@>"), ("contained_by", "<@"), ("overlaps", "&&")], +) +def test_multirange_operators(multiranges, method, operator): + assert getattr(multiranges, method)(5).to_sql() == (f'"m" {operator} %s', (5,)) + + +@pytest.mark.parametrize("method", ["contains", "contained_by", "overlaps"]) +def test_multirange_operators_fail_without_the_capability(method): + from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresMultirangeColumn, + ) + + old = PostgresDialect(version=(9, 1, 0)) + column = PostgresMultirangeColumn(old, "m") + with pytest.raises(UnsupportedFeatureError, match="supports_multirange"): + getattr(column, method)(5) From 88aad4a5a825115206c6c7b505dd7f8546a93afa Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:51:35 +0800 Subject: [PATCH 32/81] feat(postgres): give the text-search column class match and rank matches (@@) and rank (ts_rank) wrap the existing text_search functions. Render assertions and a live tsvector round-trip on postgres-18.6 pass. --- .../backend/impl/postgres/column_types.py | 12 ++++++++++ .../construct/types/test_column_operations.py | 22 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 887e09d8..4bd78470 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -258,6 +258,18 @@ class PostgresTextSearchColumn(ColumnBase): models a text-search value, so this class starts from the column surface. """ + def matches(self, query) -> "BinaryExpression": + """``col @@ query``: does the vector match the query?""" + from .functions.text_search import ts_matches + + return ts_matches(self._dialect, self, query) + + def rank(self, query, weights=None) -> "FunctionCall": + """``ts_rank(col, query[, weights])``: the relevance of the match.""" + from .functions.text_search import ts_rank + + return ts_rank(self._dialect, self, query, weights) + @property def format_method(self) -> str: """The dialect formatting method that renders this column.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index 98b398f9..86e55543 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -208,3 +208,25 @@ def test_multirange_operators_fail_without_the_capability(method): column = PostgresMultirangeColumn(old, "m") with pytest.raises(UnsupportedFeatureError, match="supports_multirange"): getattr(column, method)(5) + + +# --------------------------------------------------------------------------- +# Text search: the match operator and ranking function +# --------------------------------------------------------------------------- + + +@pytest.fixture +def tsvector(dialect): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresTextSearchColumn, + ) + + return PostgresTextSearchColumn(dialect, "tv") + + +def test_text_search_matches(tsvector): + assert tsvector.matches("foo & bar").to_sql() == ('"tv" @@ %s', ("foo & bar",)) + + +def test_text_search_rank(tsvector): + assert tsvector.rank("foo").to_sql() == ('TS_RANK("tv", %s)', ("foo",)) From 8319a4c78fef64541531e62cb94d83a521ab7783 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:54:00 +0800 Subject: [PATCH 33/81] feat(postgres): give the vector column class its distance operators l2_distance (<->), cosine_distance (<=>) and inner_product (<#>) wrap the existing pgvector functions and are gated on supports_pgvector_similarity_search(). Live round-trip on postgres-exts-18 with the vector extension passes. cosine_similarity is deliberately not exposed: the existing vector_cosine_similarity() renders 1 - v <=> x without parentheses, and the server reads that as (1 - v) <=> x. That helper needs its own fix first. --- .../backend/impl/postgres/column_types.py | 21 ++++++++++ .../construct/types/test_column_operations.py | 41 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 4bd78470..739b0bfd 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -119,6 +119,27 @@ class PostgresVectorColumn(VectorColumn): class states only the shared column surface until they are measured. """ + def l2_distance(self, other) -> "BinaryExpression": + """``col <-> other``: Euclidean distance.""" + _require(self._dialect, "supports_pgvector_similarity_search") + from .functions.pgvector import vector_l2_distance + + return vector_l2_distance(self._dialect, self, other) + + def cosine_distance(self, other) -> "BinaryExpression": + """``col <=> other``: cosine distance.""" + _require(self._dialect, "supports_pgvector_similarity_search") + from .functions.pgvector import vector_cosine_distance + + return vector_cosine_distance(self._dialect, self, other) + + def inner_product(self, other) -> "BinaryExpression": + """``col <#> other``: negative inner product.""" + _require(self._dialect, "supports_pgvector_similarity_search") + from .functions.pgvector import vector_inner_product + + return vector_inner_product(self._dialect, self, other) + class PostgresRangeColumn(RangeColumn): """A column holding a native PostgreSQL range (``int4range``, ...). diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index 86e55543..2b03bb0b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -230,3 +230,44 @@ def test_text_search_matches(tsvector): def test_text_search_rank(tsvector): assert tsvector.rank("foo").to_sql() == ('TS_RANK("tv", %s)', ("foo",)) + + +# --------------------------------------------------------------------------- +# pgvector: distance operators, gated on the extension's capability +# --------------------------------------------------------------------------- + + +@pytest.fixture +def vectors(dialect, monkeypatch): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresVectorColumn, + ) + + monkeypatch.setattr(dialect, "supports_pgvector_similarity_search", lambda: True) + return PostgresVectorColumn(dialect, "v") + + +@pytest.mark.parametrize( + "method, operator", + [ + ("l2_distance", "<->"), + ("cosine_distance", "<=>"), + ("inner_product", "<#>"), + ], +) +def test_vector_distance_operators(vectors, method, operator): + sql, params = getattr(vectors, method)([1.0, 2.0]).to_sql() + assert sql == f'"v" {operator} %s::VECTOR(2)' + assert params == ("[1.0, 2.0]",) + + +@pytest.mark.parametrize("method", ["l2_distance", "cosine_distance", "inner_product"]) +def test_vector_ops_fail_when_the_extension_is_not_available(dialect, method): + from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresVectorColumn, + ) + + column = PostgresVectorColumn(dialect, "v") + with pytest.raises(UnsupportedFeatureError, match="supports_pgvector_similarity_search"): + getattr(column, method)([1.0, 2.0]) From 83531c3e31c79e984673a66eb456571e61fa6eb1 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:55:59 +0800 Subject: [PATCH 34/81] feat(postgres): give the hstore column class its key predicates exist (EXIST) and defined (DEFINED) wrap functions/hstore.py, gated on supports_hstore_operators(). Live hstore round-trip on postgres-exts-18 shows the NULL-valued key answers exist=True, defined=False as it should. --- .../backend/impl/postgres/column_types.py | 16 +++++++++ .../construct/types/test_column_operations.py | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 739b0bfd..538e74cd 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -317,6 +317,22 @@ class PostgresHstoreColumn(ColumnBase): class starts from the column surface. """ + def exist(self, key) -> "FunctionCall": + """``EXIST(col, key)``: whether the key is present, even with NULL.""" + _require(self._dialect, "supports_hstore_operators") + from rhosocial.activerecord.backend.expression import Literal + from .functions.hstore import hstore_exist + + return hstore_exist(self._dialect, self, Literal(self._dialect, key)) + + def defined(self, key) -> "FunctionCall": + """``DEFINED(col, key)``: whether the key is present and non-NULL.""" + _require(self._dialect, "supports_hstore_operators") + from rhosocial.activerecord.backend.expression import Literal + from .functions.hstore import hstore_defined + + return hstore_defined(self._dialect, self, Literal(self._dialect, key)) + @property def format_method(self) -> str: """The dialect formatting method that renders this column.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index 2b03bb0b..d8a8bbad 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -271,3 +271,37 @@ def test_vector_ops_fail_when_the_extension_is_not_available(dialect, method): column = PostgresVectorColumn(dialect, "v") with pytest.raises(UnsupportedFeatureError, match="supports_pgvector_similarity_search"): getattr(column, method)([1.0, 2.0]) + + +# --------------------------------------------------------------------------- +# hstore: key existence, gated on the extension's operators +# --------------------------------------------------------------------------- + + +@pytest.fixture +def hstore(dialect, monkeypatch): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresHstoreColumn, + ) + + monkeypatch.setattr(dialect, "supports_hstore_operators", lambda: True) + return PostgresHstoreColumn(dialect, "h") + + +@pytest.mark.parametrize("method, name", [("exist", "EXIST"), ("defined", "DEFINED")]) +def test_hstore_key_predicates(hstore, method, name): + sql, params = getattr(hstore, method)("k").to_sql() + assert sql == f'{name}("h", %s)' + assert params == ("k",) + + +@pytest.mark.parametrize("method", ["exist", "defined"]) +def test_hstore_ops_fail_when_the_extension_is_not_available(dialect, method): + from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgresHstoreColumn, + ) + + column = PostgresHstoreColumn(dialect, "h") + with pytest.raises(UnsupportedFeatureError, match="supports_hstore_operators"): + getattr(column, method)("k") From d5f579b3b9592a3840cbab5d8aa5f59e5d66a46a Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 04:58:37 +0800 Subject: [PATCH 35/81] feat(postgres): give the PostGIS wrapper its own ST_* column class PostgisGeometryColumn(PostgresGeometryColumn) carries ST_Distance/Contains/ Within/Intersects/Area/Length, each gated on supports_postgis_spatial_functions(). The extras table keys the PostGIS wrapper value class to it, so a plain Point field keeps only the built-in operators and a PostGIS field gets the extension's surface. Render assertions and a live round-trip on postgres-exts-18 with PostGIS 3.6 pass. --- .../backend/impl/postgres/column_types.py | 54 +++++++++++++++ .../impl/postgres/mixins/column_type.py | 3 +- .../construct/types/test_column_operations.py | 69 +++++++++++++++++++ .../types/test_column_type_suggestions.py | 2 +- 4 files changed, 126 insertions(+), 2 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 538e74cd..8fef24b7 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -112,6 +112,59 @@ def overlaps(self, other) -> "BinaryExpression": return geometry_overlaps(self._dialect, self, other) +class PostgisGeometryColumn(PostgresGeometryColumn): + """A ``geometry`` column backed by the PostGIS extension. + + The ``ST_*`` functions are an extension's surface, not the core server's, + so they live on this subclass and are gated on + ``supports_postgis_spatial_functions()``. A field annotated with the + PostGIS wrapper value class resolves here; a plain geometric type keeps + the built-in operators only. + """ + + def st_distance(self, other, use_spheroid: bool = False) -> "FunctionCall": + """``ST_Distance(col, other[, use_spheroid])``.""" + _require(self._dialect, "supports_postgis_spatial_functions") + from .functions.postgis import st_distance + + return st_distance(self._dialect, self, other, use_spheroid) + + def st_contains(self, other) -> "FunctionCall": + """``ST_Contains(col, other)``.""" + _require(self._dialect, "supports_postgis_spatial_functions") + from .functions.postgis import st_contains + + return st_contains(self._dialect, self, other) + + def st_within(self, other) -> "FunctionCall": + """``ST_Within(col, other)``.""" + _require(self._dialect, "supports_postgis_spatial_functions") + from .functions.postgis import st_within + + return st_within(self._dialect, self, other) + + def st_intersects(self, other) -> "FunctionCall": + """``ST_Intersects(col, other)``.""" + _require(self._dialect, "supports_postgis_spatial_functions") + from .functions.postgis import st_intersects + + return st_intersects(self._dialect, self, other) + + def st_area(self) -> "FunctionCall": + """``ST_Area(col)``.""" + _require(self._dialect, "supports_postgis_spatial_functions") + from .functions.postgis import st_area + + return st_area(self._dialect, self) + + def st_length(self) -> "FunctionCall": + """``ST_Length(col)``.""" + _require(self._dialect, "supports_postgis_spatial_functions") + from .functions.postgis import st_length + + return st_length(self._dialect, self) + + class PostgresVectorColumn(VectorColumn): """A column holding a pgvector value. @@ -384,6 +437,7 @@ def format_method(self) -> str: __all__ = [ "PostgresGeometryColumn", "PostgresAreaGeometryColumn", + "PostgisGeometryColumn", "PostgresVectorColumn", "PostgresRangeColumn", "PostgresMultirangeColumn", diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py index c5e66794..0228c462 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py @@ -88,6 +88,7 @@ from ..column_types import ( PostgresAreaGeometryColumn, PostgresBitStringColumn, + PostgisGeometryColumn, PostgresGeometryColumn, PostgresHstoreColumn, PostgresIdentifierColumn, @@ -256,7 +257,7 @@ #: ``UseColumnType`` once its adapter is in place. POSTGRES_EXTRA_COLUMN_TYPES: Dict[Any, Type[ColumnBase]] = { PostgresBitString: PostgresBitStringColumn, - PostgresGeometry: PostgresGeometryColumn, + PostgresGeometry: PostgisGeometryColumn, Point: PostgresGeometryColumn, Line: PostgresGeometryColumn, LineSegment: PostgresGeometryColumn, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index d8a8bbad..afb0d639 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -305,3 +305,72 @@ def test_hstore_ops_fail_when_the_extension_is_not_available(dialect, method): column = PostgresHstoreColumn(dialect, "h") with pytest.raises(UnsupportedFeatureError, match="supports_hstore_operators"): getattr(column, method)("k") + + +# --------------------------------------------------------------------------- +# PostGIS: ST_* on the wrapper's column class, gated on the extension +# --------------------------------------------------------------------------- + + +@pytest.fixture +def postgis(dialect, monkeypatch): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgisGeometryColumn, + ) + + monkeypatch.setattr(dialect, "supports_postgis_spatial_functions", lambda: True) + return PostgisGeometryColumn(dialect, "g") + + +@pytest.mark.parametrize( + "method, name", + [ + ("st_contains", "ST_CONTAINS"), + ("st_within", "ST_WITHIN"), + ("st_intersects", "ST_INTERSECTS"), + ("st_distance", "ST_DISTANCE"), + ], +) +def test_postgis_predicates_and_distance(postgis, dialect, method, name): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgisGeometryColumn, + ) + + other = PostgisGeometryColumn(dialect, "h") + sql, params = getattr(postgis, method)(other).to_sql() + assert sql == f'{name}("g", "h")' + assert params == () + + +@pytest.mark.parametrize("method, name", [("st_area", "ST_AREA"), ("st_length", "ST_LENGTH")]) +def test_postgis_measurements(postgis, method, name): + assert getattr(postgis, method)().to_sql() == (f'{name}("g")', ()) + + +@pytest.mark.parametrize( + "method", + ["st_distance", "st_contains", "st_within", "st_intersects", "st_area", "st_length"], +) +def test_postgis_ops_fail_without_the_extension(dialect, method): + from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgisGeometryColumn, + ) + + column = PostgisGeometryColumn(dialect, "g") + args = () if method in ("st_area", "st_length") else (column,) + with pytest.raises(UnsupportedFeatureError, match="supports_postgis_spatial_functions"): + getattr(column, method)(*args) + + +def test_the_postgis_wrapper_resolves_to_the_extension_class(dialect): + from rhosocial.activerecord.backend.impl.postgres.column_types import ( + PostgisGeometryColumn, + ) + from rhosocial.activerecord.backend.impl.postgres.type_values import ( + Point, + PostgresGeometry, + ) + + assert dialect.suggested_extra_column_types()[PostgresGeometry] is PostgisGeometryColumn + assert dialect.suggested_extra_column_types()[Point] is not PostgisGeometryColumn diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py index 43d0a735..18597231 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py @@ -320,7 +320,7 @@ def test_the_complex_families_are_named_by_this_backend(dialect): for column_class in dialect.suggested_extra_column_types().values(): assert column_class.__module__ == pg.__name__ - assert column_class.__name__.startswith("Postgres") + assert column_class.__name__.startswith(("Postgres", "Postgis")) def test_a_postgres_named_class_is_usable_through_use_column_type(dialect): From 9ba2f7ce7a67d81e97cbfd7ace52a275a7d322b5 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 05:21:36 +0800 Subject: [PATCH 36/81] fix(postgres): group the cosine-similarity distance before subtracting ArithmeticOperation only parenthesizes an ArithmeticOperation operand, so the BinaryExpression carrying <=> was rendered without parentheses: 1 - col <=> x, which PostgreSQL reads as (1 - col) <=> x and refuses. Wrap the rendered distance in a RawSQL node that keeps its bind parameters, giving 1 - (col <=> x), and assert the grouping at the factory and column levels. cosine_similarity is now exposed on PostgresVectorColumn again. Live check on postgres-exts-18 with pgvector returns 1.0 for an identical vector. --- .../activerecord/backend/impl/postgres/column_types.py | 8 ++++++++ .../backend/impl/postgres/functions/pgvector.py | 10 +++++++++- .../construct/functions/test_pgvector_functions.py | 4 ++++ .../backend/construct/types/test_column_operations.py | 10 +++++++++- 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py index 8fef24b7..12cab93d 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py @@ -43,6 +43,7 @@ if TYPE_CHECKING: # pragma: no cover from rhosocial.activerecord.backend.expression.operators import ( + ArithmeticOperation, BinaryExpression, UnaryExpression, ) @@ -193,6 +194,13 @@ def inner_product(self, other) -> "BinaryExpression": return vector_inner_product(self._dialect, self, other) + def cosine_similarity(self, other) -> "ArithmeticOperation": + """``1 - (col <=> other)``: cosine similarity.""" + _require(self._dialect, "supports_pgvector_similarity_search") + from .functions.pgvector import vector_cosine_similarity + + return vector_cosine_similarity(self._dialect, self, other) + class PostgresRangeColumn(RangeColumn): """A column holding a native PostgreSQL range (``int4range``, ...). diff --git a/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py b/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py index 780340cb..0638ec21 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py @@ -27,6 +27,7 @@ from rhosocial.activerecord.backend.expression.operators import ( ArithmeticOperation, BinaryExpression, + RawSQL, ) from rhosocial.activerecord.backend.impl.postgres.type_values.pgvector import PostgresVector from rhosocial.activerecord.backend.impl.postgres.expression.types import ( @@ -290,8 +291,15 @@ def vector_cosine_similarity( >>> expr = vector_cosine_similarity(d, "embedding", [1.0, 2.0, 3.0]) """ cosine_dist = vector_cosine_distance(dialect, column, query_vector) + # ``ArithmeticOperation`` only parenthesizes an ``ArithmeticOperation`` + # operand; a ``BinaryExpression`` carrying ``<=>`` is not one, so without + # this wrapper it renders ``1 - col <=> x`` and the server reads that as + # ``(1 - col) <=> x``. The text is ours (a rendered expression, never user + # input) and the bind parameters are carried through unchanged. + dist_sql, dist_params = cosine_dist.to_sql() + grouped_dist = RawSQL(dialect, f"({dist_sql})", dist_params) one = core.Literal(dialect, 1) - return ArithmeticOperation(dialect, "sub", one, cosine_dist) + return ArithmeticOperation(dialect, "sub", one, grouped_dist) # === Type Construction === diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py index f14f3204..3e169b17 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py @@ -82,6 +82,10 @@ def test_vector_cosine_similarity(self, postgres_dialect: PostgresDialect): sql, params = result.to_sql() assert "-" in sql assert "<=>" in sql + # The distance must be grouped: without the parentheses the server + # reads ``1 - col <=> x`` as ``(1 - col) <=> x`` and refuses it. + assert " - (" in sql + assert "<=>" in sql class TestPgvectorLiteralFunction: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py index afb0d639..46a67979 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py @@ -261,7 +261,15 @@ def test_vector_distance_operators(vectors, method, operator): assert params == ("[1.0, 2.0]",) -@pytest.mark.parametrize("method", ["l2_distance", "cosine_distance", "inner_product"]) +def test_vector_cosine_similarity(vectors): + sql, params = vectors.cosine_similarity([1.0, 2.0]).to_sql() + assert sql == '%s - ("v" <=> %s::VECTOR(2))' + assert params == (1, "[1.0, 2.0]") + + +@pytest.mark.parametrize( + "method", ["l2_distance", "cosine_distance", "inner_product", "cosine_similarity"] +) def test_vector_ops_fail_when_the_extension_is_not_available(dialect, method): from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError from rhosocial.activerecord.backend.impl.postgres.column_types import ( From 473c0b0f874dd83e51cc2b1b185a38e41b91db74 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 05:52:43 +0800 Subject: [PATCH 37/81] test(backend): hold the data-type trio to the D9 and substitute contracts The contract lives in this repository, not in the shared testsuite: backend functionality is tested by its own backend. Core concepts are discovered rather than listed, so a future concept cannot slip past a stale list. For each declared version the tests assert that every concept is either rendered or substituted, that substitute keys are disjoint from rendered keys, that values are DataType subclasses, and that each substitute actually renders (parameter-carrying substitutes use a documented minimum instance). --- ...st_postgres_data_type_protocol_contract.py | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py new file mode 100644 index 00000000..dd946f0c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py @@ -0,0 +1,80 @@ +# tests/.../test_postgres_data_type_protocol_contract.py +"""This backend's own data-type protocol contract (D9 + substitutes). + +Backend functionality is tested here, in this repository: nothing in this file +belongs in the shared testsuite. Core concepts are discovered, not listed, so a +concept added to core later cannot slip past a stale list. +""" + +import pytest + +from rhosocial.activerecord.backend.expression.types import DataType +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect + +#: Versions spanning the gates this backend declares. +VERSIONS = [(9, 1, 0), (16, 0, 0)] + + +def _dialect(version): + return PostgresDialect(version=version) + + +def _core_concepts(): + seen = set() + stack = [DataType] + while stack: + klass = stack.pop() + if klass in seen: + continue + seen.add(klass) + stack.extend(klass.__subclasses__()) + return sorted( + { + klass.name + for klass in seen + if klass is not DataType + and klass.__module__.startswith("rhosocial.activerecord.backend.expression.types") + and klass.name + } + ) + + +def _renderable_substitute(dialect, klass): + """Minimum valid construction for substitutes that carry parameters. + + These three cannot be built with no arguments; the values are chosen only + to exercise rendering, not to stand for any real column. + """ + if klass.__name__ == "PostgresEnumColumnType": + return klass(dialect, type_name="status", values=["a", "b"]) + if klass.__name__ == "MySQLVarBinaryType": + return klass(dialect, length=16) + if klass.__name__ == "CustomType": + return klass(dialect, raw="ARRAY") + return klass(dialect) + + +@pytest.mark.parametrize("version", VERSIONS) +def test_every_core_concept_is_declared(version): + """D9: rendered or substituted -- silence is not an answer.""" + dialect = _dialect(version) + supported = set(dialect.supports_data_types()) + substitutes = dialect.substitute_data_types() + undeclared = [ + name for name in _core_concepts() if name not in supported and name not in substitutes + ] + assert not undeclared, f"{version}: {undeclared} are neither rendered nor substituted" + + +@pytest.mark.parametrize("version", VERSIONS) +def test_substitutes_are_disjoint_and_renderable(version): + """A substitute must be a DataType class this dialect really writes.""" + dialect = _dialect(version) + supported = set(dialect.supports_data_types()) + substitutes = dialect.substitute_data_types() + assert not supported & set(substitutes) + + for key, klass in substitutes.items(): + assert isinstance(klass, type) and issubclass(klass, DataType), key + sql, _ = dialect.format_data_type(_renderable_substitute(dialect, klass)) + assert sql, f"{version}: {key} -> {klass.__name__} renders nothing" From c037f1d8498dd89e9a724bf6cdfe0feacd226db5 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Tue, 17 Nov 2026 05:57:31 +0800 Subject: [PATCH 38/81] test(backend): hold formatters and probes to the 1:1 discipline D10: every format_data_type_ has a supports_data_type_ probe and vice versa, supports_data_types() names only formatter-bearing concepts, and a formatter missing from the supported map must be explained by an explicit False probe (a version gate), never by silence. The contract lives in this repository; backend functionality is not tested in the shared testsuite. --- ...st_postgres_data_type_protocol_contract.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py index dd946f0c..308d622a 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py @@ -78,3 +78,35 @@ def test_substitutes_are_disjoint_and_renderable(version): assert isinstance(klass, type) and issubclass(klass, DataType), key sql, _ = dialect.format_data_type(_renderable_substitute(dialect, klass)) assert sql, f"{version}: {key} -> {klass.__name__} renders nothing" + + +@pytest.mark.parametrize("version", VERSIONS) +def test_formatter_and_probe_families_are_one_to_one(version): + """D10: a formatter has a probe, and an absent answer is an explicit probe. + + ``supports_data_types()`` may omit a version-gated concept; that is an + answer only when its probe says False. A formatter with no probe at all, + or a supported key with no formatter, breaks the 1:1 discipline. + """ + dialect = _dialect(version) + format_names = { + member[len("format_data_type_") :] + for member in dir(dialect) + if member.startswith("format_data_type_") + } + probe_names = { + member[len("supports_data_type_") :] + for member in dir(dialect) + if member.startswith("supports_data_type_") + } + assert format_names, "the dialect must implement a format_data_type_* family" + assert format_names == probe_names, ( + f"format-only: {sorted(format_names - probe_names)}, " + f"probe-only: {sorted(probe_names - format_names)}" + ) + + supported = set(dialect.supports_data_types()) + assert supported <= format_names + for name in sorted(format_names - supported): + probe = getattr(dialect, f"supports_data_type_{name}") + assert probe() is False, f"{name} has a formatter but no False probe explains its absence" From dc2dd170f481c94ada930df11621bcb82b727810 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 01:57:13 +0800 Subject: [PATCH 39/81] test(basic): import the shared type-variant groups Bridge types, types_complex and types_long_content so the bare/annotated contracts run against this backend. --- .../feature/basic/types/conftest.py | 4 ++++ .../feature/basic/types/test_type_variants.py | 9 +++++++++ .../feature/basic/types/test_type_variants_async.py | 9 +++++++++ .../feature/basic/types_complex/conftest.py | 4 ++++ .../feature/basic/types_complex/test_complex_variants.py | 9 +++++++++ .../basic/types_complex/test_complex_variants_async.py | 9 +++++++++ .../feature/basic/types_long_content/conftest.py | 4 ++++ .../basic/types_long_content/test_long_content.py | 9 +++++++++ .../basic/types_long_content/test_long_content_async.py | 9 +++++++++ 9 files changed, 66 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py new file mode 100644 index 00000000..dc28256c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py +"""Use the shared ``basic/types`` test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.types.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py new file mode 100644 index 00000000..099a7b6a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py +"""Bridge for the shared ``basic/types`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this file +only makes its tests discoverable in this backend's test run. Do not +remove the star import -- it is the discovery mechanism. +""" + +from rhosocial.activerecord.testsuite.feature.basic.types.test_type_variants import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py new file mode 100644 index 00000000..9314f5aa --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py +"""Bridge for the shared ``basic/types`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this file +only makes its tests discoverable in this backend's test run. Do not +remove the star import -- it is the discovery mechanism. +""" + +from rhosocial.activerecord.testsuite.feature.basic.types.test_type_variants_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py new file mode 100644 index 00000000..e97b4a54 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py +"""Use the shared ``basic/types_complex`` test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.types_complex.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py new file mode 100644 index 00000000..66eca43b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py +"""Bridge for the shared ``basic/types_complex`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this file +only makes its tests discoverable in this backend's test run. Do not +remove the star import -- it is the discovery mechanism. +""" + +from rhosocial.activerecord.testsuite.feature.basic.types_complex.test_complex_variants import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py new file mode 100644 index 00000000..3981f7b7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py +"""Bridge for the shared ``basic/types_complex`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this file +only makes its tests discoverable in this backend's test run. Do not +remove the star import -- it is the discovery mechanism. +""" + +from rhosocial.activerecord.testsuite.feature.basic.types_complex.test_complex_variants_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py new file mode 100644 index 00000000..f0c89920 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py +"""Use the shared ``basic/types_long_content`` test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.types_long_content.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py new file mode 100644 index 00000000..9ca9373e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py +"""Bridge for the shared ``basic/types_long_content`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this file +only makes its tests discoverable in this backend's test run. Do not +remove the star import -- it is the discovery mechanism. +""" + +from rhosocial.activerecord.testsuite.feature.basic.types_long_content.test_long_content import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py new file mode 100644 index 00000000..a0a6d0f6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py +"""Bridge for the shared ``basic/types_long_content`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this file +only makes its tests discoverable in this backend's test run. Do not +remove the star import -- it is the discovery mechanism. +""" + +from rhosocial.activerecord.testsuite.feature.basic.types_long_content.test_long_content_async import * # noqa: F401,F403 From 64d3848b27848fd25ccc7c8564981370371fb7fc Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 02:41:59 +0800 Subject: [PATCH 40/81] test(basic): import the DB-free expressions group Bridge the shared X1-X6 field-expression contracts so they run against this backend. --- .../feature/basic/expressions/conftest.py | 4 ++++ .../feature/basic/expressions/test_expressions.py | 8 ++++++++ .../feature/basic/expressions/test_expressions_async.py | 8 ++++++++ 3 files changed, 20 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py new file mode 100644 index 00000000..9c50169d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py +"""Use the shared ``basic/expressions`` DB-free test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.expressions.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py new file mode 100644 index 00000000..f39c4838 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py @@ -0,0 +1,8 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py +"""Bridge for the shared ``basic/expressions`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this +file only makes its tests discoverable in this backend's test run. +""" + +from rhosocial.activerecord.testsuite.feature.basic.expressions.test_expressions import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py new file mode 100644 index 00000000..ef5f0196 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py @@ -0,0 +1,8 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py +"""Bridge for the shared ``basic/expressions`` test module. + +The test logic lives in ``rhosocial-activerecord-testsuite``; this +file only makes its tests discoverable in this backend's test run. +""" + +from rhosocial.activerecord.testsuite.feature.basic.expressions.test_expressions_async import * # noqa: F401,F403 From c96b9db182a73bece97c9c7edbfeba06c53091d9 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 02:51:24 +0800 Subject: [PATCH 41/81] test(basic): drop bridges for removed legacy field tests The shared testsuite deleted test_fields{,_async} along with the TypeCase/TypeTestModel fixtures. --- .../feature/basic/fields/test_fields.py | 23 ------------------- .../feature/basic/fields/test_fields_async.py | 5 ---- 2 files changed, 28 deletions(-) delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py deleted file mode 100644 index 4e26c104..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py +++ /dev/null @@ -1,23 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/test_fields.py -""" -Basic Fields Test Module for postgres backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring postgres backend compatibility. -""" -# IMPORTANT: These imports are essential for pytest to work correctly. -# Even though they may be flagged as "unused" by some IDEs or linters, -# they must not be removed. They are the mechanism by which pytest discovers -# the fixtures and the tests from the external testsuite package. - -# Although the root conftest.py sets up the environment, explicitly importing -# the fixtures here makes the dependency clear and can help with test discovery -# in some IDEs. These fixtures are defined in the testsuite package and are -# parameterized to run against the scenarios defined in `providers/scenarios.py`. -from rhosocial.activerecord.testsuite.feature.basic.conftest import ( - type_test_model, # noqa: F401 - async_type_test_model # noqa: F401 -) - -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py deleted file mode 100644 index c3c18ffe..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py -"""Bridge file for async feature.basic.fields.test_fields_async tests.""" -from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F403 From 713a967e388f9906a9ed0d925e30673001bc6ba2 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 03:06:31 +0800 Subject: [PATCH 42/81] test: keep only feature/basic imports from testsuite Cancel all non-basic testsuite feature test bridges; backend-owned tests and benchmark imports stay. --- .../feature/adapters/conftest.py | 4 - .../feature/adapters/test_json_codec.py | 3 - .../feature/adapters/test_neutral_types.py | 3 - .../adapters/test_neutral_types_async.py | 3 - .../errors/test_error_taxonomy_contract.py | 9 - .../feature/cli/conftest.py | 3 - .../feature/cli/test_cli_bulk.py | 1 - .../feature/cli/test_cli_bulk_async.py | 1 - .../feature/cli/test_cli_dml.py | 1 - .../feature/cli/test_cli_dml_async.py | 1 - .../feature/cli/test_cli_dql.py | 1 - .../feature/cli/test_cli_dql_async.py | 1 - .../feature/cli/test_cli_read_only.py | 1 - .../feature/cli/test_cli_read_only_async.py | 1 - .../feature/cli/test_cli_set_cte.py | 1 - .../feature/cli/test_cli_set_cte_async.py | 1 - .../feature/cli/test_cli_soft_delete.py | 1 - .../feature/cli/test_cli_soft_delete_async.py | 1 - .../feature/cli/test_cli_validation.py | 1 - .../feature/cli/test_cli_validation_async.py | 1 - .../feature/events/conftest.py | 3 - .../feature/events/core/conftest.py | 2 - .../feature/events/core/test_handlers.py | 9 - .../events/core/test_handlers_async.py | 5 - .../feature/events/core/test_lifecycle.py | 9 - .../events/core/test_lifecycle_async.py | 5 - .../feature/events/fixtures/models.py | 58 --- .../feature/events/fixtures/models_py310.py | 69 --- .../feature/events/fixtures/models_py311.py | 88 ---- .../feature/events/fixtures/models_py312.py | 89 ---- .../events/schema/event_test_models.sql | 20 - .../feature/events/schema/event_tests.sql | 11 - .../events/schema/event_tracking_models.sql | 9 - .../feature/interface/conftest.py | 8 - .../feature/interface/test_threadsafe_dict.py | 6 - .../interface/test_threadsafe_dict_async.py | 5 - .../feature/mixins/conftest.py | 3 - .../feature/mixins/core/conftest.py | 2 - .../mixins/core/test_combined_articles.py | 9 - .../core/test_combined_articles_async.py | 5 - .../mixins/core/test_optimistic_lock.py | 9 - .../mixins/core/test_optimistic_lock_async.py | 5 - .../feature/mixins/core/test_soft_delete.py | 9 - .../mixins/core/test_soft_delete_async.py | 5 - .../feature/mixins/core/test_timestamps.py | 9 - .../mixins/core/test_timestamps_async.py | 5 - .../feature/mixins/fixtures/models.py | 61 --- .../feature/mixins/fixtures/models_py310.py | 76 ---- .../feature/mixins/fixtures/models_py311.py | 109 ----- .../feature/mixins/fixtures/models_py312.py | 134 ------ .../feature/mixins/interfaces.py | 67 --- .../feature/mixins/schema/articles.sql | 12 - .../mixins/schema/combined_articles.sql | 12 - .../feature/mixins/schema/comments.sql | 12 - .../schema/optimistic_lock_test_models.sql | 8 - .../mixins/schema/soft_delete_test_models.sql | 8 - .../feature/mixins/schema/tasks.sql | 8 - .../mixins/schema/timestamped_posts.sql | 9 - .../mixins/schema/timestamps_test_models.sql | 9 - .../mixins/schema/versioned_products.sql | 8 - .../feature/query/aggregate/conftest.py | 4 - .../aggregate/test_active_query_aggregate.py | 8 - .../test_active_query_aggregate_async.py | 5 - .../query/aggregate/test_aggregate_queries.py | 8 - .../aggregate/test_aggregate_queries_async.py | 5 - .../feature/query/basic/conftest.py | 4 - .../query/basic/test_active_query_basic.py | 8 - .../basic/test_active_query_basic_async.py | 5 - .../feature/query/basic/test_basic.py | 8 - .../feature/query/basic/test_basic_async.py | 5 - .../query/basic/test_composite_pk_query.py | 5 - .../basic/test_composite_pk_query_async.py | 5 - .../query/basic/test_find_one_or_create.py | 3 - .../basic/test_find_one_or_create_async.py | 1 - .../feature/query/basic/test_queries.py | 8 - .../feature/query/basic/test_queries_async.py | 9 - .../feature/query/connection/conftest.py | 9 - .../connection/test_active_query_context.py | 14 - .../test_active_query_context_async.py | 5 - .../connection/test_cte_query_context.py | 14 - .../test_cte_query_context_async.py | 5 - .../connection/test_set_operation_context.py | 14 - .../test_set_operation_context_async.py | 5 - .../feature/query/cross_database/conftest.py | 4 - .../test_cross_database_compatibility.py | 8 - ...test_cross_database_compatibility_async.py | 5 - .../feature/query/cte/conftest.py | 4 - .../query/cte/test_composite_pk_cte.py | 5 - .../query/cte/test_composite_pk_cte_async.py | 5 - .../query/cte/test_cte_query_active_query.py | 8 - .../cte/test_cte_query_active_query_async.py | 5 - .../query/cte/test_cte_query_set_operation.py | 8 - .../cte/test_cte_query_set_operation_async.py | 5 - .../feature/query/eager_loading/conftest.py | 4 - .../test_eager_loading_caching.py | 5 - .../test_eager_loading_caching_async.py | 5 - .../test_eager_loading_nested.py | 5 - .../test_eager_loading_nested_async.py | 5 - .../test_eager_loading_scenarios.py | 2 - .../test_eager_loading_scenarios_async.py | 5 - .../test_eager_loading_with_all.py | 5 - .../test_eager_loading_with_all_async.py | 5 - .../test_eager_loading_with_modifier.py | 5 - .../test_eager_loading_with_modifier_async.py | 5 - .../test_eager_loading_with_one.py | 5 - .../test_eager_loading_with_one_async.py | 5 - .../feature/query/error_handling/conftest.py | 4 - .../error_handling/test_error_handling.py | 8 - .../test_error_handling_async.py | 5 - .../feature/query/joins/conftest.py | 4 - .../query/joins/test_active_query_join.py | 8 - .../joins/test_active_query_join_async.py | 5 - .../feature/query/joins/test_joins.py | 8 - .../feature/query/joins/test_joins_async.py | 5 - .../feature/query/logging/conftest.py | 4 - .../test_logging_data_summarization.py | 8 - .../test_logging_data_summarization_async.py | 5 - .../feature/query/optimization/conftest.py | 4 - .../optimization/test_query_optimization.py | 8 - .../test_query_optimization_async.py | 5 - .../feature/query/range_queries/conftest.py | 4 - .../range_queries/test_active_query_range.py | 8 - .../test_active_query_range_async.py | 5 - .../query/range_queries/test_range_queries.py | 8 - .../range_queries/test_range_queries_async.py | 5 - .../test_range_query_detailed.py | 8 - .../test_range_query_detailed_async.py | 5 - .../feature/query/relations/conftest.py | 4 - .../relations/test_relational_validation.py | 8 - .../test_relational_validation_async.py | 5 - .../query/relations/test_relations_basic.py | 8 - .../relations/test_relations_basic_async.py | 5 - .../query/relations/test_relations_with.py | 5 - .../relations/test_relations_with_async.py | 5 - .../feature/query/schema/comments.sql | 11 - .../query/schema/extended_order_items.sql | 13 - .../feature/query/schema/extended_orders.sql | 18 - .../feature/query/schema/json_users.sql | 18 - .../feature/query/schema/nodes.sql | 10 - .../feature/query/schema/order_items.sql | 12 - .../feature/query/schema/orders.sql | 11 - .../feature/query/schema/posts.sql | 11 - .../feature/query/schema/profiles.sql | 10 - .../feature/query/schema/searchable_items.sql | 9 - .../feature/query/schema/users.sql | 12 - .../feature/query/set_operations/conftest.py | 4 - .../test_active_query_set_operation.py | 8 - .../test_active_query_set_operation_async.py | 5 - .../test_composite_pk_set_operation.py | 5 - .../test_composite_pk_set_operation_async.py | 5 - .../set_operations/test_set_operation.py | 8 - .../test_set_operation_async.py | 5 - .../feature/query/special/conftest.py | 4 - .../special/test_example_query_fixtures.py | 8 - .../test_example_query_fixtures_async.py | 5 - .../query/special/test_special_queries.py | 8 - .../special/test_special_queries_async.py | 5 - .../feature/query/typed_column/conftest.py | 4 - .../typed_column/test_protocol_guarantees.py | 2 - .../test_seconds_between_contract.py | 2 - .../query/window_functions/conftest.py | 4 - .../window_functions/test_window_functions.py | 8 - .../test_window_functions_async.py | 5 - .../feature/query/worker/conftest.py | 9 - .../query/worker/test_parallel_queries.py | 11 - .../worker/test_parallel_queries_async.py | 5 - ...test_query_worker_transaction_isolation.py | 7 - .../test_transaction_isolation_async.py | 3 - .../feature/relation/base/conftest.py | 2 - .../feature/relation/base/test_base.py | 5 - .../feature/relation/base/test_base_async.py | 1 - .../feature/relation/base/test_interfaces.py | 5 - .../relation/base/test_interfaces_async.py | 1 - .../feature/relation/boundary/conftest.py | 3 - .../relation/boundary/test_boundary.py | 1 - .../relation/boundary/test_boundary_async.py | 3 - .../feature/relation/cache/conftest.py | 2 - .../feature/relation/cache/test_cache.py | 14 - .../relation/cache/test_cache_async.py | 1 - .../relation/cache/test_cache_clearing.py | 1 - .../cache/test_cache_clearing_async.py | 5 - .../feature/relation/conftest.py | 7 - .../feature/relation/derived/conftest.py | 3 - .../derived/test_derived_field_json.py | 1 - .../derived/test_derived_field_json_async.py | 3 - .../derived/test_relation_derived_field.py | 3 - .../test_relation_derived_field_async.py | 3 - .../feature/relation/descriptors/conftest.py | 2 - .../descriptors/test_descriptor_compat.py | 3 - .../test_descriptor_compat_async.py | 5 - .../relation/descriptors/test_descriptors.py | 5 - .../descriptors/test_descriptors_async.py | 3 - .../relation/eager_loading/conftest.py | 3 - .../test_nested_relationship_access.py | 5 - .../test_nested_relationship_access_async.py | 1 - .../eager_loading/test_with_method.py | 1 - .../eager_loading/test_with_method_async.py | 3 - .../feature/relation/fixtures/models.py | 420 ------------------ .../feature/relation/fixtures/models_py310.py | 144 ------ .../feature/relation/fixtures/models_py311.py | 177 -------- .../feature/relation/fixtures/models_py312.py | 214 --------- .../feature/relation/integration/conftest.py | 3 - .../relation/integration/test_integration.py | 1 - .../integration/test_integration_async.py | 3 - .../feature/relation/modifiers/conftest.py | 3 - .../modifiers/test_modifier_behavior.py | 1 - .../modifiers/test_modifier_behavior_async.py | 3 - .../modifiers/test_modifier_warning.py | 1 - .../modifiers/test_modifier_warning_async.py | 3 - .../feature/relation/ordering/conftest.py | 3 - .../ordering/test_has_many_order_by.py | 3 - .../ordering/test_has_many_order_by_async.py | 1 - .../feature/relation/validation/conftest.py | 3 - .../validation/test_path_validation.py | 1 - .../validation/test_path_validation_async.py | 3 - .../relation/validation/test_validator.py | 3 - .../validation/test_validator_async.py | 5 - 217 files changed, 2823 deletions(-) delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py deleted file mode 100644 index f28fe7b2..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py - -"""Use the shared ``feature/adapters`` directory contract.""" -from rhosocial.activerecord.testsuite.feature.adapters.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py deleted file mode 100644 index c79f4a67..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py -"""Bridge file: runs the shared testsuite neutral-type contract.""" -from rhosocial.activerecord.testsuite.feature.adapters.test_json_codec import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py deleted file mode 100644 index b9fa5525..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py -"""Bridge file: runs the shared testsuite neutral-type contract.""" -from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py deleted file mode 100644 index 51ef35f3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py -"""Bridge file: runs the shared testsuite neutral-type contract.""" -from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py deleted file mode 100644 index 20f108ac..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_error_taxonomy_contract.py -"""Run the shared error taxonomy contract against this backend. - -The testsuite module imports only the core taxonomy, so no PostgreSQL -connection is needed. Importing the module is the whole wrapper: pytest -collects the classes and methods it defines. -""" - -from rhosocial.activerecord.testsuite.feature.backend.errors.test_error_taxonomy import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py deleted file mode 100644 index f9f2379d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py -"""Use the shared ``cli`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.cli.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py deleted file mode 100644 index 508723af..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py deleted file mode 100644 index 93522c88..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py deleted file mode 100644 index daf79d05..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py deleted file mode 100644 index 43214f10..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py deleted file mode 100644 index df9f8d98..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py deleted file mode 100644 index 1a0e1d77..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py deleted file mode 100644 index 7b9befb3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py deleted file mode 100644 index d8668b1c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py deleted file mode 100644 index 253caa54..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py deleted file mode 100644 index b60ecaff..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py deleted file mode 100644 index 5fe311b2..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py deleted file mode 100644 index 21ef6585..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py deleted file mode 100644 index aa055ff4..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py deleted file mode 100644 index 28c97f34..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py deleted file mode 100644 index ef1b83db..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py -"""Use the shared ``events`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.events.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py deleted file mode 100644 index 3b1a4e11..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/core/conftest.py -from rhosocial.activerecord_postgres_test.feature.events.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py deleted file mode 100644 index e86f1d11..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py -""" -Event Handler Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.events.core.test_handlers import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py deleted file mode 100644 index 742aed66..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_handlers_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py -"""Bridge file for async feature.events.test_handlers_async tests.""" -from rhosocial.activerecord.testsuite.feature.events.core.test_handlers_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.events.core.test_handlers_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py deleted file mode 100644 index 177f2eff..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py -""" -Event Lifecycle Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.events.core.test_lifecycle import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py deleted file mode 100644 index 57dd58fd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/core/test_lifecycle_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py -"""Bridge file for async feature.events.test_lifecycle_async tests.""" -from rhosocial.activerecord.testsuite.feature.events.core.test_lifecycle_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.events.core.test_lifecycle_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py deleted file mode 100644 index 7c6d3a30..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py +++ /dev/null @@ -1,58 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py -""" -This file defines the generic ActiveRecord model classes used by the events tests. - -These models are "generic" because they define the data structure and validation -rules (using Pydantic), but they are not tied to any specific database backend. -The backend-specific provider is responsible for taking these classes and -configuring them with a live database connection at test time. -""" -from typing import Optional, Dict, List, Tuple -from datetime import datetime - -from pydantic import Field - -from rhosocial.activerecord.interface import ModelEvent -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin - - -class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord): - """A model class for testing event mechanisms""" - @classmethod - def table_name(cls): - return "event_tests" - - id: Optional[int] = None - name: str - status: str = Field(default="draft") - revision: int = Field(default=1) - content: Optional[str] = None - - def __init__(self, **data): - super().__init__(**data) - self._event_logs = [] # Used to record event triggering history - - def log_event(self, event: ModelEvent, **kwargs): - """Record the trigger history of events""" - self._event_logs.append((event, kwargs)) - - def get_event_logs(self) -> List[Tuple[ModelEvent, Dict]]: - """Get the event history""" - return self._event_logs.copy() - - def clear_event_logs(self): - """Empty the history of events""" - self._event_logs.clear() - - -class EventTrackingModel(IntegerPKMixin, ActiveRecord): - """A model for testing event tracking functionality.""" - @classmethod - def table_name(cls): - return "event_tracking_models" - - title: str - content: str - view_count: int = 0 - last_viewed_at: Optional[datetime] = None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py deleted file mode 100644 index bd3ee5e0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py +++ /dev/null @@ -1,69 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/events/fixtures/models_py310.py -""" -Python 3.10+ fixture model definitions for events tests. - -This file contains model classes using Python 3.10+ syntax features: -- `X | Y` syntax instead of `Optional[X]` or `Union[X, Y]` -- `Type | None` instead of `Optional[Type]` - -Note: This file should only be imported and used in Python 3.10+ environments. -""" -from typing import Dict -from datetime import datetime - -from pydantic import Field - -from rhosocial.activerecord.interface import ModelEvent -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin - - -# Declare that this module requires Python 3.10+ -__requires_python__ = (3, 10) - - -class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord): - """A model class for testing event mechanisms. - - Python 3.10+ version using | syntax instead of Optional. - """ - @classmethod - def table_name(cls): - return "event_tests" - - id: int | None = None - name: str - status: str = Field(default="draft") - revision: int = Field(default=1) - content: str | None = None - - def __init__(self, **data): - super().__init__(**data) - self._event_logs: list[tuple[ModelEvent, Dict]] = [] # Used to record event triggering history - - def log_event(self, event: ModelEvent, **kwargs): - """Record the trigger history of events""" - self._event_logs.append((event, kwargs)) - - def get_event_logs(self) -> list[tuple[ModelEvent, Dict]]: - """Get the event history""" - return self._event_logs.copy() - - def clear_event_logs(self): - """Empty the history of events""" - self._event_logs.clear() - - -class EventTrackingModel(IntegerPKMixin, ActiveRecord): - """A model for testing event tracking functionality. - - Python 3.10+ version using | syntax instead of Optional. - """ - @classmethod - def table_name(cls): - return "event_tracking_models" - - title: str - content: str - view_count: int = 0 - last_viewed_at: datetime | None = None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py deleted file mode 100644 index 786f4f32..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py +++ /dev/null @@ -1,88 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/events/fixtures/models_py311.py -""" -Python 3.11+ fixture model definitions for events tests. - -This file contains model classes using Python 3.11+ syntax features: -- `Self` type for methods that return an instance of the same class -- `X | Y` syntax (inherited from 3.10+) - -Note: This file should only be imported and used in Python 3.11+ environments. -""" -from __future__ import annotations - -from typing import Dict, Self -from datetime import datetime - -from pydantic import Field - -from rhosocial.activerecord.interface import ModelEvent -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin - - -# Declare that this module requires Python 3.11+ -__requires_python__ = (3, 11) - - -class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord): - """A model class for testing event mechanisms. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "event_tests" - - id: int | None = None - name: str - status: str = Field(default="draft") - revision: int = Field(default=1) - content: str | None = None - - def __init__(self, **data): - super().__init__(**data) - self._event_logs: list[tuple[ModelEvent, Dict]] = [] # Used to record event triggering history - - def log_event(self, event: ModelEvent, **kwargs): - """Record the trigger history of events""" - self._event_logs.append((event, kwargs)) - - def get_event_logs(self) -> list[tuple[ModelEvent, Dict]]: - """Get the event history""" - return self._event_logs.copy() - - def clear_event_logs(self) -> Self: - """Empty the history of events and return self for chaining.""" - self._event_logs.clear() - return self - - def set_status(self, new_status: str) -> Self: - """Set status and return self for chaining.""" - self.status = new_status - return self - - def increment_revision(self) -> Self: - """Increment revision and return self for chaining.""" - self.revision += 1 - return self - - -class EventTrackingModel(IntegerPKMixin, ActiveRecord): - """A model for testing event tracking functionality. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "event_tracking_models" - - title: str - content: str - view_count: int = 0 - last_viewed_at: datetime | None = None - - def record_view(self) -> Self: - """Record a view and return self for chaining.""" - self.view_count += 1 - self.last_viewed_at = datetime.now() - return self diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py deleted file mode 100644 index 9196e1a0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py +++ /dev/null @@ -1,89 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/events/fixtures/models_py312.py -""" -Python 3.12+ fixture model definitions for events tests. - -This file contains model classes using Python 3.12+ syntax features: -- `@override` decorator for inheritance safety -- `Self` type for methods that return an instance of the same class -- `X | Y` syntax (inherited from 3.10+) - -Note: This file should only be imported and used in Python 3.12+ environments. -""" -from __future__ import annotations - -from typing import Dict, Self -from datetime import datetime - -from pydantic import Field - -from rhosocial.activerecord.interface import ModelEvent -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin - - -# Declare that this module requires Python 3.12+ -__requires_python__ = (3, 12) - - -class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord): - """A model class for testing event mechanisms. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "event_tests" - - id: int | None = None - name: str - status: str = Field(default="draft") - revision: int = Field(default=1) - content: str | None = None - - def __init__(self, **data): - super().__init__(**data) - self._event_logs: list[tuple[ModelEvent, Dict]] = [] # Used to record event triggering history - - def log_event(self, event: ModelEvent, **kwargs): - """Record the trigger history of events""" - self._event_logs.append((event, kwargs)) - - def get_event_logs(self) -> list[tuple[ModelEvent, Dict]]: - """Get the event history""" - return self._event_logs.copy() - - def clear_event_logs(self) -> Self: - """Empty the history of events and return self for chaining.""" - self._event_logs.clear() - return self - - def set_status(self, new_status: str) -> Self: - """Set status and return self for chaining.""" - self.status = new_status - return self - - def increment_revision(self) -> Self: - """Increment revision and return self for chaining.""" - self.revision += 1 - return self - - -class EventTrackingModel(IntegerPKMixin, ActiveRecord): - """A model for testing event tracking functionality. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "event_tracking_models" - - title: str - content: str - view_count: int = 0 - last_viewed_at: datetime | None = None - - def record_view(self) -> Self: - """Record a view and return self for chaining.""" - self.view_count += 1 - self.last_viewed_at = datetime.now() - return self diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql deleted file mode 100644 index 010b55f6..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql +++ /dev/null @@ -1,20 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql --- Schema for EventTestModel -CREATE TABLE event_test_models ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - status VARCHAR(50) DEFAULT 'draft', - revision INTEGER DEFAULT 1, - content TEXT, - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -); - --- Schema for EventTrackingModel -CREATE TABLE event_tracking_models ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT, - view_count INTEGER DEFAULT 0, - last_viewed_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql b/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql deleted file mode 100644 index 85cff134..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql +++ /dev/null @@ -1,11 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql --- Schema for EventTestModel -CREATE TABLE event_tests ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - status VARCHAR(50) DEFAULT 'draft', - revision INTEGER DEFAULT 1, - content TEXT, - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql deleted file mode 100644 index 2e189ed9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql +++ /dev/null @@ -1,9 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql --- Schema for EventTrackingModel -CREATE TABLE event_tracking_models ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT, - view_count INTEGER DEFAULT 0, - last_viewed_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py deleted file mode 100644 index 52d35dc0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py -""" -Pytest configuration for interface tests. - -This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. -""" -from rhosocial.activerecord.testsuite.feature.interface.conftest import * # noqa: F403 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py deleted file mode 100644 index 3f90b13c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py +++ /dev/null @@ -1,6 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py -""" -Bridge file for ThreadSafeDict interface tests from the testsuite. -""" - -from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py deleted file mode 100644 index 67ade74a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py -"""Bridge file for async feature.interface.test_threadsafe_dict_async tests.""" -from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py deleted file mode 100644 index d9eca998..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py -"""Use the shared ``mixins`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.mixins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py deleted file mode 100644 index 07abdf52..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/core/conftest.py -from rhosocial.activerecord_postgres_test.feature.mixins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py deleted file mode 100644 index e0869313..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py -""" -Test combined articles functionality for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.core.test_combined_articles import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py deleted file mode 100644 index 217b278f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_combined_articles_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py -"""Bridge file for async feature.mixins.test_combined_articles_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.core.test_combined_articles_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.mixins.core.test_combined_articles_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py deleted file mode 100644 index 31e34947..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py -""" -Test optimistic lock functionality for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.core.test_optimistic_lock import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py deleted file mode 100644 index b9bcab2c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_optimistic_lock_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py -"""Bridge file for async feature.mixins.test_optimistic_lock_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.core.test_optimistic_lock_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.mixins.core.test_optimistic_lock_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py deleted file mode 100644 index 878c9f64..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py -""" -Test soft delete functionality for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.core.test_soft_delete import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py deleted file mode 100644 index eea2b5f0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_soft_delete_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py -"""Bridge file for async feature.mixins.test_soft_delete_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.core.test_soft_delete_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.mixins.core.test_soft_delete_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py deleted file mode 100644 index 54ce289f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py -""" -Test timestamp functionality for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility. -""" -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.mixins.core.test_timestamps import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py deleted file mode 100644 index 391975e0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/core/test_timestamps_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py -"""Bridge file for async feature.mixins.test_timestamps_async tests.""" -from rhosocial.activerecord.testsuite.feature.mixins.core.test_timestamps_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.mixins.core.test_timestamps_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py deleted file mode 100644 index 01fbcba0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py +++ /dev/null @@ -1,61 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py -""" -This file defines the generic ActiveRecord model classes used by the mixins tests. - -These models are "generic" because they define the data structure and validation -rules (using Pydantic), but they are not tied to any specific database backend. -The backend-specific provider is responsible for taking these classes and -configuring them with a live database connection at test time. -""" -from typing import Optional -from datetime import datetime # noqa: F401 - -from pydantic import Field - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin - - -class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord): - """Blog post model with timestamps""" - @classmethod - def table_name(cls): - return "timestamped_posts" - - id: Optional[int] = None - title: str - content: str - - -class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord): - """Product model with optimistic locking""" - @classmethod - def table_name(cls): - return "versioned_products" - - id: Optional[int] = None - name: str - price: float = Field(default=0.0) - - -class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord): - """Task model supporting soft deletion""" - @classmethod - def table_name(cls): - return "tasks" - - id: Optional[int] = None - title: str - is_completed: bool = Field(default=False) - - -class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord): - """Article model combining all mixins""" - @classmethod - def table_name(cls): - return "combined_articles" - - id: Optional[int] = None - title: str - content: str - status: str = Field(default="draft") diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py deleted file mode 100644 index b7d0778e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py +++ /dev/null @@ -1,76 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/mixins/fixtures/models_py310.py -""" -Python 3.10+ fixture model definitions for mixins tests. - -This file contains model classes using Python 3.10+ syntax features: -- `X | Y` syntax instead of `Optional[X]` or `Union[X, Y]` -- `Type | None` instead of `Optional[Type]` - -Note: This file should only be imported and used in Python 3.10+ environments. -""" - -from pydantic import Field - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin - - -# Declare that this module requires Python 3.10+ -__requires_python__ = (3, 10) - - -class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord): - """Blog post model with timestamps. - - Python 3.10+ version using | syntax instead of Optional. - """ - @classmethod - def table_name(cls): - return "timestamped_posts" - - id: int | None = None - title: str - content: str - - -class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord): - """Product model with optimistic locking. - - Python 3.10+ version using | syntax instead of Optional. - """ - @classmethod - def table_name(cls): - return "versioned_products" - - id: int | None = None - name: str - price: float = Field(default=0.0) - - -class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord): - """Task model supporting soft deletion. - - Python 3.10+ version using | syntax instead of Optional. - """ - @classmethod - def table_name(cls): - return "tasks" - - id: int | None = None - title: str - is_completed: bool = Field(default=False) - - -class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord): - """Article model combining all mixins. - - Python 3.10+ version using | syntax instead of Optional. - """ - @classmethod - def table_name(cls): - return "combined_articles" - - id: int | None = None - title: str - content: str - status: str = Field(default="draft") diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py deleted file mode 100644 index 978afa7f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py +++ /dev/null @@ -1,109 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/mixins/fixtures/models_py311.py -""" -Python 3.11+ fixture model definitions for mixins tests. - -This file contains model classes using Python 3.11+ syntax features: -- `Self` type for methods that return an instance of the same class -- `X | Y` syntax (inherited from 3.10+) - -Note: This file should only be imported and used in Python 3.11+ environments. -""" -from __future__ import annotations - -from typing import Self - -from pydantic import Field - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin - - -# Declare that this module requires Python 3.11+ -__requires_python__ = (3, 11) - - -class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord): - """Blog post model with timestamps. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "timestamped_posts" - - id: int | None = None - title: str - content: str - - def update_content(self, new_content: str) -> Self: - """Update content and return self for chaining.""" - self.content = new_content - return self - - -class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord): - """Product model with optimistic locking. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "versioned_products" - - id: int | None = None - name: str - price: float = Field(default=0.0) - - def set_price(self, new_price: float) -> Self: - """Set price and return self for chaining.""" - self.price = new_price - return self - - -class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord): - """Task model supporting soft deletion. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "tasks" - - id: int | None = None - title: str - is_completed: bool = Field(default=False) - - def complete(self) -> Self: - """Mark task as completed and return self for chaining.""" - self.is_completed = True - return self - - def uncomplete(self) -> Self: - """Mark task as not completed and return self for chaining.""" - self.is_completed = False - return self - - -class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord): - """Article model combining all mixins. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "combined_articles" - - id: int | None = None - title: str - content: str - status: str = Field(default="draft") - - def publish(self) -> Self: - """Publish article and return self for chaining.""" - self.status = "published" - return self - - def archive(self) -> Self: - """Archive article and return self for chaining.""" - self.status = "archived" - return self diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py deleted file mode 100644 index 176fabe4..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py +++ /dev/null @@ -1,134 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/mixins/fixtures/models_py312.py -""" -Python 3.12+ fixture model definitions for mixins tests. - -This file contains model classes using Python 3.12+ syntax features: -- `@override` decorator for inheritance safety -- `Self` type for methods that return an instance of the same class -- `X | Y` syntax (inherited from 3.10+) - -Note: This file should only be imported and used in Python 3.12+ environments. -""" -from __future__ import annotations - -from typing import Self, override - -from pydantic import Field - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin - - -# Declare that this module requires Python 3.12+ -__requires_python__ = (3, 12) - - -class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord): - """Blog post model with timestamps. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "timestamped_posts" - - id: int | None = None - title: str - content: str - - @override - def save(self, **kwargs) -> Self: - """Save the post and return self for chaining.""" - super().save(**kwargs) - return self - - def update_content(self, new_content: str) -> Self: - """Update content and return self for chaining.""" - self.content = new_content - return self - - -class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord): - """Product model with optimistic locking. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "versioned_products" - - id: int | None = None - name: str - price: float = Field(default=0.0) - - @override - def save(self, **kwargs) -> Self: - """Save the product and return self for chaining.""" - super().save(**kwargs) - return self - - def set_price(self, new_price: float) -> Self: - """Set price and return self for chaining.""" - self.price = new_price - return self - - -class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord): - """Task model supporting soft deletion. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "tasks" - - id: int | None = None - title: str - is_completed: bool = Field(default=False) - - @override - def save(self, **kwargs) -> Self: - """Save the task and return self for chaining.""" - super().save(**kwargs) - return self - - def complete(self) -> Self: - """Mark task as completed and return self for chaining.""" - self.is_completed = True - return self - - def uncomplete(self) -> Self: - """Mark task as not completed and return self for chaining.""" - self.is_completed = False - return self - - -class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord): - """Article model combining all mixins. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "combined_articles" - - id: int | None = None - title: str - content: str - status: str = Field(default="draft") - - @override - def save(self, **kwargs) -> Self: - """Save the article and return self for chaining.""" - super().save(**kwargs) - return self - - def publish(self) -> Self: - """Publish article and return self for chaining.""" - self.status = "published" - return self - - def archive(self) -> Self: - """Archive article and return self for chaining.""" - self.status = "archived" - return self diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py deleted file mode 100644 index 9ef97023..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py +++ /dev/null @@ -1,67 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py -""" -This file defines the interface (or contract) that a backend's test provider -must adhere to for the "mixins" feature group. - -By defining a standard interface, the generic tests in the testsuite can rely on -these methods being available, regardless of which database backend is actually -running the tests. Each backend must provide a concrete class that implements -these abstract methods. -""" -from abc import ABC, abstractmethod -from typing import Type, List -from rhosocial.activerecord.model import ActiveRecord - - -class IMixinsProvider(ABC): - """ - The interface for the provider of the 'mixins' feature tests. - """ - - @abstractmethod - def get_test_scenarios(self) -> List[str]: - """ - Should return a list of scenario names (e.g., ['memory', 'file']) - that this backend supports for this test group. - """ - pass - - @abstractmethod - def setup_timestamped_post_model(self, scenario_name: str) -> Type[ActiveRecord]: - """ - Should prepare the testing environment for the timestamped post model under a - given scenario and return the configured model class. - """ - pass - - @abstractmethod - def setup_versioned_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - """ - Should prepare the testing environment for the versioned product model under a - given scenario and return the configured model class. - """ - pass - - @abstractmethod - def setup_task_model(self, scenario_name: str) -> Type[ActiveRecord]: - """ - Should prepare the testing environment for the task model under a - given scenario and return the configured model class. - """ - pass - - @abstractmethod - def setup_combined_article_model(self, scenario_name: str) -> Type[ActiveRecord]: - """ - Should prepare the testing environment for the combined article model under a - given scenario and return the configured model class. - """ - pass - - @abstractmethod - def cleanup_after_test(self, scenario_name: str): - """ - Should perform any necessary cleanup after a test has run, such as - deleting temporary database files. - """ - pass diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql deleted file mode 100644 index d2d29952..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql +++ /dev/null @@ -1,12 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql --- Schema for Article (mapped from CombinedArticle) -CREATE TABLE articles ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT, - status VARCHAR(50) DEFAULT 'draft', - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - version INTEGER DEFAULT 1, - deleted_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql deleted file mode 100644 index 42de407a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql +++ /dev/null @@ -1,12 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql --- Schema for CombinedArticle -CREATE TABLE combined_articles ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT, - status VARCHAR(50) DEFAULT 'draft', - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - version INTEGER DEFAULT 1, - deleted_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql deleted file mode 100644 index 5df75274..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql +++ /dev/null @@ -1,12 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql --- Schema for Comment (used with Article) -CREATE TABLE comments ( - id SERIAL PRIMARY KEY, - title VARCHAR(255), - content TEXT, - article_id INTEGER, - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - version INTEGER DEFAULT 1, - deleted_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql deleted file mode 100644 index 7fbddbea..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql +++ /dev/null @@ -1,8 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql --- Schema for OptimisticLockTestModel (mapped from VersionedProduct) -CREATE TABLE optimistic_lock_test_models ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - price DECIMAL(10,2) DEFAULT 0.00, - version INTEGER DEFAULT 1 -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql deleted file mode 100644 index 68c1cf48..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql +++ /dev/null @@ -1,8 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql --- Schema for SoftDeleteTestModel (mapped from Task) -CREATE TABLE soft_delete_test_models ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - is_completed BOOLEAN DEFAULT FALSE, - deleted_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql deleted file mode 100644 index b73628c3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql +++ /dev/null @@ -1,8 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql --- Schema for Task -CREATE TABLE tasks ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - is_completed BOOLEAN DEFAULT FALSE, - deleted_at TIMESTAMP WITH TIME ZONE -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql deleted file mode 100644 index 71e783f1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql +++ /dev/null @@ -1,9 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql --- Schema for TimestampedPost -CREATE TABLE timestamped_posts ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT, - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql deleted file mode 100644 index 34932300..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql +++ /dev/null @@ -1,9 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql --- Schema for TimestampsTestModel (mapped from TimestampedPost) -CREATE TABLE timestamps_test_models ( - id SERIAL PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT, - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql deleted file mode 100644 index 969b8d4d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql +++ /dev/null @@ -1,8 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql --- Schema for VersionedProduct -CREATE TABLE versioned_products ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - price DECIMAL(10,2) DEFAULT 0.00, - version INTEGER DEFAULT 1 -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py deleted file mode 100644 index 8052c239..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py -"""Use the shared ``query/aggregate`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.aggregate.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py deleted file mode 100644 index cfa86988..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_aggregate.py -""" -Bridge file for ActiveQuery aggregate tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py deleted file mode 100644 index f94de7ef..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py -"""Bridge file for async feature.query.aggregate.test_active_query_aggregate_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py deleted file mode 100644 index 5a3795ff..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_aggregate_queries.py -""" -Bridge file for aggregate queries tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py deleted file mode 100644 index 7825cf5f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py -"""Bridge file for async feature.query.aggregate.test_aggregate_queries_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py deleted file mode 100644 index 198ceb3a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py -"""Use the shared ``query/basic`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.basic.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py deleted file mode 100644 index ca58d537..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_basic.py -""" -Bridge file for ActiveQuery basic tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py deleted file mode 100644 index ff034351..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py -"""Bridge file for async feature.query.basic.test_active_query_basic_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py deleted file mode 100644 index 5ec2f7cb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_basic.py -""" -Bridge file for basic tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_basic import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py deleted file mode 100644 index 5681ff04..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py -"""Bridge file for async feature.query.basic.test_basic_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py deleted file mode 100644 index 6e648edb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py -""" -Bridge file for composite PK query tests from the testsuite. -""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py deleted file mode 100644 index 9e26bffa..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py -"""Bridge file for async feature.query.basic.test_composite_pk_query_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py deleted file mode 100644 index da021fed..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py -"""Bridge file for the testsuite natural-key find_one_or_create contract.""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py deleted file mode 100644 index c2288e00..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py deleted file mode 100644 index 1fda7a9b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_queries.py -""" -Bridge file for synchronous query tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_queries import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py deleted file mode 100644 index 8e53f6fe..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_queries_async.py -""" -Bridge file for async queries tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.basic.test_queries_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py deleted file mode 100644 index c4aeddfa..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py -""" -Pytest configuration for query connection pool feature tests. - -This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. -""" - -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py deleted file mode 100644 index 403c1a9e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py +++ /dev/null @@ -1,14 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py -""" -ActiveQuery Context Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility for ActiveQuery connection pool context awareness. -""" -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import ( - sync_pool_and_model, # noqa: F401 - async_pool_and_model, # noqa: F401 -) - -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py deleted file mode 100644 index 2baf43bd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py -"""Bridge file for async feature.query.connection.test_active_query_context_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py deleted file mode 100644 index 1483e319..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py +++ /dev/null @@ -1,14 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py -""" -CTEQuery Context Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility for CTEQuery connection pool context awareness. -""" -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import ( - sync_pool_and_model, # noqa: F401 - async_pool_and_model, # noqa: F401 -) - -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py deleted file mode 100644 index 6ca0c306..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py -"""Bridge file for async feature.query.connection.test_cte_query_context_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py deleted file mode 100644 index f6acecbf..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py +++ /dev/null @@ -1,14 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py -""" -SetOperationQuery Context Test Module for PostgreSQL backend. - -This module imports and runs the shared tests from the testsuite package, -ensuring PostgreSQL backend compatibility for SetOperationQuery connection pool context awareness. -""" -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import ( - sync_pool_and_model, # noqa: F401 - async_pool_and_model, # noqa: F401 -) - -# Import shared tests from testsuite package -from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py deleted file mode 100644 index f6ff9fcc..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py -"""Bridge file for async feature.query.connection.test_set_operation_context_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py deleted file mode 100644 index 3525f4ab..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/conftest.py -"""Use the shared ``query/cross_database`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.cross_database.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py deleted file mode 100644 index e16f8d99..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_cross_database_compatibility.py -""" -Bridge file for cross-database compatibility tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py deleted file mode 100644 index 6a15e862..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py -"""Bridge file for async feature.query.cross_database.test_cross_database_compatibility_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py deleted file mode 100644 index ec7963a1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cte/conftest.py -"""Use the shared ``query/cte`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.cte.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py deleted file mode 100644 index b9788d0b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py -""" -Bridge file for composite PK CTE tests from the testsuite. -""" -from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py deleted file mode 100644 index c141ba98..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py -"""Bridge file for async feature.query.cte.test_composite_pk_cte_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py deleted file mode 100644 index b31607d1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_cte_query_active_query.py -""" -Bridge file for cte_query_active_query tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py deleted file mode 100644 index b8e6d01e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py -"""Bridge file for async feature.query.cte.test_cte_query_active_query_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py deleted file mode 100644 index db6792dc..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_cte_query_set_operation.py -""" -Bridge file for cte_query_set_operation tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py deleted file mode 100644 index 9540b625..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py -"""Bridge file for async feature.query.cte.test_cte_query_set_operation_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py deleted file mode 100644 index a111c21f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py -"""Use the shared ``query/eager_loading`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py deleted file mode 100644 index f3a2492d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_caching.py -""" -Bridge file for eager loading caching tests. -""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py deleted file mode 100644 index 3d5f8dd9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py -"""Bridge file for async feature.query.eager_loading.test_eager_loading_caching_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py deleted file mode 100644 index 60725f0d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_nested.py -""" -Bridge file for eager loading nested tests. -""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py deleted file mode 100644 index 9434e847..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py -"""Bridge file for async feature.query.eager_loading.test_eager_loading_nested_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py deleted file mode 100644 index 7b5ca3cd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py +++ /dev/null @@ -1,2 +0,0 @@ -"""Bridge file for sync eager loading scenario tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py deleted file mode 100644 index 64cae900..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_scenarios_async.py -""" -Bridge file for async eager loading scenario tests. -""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py deleted file mode 100644 index 5e6d5fc6..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_with_all.py -""" -Bridge file for eager loading with_all tests. -""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py deleted file mode 100644 index 88855189..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py -"""Bridge file for async feature.query.eager_loading.test_eager_loading_with_all_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py deleted file mode 100644 index 82549640..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_with_modifier.py -""" -Bridge file for eager loading with_modifier tests. -""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py deleted file mode 100644 index 858cbae5..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py -"""Bridge file for async feature.query.eager_loading.test_eager_loading_with_modifier_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py deleted file mode 100644 index ac1e62aa..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_with_one.py -""" -Bridge file for eager loading with_one tests. -""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py deleted file mode 100644 index b08bd846..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py -"""Bridge file for async feature.query.eager_loading.test_eager_loading_with_one_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py deleted file mode 100644 index 5e73b65c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py -"""Use the shared ``query/error_handling`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.error_handling.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py deleted file mode 100644 index 8cf006ff..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_error_handling.py -""" -Bridge file for error_handling tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py deleted file mode 100644 index d4ff165a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py -"""Bridge file for async feature.query.error_handling.test_error_handling_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py deleted file mode 100644 index d1681c38..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py -"""Use the shared ``query/joins`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.joins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py deleted file mode 100644 index 823372d6..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_join.py -""" -Bridge file for ActiveQuery join tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py deleted file mode 100644 index d1308c9d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py -"""Bridge file for async feature.query.joins.test_active_query_join_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py deleted file mode 100644 index 320a5614..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_joins.py -""" -Bridge file for joins tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.joins.test_joins import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py deleted file mode 100644 index 2e02d0eb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py -"""Bridge file for async feature.query.joins.test_joins_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py deleted file mode 100644 index ac93f80b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py -"""Use the shared ``query/logging`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.logging.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py deleted file mode 100644 index b476a587..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_logging_data_summarization.py -""" -Bridge file for logging data summarization tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py deleted file mode 100644 index cec8f64c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py -"""Bridge file for async feature.query.logging.test_logging_data_summarization_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py deleted file mode 100644 index 02b5a48e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py -"""Use the shared ``query/optimization`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.optimization.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py deleted file mode 100644 index 8d4a466d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_query_optimization.py -""" -Bridge file for query_optimization tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py deleted file mode 100644 index bb913603..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py -"""Bridge file for async feature.query.optimization.test_query_optimization_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py deleted file mode 100644 index 3b3fc04d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py -"""Use the shared ``query/range_queries`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.range_queries.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py deleted file mode 100644 index 047ce64f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_range.py -""" -Bridge file for ActiveQuery range tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py deleted file mode 100644 index 35514496..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py -"""Bridge file for async feature.query.range_queries.test_active_query_range_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py deleted file mode 100644 index 6d9837f6..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_range_queries.py -""" -Bridge file for range_queries tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py deleted file mode 100644 index 50208650..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py -"""Bridge file for async feature.query.range_queries.test_range_queries_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py deleted file mode 100644 index 1faa60ec..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_range_query_detailed.py -""" -Bridge file for range_query_detailed tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py deleted file mode 100644 index b937526b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py -"""Bridge file for async feature.query.range_queries.test_range_query_detailed_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py deleted file mode 100644 index 288b571d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relations/conftest.py -"""Use the shared ``query/relations`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.relations.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py deleted file mode 100644 index c699fc31..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_relational_validation.py -""" -Bridge file for relational_validation tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py deleted file mode 100644 index e12e565f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py -"""Bridge file for async feature.query.relations.test_relational_validation_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py deleted file mode 100644 index 86c4d037..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_relations_basic.py -""" -Bridge file for relations_basic tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py deleted file mode 100644 index ba498765..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py -"""Bridge file for async feature.query.relations.test_relations_basic_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py deleted file mode 100644 index 8e7d2338..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_relations_with_sync.py -""" -Bridge file for sync relation 'with' tests. -""" -from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_with import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py deleted file mode 100644 index 8057becf..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_relations_with_async.py -""" -Bridge file for async relation 'with' tests. -""" -from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_with_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql deleted file mode 100644 index 5747fb2e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql +++ /dev/null @@ -1,11 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql --- Schema for Comment model -CREATE TABLE comments ( - id SERIAL PRIMARY KEY, - user_id INTEGER NOT NULL, - post_id INTEGER NOT NULL, - content TEXT NOT NULL, - is_hidden BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql deleted file mode 100644 index ac4139ac..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql +++ /dev/null @@ -1,13 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql --- Schema for ExtendedOrderItem -CREATE TABLE extended_order_items ( - id SERIAL PRIMARY KEY, - order_id INTEGER NOT NULL, - product_name VARCHAR(255) NOT NULL, - quantity INTEGER NOT NULL DEFAULT 1, - price DECIMAL(10,2) NOT NULL, - category VARCHAR(255), - region VARCHAR(50), - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql deleted file mode 100644 index 78886085..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql +++ /dev/null @@ -1,18 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql --- Schema for ExtendedOrder -CREATE TABLE extended_orders ( - id SERIAL PRIMARY KEY, - user_id INTEGER NOT NULL, - order_number VARCHAR(255) NOT NULL, - total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, - status VARCHAR(50) NOT NULL DEFAULT 'pending', - priority VARCHAR(50) NOT NULL DEFAULT 'medium', - region VARCHAR(50) NOT NULL DEFAULT 'default', - category VARCHAR(255), - product VARCHAR(255), - department VARCHAR(255), - year VARCHAR(10), - quarter VARCHAR(10), - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql deleted file mode 100644 index 8934c8fd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql +++ /dev/null @@ -1,18 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql --- Schema for JsonUser model -CREATE TABLE json_users ( - id SERIAL PRIMARY KEY, - username VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL, - age INTEGER, - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE, - -- JSONB fields for JSON testing - settings JSONB, - tags JSONB, - profile JSONB, - roles JSONB, - scores JSONB, - subscription JSONB, - preferences JSONB -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql deleted file mode 100644 index 2ee019b1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql +++ /dev/null @@ -1,10 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql --- Schema for Nodes (for tree/CTE tests) -CREATE TABLE nodes ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - parent_id INTEGER, - value DECIMAL(10,2) NOT NULL DEFAULT 0.00, - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql deleted file mode 100644 index 32e90279..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql +++ /dev/null @@ -1,12 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql --- Schema for OrderItem model -CREATE TABLE order_items ( - id SERIAL PRIMARY KEY, - order_id INTEGER NOT NULL, - product_name VARCHAR(255) NOT NULL, - quantity INTEGER NOT NULL DEFAULT 1, - unit_price DECIMAL(10,2) NOT NULL, - subtotal DECIMAL(10,2) NOT NULL DEFAULT 0.00, - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql deleted file mode 100644 index 8eededd9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql +++ /dev/null @@ -1,11 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql --- Schema for Order model -CREATE TABLE orders ( - id SERIAL PRIMARY KEY, - user_id INTEGER NOT NULL, - order_number VARCHAR(255) NOT NULL, - total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, - status VARCHAR(50) NOT NULL DEFAULT 'pending', - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql deleted file mode 100644 index 25a30933..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql +++ /dev/null @@ -1,11 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql --- Schema for Post model -CREATE TABLE posts ( - id SERIAL PRIMARY KEY, - user_id INTEGER NOT NULL, - title VARCHAR(255) NOT NULL, - content TEXT, - status VARCHAR(50) NOT NULL DEFAULT 'published', - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql deleted file mode 100644 index 6b40e508..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql +++ /dev/null @@ -1,10 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql --- Schema for Profile model -CREATE TABLE profiles ( - id SERIAL PRIMARY KEY, - user_id INTEGER NOT NULL REFERENCES users(id), - bio TEXT, - avatar_url VARCHAR(512), - created_at TIMESTAMP(6), - updated_at TIMESTAMP(6) -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql deleted file mode 100644 index 4a3b59bc..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql +++ /dev/null @@ -1,9 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql - -CREATE TABLE "searchable_items" ( - "id" SERIAL PRIMARY KEY, - "name" VARCHAR(255), - "tags" TEXT, - "created_at" TIMESTAMP, - "updated_at" TIMESTAMP -); \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql deleted file mode 100644 index 4b41d485..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql +++ /dev/null @@ -1,12 +0,0 @@ --- tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql --- Schema for User model -CREATE TABLE users ( - id SERIAL PRIMARY KEY, - username VARCHAR(255) NOT NULL, - email VARCHAR(255) NOT NULL, - age INTEGER, - balance DECIMAL(10,2) NOT NULL DEFAULT 0.00, - is_active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE -); diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py deleted file mode 100644 index 7bc9a220..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/conftest.py -"""Use the shared ``query/set_operations`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.set_operations.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py deleted file mode 100644 index c2f04d67..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_set_operation.py -""" -Bridge file for ActiveQuery set operation tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py deleted file mode 100644 index a71251a5..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py -"""Bridge file for async feature.query.set_operations.test_active_query_set_operation_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py deleted file mode 100644 index 3d3034e9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py -""" -Bridge file for composite PK set operation tests from the testsuite. -""" -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py deleted file mode 100644 index f77a1f16..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py -"""Bridge file for async feature.query.set_operations.test_composite_pk_set_operation_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py deleted file mode 100644 index 9bec2b6b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_set_operation.py -""" -Bridge file for set_operation tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py deleted file mode 100644 index 46389c84..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py -"""Bridge file for async feature.query.set_operations.test_set_operation_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py deleted file mode 100644 index 84fb89fb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py -"""Use the shared ``query/special`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.special.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py deleted file mode 100644 index 79e54062..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_example_query_fixtures.py -""" -Bridge file for example_query_fixtures tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py deleted file mode 100644 index bcc2fcfe..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py -"""Bridge file for async feature.query.special.test_example_query_fixtures_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py deleted file mode 100644 index e15c2d89..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_special_queries.py -""" -Bridge file for special_queries tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py deleted file mode 100644 index acb874d3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py -"""Bridge file for async feature.query.special.test_special_queries_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py deleted file mode 100644 index dc7b8d76..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py -"""Use the shared ``query/typed_column`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.typed_column.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py deleted file mode 100644 index 7b73fe82..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py -from rhosocial.activerecord.testsuite.feature.query.typed_column.test_protocol_guarantees import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py deleted file mode 100644 index 318177ec..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py -from rhosocial.activerecord.testsuite.feature.query.typed_column.test_seconds_between_contract import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py deleted file mode 100644 index 1d6ccb99..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py -"""Use the shared ``query/window_functions`` minimal test set.""" - -from rhosocial.activerecord.testsuite.feature.query.window_functions.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py deleted file mode 100644 index 225b1ea2..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_window_functions.py -""" -Bridge file for window_functions tests from the testsuite. - -This file imports the generic tests from the testsuite package and makes them -discoverable by pytest in this project's test run. -""" -from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py deleted file mode 100644 index f025e662..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py -"""Bridge file for async feature.query.window_functions.test_window_functions_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py deleted file mode 100644 index 25979d9d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py -""" -Pytest configuration for query worker tests. - -This file imports fixtures from the corresponding testsuite, making them -available to the tests in this directory. -""" - -from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py deleted file mode 100644 index 7bfe5ecb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py -""" -Bridge file for parallel queries worker tests. - -Imports tests from testsuite and makes them discoverable by pytest. -""" -from rhosocial.activerecord.testsuite.feature.query.worker.conftest import ( - order_fixtures_for_worker, # noqa: F401 - async_order_fixtures_for_worker, # noqa: F401 -) -from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py deleted file mode 100644 index f2953770..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py -"""Bridge file for async feature.query.worker.test_parallel_queries_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py deleted file mode 100644 index f32643b9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py +++ /dev/null @@ -1,7 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py -""" -Bridge file for transaction isolation tests. - -Imports tests from testsuite and makes them discoverable by pytest. -""" -from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py deleted file mode 100644 index f73efd1c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py -"""Bridge file for async feature.query.worker.test_transaction_isolation_async tests.""" -from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py deleted file mode 100644 index 5237cde3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/base/conftest.py -"""No directory-specific fixtures: the relation topic conftest supplies them.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py deleted file mode 100644 index 1fb8802b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Tests for relation base functionality. -Imports tests from the standardized testsuite. -""" -from rhosocial.activerecord.testsuite.feature.relation.base.test_base import TestRelationDescriptor # noqa: F401 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py deleted file mode 100644 index 5259aa4a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.base.test_base_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py deleted file mode 100644 index dce937f9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Tests for relation interfaces. -Imports tests from the standardized testsuite. -""" -from rhosocial.activerecord.testsuite.feature.relation.base.test_interfaces import TestRelationInterfaces # noqa: F401 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py deleted file mode 100644 index 688ea916..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.base.test_interfaces_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py deleted file mode 100644 index a73bbce5..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/conftest.py -"""Use the shared ``relation/boundary`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.boundary.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py deleted file mode 100644 index c806b2e5..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py deleted file mode 100644 index 8b71c8fc..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py deleted file mode 100644 index 61a6dd6a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/cache/conftest.py -"""No directory-specific fixtures: the relation topic conftest supplies them.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py deleted file mode 100644 index 7e97b7cd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -Test bridge for relation cache functionality. - -This test file runs the relation cache tests from the testsuite using the PostgreSQL backend. -""" -import pytest # noqa: F401 - - -# Import the test classes from the testsuite -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache import TestRelationCache # noqa: F401 - - -# This will cause pytest to run all the tests in the imported class -# The tests will use the fixtures and providers configured in conftest.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py deleted file mode 100644 index 33f8eccb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py deleted file mode 100644 index 1550776b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py deleted file mode 100644 index 84796d5e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py -"""Bridge file for async feature.relation.cache.test_cache_clearing_async tests.""" -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py deleted file mode 100644 index 529950d2..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py +++ /dev/null @@ -1,7 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py -"""Fixtures for the relation feature tests. - -The topic conftest supplies the fixtures and the minimal test set for this -directory's database. -""" -from rhosocial.activerecord.testsuite.feature.relation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py deleted file mode 100644 index f2f51c07..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/derived/conftest.py -"""Use the shared ``relation/derived`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py deleted file mode 100644 index bcf8f56e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py deleted file mode 100644 index 15148306..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py deleted file mode 100644 index b43dbfb2..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py -"""Bridge file for sync feature.relation.derived.test_derived_field tests.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py deleted file mode 100644 index c26f8585..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py -"""Bridge file for async feature.relation.derived.test_derived_field_async tests.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py deleted file mode 100644 index a58eb73b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/conftest.py -"""No directory-specific fixtures: the relation topic conftest supplies them.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py deleted file mode 100644 index 7da186bb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/test_descriptor_compat.py - -from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py deleted file mode 100644 index 02d2f7ec..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py -"""Bridge file for async feature.relation.descriptors.test_descriptor_compat_async tests.""" -from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py deleted file mode 100644 index 9622ce84..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Tests for relation descriptor functionality. -Imports tests from the standardized testsuite. -""" -from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptors import TestRelationDescriptors # noqa: F401 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py deleted file mode 100644 index b10f32f3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/test_descriptors_async.py - -from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptors_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py deleted file mode 100644 index f5789fd7..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/conftest.py -"""Use the shared ``relation/eager_loading`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py deleted file mode 100644 index f9447d3a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Tests for nested relationship access functionality. -Imports tests from the standardized testsuite. -""" -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_nested_relationship_access import TestNestedRelationshipAccess # noqa: E501, F401 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py deleted file mode 100644 index 6ea7cbbe..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_nested_relationship_access_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py deleted file mode 100644 index 134b3e91..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py deleted file mode 100644 index c372ff6a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py deleted file mode 100644 index 3dd75e19..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py +++ /dev/null @@ -1,420 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models.py -""" -Relation model fixtures for the testsuite. - -This module provides model classes for testing relation features: -- Employee/Department: Basic BelongsTo/HasMany relations -- Author/Book/Chapter/Profile: Nested relations with HasOne -- User/Post/Comment: Relations with FieldProxy, DerivedField, and JSON fields -""" -from typing import Optional, ClassVar - -from typing_extensions import Annotated - -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord -from rhosocial.activerecord.base import DerivedField, FieldProxy -from rhosocial.activerecord.backend.expression import Column, Literal -from rhosocial.activerecord.backend.expression.functions import ( - json_extract_text, length, coalesce -) -from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne -from rhosocial.activerecord.relation.async_descriptors import AsyncBelongsTo, AsyncHasMany, AsyncHasOne - - -# ── Basic Relation Models ──────────────────────────────── - -class Employee(ActiveRecord): - @classmethod - def table_name(cls): - return "employees" - - id: Optional[int] = None - username: str - department_id: int - - department: ClassVar[BelongsTo["Department"]] = BelongsTo( - foreign_key="department_id", - inverse_of="employees" - ) - - -class Department(ActiveRecord): - @classmethod - def table_name(cls): - return "departments" - - id: Optional[int] = None - name: str - description: str = "" - - employees: ClassVar[HasMany["Employee"]] = HasMany( - foreign_key="department_id", - inverse_of="department" - ) - - -class Author(ActiveRecord): - @classmethod - def table_name(cls): - return "authors" - - id: Optional[int] = None - name: str - - books: ClassVar[HasMany["Book"]] = HasMany( - foreign_key="author_id", - inverse_of="author" - ) - profile: ClassVar[HasOne["Profile"]] = HasOne( - foreign_key="author_id", - inverse_of="author" - ) - - -class Book(ActiveRecord): - @classmethod - def table_name(cls): - return "books" - - id: Optional[int] = None - title: str - author_id: int - - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="books" - ) - chapters: ClassVar[HasMany["Chapter"]] = HasMany( - foreign_key="book_id", - inverse_of="book" - ) - - -class Chapter(ActiveRecord): - @classmethod - def table_name(cls): - return "chapters" - - id: Optional[int] = None - title: str - book_id: int - - book: ClassVar[BelongsTo["Book"]] = BelongsTo( - foreign_key="book_id", - inverse_of="chapters" - ) - - -class Profile(ActiveRecord): - @classmethod - def table_name(cls): - return "profiles" - - id: Optional[int] = None - bio: str - author_id: int - - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="profile" - ) - - -# ── Advanced Relation Models (with FieldProxy, DerivedField, JSON) ── - -class User(ActiveRecord): - @classmethod - def table_name(cls): - return "users" - - c: ClassVar[FieldProxy] = FieldProxy() - id: Optional[int] = None - name: str - email: Optional[str] = None - settings: Optional[str] = None # JSON: {"language": "zh-CN", "theme": "dark"} - - # DerivedField: display name (coalesce email to name) - display_name: ClassVar[Annotated[str, DerivedField( - lambda d: coalesce(d, Column(dialect, d, "email"), Column(dialect, d, "name")), - )]] - - # DerivedField (JSON): extract language preference - language: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.language"), - )]] - - # DerivedField (JSON): extract theme preference - theme: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.theme"), - )]] - - # Relation - posts: ClassVar[HasMany["Post"]] = HasMany( - foreign_key="user_id", - inverse_of="user" - ) - - -class Post(ActiveRecord): - @classmethod - def table_name(cls): - return "posts" - - c: ClassVar[FieldProxy] = FieldProxy() - id: Optional[int] = None - title: str - body: str - user_id: int - view_count: int = 0 - metadata: Optional[str] = None # JSON: {"tags": ["python", "orm"], "source": "blog"} - - # DerivedField: title length using FieldProxy - title_length: ClassVar[Annotated[int, DerivedField( - lambda d: length(d, Post.c.title), - )]] - - # DerivedField: hotness score - hotness: ClassVar[Annotated[int, DerivedField( - lambda d: ArithmeticOperation(dialect, "add", Column(dialect, d, "view_count"), Literal(d, 1)), - )]] - - # DerivedField (JSON): first tag from metadata - first_tag: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.tags[0]"), - )]] - - # DerivedField (JSON): source from metadata - source: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.source"), - )]] - - # Relations - user: ClassVar[BelongsTo["User"]] = BelongsTo( - foreign_key="user_id", - inverse_of="posts" - ) - comments: ClassVar[HasMany["Comment"]] = HasMany( - foreign_key="post_id", - inverse_of="post" - ) - - -class Comment(ActiveRecord): - @classmethod - def table_name(cls): - return "comments" - - c: ClassVar[FieldProxy] = FieldProxy() - id: Optional[int] = None - body: str - post_id: int - meta: Optional[str] = None # JSON: {"platform": "web", "device": "mobile"} - - # DerivedField: body length using FieldProxy - body_length: ClassVar[Annotated[int, DerivedField( - lambda d: length(d, Comment.c.body), - )]] - - # DerivedField (JSON): platform from meta - platform: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "meta"), "$.platform"), - )]] - - # Relation - post: ClassVar[BelongsTo["Post"]] = BelongsTo( - foreign_key="post_id", - inverse_of="comments" - ) - - -# ── Async Models ───────────────────────────────────────── - -class AsyncUser(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "users" - - c: ClassVar[FieldProxy] = FieldProxy() - id: Optional[int] = None - name: str - email: Optional[str] = None - settings: Optional[str] = None - - display_name: ClassVar[Annotated[str, DerivedField( - lambda d: coalesce(d, Column(dialect, d, "email"), Column(dialect, d, "name")), - )]] - - language: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.language"), - )]] - - theme: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.theme"), - )]] - - posts: ClassVar[AsyncHasMany["AsyncPost"]] = AsyncHasMany( - foreign_key="user_id", - inverse_of="user" - ) - - -class AsyncPost(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "posts" - - c: ClassVar[FieldProxy] = FieldProxy() - id: Optional[int] = None - title: str - body: str - user_id: int - view_count: int = 0 - metadata: Optional[str] = None - - title_length: ClassVar[Annotated[int, DerivedField( - lambda d: length(d, AsyncPost.c.title), - )]] - - hotness: ClassVar[Annotated[int, DerivedField( - lambda d: ArithmeticOperation(dialect, "add", Column(dialect, d, "view_count"), Literal(d, 1)), - )]] - - first_tag: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.tags[0]"), - )]] - - source: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.source"), - )]] - - user: ClassVar[AsyncBelongsTo["AsyncUser"]] = AsyncBelongsTo( - foreign_key="user_id", - inverse_of="posts" - ) - comments: ClassVar[AsyncHasMany["AsyncComment"]] = AsyncHasMany( - foreign_key="post_id", - inverse_of="post" - ) - - -class AsyncComment(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "comments" - - c: ClassVar[FieldProxy] = FieldProxy() - id: Optional[int] = None - body: str - post_id: int - meta: Optional[str] = None - - body_length: ClassVar[Annotated[int, DerivedField( - lambda d: length(d, AsyncComment.c.body), - )]] - - platform: ClassVar[Annotated[str, DerivedField( - lambda d: json_extract_text(d, Column(dialect, d, "meta"), "$.platform"), - )]] - - post: ClassVar[AsyncBelongsTo["AsyncPost"]] = AsyncBelongsTo( - foreign_key="post_id", - inverse_of="comments" - ) - - -# ── Relation Boundary Models ────────────────────────────── - -class BoundaryOwner(ActiveRecord): - @classmethod - def table_name(cls): - return "relation_boundary_owners" - - id: Optional[int] = None - name: str - - profile: ClassVar[HasOne["BoundaryProfile"]] = HasOne( - foreign_key="owner_id", - inverse_of="owner" - ) - posts: ClassVar[HasMany["BoundaryPost"]] = HasMany( - foreign_key="owner_id", - inverse_of="owner" - ) - - -class BoundaryProfile(ActiveRecord): - @classmethod - def table_name(cls): - return "relation_boundary_profiles" - - id: Optional[int] = None - bio: str - owner_id: Optional[int] = None - - owner: ClassVar[BelongsTo["BoundaryOwner"]] = BelongsTo( - foreign_key="owner_id", - inverse_of="profile" - ) - - -class BoundaryPost(ActiveRecord): - @classmethod - def table_name(cls): - return "relation_boundary_posts" - - id: Optional[int] = None - title: str - owner_id: Optional[int] = None - - owner: ClassVar[BelongsTo["BoundaryOwner"]] = BelongsTo( - foreign_key="owner_id", - inverse_of="posts" - ) - - -class AsyncBoundaryOwner(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "relation_boundary_owners" - - id: Optional[int] = None - name: str - - profile: ClassVar[AsyncHasOne["AsyncBoundaryProfile"]] = AsyncHasOne( - foreign_key="owner_id", - inverse_of="owner" - ) - posts: ClassVar[AsyncHasMany["AsyncBoundaryPost"]] = AsyncHasMany( - foreign_key="owner_id", - inverse_of="owner" - ) - - -class AsyncBoundaryProfile(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "relation_boundary_profiles" - - id: Optional[int] = None - bio: str - owner_id: Optional[int] = None - - owner: ClassVar[AsyncBelongsTo["AsyncBoundaryOwner"]] = AsyncBelongsTo( - foreign_key="owner_id", - inverse_of="profile" - ) - - -class AsyncBoundaryPost(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "relation_boundary_posts" - - id: Optional[int] = None - title: str - owner_id: Optional[int] = None - - owner: ClassVar[AsyncBelongsTo["AsyncBoundaryOwner"]] = AsyncBelongsTo( - foreign_key="owner_id", - inverse_of="posts" - ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py deleted file mode 100644 index e91bf2c1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py +++ /dev/null @@ -1,144 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models_py310.py -""" -Python 3.10+ fixture model definitions for relation tests. - -This file contains model classes using Python 3.10+ syntax features: -- `X | Y` syntax instead of `Optional[X]` or `Union[X, Y]` - -Note: This file should only be imported and used in Python 3.10+ environments. -""" -from typing import ClassVar - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne - - -# Declare that this module requires Python 3.10+ -__requires_python__ = (3, 10) - - -class Employee(ActiveRecord): - """Employee model with department relation. - - Python 3.10+ version. - """ - @classmethod - def table_name(cls): - return "employees" - - id: int | None = None - username: str - department_id: int - - # Define the relation to department - department: ClassVar[BelongsTo["Department"]] = BelongsTo( - foreign_key="department_id", - inverse_of="employees" - ) - - -class Department(ActiveRecord): - """Department model with employees relation. - - Python 3.10+ version. - """ - @classmethod - def table_name(cls): - return "departments" - - id: int | None = None - name: str - description: str = "" - - # Define the relation to employees - employees: ClassVar[HasMany["Employee"]] = HasMany( - foreign_key="department_id", - inverse_of="department" - ) - - -class Author(ActiveRecord): - """Author model with books and profile relations. - - Python 3.10+ version. - """ - @classmethod - def table_name(cls): - return "authors" - - id: int | None = None - name: str - - # Relations - books: ClassVar[HasMany["Book"]] = HasMany( - foreign_key="author_id", - inverse_of="author" - ) - profile: ClassVar[HasOne["Profile"]] = HasOne( - foreign_key="author_id", - inverse_of="author" - ) - - -class Book(ActiveRecord): - """Book model with author and chapters relations. - - Python 3.10+ version. - """ - @classmethod - def table_name(cls): - return "books" - - id: int | None = None - title: str - author_id: int - - # Relations - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="books" - ) - chapters: ClassVar[HasMany["Chapter"]] = HasMany( - foreign_key="book_id", - inverse_of="book" - ) - - -class Chapter(ActiveRecord): - """Chapter model with book relation. - - Python 3.10+ version. - """ - @classmethod - def table_name(cls): - return "chapters" - - id: int | None = None - title: str - book_id: int - - # Relations - book: ClassVar[BelongsTo["Book"]] = BelongsTo( - foreign_key="book_id", - inverse_of="chapters" - ) - - -class Profile(ActiveRecord): - """Profile model with author relation. - - Python 3.10+ version. - """ - @classmethod - def table_name(cls): - return "profiles" - - id: int | None = None - bio: str - author_id: int - - # Relations - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="profile" - ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py deleted file mode 100644 index ea692f3c..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py +++ /dev/null @@ -1,177 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models_py311.py -""" -Python 3.11+ fixture model definitions for relation tests. - -This file contains model classes using Python 3.11+ syntax features: -- `Self` type for methods that return an instance of the same class -- `X | Y` syntax (inherited from 3.10+) - -Note: This file should only be imported and used in Python 3.11+ environments. -""" -from __future__ import annotations - -from typing import ClassVar, Self - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne - - -# Declare that this module requires Python 3.11+ -__requires_python__ = (3, 11) - - -class Employee(ActiveRecord): - """Employee model with department relation. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "employees" - - id: int | None = None - username: str - department_id: int - - # Define the relation to department - department: ClassVar[BelongsTo["Department"]] = BelongsTo( - foreign_key="department_id", - inverse_of="employees" - ) - - def transfer_to(self, new_department_id: int) -> Self: - """Transfer employee to another department and return self for chaining.""" - self.department_id = new_department_id - return self - - -class Department(ActiveRecord): - """Department model with employees relation. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "departments" - - id: int | None = None - name: str - description: str = "" - - # Define the relation to employees - employees: ClassVar[HasMany["Employee"]] = HasMany( - foreign_key="department_id", - inverse_of="department" - ) - - def set_description(self, new_description: str) -> Self: - """Set description and return self for chaining.""" - self.description = new_description - return self - - -class Author(ActiveRecord): - """Author model with books and profile relations. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "authors" - - id: int | None = None - name: str - - # Relations - books: ClassVar[HasMany["Book"]] = HasMany( - foreign_key="author_id", - inverse_of="author" - ) - profile: ClassVar[HasOne["Profile"]] = HasOne( - foreign_key="author_id", - inverse_of="author" - ) - - def rename(self, new_name: str) -> Self: - """Rename author and return self for chaining.""" - self.name = new_name - return self - - -class Book(ActiveRecord): - """Book model with author and chapters relations. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "books" - - id: int | None = None - title: str - author_id: int - - # Relations - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="books" - ) - chapters: ClassVar[HasMany["Chapter"]] = HasMany( - foreign_key="book_id", - inverse_of="book" - ) - - def retitle(self, new_title: str) -> Self: - """Change book title and return self for chaining.""" - self.title = new_title - return self - - -class Chapter(ActiveRecord): - """Chapter model with book relation. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "chapters" - - id: int | None = None - title: str - book_id: int - - # Relations - book: ClassVar[BelongsTo["Book"]] = BelongsTo( - foreign_key="book_id", - inverse_of="chapters" - ) - - def rename(self, new_title: str) -> Self: - """Rename chapter and return self for chaining.""" - self.title = new_title - return self - - -class Profile(ActiveRecord): - """Profile model with author relation. - - Python 3.11+ version using | syntax and Self type. - """ - @classmethod - def table_name(cls): - return "profiles" - - id: int | None = None - bio: str - author_id: int - - # Relations - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="profile" - ) - - def update_bio(self, new_bio: str) -> Self: - """Update bio and return self for chaining.""" - self.bio = new_bio - return self diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py deleted file mode 100644 index 75a3906f..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py +++ /dev/null @@ -1,214 +0,0 @@ -# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models_py312.py -""" -Python 3.12+ fixture model definitions for relation tests. - -This file contains model classes using Python 3.12+ syntax features: -- `@override` decorator for inheritance safety -- `Self` type for methods that return an instance of the same class -- `X | Y` syntax (inherited from 3.10+) - -Note: This file should only be imported and used in Python 3.12+ environments. -""" -from __future__ import annotations - -from typing import ClassVar, Self, override - -from rhosocial.activerecord.model import ActiveRecord -from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne - - -# Declare that this module requires Python 3.12+ -__requires_python__ = (3, 12) - - -class Employee(ActiveRecord): - """Employee model with department relation. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "employees" - - id: int | None = None - username: str - department_id: int - - # Define the relation to department - department: ClassVar[BelongsTo["Department"]] = BelongsTo( - foreign_key="department_id", - inverse_of="employees" - ) - - @override - def save(self, **kwargs) -> Self: - """Save the employee and return self for chaining.""" - super().save(**kwargs) - return self - - def transfer_to(self, new_department_id: int) -> Self: - """Transfer employee to another department and return self for chaining.""" - self.department_id = new_department_id - return self - - -class Department(ActiveRecord): - """Department model with employees relation. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "departments" - - id: int | None = None - name: str - description: str = "" - - # Define the relation to employees - employees: ClassVar[HasMany["Employee"]] = HasMany( - foreign_key="department_id", - inverse_of="department" - ) - - @override - def save(self, **kwargs) -> Self: - """Save the department and return self for chaining.""" - super().save(**kwargs) - return self - - def set_description(self, new_description: str) -> Self: - """Set description and return self for chaining.""" - self.description = new_description - return self - - -class Author(ActiveRecord): - """Author model with books and profile relations. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "authors" - - id: int | None = None - name: str - - # Relations - books: ClassVar[HasMany["Book"]] = HasMany( - foreign_key="author_id", - inverse_of="author" - ) - profile: ClassVar[HasOne["Profile"]] = HasOne( - foreign_key="author_id", - inverse_of="author" - ) - - @override - def save(self, **kwargs) -> Self: - """Save the author and return self for chaining.""" - super().save(**kwargs) - return self - - def rename(self, new_name: str) -> Self: - """Rename author and return self for chaining.""" - self.name = new_name - return self - - -class Book(ActiveRecord): - """Book model with author and chapters relations. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "books" - - id: int | None = None - title: str - author_id: int - - # Relations - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="books" - ) - chapters: ClassVar[HasMany["Chapter"]] = HasMany( - foreign_key="book_id", - inverse_of="book" - ) - - @override - def save(self, **kwargs) -> Self: - """Save the book and return self for chaining.""" - super().save(**kwargs) - return self - - def retitle(self, new_title: str) -> Self: - """Change book title and return self for chaining.""" - self.title = new_title - return self - - -class Chapter(ActiveRecord): - """Chapter model with book relation. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "chapters" - - id: int | None = None - title: str - book_id: int - - # Relations - book: ClassVar[BelongsTo["Book"]] = BelongsTo( - foreign_key="book_id", - inverse_of="chapters" - ) - - @override - def save(self, **kwargs) -> Self: - """Save the chapter and return self for chaining.""" - super().save(**kwargs) - return self - - def rename(self, new_title: str) -> Self: - """Rename chapter and return self for chaining.""" - self.title = new_title - return self - - -class Profile(ActiveRecord): - """Profile model with author relation. - - Python 3.12+ version using | syntax, Self type, and @override. - """ - @classmethod - def table_name(cls): - return "profiles" - - id: int | None = None - bio: str - author_id: int - - # Relations - author: ClassVar[BelongsTo["Author"]] = BelongsTo( - foreign_key="author_id", - inverse_of="profile" - ) - - @override - def save(self, **kwargs) -> Self: - """Save the profile and return self for chaining.""" - super().save(**kwargs) - return self - - def update_bio(self, new_bio: str) -> Self: - """Update bio and return self for chaining.""" - self.bio = new_bio - return self diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py deleted file mode 100644 index 0df66180..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/integration/conftest.py -"""Use the shared ``relation/integration`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.integration.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py deleted file mode 100644 index b8dfb5ec..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py deleted file mode 100644 index cfd025f4..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py deleted file mode 100644 index 3e5c64a7..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/conftest.py -"""Use the shared ``relation/modifiers`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.modifiers.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py deleted file mode 100644 index 6e7b8df1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py deleted file mode 100644 index b350149b..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py deleted file mode 100644 index 4bb16f70..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py deleted file mode 100644 index d94f9909..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py deleted file mode 100644 index 9176c11d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/conftest.py -"""Use the shared ``relation/ordering`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.ordering.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py deleted file mode 100644 index ad2b38cb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py -"""Bridge file for the testsuite ordered HasMany contract (sync and async).""" -from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py deleted file mode 100644 index 53182b04..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py deleted file mode 100644 index e53e8def..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/validation/conftest.py -"""Use the shared ``relation/validation`` minimal test set.""" -from rhosocial.activerecord.testsuite.feature.relation.validation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py deleted file mode 100644 index 7232b1d9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py deleted file mode 100644 index 52e84cba..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F401,F403 - -from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py deleted file mode 100644 index e9b4b8e8..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/test_validator.py - -from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py deleted file mode 100644 index f8d4daeb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py -"""Bridge file for async feature.relation.validation.test_validator_async tests.""" -from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F401, F403 - -from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F403 From 3e3637b9baf3687f2f11638cc3102c3a75bf3767 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 03:16:47 +0800 Subject: [PATCH 43/81] test(backend): switch backend-owned tests to declarative parallel scopes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按 testsuite 声明式并行机制改造后端自有测试:根 conftest 声明 parallel=False,删除 legacy xdist_group 钩子;目录级数据库作用域声明 parallel=True,纯渲染目录保持未声明。 --- .../backend/adapters/native/conftest.py | 9 ++++++++ .../feature/backend/conftest.py | 21 +++++++------------ .../feature/backend/execute/conftest.py | 20 ++++++++++++++++++ .../backend/execute/ddl_view/conftest.py | 8 +++++++ .../backend/execute/introspection/conftest.py | 9 ++++++++ 5 files changed, 54 insertions(+), 13 deletions(-) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index 1e9b95cf..1031d1a8 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -17,6 +17,15 @@ import pytest +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +DECLARATION = Declaration( + parallel=True, + purpose="PostgreSQL native type tests (native) against the directory-owned database.", + passes_means="the live-database contract of this directory holds on PostgreSQL", + fails_means="the directory-owned database is corrupted or a backend behavior is wrong", +) + SCHEMA_DIR = Path(__file__).parent / "schema" BUILTIN_SCHEMA = SCHEMA_DIR / "native_types.sql" EXTENSION_SCHEMA = SCHEMA_DIR / "extension_types.sql" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py index a3c80c8b..78269532 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py @@ -18,6 +18,14 @@ AsyncPostgresBackend, ) from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +DECLARATION = Declaration( + parallel=False, + purpose="Backend-owned PostgreSQL tests; pure-render scopes stay ungrouped.", + passes_means="backend-specific behavior matches PostgreSQL semantics", + fails_means="a backend contract is violated or a directory database is corrupted", +) # --- Scenario Loading Logic --- @@ -88,19 +96,6 @@ def get_scenario( return PostgresBackend, support.postgres.scenario(name).make_config(database) -def pytest_collection_modifyitems(config, items): - """Pin a backend directory's tests to one worker. - - These directories create and drop tables in the directory's own database, - so two workers must never run tests from the same directory at once. - """ - for item in items: - parts = item.path.parts - if "backend" not in parts: - continue - item.add_marker(pytest.mark.xdist_group("postgres-backend::" + str(item.path.parent))) - - # --- Provider Logic for Fixtures --- diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py new file mode 100644 index 00000000..eddb4b17 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py @@ -0,0 +1,20 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py +"""Group the backend-owned execute tests by their directory-owned database. + +The root ``backend/conftest.py`` declares ``parallel=False`` so pure-render +scopes stay ungrouped. Every directory under ``execute/`` however drives a +live server and owns its own database (named from the directory path), so its +tests must stay on one worker per scenario. Declaring ``parallel=True`` here +makes the testsuite plugin pin each such directory to one worker per scenario; +the group key is derived from the test file's own directory, so different +execute directories still run in parallel. +""" + +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +DECLARATION = Declaration( + parallel=True, + purpose="PostgreSQL execute tests against each directory-owned database.", + passes_means="the live-database contract of the execute directory holds on PostgreSQL", + fails_means="the directory-owned database is corrupted or a backend behavior is wrong", +) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py index 32851494..31afef0e 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py @@ -16,6 +16,14 @@ ) from rhosocial.activerecord.backend.options import ExecutionOptions from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +DECLARATION = Declaration( + parallel=True, + purpose="PostgreSQL materialized view tests (ddl_view) against the directory-owned database.", + passes_means="the live-database contract of this directory holds on PostgreSQL", + fails_means="the directory-owned database is corrupted or a backend behavior is wrong", +) DDL = ExecutionOptions(stmt_type=StatementType.DDL) DQL = ExecutionOptions(stmt_type=StatementType.DQL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py index fd6fd081..152f99b0 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py @@ -9,6 +9,15 @@ import pytest import pytest_asyncio +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +DECLARATION = Declaration( + parallel=True, + purpose="PostgreSQL introspection tests (introspection) against the directory-owned database.", + passes_means="the live-database contract of this directory holds on PostgreSQL", + fails_means="the directory-owned database is corrupted or a backend behavior is wrong", +) + # SQL statements for test tables _TABLES_SQL = [ From aebece938a97991b328b82bc72e28ecd8a0f14a1 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 04:51:01 +0800 Subject: [PATCH 44/81] test: follow the testsuite fixture and naming moves Point pool_definitions at feature.query.fixtures.definitions; give backend-specific test_expressions.py unique basenames so pytest does not collide with the new basic/expressions group. --- .../{test_expressions.py => test_postgres_expressions.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/{test_expressions.py => test_postgres_expressions.py} (100%) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py similarity index 100% rename from tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py From aa71ac61f06fa842bd26ca4ba0b0112b11a3de3f Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 04:51:25 +0800 Subject: [PATCH 45/81] test: update path comments and fixture import --- .../backend/construct/statements/test_postgres_expressions.py | 2 +- .../feature/connection/pool_definitions.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py index 218aeda7..67ef7f2c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_expressions.py +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py """Tests for PostgreSQL-specific expression classes and format methods. This module tests the expression-based format methods for DDL/DML operations, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py index 4c8a684a..44ccaada 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py @@ -36,7 +36,7 @@ from rhosocial.activerecord.backend.impl.postgres.expression.types import ( PostgresSerialType, ) -from rhosocial.activerecord.testsuite.fixture_types import supports_drop_if_exists +from rhosocial.activerecord.testsuite.feature.query.fixtures.definitions import supports_drop_if_exists class Definition: From 5089bdf122d6b9e10467998447c35b419171e443 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 05:01:37 +0800 Subject: [PATCH 46/81] test: drop stale fixture imports from the CRUD bridge type_case_class / type_test_model were removed from the testsuite basic conftest; pytest injects the remaining fixtures. --- .../activerecord_postgres_test/feature/basic/crud/test_crud.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py index e1402383..c6624070 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py @@ -16,12 +16,9 @@ # parameterized to run against the scenarios defined in `providers/scenarios.py`. from rhosocial.activerecord.testsuite.feature.basic.conftest import ( user_class, # noqa: F401 - type_case_class, # noqa: F401 - type_test_model, # noqa: F401 validated_user_class, # noqa: F401 validated_user, # noqa: F401 async_user_class, # noqa: F401 - async_type_case_class, # noqa: F401 async_validated_user_class, # noqa: F401 async_validated_user # noqa: F401 ) From 772bcfb1ad8eab1692d4482eca5e6788e18749d6 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 12:20:56 +0800 Subject: [PATCH 47/81] test: follow core's dedicated unsupported-data-type error Core now raises UnsupportedDataTypeError (a TypeError subclass) for a concept the dialect neither renders nor substitutes; the roundtrip pins expected the exact TypeError. --- .../construct/expression/test_expression_namespace.py | 5 +++++ .../expression/test_expression_roundtrip_all.py | 10 +++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py index 19966e6c..bad59444 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py @@ -21,6 +21,10 @@ from rhosocial.activerecord.backend.impl import postgres EXPRESSION_NS = postgres.__name__ + ".expression" +# Column classes that model a column's *surface* (no family operation) live in +# ``column_types``, parallel to ``expression`` rather than inside it. They are +# still BaseExpression subclasses, but that module is a legitimate home. +COLUMN_TYPES_NS = postgres.__name__ + ".column_types" BACKEND_NS = postgres.__name__ + "." @@ -83,6 +87,7 @@ def test_no_expression_defined_outside_expression_namespace(all_expression_class for cls in all_expression_classes if cls.__module__.startswith(BACKEND_NS) and not cls.__module__.startswith(EXPRESSION_NS) + and not cls.__module__.startswith(COLUMN_TYPES_NS) ] assert not offenders, ( "BaseExpression subclasses defined in this backend but outside " diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py index 15a62486..9a8125f1 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py @@ -129,7 +129,7 @@ class name -- ``Literal`` the single exception, naming its fourteen value kinds import pytest -from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError +from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedDataTypeError, UnsupportedFeatureError from rhosocial.activerecord.backend.expression import graph as graph_mod from rhosocial.activerecord.backend.expression.advanced_functions import ( CaseExpression, @@ -1266,7 +1266,7 @@ def _no_such_formatter(formatter_name: str) -> str: # PostgreSQL has no such type -- ``CREATE TYPE ... AS ENUM`` goes through # ``PostgresEnumType`` -- so there is no ``format_data_type_enum`` to reach. "rhosocial.activerecord.backend.expression.types.enum_.EnumType": ( - TypeError, + UnsupportedDataTypeError, "does not support the generic type 'enum'", ), @@ -1346,7 +1346,7 @@ def _no_such_formatter(formatter_name: str) -> str: # UnsupportedFeatureError, because the class is incomplete rather than the # dialect being unable. "rhosocial.activerecord.backend.expression.types._base.DataType": ( - TypeError, + UnsupportedDataTypeError, "does not support the generic type None", ), @@ -1372,11 +1372,11 @@ def _no_such_formatter(formatter_name: str) -> str: # there is no ``format_data_type_binary`` to dispatch to. A dialect gap, not a # defect: the dialect is saying it cannot render them. "rhosocial.activerecord.backend.expression.types.binary.BinaryType": ( - TypeError, + UnsupportedDataTypeError, "does not support the generic type 'binary'", ), "rhosocial.activerecord.backend.expression.types.binary.VarBinaryType": ( - TypeError, + UnsupportedDataTypeError, "does not support the generic type 'varbinary'", ), From 06e30ed470b60e2f6e74f03fe2dd4c93d85e0e8d Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 12:57:50 +0800 Subject: [PATCH 48/81] test: follow suite declaration and auto-id contracts Declare DB-owning directories for xdist grouping; update stale DDL/decimal tests to the new core contracts. --- tests/benchmark/relation/conftest.py | 12 +++++++++++- .../feature/backend/adapters/native/conftest.py | 2 +- .../feature/backend/conftest.py | 2 +- .../feature/backend/execute/conftest.py | 2 +- .../feature/backend/execute/ddl_view/conftest.py | 2 +- .../backend/execute/introspection/conftest.py | 2 +- .../feature/basic/core/conftest.py | 10 ++++++++++ .../feature/connection/conftest.py | 10 ++++++++++ .../feature/query/collation/conftest.py | 10 ++++++++++ 9 files changed, 46 insertions(+), 6 deletions(-) diff --git a/tests/benchmark/relation/conftest.py b/tests/benchmark/relation/conftest.py index 5cb5bf53..df2cd96d 100644 --- a/tests/benchmark/relation/conftest.py +++ b/tests/benchmark/relation/conftest.py @@ -6,6 +6,7 @@ Redis benchmark support is not introduced in this release. The related source snippets are kept as comments for follow-up external cache design. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration from rhosocial.activerecord.backend.options import ExecutionOptions from rhosocial.activerecord.backend.schema import StatementType @@ -62,7 +63,16 @@ class RelationBenchmarkContext: # Redis benchmark is not introduced in this release. Keep the fixture shape as # comments for follow-up external cache design instead of deleting the source. # --------------------------------------------------------------------------- -# @pytest.fixture(scope="session") +# + +# This directory owns a database shared by all its tests within a scenario; +# pin them to one worker so setup/teardown never races on the same database. +DECLARATION = Declaration( + parallel=True, + purpose="Directory-owned PostgreSQL database shared by this test group.", +) + +@pytest.fixture(scope="session") # def _redis_client(): # redis = pytest.importorskip("redis") # try: diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index 1031d1a8..e21444df 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -11,13 +11,13 @@ Extension tables live in ``schema/extension_types.sql`` and are only created by a class fixture that has already established the extension exists. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration import re from pathlib import Path import pytest -from rhosocial.activerecord.testsuite.pytest_plugin import Declaration DECLARATION = Declaration( parallel=True, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py index 78269532..3d27cc7f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py @@ -5,6 +5,7 @@ connection parameters; the database name is derived from the directory that owns the test, so two directories never share tables. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration import os from typing import Any, Dict, Tuple, Type @@ -18,7 +19,6 @@ AsyncPostgresBackend, ) from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig -from rhosocial.activerecord.testsuite.pytest_plugin import Declaration DECLARATION = Declaration( parallel=False, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py index eddb4b17..8dbfaf3d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py @@ -9,9 +9,9 @@ the group key is derived from the test file's own directory, so different execute directories still run in parallel. """ - from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + DECLARATION = Declaration( parallel=True, purpose="PostgreSQL execute tests against each directory-owned database.", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py index 31afef0e..f703465d 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py @@ -1,5 +1,6 @@ # tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py """Fixtures for PostgreSQL materialized view integration tests.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration import pytest import pytest_asyncio @@ -16,7 +17,6 @@ ) from rhosocial.activerecord.backend.options import ExecutionOptions from rhosocial.activerecord.backend.schema import StatementType -from rhosocial.activerecord.testsuite.pytest_plugin import Declaration DECLARATION = Declaration( parallel=True, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py index 152f99b0..1cc5bb0f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py @@ -5,11 +5,11 @@ This module provides fixtures for testing database introspection functionality with PostgreSQL backends. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration import pytest import pytest_asyncio -from rhosocial.activerecord.testsuite.pytest_plugin import Declaration DECLARATION = Declaration( parallel=True, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py index ab5763da..ecfe2ee6 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py @@ -10,6 +10,7 @@ - ``schema``: those three tables, dropped and recreated for every test (function scope), so each test starts from empty tables. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration from pathlib import Path @@ -35,6 +36,15 @@ def _database_name() -> str: return "test_" + "_".join(parts[start:]) + + +# This directory owns a database shared by all its tests within a scenario; +# pin them to one worker so setup/teardown never races on the same database. +DECLARATION = Declaration( + parallel=True, + purpose="Directory-owned PostgreSQL database shared by this test group.", +) + @pytest.fixture(scope="session") def database_config(backend_scenario): """The scenario, its connection configuration, and the database name.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py index e57892a9..ce8d74a3 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py @@ -11,6 +11,7 @@ tests for one directory stay on one worker, while different scenarios are different databases and may run in parallel. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration from functools import partial from pathlib import Path @@ -44,6 +45,15 @@ def _database_name() -> str: return "test_" + "_".join(parts[start:]) + + +# This directory owns a database shared by all its tests within a scenario; +# pin them to one worker so setup/teardown never races on the same database. +DECLARATION = Declaration( + parallel=True, + purpose="Directory-owned PostgreSQL database shared by this test group.", +) + @pytest.fixture(scope="session") def database_config(backend_scenario): """The scenario, its connection configuration, and the directory database name.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py index a27485b1..14cf9442 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py @@ -8,6 +8,7 @@ - ``schema``: the ``searchable_items`` table, dropped and recreated for every test (function scope), so each test starts from an empty table. """ +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration from pathlib import Path @@ -32,6 +33,15 @@ def _database_name() -> str: return "test_" + "_".join(parts[start:]) + + +# This directory owns a database shared by all its tests within a scenario; +# pin them to one worker so setup/teardown never races on the same database. +DECLARATION = Declaration( + parallel=True, + purpose="Directory-owned PostgreSQL database shared by this test group.", +) + @pytest.fixture(scope="session") def database_config(backend_scenario): """The scenario, its connection configuration, and the database name.""" From 479a727cbafb79d2cff455100518fc70b2a2cb9a Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Wed, 18 Nov 2026 23:34:20 +0800 Subject: [PATCH 49/81] feat(ddl): auto-increment suggestions, field generators, and narrowed CI scope --- .github/workflows/test.yml | 8 +- .../backend/impl/postgres/dialect.py | 3 + .../backend/impl/postgres/mixins/__init__.py | 2 + .../backend/impl/postgres/mixins/ddl_table.py | 17 +---- ...nteger_auto_increment_column_suggestion.py | 48 ++++++++++++ tests/benchmark/relation/conftest.py | 2 + .../backend/adapters/native/conftest.py | 1 + .../feature/backend/conftest.py | 1 + .../construct/ddl/test_auto_increment_ddl.py | 38 ++++------ .../dialect/test_protocol_conformance.py | 1 + .../feature/backend/execute/conftest.py | 1 + .../backend/execute/ddl_view/conftest.py | 1 + .../backend/execute/introspection/conftest.py | 1 + .../test_identity_execution.py | 9 ++- .../feature/basic/core/conftest.py | 75 ------------------- .../basic/core/test_basic_mapped_models.py | 10 --- .../core/test_basic_mapped_models_async.py | 1 - .../basic/field_generation/conftest.py | 2 + .../field_generation/test_field_generation.py | 1 + .../test_field_generation_async.py | 1 + .../feature/connection/conftest.py | 1 + .../feature/query/collation/conftest.py | 2 + 22 files changed, 93 insertions(+), 133 deletions(-) create mode 100644 src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d274916a..1e626dec 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -326,7 +326,7 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup test: name: Python ${{ matrix.python-version }} / postgres ${{ matrix.postgres-version }} @@ -439,14 +439,14 @@ jobs: if: matrix.postgres-version != '18' run: | export PYTHONPATH=src:tests - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup - name: Run tests with coverage (only for postgres 18 on Python 3.14) if: matrix.postgres-version == '18' && matrix.python-version == '3.14' run: | export PYTHONPATH=src:tests pip install codecov - python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml - name: Upload coverage to Codecov if: matrix.postgres-version == '18' && matrix.python-version == '3.14' @@ -525,4 +525,4 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup diff --git a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py index a3a918c8..093b703d 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py @@ -265,6 +265,7 @@ PostgresExpressionMixin, PostgresFunctionMixin, PostgresLiteralValueMixin, + PostgresIntegerAutoIncrementColumnSuggestionMixin, ) from .protocols.ddl.type import PostgresTypeSupport @@ -369,6 +370,8 @@ class PostgresDialect( + # Backend suggestion first: no core mixin may shadow its answer. + PostgresIntegerAutoIncrementColumnSuggestionMixin, # The bases below come in bundles: a backend mixin, then the core bundle # it stands in for. The backend's answer has to come first -- a mixin # placed after the class it overrides never wins -- so a new mixin goes diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py index d813594a..ef367094 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py @@ -11,6 +11,7 @@ - extensions: Extension mixins (pgvector, postgis, hstore, etc.) """ +from .integer_auto_increment_column_suggestion import PostgresIntegerAutoIncrementColumnSuggestionMixin from .object_name import PostgresObjectNameMixin from .extension import PostgresExtensionMixin from .materialized_view import PostgresMaterializedViewMixin @@ -137,6 +138,7 @@ from .introspection import PostgresIntrospectionCapabilityMixin __all__ = [ + 'PostgresIntegerAutoIncrementColumnSuggestionMixin', # Core mixins "PostgresObjectNameMixin", "PostgresExtensionMixin", diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py index 26f967f7..b22d6bd9 100644 --- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py @@ -243,15 +243,7 @@ def format_column_definition(self, col_def) -> Tuple[str, tuple]: ) all_params: List[Any] = [] - is_serial = any( - isinstance(constraint.branch, ColumnPrimaryKeyConstraint) - and constraint.branch.is_auto_increment - for constraint in col_def.constraints - ) - if is_serial: - type_sql = self._serial_type_sql(col_def.data_type) - else: - type_sql, _ = col_def.data_type.to_sql() + type_sql, _ = col_def.data_type.to_sql() if not re.fullmatch(r"[A-Za-z0-9_\s(),\[\]]+", type_sql): raise ValueError( f"Invalid data type '{type_sql}': " @@ -264,13 +256,6 @@ def format_column_definition(self, col_def) -> Tuple[str, tuple]: col_sql += attr_sql all_params.extend(attr_params) for constraint in col_def.constraints: - # The auto-increment request was answered by the type above; it - # contributes no clause of its own. - if ( - isinstance(constraint.branch, ColumnPrimaryKeyConstraint) - and constraint.branch.is_auto_increment - ): - continue suffix, params = self.format_column_constraint(constraint) col_sql += suffix all_params.extend(params) diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py new file mode 100644 index 00000000..2ce4e459 --- /dev/null +++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py @@ -0,0 +1,48 @@ +# src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py +"""PostgresIntegerAutoIncrementColumnSuggestionMixin -- postgres's integer auto-increment column suggestion. + +The answer is the backend's own spelling, assembled from its capability +probes where it has one. It is placed first in the dialect bases so no core +mixin can shadow it, and it renders nothing itself -- the returned clause's +formatter owns the SQL spelling. +""" + +from typing import TYPE_CHECKING + +from ....expression.statements import IntegerAutoIncrementColumnSuggestion + +if TYPE_CHECKING: # pragma: no cover + from ....expression.types._base import DataType + + +class PostgresIntegerAutoIncrementColumnSuggestionMixin: + """Suggest postgres's declaration for a generated integer key.""" + + def suggest_integer_auto_increment_column( + self, default_type: "DataType" + ) -> IntegerAutoIncrementColumnSuggestion: + from ....expression.types import BigIntType, IntegerType, SmallIntType + from ..expression.types import ( + PostgresBigSerialType, + PostgresSerialType, + PostgresSmallSerialType, + ) + + # PostgreSQL has no column marker: the SERIAL pseudo-type carries the + # sequence, so auto_increment=False tells the framework to add no + # clause. The width mapping mirrors the engine's three serial types. + for core_type, serial_type in ( + (SmallIntType, PostgresSmallSerialType), + (IntegerType, PostgresSerialType), + (BigIntType, PostgresBigSerialType), + ): + if isinstance(default_type, core_type): + return IntegerAutoIncrementColumnSuggestion(serial_type(self), False) + from ....dialect.exceptions import UnsupportedFeatureError + + raise UnsupportedFeatureError( + self.name, + "AUTO_INCREMENT column", + "SERIAL covers smallint, integer and bigint; " + f"{type(default_type).__name__} is none of them", + ) diff --git a/tests/benchmark/relation/conftest.py b/tests/benchmark/relation/conftest.py index df2cd96d..ccbb153c 100644 --- a/tests/benchmark/relation/conftest.py +++ b/tests/benchmark/relation/conftest.py @@ -68,6 +68,8 @@ class RelationBenchmarkContext: # This directory owns a database shared by all its tests within a scenario; # pin them to one worker so setup/teardown never races on the same database. DECLARATION = Declaration( + # This scope opens a database; the plugin enforces this declaration. + uses_database=True, parallel=True, purpose="Directory-owned PostgreSQL database shared by this test group.", ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py index e21444df..311f75aa 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py @@ -20,6 +20,7 @@ DECLARATION = Declaration( + uses_database=True, parallel=True, purpose="PostgreSQL native type tests (native) against the directory-owned database.", passes_means="the live-database contract of this directory holds on PostgreSQL", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py index 3d27cc7f..53f59e10 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py @@ -21,6 +21,7 @@ from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig DECLARATION = Declaration( + uses_database=True, parallel=False, purpose="Backend-owned PostgreSQL tests; pure-render scopes stay ungrouped.", passes_means="backend-specific behavior matches PostgreSQL semantics", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py index 2ba22424..74e344dc 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py @@ -16,6 +16,7 @@ it explicitly (``IdentityClause``); it is simply not what an auto-increment request means. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import pytest @@ -42,20 +43,20 @@ def dialect(): return PostgresDialect(version=(16, 0, 0)) -def _pk(dialect): - return [ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ] +def _id_column(dialect, data_type): + suggested_type, attributes = auto_increment_parts(dialect, data_type) + return ColumnDefinition( + dialect, "id", suggested_type, + constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))], + attributes=attributes, + ) def _build_table(dialect): return CreateTableStatement( dialect=dialect, table=Table(dialect, 'test_tbl'), columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect=dialect), constraints=_pk(dialect)), + _id_column(dialect, IntegerType(dialect=dialect)), ColumnDefinition(dialect, "name", TextType(dialect=dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), ColumnDefinition(dialect, "flag", BooleanType(dialect=dialect), @@ -83,7 +84,7 @@ def test_boolean_default_true(self, dialect): expr = CreateTableStatement( dialect=dialect, table=Table(dialect, 'bool_test'), columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect=dialect), constraints=_pk(dialect)), + _id_column(dialect, IntegerType(dialect=dialect)), ColumnDefinition(dialect, "flag", BooleanType(dialect=dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]), @@ -96,7 +97,7 @@ def test_timestamp_type(self, dialect): expr = CreateTableStatement( dialect=dialect, table=Table(dialect, 'ts_test'), columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect=dialect), constraints=_pk(dialect)), + _id_column(dialect, IntegerType(dialect=dialect)), ColumnDefinition(dialect, "created_at", TimestampType(dialect=dialect)), ], ) @@ -130,9 +131,7 @@ def test_integer_widths_map_to_their_serial(self): dialect=dialect, table=Table(dialect, "serial_tbl"), columns=[ - ColumnDefinition( - dialect, "id", core_type(dialect=dialect), constraints=_pk(dialect) - ) + _id_column(dialect, core_type(dialect=dialect)) ], ) sql, _ = expr.to_sql() @@ -141,17 +140,10 @@ def test_integer_widths_map_to_their_serial(self): def test_non_integer_auto_increment_is_refused(self): """SERIAL has three widths; anything else is refused, not approximated.""" dialect = PostgresDialect(version=(16, 0, 0)) - expr = CreateTableStatement( - dialect=dialect, - table=Table(dialect, "bad_tbl"), - columns=[ - ColumnDefinition( - dialect, "id", TextType(dialect=dialect), constraints=_pk(dialect) - ) - ], - ) + # The backend suggestion is consulted when the column definition is + # built, so the refusal happens there rather than at render time. with pytest.raises(UnsupportedFeatureError, match="AUTO_INCREMENT column"): - expr.to_sql() + _id_column(dialect, TextType(dialect=dialect)) def test_serial_type_still_spellable_explicitly(self): """A caller that asks for SERIAL by type keeps that path.""" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py index 1183cb5c..d4cc1a9f 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py @@ -159,6 +159,7 @@ def get_postgres_protocols(): dialect_protocols.GraphTableSupport, dialect_protocols.ILIKESupport, dialect_protocols.AutoIncrementColumnSupport, + dialect_protocols.IntegerAutoIncrementColumnSuggestionSupport, dialect_protocols.DatabaseAssignedColumnSupport, dialect_protocols.IdentityColumnSupport, dialect_protocols.GeneratedColumnSupport, diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py index 8dbfaf3d..4b391c4b 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py @@ -13,6 +13,7 @@ DECLARATION = Declaration( + uses_database=True, parallel=True, purpose="PostgreSQL execute tests against each directory-owned database.", passes_means="the live-database contract of the execute directory holds on PostgreSQL", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py index f703465d..b6ba3af2 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py @@ -19,6 +19,7 @@ from rhosocial.activerecord.backend.schema import StatementType DECLARATION = Declaration( + uses_database=True, parallel=True, purpose="PostgreSQL materialized view tests (ddl_view) against the directory-owned database.", passes_means="the live-database contract of this directory holds on PostgreSQL", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py index 1cc5bb0f..83cd9e47 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py @@ -12,6 +12,7 @@ DECLARATION = Declaration( + uses_database=True, parallel=True, purpose="PostgreSQL introspection tests (introspection) against the directory-owned database.", passes_means="the live-database contract of this directory holds on PostgreSQL", diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py index 83dc6590..ab20bbb0 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py @@ -19,6 +19,7 @@ Each verdict is preceded by a sentinel: a deliberately invalid statement must be classified ``REJECTED``, or a null result could be read as acceptance. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import pytest @@ -140,15 +141,15 @@ def _auto_increment_table(dialect, table_name): columns=[ ColumnDefinition( dialect, - "id", - IntegerType(dialect=dialect), + "id"[0], + auto_increment_parts(dialect, IntegerType(dialect=dialect))[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ) ], - ) + attributes=auto_increment_parts(dialect, IntegerType(dialect=dialect))[1]) ], ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py deleted file mode 100644 index ecfe2ee6..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py +++ /dev/null @@ -1,75 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/core/conftest.py -"""L2 backend fixtures for the mapped-model basic tests. - -The directory runs the shared ``basic`` mapped-model tests; the models they -request (``MappedUser``, ``MappedPost``, ``MappedComment``) read and write the -topic's ``users``, ``posts`` and ``comments`` tables, so the schema group is -exactly those three definitions. - -- ``database``: one database per directory (session scope, emptied at start); -- ``schema``: those three tables, dropped and recreated for every test - (function scope), so each test starts from empty tables. -""" -from rhosocial.activerecord.testsuite.pytest_plugin import Declaration - -from pathlib import Path - -import pytest - -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( - CommentDefinition, - PostDefinition, - UserDefinition, -) - -DDL = ExecutionOptions(stmt_type=StatementType.DDL) - -DEFINITIONS = (UserDefinition, PostDefinition, CommentDefinition) - - -def _database_name() -> str: - """Database name from this directory's namespace (below ``feature``).""" - parts = Path(__file__).parent.parts - start = parts.index("feature") + 1 - return "test_" + "_".join(parts[start:]) - - - - -# This directory owns a database shared by all its tests within a scenario; -# pin them to one worker so setup/teardown never races on the same database. -DECLARATION = Declaration( - parallel=True, - purpose="Directory-owned PostgreSQL database shared by this test group.", -) - -@pytest.fixture(scope="session") -def database_config(backend_scenario): - """The scenario, its connection configuration, and the database name.""" - name = _database_name() - return backend_scenario, backend_scenario.make_config(name), name - - -@pytest.fixture(scope="session") -def database(database_config): - """The directory's database, prepared once and left for later files.""" - scenario, config, name = database_config - scenario.reset_database(name) - backend = scenario.backend_class(connection_config=config) - backend.connect() - backend.introspect_and_adapt() - yield backend - backend.disconnect() - - -@pytest.fixture(scope="function", autouse=True) -def schema(database): - """Drop and recreate the tables this directory uses, before every test.""" - fixtures = [definition(database.dialect) for definition in DEFINITIONS] - for fixture in fixtures: - database.execute(*fixture.create_table.to_sql(), options=DDL) - yield - for fixture in reversed(fixtures): - database.execute(*fixture.drop_table.to_sql(), options=DDL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py deleted file mode 100644 index eb892392..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py +++ /dev/null @@ -1,10 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models.py -""" -This module serves as a bridge to execute the generic basic mapped models tests -defined in the `rhosocial-activerecord-testsuite` package against the PostgreSQL backend. - -The fixtures those cases request (including ``mapped_models_fixtures``) come -from the shared ``basic`` topic conftest inherited from the parent directory. -""" - -from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py deleted file mode 100644 index 9fb037a7..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/core/test_basic_mapped_models_async.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py new file mode 100644 index 00000000..a3e5c8d8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py @@ -0,0 +1,2 @@ +"""Use the shared ``basic/field_generation`` database-free test set.""" +from rhosocial.activerecord.testsuite.feature.basic.field_generation.conftest import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py new file mode 100644 index 00000000..8e1ef97c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.field_generation.test_field_generation import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py new file mode 100644 index 00000000..ae6648ba --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.field_generation.test_field_generation_async import * # noqa: F401, F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py index ce8d74a3..f6afccec 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py @@ -50,6 +50,7 @@ def _database_name() -> str: # This directory owns a database shared by all its tests within a scenario; # pin them to one worker so setup/teardown never races on the same database. DECLARATION = Declaration( + uses_database=True, parallel=True, purpose="Directory-owned PostgreSQL database shared by this test group.", ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py index 14cf9442..98495f49 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py @@ -38,6 +38,8 @@ def _database_name() -> str: # This directory owns a database shared by all its tests within a scenario; # pin them to one worker so setup/teardown never races on the same database. DECLARATION = Declaration( + # This scope opens a database; the plugin enforces this declaration. + uses_database=True, parallel=True, purpose="Directory-owned PostgreSQL database shared by this test group.", ) From 1d82b9785dfcd339306aba3b96c682a3a92146c9 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 01:11:09 +0800 Subject: [PATCH 50/81] fix(ddl): restore primary-key identity for long-content models --- .../basic/types_long_content/conftest.py | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py index f0c89920..ca697a6c 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py @@ -1,4 +1,28 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py -"""Use the shared ``basic/types_long_content`` test set.""" +"""Use the shared ``basic/types_long_content`` test set. + +The shared ``LongRow`` / ``AsyncLongRow`` fixtures declare ``id: Optional[int]`` +but no ``__primary_key__``. Since the primary-key-declaration refactor, a bare +``ActiveRecord`` subclass is keyless (``primary_key() is None``), so ``save()`` +no longer writes back the generated id and ``find_one()`` refuses to address +the row. PostgreSQL is one of the few dialects that renders all four content +concepts (text/blob/json/xml), so this group actually runs its round-trip tests +here and is the only backend affected. + +The declaration belongs in the shared fixture, but until it is added there the +postgres bridge restores it locally. Setting the class attribute (rather than +subclassing) keeps the shared fixtures and the imported test module operating +on the very same model objects. +""" from rhosocial.activerecord.testsuite.feature.basic.types_long_content.conftest import * # noqa: F401,F403 +from rhosocial.activerecord.testsuite.feature.basic.fixtures.types_long_content_models import ( + AsyncLongRow, + LongRow, +) + +for _long_row_class in (LongRow, AsyncLongRow): + if _long_row_class.__primary_key__ is None: + _long_row_class.__primary_key__ = "id" + +del _long_row_class From e2483f3f10edfd37b9140a07d309870452497271 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 01:18:41 +0800 Subject: [PATCH 51/81] fix(ddl): gate complex geometry tests on PostGIS availability --- .../feature/basic/types_complex/conftest.py | 91 ++++++++++++++++++- 1 file changed, 90 insertions(+), 1 deletion(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py index e97b4a54..2c2ff486 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py @@ -1,4 +1,93 @@ # tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py -"""Use the shared ``basic/types_complex`` test set.""" +"""Use the shared ``basic/types_complex`` test set, gated on PostGIS. +The shared fixture declares its geometry column through ``CustomType``, which +PostgreSQL renders verbatim: DDL *builds* even when PostGIS is absent, so the +shared capability gate (which only skips when DDL building fails) never fires +and ``CREATE TABLE`` raises ``type "geometry" does not exist`` on a plain +server. This backend bridge adds the missing capability gate locally: + +* the shared ``schema`` fixture is autouse, so every test in the group builds + the GEOMETRY table at setup. We override it as opt-in so declaration-only + tests keep running on servers without PostGIS; +* the tests that actually build or use the table are skipped with a named + reason when the scenario's server has no PostGIS, using the dialect's own + ``is_extension_available`` probe. +""" + +import re +from functools import lru_cache +from pathlib import Path + +import pytest + +import support.postgres +from rhosocial.activerecord.testsuite.feature.basic.fixtures.operations import ( + create_schema, + drop_schema, +) +from rhosocial.activerecord.testsuite.feature.basic.fixtures.types_complex_models import ( + COMPLEX_FIXTURES, +) from rhosocial.activerecord.testsuite.feature.basic.types_complex.conftest import * # noqa: F401,F403 +from rhosocial.activerecord.testsuite.feature.basic.types_complex.conftest import ( + _unsupported_reason, +) + +_SKIP_REASON = "PostGIS not available on this server" + + +@lru_cache(maxsize=None) +def _postgis_available(scenario_name: str) -> bool: + """Ask the scenario's dialect whether PostGIS can be used on its server.""" + scenario = support.postgres.scenario(scenario_name) + backend = scenario.backend_class(connection_config=scenario.make_config("postgres")) + try: + backend.connect() + try: + backend.introspect_and_adapt() + return bool(backend.dialect.is_extension_available("postgis")) + finally: + backend.disconnect() + except Exception: + # A probe we could not perform is not evidence that PostGIS is absent. + # Leave the test to run so a real connection problem surfaces normally. + return True + + +@pytest.fixture(scope="function") +def schema(database): + """Opt-in override of the shared autouse fixture. + + Declaration-only tests must not build the GEOMETRY table at setup: on a + server without PostGIS that would make them error before they can assert + anything. Tests that need the tables request this fixture (directly or + through the ``complex_*_class`` fixtures) as before. + """ + why = _unsupported_reason(database.dialect) + if why is not None: + pytest.skip(why) + create_schema(database, COMPLEX_FIXTURES) + yield + drop_schema(database, COMPLEX_FIXTURES) + + +def pytest_collection_modifyitems(config, items): + """Skip the PostGIS-dependent tests on scenarios without PostGIS.""" + here = Path(__file__).resolve().parent + for item in items: + path = Path(str(item.fspath)).resolve() + if here not in path.parents: + continue + # Only tests that build or use the tables request ``schema`` (directly + # or through the complex_*_class fixtures). Declaration-only tests do + # not, so they keep running on servers without PostGIS. + if "schema" not in item.fixturenames: + continue + match = re.search(r"\[([^\]]+)\]\s*$", item.name) + if match is None: + # No scenario in the node id: let the test run rather than + # guessing about a server we have not identified. + continue + if not _postgis_available(match.group(1)): + item.add_marker(pytest.mark.skip(reason=_SKIP_REASON)) From 70939dfd403c6f90e2a9ab916465a859d6a42b40 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 01:49:05 +0800 Subject: [PATCH 52/81] fix(ddl): probe geometry type directly for the complex-test skip gate --- .../feature/basic/types_complex/conftest.py | 34 +++++++++++++------ 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py index 2c2ff486..ca2e4294 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py @@ -11,8 +11,9 @@ the GEOMETRY table at setup. We override it as opt-in so declaration-only tests keep running on servers without PostGIS; * the tests that actually build or use the table are skipped with a named - reason when the scenario's server has no PostGIS, using the dialect's own - ``is_extension_available`` probe. + reason when the scenario's server has no ``geometry`` type. The catalog is + queried directly: a server can advertise PostGIS as installable while no + database actually has the type, which the extension-name probe cannot tell. """ import re @@ -22,6 +23,8 @@ import pytest import support.postgres +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType from rhosocial.activerecord.testsuite.feature.basic.fixtures.operations import ( create_schema, drop_schema, @@ -34,23 +37,34 @@ _unsupported_reason, ) -_SKIP_REASON = "PostGIS not available on this server" +_SKIP_REASON = "geometry type not available on this server (PostGIS required)" + +_GEOMETRY_TYPE_SQL = "SELECT 1 FROM pg_type WHERE typname = 'geometry' LIMIT 1" @lru_cache(maxsize=None) -def _postgis_available(scenario_name: str) -> bool: - """Ask the scenario's dialect whether PostGIS can be used on its server.""" +def _geometry_type_available(scenario_name: str) -> bool: + """Whether the scenario's server actually has a ``geometry`` type. + + Ask the catalog, not the extension name: PostGIS can be advertised as + installable while the type is missing from the database the tests run in. + Probe ``template1`` because the per-directory test database is created + from it with no explicit TEMPLATE, so the type's presence there decides + whether the test tables can use it. + """ scenario = support.postgres.scenario(scenario_name) - backend = scenario.backend_class(connection_config=scenario.make_config("postgres")) + backend = scenario.backend_class(connection_config=scenario.make_config("template1")) try: backend.connect() try: - backend.introspect_and_adapt() - return bool(backend.dialect.is_extension_available("postgis")) + result = backend.execute( + _GEOMETRY_TYPE_SQL, (), options=ExecutionOptions(stmt_type=StatementType.DQL) + ) + return bool(result.data) finally: backend.disconnect() except Exception: - # A probe we could not perform is not evidence that PostGIS is absent. + # A probe we could not perform is not evidence that the type is absent. # Leave the test to run so a real connection problem surfaces normally. return True @@ -89,5 +103,5 @@ def pytest_collection_modifyitems(config, items): # No scenario in the node id: let the test run rather than # guessing about a server we have not identified. continue - if not _postgis_available(match.group(1)): + if not _geometry_type_available(match.group(1)): item.add_marker(pytest.mark.skip(reason=_SKIP_REASON)) From 5ef59bf169a7e018ece4b4bf9317c49b65f51110 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 11:07:45 +0800 Subject: [PATCH 53/81] test(feature): bridge restructured query/cte/setop/relation/events topics --- .../feature/basic/events/conftest.py | 3 + .../feature/basic/events/core/conftest.py | 3 + .../basic/events/core/test_handlers.py | 3 + .../basic/events/core/test_handlers_async.py | 3 + .../basic/events/core/test_lifecycle.py | 3 + .../basic/events/core/test_lifecycle_async.py | 3 + .../feature/cte/conftest.py | 3 + .../feature/cte/test_composite_pk_cte.py | 9 + .../cte/test_composite_pk_cte_async.py | 9 + .../feature/query/README.md | 5 + .../feature/query/basic/conftest.py | 3 + .../basic/test_composite_pk_query_async.py | 9 + .../basic/test_placeholder_conversion.py | 166 ++++ .../feature/query/column_helpers.py | 93 +++ .../feature/query/conftest.py | 5 +- .../core/test_aggregate_window_families.py | 242 ++++++ .../query/core/test_boolean_connectives.py | 82 ++ .../query/core/test_column_type_support.py | 785 ++++++++++++++++++ .../test_document_and_conversion_families.py | 489 +++++++++++ .../query/core/test_operation_boundaries.py | 390 +++++++++ .../query/core/test_operation_symmetry.py | 113 +++ .../query/core/test_predicate_alias.py | 166 ++++ .../test_string_concatenation_operator.py | 164 ++++ .../core/test_string_value_operations.py | 209 +++++ .../core/test_surface_only_column_types.py | 200 +++++ .../core/test_temporal_value_families.py | 283 +++++++ .../feature/query/core/test_typed_columns.py | 418 ++++++++++ .../query/core/test_value_family_inference.py | 226 +++++ .../query/core/test_value_type_lattice.py | 214 +++++ .../feature/query/joins/conftest.py | 3 + .../query/joins/test_join_on_params.py | 232 ++++++ .../joins/test_join_right_table_resolution.py | 178 ++++ .../feature/query/relation/README.md | 13 + .../feature/query/relation/conftest.py | 7 + .../relation/core/test_async_descriptors.py | 242 ++++++ .../query/relation/core/test_batch_loading.py | 218 +++++ .../query/relation/core/test_cache_result.py | 106 +++ .../relation/core/test_cache_serialization.py | 462 +++++++++++ .../relation/core/test_descriptor_coverage.py | 650 +++++++++++++++ .../core/test_descriptor_db_coverage.py | 352 ++++++++ .../relation/core/test_instance_cache.py | 281 +++++++ .../query/relation/core/test_redis_cache.py | 279 +++++++ .../relation/core/test_relation_management.py | 238 ++++++ .../core/test_relation_modifier_cache.py | 350 ++++++++ .../relation/core/test_relation_validation.py | 402 +++++++++ .../query/relation/core/test_type_resolver.py | 269 ++++++ .../query/relation/core/test_with_modifier.py | 472 +++++++++++ .../feature/query/relation/legacy/conftest.py | 281 +++++++ .../relation/legacy/test_with_integration.py | 242 ++++++ .../query/relation/ordering/conftest.py | 3 + .../ordering/test_has_many_order_by_unit.py | 460 ++++++++++ .../feature/query_integration/conftest.py | 3 + .../test_active_query_set_operation.py | 9 + .../test_active_query_set_operation_async.py | 9 + .../test_cte_query_active_query.py | 9 + .../test_cte_query_active_query_async.py | 9 + .../test_cte_query_set_operation.py | 9 + .../test_cte_query_set_operation_async.py | 9 + .../feature/setop/conftest.py | 3 + .../setop/test_composite_pk_set_operation.py | 9 + .../test_composite_pk_set_operation_async.py | 9 + .../feature/setop/test_set_operation.py | 9 + .../feature/setop/test_set_operation_async.py | 9 + 63 files changed, 10134 insertions(+), 3 deletions(-) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/README.md create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py new file mode 100644 index 00000000..30b0011e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py +"""Use the shared ``basic/events`` L2 environment (SQLite backend).""" +from rhosocial.activerecord.testsuite.feature.basic.events.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py new file mode 100644 index 00000000..4bcf62c1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py +"""Use the shared ``basic/events/core`` L2 environment (SQLite backend).""" +from rhosocial.activerecord.testsuite.feature.basic.events.core.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py new file mode 100644 index 00000000..a8b7c529 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py +"""Bridge file for event handler tests from the testsuite.""" +from rhosocial.activerecord.testsuite.feature.basic.events.core.test_handlers import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py new file mode 100644 index 00000000..eeefa69d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py +"""Bridge file for async event handler tests from the testsuite.""" +from rhosocial.activerecord.testsuite.feature.basic.events.core.test_handlers_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py new file mode 100644 index 00000000..7c39be35 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py +"""Bridge file for event lifecycle tests from the testsuite.""" +from rhosocial.activerecord.testsuite.feature.basic.events.core.test_lifecycle import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py new file mode 100644 index 00000000..ff8bd865 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py +"""Bridge file for async event lifecycle tests from the testsuite.""" +from rhosocial.activerecord.testsuite.feature.basic.events.core.test_lifecycle_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py new file mode 100644 index 00000000..90e9e46d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py +"""Use the shared ``cte`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.cte.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py new file mode 100644 index 00000000..064547d3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py +""" +Bridge file for composite PK CTE query tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.cte.test_composite_pk_cte import * # noqa: F403 +except ImportError: + pytest.skip("composite_pk testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py new file mode 100644 index 00000000..a506d773 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py +""" +Bridge file for composite PK async CTE query tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.cte.test_composite_pk_cte_async import * # noqa: F403 +except ImportError: + pytest.skip("composite_pk testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/README.md b/tests/rhosocial/activerecord_postgres_test/feature/query/README.md new file mode 100644 index 00000000..446745b8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/README.md @@ -0,0 +1,5 @@ +# query tests + +Placeholder - describe this directory's scope, fixtures and parallelism declaration. + +See [feature tests](../README.md) and [tests/README.md](../../../../README.md). diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py new file mode 100644 index 00000000..064db239 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py +"""Use the shared ``query/basic`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.basic.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py new file mode 100644 index 00000000..2208833e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py +""" +Bridge file for composite PK async ActiveQuery tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F403 +except ImportError: + pytest.skip("composite_pk testsuite not available", allow_module_level=True) \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py new file mode 100644 index 00000000..5e2797d0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py @@ -0,0 +1,166 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py +"""Unit tests for convert_qmark_placeholder utility function.""" + +import pytest +from unittest.mock import MagicMock + +from rhosocial.activerecord.query.utils import convert_qmark_placeholder + + +@pytest.fixture +def sqlite_dialect(): + """Create a mock SQLite dialect that uses '?' as placeholder.""" + dialect = MagicMock() + dialect.get_parameter_placeholder.return_value = "?" + return dialect + + +@pytest.fixture +def mysql_dialect(): + """Create a mock MySQL dialect that uses '%s' as placeholder.""" + dialect = MagicMock() + dialect.get_parameter_placeholder.return_value = "%s" + return dialect + + +@pytest.fixture +def postgres_dialect(): + """Create a mock PostgreSQL dialect that uses '%s' as placeholder.""" + dialect = MagicMock() + dialect.get_parameter_placeholder.return_value = "%s" + return dialect + + +class TestSQLiteDialect: + """Tests for SQLite dialect ('?' placeholder — no conversion needed).""" + + def test_no_conversion_needed(self, sqlite_dialect): + """SQLite uses '?' natively, so '?' should remain unchanged.""" + sql = "SELECT * FROM users WHERE name = ? AND age > ?" + assert convert_qmark_placeholder(sqlite_dialect, sql) == sql + + def test_escape_reduces_to_literal(self, sqlite_dialect): + """Escaped \\? should be reduced to literal ? for SQLite.""" + sql = r"col \? 'key'" + assert convert_qmark_placeholder(sqlite_dialect, sql) == "col ? 'key'" + + def test_double_backslash_reduces_to_single(self, sqlite_dialect): + """Escaped \\\\ should be reduced to literal \\ for SQLite.""" + sql = r"path \\?" + assert convert_qmark_placeholder(sqlite_dialect, sql) == "path \\?" + + def test_no_placeholders(self, sqlite_dialect): + """SQL without placeholders should pass through unchanged.""" + sql = "SELECT * FROM users" + assert convert_qmark_placeholder(sqlite_dialect, sql) == sql + + +class TestMySQLDialect: + """Tests for MySQL dialect ('%s' placeholder).""" + + def test_single_placeholder(self, mysql_dialect): + """Single '?' should be converted to '%s'.""" + sql = "SELECT * FROM users WHERE name = ?" + assert convert_qmark_placeholder(mysql_dialect, sql) == "SELECT * FROM users WHERE name = %s" + + def test_multiple_placeholders(self, mysql_dialect): + """Multiple '?' should all be converted to '%s'.""" + sql = "SELECT * FROM users WHERE name = ? AND age > ?" + expected = "SELECT * FROM users WHERE name = %s AND age > %s" + assert convert_qmark_placeholder(mysql_dialect, sql) == expected + + def test_no_placeholders(self, mysql_dialect): + """SQL without placeholders should pass through unchanged.""" + sql = "SELECT * FROM users" + assert convert_qmark_placeholder(mysql_dialect, sql) == sql + + def test_escape_produces_literal_qmark(self, mysql_dialect): + """Escaped \\? should produce literal ? (not %s).""" + sql = r"col \? 'key'" + assert convert_qmark_placeholder(mysql_dialect, sql) == "col ? 'key'" + + +class TestPostgreSQLDialect: + """Tests for PostgreSQL dialect ('%s' placeholder, same as MySQL).""" + + def test_single_placeholder(self, postgres_dialect): + """Single '?' should be converted to '%s'.""" + sql = "SELECT * FROM users WHERE name = ?" + assert convert_qmark_placeholder(postgres_dialect, sql) == "SELECT * FROM users WHERE name = %s" + + def test_multiple_placeholders(self, postgres_dialect): + """Multiple '?' should all be converted to '%s'.""" + sql = "INSERT INTO users (name, age) VALUES (?, ?)" + expected = "INSERT INTO users (name, age) VALUES (%s, %s)" + assert convert_qmark_placeholder(postgres_dialect, sql) == expected + + def test_escape_hstore_operator(self, postgres_dialect): + """Escaped \\? should produce literal ? for PostgreSQL hstore/jsonb operators.""" + sql = r"hstore_col \? 'key'" + assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col ? 'key'" + + def test_escape_pipe_operator(self, postgres_dialect): + """Escaped \\? before | should preserve ?| operator.""" + sql = r"hstore_col \?| array['x']" + assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col ?| array['x']" + + def test_escape_ampersand_operator(self, postgres_dialect): + """Escaped \\? before & should preserve ?& operator.""" + sql = r"hstore_col \?& array['x', 'y']" + assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col ?& array['x', 'y']" + + def test_mixed_placeholders_and_operators(self, postgres_dialect): + """Mix of placeholders and escaped operators should convert correctly.""" + sql = r"SELECT * FROM t WHERE a = ? AND h \?| array['x']" + expected = "SELECT * FROM t WHERE a = %s AND h ?| array['x']" + assert convert_qmark_placeholder(postgres_dialect, sql) == expected + + def test_unescaped_qmark_pipe_is_converted(self, postgres_dialect): + """Unescaped ?| should have ? converted to %s (no special handling).""" + sql = "hstore_col ?| array['x']" + # ? is converted to %s, | stays + assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col %s| array['x']" + + +class TestEdgeCases: + """Edge case tests.""" + + def test_empty_string(self, mysql_dialect): + """Empty string should return empty string.""" + assert convert_qmark_placeholder(mysql_dialect, "") == "" + + def test_only_placeholder(self, mysql_dialect): + """String with only '?' should become '%s'.""" + assert convert_qmark_placeholder(mysql_dialect, "?") == "%s" + + def test_only_escaped(self, mysql_dialect): + """String with only '\\?' should become '?'.""" + assert convert_qmark_placeholder(mysql_dialect, "\\?") == "?" + + def test_consecutive_placeholders(self, mysql_dialect): + """Consecutive '?' should all be converted.""" + assert convert_qmark_placeholder(mysql_dialect, "??") == "%s%s" + + def test_escape_at_end(self, mysql_dialect): + """\\ at end of string without following ? should be preserved.""" + assert convert_qmark_placeholder(mysql_dialect, "test\\") == "test\\" + + def test_double_escape(self, mysql_dialect): + """\\\\? should produce literal \\ followed by placeholder %s.""" + # In Python raw string: r"\\?" = two chars: \, ? + # But in regular string: "\\\\?" = three chars: \, \, ? + # The scanner sees \\ → \, then ? → %s + result = convert_qmark_placeholder(mysql_dialect, "\\\\?") + assert result == "\\%s" + + def test_double_backslash_then_escaped_qmark(self, mysql_dialect): + """\\\\\\? should produce literal \\ followed by literal ?.""" + # Scanner: \\ → \, \? → ? + result = convert_qmark_placeholder(mysql_dialect, "\\\\\\?") + assert result == "\\?" + + def test_placeholder_in_string_literal(self, mysql_dialect): + """The function does NOT parse SQL semantics — ? inside quotes is also converted. + This is by design: users must escape literal ? characters.""" + sql = "SELECT * FROM t WHERE col = '?'" + assert convert_qmark_placeholder(mysql_dialect, sql) == "SELECT * FROM t WHERE col = '%s'" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py b/tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py new file mode 100644 index 00000000..777a48ca --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py @@ -0,0 +1,93 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py +"""Test-side helpers for the column-class selection path, and its canonical list. + +The production path is ``base/field_proxy.py``: ``Model.c.`` asks the +model for the field's column-type declaration (dialect-free), then +``FieldAccessor`` selects the class the model's backend answers. This module +mirrors that selection step for a bare annotation, so a test can build a column +without declaring a model. + +``COMMON_TYPES`` is the test-side name for the framework-modelled Python types +every backend must answer for. The list itself now lives in the framework +(``base/framework_types.FRAMEWORK_PYTHON_TYPES``) because two dialect tables -- +the column-class table and the suggested storage-type table -- are keyed by it, +and stating it twice is how the two would drift. The tests hold each backend to +the framework's list, not to a second copy of it. + +Deliberately **not** a fallback: an annotation the selection cannot classify +raises :class:`ColumnTypeResolutionError` exactly as ``Model.c.`` +would, so a test that builds a column from a bad annotation fails here for the +same reason the model would, and the two cannot drift apart. +""" + +from typing import Any, Optional, Tuple, Type + +from rhosocial.activerecord.backend.expression.column_types import ColumnBase +from rhosocial.activerecord.backend.expression.core import Column +from rhosocial.activerecord.base.framework_types import FRAMEWORK_PYTHON_TYPES +from rhosocial.activerecord.base.field_proxy import ( + ColumnTypeResolutionError, + FieldAccessor, +) + +#: The framework-modelled Python types, in declared reading order. The order +#: matters where a subclass walk meets an ambiguous annotation: ``bool`` ahead +#: of ``int``, and ``enum.Enum`` tested before the walk (a ``(int, Enum)`` stays +#: an enum). The list lives in the framework because both dialect tables are +#: keyed by it; this name is the test-side alias. +COMMON_TYPES: Tuple[Any, ...] = FRAMEWORK_PYTHON_TYPES + + +def resolve_column_class(dialect: Any, annotation: Any, declared: Any = None) -> Type[ColumnBase]: + """The class *dialect* selects for *annotation*. + + The field accessor's own selection step, invoked without a model. *declared* + is the field's column-type declaration when a test exercises one; ``None`` + asks the backend's tables. + """ + return FieldAccessor._select_column_class(dialect, annotation, declared) + + +def build_column( + dialect: Any, + column_name: str, + annotation: Any, + table: Optional[str] = None, + schema_name: Optional[str] = None, + column_type: Any = None, +) -> ColumnBase: + """Build the column expression *dialect* selects for *annotation*. + + Args: + dialect: The dialect to select through. Selection is per-backend by + design, so a test that wants a specific column class must say which + backend's answer it is asking for. + column_name: The SQL name to render. + annotation: The Python annotation, ``Annotated`` / ``Optional`` included. + table: Optional table qualifier. + schema_name: Optional schema qualifier. + column_type: A ``UseColumnType`` when the test is exercising an explicit + declaration; ``None`` asks the backend's tables. + + Returns: + The constructed column expression. + + Raises: + ColumnTypeResolutionError: The backend's tables have no column class for + *annotation*, or answered ``None`` for its entry. + """ + column_class = resolve_column_class(dialect, annotation, column_type) + if column_class is Column: + # The untyped column keeps its own narrower constructor and can only + # arrive by being declared explicitly, so this is a shape difference + # rather than a fallback. + return Column(dialect, column_name, table=table, schema_name=schema_name) + return column_class(dialect, column_name, table=table, schema_name=schema_name) + + +__all__ = [ + "COMMON_TYPES", + "ColumnTypeResolutionError", + "build_column", + "resolve_column_class", +] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py index 14b936c8..8d381eed 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py @@ -1,9 +1,8 @@ # tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py -""" -Pytest configuration for query feature tests. +"""Pytest configuration for query feature tests. This file imports fixtures from the corresponding testsuite, making them available to the tests in this directory. """ -from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F403 +from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py new file mode 100644 index 00000000..19e7dfbd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py @@ -0,0 +1,242 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_aggregate_window_families.py +"""What aggregating and windowing a value gives back. + +Each aggregate is its own node class now, so the identity of the function +travels on the node instead of inside a generic name string: COUNT is a +CountFunction, SUM a SumFunction, and so on. A count is a whole number however +wide the thing counted is; an average is numeric whatever it averages; MIN and +MAX hand back something of the operand's kind, which the node cannot know, so +they offer only the operations every value has. + +A window function is either a count or a value from another row, and confusing +the two is how a name column ends up arithmetic. ROW_NUMBER counts; LAG +borrows. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_aggregate_window_families.py +import pytest + +from rhosocial.activerecord.backend.expression.declared import ( + IntegerAnnotation, + NumberAnnotation, + TextAnnotation, +) +from rhosocial.activerecord.backend.expression import ( + AvgFunction, + CountFunction, + FunctionCall, + MaxFunction, + MinFunction, + SumFunction, +) +from rhosocial.activerecord.backend.expression.value_types import ( + ArrayValue, + BooleanValue, + JSONValue, + NumericValue, + OpaqueValue, + TemporalValue, + TextValue, +) +from rhosocial.activerecord.backend.expression import functions as F + + +@pytest.fixture +def dialect(): + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + d = SQLiteDialect() + d._version = (3, 46, 1) + return d + + +@pytest.fixture +def columns(dialect): + from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column + + return { + "int": build_column(dialect, "i", int), + "float": build_column(dialect, "f", float), + "str": build_column(dialect, "s", str), + "json": build_column(dialect, "j", dict), + } + + +# --------------------------------------------------------------------------- +# Counting +# --------------------------------------------------------------------------- + + +def test_count_is_always_a_whole_number(dialect, columns): + """However wide the thing counted, the answer is a number of rows.""" + for column in columns.values(): + assert isinstance(F.count(dialect, column), CountFunction) + + +def test_count_takes_arithmetic_and_not_string_operations(dialect, columns): + count = F.count(dialect, columns["int"]) + assert hasattr(count, "__add__") + assert not hasattr(count, "upper") + + +# --------------------------------------------------------------------------- +# Averaging widens +# --------------------------------------------------------------------------- + + +def test_avg_is_numeric_whatever_it_averages(dialect, columns): + """Averaging whole numbers gives a fraction, so the family has to allow + one. SQL Server is the exception that returns an integer here, which is + exactly why it is not something to build an operation surface on.""" + for column in columns.values(): + assert isinstance(F.avg(dialect, column), AvgFunction) + + +# --------------------------------------------------------------------------- +# Adding, minimising and maximising are their own node classes +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "factory, node_class", + [("sum_", SumFunction), ("min_", MinFunction), ("max_", MaxFunction)], +) +def test_a_reduction_is_its_own_node_class(dialect, columns, factory, node_class): + """The reduction's identity is the node class, not a name string. + + SUM / MIN / MAX used to be guessed into a value family from the operand's + column class; now each is its own node, and the operand kind does not + change which node comes back. + """ + reduce_it = getattr(F, factory) + for column in columns.values(): + assert isinstance(reduce_it(dialect, column), node_class) + + +@pytest.mark.parametrize( + "factory, node_class", + [("sum_", SumFunction), ("min_", MinFunction), ("max_", MaxFunction)], +) +def test_a_literal_input_is_still_the_classed_node(dialect, factory, node_class): + """A literal operand does not change which node comes back. + + The reduction is classed by the function, not inferred from the operand + kind, so a literal -- which declares no kind -- yields the same node a + column would. + """ + result = getattr(F, factory)(dialect, 1) + assert isinstance(result, node_class) + + +def test_min_does_not_guess_the_operand_family(dialect, columns): + """MIN hands back something of the operand's kind, which the node cannot + know, so it offers only the operations every value has rather than + guessing a family from the operand.""" + result = F.min_(dialect, columns["str"]) + assert isinstance(result, MinFunction) + assert not isinstance(result, (NumberAnnotation, TextAnnotation)) + assert hasattr(result, "is_null") + + +# --------------------------------------------------------------------------- +# Building a document or a sequence +# --------------------------------------------------------------------------- + + +def test_building_a_json_aggregate_gives_json(dialect, columns): + assert isinstance(F.json_objectagg(dialect, columns["int"], columns["str"]), JSONValue) + assert isinstance(F.json_arrayagg(dialect, columns["json"]), JSONValue) + + +def test_collecting_into_an_array_gives_an_array(dialect, columns): + assert isinstance(F.array_agg(dialect, columns["int"]), ArrayValue) + + +# --------------------------------------------------------------------------- +# Windowing: a count, or a value from another row +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("factory", ["row_number", "rank", "dense_rank"]) +def test_a_rank_is_a_whole_number(dialect, factory): + for windowed in (getattr(F, factory)(dialect),): + assert isinstance(windowed, NumericValue) + assert hasattr(windowed, "__add__") + assert not hasattr(windowed, "upper") + + +@pytest.mark.parametrize( + "factory, extra", + [("lag", ()), ("lead", ()), ("first_value", ()), ("last_value", ()), ("nth_value", (2,))], +) +def test_a_value_from_another_row_keeps_its_family(dialect, columns, factory, extra): + """LAG over a name column is a name, not a count. + + Which is asserted by the arithmetic that is *absent*: a name is not a + number, so no ``sqrt``. The string operations are present, because the + result genuinely is a string -- it was ``not hasattr(windowed, "upper")`` + before the class replaced the tag, and that assertion is what the tag was + costing: the node carried ``family="string"`` while offering none of the + string surface, so a caller could not tell from the object which operations + it had. Now the class says it, and the operations come with it. + """ + windowed = getattr(F, factory)(dialect, columns["str"], *extra) + assert isinstance(windowed, TextAnnotation) + assert hasattr(windowed, "like") + assert not hasattr(windowed, "sqrt") + + +def test_lag_over_a_float_column_is_fractional(dialect, columns): + assert isinstance(F.lag(dialect, columns["float"]), NumberAnnotation) + + +# --------------------------------------------------------------------------- +# The node states its family, and the round trip survives it +# --------------------------------------------------------------------------- + + +def test_a_typed_aggregate_reports_its_family_for_introspection(dialect, columns): + """Introspection has to see what a result is, or nothing downstream can + read it. + + It used to read ``get_params()["family"]``. That keyword is gone: it + duplicated the class, and a tag that can disagree with the class it sits on + is worse than no tag at all. The class is the introspection surface now, so + this asserts the class -- which is what a caller would have branched on + anyway. + """ + result = F.count(dialect, columns["int"]) + assert isinstance(result, CountFunction) + + +def test_a_typed_window_reports_its_family_for_introspection(dialect, columns): + """Same for a window function: the class, not the removed ``family`` tag.""" + result = F.lag(dialect, columns["int"]) + assert isinstance(result, IntegerAnnotation) + + +def test_an_untyped_aggregate_reports_no_family(dialect, columns): + """A node constructed directly is the untyped one, and says so by being it. + + ``get_params()["family"] is None`` was how this used to be checked. There is + no ``family`` parameter to be ``None`` now, so the assertion is the class: + a bare ``FunctionCall`` is not a typed value, which is the same + statement without the tag that could contradict it. + """ + result = FunctionCall(dialect, "COUNT", columns["int"], is_aggregate=True) + assert not isinstance( + result, + ( + ArrayValue, + BooleanValue, + JSONValue, + NumericValue, + OpaqueValue, + TemporalValue, + TextValue, + ), + ) +def test_declaring_a_family_does_not_change_the_sql(dialect, columns): + """Typing is a surface decision, never a rendering one.""" + assert F.count(dialect, columns["int"]).to_sql()[0] == "COUNT(\"i\")" + assert F.lag(dialect, columns["int"]).to_sql()[0] == "LAG(\"i\", ?)" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py new file mode 100644 index 00000000..c3957152 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py @@ -0,0 +1,82 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_boolean_connectives.py +"""A value's connectives keep the value type; a predicate's stay predicates. + +``p1 & p2`` combines predicates for a WHERE clause. A truth *value* needs the +same three operators with a different result: ``(flag & other)`` must be +something a SELECT list can carry, so it stays a boolean value +(:class:`LogicalValue`) with the same SQL. One implementation, +dispatched by the receiver, which is what these tests pin. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_boolean_connectives.py +import pytest + +from rhosocial.activerecord.backend.expression import BooleanColumn +from rhosocial.activerecord.backend.expression.bases import SQLPredicate, SQLValue +from rhosocial.activerecord.backend.expression.core import LogicalValue +from rhosocial.activerecord.backend.expression.predicates import LogicalPredicate + + +@pytest.fixture +def dialect(): + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + return SQLiteDialect() + + +def test_a_boolean_values_connectives_keep_the_value_type(dialect): + flag = BooleanColumn(dialect, "flag") + other = BooleanColumn(dialect, "other") + + combined = flag & other + assert isinstance(combined, LogicalValue) + assert isinstance(combined, SQLValue) + assert not isinstance(combined, SQLPredicate) + + sql, params = combined.to_sql() + assert "AND" in sql and params == () + + +def test_a_value_can_be_negated_and_chained(dialect): + flag = BooleanColumn(dialect, "flag") + other = BooleanColumn(dialect, "other") + + assert isinstance(~flag, LogicalValue) + + chained = (flag & other) | flag + assert isinstance(chained, LogicalValue) + assert "OR" in chained.to_sql()[0] + + +def test_a_predicate_combination_stays_a_predicate(dialect): + flag = BooleanColumn(dialect, "flag") + other = BooleanColumn(dialect, "other") + + combined = flag.is_true() & other.is_true() + assert isinstance(combined, LogicalPredicate) + assert isinstance(combined, SQLPredicate) + assert not isinstance(combined, SQLValue) + + assert isinstance(~flag.is_true(), LogicalPredicate) + + +def test_a_value_expression_can_be_aliased_into_a_select_list(dialect): + flag = BooleanColumn(dialect, "flag") + aliased = (flag & flag).as_("both") + sql, params = aliased.to_sql() + assert "AND" in sql and "both" in sql + + +def test_a_boolean_value_can_be_compared(dialect): + flag = BooleanColumn(dialect, "flag") + predicate = (flag & flag) == flag + assert isinstance(predicate, SQLPredicate) + + +def test_both_receivers_render_the_same_connective(dialect): + flag = BooleanColumn(dialect, "flag") + other = BooleanColumn(dialect, "other") + + value_sql = (flag & other).to_sql()[0] + predicate_sql = (flag.is_true() & other.is_true()).to_sql()[0] + assert "AND" in value_sql and "AND" in predicate_sql diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py new file mode 100644 index 00000000..52e90bb0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py @@ -0,0 +1,785 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_column_type_support.py +"""The column-type support protocol: entry contract, backend authority, failures. + +Four questions, and nothing here needs a database to answer them: + +1. **Is the entry contract kept?** Every backend answers the common Python + types the tests enumerate, so a model never meets a table with a hole. +2. **Whose answer is it?** The backend's own tables, always: a dialect that + overrides one entry changes exactly that entry, and a backend's extra table + carries its own Python types without touching the common ones. +3. **What does a declared column type look like, and what fails loudly?** + ``Model.column_type()`` presents the declaration as written (a + ``UseColumnType`` marker, a class, or a sequence); the field accessor + selects from it; ``Any``, a bare ``Union``, an unregistered custom class + and a ``None`` table entry all raise. +4. **What do the declaration accessors present?** ``column_type`` and + ``column_data_type`` are dialect-free declarations -- no fallback, no + selection -- and the batch method mirrors the data-type one. + +Plus the boolean algebra surface and its literal discipline: ``TRUE``/``FALSE`` +as keywords, never ``1``/``0``, which PostgreSQL rejects outright +(``operator does not exist: boolean = integer``). +""" + +import datetime +import decimal +import enum +import typing +import uuid +from typing import Any, ClassVar, Dict, List, Optional, Union + +import pytest + +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, +) +from rhosocial.activerecord.backend.dialect.mixins import ColumnTypeMixin +from rhosocial.activerecord.backend.dialect.protocols import ColumnTypeSupport +from rhosocial.activerecord.backend.expression.column_types import ( + ArrayColumn, + ColumnBase, + TimestampColumn, + IntegerColumn, + JSONColumn, + NumericColumn, + StringColumn, + UUIDColumn, +) +from rhosocial.activerecord.backend.expression.types import JsonType +from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect +from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect +from rhosocial.activerecord.backend.impl.sqlite.mixins.column_type import ( + SQLITE_COLUMN_TYPES, +) +from rhosocial.activerecord.base.field_proxy import ( + ColumnTypeResolutionError, + FieldProxy, +) +from rhosocial.activerecord.base.fields import DDLAnnotation, UseColumnType, UseSqlType +from rhosocial.activerecord.model import ActiveRecord + +from rhosocial.activerecord_postgres_test.feature.query.column_helpers import ( + COMMON_TYPES, + build_column, + resolve_column_class, +) + + +def sqlite_dialect(version=(3, 46, 1)): + """A version-adapted SQLite dialect. + + ``supports_json_type`` reads ``self.version``, and an unadapted dialect + raises rather than answering -- so every test that renders needs a version. + 3.46 is a real release well past the 3.38.0 line where the JSON functions + became part of SQLite proper. + """ + return SQLiteDialect(version=version) + + +def dummy_dialect(): + """An adapted dummy dialect: the dialect-less baseline, not a server.""" + dialect = DummyDialect() + dialect._version = (3, 46, 1) + return dialect + + +def resolve(dialect, annotation, declared=None): + """The selection step, for the cases below that read as "resolve this".""" + return resolve_column_class(dialect, annotation, declared) + + +_ENTRY_IDS = [getattr(entry, "__name__", str(entry)) for entry in COMMON_TYPES] + + +# --------------------------------------------------------------------------- +# 1. The entry contract +# --------------------------------------------------------------------------- + + +def test_the_canonical_entry_list_is_the_declared_order(): + """Order is the protocol's reading order, and the list lives in the framework. + + Both dialect tables are keyed by ``FRAMEWORK_PYTHON_TYPES``, so the order + stated here is the one both lookups walk. The six complex families come last + because the subclass walk must meet ``bool`` before ``int`` and must meet + ``Geometry`` only for a geometry annotation. + """ + assert _ENTRY_IDS == [ + "bool", + "int", + "float", + "Decimal", + "str", + "bytes", + "bytearray", + "date", + "time", + "datetime", + "timedelta", + "UUID", + "dict", + "list", + "tuple", + "set", + "frozenset", + "Enum", + "Geometry", + "Vector", + "BitString", + "Range", + "Multirange", + "MacAddress", + ] + + +def test_entry_list_has_no_duplicates(): + """A duplicate would make 'answer every entry' ambiguous.""" + assert len(set(COMMON_TYPES)) == len(COMMON_TYPES) + + +def test_the_protocol_is_structural(): + """A dialect satisfies it by answering the two tables, nothing else.""" + dialect = sqlite_dialect() + assert isinstance(dialect, ColumnTypeSupport) + assert callable(dialect.suggested_column_types) + assert callable(dialect.suggested_extra_column_types) + + +def _assert_answered_or_refused(dialect, entry): + """Every framework type is either answered with a class or refused with None. + + ``None`` is the protocol's stated answer for "no column class for this value + family", so the resolution must fail with that message rather than fall + through to another table or pick a class anyway. + """ + if dialect.suggested_column_types()[entry] is None: + with pytest.raises(ColumnTypeResolutionError, match="has no column class"): + resolve(dialect, entry) + else: + assert issubclass(resolve(dialect, entry), ColumnBase) + + +@pytest.mark.parametrize("entry", COMMON_TYPES, ids=_ENTRY_IDS) +def test_every_entry_resolves_or_is_refused_by_sqlite(entry): + _assert_answered_or_refused(sqlite_dialect(), entry) + + +@pytest.mark.parametrize("entry", COMMON_TYPES, ids=_ENTRY_IDS) +def test_every_entry_resolves_or_is_refused_by_the_dummy_baseline(entry): + _assert_answered_or_refused(dummy_dialect(), entry) + + +def test_boolean_is_its_own_entry_not_an_integer(): + """``bool`` is an ``int`` subclass; the entry order is what keeps them apart. + + Without the order, ``bool`` would walk to ``int`` and a truth-value field + would offer integer arithmetic -- which MySQL and SQLite would happily + execute on a column holding 0/1. + """ + assert COMMON_TYPES.index(bool) < COMMON_TYPES.index(int) + assert resolve(sqlite_dialect(), bool) is not resolve(sqlite_dialect(), int) + + +def test_date_and_time_are_separate_entries_sharing_a_column_class(): + """They are distinct entries because the framework asks about each of them. + + They answer the same column class today, which is a modelling gap the entry + list is what will eventually close (splitting ``TimestampColumn`` by operation + set). Asserting the shared answer keeps that gap visible: when one of them + splits, this test is what notices. + """ + assert resolve(sqlite_dialect(), datetime.date) is TimestampColumn + assert resolve(sqlite_dialect(), datetime.time) is TimestampColumn + + +# --------------------------------------------------------------------------- +# 2. The backend is the authority +# --------------------------------------------------------------------------- + + +class OverridingDialect(SQLiteDialect): + """A backend that disagrees with SQLite about exactly one entry. + + Its table is SQLite's own with one entry replaced, so "the seventeen other + answers are untouched" is a statement about this dialect versus the backend + it extends. ``str`` answers with a class neither would have picked, which is + what makes the authority observable: a core-side table consulted first would + ignore this. + """ + + def suggested_column_types(self): + table = super().suggested_column_types() + table[str] = NumericColumn + return table + + +class RefusingDialect(SQLiteDialect): + """A backend with no column class for one entry. + + The honest "this backend has none", which is what MySQL 5.6 and Firebird + would have to say about a value family they cannot carry. It must reach the + caller as a failure rather than as a fallback to another table. + """ + + def suggested_column_types(self): + table = super().suggested_column_types() + table[dict] = None + return table + + +class Complex: + """A user type the framework does not model; carried by the extra table.""" + + +class ExtendingDialect(SQLiteDialect): + """A backend with a Python type of its own, in its own table.""" + + def suggested_extra_column_types(self): + return {Complex: JSONColumn} + + +def test_backend_override_changes_only_its_own_entry(): + """One overridden entry, one changed answer, seventeen untouched.""" + dialect = OverridingDialect(version=(3, 46, 1)) + + assert resolve(dialect, str) is NumericColumn + assert resolve(sqlite_dialect(), str) is StringColumn + + for entry in COMMON_TYPES: + if entry is str: + continue + _assert_answered_or_refused(dialect, entry) + _assert_answered_or_refused(sqlite_dialect(), entry) + + +def test_a_backend_may_extend_with_an_entry_of_its_own(): + """The extension path for a Python type the framework does not model.""" + dialect = ExtendingDialect(version=(3, 46, 1)) + + assert resolve(dialect, Complex) is JSONColumn + assert resolve(dialect, Optional[Complex]) is JSONColumn + # ...and the common entries keep working alongside it. + assert resolve(dialect, int) is IntegerColumn + + +def test_the_returned_tables_are_copies(): + """A caller walking a table must not mutate what the next field reads.""" + dialect = sqlite_dialect() + table = dialect.suggested_column_types() + table.clear() + assert set(dialect.suggested_column_types()) == set(COMMON_TYPES) + + +def test_the_mixin_withholds_the_common_table(): + """There is no inherited table: a dialect that does not answer is told so.""" + + class Bare(ColumnTypeMixin): + pass + + with pytest.raises(NotImplementedError): + Bare().suggested_column_types() + assert Bare().suggested_extra_column_types() == {} + + +def test_sqlite_answers_exactly_the_framework_types(): + """Its table is complete, and none of the twenty-four entries is refused. + + The six complex families used to be ``None`` for a real reason -- SQLite + has no spatial or vector operation -- but the core classes they now name + promise only the column surface (alias, null tests, casting, collation), + which SQLite does execute on a value it stores as text or JSON. + """ + from rhosocial.activerecord.backend.expression.column_types import ( + BitStringColumn, + GeometryColumn, + IntervalColumn, + MacAddressColumn, + MultirangeColumn, + RangeColumn, + VectorColumn, + ) + + assert set(SQLITE_COLUMN_TYPES) == set(COMMON_TYPES) + assert all(value is not None for value in SQLITE_COLUMN_TYPES.values()) + assert resolve(sqlite_dialect(), Geometry) is GeometryColumn + assert resolve(sqlite_dialect(), Vector) is VectorColumn + assert resolve(sqlite_dialect(), BitString) is BitStringColumn + assert resolve(sqlite_dialect(), Range) is RangeColumn + assert resolve(sqlite_dialect(), Multirange) is MultirangeColumn + assert resolve(sqlite_dialect(), MacAddress) is MacAddressColumn + assert resolve(sqlite_dialect(), datetime.timedelta) is IntervalColumn + + +def test_the_dummy_dialect_states_its_own_baseline(): + """It stands for no server, so it states no backend's answers. + + SQLite is built into core and the dummy is the other dialect core ships, so + the two are easy to conflate. They are deliberately different: the dummy is + the dialect-less default a test reads, and copying a real backend's table + into it would make "what does the portable baseline say" unanswerable. + """ + dummy = dummy_dialect() + assert set(dummy.suggested_column_types()) == set(COMMON_TYPES) + assert resolve(dummy, list) is ArrayColumn + assert resolve(sqlite_dialect(), list) is JSONColumn + # ``Decimal`` was merged into NumericColumn on both sides; asserting the + # shared answer keeps the merge deliberate. + assert resolve(dummy, decimal.Decimal) is NumericColumn + assert resolve(sqlite_dialect(), decimal.Decimal) is NumericColumn + + +# --------------------------------------------------------------------------- +# 3. Declared column types: three forms, and what is refused +# --------------------------------------------------------------------------- + + +def test_use_column_type_overrides_the_tables(): + """Naming a class bypasses the recommendation, and only the recommendation.""" + assert resolve(sqlite_dialect(), int, UseColumnType(StringColumn)) is StringColumn + + +def test_a_bare_class_declaration_answers(): + """``column_type`` may present a class directly; the selector accepts it.""" + assert resolve(sqlite_dialect(), int, StringColumn) is StringColumn + + +def test_a_single_candidate_sequence_answers(): + """A one-element sequence is a declaration with one candidate.""" + assert resolve(sqlite_dialect(), int, [StringColumn]) is StringColumn + + +def test_a_multi_candidate_sequence_is_refused(): + """Choosing among candidates needs the capability declaration, which is not here. + + Taking the first silently would make the declaration a lie the caller + cannot see. + """ + with pytest.raises(ColumnTypeResolutionError, match="capability"): + resolve(sqlite_dialect(), int, [StringColumn, JSONColumn]) + + +def test_an_empty_sequence_is_refused(): + with pytest.raises(ColumnTypeResolutionError, match="empty sequence"): + resolve(sqlite_dialect(), int, []) + + +def test_a_non_declaration_is_refused(): + with pytest.raises(ColumnTypeResolutionError, match="not a column-type declaration"): + resolve(sqlite_dialect(), int, "StringColumn") + + +def test_use_column_type_saves_an_annotation_no_table_could_classify(): + """The escape hatch is what makes every other failure actionable.""" + assert resolve(sqlite_dialect(), Any, UseColumnType(StringColumn)) is StringColumn + + +def test_use_column_type_with_several_classes_is_refused(): + """Multi-candidate selection needs the capability declaration, which is not here. + + Declaring two classes is a request to negotiate with the backend, and there + is nothing to ask yet. Taking the first silently would make the declaration + a lie the caller cannot see. + """ + with pytest.raises(TypeError, match="capability"): + UseColumnType(StringColumn, JSONColumn) + + +def test_use_column_type_with_no_classes_is_refused(): + with pytest.raises(TypeError, match="at least one"): + UseColumnType() + + +@pytest.mark.parametrize( + "bad_factory, why", + [ + (str, "builtin"), + (lambda: "StringColumn", "name"), + (lambda: StringColumn(sqlite_dialect(), "x"), "instance"), + ], + ids=["builtin", "string", "instance"], +) +def test_use_column_type_rejects_non_column_classes(bad_factory, why): + """A column class is a type, never an instance -- an instance carries state. + + Built through factories because a column instance needs a dialect, and + constructing one at collection time would put a database-free object in the + module preamble. + """ + with pytest.raises(TypeError, match="ColumnBase"): + UseColumnType(bad_factory()) + + +def test_use_column_type_is_not_a_ddl_annotation(): + """Strict independence: the DDL collector must never see it. + + ``UseSqlType`` is a ``DDLAnnotation``; this one deliberately is not. If it + were, the DDL layer would be one refactor away from inferring a storage type + from a column declaration -- the exact coupling the independence ruling + forbids. + """ + assert not isinstance(UseColumnType(StringColumn), DDLAnnotation) + + +def test_use_column_type_is_independent_of_use_sql_type(): + """Both declared, and neither is inferred from the other.""" + Annotated = getattr(typing, "Annotated", None) + if Annotated is None: + pytest.skip("typing.Annotated requires Python 3.9+") + + annotation = Annotated[int, UseSqlType(JsonType()), UseColumnType(StringColumn)] + declared = [m for m in annotation.__metadata__ if isinstance(m, UseColumnType)][0] + + assert resolve(sqlite_dialect(), annotation, declared) is StringColumn + # The DDL side still sees only its own candidate. + assert [type(d).__name__ for d in annotation.__metadata__] == [ + "UseSqlType", + "UseColumnType", + ] + assert UseSqlType(JsonType()).data_type.name == "json" + + +# --------------------------------------------------------------------------- +# 4. The model-side declaration accessors (dialect-free) +# --------------------------------------------------------------------------- + + +def _declared_model(dialect): + Annotated = getattr(typing, "Annotated", None) + if Annotated is None: + pytest.skip("typing.Annotated requires Python 3.9+") + + class Declared(ActiveRecord): + @classmethod + def table_name(cls): + return "declared_types" + + @classmethod + def primary_key(cls): + return "id" + + c: ClassVar[FieldProxy] = FieldProxy() + + id: int + label: Annotated[str, UseColumnType(JSONColumn)] + payload: Annotated[dict, UseSqlType(JsonType())] + + Declared.__backend__ = type("B", (), {"dialect": dialect})() + return Declared + + +def test_column_type_presents_the_declaration_or_none(): + """``column_type`` presents; it does not resolve and does not fall back.""" + Model = _declared_model(sqlite_dialect()) + + declared = Model.column_type("label") + assert isinstance(declared, UseColumnType) + assert declared.column_class is JSONColumn + assert Model.column_type("id") is None + + +def test_two_column_type_declarations_on_one_field_are_refused(): + Annotated = getattr(typing, "Annotated", None) + if Annotated is None: + pytest.skip("typing.Annotated requires Python 3.9+") + + class Bad(ActiveRecord): + @classmethod + def table_name(cls): + return "bad_declarations" + + @classmethod + def primary_key(cls): + return "id" + + c: ClassVar[FieldProxy] = FieldProxy() + + id: int + broken: Annotated[ + Any, + UseColumnType(StringColumn), + UseColumnType(JSONColumn), + ] + + Bad.__backend__ = type("B", (), {"dialect": sqlite_dialect()})() + with pytest.raises(TypeError, match="UseColumnType declarations"): + Bad.column_type("broken") + + +def test_column_data_type_presents_the_declaration_or_none(): + """The renamed accessor: dialect-free declaration, no inference.""" + Model = _declared_model(sqlite_dialect()) + + assert Model.column_data_type("id") is None + marker = Model.column_data_type("payload") + assert isinstance(marker, UseSqlType) + assert isinstance(marker.data_types[0], JsonType) + + +def test_columns_data_type_batches(): + Model = _declared_model(sqlite_dialect()) + + batch = Model.columns_data_type() + assert set(batch) == {"id", "label", "payload"} + assert batch["payload"] is Model.column_data_type("payload") + + +def test_the_accessor_path_end_to_end(): + """The declared class wins where the table would have answered otherwise.""" + Model = _declared_model(sqlite_dialect()) + + assert type(Model.c.label) is JSONColumn # declared + assert type(Model.c.id) is IntegerColumn # selected from the table + assert type(Model.c.payload) is JSONColumn # table, not the DDL declaration + + +# --------------------------------------------------------------------------- +# 5. Failures: tables with holes, refused entries, unclassifiable annotations +# --------------------------------------------------------------------------- + + +def test_a_missing_entry_is_reported_against_the_backends_table(): + class PartialDialect(SQLiteDialect): + def suggested_column_types(self): + return {str: StringColumn} + + with pytest.raises(ColumnTypeResolutionError, match="Cannot choose a column class"): + resolve(PartialDialect(version=(3, 46, 1)), int) + + +def test_a_none_entry_fails_and_names_the_declaration_that_fixes_it(): + with pytest.raises(ColumnTypeResolutionError) as excinfo: + resolve(RefusingDialect(version=(3, 46, 1)), dict) + message = str(excinfo.value) + assert "no column class for" in message + assert "UseColumnType" in message + + +def test_a_none_entry_does_not_leak_into_other_entries(): + """One refusal must not make the whole backend unusable.""" + dialect = RefusingDialect(version=(3, 46, 1)) + assert resolve(dialect, str) is StringColumn + assert resolve(dialect, int) is IntegerColumn + + +def test_a_table_entry_that_is_not_a_column_class_raises(): + """A malformed table is a backend bug, caught where it is written down.""" + + class WrongDialect(SQLiteDialect): + def suggested_column_types(self): + table = super().suggested_column_types() + table[str] = "StringColumn" + return table + + with pytest.raises(ColumnTypeResolutionError, match="not a ColumnBase subclass"): + resolve(WrongDialect(version=(3, 46, 1)), str) + + +@pytest.mark.parametrize( + "annotation", + [Any, Union[int, str], List[int], Dict[str, int]], + ids=["Any", "bare-union", "parameterised-list", "parameterised-dict"], +) +def test_unclassifiable_annotations_fail(annotation): + """``Any``, a bare ``Union``, a parameterised container: no entry, no answer. + + Each of these used to become the permissive ``Column``. Now it is a + definition-time failure naming what to write instead, which is the change + the ruling asked for: a field the framework cannot type is a mistake in the + model, and a silent fallback hides it until the database complains. + """ + with pytest.raises(ColumnTypeResolutionError) as excinfo: + resolve(sqlite_dialect(), annotation) + assert "UseColumnType" in str(excinfo.value) + + +def test_an_unregistered_custom_class_fails(): + """A class the framework does not model is unclassifiable, not a string.""" + + class Money: + pass + + with pytest.raises(ColumnTypeResolutionError, match="Cannot choose a column class"): + resolve(sqlite_dialect(), Money) + + +def test_a_subclass_of_an_entry_resolves_through_the_walk(): + """``class MyStr(str)`` is a string; the walk is what says so.""" + assert resolve(sqlite_dialect(), type("Code", (str,), {})) is StringColumn + + +def test_an_enum_subclass_resolves_to_the_enum_entry(): + """Before the subclass walk, so a ``(int, Enum)`` is not filed as an int.""" + assert resolve(sqlite_dialect(), enum.Enum) is StringColumn + + class Weekday(enum.IntEnum): + MONDAY = 1 + + assert resolve(sqlite_dialect(), Weekday) is StringColumn + + +def test_optional_and_annotated_still_resolve(): + Annotated = getattr(typing, "Annotated", None) + if Annotated is None: + pytest.skip("typing.Annotated requires Python 3.9+") + + assert resolve(sqlite_dialect(), Optional[dict]) is JSONColumn + # An unrelated marker is simply not a UseColumnType; the selector resolves + # from the peeled annotation and the declaration is read by the model layer. + assert resolve(sqlite_dialect(), Annotated[str, "marker"]) is StringColumn + + +# --------------------------------------------------------------------------- +# 6. Boolean algebra and the literal discipline +# --------------------------------------------------------------------------- + + +def _flag(name="flag"): + return build_column(sqlite_dialect(), name, bool) + + +def test_is_true_and_is_false_render_keywords(): + """``IS TRUE`` / ``IS FALSE``, three-valued-logic correct. + + ``= TRUE`` would match differently under three-valued logic, and ``= 1`` + is not portable at all: PostgreSQL rejects ``boolean = integer`` outright. + """ + assert _flag().is_true().to_sql() == ('"flag" IS TRUE', ()) + assert _flag().is_false().to_sql() == ('"flag" IS FALSE', ()) + + +def test_and_or_not_render_connectives_not_bitwise_operators(): + """``AND`` / ``OR`` / ``NOT`` — MySQL accepts bitwise ``&`` / ``|`` too, and + on a boolean column those compute something else entirely.""" + column = _flag() + assert (column.is_true() & column.is_false()).to_sql() == ( + '"flag" IS TRUE AND "flag" IS FALSE', + (), + ) + assert (column.is_true() | column.is_false()).to_sql() == ( + '"flag" IS TRUE OR "flag" IS FALSE', + (), + ) + assert (~column.is_true()).to_sql() == ('NOT ("flag" IS TRUE)', ()) + + +def test_boolean_algebra_never_renders_one_or_zero(): + """The rendering discipline, asserted rather than described. + + ``1`` / ``0`` as a boolean literal is the one thing that works on SQLite and + MySQL and fails on PostgreSQL, so a regression that renders it would pass on + two backends and break on a third. The literal has to be the keyword. + """ + column = _flag() + rendered = [ + column.is_true().to_sql()[0], + column.is_false().to_sql()[0], + (column.is_true() & column.is_false()).to_sql()[0], + (column.is_true() | column.is_false()).to_sql()[0], + (~column.is_true()).to_sql()[0], + ] + for sql in rendered: + assert " TRUE" in sql or "FALSE" in sql + # No integer literal standing in for the value. + assert " IS 1" not in sql + assert " IS 0" not in sql + assert "= 1" not in sql + assert "= 0" not in sql + + +def test_boolean_columns_only_carry_the_boolean_surface(): + """``str`` has no ``AND``; that is what the narrow classes are for. + + The mixin is composed into :class:`BooleanColumn` rather than inherited + from :class:`ColumnBase` precisely so that these three operators stay off + every other family — giving ``str`` an ``AND`` would be the guess the narrow + classes exist to avoid. + """ + assert hasattr(build_column(sqlite_dialect(), "f", bool), "__and__") + assert hasattr(build_column(sqlite_dialect(), "f", bool), "__or__") + assert hasattr(build_column(sqlite_dialect(), "f", bool), "__invert__") + assert not hasattr(build_column(sqlite_dialect(), "s", str), "__and__") + assert not hasattr(build_column(sqlite_dialect(), "n", int), "__invert__") + + +def test_negating_the_column_is_not_the_same_as_is_false(): + """``~flag`` is NOT; three-valued logic makes ``NOT NULL`` unknown. + + Callers asking "is it false?" say ``is_false()``. ``~`` is the connective. + """ + column = _flag() + assert column.is_false().to_sql()[0] != f"NOT ({column.to_sql()[0]})" + + +def test_boolean_algebra_composes_with_other_predicates(): + """The connectives are the same ones predicates use, so they interleave.""" + column = _flag() + name = build_column(sqlite_dialect(), "name", str) + combined = (column.is_true() & name.like("a%")) | column.is_false() + sql, params = combined.to_sql() + assert " AND " in sql and " OR " in sql + assert params == ("a%",) + + +# --------------------------------------------------------------------------- +# 7. Two backends, one contract -- and no free resolvers +# --------------------------------------------------------------------------- + + +def test_two_dialects_differ_only_where_stated(): + """The dummy and SQLite differ exactly in the sequence entries. + + SQLite has no array type, so its four sequence entries are JSON documents; + the dummy keeps the portable ``ArrayColumn``. Every other entry agrees — + ``float`` and ``Decimal`` are ``NumericColumn`` on both sides, and + ``timedelta`` is ``IntervalColumn`` on both. A backend that deviated + anywhere else would be changing an answer no decision asked it to change. + """ + dummy, sqlite = dummy_dialect(), sqlite_dialect() + deviated = {list, tuple, set, frozenset} + for entry in COMMON_TYPES: + if entry in deviated: + continue + if sqlite.suggested_column_types()[entry] is None: + assert dummy.suggested_column_types()[entry] is None + continue + assert resolve(dummy, entry) is resolve(sqlite, entry) + assert resolve(sqlite, list) is JSONColumn + assert resolve(dummy, list) is ArrayColumn + + +def test_the_public_surface_has_no_free_resolvers(): + """Resolution belongs to the field accessor; there is no module function.""" + import rhosocial.activerecord.base as base_package + + assert not hasattr(base_package, "build_column") + assert not hasattr(base_package, "column_class_for") + assert not hasattr(base_package, "column_dispatch") + + +def test_the_permissive_column_is_still_constructible_by_hand(): + """Retiring the fallback did not retire the class. + + ``Column(dialect, "x")`` is how a caller with a bare column name gets an + expression; what is gone is the framework deciding that an unclassifiable + annotation becomes one. + """ + from rhosocial.activerecord.backend.expression import Column + + column = Column(sqlite_dialect(), "anything") + assert column.to_sql() == ('"anything"', ()) + + +def test_uuid_stays_its_own_column_family(): + """A UUID has no portable operator, but it is still not a string.""" + assert resolve(sqlite_dialect(), uuid.UUID) is UUIDColumn + assert resolve(sqlite_dialect(), uuid.UUID) is not StringColumn + + +def test_decimal_is_a_number_and_not_a_string(): + assert issubclass(resolve(sqlite_dialect(), decimal.Decimal), NumericColumn) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py new file mode 100644 index 00000000..f7cd2f5a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py @@ -0,0 +1,489 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_document_and_conversion_families.py +"""The families that carry documents, sequences, casts and XML. + +A JSON extraction is not always a document: `->` hands back JSON and `->>` +hands back text, so the same node class reports two families and the chain +narrows. A cast states its result in the target type, which is the only place +it can come from. And an operation over several values — GREATEST, a CASE — +answers with their common kind, or with nothing when they disagree. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_document_and_conversion_families.py +import pytest + +from rhosocial.activerecord.backend.expression import functions as F, FunctionCall, Literal, XMLColumn +from rhosocial.activerecord.backend.expression.bases import SQLValue +from rhosocial.activerecord.backend.expression.column_types import annotation_for +from rhosocial.activerecord.backend.expression.type_name import is_valid_type_name +from rhosocial.activerecord.backend.expression.types import ( + CustomType, + JsonType, + VarCharType, + XmlType, +) +from rhosocial.activerecord.backend.expression.advanced_functions import CaseExpression +from rhosocial.activerecord.backend.expression.declared import ( + ArrayAnnotation, + BinaryAnnotation, + BooleanAnnotation, + IntegerAnnotation, + JSONAnnotation, + NumberAnnotation, + TemporalAnnotation, + TextAnnotation, + UUIDAnnotation, + XMLAnnotation, +) +from rhosocial.activerecord.backend.expression.value_types import ( + ArrayValue, + JSONValue, + NumericValue, + TemporalValue, + TextValue, + XMLValue, +) + +#: Every value class the lattice holds. "No typed result" is asserted by saying +#: the result is none of these, so the list has to be the whole set: an +#: assertion that forgets a class would pass for the wrong reason. +TYPED_VALUE_CLASSES = ( + ArrayAnnotation, + BinaryAnnotation, + BooleanAnnotation, + IntegerAnnotation, + JSONAnnotation, + NumberAnnotation, + TemporalAnnotation, + TextAnnotation, + UUIDAnnotation, + XMLAnnotation, +) + + +def is_typed_as_one_of_these(result): + """Whether *result* is any of the typed value classes. + + A node that declares no type is honest about it: it is none of these. This + is the shape the tests that want "unknown" assert, and it is why the list + above is spelled out rather than imported wholesale -- a class added to the + lattice has to be added here too, or these assertions would go on passing + while the answer they are about became possible. + """ + return isinstance(result, TYPED_VALUE_CLASSES) + + +@pytest.fixture +def dialect(): + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + d = SQLiteDialect() + d._version = (3, 46, 1) + return d + + +@pytest.fixture +def columns(dialect): + from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column + + return { + "int": build_column(dialect, "i", int), + "float": build_column(dialect, "f", float), + "str": build_column(dialect, "s", str), + "json": build_column(dialect, "j", dict), + "array": build_column(dialect, "l", list), + } + + +# --------------------------------------------------------------------------- +# The same node, two families +# --------------------------------------------------------------------------- + + +def test_arrow_extraction_gives_a_document(dialect, columns): + assert isinstance(F.json_extract(dialect, columns["json"], Literal(dialect, "$.a")), JSONValue) + + +def test_double_arrow_extraction_gives_text(dialect, columns): + """`->>` is a narrowing: a document becomes a string and cannot widen back.""" + assert isinstance(F.json_extract_text(dialect, columns["json"], "$.a"), TextValue) + + +def test_a_built_document_is_a_document(dialect, columns): + assert isinstance(F.json_build_object(dialect, "k", 1), JSONValue) + assert isinstance(F.json_array_elements(dialect, columns["json"]), JSONValue) + + +def test_a_document_offers_the_json_accessors(dialect, columns): + built = F.json_build_object(dialect, "k", 1) + assert isinstance(built, JSONValue) + assert hasattr(built, "json_path") + assert not hasattr(built, "upper") + + +def test_text_reports_a_string_family(dialect, columns): + """Narrowing is reported, which is what propagation reads. + + The JSON accessors stay, because one node class serves both arrow + directions and the wrapper cannot hide what it forwards — that is a known + over-offer on this one class, not a claim that text is a document. + """ + text = F.json_extract_text(dialect, columns["json"], "$.a") + assert isinstance(text, TextValue) + assert text.to_sql()[0].endswith("->>'$.a'") + + +# --------------------------------------------------------------------------- +# Sequences +# --------------------------------------------------------------------------- + + +def test_a_sequence_is_a_sequence(dialect, columns): + assert isinstance(F.unnest(dialect, columns["array"]), ArrayValue) + + +def test_measuring_a_sequence_gives_a_whole_number(dialect, columns): + assert isinstance(F.array_length(dialect, columns["array"], 1), NumericValue) + + +# --------------------------------------------------------------------------- +# Operations over several values +# --------------------------------------------------------------------------- + + +def test_greatest_answers_with_what_its_arguments_answer_with(dialect, columns): + assert isinstance(F.greatest(dialect, columns["int"], columns["int"]), IntegerAnnotation) + + +def test_greatest_of_mixed_kinds_is_unknown(dialect, columns): + """The comparison is legal SQL and the answer is neither kind, so neither + surface may be offered. Guessing the first or the widest would be wrong.""" + assert not is_typed_as_one_of_these(F.greatest(dialect, columns["int"], columns["str"])) + + +def test_least_agrees_with_greatest(dialect, columns): + assert isinstance(F.least(dialect, columns["float"], columns["float"]), NumberAnnotation) + + +def test_nullif_keeps_the_value_it_tests(dialect, columns): + assert isinstance(F.nullif(dialect, columns["str"], None), TextAnnotation) + + +# --------------------------------------------------------------------------- +# what an operation over several values keeps +# --------------------------------------------------------------------------- + + +def test_a_consensus_needs_exactly_one(dialect, columns): + """A CASE over disagreeing branches is legal SQL that answers with neither + kind, so neither surface may be offered.""" + mixed = CaseExpression(dialect, cases=[(columns["int"], columns["int"])], + else_result=columns["float"]) + assert not is_typed_as_one_of_these(mixed) + + +def test_an_argument_without_a_family_does_not_break_a_consensus(dialect, columns): + """A literal says nothing, so it neither agrees nor disagrees.""" + with_literal = CaseExpression(dialect, cases=[(columns["int"], Literal(dialect, 1))], + else_result=columns["int"]) + assert isinstance(with_literal, NumericValue) + + +# --------------------------------------------------------------------------- +# A cast states its result in the target type +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "sql_type", + [ + "VARCHAR(255)", + "TEXT", + "NVARCHAR2(10)", + "INTEGER", + "BIGINT", + "DECIMAL(10,2)", + "DOUBLE PRECISION", + "BOOLEAN", + "TIMESTAMP", + "JSONB", + "BLOB", + "UUID", + "XML", + ], +) +def test_real_sql_type_names_are_names(sql_type): + """These are all type names a database has. + + They used to be pinned to the value family a cast to them produces. There is + no such table now: ``cast`` answers with the class of the ``DataType`` it + was handed, so the name carries no type of its own to be right about. What + remains is that the name is recognised -- the grammar, not a meaning. + """ + assert is_valid_type_name(sql_type) + + +def test_an_unknown_sql_type_is_still_a_name(): + """A name nobody here knows is still shaped like a name. + + What it means is the dialect's business, decided when the dialect is + asked to render it, not something this package guesses at here. + """ + assert is_valid_type_name("GEOMETRY") + assert is_valid_type_name("POINT") + assert not is_valid_type_name(None) + + +def test_cast_takes_its_type_from_the_target_type(dialect, columns): + """The cast answers with the surface of the type it was handed.""" + assert isinstance( + F.cast(dialect, columns["int"], VarCharType(dialect, length=10)), + TextValue, + ) + assert isinstance( + F.cast(dialect, columns["int"], JsonType(dialect)), JSONValue + ) + + +def test_an_unmodelled_target_type_yields_no_typed_result(dialect, columns): + """A user-defined type has no value class to answer with. + + Offering JSON navigation on a type nobody here has heard of would be worse + than saying nothing, so the cast comes back untyped and the caller says what + they meant with ``as_*``. + """ + result = F.cast(dialect, columns["int"], CustomType(dialect, raw="GEOMETRY")) + assert not is_typed_as_one_of_these(result) + + +# --------------------------------------------------------------------------- +# Formatting and parsing +# --------------------------------------------------------------------------- + + +def test_to_char_gives_text(dialect, columns): + assert isinstance(F.to_char(dialect, columns["int"]), TextValue) + + +def test_to_number_gives_a_number(dialect, columns): + assert isinstance(F.to_number(dialect, columns["int"]), NumericValue) + + +def test_to_date_gives_a_date(dialect, columns): + """``TO_DATE`` answers with a **date**, not a timestamp. + + Every backend's ``TO_DATE`` produces a calendar date, so typing it as a + timestamp offered the time-of-day operations on a value that has no time of + day. Asserting the date here is what stops that coming back. + """ + node = F.to_date(dialect, columns["int"]) + assert isinstance(node, TemporalValue) + # A date and a date-time carry the same surface -- the operations are the + # same -- so "not a timestamp" is a statement about the node's class, which + # is where the distinction now lives. + assert type(node).__name__ == "ToDateFunction" + + +# --------------------------------------------------------------------------- +# Session identity is a name +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("factory", ["current_user", "session_user", "system_user"]) +def test_the_session_identity_is_a_name(dialect, factory): + result = getattr(F, factory)(dialect) + # What makes it a *name* is the surface it carries, not the class it is: + # a node is its own class now, so the old ``isinstance(result, + # StringValue)`` would be asserting the wrapper this family no longer has. + # Text answers text operations and refuses numeric ones. + assert hasattr(result, "upper") + assert not hasattr(result, "sqrt") + + +# --------------------------------------------------------------------------- +# XML +# --------------------------------------------------------------------------- + + +def test_the_xml_document_nodes_are_xml_values(dialect): + """An XML constructor declares the XML value class, and nothing else. + + This used to assert the opposite -- that no class in the lattice covered + XML -- because the value family was a tag in a closed table and no tag + existed. The class is the statement now: every constructor that builds a + document derives from ``XMLValue``, so ``isinstance`` answers + from the object. What the class carries is the XML surface — the null + tests and casting, and no comparison (see the refusal test below). + """ + from rhosocial.activerecord.backend.expression import xml as X + + document_nodes = ( + X.XMLParseExpression, + X.XMLElementExpression, + X.XMLForestExpression, + X.XMLConcatExpression, + X.XMLCommentExpression, + X.XMLPIExpression, + X.XMLRootExpression, + X.XMLAggExpression, + X.XMLQueryExpression, + ) + other_families = tuple( + cls for cls in TYPED_VALUE_CLASSES if cls is not XMLValue + ) + for cls in document_nodes: + assert issubclass(cls, XMLValue), cls.__name__ + assert issubclass(cls, SQLValue), cls.__name__ + # It is an XML value and none of the other typed classes: a document + # is not text that can be upper-cased, not JSON to navigate, not a + # sequence to unnest. + assert not issubclass(cls, other_families), cls.__name__ + + +def test_xmlserialize_yields_the_character_value_it_names(dialect): + """Serialization leaves the XML family: the result is the text asked for. + + ``XMLSERIALIZE(... AS VARCHAR(100))`` answers with a character value, so + the node declares ``StringValue`` and the string operations + follow it out of the XML surface. + """ + from rhosocial.activerecord.backend.expression import xml as X + + assert issubclass(X.XMLSerializeExpression, TextValue) + serialized = F.xmlserialize(dialect, "", "VARCHAR(100)") + assert isinstance(serialized, TextValue) + assert not isinstance(serialized, XMLValue) + + +def test_xmlexists_is_a_predicate_not_a_value(): + """It answers a WHERE clause, so it has no value family to declare.""" + from rhosocial.activerecord.backend.expression import xml as X + from rhosocial.activerecord.backend.expression.bases import SQLPredicate + + assert issubclass(X.XMLExistsPredicate, SQLPredicate) + assert not issubclass(X.XMLExistsPredicate, XMLValue) + + +def test_a_cast_to_xml_is_an_xml_value(dialect, columns): + """The cast takes its type from the target: ``CAST(x AS XML)`` is XML.""" + result = F.cast(dialect, columns["str"], XmlType(dialect)) + assert isinstance(result, XMLValue) + assert not isinstance(result, TextValue) + + +def test_a_function_that_declares_no_result_can_say_xml(dialect): + """``as_xml()`` is how a caller states what a generic call yields. + + It returns an *annotation*: the XML surface, and nothing else. The text + surface is not merely unused here, it is gone -- which is the point of + stating the type, since ``.like()`` on an XML document is not a question any + backend answers. The SQL is untouched: only the declared type moved. + """ + from rhosocial.activerecord.backend.expression.declared import XMLAnnotation + + call = FunctionCall(dialect, "MYSTERY_FUNC") + typed = call.as_xml() + assert isinstance(typed, XMLAnnotation) + assert not hasattr(typed, "like") + assert typed.to_sql() == call.to_sql() + + +def test_an_xml_column_refuses_comparison_and_keeps_the_null_tests(dialect): + """The XML column surface, exactly as every XML backend defines it. + + PostgreSQL refuses ``xml = xml`` ("operator does not exist: xml = xml"), + SQL Server documents that the xml data type "cannot be compared or + sorted", and Oracle's ``XMLType`` has no comparison operators. Refusing + here names the operation at the call; without the declaration Python + would silently answer with identity equality. ``IS NULL`` is accepted by + all three, so the null tests stay. + """ + column = XMLColumn(dialect, "doc") + + for operation, dunder in [ + (lambda c: c == 1, "__eq__"), + (lambda c: c != 1, "__ne__"), + (lambda c: c < 1, "__lt__"), + (lambda c: c <= 1, "__le__"), + (lambda c: c > 1, "__gt__"), + (lambda c: c >= 1, "__ge__"), + ]: + with pytest.raises(AttributeError, match=dunder): + operation(column) + + assert "IS NULL" in column.is_null().to_sql()[0] + assert "IS NOT NULL" in column.is_not_null().to_sql()[0] + + +# --------------------------------------------------------------------------- +# Every family has a wrapper +# --------------------------------------------------------------------------- + + +def test_a_type_the_core_does_not_hold_is_reported_unknown(): + """The lattice is closed. An extension type a backend models fully is still + unknown here, because the core does not know which backends exist and cannot + say what such a type means for the operations its own results offer. + + Declaring one used to look like it worked -- the attribute was there, and + reading it gave the name back -- so nothing pinned the difference between a + type that is honoured and one that is quietly dropped. A tag could claim a + name the core held no class for; a class cannot, because the operations it + offers come with it. + """ + class ExtensionValue(SQLValue): + # A name on the class, which is what declaring a type used to mean. It + # confers nothing: nothing reads it, and annotation_for answers from the + # MRO, where this class appears under no mapped name. + declared_type = "network" + + instance = ExtensionValue.__new__(ExtensionValue) + assert ExtensionValue.declared_type == "network" + assert annotation_for(instance) is None + assert not is_typed_as_one_of_these(instance) + + +def test_every_typed_value_declares_a_family_from_the_lattice(): + """Each result class states its own family, and it has to be one the + lattice knows -- otherwise it offers operations nothing downstream expects. + + This replaced a test that every family but XML had a wrapper in a registry. + There is no registry now: a factory constructs the class it means, so there + is no table left to be complete. The family is named by the ``Value`` + suffix (规范 4.9), and the scan follows that suffix -- so a rename that + moves the family fails here rather than quietly emptying the set.""" + import inspect + + from rhosocial.activerecord.backend.expression import core + + declared = { + name: cls + for name, cls in inspect.getmembers(core, inspect.isclass) + if name.endswith("Value") and name != "SQLValue" + } + assert declared, "the typed values moved" + # Every typed value declares its type by being a class, so the only + # thing left to check is that each one is still reachable and distinct. + assert len(set(declared.values())) == len(declared), "two names bind one class" + + +def test_every_temporal_type_is_reachable(): + """The four temporal kinds exist and are distinct. + + They were one class with a label saying which it was, then four classes, and + now four members of :class:`LiteralKind` -- one closed vocabulary rather than + one class per type. This pins that a timestamp, a date, a time and an + interval are still told apart, because ``datetime`` is a subclass of ``date`` + and matching them in the wrong order would fold the first three together. + """ + + from rhosocial.activerecord.backend.expression.values import LiteralKind + + for name, sample in ( + ("TIMESTAMP", __import__("datetime").datetime(2026, 10, 18, 1, 2, 3)), + ("DATE", __import__("datetime").date(2026, 10, 18)), + ("TIME", __import__("datetime").time(1, 2, 3)), + ("INTERVAL", __import__("datetime").timedelta(days=1)), + ): + kind = LiteralKind[name] + assert LiteralKind.match(sample) is kind, name + assert kind.wire.endswith("_value"), name diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py new file mode 100644 index 00000000..fd1ca495 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py @@ -0,0 +1,390 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_operation_boundaries.py +"""The four string boundaries the 2026-10-09 ruling settled, plus the NULL-safe +comparison it added to the surface. + +``operation-groups-matrix.md`` section F records the measurement: what the ten +backends answer for a negative count, an empty pad, a position below 1 and a +multi-character trim set, and which answer -- if any -- is common ground. This +file pins the outcome. Edges every backend agrees on render; the rest are +refused at construction instead of rendered into whatever the dialect happens +to do. ``is_distinct_from`` is here too: its spelling varies by backend, so it +is a dialect hook with a gate, and the gate refuses rather than substitutes a +different question. So are the function version floors SQLite records: they +used to be answerable through ``supports_functions()`` and ignorable at render +time, and now rendering a call the dialect's version predates refuses. +""" + +import pytest + +from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError +from rhosocial.activerecord.backend.expression.column_types import NumericColumn, StringColumn +from rhosocial.activerecord.backend.expression.core import FunctionCall, Literal +from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect +from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + +@pytest.fixture +def sqlite_dialect(): + dialect = SQLiteDialect() + dialect.version = (3, 46, 1) + return dialect + + +@pytest.fixture +def name(sqlite_dialect): + return StringColumn(sqlite_dialect, "name") + + +@pytest.fixture +def portable_name(): + """A column on the portable baseline, where the common spellings render.""" + return StringColumn(DummyDialect(), "name") + + +REFUSALS = [ + ("left", (-1,)), + ("right", (-1,)), + ("lpad", (-1,)), + ("lpad", (5, "")), + ("rpad", (-1,)), + ("rpad", (5, "")), + ("substr", (0,)), + ("substr", (-2, 3)), + ("substr", (1, -1)), + ("trim", ("xy",)), + ("trim", ("",)), +] + + +@pytest.mark.parametrize( + "method,args", + [("left", (-1,)), ("right", (-1,)), ("lpad", (-1,)), ("lpad", (5, "")), + ("rpad", (-1,)), ("rpad", (5, "")), ("substr", (0,)), ("substr", (-2, 3)), + ("substr", (1, -1)), ("trim", ("xy",)), ("trim", ("",))], + ids=("left", "right", "lpad_negative", "lpad_empty_pad", + "rpad_negative", "rpad_empty_pad", "substr_start0", "substr_negative_start", + "substr_negative_length", "trim_two_chars", "trim_empty_set"), +) +def test_the_edge_where_the_backends_disagree_is_refused(name, method, args): + """No two backends answer these the same way, so the answer is a refusal + at construction rather than a silent coin flip at render time.""" + with pytest.raises(ValueError): + getattr(name, method)(*args) + + +@pytest.mark.parametrize( + "method,args,expected_sql,expected_params", + [ + ("left", (0,), 'LEFT("name", ?)', (0,)), + ("repeat", (0,), 'REPEAT("name", ?)', (0,)), + ("substr", (1, 0), 'SUBSTRING("name", ?, ?)', (1, 0)), + ], +) +def test_the_edge_every_backend_agrees_on_renders(portable_name, method, args, expected_sql, expected_params): + """The inside of the contract: zero-length results, the empty substring, + the whole-string over-length read and a one-character trim set behave the + same on every backend, so they render. Asserted on the portable baseline + because what is under test is the core spelling, not a dialect's.""" + sql, params = getattr(portable_name, method)(*args).to_sql() + assert sql == expected_sql + assert params == expected_params + + +@pytest.mark.parametrize( + "direction,expected_sql,expected_params", + [ + ("BOTH", 'TRIM("name", ?)', ("x",)), + ("LEADING", 'LTRIM("name", ?)', ("x",)), + ("TRAILING", 'RTRIM("name", ?)', ("x",)), + ], +) +def test_sqlite_spells_trim_as_its_function_form(direction, expected_sql, expected_params): + """SQLite parses no ``trim( from )`` syntax, so the node + renders as the function form there. Same node, dialect-chosen spelling -- + which is why the factory builds a TrimExpression and not a SQL string.""" + dialect = SQLiteDialect() + dialect.version = (3, 46, 1) + column = StringColumn(dialect, "name") + sql, params = column.trim("x", direction).to_sql() + assert sql == expected_sql + assert params == expected_params + + +def test_the_default_spelling_is_the_standard_form(): + """A dialect that speaks the standard form renders it, unchanged from what + the raw SQL used to produce.""" + column = StringColumn(DummyDialect(), "name") + assert column.trim().to_sql() == ('TRIM(BOTH FROM "name")', ()) + assert column.trim("x").to_sql() == ('TRIM(BOTH ? FROM "name")', ("x",)) + + +def test_lpad_defaults_to_a_space_and_passes_it_explicitly(portable_name): + """MySQL raises 1582 without a pad and MariaDB supplies one, so the core + always spells it out instead of letting the backend choose.""" + sql, params = portable_name.lpad(3).to_sql() + assert sql == 'LPAD("name", ?, ?)' + assert params == (3, " ") + + +def test_a_negative_repeat_is_the_empty_string(name): + """PostgreSQL, MySQL, MariaDB and ClickHouse all answer ``''`` for a + negative count; SQL Server answers NULL and Oracle, Firebird and SQLite + lack the function, so the core answers once instead of four times.""" + expr = name.repeat(-1) + assert "REPEAT" not in expr.to_sql()[0] + assert expr.to_sql() == ("?", ("",)) + + +def test_is_distinct_from_renders_the_null_safe_comparison(): + """The default rendering is the standard spelling; backends that spell it + differently override the hook instead of every call site writing dialect + SQL.""" + column = StringColumn(DummyDialect(), "age") + assert column.is_distinct_from(0).to_sql() == ('"age" IS DISTINCT FROM ?', (0,)) + assert column.is_not_distinct_from(0).to_sql() == ('"age" IS NOT DISTINCT FROM ?', (0,)) + + +@pytest.mark.parametrize("version,expected", [((3, 39, 0), True), ((3, 38, 0), False)]) +def test_sqlite_gates_the_spelling_on_its_version(version, expected): + dialect = SQLiteDialect() + dialect.version = version + assert dialect.supports_distinct_from() is expected + + +def test_sqlite_below_the_gate_refuses_rather_than_substituting(): + dialect = SQLiteDialect() + dialect.version = (3, 38, 0) + column = StringColumn(dialect, "age") + with pytest.raises(UnsupportedFeatureError): + column.is_distinct_from(0).to_sql() + + +# --------------------------------------------------------------------------- +# A recorded function version floor is a gate, not a footnote +# --------------------------------------------------------------------------- + + +SQLITE_FUNCTION_FLOORS = [ + ("iif", (3, 32, 0)), + ("pow", (3, 35, 0)), + # json_extract is deliberately absent: the JSON1 functions predate their + # 3.38.0 promotion into core (they exist since 3.9.0 behind a compile-time + # option), so availability depends on how SQLite was built, not on the + # version -- CI's own 3.35.0 server executes json_extract. A recorded floor + # there would refuse SQL the server accepts. + ("unhex", (3, 45, 0)), + ("json_array_insert", (3, 53, 0)), + ("jsonb_array_insert", (3, 53, 0)), +] + + +def _gated_call(dialect, func_name): + """One call to *func_name*, as the renderer meets it: the name the caller + handed over, spelled upper-case in the SQL.""" + return FunctionCall(dialect, func_name, Literal(dialect, "x")) + + +def _one_patch_below(floor): + """The release before *floor*: same major and minor, one patch short.""" + return (floor[0], floor[1], floor[2] - 1) + + +@pytest.mark.parametrize( + "func_name,floor", + SQLITE_FUNCTION_FLOORS, + ids=[func_name for func_name, _floor in SQLITE_FUNCTION_FLOORS], +) +def test_a_floor_the_dialect_is_below_refuses_instead_of_rendering(func_name, floor): + """SQLite records when each function arrived. Rendering one anyway emits + SQL this SQLite will reject, so the floor is a refusal at render time + rather than an observation in a table nobody reads.""" + dialect = SQLiteDialect() + dialect.version = _one_patch_below(floor) + with pytest.raises(UnsupportedFeatureError): + _gated_call(dialect, func_name).to_sql() + + +@pytest.mark.parametrize( + "func_name,floor", + SQLITE_FUNCTION_FLOORS, + ids=[func_name for func_name, _floor in SQLITE_FUNCTION_FLOORS], +) +def test_a_floor_the_dialect_meets_renders(func_name, floor): + """The gate is a floor, not a ban: at the recorded version the same call + renders exactly as it does on a newer one -- the version changes what is + refused, never what is spelled.""" + dialect = SQLiteDialect() + dialect.version = floor + assert _gated_call(dialect, func_name).to_sql() == (f"{func_name.upper()}(?)", ("x",)) + + +def test_the_refusal_names_the_function_the_floor_and_the_version(): + """A refusal the caller cannot act on is only a different way of failing, + so the message says which function, which version it arrived in and which + one is in force: the choice is between a newer server and another + spelling.""" + dialect = SQLiteDialect() + dialect.version = (3, 52, 0) + call = FunctionCall( + dialect, + "json_array_insert", + Literal(dialect, "[]"), + Literal(dialect, "$[0]"), + Literal(dialect, 1), + ) + with pytest.raises(UnsupportedFeatureError) as excinfo: + call.to_sql() + message = str(excinfo.value) + assert "JSON_ARRAY_INSERT" in message + assert "3.53.0" in message + assert "3.52.0" in message + + +def test_the_query_surface_and_the_gate_answer_the_same_thing(): + """``supports_functions`` keeps its shape and stays the query surface; what + changed is that a False in it is no longer advisory. Below the floor both + answer no, at it both answer yes.""" + for version, expected in ((3, 52, 0), False), ((3, 53, 0), True): + dialect = SQLiteDialect() + dialect.version = version + assert dialect.supports_functions()["json_array_insert"] is expected + call = _gated_call(dialect, "json_array_insert") + if expected: + assert call.to_sql() == ("JSON_ARRAY_INSERT(?)", ("x",)) + else: + with pytest.raises(UnsupportedFeatureError): + call.to_sql() + + +def test_a_name_no_floor_is_recorded_for_renders_on_the_oldest_dialect(): + """No floor is not a floor of zero. A name nobody has measured is not + gated here, so it renders on a dialect that predates every gate in the + table -- the gate only ever refuses what a backend declared.""" + dialect = SQLiteDialect() + dialect.version = (3, 8, 0) + assert dialect.function_version_floor("lower") is None + column = StringColumn(dialect, "name") + assert column.lower().to_sql() == ('LOWER("name")', ()) + assert dialect.function_version_floor("pow") == (3, 35, 0) + + +# --------------------------------------------------------------------------- +# The per-dialect spellings, and the emulations behind them +# --------------------------------------------------------------------------- + + +SQLITE_SPELLINGS = [ + ("left", (2,), 'SUBSTR("name", ?, ?)', (1, 2)), + ("right", (2,), 'SUBSTR("name", MAX(LENGTH("name") - ? + ?, ?), ?)', (2, 1, 1, 2)), + ( + "lpad", + (4, "xy"), + 'CASE WHEN ? <= LENGTH("name") THEN SUBSTR("name", ?, ?) ' + 'ELSE SUBSTR(REPLACE(HEX(ZEROBLOB(?)), ?, ?) || "name", - ?) END', + (4, 1, 4, 4, "00", "xy", 4), + ), + ( + "rpad", + (4, "-"), + 'SUBSTR("name" || REPLACE(HEX(ZEROBLOB(?)), ?, ?), ?, ?)', + (4, "00", "-", 1, 4), + ), + ("repeat", (3,), 'REPLACE(HEX(ZEROBLOB(?)), ?, "name")', (3, "00")), + ("ascii", (), 'UNICODE("name")', ()), + ("strpos", ("cd",), 'INSTR("name", ?)', ("cd",)), + ("position", ("cd",), 'INSTR("name", ?)', ("cd",)), +] + + +@pytest.mark.parametrize("method,args,expected_sql,expected_params", SQLITE_SPELLINGS) +def test_sqlite_spells_what_it_lacks(sqlite_dialect, method, args, expected_sql, expected_params): + """SQLite has none of these functions and no ``trim(... from ...)`` syntax, + so each is either renamed, reordered, or emulated out of ordinary nodes -- + measured 2026-10-09 and verified against a real database below. Nothing + here is assembled as a SQL string.""" + column = StringColumn(sqlite_dialect, "name") + sql, params = getattr(column, method)(*args).to_sql() + assert sql == expected_sql + assert params == expected_params + + +def test_sqlite_truncates_with_arithmetic_because_trunc_takes_one_argument(sqlite_dialect): + """SQLite's ``TRUNC`` is unary, so a precision is carried by scaling, + truncating toward zero, and scaling back -- exact for negatives, which + rounding would not be.""" + column = NumericColumn(sqlite_dialect, "n") + sql, params = column.truncate(2).to_sql() + assert sql == 'TRUNC("n" * POW(?, ?)) / POW(?, ?)' + assert params == (10, 2, 10, 2) + assert column.truncate().to_sql() == ('TRUNC("n")', ()) + + +def test_sqlite_takes_the_log_base_first(sqlite_dialect): + """SQLite spells ``log(base, x)`` where the core order is ``log(x, base)``; + the one-argument form is the natural logarithm on both.""" + column = NumericColumn(sqlite_dialect, "n") + assert column.log(10).to_sql() == ("LOG(?, \"n\")", (10,)) + assert column.log().to_sql() == ('LOG("n")', ()) + + +STRING_ROUNDTRIPS = [ + ("left(2)", lambda c: c.left(2), "abcdef", "ab"), + ("left(0)", lambda c: c.left(0), "abcdef", ""), + ("left(99)", lambda c: c.left(99), "abcdef", "abcdef"), + ("right(2)", lambda c: c.right(2), "abcdef", "ef"), + ("right(0)", lambda c: c.right(0), "abcdef", ""), + ("right(99)", lambda c: c.right(99), "abcdef", "abcdef"), + ("lpad(8, 'xy')", lambda c: c.lpad(8, "xy"), "abcdef", "xyabcdef"), + ("lpad(3, 'xy')", lambda c: c.lpad(3, "xy"), "abcdef", "abc"), + ("lpad(4)", lambda c: c.lpad(4), "ab", " ab"), + ("rpad(8, '-')", lambda c: c.rpad(8, "-"), "abcdef", "abcdef--"), + ("rpad(3, '-')", lambda c: c.rpad(3, "-"), "abcdef", "abc"), + ("repeat(3)", lambda c: c.repeat(3), "ab", "ababab"), + ("repeat(0)", lambda c: c.repeat(0), "ab", ""), + ("trim('f')", lambda c: c.trim("f"), "abcdef", "abcde"), + ("trim()", lambda c: c.trim(), " abc ", "abc"), +] + +NUMERIC_ROUNDTRIPS = [ + ("truncate(2)", lambda c: c.truncate(2), 3.14159, 3.14), + ("truncate(2) negative", lambda c: c.truncate(2), -3.14159, -3.14), + ("truncate(0)", lambda c: c.truncate(0), 3.7, 3.0), + ("truncate()", lambda c: c.truncate(), -3.7, -3.0), +] + + +@pytest.mark.parametrize( + "label,build,value,expected", + STRING_ROUNDTRIPS, + ids=[label for label, _build, _value, _expected in STRING_ROUNDTRIPS], +) +def test_the_sqlite_emulation_answers_what_the_function_answers(sqlite_dialect, label, build, value, expected): + """The spelling checks above prove the SQL is *shaped* right; this proves it + *means* right -- each expression is executed against a real SQLite and must + produce the answer PostgreSQL, MySQL and ClickHouse give for the same call. + A spelling that looks correct and answers something else is the failure this + test exists for.""" + import sqlite3 + + connection = sqlite3.connect(":memory:") + connection.execute("CREATE TABLE t (s TEXT)") + connection.execute("INSERT INTO t VALUES (?)", (value,)) + column = StringColumn(sqlite_dialect, "s") + sql, params = build(column).to_sql() + got = connection.execute(f"SELECT {sql} FROM t", tuple(params)).fetchone()[0] + assert got == expected, f"{label}: SQLite answered {got!r}, the function answers {expected!r}" + + +@pytest.mark.parametrize("label,build,value,expected", NUMERIC_ROUNDTRIPS) +def test_the_sqlite_numeric_emulation_answers_what_the_function_answers( + sqlite_dialect, label, build, value, expected +): + import sqlite3 + + connection = sqlite3.connect(":memory:") + connection.execute("CREATE TABLE t (n REAL)") + connection.execute("INSERT INTO t VALUES (?)", (value,)) + column = NumericColumn(sqlite_dialect, "n") + sql, params = build(column).to_sql() + got = connection.execute(f"SELECT {sql} FROM t", tuple(params)).fetchone()[0] + assert got == expected, f"{label}: SQLite answered {got!r}, the function answers {expected!r}" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py new file mode 100644 index 00000000..66fab5dd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py @@ -0,0 +1,113 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_operation_symmetry.py +"""Same-family column and value classes must offer the same operations. + +The P1 unification says a family is one thing on both sides: the class a +``Model.c.`` builds (a column) and the class an operation result builds +(a value) attach the same operation groups, so a value that came out of an +expression can be used exactly like the column it came from. Drift between the +two sides is invisible until a caller hits it -- ``name.length()`` returning a +number that lost an operation the string column still has, say -- so the sets +are asserted equal here. + +Definition of the compared set: + +* public callables plus the operator dunders (``__add__`` ... ``__and__``); +* minus the names provided by :class:`NotANumberMixin`. The refusal set is a + separate axis -- it answers "is this family a number", and whether a side + declares the refusal or merely lacks the operator is pinned where it + belongs (the family's own tests). Comparing the *offered* operations is + what "same family, same groups" means. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_operation_symmetry.py +import pytest + +from rhosocial.activerecord.backend.expression import ( + ArrayColumn, + BinaryColumn, + BooleanColumn, + TimestampColumn, + IntegerColumn, + JSONColumn, + NumericColumn, + StringColumn, + UUIDColumn, + XMLColumn, +) +from rhosocial.activerecord.backend.expression.declared import ( + ArrayAnnotation, + BinaryAnnotation, + BooleanAnnotation, + IntegerAnnotation, + JSONAnnotation, + NumberAnnotation, + TextAnnotation, + TemporalAnnotation, + UUIDAnnotation, + XMLAnnotation, +) +from rhosocial.activerecord.backend.expression.mixins import NotANumberMixin + +OPERATORS = { + "__add__", + "__sub__", + "__mul__", + "__truediv__", + "__mod__", + "__and__", + "__or__", + "__invert__", + "__eq__", + "__ne__", + "__lt__", + "__le__", + "__gt__", + "__ge__", +} + +_REFUSALS = {name for name, value in vars(NotANumberMixin).items() if callable(value)} + +#: Not operations on a value, so not part of what "the same operations" means. +#: ``collate`` and ``validate`` are a column's storage; ``get_params`` belongs to +#: the artifact rather than to the type; ``surface`` is the declaration of +#: which operations a node carries, which is the thing being compared here and so +#: cannot also be one of the things compared; and ``kind`` is a node's identity +#: on the wire (§4.9.2) -- defined once on the expression base, which an +#: annotation is not. +_NOT_OPERATIONS = {"collate", "validate", "get_params", "value_type_of", "kind"} + + +def _operations(cls): + """The operation names *cls* offers: public callables + operator dunders.""" + names = set() + for name in dir(cls): + if name.startswith("_") and name not in OPERATORS: + continue + if callable(getattr(cls, name, None)): + names.add(name) + return names - _REFUSALS - _NOT_OPERATIONS + + +FAMILIES = [ + (StringColumn, TextAnnotation), + (NumericColumn, NumberAnnotation), + (IntegerColumn, IntegerAnnotation), + (BooleanColumn, BooleanAnnotation), + (TimestampColumn, TemporalAnnotation), + (BinaryColumn, BinaryAnnotation), + (UUIDColumn, UUIDAnnotation), + (JSONColumn, JSONAnnotation), + (ArrayColumn, ArrayAnnotation), + (XMLColumn, XMLAnnotation), +] + + +@pytest.mark.parametrize("column_class, value_class", FAMILIES, ids=lambda c: c.__name__) +def test_the_two_sides_of_a_family_offer_the_same_operations(column_class, value_class): + column_ops = _operations(column_class) + value_ops = _operations(value_class) + assert column_ops == value_ops, ( + f"{column_class.__name__} and {value_class.__name__} drifted apart:\n" + f" only on the column: {sorted(column_ops - value_ops)}\n" + f" only on the value: {sorted(value_ops - column_ops)}" + ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py new file mode 100644 index 00000000..23449d00 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py @@ -0,0 +1,166 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_predicate_alias.py +"""Predicates must be able to carry an alias. + +A predicate is not confined to a WHERE clause. ``LIKE`` and its relatives also +appear in a SELECT list, inside ``CASE WHEN``, in a ``JOIN ... ON`` condition, +and in DDL as a ``CHECK`` constraint or a partial-index predicate. In the +projection case the boolean is a column like any other and needs a name. + +None of the predicate formatters honoured an alias, and ``SQLPredicate`` did +not even offer ``as_()``, so an aliased predicate silently rendered a bare +boolean — or could not be aliased at all. These tests pin the behaviour for +every predicate family, and pin the equally important inverse: no alias means +no ``AS`` in the output. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_predicate_alias.py +import pytest + +from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect +from rhosocial.activerecord.backend.expression import Column, Literal, NumericColumn, StringColumn +from rhosocial.activerecord.backend.expression.predicates import ( + IsBooleanPredicate, + IsNullPredicate, +) + + +@pytest.fixture +def dialect(): + d = SQLiteDialect() + d._version = (3, 46, 1) + return d + + +@pytest.fixture +def name(dialect): + # Typed: the families below are exercised through the capability mixins + # (``LIKE`` / ``ILIKE``), which live on the typed classes only. + return StringColumn(dialect, "name", table="t") + + +@pytest.fixture +def qty(dialect): + return NumericColumn(dialect, "qty", table="t") + + +def ident(dialect, alias): + return dialect.format_identifier(alias) + + +# --------------------------------------------------------------------------- +# Every predicate family honours the alias +# --------------------------------------------------------------------------- + + +def _families(dialect, name, qty): + """One aliased predicate per family, keyed by name.""" + return { + "comparison": (name == Literal(dialect, "x")).as_("a"), + "like": name.like("a%").as_("a"), + "ilike": name.ilike("a%").as_("a"), + "logical_and": ((name == Literal(dialect, "x")) & (qty > Literal(dialect, 0))).as_("a"), + "logical_or": ((name == Literal(dialect, "x")) | (qty > Literal(dialect, 0))).as_("a"), + "not": (~(name == Literal(dialect, "x"))).as_("a"), + "in": name.in_([1, 2]).as_("a"), + "between": name.between(Literal(dialect, "a"), Literal(dialect, "z")).as_("a"), + "is_null": IsNullPredicate(dialect, name).as_("a"), + "is_boolean": IsBooleanPredicate(dialect, name, True).as_("a"), + } + + +@pytest.mark.parametrize( + "family", + [ + "comparison", + "like", + "ilike", + "logical_and", + "logical_or", + "not", + "in", + "between", + "is_null", + "is_boolean", + ], +) +def test_predicate_alias_reaches_the_sql(dialect, name, qty, family): + """The alias must appear in the rendered statement.""" + expr = _families(dialect, name, qty)[family] + sql, _ = expr.to_sql() + assert sql.endswith(f"AS {ident(dialect, 'a')}") + assert sql.count("AS ") == 1, f"alias applied more than once: {sql!r}" + + +@pytest.mark.parametrize( + "family", + [ + "comparison", + "like", + "ilike", + "logical_and", + "logical_or", + "not", + "in", + "between", + "is_null", + "is_boolean", + ], +) +def test_unaliased_predicate_has_no_as_clause(dialect, name, qty, family): + """The inverse: no alias must not introduce a stray ``AS``. + + A formatter that appended an empty ``AS`` would be just as broken as one + that dropped the alias, and the regression is invisible unless it is + pinned separately. + """ + expr = _families(dialect, name, qty)[family] + expr = type(expr).as_(expr, expr.alias) + expr.alias = None + sql, _ = expr.to_sql() + assert " AS " not in sql, f"unexpected AS without an alias: {sql!r}" + + +# --------------------------------------------------------------------------- +# The reason this matters: a predicate used as a projected column +# --------------------------------------------------------------------------- + + +def test_projected_predicate_is_named_like_a_column(dialect, name): + """``SELECT name LIKE 'a%' AS is_apple`` is the motivating case.""" + sql, params = name.like("a%").as_("is_apple").to_sql() + assert sql == f'"t"."name" LIKE {dialect.get_parameter_placeholder()} AS {ident(dialect, "is_apple")}' + assert params == ("a%",) + + +def test_alias_works_for_a_bare_column_too(dialect): + """The base behaviour must be unchanged by the predicate change. + + Deliberately a bare ``Column``: the ``name`` fixture is typed now, and this + case is specifically about the untyped reference still aliasing. + """ + sql, _ = Column(dialect, "name", table="t").as_("n").to_sql() + assert sql == f'"t"."name" AS {ident(dialect, "n")}' + + +# --------------------------------------------------------------------------- +# Empty value list: a branch of the IN formatter with its own return +# --------------------------------------------------------------------------- + + +def test_empty_in_list_keeps_its_alias(dialect, name): + """``IN ()`` is a separate return path in the IN formatter.""" + sql, params = name.in_([]).as_("none").to_sql() + assert sql.endswith(f"AS {ident(dialect, 'none')}") + assert params == () + + +# --------------------------------------------------------------------------- +# Parameters are unaffected by aliasing +# --------------------------------------------------------------------------- + + +def test_aliasing_preserves_parameters(dialect, name, qty): + """The alias is pure SQL decoration; bind order must not shift.""" + expr = (name.like("a%") & (qty > Literal(dialect, 5))).as_("both") + _, params = expr.to_sql() + assert params == ("a%", 5) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py new file mode 100644 index 00000000..0639f1ef --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py @@ -0,0 +1,164 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_concatenation_operator.py +"""``||`` is concatenation in SQL and logical OR in several backends. + +PostgreSQL, Oracle, Snowflake, Firebird and ClickHouse read ``||`` as string +concatenation. MySQL and MariaDB read it as logical OR unless the server runs +with ``PIPES_AS_CONCAT``, and SQL Server reads it as logical OR outright. +Emitting the bare token on those backends returns a boolean where a string was +meant — a wrong answer rather than a syntax error, which is why it can survive +a test suite. + +So the node records the *intent* and the dialect picks the spelling. These +tests pin the contract: the intent survives the round trip, the default is the +standard operator, and a dialect that declares a function gets one. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_concatenation_operator.py +import pytest + +from rhosocial.activerecord.backend.expression import StringColumn +from rhosocial.activerecord.backend.expression import functions as string_functions +from rhosocial.activerecord.backend.expression.operators import ( + BinaryExpression, + ConcatenationOperation, +) + + +@pytest.fixture +def dialect(): + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + d = SQLiteDialect() + d._version = (3, 46, 1) + return d + + +@pytest.fixture +def operands(dialect): + """Two string columns. + + StringColumn rather than Column: the point of the round trip is that the + result is still a string, and a bare Column carries no string surface to + lose. + """ + return ( + StringColumn(dialect, "a", table="t"), + StringColumn(dialect, "b", table="t"), + ) + + +# --------------------------------------------------------------------------- +# The node carries intent, not an operator +# --------------------------------------------------------------------------- + + +def test_concat_op_builds_an_intent_node(dialect, operands): + left, right = operands + expr = string_functions.concat_op(dialect, left, right) + assert isinstance(expr, ConcatenationOperation) + + +def test_the_intent_node_is_not_a_bare_binary_expression(dialect, operands): + """The node is its own kind, not a BinaryExpression with a token. + + A bare BinaryExpression with op ``||`` says nothing about intent, which is + exactly why concat_op stopped producing one. + """ + left, right = operands + expr = string_functions.concat_op(dialect, left, right) + assert not isinstance(expr, BinaryExpression) + assert expr.left is left and expr.right is right + + +def test_the_operator_is_not_a_parameter(dialect, operands): + """Concatenation carries no ``op``: the kind is the intent. + + ``left`` and ``right`` are the node's only construction parameters, so + nothing about the operator token travels in the artifact. + """ + left, right = operands + expr = ConcatenationOperation(dialect, left, right) + assert not hasattr(expr, "op") + assert set(expr.get_params()) == {"left", "right"} + + +# --------------------------------------------------------------------------- +# The default spelling +# --------------------------------------------------------------------------- + + +def test_default_dialect_uses_the_standard_operator(dialect, operands): + """SQLite and PostgreSQL both read ``||`` as concatenation.""" + left, right = operands + assert dialect.string_concatenation_function() is None + assert string_functions.concat_op(dialect, left, right).to_sql()[ + 0 + ] == '"t"."a" || "t"."b"' + + +def test_a_declared_function_replaces_the_operator(dialect, operands): + """The declaration is consulted, so the same node renders differently.""" + left, right = operands + dialect.STRING_CONCATENATION = "CONCAT" + assert dialect.string_concatenation_function() == "CONCAT" + assert string_functions.concat_op(dialect, left, right).to_sql()[0] == ( + 'CONCAT("t"."a", "t"."b")' + ) + + +def test_declaration_must_be_a_string(dialect): + """A non-string declaration is ignored rather than interpolated.""" + dialect.STRING_CONCATENATION = None + assert dialect.string_concatenation_function() is None + dialect.STRING_CONCATENATION = 42 + assert dialect.string_concatenation_function() is None + + +# --------------------------------------------------------------------------- +# Chaining: the result is a string +# --------------------------------------------------------------------------- + + +def test_result_keeps_the_string_value_surface(operands): + left, _ = operands + result = left.concat_using_operator("x") + for method in ("upper", "substr", "like", "trim", "concat_using_operator"): + assert hasattr(result, method), f"concatenation lost {method}" + + +def test_chaining_after_concatenation(operands): + left, right = operands + sql, _ = left.concat_using_operator(right).upper().to_sql() + assert "UPPER" in sql + assert "||" in sql or "CONCAT" in sql + + +def test_alias_reaches_the_sql(operands): + left, right = operands + sql, _ = left.concat_using_operator(right).as_("joined").to_sql() + assert " AS " in sql + + +def test_no_alias_means_no_as(operands): + left, right = operands + sql, _ = left.concat_using_operator(right).to_sql() + assert " AS " not in sql + + +def test_parameters_are_preserved(operands): + left, right = operands + _, params = left.concat_using_operator(right).to_sql() + assert params == () + + +# --------------------------------------------------------------------------- +# concat_op is not the path for logical OR +# --------------------------------------------------------------------------- + + +def test_logical_or_does_not_go_through_concatenation(operands): + """OR has its own node and formatter, so the two never meet.""" + left, _ = operands + predicate = left.like("a%") | left.like("b%") + assert not isinstance(predicate, ConcatenationOperation) + assert " OR " in predicate.to_sql()[0] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py new file mode 100644 index 00000000..54a9347a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py @@ -0,0 +1,209 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_value_operations.py +"""String value operations belong on the string column, and chain. + +``StringMixin`` used to hold exactly two methods, ``like`` and ``ilike``, and +both returned a predicate. A class named ``StringColumn`` therefore offered no +string operations at all — only the ability to be LIKE-matched — while the 26 +string functions that did exist sat unused in ``functions/string.py``. + +The split this file pins: + +- :class:`StringValueMixin` derives new strings and chains. +- :class:`StringPatternPredicateMixin` answers questions and ends the chain. +- Numeric results stay off the string surface, because ``LENGTH(x) LIKE '3'`` + is a type error in every backend. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_value_operations.py +import pytest + +from rhosocial.activerecord.backend.expression.value_types import TextValue + +from rhosocial.activerecord.backend.expression import ( + LikePredicate, + UpperFunction, + build_json_path, +) +from rhosocial.activerecord.backend.expression import functions as string_functions + +from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column + + +@pytest.fixture +def dialect(): + # The portable baseline dialect, not SQLite: what this file pins is the + # *core* layer -- each operation reaches its factory and the result is a + # typed string. Which spelling a given backend then writes is a per-dialect + # question and lives in test_operation_boundaries.py, where SQLite's + # INSTR/SUBSTR/TRUNC and its pad and repeat emulations are checked against + # a real database. + from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect + + return DummyDialect() + + +@pytest.fixture +def name(dialect): + return build_column(dialect, "name", str) + + +# --------------------------------------------------------------------------- +# The string surface exists and derives +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "method, args, expected_function", + [ + ("upper", (), "UPPER"), + ("lower", (), "LOWER"), + ("initcap", (), "INITCAP"), + ("reverse", (), "REVERSE"), + ("left", (2,), "LEFT"), + ("right", (2,), "RIGHT"), + ("lpad", (5,), "LPAD"), + ("rpad", (5,), "RPAD"), + ("repeat", (2,), "REPEAT"), + ("trim", (), "TRIM"), + ("substr", (1, 3), "SUBSTRING"), + ("replace", ("a", "b"), "REPLACE"), + ("translate", ("ab", "cd"), "TRANSLATE"), + ("overlay", ("x", 2), "OVERLAY"), + ], + ids=lambda v: v if isinstance(v, str) else "", +) +def test_string_operation_renders_its_function( + name, method, args, expected_function +): + """Each operation must reach the factory that already existed.""" + result = getattr(name, method)(*args) + sql, _ = result.to_sql() + assert expected_function in sql + + +def test_string_operations_return_a_typed_string_value(name): + """The result must be a string-valued node, not a bare function call.""" + assert isinstance(name.upper(), UpperFunction) + + +# --------------------------------------------------------------------------- +# Chaining — the reason the result is typed +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "build, expected_functions", + [ + (lambda c: c.upper(), ["UPPER"]), + (lambda c: c.upper().substr(1, 3), ["UPPER", "SUBSTRING"]), + (lambda c: c.upper().left(2).lower(), ["UPPER", "LEFT", "LOWER"]), + (lambda c: c.trim().replace("a", "b"), ["TRIM", "REPLACE"]), + (lambda c: c.substr(1, 2).upper().lower(), ["SUBSTRING", "UPPER", "LOWER"]), + ], + ids=["one", "two", "three", "trim-replace", "substr-upper-lower"], +) +def test_string_operations_chain(name, build, expected_functions): + """A derived string is still a string, so the next operation exists.""" + sql, _ = build(name).to_sql() + for function in expected_functions: + assert function in sql, f"{function} missing from {sql!r}" + + +def test_chained_result_keeps_the_whole_string_surface(name): + """Three levels deep, the value operations are all still available.""" + result = name.upper().left(2).lower() + for method in ("upper", "lower", "substr", "trim", "concat", "replace"): + assert hasattr(result, method), f"chain lost {method}" + + +def test_chained_result_keeps_the_pattern_predicates(name): + """String-ness is what makes LIKE legal on the result.""" + result = name.upper().left(2) + sql, _ = result.like("A%").to_sql() + assert "LIKE" in sql + assert "UPPER" in sql + + +# --------------------------------------------------------------------------- +# Crossing into the predicate domain ends the value chain +# --------------------------------------------------------------------------- + + +def test_pattern_predicate_terminates_the_chain(name): + """A predicate is a boolean; it never becomes a string again.""" + predicate = name.upper().like("A%") + assert isinstance(predicate, LikePredicate) + for method in ("upper", "substr", "trim", "concat"): + assert not hasattr(predicate, method), ( + f"predicate wrongly offers {method}; the value chain should have ended" + ) + + +def test_predicate_still_combines(name): + """Ending the value chain does not end the predicate chain.""" + combined = (name.like("A%") | name.like("B%")) & name.ilike("%x%") + sql, _ = combined.to_sql() + assert " OR " in sql and " AND " in sql + + +# --------------------------------------------------------------------------- +# Numeric results are not on the string surface +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "factory", ["length", "ascii", "octet_length", "bit_length"] +) +def test_numeric_result_is_not_a_string_value(dialect, name, factory): + """``LENGTH(x) LIKE '3'`` is a type error; the surface must not offer it.""" + result = getattr(string_functions, factory)(dialect, name) + assert not isinstance(result, TextValue) + + +@pytest.mark.parametrize( + "method, args", + [("length", ()), ("ascii", ()), ("strpos", ("x",)), ("position", ("x",))], +) +def test_string_column_offers_them_but_the_result_is_not_a_string(name, method, args): + """A legal string operation whose *result* is a number. + + ``LENGTH(s) LIKE '3'`` is still a type error, but it is caught by the + result's type rather than by hiding the method. Hiding it would be wrong: + these are well-defined on every backend, and ``strpos`` and ``position`` + differ in availability, so "does a string offer it" is not the same + question as "is the answer a string". + """ + assert hasattr(name, method), f"StringColumn lost a legal operation {method}()" + result = getattr(name, method)(*args) + assert not isinstance(result, TextValue) + + +# --------------------------------------------------------------------------- +# Existing behaviour is preserved +# --------------------------------------------------------------------------- + + +def test_free_functions_still_work_and_are_now_typed(dialect, name): + """Existing call sites keep working; they gain a string-valued node.""" + result = string_functions.upper(dialect, name) + assert isinstance(result, UpperFunction) + assert result.like("A%").to_sql()[0].endswith("LIKE ?") + + +def test_concat_includes_the_receiver(dialect, name): + """A variadic factory must receive the column as an operand. + + Passing the operand list as a single argument would bind the whole list to + one placeholder, which is what an earlier version of the mixin did. + """ + other = build_column(dialect, "other", str) + sql, params = name.concat(other, "x").to_sql() + assert sql.count("?") == 1 + assert params == ("x",) + assert '"other"' in sql + + +def test_json_path_builder_is_untouched(): + """The integer-index rule is a separate concern and must not regress.""" + assert build_json_path("tags", 0) == "$.tags[0]" + assert build_json_path("tags", "0") == "$.tags.0" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py new file mode 100644 index 00000000..19c9fd95 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py @@ -0,0 +1,200 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py +"""The seven surface-only column classes and the tables that answer them. + +These families have no operation the framework can promise on every backend -- +see ``value_types.SurfaceOnlyValue`` for the evidence -- so their column +classes take ``ColumnBase`` alone. This file checks the three things that +follows from: + +1. each class exists, is concrete, and builds a column that renders; +2. it offers the column surface (alias, null tests, casting) and no family + operation, in particular no comparison; +3. every dialect table that names it -- SQLite and the dummy baseline -- stays + complete (all twenty-four entries) and answers nothing with ``None``. +""" + +import datetime +import inspect + +import pytest + +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, +) +from rhosocial.activerecord.backend.dialect.mixins import ColumnTypeMixin +from rhosocial.activerecord.backend.expression import ( + BitStringColumn, + ColumnBase, + GeometryColumn, + IntervalColumn, + MacAddressColumn, + MultirangeColumn, + RangeColumn, + VectorColumn, +) +from rhosocial.activerecord.backend.expression.column_types import annotation_for +from rhosocial.activerecord.backend.expression.declared import SurfaceOnlyAnnotation +from rhosocial.activerecord.backend.expression.mixins import ComparisonMixin +from rhosocial.activerecord.backend.expression.value_types import SurfaceOnlyValue +from rhosocial.activerecord.backend.impl.dummy.column_type import DUMMY_COLUMN_TYPES +from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect +from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect +from rhosocial.activerecord.backend.impl.sqlite.mixins.column_type import ( + SQLITE_COLUMN_TYPES, +) +from rhosocial.activerecord.base.framework_types import FRAMEWORK_PYTHON_TYPES +from rhosocial.activerecord_postgres_test.feature.query.column_helpers import ( + resolve_column_class, +) + +#: ``{class: the framework type it answers}``, written out rather than derived: +#: a derived table would only restate the code back at itself. +SURFACE_ONLY = [ + (GeometryColumn, Geometry), + (VectorColumn, Vector), + (BitStringColumn, BitString), + (RangeColumn, Range), + (MultirangeColumn, Multirange), + (MacAddressColumn, MacAddress), + (IntervalColumn, datetime.timedelta), +] + +_IDS = [klass.__name__ for klass, _ in SURFACE_ONLY] + + +def sqlite_dialect(version=(3, 46, 1)): + return SQLiteDialect(version=version) + + +def dummy_dialect(): + dialect = DummyDialect() + dialect._version = (3, 46, 1) + return dialect + + +def test_the_value_surface_is_abstract(): + """A surface is not a node: it must not be instantiable. + + The annotation derived from it *is* a node -- it renders -- because + ``_Annotation`` supplies the ``format_method`` the surface declares. + """ + assert inspect.isabstract(SurfaceOnlyValue) + assert not inspect.isabstract(SurfaceOnlyAnnotation) + + +def test_the_value_surface_offers_no_family_operation(): + """Only alias, null tests and casting -- no comparison, no arithmetic.""" + assert ComparisonMixin not in SurfaceOnlyValue.__mro__ + assert not hasattr(SurfaceOnlyValue, "compare") + assert not hasattr(SurfaceOnlyValue, "add") + + +@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) +def test_each_class_is_concrete_and_renders(klass, entry): + """The protocol needs a class that builds; a failure here is a table hole.""" + assert inspect.isclass(klass) + assert not inspect.isabstract(klass) + assert issubclass(klass, ColumnBase) + column = klass(sqlite_dialect(), "c") + assert isinstance(column, ColumnBase) + assert column.to_sql() == ('"c"', ()) + + +@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) +def test_each_class_carries_only_the_column_surface(klass, entry): + """No comparison, no arithmetic, no string or JSON handling.""" + assert ComparisonMixin not in klass.__mro__ + column = klass(sqlite_dialect(), "c") + assert not hasattr(column, "compare") + assert not hasattr(column, "like") + assert not hasattr(column, "add") + # What it *does* carry is the shared column surface. + assert hasattr(column, "is_null") + assert hasattr(column, "is_not_null") + assert hasattr(column, "as_") + assert hasattr(column, "cast") + + +@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) +def test_each_class_is_annotated_with_the_surface_only_answer(klass, entry): + """The invariant test also asks this; asserting the exact answer pins it.""" + assert annotation_for(klass(sqlite_dialect(), "c")) is SurfaceOnlyAnnotation + + +def test_the_annotation_names_the_value_type_it_carries(): + """CASE and CAST read the value type off the annotation, so it must resolve.""" + assert SurfaceOnlyAnnotation.value_type_of() is SurfaceOnlyValue + + +def test_the_annotation_renders_its_source(): + """An annotation is a node: it wraps what it types and renders it.""" + from rhosocial.activerecord.backend.expression import Column + + dialect = sqlite_dialect() + annotated = SurfaceOnlyAnnotation(dialect, Column(dialect, "c", table="t")) + assert annotated.to_sql() == ('"t"."c"', ()) + + +def test_the_annotation_renders_an_aliasless_source(): + """The wrapped node need not expose an ``alias`` slot at all. + + A Literal renders a value and has no column-like surface, so reading + ``source.alias`` unconditionally raised AttributeError here. + """ + from rhosocial.activerecord.backend.expression import Literal + + dialect = sqlite_dialect() + annotated = SurfaceOnlyAnnotation(dialect, Literal(dialect, 1)) + assert annotated.to_sql() == ("?", (1,)) + + +@pytest.mark.parametrize( + "table, dialect_factory, expected", + [ + (SQLITE_COLUMN_TYPES, sqlite_dialect, "sqlite"), + (DUMMY_COLUMN_TYPES, dummy_dialect, "dummy"), + ], + ids=["sqlite", "dummy"], +) +def test_the_table_is_complete_and_refuses_nothing(table, dialect_factory, expected): + """Twenty-four entries, none answered with ``None``.""" + assert set(table) == set(FRAMEWORK_PYTHON_TYPES) + assert [key for key, value in table.items() if value is None] == [] + + +@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) +@pytest.mark.parametrize( + "dialect_factory, expected", + [(sqlite_dialect, "sqlite"), (dummy_dialect, "dummy")], + ids=["sqlite", "dummy"], +) +def test_the_tables_resolve_to_the_new_class(klass, entry, dialect_factory, expected): + assert resolve_column_class(dialect_factory(), entry) is klass + + +@pytest.mark.parametrize( + "dialect_factory, table", + [(sqlite_dialect, SQLITE_COLUMN_TYPES), (dummy_dialect, DUMMY_COLUMN_TYPES)], + ids=["sqlite", "dummy"], +) +def test_every_answer_selects_to_a_buildable_column(dialect_factory, table): + """Table completeness is only real if every answer builds and renders.""" + dialect = dialect_factory() + for entry in FRAMEWORK_PYTHON_TYPES: + column = resolve_column_class(dialect, entry)(dialect, "c") + assert isinstance(column, ColumnBase) + assert column.to_sql() == ('"c"', ()) + + +def test_the_base_mixin_still_states_no_table(): + """Neither dialect learnt a fallback: the tables are the answers.""" + + class Bare(ColumnTypeMixin): + pass + + assert Bare().suggested_extra_column_types() == {} diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py new file mode 100644 index 00000000..1aab9a53 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py @@ -0,0 +1,283 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_temporal_value_families.py +"""What each temporal operation answers with. + +A datetime is not one type. ``YEAR(ts)`` is a whole number, ``EXTRACT`` is a +number, ``NOW() + interval`` is a timestamp again, and ``NOW() - NOW()`` is an +interval. Getting these confused is silent — the SQL is still valid and +the answer is simply the wrong kind of thing — so each one is pinned here. + +The result's family is what decides the next operation, so the surface is +asserted too: a year may be added to, a timestamp may not be upper-cased. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_temporal_value_families.py +import datetime + +import pytest + +from rhosocial.activerecord.backend.expression import functions as datetime_functions +from rhosocial.activerecord.backend.expression.value_types import ( + NumericValue, + TemporalValue, +) +from rhosocial.activerecord.backend.expression.datetime import ( + DatetimeAddExpression, + DatetimeSubtractExpression, +) +from rhosocial.activerecord.backend.expression.operators import ArithmeticOperation + + +@pytest.fixture +def dialect(): + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + d = SQLiteDialect() + d._version = (3, 46, 1) + return d + + +@pytest.fixture +def timestamp(dialect): + from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column + + return build_column(dialect, "ts", datetime.datetime) + + +# --------------------------------------------------------------------------- +# The present, in each of its precisions +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "factory, cls", + [ + ("now", TemporalValue), + ("current_timestamp", TemporalValue), + ("localtimestamp", TemporalValue), + ("current_date", TemporalValue), + ("current_time", TemporalValue), + ], +) +def test_the_present_keeps_its_precision(dialect, factory, cls): + """A date is not a timestamp and a time is not either. + + Four separate classes now, where there was one class and a label saying + which it was standing in for. Each factory returns the class its own + precision calls for, and that is readable off the result. + """ + assert isinstance(getattr(datetime_functions, factory)(dialect), cls) + + +# --------------------------------------------------------------------------- +# Pulling a component out of a timestamp gives a whole number +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "factory", ["year", "month", "day", "hour", "minute", "second"] +) +def test_a_component_is_a_whole_number(dialect, timestamp, factory): + """A calendar component is a whole number on every backend. + + Asserted on the node's own class: the integral node is a distinct class from + the fractional one precisely because ``EXTRACT(EPOCH FROM ts)`` is not whole, + and that distinction now lives in the node rather than in a value class whose + operations were identical anyway. + """ + node = getattr(datetime_functions, factory)(dialect, timestamp) + assert type(node).__name__ == "ExtractFieldExpression" + + +def test_a_component_takes_arithmetic_and_not_string_operations(dialect, timestamp): + """A year is a number, so the number surface follows and the string one + does not. Getting this wrong is how ``str(year(ts))`` sneaks in.""" + year = datetime_functions.year(dialect, timestamp) + assert hasattr(year, "__add__") + assert not hasattr(year, "upper") + + +# --------------------------------------------------------------------------- +# Extraction is numeric because the unit decides it +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("factory", ["extract", "date_part"]) +def test_extraction_is_numeric(dialect, timestamp, factory): + """``EXTRACT(EPOCH FROM ts)`` is fractional, so the family is too wide to + be a whole number. Widening here is deliberate: claiming integer would + offer ``bit_length`` on a value that may be a million and a half.""" + assert isinstance(getattr(datetime_functions, factory)(dialect, "year", timestamp), NumericValue) + + +def test_date_diff_counts_whole_units(dialect): + now = datetime_functions.now(dialect) + assert isinstance(now.date_diff("day", now), NumericValue) + + +# --------------------------------------------------------------------------- +# Arithmetic on time stays time +# --------------------------------------------------------------------------- + + +def test_truncation_stays_a_timestamp(dialect): + assert isinstance(datetime_functions.now(dialect).date_trunc("day"), TemporalValue) + + +@pytest.mark.parametrize("method", ["date_add", "date_sub"]) +def test_shifting_time_stays_a_timestamp(dialect, method): + now = datetime_functions.now(dialect) + result = getattr(now, method)(1, "days") + assert isinstance(result, TemporalValue) + assert isinstance(result, (DatetimeAddExpression, DatetimeSubtractExpression)) + + +def test_an_interval_is_its_own_family(dialect): + """A span is not a point in time, which is why date_add takes one.""" + assert isinstance(datetime_functions.interval(dialect, 1, "day"), TemporalValue) + + +# --------------------------------------------------------------------------- +# The operators are interval-based; a point in time has no sum +# --------------------------------------------------------------------------- + + +def test_a_timestamp_moves_by_an_interval(dialect): + """Constructed, not rendered: SQLite has no interval node yet (the + emulation belongs to the data-type step), and what this test pins is the + gate that lets the combination through at all.""" + now = datetime_functions.now(dialect) + one_day = datetime_functions.interval(dialect, 1, "day") + expression = now + one_day + assert isinstance(expression, ArithmeticOperation) + + +def test_two_points_subtract_to_an_interval(dialect): + now = datetime_functions.now(dialect) + sql, params = (now - now).to_sql() + assert "-" in sql + + +def test_two_points_have_no_sum(dialect): + """``created_at + created_at`` used to render and fail only in SQL.""" + now = datetime_functions.now(dialect) + with pytest.raises(AttributeError, match="no sum"): + now + now + + +def test_interval_arithmetic_stays_between_intervals(dialect): + one_day = datetime_functions.interval(dialect, 1, "day") + two_days = datetime_functions.interval(dialect, 2, "day") + for expression in (one_day + two_days, one_day - two_days, one_day * 2): + assert isinstance(expression, ArithmeticOperation) + + +def test_a_number_does_not_move_a_point_in_time(dialect): + now = datetime_functions.now(dialect) + with pytest.raises(AttributeError): + now + 1 + + +def test_a_span_is_not_divided(dialect): + one_day = datetime_functions.interval(dialect, 1, "day") + with pytest.raises(AttributeError): + one_day / 2 + + +def test_a_temporal_column_follows_the_same_gate(dialect, timestamp): + """The column and the value are the same expression layer, so the gate + has to see a temporal *column* as a temporal operand too.""" + one_day = datetime_functions.interval(dialect, 1, "day") + assert isinstance(timestamp + one_day, ArithmeticOperation) + assert isinstance(timestamp - timestamp, ArithmeticOperation) + with pytest.raises(AttributeError, match="no sum"): + timestamp + timestamp + + +# --------------------------------------------------------------------------- +# A node with a class of its own is its type; there is nothing to declare +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "factory, args, result_cls", + [ + ("extract", ("year",), NumericValue), + ("date_part", ("year",), NumericValue), + ("interval", (1, "day"), TemporalValue), + ("date_diff", ("day",), NumericValue), + ("seconds_between", (), NumericValue), + ], +) +def test_a_temporal_operation_yields_its_own_type(dialect, timestamp, factory, args, result_cls): + """What a temporal operation yields is decided where it is built. + + ``EXTRACT`` yields a number and ``DATE_DIFF`` a whole number; each is + decided by the factory that builds the node, and neither needed a label to + say so afterwards. ``SECONDS_BETWEEN`` is the fractional member: seconds + are divisible, so its result is the numeric family again. + """ + if factory == "interval": + result = getattr(datetime_functions, factory)(dialect, *args) + elif factory in ("date_diff", "seconds_between"): + result = getattr(datetime_functions, factory)(dialect, *args, timestamp, timestamp) + else: + result = getattr(datetime_functions, factory)(dialect, *args, timestamp) + assert isinstance(result, result_cls) + + +def test_a_temporal_value_offers_temporal_operations(dialect): + now = datetime_functions.now(dialect) + for method in ("date_add", "date_sub", "date_diff", "seconds_between", "date_part", "extract"): + assert hasattr(now, method), f"a timestamp lost {method}" + + +def test_a_temporal_value_does_not_offer_string_operations(dialect): + assert not hasattr(datetime_functions.now(dialect), "upper") + + +@pytest.mark.parametrize( + "factory", + ["now", "current_date", "current_time", "current_timestamp", "localtimestamp"], +) +def test_each_temporal_value_is_its_own_node(dialect, factory): + """They offer the same operations, so they share a surface -- but they are + four different types, and each says so with its own class. + + A date and a date-time used to be one class with a label saying which it + was. Now the node is the statement, so this pins that a point in time is + still distinguishable from a span and from the other points by the class + the factory chose. + """ + node = getattr(datetime_functions, factory)(dialect) + assert isinstance(node, TemporalValue) + assert hasattr(node, "date_add") + + +def test_an_interval_is_a_span_and_not_a_point(dialect): + """The distinction the temporal gate asks about, stated by the node. + + ``_is_interval_value`` used to ask about a class nothing ever constructed, + which made the whole gate unreachable. The marker it asks about now is one + the interval node carries. + """ + from rhosocial.activerecord.backend.expression.mixins import IntervalMixin + + interval = datetime_functions.interval(dialect, 1, "day") + assert isinstance(interval, IntervalMixin) + assert isinstance(interval, TemporalValue) + assert not isinstance(datetime_functions.now(dialect), IntervalMixin) + + +def test_the_sql_does_not_change_when_a_type_is_stated(dialect, timestamp): + """Typing is a surface decision, never a rendering one.""" + from rhosocial.activerecord.backend.expression import FunctionCall + + call = FunctionCall(dialect, "MY_FUNC", timestamp) + assert call.as_datetime().to_sql() == call.to_sql() + + +def test_an_alias_survives_a_stated_type(dialect, timestamp): + from rhosocial.activerecord.backend.expression import FunctionCall + + call = FunctionCall(dialect, "MY_FUNC", timestamp) + assert " AS " in call.as_datetime().as_("when").to_sql()[0] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py new file mode 100644 index 00000000..79fbd998 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py @@ -0,0 +1,418 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_typed_columns.py +"""Type-narrowed column expressions. + +The column a model field resolves to depends on the field's Python +annotation, so a numeric field offers arithmetic and no ``.like()``, a JSON +field offers path access, and so on. These tests pin the selection the field +accessor makes, the narrowing it produces, and the guarantees that make it +safe to rely on. + +No database is involved — every assertion is on the expression tree or the +SQL a dialect produces from it — so no provider fixture is required. +""" + +import datetime +import decimal +import typing +import uuid +from typing import Any, ClassVar, Dict, List, Optional, Union + +import pytest + +from rhosocial.activerecord.backend.expression import ( + ArrayColumn, + BinaryColumn, + BooleanColumn, + Column, + ColumnBase, + TimestampColumn, + IntegerColumn, + IntervalColumn, + JSONColumn, + NumericColumn, + StringColumn, + UUIDColumn, + build_json_path, +) +from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect +from rhosocial.activerecord.base.field_proxy import ( + ColumnTypeResolutionError, + FieldAccessor, + FieldProxy, +) +from rhosocial.activerecord.base.fields import UseColumnType +from rhosocial.activerecord.model import ActiveRecord + +from rhosocial.activerecord_postgres_test.feature.query.column_helpers import ( + build_column, + resolve_column_class, +) + + +def column_class_for(annotation, dialect=None): + """The class the field accessor's selection picks for *annotation*. + + A one-line shim so the cases below read as "resolve this annotation" the + way ``Model.c.`` does it. The selection lives on + :class:`FieldAccessor`; a free framework-level function would have to + invent a backend or reach for a core-side table, which is the + core-authority shape the architecture removed. + """ + if dialect is None: + dialect = sqlite_dialect() + return resolve_column_class(dialect, annotation) + + +def sqlite_dialect(): + """A version-adapted SQLite dialect. + + ``supports_json_*`` reads ``self.version``, so the dialect must be + adapted before any rendering; 3.46 satisfies every gate these tests + exercise (JSON arrows need 3.38). + """ + dialect = SQLiteDialect() + dialect._version = (3, 46, 1) + return dialect + + +# --------------------------------------------------------------------------- +# Selection: annotation -> column class +# --------------------------------------------------------------------------- + +_DISPATCH = [ + (str, StringColumn), + (int, IntegerColumn), + (float, NumericColumn), + (bool, BooleanColumn), + (bytes, BinaryColumn), + (dict, JSONColumn), + # No array type exists in SQLite, so a `list` field is a JSON document here + # rather than an ArrayColumn. The same model on PostgreSQL gets a real array; + # that divergence is the protocol working, not a bug (see + # `test_column_type_support.py`). + (list, JSONColumn), + (decimal.Decimal, NumericColumn), + (datetime.datetime, TimestampColumn), + (datetime.date, TimestampColumn), + (datetime.timedelta, IntervalColumn), + (uuid.UUID, UUIDColumn), +] + + +@pytest.mark.parametrize("annotation, expected", _DISPATCH, ids=lambda v: getattr(v, "__name__", str(v))) +def test_dispatch_by_annotation(annotation, expected): + assert column_class_for(annotation) is expected + + +@pytest.mark.parametrize( + "annotation", + [ + Optional[str], + Optional[dict], + ], + ids=lambda v: str(v), +) +def test_optional_annotations_resolve_to_the_inner_entry(annotation): + assert column_class_for(annotation) in {StringColumn, JSONColumn} + + +@pytest.mark.parametrize( + "annotation", + [ + List[int], # a parameterised container is not classifiable + Dict[str, int], + Union[int, str], # genuinely ambiguous + Any, + ], + ids=lambda v: str(v), +) +def test_unclassifiable_annotations_fail(annotation): + """No guessing, and no escape: each of these raises at build time. + + This is the "全量或失败" ruling. These four used to become the permissive + ``Column``, which offered every operation to a value whose type nothing was + known about — so ``Model.c.meta.like('%x%')`` rendered happily and failed at + the database, with the error pointing at the SQL rather than at the + annotation that caused it. Narrowing exists to catch that at the point the + field is declared, so a hole in it is a hole in the guarantee. + + ``UseColumnType`` is the way through: it says which operations the value + carries, which is a statement the framework can honour on any backend. + """ + with pytest.raises(ColumnTypeResolutionError) as excinfo: + column_class_for(annotation) + assert "UseColumnType" in str(excinfo.value) + + +def test_optional_and_annotated_are_stripped(): + # typing.Annotated arrived in 3.9 and this project supports 3.8, so the + # alias is built the way the runtime marks one on every version. + Annotated = getattr(typing, "Annotated", None) + if Annotated is None: + pytest.skip("typing.Annotated requires Python 3.9+") + + strip = FieldAccessor._strip_annotation + assert strip(Optional[dict]) is dict + assert strip(Annotated[str, "some-marker"]) is str + assert strip(Optional[Annotated[str, "m"]]) is str + + +# --------------------------------------------------------------------------- +# Narrowing: each family offers only what its value type supports +# --------------------------------------------------------------------------- + + +def test_string_column_has_like_but_no_arithmetic(): + col = build_column(sqlite_dialect(), "name", str) + assert isinstance(col, StringColumn) + assert hasattr(col, "like") and hasattr(col, "ilike") + + # Arithmetic is refused explicitly rather than left absent: the operator is + # looked up on the type by the interpreter, so a missing one produces + # CPython's own TypeError instead of the package's message. hasattr is true + # because the method exists to raise, which is why the check calls it. + with pytest.raises(AttributeError): + col + 1 + with pytest.raises(AttributeError): + col * 2 + + +def test_integer_column_has_arithmetic_but_no_like(): + col = build_column(sqlite_dialect(), "age", int) + assert isinstance(col, IntegerColumn) + assert hasattr(col, "__add__") and hasattr(col, "__mul__") + assert not hasattr(col, "like") + + +def test_json_column_has_path_access_only(): + col = build_column(sqlite_dialect(), "settings", dict) + assert isinstance(col, JSONColumn) + assert hasattr(col, "json_path") and hasattr(col, "json_value") + assert not hasattr(col, "like") + assert not hasattr(col, "__add__") + + +def test_uuid_column_offers_no_uuid_specific_operator(): + """Portable SQL has none, so a UUID column is just a value column.""" + col = build_column(sqlite_dialect(), "uid", uuid.UUID) + assert isinstance(col, UUIDColumn) + assert not hasattr(col, "like") + assert not hasattr(col, "json_path") + with pytest.raises(AttributeError): + col + 1 + + +def test_bare_column_offers_no_operation(): + """The hand-built ``Column`` is a reference, and references do not guess. + + Nothing established what the column holds, so offering an operation + would be a promise the database never made — and the previous shape had + the failure the typed classes exist to prevent: comparing two of them + answered Python's identity question silently. The class renders (its one + job), the shared surface answers questions about the *reference* itself, + and predicates are built explicitly where the column's type is unknown. + """ + col = Column(sqlite_dialect(), "anything") + assert col.to_sql() == ('"anything"', ()) + for operation in ("like", "__add__", "json_path", "in_", "upper"): + assert not hasattr(col, operation), f"a bare column wrongly offers {operation}" + + +# --------------------------------------------------------------------------- +# Rendering: unchanged SQL, and a common format_column +# --------------------------------------------------------------------------- + +_RENDER_CLASSES = [ + Column, StringColumn, NumericColumn, TimestampColumn, BooleanColumn, + BinaryColumn, UUIDColumn, JSONColumn, ArrayColumn, +] + + +@pytest.mark.parametrize("column_class", _RENDER_CLASSES, ids=lambda c: c.__name__) +def test_every_column_class_renders_identically(column_class): + """Narrowing changed the API, not the SQL.""" + dialect = sqlite_dialect() + col = column_class(dialect, "settings", table="t", schema_name="s") + assert col.to_sql() == ('"s"."t"."settings"', ()) + + +@pytest.mark.parametrize("column_class", _RENDER_CLASSES, ids=lambda c: c.__name__) +def test_every_column_class_is_a_column_base(column_class): + """The 8 isinstance() consumers test for ColumnBase, so all must match.""" + assert isinstance(column_class(sqlite_dialect(), "x"), ColumnBase) + + +@pytest.mark.parametrize("column_class", _RENDER_CLASSES, ids=lambda c: c.__name__) +def test_qualified_and_aliased_rendering(column_class): + dialect = sqlite_dialect() + assert column_class(dialect, "c").to_sql() == ('"c"', ()) + assert column_class(dialect, "c", table="t").to_sql() == ('"t"."c"', ()) + assert column_class(dialect, "c", alias="a").to_sql() == ('"c" AS "a"', ()) + + +# --------------------------------------------------------------------------- +# JSON path building +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "keys, expected", + [ + ((), "$"), + (("a",), "$.a"), + (("a", "b"), "$.a.b"), + (("tags", 0), "$.tags[0]"), + (("a", 0, "b"), "$.a[0].b"), + (("tags", "[0]"), "$.tags[0]"), + ], + ids=lambda v: str(v), +) +def test_build_json_path(keys, expected): + assert build_json_path(*keys) == expected + + +def test_string_zero_is_a_key_not_an_index(): + """``"0"`` names a key; only an int is an index. + + ``$.tags.0`` is a key literally named ``0`` and matches nothing, so the + distinction is carried by the type rather than the spelling. + """ + assert build_json_path("tags", "0") == "$.tags.0" + assert build_json_path("tags", 0) == "$.tags[0]" + + +def test_bool_is_rejected_as_a_path_segment(): + """bool is an int subclass; silently treating True as index 1 is a trap.""" + with pytest.raises(TypeError, match="bool"): + build_json_path("a", True) + + +def test_json_path_renders_bracket_for_integer_index(): + dialect = sqlite_dialect() + col = build_column(dialect, "settings", dict) + assert col.json_path("tags", 0).to_sql() == ('"settings"->>\'$.tags[0]\'', ()) + + +def test_json_path_chains_without_renesting_the_path(): + """Chaining accumulates; it must not re-anchor the second path at ``$``.""" + dialect = sqlite_dialect() + col = build_column(dialect, "settings", dict) + assert col.json_value("a").json_value("b").to_sql() == ( + '"settings"->\'$.a\'->\'$.b\'', + (), + ) + + +def test_json_path_alias_lands_on_the_outermost_form(): + dialect = sqlite_dialect() + col = build_column(dialect, "settings", dict) + assert col.as_("j").json_path("a").to_sql() == ('"settings"->>\'$.a\' AS "j"', ()) + + +# --------------------------------------------------------------------------- +# End to end through FieldProxy +# --------------------------------------------------------------------------- + + +def _annotated(): + """``typing.Annotated``, or a skip — the alias is 3.9+ and this file is 3.8-safe.""" + alias = getattr(typing, "Annotated", None) + if alias is None: + pytest.skip("typing.Annotated requires Python 3.9+") + return alias + + +def _model(dialect): + Annotated = _annotated() + + class Widget(ActiveRecord): + @classmethod + def table_name(cls): + return "typed_widget" + + @classmethod + def primary_key(cls): + return "id" + + c: ClassVar[FieldProxy] = FieldProxy() + + id: int + name: str + qty: int + price: decimal.Decimal + created: datetime.datetime + settings: dict + tags: list + uid: uuid.UUID + flag: bool + # `Any` is not classifiable, so this field has to say what its value can + # do. The declaration is the whole point: without it the field does not + # resolve at all, which is the "全量或失败" ruling applied to a model. + meta: Annotated[Any, UseColumnType(JSONColumn)] + + Widget.__backend__ = type("B", (), {"dialect": dialect})() + return Widget + + +@pytest.mark.parametrize( + "field, expected", + [ + ("id", IntegerColumn), + ("name", StringColumn), + ("qty", IntegerColumn), + ("price", NumericColumn), + ("created", TimestampColumn), + ("settings", JSONColumn), + ("tags", JSONColumn), + ("uid", UUIDColumn), + ("flag", BooleanColumn), + ("meta", JSONColumn), # Any, resolved through UseColumnType + ], +) +def test_field_proxy_returns_the_matching_class(field, expected): + Widget = _model(sqlite_dialect()) + assert type(getattr(Widget.c, field)) is expected + + +def test_field_proxy_refuses_an_undeclared_any(): + """A model field typed ``Any`` with no declaration fails where it is read. + + The proxy is where a column is built, so this is the earliest point at which + the model can be told — and telling it here beats a driver error naming a + column at query time. + """ + + class Loose(ActiveRecord): + @classmethod + def table_name(cls): + return "typed_loose" + + @classmethod + def primary_key(cls): + return "id" + + c: ClassVar[FieldProxy] = FieldProxy() + + id: int + meta: Any + + Loose.__backend__ = type("B", (), {"dialect": sqlite_dialect()})() + with pytest.raises(ColumnTypeResolutionError, match="UseColumnType"): + # The proxy builds the column on attribute access, so the bare + # expression is the call under test -- the same shape as the + # AttributeError case below it. + Loose.c.meta # noqa: B018 + + +def test_field_proxy_query_uses_narrowed_operations(): + dialect = sqlite_dialect() + Widget = _model(dialect) + sql, params = Widget.query().where(Widget.c.settings.json_path("lang") == "en").to_sql() + assert sql == """SELECT * FROM "typed_widget" WHERE "typed_widget"."settings"->>'$.lang' = ?""" + assert params == ("en",) + + +def test_field_proxy_unknown_field_still_raises_attribute_error(): + Widget = _model(sqlite_dialect()) + with pytest.raises(AttributeError, match="does not exist on model"): + Widget.c.no_such_field diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py new file mode 100644 index 00000000..d9cf0f73 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py @@ -0,0 +1,226 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_family_inference.py +"""Result families, and the lattice they add up to. + +A family is what decides an expression's operation surface, and it has to be +accurate in both directions. Over-narrowing removes a legal operation; +over-widening offers an illegal one. Both failures are silent — the SQL is +still produced, it is just wrong — so the families are pinned here. + +The distinction that matters most is whole number against fraction. ``int`` and +``float`` share a column class, so the family has to come from the annotation +rather than the class, or "integer in, integer out" cannot be expressed and +``ceil`` of an integer claims to be fractional. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_family_inference.py +import datetime +import uuid + +import pytest + +from rhosocial.activerecord.backend.expression import Column, FunctionCall +from rhosocial.activerecord.backend.expression import functions as F +from rhosocial.activerecord.backend.expression.column_types import annotation_for +from rhosocial.activerecord.backend.expression.declared import ( + ArrayAnnotation, + BinaryAnnotation, + BooleanAnnotation, + IntegerAnnotation, + JSONAnnotation, + NumberAnnotation, + TemporalAnnotation, + TextAnnotation, + UUIDAnnotation, + XMLAnnotation, +) + +#: Every value class the lattice holds, for the "declares nothing" assertions. +TYPED_VALUE_CLASSES = ( + ArrayAnnotation, + BinaryAnnotation, + BooleanAnnotation, + IntegerAnnotation, + JSONAnnotation, + NumberAnnotation, + TemporalAnnotation, + TextAnnotation, + UUIDAnnotation, + XMLAnnotation, +) + + +@pytest.fixture +def dialect(): + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + d = SQLiteDialect() + d._version = (3, 46, 1) + return d + + +@pytest.fixture +def columns(dialect): + from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column + + return { + "string": build_column(dialect, "s", str), + "int": build_column(dialect, "i", int), + "float": build_column(dialect, "f", float), + "bool": build_column(dialect, "b", bool), + "json": build_column(dialect, "j", dict), + "bytes": build_column(dialect, "y", bytes), + "uuid": build_column(dialect, "u", uuid.UUID), + "datetime": build_column(dialect, "d", datetime.datetime), + } + + +# --------------------------------------------------------------------------- +# A column's family comes from its annotation +# --------------------------------------------------------------------------- + + +def test_every_column_class_has_an_annotation(columns): + """The map is complete, so no column class is silently untyped. + + There is no registry of family *names* to be complete any more -- a type is + a class. But there is a table from column class to value class (see + ``column_types.annotation_for``), and a column class missing from it would + make every operation over that column quietly untyped, which is the failure + this file exists to catch. So it is checked here instead of assumed. + """ + import inspect + + from rhosocial.activerecord.backend.expression import column_types as CT + + declared = { + name + for name, klass in vars(CT).items() + if inspect.isclass(klass) + and issubclass(klass, CT.ColumnBase) + and klass is not CT.ColumnBase + } + assert declared, "the typed column classes moved" + for name in sorted(declared): + column = getattr(CT, name).__new__(getattr(CT, name)) + assert annotation_for(column) is not None, f"{name} has no annotation" + # The base is now an ABC, so there is no "untyped column object" left to + # map -- not being able to build one is the stronger form of the same + # invariant. The untyped column that *can* be built is the bare ``Column``, + # which lives outside this module, and staying unmapped is still the point. + assert inspect.isabstract(CT.ColumnBase), "the typed base must not be instantiable" + from rhosocial.activerecord.backend.expression import Column as BareColumn + + assert annotation_for(BareColumn.__new__(BareColumn)) is None + + +def test_every_core_data_type_has_an_annotation_or_is_explicitly_impossible(): + """The DDL-type -> value-class map is closed, so a cast cannot go silently + untyped. + + There is a second completeness question beside the column one above, and it + is asked of the *target* side of a cast: ``cast`` answers from the class of + the ``DataType`` it was handed (``type_conversion._type_annotations()``), + so a core type missing from that table would make every cast to it come + back untyped and the operations its value supports invisible. A type added + to the core without a map entry must therefore be a test failure here, not + a quiet degradation. + + The loop walks every concrete core ``DataType`` currently loaded rather + than a hand-kept list, so a new core type file cannot dodge it by not being + imported. + + ``CustomType`` is the one deliberate exception and is asserted as such: it + is the escape hatch for a name this library does not model, so there is no + family it could honestly promise operations on (see its docstring), and the + map deliberately leaves it out. + """ + import inspect + + from rhosocial.activerecord.backend.expression import types as core_types + from rhosocial.activerecord.backend.expression.functions.type_conversion import ( + _type_annotations, + ) + + core_prefix = "rhosocial.activerecord.backend.expression.types" + seen = set() + stack = [core_types.DataType] + while stack: + klass = stack.pop() + if klass in seen: + continue + seen.add(klass) + stack.extend(klass.__subclasses__()) + declared = { + klass.__name__: klass + for klass in seen + if klass is not core_types.DataType + and not inspect.isabstract(klass) + and klass.__module__.startswith(core_prefix) + } + assert declared, "the core types moved" + + mapping = _type_annotations() + # The exception, stated rather than merely skipped. ``CustomType`` is the + # escape hatch for a type nobody here has heard of; mapping it to any value + # class would offer operations the database may reject. Asserting it stays + # unmapped is what keeps the exception the only one. + assert core_types.CustomType in declared.values() + assert core_types.CustomType not in mapping, ( + "CustomType must not map to a value class: it exists precisely because " + "nothing here knows what the type is, so no value surface can be " + "claimed for it" + ) + + for name, klass in sorted(declared.items()): + if klass is core_types.CustomType: + continue + assert any(base in mapping for base in klass.__mro__), ( + f"{name} has no annotation: add it to " + f"functions/type_conversion._type_annotations(), or add it to " + f"the deliberate-exception list here with the reason it cannot " + f"honestly have one" + ) + + +def test_a_bare_function_call_has_no_family(dialect, columns): + """It says nothing about what a database would return.""" + call = FunctionCall(dialect, "MY_FUNC", columns["string"]) + assert not isinstance(call, TYPED_VALUE_CLASSES) + + +def test_a_hand_written_column_has_no_family(dialect): + """A permissive Column means "unknown type", which is not the same as any.""" + assert not isinstance(Column(dialect, "x", table="t"), TYPED_VALUE_CLASSES) + + +@pytest.mark.parametrize( + "key, expected", + [ + ("string", TextAnnotation), + ("int", IntegerAnnotation), + ("float", NumberAnnotation), + ("bool", BooleanAnnotation), + ("json", JSONAnnotation), + ("bytes", BinaryAnnotation), + ("uuid", UUIDAnnotation), + ("datetime", TemporalAnnotation), + ], +) +def test_each_annotation_lands_in_its_type(columns, key, expected): + """The annotation picks the column class, and the class picks the annotation. + + This used to compare against a family *name* read off an attribute. The + attribute is gone and the class is the whole of it, so the assertion is the + annotation an operation over that column now returns. + """ + assert annotation_for(columns[key]) is expected + + +def test_a_disagreement_yields_no_type(dialect, columns): + """GREATEST of an integer and a string is legal SQL and is neither, so the + call stays generic rather than promising the first or the widest.""" + mixed = F.greatest(dialect, columns["int"], columns["string"]) + assert not isinstance(mixed, TYPED_VALUE_CLASSES) + assert mixed.to_sql() == FunctionCall( + dialect, "GREATEST", columns["int"], columns["string"] + ).to_sql() diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py new file mode 100644 index 00000000..a569088e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py @@ -0,0 +1,214 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_type_lattice.py +"""Every operation declares a result type, and the type gates the next operation. + +The rule this file pins: an operation's result determines which operations are +available next. ``upper()`` returns a string, so ``substr()`` follows. +``length()`` is a legal string operation whose result is a *number*, so +``upper()`` does not — and that falls out of the types rather than out of a +check somewhere. + +The two halves that are easy to get wrong are both pinned here: a result must +not lose its own surface, and it must not gain a surface belonging to another +family. +""" + +# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_type_lattice.py +import pytest + +from rhosocial.activerecord.backend.expression import ( + CharLengthFunction, +) + + +@pytest.fixture +def dialect(): + # The portable baseline: this file pins result *types* and the core + # spellings. Which spelling a backend writes is checked in + # test_operation_boundaries.py, against SQLite and a real database. + from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect + + return DummyDialect() + + +@pytest.fixture +def name(dialect): + from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column + + return build_column(dialect, "name", str) + + +# --------------------------------------------------------------------------- +# A string operation whose result is a number +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "method, args, function", + [ + ("length", (), "LENGTH"), + ("ascii", (), "ASCII"), + ("octet_length", (), "OCTET_LENGTH"), + ("bit_length", (), "BIT_LENGTH"), + ("strpos", ("a",), "STRPOS"), + ("position", ("a",), "POSITION"), + ], + ids=["length", "ascii", "octet_length", "bit_length", "strpos", "position"], +) +def test_number_returning_operation_yields_an_integer(name, method, args, function): + """These read a string and produce a count or a code. + + Each is now a node of its own -- ``CharLengthFunction``, + ``AsciiFunction``, ``OctetLengthFunction``, ``BitLengthFunction``, + ``PositionExpression`` -- so what the six share is asserted as the + **surface** rather than as a class: arithmetic is available and the string + surface is not. Asserting ``isinstance(result, IntegerAnnotation)`` would pin + the wrapper these operations used to be returned in, which is exactly what + the per-function classes removed. + """ + result = getattr(name, method)(*args) + assert hasattr(result, "__add__") + assert not hasattr(result, "upper") + assert function in result.to_sql()[0] + + +def test_the_whole_string_surface_offers_them(name): + """They are string operations, so they belong on the string surface. + + Their absence earlier was a gap in the surface, not a rule that only + string-to-string operations exist. + """ + for method in ("length", "ascii", "strpos", "position", "octet_length", "bit_length"): + assert hasattr(name, method), f"StringColumn is missing {method}" + + +# --------------------------------------------------------------------------- +# The result type gates the next operation +# --------------------------------------------------------------------------- + + +#: How many arguments each string operation *requires*, so the parametrized +#: test can call them all the same way. `substr` also takes an optional length +#: and `trim` optional characters and a direction; passing the minimum is +#: enough to reach the return, which is what is under test here. +#: +#: The placeholders are typed, not a repeated ``"x"``. Positions and counts are +#: integers and text operands are strings, and a call that got them wrong used +#: to pass silently -- a literal carrier accepted any value -- which is how +#: ``substr("x")`` came to mean "substring starting one character in" nowhere. +#: The typed value nodes now refuse it, which is the point of them. +_REQUIRED_ARGS = { + "upper": [], "lower": [], "trim": [], "initcap": [], + "substr": [1], "left": [1], "right": [1], + "concat": ["x"], + "replace": ["a", "b"], +} + + +def _call(name, method): + return getattr(name, method)(*_REQUIRED_ARGS[method]) + + +@pytest.mark.parametrize( + "method", ["upper", "lower", "substr", "trim", "concat", "replace", "left", "initcap"] +) +def test_string_result_keeps_the_string_surface(name, method): + """The result is a string and *says* so by offering the next operation. + + What is asserted is the surface, not one class: most of these return a + StringValue, but a node with its own dialect hook -- TRIM, whose + standard spelling is a syntax error on SQLite -- is its own class and + carries the same mixins, which is what makes ``col.trim().upper()`` legal. + """ + result = _call(name, method) + assert hasattr(result, "upper"), f"{method} did not return a string value" + assert hasattr(result, "substr"), f"{method} did not return a string value" + + +@pytest.mark.parametrize( + "chained, expected_functions", + [ + (lambda c: c.upper().substr(1, 3), ["UPPER", "SUBSTRING"]), + (lambda c: c.trim().replace("a", "b"), ["TRIM", "REPLACE"]), + (lambda c: c.upper().lower().initcap(), ["UPPER", "LOWER", "INITCAP"]), + ], + ids=["upper-substr", "trim-replace", "case-chain"], +) +def test_string_chain_stays_string(name, chained, expected_functions): + sql, _ = chained(name).to_sql() + for function in expected_functions: + assert function in sql + + +def test_number_result_loses_the_string_surface(name): + """A length has no case, so ``upper()`` must not exist on it.""" + result = name.length() + for method in ("upper", "lower", "substr", "trim", "initcap", "reverse"): + assert not hasattr(result, method), ( + f"an integer result wrongly offers {method}" + ) + + +def test_number_result_keeps_integer_operations(name): + """Arithmetic is legal on an integer, and stays an integer.""" + result = name.length() + assert hasattr(result, "__add__") + assert hasattr(result, "__sub__") + assert hasattr(result, "__mul__") + + +# --------------------------------------------------------------------------- +# The chain crosses families correctly +# --------------------------------------------------------------------------- + + +def test_string_then_number(name): + """upper() is a string, length() of it is a number.""" + result = name.upper().length() + assert isinstance(result, CharLengthFunction) + assert "LENGTH" in result.to_sql()[0] and "UPPER" in result.to_sql()[0] + + +def test_number_comparison_chains(name): + sql, _ = (name.length() > 5).to_sql() + assert "LENGTH" in sql and ">" in sql + + +def test_arithmetic_on_a_number_result(name): + """``length + 1`` is an arithmetic expression over an integer value.""" + sql, params = (name.length() + 1).to_sql() + assert "LENGTH" in sql + assert params == (1,) + + +def test_a_number_result_can_be_compared_but_not_matched(name): + """Comparison is universal; ``LIKE`` is not. + + Every value can be compared, so ``length() > 5`` is offered. ``LIKE`` is + text matching and a whole number is not text, so the operation is not + offered — it fails here, at the point of the call, rather than at the + database. This used to be the other way round and the reason the typed + column classes exist at all. + """ + result = name.length() + assert " > " in (result > 0).to_sql()[0] + with pytest.raises(AttributeError): + result.like("1%") + + +# --------------------------------------------------------------------------- +# Crossing into a predicate ends the value chain +# --------------------------------------------------------------------------- + + +def test_predicate_ends_the_chain(name): + """A predicate is the end of the value chain whatever produced it.""" + predicate = name.upper().like("A%") + for method in ("upper", "length", "substr"): + assert not hasattr(predicate, method), ( + f"predicate wrongly offers {method}; the value chain should have ended" + ) + + +def test_integer_value_can_be_aliased(name): + sql, _ = name.length().as_("n").to_sql() + assert " AS " in sql diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py new file mode 100644 index 00000000..4f98e988 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py +"""Use the shared ``query/joins`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.joins.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py new file mode 100644 index 00000000..46cd32e4 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py @@ -0,0 +1,232 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py +"""Tests for the on_params parameter in JOIN methods (sync and async).""" + +from decimal import Decimal + +import pytest + + +class TestSyncJoinOnParams: + """Synchronous JOIN with on_params tests.""" + + def test_inner_join_with_on_params(self, order_fixtures): + """Test inner_join with a string ON condition and on_params.""" + User, Order, OrderItem = order_fixtures + + user = User(username="on_params_user", email="op@example.com", age=30) + user.save() + + order = Order(user_id=user.id, order_number="OP-001", total_amount=Decimal("100.00")) + order.save() + + results = ( + Order.query() + .inner_join( + User, + on='"user_id" = ?', + on_params=[user.id], + ) + .where(Order.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + def test_left_join_with_on_params(self, order_fixtures): + """Test left_join with a string ON condition and on_params.""" + User, Order, OrderItem = order_fixtures + + user = User(username="left_op_user", email="lop@example.com", age=30) + user.save() + + order = Order(user_id=user.id, order_number="LOP-001", total_amount=Decimal("50.00")) + order.save() + + results = ( + Order.query() + .left_join( + User, + on='"user_id" = ?', + on_params=[user.id], + ) + .where(Order.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + def test_join_with_on_params_and_alias(self, order_fixtures): + """Test join with on_params and table alias.""" + User, Order, OrderItem = order_fixtures + + user = User(username="alias_op_user", email="aop@example.com", age=30) + user.save() + + order = Order(user_id=user.id, order_number="AOP-001", total_amount=Decimal("120.00")) + order.save() + + results = ( + Order.query() + .inner_join( + User, + on='"user_id" = ?', + on_params=[user.id], + alias="u", + ) + .where(Order.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + def test_join_with_on_params_none_and_no_placeholders(self, order_fixtures): + """Test join with on_params=None when string ON has no placeholders.""" + User, Order, OrderItem = order_fixtures + + user = User(username="nop_op_user", email="nop@example.com", age=30) + user.save() + + order = Order(user_id=user.id, order_number="NOP-001", total_amount=Decimal("80.00")) + order.save() + + # Use a string ON condition without placeholders so on_params=None is valid + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + results = ( + Order.query() + .inner_join( + User, + on='"user_id" = "users"."id"', + on_params=None, + ) + .where(Order.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + def test_join_with_multiple_on_params(self, order_fixtures): + """Test join with multiple on_params values.""" + User, Order, OrderItem = order_fixtures + + user = User(username="multi_op_user", email="mop@example.com", age=30) + user.save() + + order = Order(user_id=user.id, order_number="MOP-001", total_amount=Decimal("100.00"), status="active") + order.save() + + results = ( + Order.query() + .inner_join( + User, + on='"user_id" = ? AND "status" = ?', + on_params=[user.id, "active"], + ) + .where(Order.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + +class TestAsyncJoinOnParams: + """Asynchronous JOIN with on_params tests.""" + + @pytest.mark.asyncio + async def test_async_inner_join_with_on_params(self, async_order_fixtures): + """Test async inner_join with a string ON condition and on_params.""" + AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures + + user = AsyncUser(username="async_op_user", email="aop@example.com", age=30) + await user.save() + + order = AsyncOrder(user_id=user.id, order_number="AOP-001", total_amount=Decimal("100.00")) + await order.save() + + results = ( + await AsyncOrder.query() + .inner_join( + AsyncUser, + on='"user_id" = ?', + on_params=[user.id], + ) + .where(AsyncOrder.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + @pytest.mark.asyncio + async def test_async_left_join_with_on_params(self, async_order_fixtures): + """Test async left_join with a string ON condition and on_params.""" + AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures + + user = AsyncUser(username="async_lop_user", email="alop@example.com", age=30) + await user.save() + + order = AsyncOrder(user_id=user.id, order_number="ALOP-001", total_amount=Decimal("50.00")) + await order.save() + + results = ( + await AsyncOrder.query() + .left_join( + AsyncUser, + on='"user_id" = ?', + on_params=[user.id], + ) + .where(AsyncOrder.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + @pytest.mark.asyncio + async def test_async_join_with_on_params_and_alias(self, async_order_fixtures): + """Test async join with on_params and table alias.""" + AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures + + user = AsyncUser(username="async_aop_user", email="aaop@example.com", age=30) + await user.save() + + order = AsyncOrder(user_id=user.id, order_number="AAOP-001", total_amount=Decimal("120.00")) + await order.save() + + results = ( + await AsyncOrder.query() + .inner_join( + AsyncUser, + on='"user_id" = ?', + on_params=[user.id], + alias="u", + ) + .where(AsyncOrder.c.id == order.id) + .all() + ) + + assert len(results) >= 1 + + @pytest.mark.asyncio + async def test_async_join_with_multiple_on_params(self, async_order_fixtures): + """Test async join with multiple on_params values.""" + AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures + + user = AsyncUser(username="async_mop_user", email="amop@example.com", age=30) + await user.save() + + order = AsyncOrder(user_id=user.id, order_number="AMOP-001", total_amount=Decimal("100.00"), status="active") + await order.save() + + results = ( + await AsyncOrder.query() + .inner_join( + AsyncUser, + on='"user_id" = ? AND "status" = ?', + on_params=[user.id, "active"], + ) + .where(AsyncOrder.c.id == order.id) + .all() + ) + + assert len(results) >= 1 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py new file mode 100644 index 00000000..46f6cf42 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py @@ -0,0 +1,178 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py +""" +Unit tests for JoinQueryMixin._resolve_right_table / AsyncJoinQueryMixin._resolve_right_table. + +These tests lock in the alias non-contamination contract for join targets: +passing a NamedRelationRef or JoinClause with an alias must return a NEW +aliased copy and never mutate the caller's expression (regression tests for +the ``as_()`` copy semantics and the ``issubclass`` model-class guard). +""" + +from types import SimpleNamespace + +import pytest + +from rhosocial.activerecord.backend.expression import JoinExpression +from rhosocial.activerecord.backend.expression.sources import NamedRelationRef +from rhosocial.activerecord.backend.expression.query_parts import JoinClause +from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect +from rhosocial.activerecord.query.join import JoinQueryMixin +from rhosocial.activerecord.query.async_join import AsyncJoinQueryMixin +from rhosocial.activerecord.backend.expression.objects import Table + + +@pytest.fixture +def dummy_dialect(): + """Provides a DummyDialect instance that supports all features.""" + return DummyDialect() + + +def _make_join_expression(dialect: DummyDialect) -> JoinClause: + """Build a minimal valid JoinClause for alias tests.""" + return JoinClause( + dialect, + left_table=NamedRelationRef(dialect, Table(dialect, "users")), + right_table=NamedRelationRef(dialect, Table(dialect, "items")), + join_type="INNER JOIN", + using=["id"], + ) + + +class _SyncJoinQueryStub(JoinQueryMixin): + """Minimal query double exposing only what JoinQueryMixin needs.""" + + def __init__(self, dialect: DummyDialect): + self._dialect = dialect + self.join_clause = None + + def backend(self): + return SimpleNamespace(dialect=self._dialect) + + +class _AsyncJoinQueryStub(AsyncJoinQueryMixin): + """Minimal async query double exposing only what AsyncJoinQueryMixin needs.""" + + def __init__(self, dialect: DummyDialect): + self._dialect = dialect + self.join_clause = None + + def backend(self): + return SimpleNamespace(dialect=self._dialect) + + +class TestSyncResolveRightTable: + """Sync _resolve_right_table alias resolution tests.""" + + def test_table_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): + table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) + query = _SyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table(table, alias="o") + + assert resolved is not table + assert isinstance(resolved, (NamedRelationRef, JoinExpression)) + assert resolved.alias == "o" + assert table.alias is None + assert resolved.to_sql()[0] == '"orders" AS "o"' + assert table.to_sql()[0] == '"orders"' + + def test_same_table_reused_with_two_aliases(self, dummy_dialect: DummyDialect): + """Self-join style reuse: one NamedRelationRef, two independent aliases.""" + table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) + query = _SyncJoinQueryStub(dummy_dialect) + + first = query._resolve_right_table(table, alias="o1") + second = query._resolve_right_table(table, alias="o2") + + assert first is not second + assert first.alias == "o1" + assert second.alias == "o2" + assert table.alias is None + + def test_table_expression_without_alias_is_passthrough(self, dummy_dialect: DummyDialect): + table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) + query = _SyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table(table, alias=None) + + assert resolved is table + + def test_join_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): + join_expr = _make_join_expression(dummy_dialect) + query = _SyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table(join_expr, alias="jx") + + assert resolved is not join_expr + assert isinstance(resolved, (NamedRelationRef, JoinExpression)) + assert resolved.alias == "jx" + assert join_expr.alias is None + assert resolved.to_sql()[0].endswith('AS "jx"') + + def test_string_target_with_alias(self, dummy_dialect: DummyDialect): + query = _SyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table("orders", alias="o") + + assert isinstance(resolved, NamedRelationRef) + assert resolved.alias == "o" + + def test_unsupported_type_raises_type_error(self, dummy_dialect: DummyDialect): + query = _SyncJoinQueryStub(dummy_dialect) + + with pytest.raises(TypeError): + query._resolve_right_table(42, alias="o") # type: ignore[arg-type] + + +class TestAsyncResolveRightTable: + """Async _resolve_right_table alias resolution tests.""" + + def test_table_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): + table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) + query = _AsyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table(table, alias="o") + + assert resolved is not table + assert isinstance(resolved, (NamedRelationRef, JoinExpression)) + assert resolved.alias == "o" + assert table.alias is None + assert resolved.to_sql()[0] == '"orders" AS "o"' + assert table.to_sql()[0] == '"orders"' + + def test_same_table_reused_with_two_aliases(self, dummy_dialect: DummyDialect): + table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) + query = _AsyncJoinQueryStub(dummy_dialect) + + first = query._resolve_right_table(table, alias="o1") + second = query._resolve_right_table(table, alias="o2") + + assert first is not second + assert first.alias == "o1" + assert second.alias == "o2" + assert table.alias is None + + def test_join_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): + join_expr = _make_join_expression(dummy_dialect) + query = _AsyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table(join_expr, alias="jx") + + assert resolved is not join_expr + assert isinstance(resolved, (NamedRelationRef, JoinExpression)) + assert resolved.alias == "jx" + assert join_expr.alias is None + + def test_string_target_with_alias(self, dummy_dialect: DummyDialect): + query = _AsyncJoinQueryStub(dummy_dialect) + + resolved = query._resolve_right_table("orders", alias="o") + + assert isinstance(resolved, NamedRelationRef) + assert resolved.alias == "o" + + def test_unsupported_type_raises_type_error(self, dummy_dialect: DummyDialect): + query = _AsyncJoinQueryStub(dummy_dialect) + + with pytest.raises(TypeError): + query._resolve_right_table(42, alias="o") # type: ignore[arg-type] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md new file mode 100644 index 00000000..43a6c447 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md @@ -0,0 +1,13 @@ +# query/relation tests (sqlite bridge) + +SQLite bridge for the shared `feature/query/relation` testsuite topic. This +directory was moved from `feature/relation/` and merged with the old +`feature/query/relations/` bridge group, mirroring the testsuite source tree. + +- `conftest.py` — star-imports `testsuite.feature.query.relation.conftest`. +- `core/` — sqlite-local relation tests (unchanged). +- `ordering/` — bridge to `testsuite.feature.query.relation.ordering`. +- `legacy/` — the merged old `query/relations` real-database `with_()` integration + tests (`test_with_integration.py`) plus a self-contained L2 conftest. + +See [feature tests](../README.md) and [tests/README.md](../../../../README.md). diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py new file mode 100644 index 00000000..6659724d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py @@ -0,0 +1,7 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py +"""Fixtures for the relation feature tests. + +The topic conftest supplies the fixtures and the minimal test set for this +directory's database. +""" +from rhosocial.activerecord.testsuite.feature.query.relation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py new file mode 100644 index 00000000..74b202df --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py @@ -0,0 +1,242 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_async_descriptors.py +""" +Async relation descriptor tests. + +These tests mirror the sync descriptor tests but use async versions +to ensure sync/async parity. +""" + +import pytest +from typing import ClassVar + +from pydantic import BaseModel + +from rhosocial.activerecord.relation.base import RelationManagementMixin +from rhosocial.activerecord.relation.async_descriptors import ( + AsyncBelongsTo, + AsyncHasOne, + AsyncHasMany, +) +from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache + + +class AsyncAuthor(RelationManagementMixin, BaseModel): + id: int + name: str + books: ClassVar[AsyncHasMany["AsyncBook"]] = AsyncHasMany(foreign_key="author_id", inverse_of="author") + + +class AsyncBook(RelationManagementMixin, BaseModel): + id: int + title: str + author_id: int + author: ClassVar[AsyncBelongsTo["AsyncAuthor"]] = AsyncBelongsTo(foreign_key="author_id", inverse_of="books") + + +class AsyncProfile(RelationManagementMixin, BaseModel): + id: int + bio: str + author_id: int + author: ClassVar[AsyncBelongsTo["AsyncAuthor"]] = AsyncBelongsTo(foreign_key="author_id", inverse_of="profile") + + +class AsyncAuthorWithProfile(RelationManagementMixin, BaseModel): + id: int + name: str + books: ClassVar[AsyncHasMany["AsyncBook"]] = AsyncHasMany(foreign_key="author_id", inverse_of="author") + profile: ClassVar[AsyncHasOne["AsyncProfile"]] = AsyncHasOne(foreign_key="author_id", inverse_of="author") + + +class TestAsyncRelationDescriptors: + """Tests for async relation descriptor functionality.""" + + def test_async_belongs_to_descriptor(self): + """Test AsyncBelongsTo descriptor functionality.""" + relation = AsyncBook.get_relation("author") + assert isinstance(relation, AsyncBelongsTo) + assert relation.foreign_key == "author_id" + assert relation.inverse_of == "books" + + def test_async_has_many_descriptor(self): + """Test AsyncHasMany descriptor functionality.""" + relation = AsyncAuthor.get_relation("books") + assert isinstance(relation, AsyncHasMany) + assert relation.foreign_key == "author_id" + assert relation.inverse_of == "author" + + def test_async_has_one_descriptor(self): + """Test AsyncHasOne descriptor functionality.""" + relation = AsyncAuthorWithProfile.get_relation("profile") + assert isinstance(relation, AsyncHasOne) + assert relation.foreign_key == "author_id" + assert relation.inverse_of == "author" + + def test_async_descriptor_set_name_callback(self): + """Test that __set_name__ is called on descriptor assignment.""" + + class AsyncTestModel(RelationManagementMixin, BaseModel): + id: int + items: ClassVar[AsyncHasMany["AsyncOtherItem"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") + + class AsyncOtherItem(RelationManagementMixin, BaseModel): + id: int + test_id: int + test: ClassVar[AsyncBelongsTo["AsyncTestModel"]] = AsyncBelongsTo(foreign_key="test_id", inverse_of="items") + + relation = AsyncTestModel.get_relation("items") + assert relation.name == "items" + assert relation._owner == AsyncTestModel + + def test_async_descriptor_invalid_foreign_key_type(self): + """Test that non-string foreign_key raises TypeError.""" + with pytest.raises(TypeError) as exc_info: + + class BadModel(RelationManagementMixin, BaseModel): + id: int + rel: ClassVar[AsyncHasMany] = AsyncHasMany(foreign_key=123, inverse_of="test") + + assert "foreign_key must be a string" in str(exc_info.value) + + def test_async_descriptor_invalid_cache_config(self): + """Test that non-CacheConfig cache_config raises TypeError at class definition.""" + + # This test verifies that invalid cache_config type would raise TypeError + # The actual error is raised at class definition time by Pydantic validation + # We just verify the descriptor accepts cache_config parameter + class AsyncModelWithCache(RelationManagementMixin, BaseModel): + id: int + rel: ClassVar[AsyncHasMany["AsyncTargetForCache"]] = AsyncHasMany( + foreign_key="test_id", inverse_of="test", cache_config=CacheConfig(ttl=60) + ) + + class AsyncTargetForCache(RelationManagementMixin, BaseModel): + id: int + test_id: int + test: ClassVar[AsyncBelongsTo["AsyncModelWithCache"]] = AsyncBelongsTo( + foreign_key="test_id", inverse_of="rel" + ) + + relation = AsyncModelWithCache.get_relation("rel") + assert relation._cache_config.ttl == 60 + + def test_async_descriptor_get_relation(self): + """Test that get_relation returns the correct descriptor.""" + relation = AsyncAuthor.get_relation("books") + assert relation is not None + assert isinstance(relation, AsyncHasMany) + + def test_async_descriptor_get_relations(self): + """Test that get_relations returns all relations.""" + relations = AsyncAuthor.get_relations() + assert "books" in relations + + def test_async_descriptor_unknown_relation(self): + """Test that get_relation returns None for unknown relation.""" + relation = AsyncAuthor.get_relation("unknown_relation") + assert relation is None + + +class TestAsyncRelationCache: + """Tests for async relation caching behavior.""" + + def test_async_instance_cache_set_get(self): + """Test basic async instance cache set and get.""" + + class AsyncTestModel(RelationManagementMixin, BaseModel): + id: int + rel: ClassVar[AsyncHasMany["AsyncTarget"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") + + class AsyncTarget(RelationManagementMixin, BaseModel): + id: int + test_id: int + test: ClassVar[AsyncBelongsTo["AsyncTestModel"]] = AsyncBelongsTo(foreign_key="test_id", inverse_of="rel") + + instance = AsyncTestModel(id=1) + config = CacheConfig(enabled=True) + + InstanceCache.set(instance, "rel", [{"id": 1, "name": "test"}], config) + + result = InstanceCache.get(instance, "rel", config) + assert result == [{"id": 1, "name": "test"}] + + def test_async_instance_cache_disabled(self): + """Test that caching is disabled when config.enabled is False.""" + + class AsyncTestModel(RelationManagementMixin, BaseModel): + id: int + rel: ClassVar[AsyncHasMany["AsyncTarget"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") + + class AsyncTarget(RelationManagementMixin, BaseModel): + id: int + test_id: int + + instance = AsyncTestModel(id=1) + config = CacheConfig(enabled=False) + + InstanceCache.set(instance, "rel", [{"id": 1}], config) + + result = InstanceCache.get(instance, "rel", config) + assert result is None + + def test_async_instance_cache_delete(self): + """Test async instance cache deletion.""" + + class AsyncTestModel(RelationManagementMixin, BaseModel): + id: int + rel: ClassVar[AsyncHasMany["AsyncTarget"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") + + class AsyncTarget(RelationManagementMixin, BaseModel): + id: int + test_id: int + + instance = AsyncTestModel(id=1) + config = CacheConfig() + + InstanceCache.set(instance, "rel", [{"id": 1}], config) + assert InstanceCache.get(instance, "rel", config) == [{"id": 1}] + + InstanceCache.delete(instance, "rel") + + assert InstanceCache.get(instance, "rel", config) is None + + +class TestAsyncRelationManagementMixin: + """Tests for async RelationManagementMixin functionality.""" + + def test_async_register_relation(self): + """Test registering async relation.""" + + class AsyncTestModel(RelationManagementMixin, BaseModel): + id: int + + from rhosocial.activerecord.relation.descriptors import RelationDescriptor + + descriptor = RelationDescriptor(foreign_key="test_id") + AsyncTestModel.register_relation("test_rel", descriptor) + + assert "test_rel" in AsyncTestModel.get_relations() + assert AsyncTestModel.get_relation("test_rel") == descriptor + + def test_async_clear_relation_cache(self): + """Test clearing async relation cache.""" + instance = AsyncAuthor(id=1, name="Test") + + InstanceCache.set(instance, "books", [{"id": 1}], CacheConfig()) + + assert InstanceCache.get(instance, "books", CacheConfig()) is not None + + instance.clear_relation_cache("books") + + assert InstanceCache.get(instance, "books", CacheConfig()) is None + + def test_async_clear_all_relations_cache(self): + """Test clearing all async relation caches.""" + instance = AsyncAuthor(id=1, name="Test") + + InstanceCache.set(instance, "books", [{"id": 1}], CacheConfig()) + + assert InstanceCache.get(instance, "books", CacheConfig()) is not None + + instance.clear_relation_cache() + + assert InstanceCache.get(instance, "books", CacheConfig()) is None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py new file mode 100644 index 00000000..f173e2fe --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py @@ -0,0 +1,218 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_batch_loading.py +""" +Tests for batch loading behavior in relations. + +These tests cover the batch loading functionality which is critical for +avoiding N+1 query problems in python-activerecord. +""" + +import pytest +from typing import ClassVar, Any, Optional, List, Dict + +from pydantic import BaseModel + +from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache +from rhosocial.activerecord.relation.base import RelationManagementMixin +from rhosocial.activerecord.relation.descriptors import ( + HasMany, + BelongsTo, + HasOne, +) +from rhosocial.activerecord.relation.interfaces import IRelationLoader + + +class AuthorForBatch(RelationManagementMixin, BaseModel): + id: int + name: str + books: ClassVar[HasMany["BookForBatch"]] = HasMany(foreign_key="author_id", inverse_of="author") + + +class BookForBatch(RelationManagementMixin, BaseModel): + id: int + title: str + author_id: int + author: ClassVar[BelongsTo["AuthorForBatch"]] = BelongsTo(foreign_key="author_id", inverse_of="books") + + +class RecordingBatchLoader(IRelationLoader): + """Loader that records what instances were loaded.""" + + def __init__(self, return_value=None): + self.loaded_instances: List[Any] = [] + self.batch_loaded_instances: List[List[Any]] = [] + self.return_value = return_value or [{"id": 1, "title": "Test Book"}] + + def load(self, instance: Any) -> Optional[List[Any]]: + self.loaded_instances.append(instance) + return self.return_value + + def batch_load(self, instances: List[Any], base_query: Any) -> Dict[int, Any]: + self.batch_loaded_instances.append(instances) + return {id(inst): self.return_value for inst in instances} + + +class TestBatchLoading: + """Tests for relation batch loading functionality.""" + + @pytest.fixture + def loader(self): + return RecordingBatchLoader() + + def test_batch_load_called_with_instances(self): + """Test that batch_load receives the correct instances.""" + loader = RecordingBatchLoader() + relation = AuthorForBatch.get_relation("books") + relation._loader = loader + + author1 = AuthorForBatch(id=1, name="Author 1") + author2 = AuthorForBatch(id=2, name="Author 2") + + relation.batch_load([author1, author2], None) + + assert len(loader.batch_loaded_instances) == 1 + assert len(loader.batch_loaded_instances[0]) == 2 + assert author1 in loader.batch_loaded_instances[0] + assert author2 in loader.batch_loaded_instances[0] + + def test_batch_load_returns_dict(self): + """Test that batch_load returns a dict mapping instance IDs.""" + loader = RecordingBatchLoader() + relation = AuthorForBatch.get_relation("books") + relation._loader = loader + + author = AuthorForBatch(id=1, name="Author 1") + + result = relation.batch_load([author], None) + + assert isinstance(result, dict) + assert id(author) in result + + def test_cached_results_not_loaded_again(self): + """Test that cached results are not loaded again in batch.""" + RecordingBatchLoader() + relation = AuthorForBatch.get_relation("books") + relation._cache_config = CacheConfig() + + author1 = AuthorForBatch(id=1, name="Author 1") + author2 = AuthorForBatch(id=2, name="Author 2") + + InstanceCache.set(author1, "books", [{"id": 99, "title": "Cached"}], CacheConfig()) + + result = relation.batch_load([author1, author2], None) + + assert id(author1) in result + assert result[id(author1)][0]["id"] == 99 + + def test_batch_load_with_empty_list(self): + """Test batch_load with empty instances list.""" + loader = RecordingBatchLoader() + relation = AuthorForBatch.get_relation("books") + relation._loader = loader + + result = relation.batch_load([], None) + + assert result == {} + assert len(loader.batch_loaded_instances) == 0 + + def test_all_cached_no_batch_load(self): + """Test that if all instances are cached, batch_load is not called.""" + loader = RecordingBatchLoader() + relation = AuthorForBatch.get_relation("books") + relation._cache_config = CacheConfig() + + author1 = AuthorForBatch(id=1, name="Author 1") + author2 = AuthorForBatch(id=2, name="Author 2") + + InstanceCache.set(author1, "books", [{"id": 1, "title": "Book 1"}], CacheConfig()) + InstanceCache.set(author2, "books", [{"id": 2, "title": "Book 2"}], CacheConfig()) + + relation.batch_load([author1, author2], None) + + assert len(loader.batch_loaded_instances) == 0 + + def test_partial_cache_loads_remaining(self): + """Test that only uncached instances are loaded.""" + relation = AuthorForBatch.get_relation("books") + relation._loader = RecordingBatchLoader() + relation._cache_config = CacheConfig() + + author1 = AuthorForBatch(id=1, name="Author 1") + author2 = AuthorForBatch(id=2, name="Author 2") + + InstanceCache.set(author1, "books", [{"id": 1, "title": "Cached"}], CacheConfig()) + + result = relation.batch_load([author1, author2], None) + + assert id(author1) in result + assert result[id(author1)][0]["id"] == 1 + assert id(author2) in result + + +class TestBelongsToBatchLoading: + """Tests for BelongsTo batch loading.""" + + def test_belongs_to_batch_load(self): + """Test BelongsTo relation batch loading.""" + + class BatchLoader(IRelationLoader): + def load(self, instance: Any) -> Optional[Any]: + return {"id": instance.author_id, "name": f"Author {instance.author_id}"} + + def batch_load(self, instances: List[Any], base_query: Any) -> Dict[int, Any]: + {inst.author_id for inst in instances} + return {id(inst): {"id": inst.author_id, "name": f"Author {inst.author_id}"} for inst in instances} + + loader = BatchLoader() + relation = BookForBatch.get_relation("author") + relation._loader = loader + + book1 = BookForBatch(id=1, title="Book 1", author_id=1) + book2 = BookForBatch(id=2, title="Book 2", author_id=2) + + result = relation.batch_load([book1, book2], None) + + assert isinstance(result, dict) + assert id(book1) in result + assert id(book2) in result + + +class TestHasOneBatchLoading: + """Tests for HasOne batch loading.""" + + def test_has_one_batch_load(self): + """Test HasOne relation batch loading.""" + + class ProfileForHasOne(RelationManagementMixin, BaseModel): + id: int + bio: str + author_id: int + author: ClassVar[BelongsTo["AuthorForHasOne"]] = BelongsTo(foreign_key="author_id", inverse_of="profile") + + class AuthorForHasOne(RelationManagementMixin, BaseModel): + id: int + name: str + profile: ClassVar[HasOne["ProfileForHasOne"]] = HasOne(foreign_key="author_id", inverse_of="author") + + class HasOneBatchLoader(IRelationLoader): + def load(self, instance: Any) -> Optional[Any]: + return {"id": 1, "bio": "Bio", "author_id": instance.id} + + def batch_load(self, instances: List[Any], base_query: Any) -> Dict[int, Any]: + return { + id(inst): {"id": inst.id, "bio": f"Bio for {inst.name}", "author_id": inst.id} for inst in instances + } + + loader = HasOneBatchLoader() + relation = AuthorForHasOne.get_relation("profile") + relation._loader = loader + + author1 = AuthorForHasOne(id=1, name="Author 1") + author2 = AuthorForHasOne(id=2, name="Author 2") + + result = relation.batch_load([author1, author2], None) + + assert isinstance(result, dict) + assert id(author1) in result + assert id(author2) in result + assert result[id(author1)]["author_id"] == 1 + assert result[id(author2)]["author_id"] == 2 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py new file mode 100644 index 00000000..bd7f2d47 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py @@ -0,0 +1,106 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_cache_result.py +""" +Tests for CacheResult dataclass and InstanceCache.get_with_meta(). + +Cache stampede protection and proactive refresh are intentionally +excluded from the framework. These tests verify the metadata-building +blocks that application code uses to implement its own strategy. +""" + + +from pydantic import BaseModel + +from rhosocial.activerecord.relation.cache import ( # noqa: E402 + CacheConfig, + CacheResult, + InstanceCache, +) + + +class TestCacheResult: + """CacheResult dataclass construction and defaults.""" + + def test_basic(self): + r = CacheResult(value="hello", age=10.0, origin="box-a", ttl=300) + assert r.value == "hello" + assert r.age == 10.0 + assert r.origin == "box-a" + assert r.ttl == 300 + + def test_defaults(self): + r = CacheResult(value=42) + assert r.age == 0.0 + assert r.origin is None + assert r.ttl is None + + def test_various_types(self): + r = CacheResult(value=[1, 2, 3]) + assert r.value == [1, 2, 3] + + r = CacheResult(value={"key": "val"}) + assert r.value == {"key": "val"} + + r = CacheResult(value=None) + assert r.value is None + + +class TestGetWithMeta: + """InstanceCache.get_with_meta() returns CacheResult with metadata.""" + + class _Model(BaseModel): + id: int + + def test_hit(self): + inst = self._Model(id=1) + cfg = CacheConfig(ttl=300) + InstanceCache.set(inst, "posts", ["p1", "p2"], cfg) + r = InstanceCache.get_with_meta(inst, "posts", cfg) + assert r is not None + assert r.value == ["p1", "p2"] + assert r.ttl == 300 + assert r.origin is None # InMemoryCache has no origin + assert r.age == 0.0 + + def test_miss(self): + inst = self._Model(id=2) + cfg = CacheConfig(ttl=300) + r = InstanceCache.get_with_meta(inst, "nonexistent", cfg) + assert r is None + + def test_disabled(self): + inst = self._Model(id=3) + cfg = CacheConfig(enabled=False) + InstanceCache.set(inst, "posts", ["p1"], CacheConfig()) + r = InstanceCache.get_with_meta(inst, "posts", cfg) + assert r is None + + def test_ttl_none(self): + inst = self._Model(id=4) + cfg = CacheConfig(ttl=None) + InstanceCache.set(inst, "data", "xyz", cfg) + r = InstanceCache.get_with_meta(inst, "data", cfg) + assert r is not None + assert r.value == "xyz" + assert r.ttl is None + + def test_origin_reflects_backend(self): + """get_with_meta origin matches the active backend origin.""" + orig_backend = InstanceCache._backend + try: + from rhosocial.activerecord.relation.cache_backends import InMemoryCache + + class CustomOrigin(InMemoryCache): + @property + def origin(self): + return "custom-node" + + InstanceCache.set_backend(CustomOrigin()) + + inst = self._Model(id=5) + cfg = CacheConfig(ttl=60) + InstanceCache.set(inst, "rel", "val", cfg) + r = InstanceCache.get_with_meta(inst, "rel", cfg) + assert r is not None + assert r.origin == "custom-node" + finally: + InstanceCache.set_backend(orig_backend) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py new file mode 100644 index 00000000..f2c3dec1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py @@ -0,0 +1,462 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_cache_serialization.py +""" +Comprehensive round-trip tests for cache serialization. + +Covers JSON (default), msgpack (when available), and pickle (UNSAFE) +serializers with simple values, complex Python objects, edge cases, +and large content from the testsuite sample files. +""" + +import json +import math +import os +from datetime import date, datetime, time, timedelta +from enum import Enum, auto +from typing import Any, Dict, List, Optional + +import pytest + +from rhosocial.activerecord.relation.cache_backends._protocol import CacheSerializer # noqa: E402 + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +_SAMPLE_DIR = None + + +def _find_samples() -> Optional[str]: + """Locate the testsuite sample directory.""" + global _SAMPLE_DIR + if _SAMPLE_DIR is not None: + return _SAMPLE_DIR + try: + import rhosocial.activerecord.testsuite as _ts + + base = os.path.dirname(_ts.__file__) + for attempt in [ + os.path.join(base, "feature", "query", "samples"), + os.path.join(base, "..", "..", "..", "..", "testsuite", "feature", "query", "samples"), + ]: + path = os.path.abspath(attempt) + if os.path.isdir(path): + _SAMPLE_DIR = path + return _SAMPLE_DIR + except Exception: + pass + return None + + +def _load_sample(name: str) -> str: + d = _find_samples() + if d is None: + pytest.skip("testsuite sample directory not found") + path = os.path.join(d, name) + if not os.path.exists(path): + pytest.skip(f"sample file not found: {path}") + with open(path, "r", encoding="utf-8") as f: + return f.read() + + +# --------------------------------------------------------------------------- +# Test data +# --------------------------------------------------------------------------- + + +class Color(Enum): + RED = auto() + GREEN = auto() + BLUE = auto() + + +SIMPLE_VALUES: List[Any] = [ + "hello", + "", + 0, + 1, + -1, + 3.14, + True, + False, + None, + [], + {}, + [1, 2, 3], + {"a": 1, "b": 2}, +] + +COMPLEX_VALUES: List[Any] = [ + {"nested": {"deeply": [1, [2, [3]]], "key": "val"}}, + [{"id": i, "name": f"Item {i}"} for i in range(100)], + {"mixed": [1, "two", 3.0, True, None, [1, 2], {"k": "v"}]}, + {"empty_nested": {"a": {}, "b": [], "c": {"d": {}}}}, +] + +EXTENDED_VALUES: List[Any] = [ + datetime(2026, 6, 2, 14, 30, 0, 123456), + date(2026, 6, 2), + time(14, 30, 0, 123456), + timedelta(days=7, hours=3, minutes=15), + Color.RED, + bytes([0x00, 0xFF, 0xAB, 0xCD]), + {1, 2, 3, 4, 5}, + complex(3, 4), + range(0, 10, 2), + {"dt": datetime.now(), "color": Color.BLUE, "data": bytes([1, 2, 3])}, + [datetime(2026, 1, 1), timedelta(hours=1), Color.GREEN], +] + +FLOAT_EPS = 1e-9 + + +# --------------------------------------------------------------------------- +# Serializer fixtures +# --------------------------------------------------------------------------- + + +@pytest.fixture(params=["json", "msgpack", "pickle"]) +def serializer(request) -> CacheSerializer: + fmt = request.param + if fmt == "msgpack": + try: + import msgpack # noqa: F401 + except ImportError: + pytest.skip("msgpack not installed") + return None + return CacheSerializer(format=fmt) + + +@pytest.fixture +def json_serializer() -> CacheSerializer: + return CacheSerializer(format="json") + + +@pytest.fixture +def pickle_serializer() -> CacheSerializer: + return CacheSerializer(format="pickle") + + +# --------------------------------------------------------------------------- +# Round-trip tests +# --------------------------------------------------------------------------- + + +class TestCacheSerializerBasic: + """Basic values round-trip through all serializer formats.""" + + @pytest.mark.parametrize("value", SIMPLE_VALUES) + def test_simple(self, serializer, value): + data = serializer.serialize(value) + restored = serializer.deserialize(data) + assert restored == value + assert type(restored) is type(value) + + def test_list_of_strings(self, serializer): + value = ["a" * 100] * 1000 + data = serializer.serialize(value) + restored = serializer.deserialize(data) + assert restored == value + assert len(restored) == 1000 + + +class TestCacheSerializerComplex: + """Complex nested values round-trip.""" + + @pytest.mark.parametrize("value", COMPLEX_VALUES) + def test_complex(self, serializer, value): + data = serializer.serialize(value) + restored = serializer.deserialize(data) + assert restored == value + + def test_large_dict(self, serializer): + value = {f"key_{i}": f"value_{i}" for i in range(5000)} + data = serializer.serialize(value) + restored = serializer.deserialize(data) + assert restored == value + assert len(restored) == 5000 + + +class TestCacheSerializerExtended: + """Extended types (datetime, Enum, bytes, etc.) through JSON (and msgpack).""" + + def _roundtrip_json(self, value): + ser = CacheSerializer(format="json") + data = ser.serialize(value) + return ser.deserialize(data) + + def test_datetime(self): + v = datetime(2026, 6, 2, 14, 30, 0, 123456) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "datetime" + assert restored["value"] == v.isoformat() + + def test_date(self): + v = date(2026, 6, 2) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "datetime" + assert restored["value"] == v.isoformat() + + def test_time(self): + v = time(14, 30, 0, 123456) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "time" + assert restored["value"] == v.isoformat() + + def test_timedelta(self): + v = timedelta(days=7, hours=3, minutes=15) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "timedelta" + assert isinstance(restored["value"], float) + assert abs(restored["value"] - v.total_seconds()) < FLOAT_EPS + + def test_enum(self): + v = Color.RED + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "enum" + assert restored["value"] == "RED" + + def test_bytes(self): + v = bytes([0x00, 0xFF, 0xAB, 0xCD]) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "bytes" + assert bytes.fromhex(restored["value"]) == v + + def test_set(self): + v = {1, 2, 3, 4, 5} + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "set" + assert set(restored["value"]) == v + + def test_complex_number(self): + v = complex(3, 4) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "complex" + assert restored["value"] == [3.0, 4.0] + + def test_range(self): + v = range(0, 10, 2) + restored = self._roundtrip_json(v) + assert isinstance(restored, dict) + assert restored["__type__"] == "range" + assert restored["value"] == [0, 10, 2] + + +class TestCacheSerializerMsgpackExtended: + """Extended types through msgpack (native support for bytes, etc.).""" + + @pytest.fixture + def msgpack_ser(self): + try: + import msgpack # noqa: F401 + except ImportError: + pytest.skip("msgpack not installed") + return CacheSerializer(format="msgpack") + + def test_bytes(self, msgpack_ser): + v = bytes([0x00, 0xFF, 0xAB]) + restored = msgpack_ser.deserialize(msgpack_ser.serialize(v)) + assert restored == v + + def test_datetime(self, msgpack_ser): + v = datetime(2026, 6, 2, 14, 30, 0) + restored = msgpack_ser.deserialize(msgpack_ser.serialize(v)) + # msgpack does not preserve datetime natively — it's treated as string + assert isinstance(restored, str) + + def test_set(self, msgpack_ser): + v = {1, 2, 3} + data = msgpack_ser.serialize(v) + with pytest.raises(TypeError): + msgpack_ser.deserialize(data) + + def test_enum(self, msgpack_ser): + v = Color.GREEN + data = msgpack_ser.serialize(v) + with pytest.raises(TypeError): + msgpack_ser.deserialize(data) + + +class TestCacheSerializerLargeContent: + """Large content round-trip using testsuite sample files.""" + + SAMPLE_FILES = [ + "jsonplaceholder_posts.json", + "python_home.html", + "plant_catalog.xml", + "unicode_multilingual.html", + "unicode_multilingual.json", + "unicode_multilingual.xml", + ] + + @pytest.mark.parametrize("filename", SAMPLE_FILES) + def test_large_content_json(self, json_serializer, filename): + content = _load_sample(filename) + data = json_serializer.serialize(content) + restored = json_serializer.deserialize(data) + assert restored == content + assert isinstance(restored, str) + assert len(restored) == len(content) + + @pytest.mark.parametrize("filename", SAMPLE_FILES) + def test_large_content_pickle(self, pickle_serializer, filename): + content = _load_sample(filename) + data = pickle_serializer.serialize(content) + restored = pickle_serializer.deserialize(data) + assert restored == content + + def test_json_placeholder_structure(self, json_serializer): + """Load a JSON file as dict, serialize and restore via JSON serializer.""" + content = _load_sample("jsonplaceholder_posts.json") + parsed = json.loads(content) + data = json_serializer.serialize(parsed) + restored = json_serializer.deserialize(data) + assert restored == parsed + assert len(restored) == len(parsed) + assert isinstance(restored, list) + + def test_multilingual_json_structure(self, json_serializer): + """Multilingual JSON with Unicode content.""" + content = _load_sample("unicode_multilingual.json") + parsed = json.loads(content) + data = json_serializer.serialize(parsed) + restored = json_serializer.deserialize(data) + assert restored == parsed + + +class TestCacheSerializerEdgeCases: + """Edge cases and error handling.""" + + def test_empty_string(self, serializer): + v = "" + data = serializer.serialize(v) + assert serializer.deserialize(data) == v + + def test_very_long_string(self, serializer): + v = "x" * 100_000 + data = serializer.serialize(v) + restored = serializer.deserialize(data) + assert restored == v + assert len(restored) == 100_000 + + def test_none_value(self, serializer): + data = serializer.serialize(None) + assert serializer.deserialize(data) is None + + def test_boolean_values(self, serializer): + for v in [True, False]: + data = serializer.serialize(v) + restored = serializer.deserialize(data) + assert restored is v or restored == v + assert isinstance(restored, bool) + + def test_integer_edge_cases(self, serializer): + for v in [0, 1, -1, 2**31 - 1, -(2**31), 2**63 - 1, -(2**63)]: + data = serializer.serialize(v) + restored = serializer.deserialize(data) + assert restored == v + assert type(restored) is type(v) + + def test_float_edge_cases(self, serializer): + for v in [0.0, -0.0, 3.141592653589793, float("inf"), float("-inf"), 1.7976931348623157e308, 5e-324]: + if math.isnan(v): + continue # NaN comparison is tricky + data = serializer.serialize(v) + restored = serializer.deserialize(data) + if isinstance(restored, float) and math.isnan(v): + assert math.isnan(restored) + else: + assert restored == v + + def test_deeply_nested_structure(self, serializer): + v = {"level1": {"level2": {"level3": {"level4": {"level5": "deep"}}}}} + data = serializer.serialize(v) + restored = serializer.deserialize(data) + assert restored == v + + def test_large_list_of_small_dicts(self, serializer): + v = [{"id": i, "val": str(i)} for i in range(10000)] + data = serializer.serialize(v) + restored = serializer.deserialize(data) + assert restored == v + assert len(restored) == 10000 + + +class TestCacheSerializerInvalidInput: + """Error handling for invalid/unsupported inputs.""" + + def test_unknown_format(self): + with pytest.raises(ValueError, match="Unknown serializer format"): + CacheSerializer(format="xml") + + def test_msgpack_not_installed(self): + + # Simulate missing msgpack by checking if we can bypass it + try: + import msgpack # noqa: F401 + + pytest.skip("msgpack is installed, can't test missing case") + except ImportError: + with pytest.raises(ImportError, match="msgpack"): + CacheSerializer(format="msgpack") + + def test_unserializable_object_json(self): + """JSON serializer can't handle arbitrary objects.""" + ser = CacheSerializer(format="json") + + class Unserializable: + pass + + with pytest.raises(TypeError): + ser.serialize(Unserializable()) + + def test_circular_reference_json(self): + """JSON serializer should raise on circular refs.""" + ser = CacheSerializer(format="json") + v: Dict[str, Any] = {"key": None} + v["key"] = v + with pytest.raises((ValueError, TypeError)): + ser.serialize(v) + + def test_pickle_serializer_warning(self): + with pytest.warns(UserWarning, match="unsafe"): + CacheSerializer(format="pickle") + + +class TestCacheSerializerCrossFormat: + """Data serialized in one format should not be expected to + deserialize correctly in another (negative testing).""" + + def test_json_data_cannot_be_read_by_pickle(self): + ser_json = CacheSerializer(format="json") + data = ser_json.serialize("hello") + ser_pickle = CacheSerializer(format="pickle") + with pytest.raises(Exception): # noqa: B017 + ser_pickle.deserialize(data) + + def test_pickle_data_cannot_be_read_by_json(self): + ser_pickle = CacheSerializer(format="pickle") + data = ser_pickle.serialize("hello") + ser_json = CacheSerializer(format="json") + with pytest.raises(Exception): # noqa: B017 + ser_json.deserialize(data) + + +class TestCacheSerializerFormatProperty: + """Serializer exposes its format.""" + + def test_format_property(self): + assert CacheSerializer(format="json").format == "json" + assert CacheSerializer(format="pickle").format == "pickle" + assert CacheSerializer().format == "json" + + def test_case_insensitive(self): + assert CacheSerializer(format="JSON").format == "json" + assert CacheSerializer(format="Pickle").format == "pickle" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py new file mode 100644 index 00000000..c34518cb --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py @@ -0,0 +1,650 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_descriptor_coverage.py +""" +Targeted tests to cover uncovered code paths in descriptors.py and async_descriptors.py. +Also identifies dead code. +""" + +from typing import ClassVar, ForwardRef + +import pytest +from pydantic import BaseModel + +from rhosocial.activerecord.relation.base import RelationManagementMixin +from rhosocial.activerecord.relation.descriptors import ( + BelongsTo, + HasOne, + HasMany, + DefaultIRelationLoader, +) +from rhosocial.activerecord.relation.type_resolver import evaluate_annotation +from rhosocial.activerecord.relation.async_descriptors import ( + AsyncBelongsTo, + AsyncHasMany, + AsyncDefaultRelationLoader, +) +from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache +from rhosocial.activerecord.relation.interfaces import IRelationLoader + + +# ============================================================================== +# 1. __init__ validation paths +# ============================================================================== + + +class TestDescriptorInit: + """Cover __init__ validation branches.""" + + def test_sync_invalid_foreign_key_type(self): + with pytest.raises(TypeError, match="foreign_key must be a string"): + BelongsTo(foreign_key=123) + + def test_sync_invalid_cache_config_type(self): + with pytest.raises(TypeError, match="cache_config must be instance of CacheConfig"): + BelongsTo(foreign_key="x_id", cache_config="not_a_cache_config") # type: ignore + + def test_async_invalid_foreign_key_type(self): + with pytest.raises(TypeError, match="foreign_key must be a string"): + AsyncBelongsTo(foreign_key=123) + + def test_async_invalid_cache_config_type(self): + with pytest.raises(TypeError, match="cache_config must be instance of CacheConfig"): + AsyncBelongsTo(foreign_key="x_id", cache_config="not_a_cache_config") # type: ignore + + +# ============================================================================== +# 2. __get__ class-level access +# ============================================================================== + + +class TestDescriptorGetClassLevel: + """Cover __get__ with instance=None path.""" + + def test_sync_get_on_class_returns_self(self): + class Dept(RelationManagementMixin, BaseModel): + id: int + name: str + employees: ClassVar[HasMany["Emp"]] = HasMany(foreign_key="dept_id", inverse_of="department") + + class Emp(RelationManagementMixin, BaseModel): + id: int + dept_id: int + department: ClassVar[BelongsTo["Dept"]] = BelongsTo(foreign_key="dept_id", inverse_of="employees") + + descriptor = Dept.__dict__["employees"] + result = descriptor.__get__(None, Dept) + assert result is descriptor + + def test_async_get_on_class_returns_self(self): + class Dept(RelationManagementMixin, BaseModel): + id: int + name: str + employees: ClassVar[AsyncHasMany["Emp"]] = AsyncHasMany(foreign_key="dept_id", inverse_of="department") + + class Emp(RelationManagementMixin, BaseModel): + id: int + dept_id: int + department: ClassVar[AsyncBelongsTo["Dept"]] = AsyncBelongsTo(foreign_key="dept_id", inverse_of="employees") + + descriptor = Dept.__dict__["employees"] + result = descriptor.__get__(None, Dept) + assert result is descriptor + + +# ============================================================================== +# 3. __delete__ +# ============================================================================== + + +class TestDescriptorDelete: + """Cover __delete__ path.""" + + def test_sync_delete_clears_cache(self): + class Owner(RelationManagementMixin, BaseModel): + id: int + items: ClassVar[HasMany["Item"]] = HasMany(foreign_key="owner_id", inverse_of="owner") + + class Item(RelationManagementMixin, BaseModel): + id: int + owner_id: int + owner: ClassVar[BelongsTo["Owner"]] = BelongsTo(foreign_key="owner_id", inverse_of="items") + + instance = Owner(id=1) + InstanceCache.set(instance, "items", [Item(id=1, owner_id=1)], CacheConfig()) + assert InstanceCache.get(instance, "items", CacheConfig()) is not None + + descriptor = Owner.__dict__["items"] + descriptor.__delete__(instance) + assert InstanceCache.get(instance, "items", CacheConfig()) is None + + def test_async_delete_clears_cache(self): + class Owner(RelationManagementMixin, BaseModel): + id: int + items: ClassVar[AsyncHasMany["Item"]] = AsyncHasMany(foreign_key="owner_id", inverse_of="owner") + + class Item(RelationManagementMixin, BaseModel): + id: int + owner_id: int + owner: ClassVar[AsyncBelongsTo["Owner"]] = AsyncBelongsTo(foreign_key="owner_id", inverse_of="items") + + instance = Owner(id=1) + InstanceCache.set(instance, "items", [Item(id=1, owner_id=1)], CacheConfig()) + assert InstanceCache.get(instance, "items", CacheConfig()) is not None + + descriptor = Owner.__dict__["items"] + descriptor.__delete__(instance) + assert InstanceCache.get(instance, "items", CacheConfig()) is None + + +# ============================================================================== +# 4. _load_relation paths (cache hit, loader error) +# ============================================================================== + + +class FakeSyncLoader(IRelationLoader): + def __init__(self, return_value=None, raise_error=False): + self.return_value = return_value + self.raise_error = raise_error + self.load_called = False + + def load(self, instance): + self.load_called = True + if self.raise_error: + raise RuntimeError("loader failed") + return self.return_value + + def batch_load(self, instances, base_query): + return {id(instances[0]): self.return_value} + + +class TestLoadRelation: + """Cover _load_relation cache hit, miss, and error paths.""" + + def test_sync_load_cache_hit(self): + data = {"id": 1} + loader = FakeSyncLoader(return_value=data) + + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id", loader=loader) + + instance = Source(id=1, target_id=1) + # Pre-set cache + InstanceCache.set(instance, "target", data, CacheConfig()) + # Access via descriptor + result = instance.target() + assert result == data + assert not loader.load_called + + def test_sync_load_cache_miss(self): + class Target(RelationManagementMixin, BaseModel): + id: int + name: str + + data = Target(id=1, name="test") + loader = FakeSyncLoader(return_value=data) + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id", loader=loader) + + instance = Source(id=1, target_id=1) + result = instance.target() + assert result == data + assert loader.load_called + + def test_sync_load_loader_error_returns_none(self): + loader = FakeSyncLoader(raise_error=True) + + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id", loader=loader) + + instance = Source(id=1, target_id=1) + result = instance.target() + assert result is None + + @pytest.mark.asyncio + async def test_async_load_cache_hit(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + data = {"id": 1} + loader = FakeSyncLoader(return_value=data) + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id", loader=loader) + + instance = Source(id=1, target_id=1) + InstanceCache.set(instance, "target", data, CacheConfig()) + result = await instance.target() + assert result == data + + +# ============================================================================== +# 5. _create_relation_method with args — exercises dead self._query path +# ============================================================================== + + +class TestCreateRelationMethodNoArgs: + """_create_relation_method no longer accepts args (dead code removed).""" + + def test_sync_relation_method_rejects_args(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") + + instance = Source(id=1, target_id=1) + method = Source.target.__get__(instance, Source) + with pytest.raises(TypeError): + method(some_arg="value") + + @pytest.mark.asyncio + async def test_async_relation_method_rejects_args(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") + + instance = Source(id=1, target_id=1) + method = Source.target.__get__(instance, Source) + with pytest.raises(TypeError): + await method(some_arg="value") + + +# ============================================================================== +# 6. _evaluate_forward_ref +# ============================================================================== + + +class TestEvaluateForwardRef: + """Cover evaluate_annotation function from type_resolver.""" + + def test_evaluate_string_ref(self): + class DummyModel(RelationManagementMixin, BaseModel): + id: int + + result = evaluate_annotation("DummyModel", DummyModel) + assert result is DummyModel + + def test_evaluate_forward_ref_direct(self): + class DummyModel(RelationManagementMixin, BaseModel): + id: int + + ref = ForwardRef("DummyModel") + result = evaluate_annotation(ref, DummyModel) + assert result is DummyModel + + def test_evaluate_forward_ref_with_module_scope(self): + """Test that forward ref resolves using module globals.""" + + class DummyModel(RelationManagementMixin, BaseModel): + id: int + + ref = ForwardRef("BaseModel") + result = evaluate_annotation(ref, DummyModel) + assert result is BaseModel + + +# ============================================================================== +# 7. RelationshipValidator / AsyncRelationshipValidator +# ============================================================================== + + +class TestRelationshipValidatorPaths: + """Cover RelationshipValidator validation branches.""" + + def test_valid_belongs_to_has_many_pair(self): + class Dept(RelationManagementMixin, BaseModel): + id: int + employees: ClassVar[HasMany["Emp"]] = HasMany(foreign_key="dept_id", inverse_of="department") + + class Emp(RelationManagementMixin, BaseModel): + id: int + dept_id: int + department: ClassVar[BelongsTo["Dept"]] = BelongsTo(foreign_key="dept_id", inverse_of="employees") + + # Trigger validation by accessing relation + Emp(id=1, dept_id=1).department() + + def test_valid_belongs_to_has_one_pair(self): + class User(RelationManagementMixin, BaseModel): + id: int + profile: ClassVar[HasOne["Profile"]] = HasOne(foreign_key="user_id", inverse_of="user") + + class Profile(RelationManagementMixin, BaseModel): + id: int + user_id: int + user: ClassVar[BelongsTo["User"]] = BelongsTo(foreign_key="user_id", inverse_of="profile") + + # Trigger validation + Profile(id=1, user_id=1).user() + + def test_invalid_has_many_has_many_pair(self): + """HasMany↔HasMany should fail validation on relation access.""" + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + a: ClassVar[HasMany["A"]] = HasMany(foreign_key="a_id", inverse_of="bs") + + # Validation is lazy — triggered on relation access + with pytest.raises(ValueError, match="Invalid relationship pair"): + A(id=1).bs() + + def test_auto_set_inverse_of(self): + """When inverse_of is None on the related model, it should be auto-set.""" + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + a: ClassVar[BelongsTo["A"]] = BelongsTo(foreign_key="a_id") + + # Trigger validation by accessing the relation + A(id=1).bs() + assert B.get_relation("a").inverse_of == "bs" + + def test_async_valid_belongs_to_has_many_pair(self): + class Dept(RelationManagementMixin, BaseModel): + id: int + employees: ClassVar[AsyncHasMany["Emp"]] = AsyncHasMany(foreign_key="dept_id", inverse_of="department") + + class Emp(RelationManagementMixin, BaseModel): + id: int + dept_id: int + department: ClassVar[AsyncBelongsTo["Dept"]] = AsyncBelongsTo(foreign_key="dept_id", inverse_of="employees") + + def test_missing_inverse_relationship(self): + """Inverse name does not exist on related model.""" + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="nonexistent") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + + with pytest.raises(ValueError, match="Inverse relationship.*not found"): + A(id=1).bs() + + def test_non_relation_inverse(self): + """Inverse exists but is not a RelationDescriptor.""" + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + a: ClassVar[str] = "not_a_descriptor" + + with pytest.raises(ValueError, match="must be a RelationDescriptor"): + A(id=1).bs() + + def test_async_missing_inverse_relationship(self): + """Inverse name does not exist on related model.""" + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[AsyncHasMany["B"]] = AsyncHasMany(foreign_key="a_id", inverse_of="nonexistent") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + + with pytest.raises(ValueError, match="Inverse relationship.*not found"): + A(id=1).bs() + + def test_async_auto_set_inverse_of(self): + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[AsyncHasMany["B"]] = AsyncHasMany(foreign_key="a_id", inverse_of="a") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + a: ClassVar[AsyncBelongsTo["A"]] = AsyncBelongsTo(foreign_key="a_id") + + # Trigger validation via get_related_model directly (avoids coroutine) + desc = A.get_relation("bs") + desc.get_related_model(A) + assert B.get_relation("a").inverse_of == "bs" + + def test_inconsistent_inverse_wrong_owner(self): + """Trigger 'Inconsistent inverse' by validating with an unrelated owner. + + WARNING: This simulates an unnatural scenario where validate() is called + with an owner class that does NOT own the descriptor. Under normal class + definition this path is unreachable, because validate() is only invoked + from __set_name__, which always passes the actual owner class. + Do NOT replicate this pattern in application code. + """ + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + a: ClassVar[BelongsTo["A"]] = BelongsTo(foreign_key="a_id", inverse_of="bs") + + # After B's validation, A.bs.inverse_of was auto-set to 'a'. + # Now call A.bs's validator with an unrelated owner class C. + class C(RelationManagementMixin, BaseModel): + id: int + + with pytest.raises(ValueError, match="Inconsistent inverse"): + A.get_relation("bs")._validator.validate(C, B) + + def test_async_inconsistent_inverse_wrong_owner(self): + """Async: trigger 'Inconsistent inverse' via unrelated owner. + + WARNING: Same unnatural scenario as the sync version. Do NOT replicate + in application code. + """ + + class A(RelationManagementMixin, BaseModel): + id: int + bs: ClassVar[AsyncHasMany["B"]] = AsyncHasMany(foreign_key="a_id", inverse_of="a") + + class B(RelationManagementMixin, BaseModel): + id: int + a_id: int + a: ClassVar[AsyncBelongsTo["A"]] = AsyncBelongsTo(foreign_key="a_id", inverse_of="bs") + + class C(RelationManagementMixin, BaseModel): + id: int + + with pytest.raises(ValueError, match="Inconsistent inverse"): + A.get_relation("bs")._validator.validate(C, B) + + +# ============================================================================== +# 8. DefaultIRelationLoader & AsyncDefaultRelationLoader — basic init +# ============================================================================== + + +class TestDefaultLoadersInit: + """Default loaders are created internally; verify existence.""" + + def test_sync_default_loader_created(self): + desc = BelongsTo(foreign_key="x_id") + loader = desc._loader + assert isinstance(loader, DefaultIRelationLoader) + assert loader.descriptor is desc + + def test_async_default_loader_created(self): + desc = AsyncBelongsTo(foreign_key="x_id") + loader = desc._loader + assert isinstance(loader, AsyncDefaultRelationLoader) + assert loader.descriptor is desc + + +# ============================================================================== +# 9. _create_query_method coverage via descriptor +# ============================================================================== + + +class TestCreateQueryMethod: + """Cover _create_query_method for both BelongsTo and HasOne/HasMany.""" + + def test_query_method_exists(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") + + assert hasattr(Source, "target_query") + # Calling requires a proper instance with backend → skip call, just check existence. + + def test_async_query_method_exists(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") + + assert hasattr(Source, "target_query") + + +# ============================================================================== +# 10. batch_load on RelationDescriptor / AsyncRelationDescriptor +# ============================================================================== + + +class TestDescriptorBatchLoad: + """Cover RelationDescriptor.batch_load with empty records.""" + + def test_sync_batch_load_empty_records(self): + desc = BelongsTo(foreign_key="x_id") + desc.name = "test_rel" + result = desc.batch_load([], None) + assert result == {} + + @pytest.mark.asyncio + async def test_async_batch_load_empty_records(self): + desc = AsyncBelongsTo(foreign_key="x_id") + desc.name = "test_rel" + result = await desc.batch_load([], None) + assert result == {} + + +# ============================================================================== +# 11. log method with offset +# ============================================================================== + + +class TestLogMethod: + """Cover the log method's offset handling.""" + + def test_log_with_offset(self): + desc = BelongsTo(foreign_key="x_id") + # Should not crash even without _owner + desc.log(10, "test message", offset=2) + + +# ============================================================================== +# 12. Resolve model type from annotations with ClassVar +# ============================================================================== + + +class TestResolveModel: + """Cover _resolve_model with different annotation patterns.""" + + def test_sync_resolve_belongs_to(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") + + desc = Source.get_relation("target") + model = desc.get_related_model(Source) + assert model is Target + + def test_async_resolve_belongs_to(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") + + desc = Source.get_relation("target") + model = desc.get_related_model(Source) + assert model is Target + + +# ============================================================================== +# 13. clear_cache on the bound relation method +# ============================================================================== + + +class TestRelationMethodClearCache: + """Cover the clear_cache lambda on relation methods.""" + + def test_sync_clear_cache(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") + + instance = Source(id=1, target_id=1) + InstanceCache.set(instance, "target", Target(id=1), CacheConfig()) + method = Source.target.__get__(instance, Source) + method.clear_cache() + assert InstanceCache.get(instance, "target", CacheConfig()) is None + + def test_async_clear_cache(self): + class Target(RelationManagementMixin, BaseModel): + id: int + + class Source(RelationManagementMixin, BaseModel): + id: int + target_id: int + target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") + + instance = Source(id=1, target_id=1) + InstanceCache.set(instance, "target", Target(id=1), CacheConfig()) + method = Source.target.__get__(instance, Source) + method.clear_cache() + assert InstanceCache.get(instance, "target", CacheConfig()) is None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py new file mode 100644 index 00000000..30764da9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py @@ -0,0 +1,352 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_descriptor_db_coverage.py +""" +Database-backed tests covering descriptor code paths that require SQLite. + +Covers: _create_query_method, _load_relation, DefaultIRelationLoader.load/batch_load, +RelationDescriptor.batch_load, cache interaction, HasOne path. +""" + +import pytest + +from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache + + +# ============================================================================== +# _create_query_method — calls model_class.query() with FK/PK filter +# ============================================================================== + + +class TestCreateQueryMethod: + """Cover _create_query_method for BelongsTo, HasMany, HasOne.""" + + def _save(self, model): + model.save() + return model + + def test_belongs_to_query_method(self, user_post_comment_classes): + """BelongsTo query filters by FK matching instance PK.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Alice") + user.save() + post = post_class(title="Post", body="Body", user_id=user.id) + post.save() + + query = post.user_query() + assert user.id is not None + results = query.all() + assert len(results) == 1 + assert results[0].id == user.id + + def test_has_many_query_method(self, user_post_comment_classes): + """HasMany query filters by FK matching instance PK.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Bob") + user.save() + p1 = post_class(title="Post A", body="Body", user_id=user.id) + p1.save() + p2 = post_class(title="Post B", body="Body", user_id=user.id) + p2.save() + + query = user.posts_query() + results = query.all() + assert len(results) == 2 + + def test_has_one_query_method(self, user_post_comment_classes): + """HasOne query method exists and can be called.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Carol") + user.save() + query = user.posts_query() + assert query is not None + assert user.id is not None + + +# ============================================================================== +# DefaultIRelationLoader.batch_load — BelongsTo path +# ============================================================================== + + +class TestDefaultLoaderBelongsTo: + """Cover DefaultIRelationLoader.batch_load for BelongsTo.""" + + def test_belongs_to_load_single(self, user_post_comment_classes): + """BelongsTo: comment loads its post.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Dave") + user.save() + post = post_class(title="Test", body="Body", user_id=user.id) + post.save() + comment = comment_class(body="Nice!", post_id=post.id) + comment.save() + + result = comment.post() + assert result is not None + assert result.id == post.id + assert result.title == "Test" + + def test_belongs_to_batch_load(self, user_post_comment_classes): + """BelongsTo batch_load: multiple comments share/span posts.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Eve") + user.save() + post1 = post_class(title="P1", body="B1", user_id=user.id) + post1.save() + post2 = post_class(title="P2", body="B2", user_id=user.id) + post2.save() + + c1 = comment_class(body="C1", post_id=post1.id) + c1.save() + c2 = comment_class(body="C2", post_id=post1.id) + c2.save() + c3 = comment_class(body="C3", post_id=post2.id) + c3.save() + + result = c2.post() + assert result is not None + assert result.id == post1.id + + +# ============================================================================== +# DefaultIRelationLoader.batch_load — HasMany path +# ============================================================================== + + +class TestDefaultLoaderHasMany: + """Cover DefaultIRelationLoader.batch_load for HasMany.""" + + def test_has_many_load(self, user_post_comment_classes): + """HasMany: user loads posts.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Heidi") + user.save() + p1 = post_class(title="A", body="B1", user_id=user.id) + p1.save() + p2 = post_class(title="B", body="B2", user_id=user.id) + p2.save() + + results = user.posts() + assert len(results) == 2 + + def test_has_many_empty(self, user_post_comment_classes): + """HasMany: user with no posts returns [].""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Ivan") + user.save() + + results = user.posts() + assert results == [] + + def test_has_many_batch_multiple_users(self, user_post_comment_classes): + """HasMany: multiple users with posts.""" + user_class, post_class, comment_class = user_post_comment_classes + u1 = user_class(name="Judy") + u1.save() + u2 = user_class(name="Karl") + u2.save() + p1 = post_class(title="U1P1", body="B", user_id=u1.id) + p1.save() + p2 = post_class(title="U2P1", body="B", user_id=u2.id) + p2.save() + p3 = post_class(title="U2P2", body="B", user_id=u2.id) + p3.save() + + r1 = u1.posts() + assert len(r1) == 1 + r2 = u2.posts() + assert len(r2) == 2 + + +# ============================================================================== +# DefaultIRelationLoader.batch_load — HasOne path +# ============================================================================== + + +class TestDefaultLoaderHasOne: + """Cover DefaultIRelationLoader.batch_load for HasOne.""" + + def test_has_one_load(self, user_post_comment_classes): + """HasOne — default loader branching is identical to HasMany for WHERE. + + The actual HasOne-vs-HasMany distinction in batch_load is just + taking result[0] vs result list. Verify HasMany path works. + """ + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Leo") + user.save() + p1 = post_class(title="H1", body="B", user_id=user.id) + p1.save() + results = user.posts() + assert len(results) == 1 + + +# ============================================================================== +# _load_relation — cache interaction +# ============================================================================== + + +class TestLoadRelationDb: + """Cover _load_relation with cache hit/miss/error using DB loader.""" + + def test_cache_hit_after_initial_load(self, user_post_comment_classes): + """Second access uses cache.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Mallory") + user.save() + p = post_class(title="Cached", body="B", user_id=user.id) + p.save() + + results = user.posts() + assert len(results) == 1 + + results2 = user.posts() + assert len(results2) == 1 + + def test_cache_bypass_with_disabled_cache(self, user_post_comment_classes): + """When cache is disabled, each access reloads.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Nina") + user.save() + + desc = user_class.get_relation("posts") + config = desc._cache_config + desc._cache_config = CacheConfig(enabled=False) + + p = post_class(title="NoCache", body="B", user_id=user.id) + p.save() + r1 = user.posts() + assert len(r1) == 1 + + desc._cache_config = config + + def test_cache_cleared_on_delete(self, user_post_comment_classes): + """__delete__ clears the instance cache.""" + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Oscar") + user.save() + post = post_class(title="Del", body="B", user_id=user.id) + post.save() + c = comment_class(body="C", post_id=post.id) + c.save() + + _ = post.comments() + + desc = post_class.get_relation("comments") + desc.__delete__(post) + + results = post.comments() + assert len(results) == 1 + + def test_cache_write_failure_still_returns_loaded_data(self, user_post_comment_classes, mocker): + user_class, post_class, comment_class = user_post_comment_classes + user = user_class(name="Peggy") + user.save() + post = post_class(title="CacheWriteFail", body="B", user_id=user.id) + post.save() + + mocker.patch.object(InstanceCache, "set", side_effect=TypeError("cache write failed")) + + results = user.posts() + assert len(results) == 1 + assert results[0].id == post.id + + +# ============================================================================== +# Async DefaultIRelationLoader +# ============================================================================== + + +class TestAsyncDefaultLoader: + """Cover AsyncDefaultRelationLoader with DB.""" + + @pytest.mark.asyncio + async def test_async_belongs_to_load(self, async_user_post_comment_classes): + user_class, post_class, comment_class = async_user_post_comment_classes + user = user_class(name="AsyncAlice") + await user.save() + post = post_class(title="AsyncPost", body="Body", user_id=user.id) + await post.save() + comment = comment_class(body="Nice", post_id=post.id) + await comment.save() + + result = await comment.post() + assert result is not None + assert result.id == post.id + + @pytest.mark.asyncio + async def test_async_has_many_load(self, async_user_post_comment_classes): + user_class, post_class, comment_class = async_user_post_comment_classes + user = user_class(name="AsyncBob") + await user.save() + p1 = post_class(title="A1", body="B1", user_id=user.id) + await p1.save() + p2 = post_class(title="A2", body="B2", user_id=user.id) + await p2.save() + + results = await user.posts() + assert len(results) == 2 + + @pytest.mark.asyncio + async def test_async_has_many_empty(self, async_user_post_comment_classes): + user_class, post_class, comment_class = async_user_post_comment_classes + user = user_class(name="AsyncCarol") + await user.save() + + results = await user.posts() + assert results == [] + + @pytest.mark.asyncio + async def test_async_cache_hit(self, async_user_post_comment_classes): + user_class, post_class, comment_class = async_user_post_comment_classes + user = user_class(name="AsyncEve") + await user.save() + p = post_class(title="Cached", body="B", user_id=user.id) + await p.save() + + r1 = await user.posts() + r2 = await user.posts() + assert len(r1) == 1 + assert len(r2) == 1 + + @pytest.mark.asyncio + async def test_async_batch_load_empty_records(self, async_user_post_comment_classes): + """AsyncRelationDescriptor.batch_load with empty records.""" + user_class, post_class, comment_class = async_user_post_comment_classes + desc = user_class.get_relation("posts") + result = await desc.batch_load([], None) + assert result == {} + + +# ============================================================================== +# Async _create_query_method +# ============================================================================== + + +class TestAsyncCreateQueryMethod: + """Cover async _create_query_method.""" + + @pytest.mark.asyncio + async def test_async_belongs_to_query(self, async_user_post_comment_classes): + user_class, post_class, comment_class = async_user_post_comment_classes + user = user_class(name="Alice") + await user.save() + post = post_class(title="P", body="B", user_id=user.id) + await post.save() + + query = post.user_query() + results = await query.all() + assert len(results) == 1 + assert results[0].id == user.id + + @pytest.mark.asyncio + async def test_async_has_many_query(self, async_user_post_comment_classes): + user_class, post_class, comment_class = async_user_post_comment_classes + user = user_class(name="Bob") + await user.save() + p1 = post_class(title="A", body="B1", user_id=user.id) + await p1.save() + p2 = post_class(title="B", body="B2", user_id=user.id) + await p2.save() + + query = user.posts_query() + results = await query.all() + assert len(results) == 2 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py new file mode 100644 index 00000000..97467851 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py @@ -0,0 +1,281 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_instance_cache.py +""" +Granular tests for InstanceCache functionality. + +These tests cover the instance-level caching mechanism specific to python-activerecord, +which is distinct from the RelationCache (class-level cache). +""" + +import time + +from pydantic import BaseModel + +from rhosocial.activerecord.relation.cache import ( + CacheConfig, + InstanceCache, + CacheEntry, +) + + +class TestInstanceCache: + """Tests for the InstanceCache functionality.""" + + def test_get_cache_attr_name(self): + """Test cache attribute name generation.""" + attr_name = InstanceCache.get_cache_attr_name("posts") + assert attr_name == "_relation_cache_posts" + + attr_name = InstanceCache.get_cache_attr_name("user") + assert attr_name == "_relation_cache_user" + + def test_get_instance_cache_creates_cache(self): + """Test that get_instance_cache creates cache dict if not exists.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + + cache = InstanceCache.get_instance_cache(instance, "test_relation") + assert isinstance(cache, dict) + assert "entry" not in cache + + def test_get_instance_cache_returns_existing(self): + """Test that get_instance_cache returns existing cache.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + + cache1 = InstanceCache.get_instance_cache(instance, "test_relation") + cache1["custom_key"] = "custom_value" + + cache2 = InstanceCache.get_instance_cache(instance, "test_relation") + assert cache2["custom_key"] == "custom_value" + + def test_instance_cache_isolation_between_relations(self): + """Test that different relations have isolated caches.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + + cache1 = InstanceCache.get_instance_cache(instance, "relation_a") + cache1["entry"] = CacheEntry("value_a") + + cache2 = InstanceCache.get_instance_cache(instance, "relation_b") + cache2["entry"] = CacheEntry("value_b") + + result_a = InstanceCache.get(instance, "relation_a", CacheConfig()) + result_b = InstanceCache.get(instance, "relation_b", CacheConfig()) + + assert result_a == "value_a" + assert result_b == "value_b" + + def test_instance_cache_isolation_between_instances(self): + """Test that different instances have isolated caches.""" + + class TestModel(BaseModel): + id: int + + instance1 = TestModel(id=1) + instance2 = TestModel(id=2) + + InstanceCache.set(instance1, "test_relation", "value1", CacheConfig()) + InstanceCache.set(instance2, "test_relation", "value2", CacheConfig()) + + result1 = InstanceCache.get(instance1, "test_relation", CacheConfig()) + result2 = InstanceCache.get(instance2, "test_relation", CacheConfig()) + + assert result1 == "value1" + assert result2 == "value2" + + def test_instance_cache_set_and_get(self): + """Test basic set and get operations.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig(enabled=True) + + InstanceCache.set(instance, "test_relation", "test_value", config) + + result = InstanceCache.get(instance, "test_relation", config) + assert result == "test_value" + + def test_instance_cache_disabled(self): + """Test that caching is disabled when config.enabled is False.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig(enabled=False) + + InstanceCache.set(instance, "test_relation", "test_value", config) + + result = InstanceCache.get(instance, "test_relation", config) + assert result is None + + def test_instance_cache_get_no_entry(self): + """Test get returns None when no entry exists.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig() + + result = InstanceCache.get(instance, "nonexistent", config) + assert result is None + + def test_instance_cache_expiration(self): + """Test cache entry expiration.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig(ttl=1) + + InstanceCache.set(instance, "test_relation", "test_value", config) + + result = InstanceCache.get(instance, "test_relation", config) + assert result == "test_value" + + time.sleep(1.1) + + result = InstanceCache.get(instance, "test_relation", config) + assert result is None + + def test_instance_cache_expiration_disabled(self): + """Test that entries with no TTL never expire.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig(ttl=None) + + InstanceCache.set(instance, "test_relation", "test_value", config) + + time.sleep(0.5) + + result = InstanceCache.get(instance, "test_relation", config) + assert result == "test_value" + + def test_instance_cache_delete(self): + """Test cache entry deletion.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig() + + InstanceCache.set(instance, "test_relation", "test_value", config) + assert InstanceCache.get(instance, "test_relation", config) == "test_value" + + InstanceCache.delete(instance, "test_relation") + + result = InstanceCache.get(instance, "test_relation", config) + assert result is None + + def test_instance_cache_delete_nonexistent(self): + """Test delete on nonexistent entry doesn't raise.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + + InstanceCache.delete(instance, "nonexistent") + + def test_instance_cache_clear(self): + """Test clearing cache for a specific relation.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig() + + InstanceCache.set(instance, "relation_a", "value_a", config) + InstanceCache.set(instance, "relation_b", "value_b", config) + + InstanceCache.delete(instance, "relation_a", config) + + result_a = InstanceCache.get(instance, "relation_a", config) + result_b = InstanceCache.get(instance, "relation_b", config) + + assert result_a is None + assert result_b == "value_b" + + def test_instance_cache_clear_disabled(self): + """Test that clear does nothing when caching is disabled.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig(enabled=False) + + InstanceCache.set(instance, "test_relation", "test_value", config) + InstanceCache.delete(instance, "test_relation", config) + + def test_instance_cache_with_complex_values(self): + """Test caching complex objects like lists and dicts.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig() + + complex_value = [ + {"id": 1, "name": "Item 1"}, + {"id": 2, "name": "Item 2"}, + ] + InstanceCache.set(instance, "items", complex_value, config) + + result = InstanceCache.get(instance, "items", config) + assert result == complex_value + + def test_instance_cache_with_none_value(self): + """Test caching None values.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + config = CacheConfig() + + InstanceCache.set(instance, "optional", None, config) + + result = InstanceCache.get(instance, "optional", config) + assert result is None + + def test_multiple_relations_on_same_instance(self): + """Test multiple relations with different configs.""" + + class TestModel(BaseModel): + id: int + + instance = TestModel(id=1) + + config_a = CacheConfig(ttl=1) + config_b = CacheConfig(ttl=None) + + InstanceCache.set(instance, "short_ttl", "value_a", config_a) + InstanceCache.set(instance, "no_ttl", "value_b", config_b) + + assert InstanceCache.get(instance, "short_ttl", config_a) == "value_a" + assert InstanceCache.get(instance, "no_ttl", config_b) == "value_b" + + time.sleep(1.1) + + assert InstanceCache.get(instance, "short_ttl", config_a) is None + assert InstanceCache.get(instance, "no_ttl", config_b) == "value_b" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py new file mode 100644 index 00000000..b8a3e1e0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py @@ -0,0 +1,279 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_redis_cache.py +""" +Tests for RedisCache backend. + +Requires a running Redis instance reachable via the REDIS_HOST / REDIS_PORT +environment variables (defaults: localhost:6379, no password). If unavailable, +Redis-dependent tests are skipped — the RedisCache instance is real but the +fixture verifies connectivity at module scope. + +The pytest ``redis`` marker remains defined for callers that prefer to exclude +Redis tests explicitly (``pytest -m 'not redis'``). +""" + +import pytest +import time + +from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache +from rhosocial.activerecord.relation.cache_backends import ( # noqa: E402 + RedisCache, + RedisConfig, + CacheSerializer, + InMemoryCache, +) + +pytestmark = [pytest.mark.redis, pytest.mark.xdist_group("redis_cache")] + + +class _DummyModel: + """Minimal model stub for cache key unit tests.""" + + primary_key_name = "id" + + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + + def primary_key(self): + return self.primary_key_name + + +class _DummyNoPK(_DummyModel): + primary_key_name = "id" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + # deliberately not setting "id" + + +@pytest.fixture(scope="module") +def redis_client(): + redis = pytest.importorskip("redis") + config = RedisConfig.from_env() + try: + client = redis.Redis( + host=config.host, + port=config.port, + password=config.password or None, + db=config.db, + socket_connect_timeout=config.socket_connect_timeout, + ) + client.ping() + yield client + client.flushdb() + except Exception as e: + pytest.skip(f"Redis not available ({e})") + yield None + finally: + try: + client.close() + except Exception: + pass + + +@pytest.fixture +def redis_cache(redis_client): + """Create RedisCache with a clean DB per test.""" + redis_client.flushdb() + return RedisCache(redis_client, prefix="test:cache:") + + +@pytest.fixture +def config(): + return CacheConfig(enabled=True, ttl=300) + + +class TestRedisCacheKey: + """Key generation and format.""" + + def test_key_format(self, redis_cache, config): + """Key follows {prefix}ModelName:pk:relation.""" + instance = _DummyModel(id=42) + key = redis_cache._make_key(instance, "posts") + assert key == "test:cache:_DummyModel:42:posts" + + def test_missing_pk_raises(self, redis_cache): + """Instance without PK raises ValueError.""" + instance = _DummyNoPK() + with pytest.raises(ValueError, match="no primary key"): + redis_cache._make_key(instance, "posts") + + +class TestRedisCacheBasic: + """Basic get/set/delete operations.""" + + def test_set_and_get(self, redis_cache, config, redis_client): + inst = _DummyModel(id=1) + value = ["item1", "item2"] + + redis_cache.set(inst, "items", value, config) + key = redis_cache._make_key(inst, "items") + assert redis_client.exists(key) + + result = redis_cache.get(inst, "items", config) + assert result == value + + def test_get_miss(self, redis_cache, config): + inst = _DummyModel(id=1) + result = redis_cache.get(inst, "items", config) + assert result is None + + def test_delete(self, redis_cache, config, redis_client): + inst = _DummyModel(id=1) + redis_cache.set(inst, "items", "data", config) + key = redis_cache._make_key(inst, "items") + assert redis_client.exists(key) + + redis_cache.delete(inst, "items") + assert not redis_client.exists(key) + assert redis_cache.get(inst, "items", config) is None + + def test_disabled_config_skips(self, redis_cache): + inst = _DummyModel(id=1) + disabled = CacheConfig(enabled=False) + + redis_cache.set(inst, "items", "data", disabled) + assert redis_cache.get(inst, "items", disabled) is None + + redis_cache.delete(inst, "items", disabled) + + def test_ttl_expiry(self, redis_cache, config, redis_client): + inst = _DummyModel(id=1) + ttl_config = CacheConfig(enabled=True, ttl=1) + + redis_cache.set(inst, "items", "expirable", ttl_config) + assert redis_cache.get(inst, "items", ttl_config) == "expirable" + + time.sleep(1.5) + assert redis_cache.get(inst, "items", ttl_config) is None + + def test_no_ttl_persists(self, redis_cache, redis_client): + inst = _DummyModel(id=1) + no_ttl = CacheConfig(enabled=True, ttl=None) + + redis_cache.set(inst, "items", "persistent", no_ttl) + key = redis_cache._make_key(inst, "items") + ttl = redis_client.ttl(key) + assert ttl == -1 # no expiry + + +class UpperSerializer(CacheSerializer): + """A serializer that uppercases string values before pickle.""" + + def __init__(self): + super().__init__(format="pickle") + + def serialize(self, value): + return super().serialize(value.upper()) + + +class TestRedisCacheSerialization: + """Custom serialization support.""" + + def test_custom_serializer(self, redis_cache, config, redis_client): + cache = RedisCache(redis_client, prefix="test:ser:", serializer=UpperSerializer()) + inst = _DummyModel(id=1) + + cache.set(inst, "name", "hello", config) + result = cache.get(inst, "name", config) + assert result == "HELLO" + + +class TestRedisCacheOrigin: + """Origin metadata (observability).""" + + def test_record_origin(self, redis_cache, config, redis_client, caplog): + caplog.set_level("DEBUG", logger="rhosocial.activerecord.relation.cache_backends.redis") + cache = RedisCache(redis_client, prefix="test:origin:", record_origin=True, origin_name="test-host") + inst = _DummyModel(id=1) + + cache.set(inst, "items", "data", config) + result = cache.get(inst, "items", config) + assert result == "data" + + assert any("origin=test-host" in msg for msg in caplog.messages) + + def test_origin_default_off(self, redis_cache, config, redis_client): + """record_origin=False stores raw serialized bytes, not JSON wrapper.""" + import json + + inst = _DummyModel(id=1) + redis_cache.set(inst, "items", "plain", config) + key = redis_cache._make_key(inst, "items") + raw = redis_client.get(key) + assert isinstance(raw, bytes) + assert json.loads(raw) == "plain" + + +class TestRedisInMemorySwitch: + """Switching backends via InstanceCache.set_backend.""" + + def test_switch_to_redis_and_back(self, redis_cache): + inst = _DummyModel(id=1) + config = CacheConfig(enabled=True, ttl=300) + + original = InstanceCache._backend + try: + InstanceCache.set_backend(redis_cache) + InstanceCache.set(inst, "data", "from-redis", config) + assert InstanceCache.get(inst, "data", config) == "from-redis" + + InstanceCache.set_backend(InMemoryCache()) + InstanceCache.set(inst, "data", "from-memory", config) + assert InstanceCache.get(inst, "data", config) == "from-memory" + finally: + InstanceCache.set_backend(original) + + def test_after_switch_redis_persists(self, redis_client): + """Data set via RedisCache remains accessible to a fresh RedisCache instance.""" + inst = _DummyModel(id=1) + config = CacheConfig(enabled=True, ttl=300) + + redis_client.flushdb() + c1 = RedisCache(redis_client, prefix="test:switch:") + c1.set(inst, "items", "persisted", config) + + c2 = RedisCache(redis_client, prefix="test:switch:") + assert c2.get(inst, "items", config) == "persisted" + + +class TestRedisInconsistency: + """Stale/inconsistent data scenario (read-only).""" + + def test_stale_data_returned(self, redis_cache, config, redis_client): + """If data is changed in DB but cache is not invalidated, stale value is returned.""" + inst = _DummyModel(id=1) + redis_cache.set(inst, "count", 10, config) + + # Simulate DB update without cache invalidation + redis_cache.set(inst, "count", 99, config) + + assert redis_cache.get(inst, "count", config) == 99 + + +class TestRedisInstanceInvalidation: + """invalidate_instance clears all cached relations for an instance.""" + + def test_invalidate_instance(self, redis_cache, config, redis_client): + inst = _DummyModel(id=1) + redis_cache.set(inst, "posts", ["p1", "p2"], config) + redis_cache.set(inst, "comments", ["c1"], config) + + assert redis_cache.get(inst, "posts", config) is not None + assert redis_cache.get(inst, "comments", config) is not None + + redis_cache.invalidate_instance(inst) + + assert redis_cache.get(inst, "posts", config) is None + assert redis_cache.get(inst, "comments", config) is None + + def test_invalidate_instance_other_untouched(self, redis_cache, config, redis_client): + inst1 = _DummyModel(id=1) + inst2 = _DummyModel(id=2) + + redis_cache.set(inst1, "data", "a", config) + redis_cache.set(inst2, "data", "b", config) + + redis_cache.invalidate_instance(inst1) + assert redis_cache.get(inst1, "data", config) is None + assert redis_cache.get(inst2, "data", config) == "b" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py new file mode 100644 index 00000000..b482ae53 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py @@ -0,0 +1,238 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_relation_management.py +""" +Tests for RelationManagementMixin methods. + +These tests cover the relation management functionality provided by the +RelationManagementMixin class in python-activerecord. +""" + +import pytest +from typing import ClassVar + +from pydantic import BaseModel + +from rhosocial.activerecord.relation.base import RelationManagementMixin +from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache +from rhosocial.activerecord.relation.descriptors import ( + HasMany, + BelongsTo, + HasOne, + RelationDescriptor, +) + + +class Department(RelationManagementMixin, BaseModel): + id: int + name: str + employees: ClassVar[HasMany["Employee"]] = HasMany(foreign_key="department_id", inverse_of="department") + + +class Employee(RelationManagementMixin, BaseModel): + id: int + name: str + department_id: int + department: ClassVar[BelongsTo["Department"]] = BelongsTo(foreign_key="department_id", inverse_of="employees") + + +class Profile(RelationManagementMixin, BaseModel): + id: int + bio: str + author_id: int + author: ClassVar[BelongsTo["Author"]] = BelongsTo(foreign_key="author_id", inverse_of="profile") + + +class Author(RelationManagementMixin, BaseModel): + id: int + name: str + books: ClassVar[HasMany["Book"]] = HasMany(foreign_key="author_id", inverse_of="author") + profile: ClassVar[HasOne["Profile"]] = HasOne(foreign_key="author_id", inverse_of="author") + + +class Book(RelationManagementMixin, BaseModel): + id: int + title: str + author_id: int + author: ClassVar[BelongsTo["Author"]] = BelongsTo(foreign_key="author_id", inverse_of="books") + + +class TestRelationManagementMixin: + """Tests for RelationManagementMixin functionality.""" + + def test_ensure_relations_creates_dict(self): + """Test that _ensure_relations creates the relations dict if not exists.""" + + class NewModel(RelationManagementMixin, BaseModel): + id: int + + relations = NewModel._ensure_relations() + assert isinstance(relations, dict) + assert "_relations_dict" in NewModel.__dict__ + + def test_ensure_relations_returns_existing(self): + """Test that _ensure_relations returns existing dict.""" + relations1 = Department._ensure_relations() + relations2 = Department._ensure_relations() + assert relations1 is relations2 + + def test_register_relation(self): + """Test registering a new relation.""" + + class TestModel(RelationManagementMixin, BaseModel): + id: int + + class TestRelation(HasMany): + pass + + class TestDescriptor(RelationDescriptor): + pass + + descriptor = RelationDescriptor(foreign_key="test_id") + TestModel.register_relation("test_rel", descriptor) + + assert "test_rel" in TestModel.get_relations() + assert TestModel.get_relation("test_rel") == descriptor + + def test_register_relation_overwrites(self): + """Test that registering a relation with same name overwrites.""" + + class TestModel(RelationManagementMixin, BaseModel): + id: int + + descriptor1 = RelationDescriptor(foreign_key="test_id") + descriptor2 = RelationDescriptor(foreign_key="other_id") + + TestModel.register_relation("test_rel", descriptor1) + TestModel.register_relation("test_rel", descriptor2) + + assert TestModel.get_relation("test_rel") == descriptor2 + + def test_get_relation_returns_none_for_unknown(self): + """Test that get_relation returns None for unknown relation.""" + result = Department.get_relation("unknown_relation") + assert result is None + + def test_get_relations_returns_all(self): + """Test that get_relations returns all registered relations.""" + relations = Department.get_relations() + assert "employees" in relations + + def test_get_relations_excludes_inherited(self): + """Test that get_relations only returns own relations, not inherited.""" + + class Parent(RelationManagementMixin, BaseModel): + id: int + parent_rel: ClassVar[HasMany["Other"]] = HasMany(foreign_key="parent_id", inverse_of="parent") + + class Child(Parent): + pass + + class Other(RelationManagementMixin, BaseModel): + id: int + parent_id: int + parent: ClassVar[BelongsTo["Parent"]] = BelongsTo(foreign_key="parent_id", inverse_of="parent_rel") + + parent_relations = Parent.get_relations() + assert "parent_rel" in parent_relations + + def test_clear_relation_cache_specific(self): + """Test clearing specific relation cache.""" + employee = Employee(id=1, name="Test", department_id=1) + + InstanceCache.set(employee, "department", {"id": 1, "name": "Dept"}, CacheConfig()) + + assert InstanceCache.get(employee, "department", CacheConfig()) is not None + + employee.clear_relation_cache("department") + + assert InstanceCache.get(employee, "department", CacheConfig()) is None + + def test_clear_relation_cache_all(self): + """Test clearing all relation caches.""" + employee = Employee(id=1, name="Test", department_id=1) + + InstanceCache.set(employee, "department", {"id": 1, "name": "Dept"}, CacheConfig()) + + assert InstanceCache.get(employee, "department", CacheConfig()) is not None + + employee.clear_relation_cache() + + assert InstanceCache.get(employee, "department", CacheConfig()) is None + + def test_clear_relation_cache_invalid_name_raises(self): + """Test that clearing invalid relation name raises ValueError.""" + employee = Employee(id=1, name="Test", department_id=1) + + with pytest.raises(ValueError) as exc_info: + employee.clear_relation_cache("invalid_relation") + + assert "Unknown relation" in str(exc_info.value) + + +class TestRelationInheritance: + """Tests for relation inheritance behavior.""" + + def test_child_class_can_override_relation(self): + """Test that child class can override parent relation.""" + + class ParentModel(RelationManagementMixin, BaseModel): + id: int + related: ClassVar[HasOne["OtherModel"]] = HasOne(foreign_key="parent_id", inverse_of="parent") + + class OtherModel(RelationManagementMixin, BaseModel): + id: int + parent_id: int + parent: ClassVar[BelongsTo["ParentModel"]] = BelongsTo(foreign_key="parent_id", inverse_of="related") + + parent_rel = ParentModel.get_relation("related") + assert isinstance(parent_rel, HasOne) + + def test_relations_dict_is_class_specific(self): + """Test that each class has its own relations dict.""" + + class Parent(RelationManagementMixin, BaseModel): + id: int + + class Child(Parent): + pass + + Parent.register_relation("test", RelationDescriptor(foreign_key="test_id")) + + child_relations = Child._ensure_relations() + + assert "test" not in child_relations or "_relations_dict" not in Child.__dict__ + + +class TestRelationValidation: + """Tests for relation validation behavior.""" + + def test_inverse_validation(self): + """Test that inverse relationships are validated.""" + + class AuthorWithValidation(RelationManagementMixin, BaseModel): + id: int + books: ClassVar[HasMany["BookWithValidation"]] = HasMany(foreign_key="author_id", inverse_of="author") + + class BookWithValidation(RelationManagementMixin, BaseModel): + id: int + author_id: int + author: ClassVar[BelongsTo["AuthorWithValidation"]] = BelongsTo(foreign_key="author_id", inverse_of="books") + + author_rel = AuthorWithValidation.get_relation("books") + book_rel = BookWithValidation.get_relation("author") + + assert author_rel is not None + assert book_rel is not None + + def test_missing_inverse_does_not_raise(self): + """Test that missing inverse doesn't raise during registration.""" + + class ModelWithoutInverse(RelationManagementMixin, BaseModel): + id: int + related: ClassVar[HasMany["Target"]] = HasMany(foreign_key="model_id", inverse_of=None) + + class Target(RelationManagementMixin, BaseModel): + id: int + model_id: int + + relation = ModelWithoutInverse.get_relation("related") + assert relation is not None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py new file mode 100644 index 00000000..8931ec61 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py @@ -0,0 +1,350 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_relation_modifier_cache.py +""" +Database-backed relation cache tests using real SQLite with SQL query counting. + +Verifies that the instance-level cache (InstanceCache) correctly prevents +redundant SQL queries on repeated relation access, and that cache invalidation +(for delete, TTL expiry, disabled cache, etc.) re-queries the database. +""" + +import pytest +import time +from typing import ClassVar, Dict, Any, Tuple + +from pydantic import BaseModel + +from rhosocial.activerecord.relation.base import RelationManagementMixin +from rhosocial.activerecord.relation.cache import CacheConfig +from rhosocial.activerecord.relation.descriptors import HasMany, BelongsTo + + +class QueryCounter: + """Wraps backend fetch methods to count executed SQL queries.""" + + def __init__(self, backends: Dict[str, Any]): + self.count = 0 + self._originals: Dict[str, Tuple] = {} + for name, backend in backends.items(): + self._originals[name] = (backend.fetch_all, backend.fetch_one) + backend.fetch_all = self._wrap(backend.fetch_all) + backend.fetch_one = self._wrap(backend.fetch_one) + + def _wrap(self, original): + def wrapper(sql, params=None, column_adapters=None, **kwargs): + self.count += 1 + return original( + sql, + params, + column_adapters=column_adapters, + **kwargs, + ) + + return wrapper + + def reset(self): + self.count = 0 + + +@pytest.fixture +def cache_test_env(user_post_comment_classes): + """Set up test data and wrap backends with a query counter. + + Returns (user_class, post_class, comment_class, user, post, counter). + """ + user_class, post_class, comment_class = user_post_comment_classes + + backends = {} + for cls in (user_class, post_class, comment_class): + try: + backends[cls.__name__] = cls.backend() + except Exception: + pass + counter = QueryCounter(backends) + + user = user_class(name="Cache User", email="cache@example.com") + user.save() + post = post_class(title="Cache Post", body="Content", user_id=user.id) + post.save() + + counter.reset() + yield user_class, post_class, comment_class, user, post, counter + + for name, backend in backends.items(): + orig_all, orig_one = counter._originals.get(name, (None, None)) + if orig_all is not None: + backend.fetch_all = orig_all + if orig_one is not None: + backend.fetch_one = orig_one + + +class TestRelationCacheFirstAccess: + """First relation access should query the database.""" + + def test_first_access_queries_db(self, cache_test_env): + """First access to a relation executes SQL.""" + _, _, _, user, _, counter = cache_test_env + results = user.posts() + assert len(results) == 1 + assert counter.count > 0 + + def test_first_access_has_many_empty(self, cache_test_env): + """HasMany with no related records still executes a query.""" + user_class, _, _, _, _, counter = cache_test_env + user2 = user_class(name="Empty User", email="empty@example.com") + user2.save() + counter.reset() + + results = user2.posts() + assert results == [] + assert counter.count > 0 + + def test_first_access_belongs_to(self, cache_test_env): + """BelongsTo first access executes SQL.""" + _, _, _, _, post, counter = cache_test_env + result = post.user() + assert result is not None + assert counter.count > 0 + + +class TestRelationCacheSecondAccess: + """Second (and subsequent) accesses should hit the cache.""" + + def test_second_access_has_many_uses_cache(self, cache_test_env): + """Second HasMany access uses cache (no SQL).""" + _, _, _, user, _, counter = cache_test_env + r1 = user.posts() + q1 = counter.count + + r2 = user.posts() + assert counter.count == q1 + assert len(r1) == len(r2) + + def test_second_access_belongs_to_uses_cache(self, cache_test_env): + """Second BelongsTo access uses cache (no SQL).""" + _, _, _, _, post, counter = cache_test_env + r1 = post.user() + q1 = counter.count + + r2 = post.user() + assert counter.count == q1 + assert r1.id == r2.id + + def test_multiple_accesses_no_extra_queries(self, cache_test_env): + """Three accesses cause only one SQL query total.""" + _, _, _, user, _, counter = cache_test_env + user.posts() + q1 = counter.count + + for _ in range(5): + user.posts() + + assert counter.count == q1 + + +class TestRelationCacheInvalidation: + """Cache invalidation scenarios (delete, clear, TTL, disabled).""" + + def test_cache_cleared_on_delete(self, cache_test_env): + """__delete__ clears cache; next access re-queries.""" + user_class, _, _, user, _, counter = cache_test_env + user.posts() + counter.reset() + + desc = user_class.get_relation("posts") + desc.__delete__(user) + + results = user.posts() + assert len(results) == 1 + assert counter.count > 0 + + def test_clear_relation_cache_method(self, cache_test_env): + """clear_relation_cache(name) forces a new query.""" + _, _, _, user, _, counter = cache_test_env + user.posts() + counter.reset() + + user.clear_relation_cache("posts") + + results = user.posts() + assert len(results) == 1 + assert counter.count > 0 + + def test_clear_all_relations_cache(self, cache_test_env): + """clear_relation_cache() without args clears all caches.""" + _, _, _, user, _, counter = cache_test_env + user.posts() + counter.reset() + + user.clear_relation_cache() + + results = user.posts() + assert len(results) == 1 + assert counter.count > 0 + + def test_cache_with_disabled_config(self, cache_test_env): + """disabled cache executes a query on every access.""" + user_class, _, _, user, _, counter = cache_test_env + + desc = user_class.get_relation("posts") + orig_config = desc._cache_config + desc._cache_config = CacheConfig(enabled=False) + + try: + user.posts() + counter.reset() + + user.posts() + q1 = counter.count + + user.posts() + assert counter.count > q1 + finally: + desc._cache_config = orig_config + + def test_cache_with_expired_ttl(self, cache_test_env): + """Expired TTL causes a new query.""" + user_class, _, _, user, _, counter = cache_test_env + + desc = user_class.get_relation("posts") + orig_config = desc._cache_config + desc._cache_config = CacheConfig(ttl=1) + + try: + user.posts() + counter.reset() + + time.sleep(1.1) + + results = user.posts() + assert len(results) == 1 + assert counter.count > 0 + finally: + desc._cache_config = orig_config + + +class TestRelationCacheIsolation: + """Cache isolation between instances and relations.""" + + def test_cache_isolation_between_instances(self, cache_test_env): + """Different instances have independent caches.""" + user_class, post_class, _, user, _, counter = cache_test_env + + user2 = user_class(name="Second User", email="u2@example.com") + user2.save() + post2 = post_class(title="Second Post", body="Content", user_id=user2.id) + post2.save() + + user.posts() + user2.posts() + counter.reset() + + r1 = user.posts() + r2 = user2.posts() + assert counter.count == 0 + assert len(r1) == 1 + assert len(r2) == 1 + + def test_different_relations_independent_cache(self, cache_test_env): + """Different relation types on the same instance cache independently.""" + _, _, _, user, post, counter = cache_test_env + + _ = post.user() + counter.reset() + + post.user() + assert counter.count == 0 # BelongsTo cached + + _ = user.posts() + assert counter.count > 0 # HasMany not cached on post instance + + +class TestRelationCacheBulk: + """Bulk / edge-case scenarios.""" + + def test_reload_same_data_idempotent(self, cache_test_env): + """Adding more related data after caching is not visible until cache cleared.""" + user_class, post_class, _, user, _, counter = cache_test_env + + user.posts() + counter.reset() + + extra = post_class(title="Extra Post", body="Extra", user_id=user.id) + extra.save() + + results = user.posts() + assert len(results) == 1 + assert counter.count == 0 # Cache returns stale data + + user.clear_relation_cache("posts") + counter.reset() + + results = user.posts() + assert len(results) == 2 + assert counter.count > 0 + + +# ── Non-DB protocol tests (kept from original mock-based file) ───── + + +class TestRelationDescriptorProtocol: + """Tests for relation descriptor protocol methods.""" + + def test_get_descriptor_from_class(self): + """Test accessing descriptor from class returns descriptor itself.""" + + class _Author(RelationManagementMixin, BaseModel): + id: int + books: ClassVar[HasMany["_Book"]] = HasMany(foreign_key="author_id") + + class _Book(RelationManagementMixin, BaseModel): + id: int + author_id: int + author: ClassVar[BelongsTo["_Author"]] = BelongsTo(foreign_key="author_id") + + relation = _Author.get_relation("books") + assert isinstance(relation, HasMany) + assert relation.foreign_key == "author_id" + + def test_get_descriptor_from_instance_returns_method(self): + """Test accessing descriptor from instance returns bound method.""" + + class _Author(RelationManagementMixin, BaseModel): + id: int + books: ClassVar[HasMany["_Book"]] = HasMany(foreign_key="author_id") + + class _Book(RelationManagementMixin, BaseModel): + id: int + author_id: int + + author = _Author(id=1) + books_relation = author.books + assert callable(books_relation) + + def test_set_name_callback(self): + """Test that __set_name__ is called on descriptor assignment.""" + + class _OtherItem(RelationManagementMixin, BaseModel): + id: int + test_id: int + + class _TestModel(RelationManagementMixin, BaseModel): + id: int + items: ClassVar[HasMany["_OtherItem"]] = HasMany(foreign_key="test_id", inverse_of="test") + + relation = _TestModel.get_relation("items") + assert relation.name == "items" + assert relation._owner == _TestModel + + def test_query_method_created(self): + """Test that query method is created for relation.""" + + class _Author(RelationManagementMixin, BaseModel): + id: int + books: ClassVar[HasMany["_Book"]] = HasMany(foreign_key="author_id") + + class _Book(RelationManagementMixin, BaseModel): + id: int + author_id: int + + assert hasattr(_Author, "books_query") + assert callable(_Author.books_query) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py new file mode 100644 index 00000000..316d50d0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py @@ -0,0 +1,402 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_relational_validation.py +""" +Tests for relational query validation and error handling. + +These tests cover: +1. Invalid relation path format validation +2. Relation not found error handling +3. Edge cases and boundary conditions +""" + +import pytest +from unittest.mock import MagicMock + +from rhosocial.activerecord.interface import IQuery +from rhosocial.activerecord.query.relational import ( + RelationalQueryMixin, + InvalidRelationPathError, + RelationNotFoundError, +) + + +class MockQueryBase(IQuery): + """Mock base class for testing.""" + + def __init__(self): + self.model_class = MagicMock() + self.model_class.__name__ = "MockModel" + self.condition_groups = [[]] + self.current_group = 0 + self.order_clauses = [] + self.join_clauses = [] + self.limit_count = None + self.offset_count = None + from rhosocial.activerecord.backend.expression import AllColumnsWildcard + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + self.select_columns = [AllColumnsWildcard(SQLiteDialect())] + self._explain_enabled = False + self._explain_options = None + + def all(self): + return [] + + def one(self): + return None + + def one_or_fail(self): + return None + + def where(self, condition, params=None): + return self + + def or_where(self, condition, params=None): + return self + + def order_by(self, *clauses): + return self + + def join(self, join_clause): + return self + + def limit(self, count): + return self + + def offset(self, count): + return self + + def select(self, *columns, append=False): + return self + + def count(self): + return 0 + + def exists(self): + return False + + def build(self): + return "", () + + def to_sql(self): + return "", () + + def explain(self, *args, **kwargs): + return self + + def between(self, column, start, end): + return self + + def not_between(self, column, start, end): + return self + + def start_or_group(self): + return self + + def end_or_group(self): + return self + + def in_list(self, column, values, empty_result=True): + return self + + def is_not_null(self, column): + return self + + def is_null(self, column): + return self + + def like(self, column, pattern): + return self + + def not_like(self, column, pattern): + return self + + def not_in(self, column, values, empty_result=False): + return self + + def query(self, conditions=None): + return self + + def to_dict(self, include=None, exclude=None): + return self + + +class MockQuery(RelationalQueryMixin, MockQueryBase): + """Mock query class for testing.""" + + def __init__(self): + super().__init__() + self._log = MagicMock() + + +class TestInvalidRelationPath: + """Tests for invalid relation path validation.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_empty_relation_path(self, query): + """Test that empty relation path raises InvalidRelationPathError.""" + with pytest.raises(InvalidRelationPathError) as exc_info: + query.with_("") + assert "cannot be empty" in str(exc_info.value) + + def test_leading_dot(self, query): + """Test that path with leading dot raises InvalidRelationPathError.""" + with pytest.raises(InvalidRelationPathError) as exc_info: + query.with_(".posts") + assert "cannot start with a dot" in str(exc_info.value) + + def test_trailing_dot(self, query): + """Test that path with trailing dot raises InvalidRelationPathError.""" + with pytest.raises(InvalidRelationPathError) as exc_info: + query.with_("posts.") + assert "cannot end with a dot" in str(exc_info.value) + + def test_consecutive_dots(self, query): + """Test that path with consecutive dots raises InvalidRelationPathError.""" + with pytest.raises(InvalidRelationPathError) as exc_info: + query.with_("posts..comments") + assert "cannot contain consecutive dots" in str(exc_info.value) + + def test_multiple_invalid_paths(self, query): + """Test that multiple invalid paths are validated in order.""" + # The first invalid path should raise + with pytest.raises(InvalidRelationPathError): + query.with_("posts", "") + + def test_analyze_relation_path_valid(self, query): + """Test analyze_relation_path with valid path.""" + parts, configs = query.analyze_relation_path("posts.comments") + assert parts == ["posts", "comments"] + assert configs == ["posts", "posts.comments"] + + def test_analyze_relation_path_single(self, query): + """Test analyze_relation_path with single relation.""" + parts, configs = query.analyze_relation_path("posts") + assert parts == ["posts"] + assert configs == ["posts"] + + def test_analyze_relation_path_invalid(self, query): + """Test analyze_relation_path with invalid path raises error.""" + with pytest.raises(InvalidRelationPathError): + query.analyze_relation_path("") + + +class TestRelationNotFound: + """Tests for relation not found error handling.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_relation_not_found_on_model(self, query): + """Test that RelationNotFoundError is raised when relation doesn't exist.""" + # Setup mock to return None for get_relation + query.model_class.get_relation = MagicMock(return_value=None) + query.model_class.hasattr = lambda x: True + query.model_class.__name__ = "User" + + with pytest.raises(RelationNotFoundError) as exc_info: + query.with_("nonexistent_relation") + assert "not found" in str(exc_info.value) + + def test_nested_relation_not_found(self, query): + """Test that RelationNotFoundError is raised for nested relation.""" + # Setup mock: posts exists, comments doesn't exist on Post model + mock_post_model = MagicMock() + mock_post_model.__name__ = "Post" + mock_post_model.get_relation = MagicMock(return_value=None) + mock_post_model.hasattr = lambda x: True + + mock_posts_rel = MagicMock() + mock_posts_rel.get_related_model = MagicMock(return_value=mock_post_model) + + def get_relation_side_effect(name): + if name == "posts": + return mock_posts_rel + return None + + query.model_class.get_relation = MagicMock(side_effect=get_relation_side_effect) + query.model_class.hasattr = lambda x: True + + with pytest.raises(RelationNotFoundError) as exc_info: + query.with_("posts.comments") + assert "comments" in str(exc_info.value) + + def test_model_class_not_has_get_relation(self, query): + """Test error when model doesn't have get_relation method.""" + query.model_class = MagicMock() + # Remove get_relation from mock + if hasattr(query.model_class, "get_relation"): + del query.model_class.get_relation + + with pytest.raises((RelationNotFoundError, AttributeError)): + query.with_("posts") + + def test_partial_path_valid_full_invalid(self, query): + """Test that valid partial path with invalid full path raises error.""" + # Setup: first part exists, second doesn't + mock_post_model = MagicMock() + mock_post_model.__name__ = "Post" + mock_post_model.get_relation = MagicMock(return_value=None) + mock_post_model.hasattr = lambda x: True + + mock_posts_rel = MagicMock() + mock_posts_rel.get_related_model = MagicMock(return_value=mock_post_model) + + def get_relation_side_effect(name): + if name == "posts": + return mock_posts_rel + if name == "nonexistent": + return None + return None + + query.model_class.get_relation = MagicMock(side_effect=get_relation_side_effect) + query.model_class.hasattr = lambda x: True + + with pytest.raises(RelationNotFoundError): + query.with_("posts.nonexistent") + + +class TestWithEdgeCases: + """Tests for edge cases in with_() method.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_with_no_relations(self, query): + """Test that with_() works with no arguments.""" + result = query.with_() + assert result is query + + def test_with_single_string_relation(self, query): + """Test with_() with single string relation.""" + # Setup mock to allow validation to pass + mock_rel = MagicMock() + mock_rel.get_related_model = MagicMock( + return_value=MagicMock( + __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True + ) + ) + + query.model_class.get_relation = MagicMock(return_value=mock_rel) + query.model_class.hasattr = lambda x: True + + query.with_("posts") + configs = query.get_relation_configs() + assert "posts" in configs + + def test_with_single_tuple_relation(self, query): + """Test with_() with single tuple (path, modifier).""" + mock_rel = MagicMock() + mock_rel.get_related_model = MagicMock( + return_value=MagicMock( + __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True + ) + ) + + query.model_class.get_relation = MagicMock(return_value=mock_rel) + query.model_class.hasattr = lambda x: True + + def modifier(q): + return q + + query.with_(("posts", modifier)) + configs = query.get_relation_configs() + assert "posts" in configs + assert configs["posts"].query_modifier == modifier + + def test_with_none_modifier(self, query): + """Test with_() with explicit None modifier.""" + mock_rel = MagicMock() + mock_rel.get_related_model = MagicMock( + return_value=MagicMock( + __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True + ) + ) + + query.model_class.get_relation = MagicMock(return_value=mock_rel) + query.model_class.hasattr = lambda x: True + + query.with_(("posts", None)) + configs = query.get_relation_configs() + assert "posts" in configs + assert configs["posts"].query_modifier is None + + def test_multiple_relations_with_validation(self, query): + """Test with_() with multiple relations that pass validation.""" + mock_rel = MagicMock() + mock_rel.get_related_model = MagicMock( + return_value=MagicMock( + __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True + ) + ) + + query.model_class.get_relation = MagicMock(return_value=mock_rel) + query.model_class.hasattr = lambda x: True + + query.with_("posts", "comments", "profile") + configs = query.get_relation_configs() + assert "posts" in configs + assert "comments" in configs + assert "profile" in configs + + +class TestRelationConfig: + """Tests for RelationConfig behavior.""" + + def test_relation_config_defaults(self): + """Test RelationConfig with default values.""" + from rhosocial.activerecord.query.relational import RelationConfig + + config = RelationConfig(name="posts", nested=[]) + assert config.name == "posts" + assert config.nested == [] + assert config.query_modifier is None + + def test_relation_config_with_modifier(self): + """Test RelationConfig with query modifier.""" + from rhosocial.activerecord.query.relational import RelationConfig + + def modifier(q): + return q + + config = RelationConfig(name="posts", nested=["comments"], query_modifier=modifier) + assert config.name == "posts" + assert config.nested == ["comments"] + assert config.query_modifier == modifier + + +class TestGetRelationConfigs: + """Tests for get_relation_configs method.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_get_relation_configs_empty(self, query): + """Test get_relation_configs returns empty dict initially.""" + configs = query.get_relation_configs() + assert configs == {} + + def test_get_relation_configs_returns_copy(self, query): + """Test that get_relation_configs returns a copy, not original.""" + mock_rel = MagicMock() + mock_rel.get_related_model = MagicMock( + return_value=MagicMock( + __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True + ) + ) + + query.model_class.get_relation = MagicMock(return_value=mock_rel) + query.model_class.hasattr = lambda x: True + + query.with_("posts") + configs = query.get_relation_configs() + configs["new_key"] = "new_value" + + # Original should not be modified + original_configs = query.get_relation_configs() + assert "new_key" not in original_configs diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py new file mode 100644 index 00000000..852e92a8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py @@ -0,0 +1,269 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_type_resolver.py +"""Tests for the centralized type_resolver module.""" + +from typing import ClassVar, ForwardRef, Optional + +import pytest +from pydantic import BaseModel + +from rhosocial.activerecord.relation.base import RelationManagementMixin +from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany +from rhosocial.activerecord.relation.async_descriptors import AsyncBelongsTo +from rhosocial.activerecord.relation.type_resolver import ( + resolve_model_fqn, + evaluate_annotation, + resolve_relation_type, + _build_owner_namespace, + _unwrap_generic_type, +) + + +class TestResolveModelFqn: + def test_module_level_class(self): + fqn = resolve_model_fqn(BaseModel) + assert fqn == "pydantic.main.BaseModel" + + def test_nested_class_qname(self): + class Outer: + class Inner: + pass + + fqn = resolve_model_fqn(Outer.Inner) + assert "Outer.Inner" in fqn + + +class TestEvaluateAnnotation: + def test_evaluate_string_ref(self): + class MyModel(RelationManagementMixin, BaseModel): + id: int + + result = evaluate_annotation("MyModel", MyModel) + assert result is MyModel + + def test_evaluate_with_extra_ns(self): + class Owner(RelationManagementMixin, BaseModel): + id: int + + class Dynamic: + pass + + result = evaluate_annotation("Dynamic", Owner, extra_ns={"Dynamic": Dynamic}) + assert result is Dynamic + + def test_evaluate_unresolvable_name(self): + class Owner(RelationManagementMixin, BaseModel): + id: int + + with pytest.raises(NameError, match="name 'NoSuchModel' is not defined"): + evaluate_annotation("NoSuchModel", Owner) + + def test_evaluate_forward_ref_direct(self): + class MyModel(RelationManagementMixin, BaseModel): + id: int + + ref = ForwardRef("MyModel") + result = evaluate_annotation(ref, MyModel) + assert result is MyModel + + def test_evaluate_via_frame_fallback(self): + class MyModel(RelationManagementMixin, BaseModel): + id: int + + class Owner(RelationManagementMixin, BaseModel): + id: int + rel: ClassVar[BelongsTo["MyModel"]] = BelongsTo(foreign_key="my_id") + + result = evaluate_annotation("MyModel", Owner) + assert result is MyModel + + +class TestBuildOwnerNamespace: + def test_includes_owner_types(self): + class Inner: + pass + + class Outer(RelationManagementMixin, BaseModel): + id: int + + Outer.Inner = Inner + ns = _build_owner_namespace(Outer) + assert "Outer" in ns + assert "Inner" in ns + assert ns["Inner"] is Inner + + +class TestUnwrapGenericType: + def test_simple_generic(self): + result = _unwrap_generic_type(HasMany[str], __import__("typing")) + assert result is str + + def test_classvar_wrapped(self): + from typing import ClassVar as CV + + cv = CV[BelongsTo[str]] + result = _unwrap_generic_type(cv, __import__("typing")) + assert result is str + + +class TestResolveRelationType: + def test_resolve_missing_field(self): + class Owner(RelationManagementMixin, BaseModel): + id: int + + assert resolve_relation_type(Owner, "no_such_field") is None + + def test_resolve_type_direct(self): + class Owner(RelationManagementMixin, BaseModel): + id: int + ref: int = 0 + + assert resolve_relation_type(Owner, "id") is int + + def test_resolve_string_annotation(self): + Owner = type("Owner", (dict,), {"__annotations__": {"ref": "int"}}) + result = resolve_relation_type(Owner, "ref") + assert result is int + + +class TestDescriptorCompat: + """Sync/async descriptor mixing is rejected at class creation time. + These tests are covered comprehensively in test_descriptor_compat.py. + This file focuses on the type_resolver utilities. + """ + + +class TestRelatedModelTypeValidation: + """Ensure relation target models are validated at resolution time.""" + + def test_sync_descriptor_target_must_be_sync_model(self): + from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord + + class AsyncTarget(AsyncActiveRecord): + @classmethod + def table_name(cls): + return "async_target_check" + + id: Optional[int] = None + + class Owner(ActiveRecord): + @classmethod + def table_name(cls): + return "owner_check" + + id: Optional[int] = None + ref_id: int + bad: ClassVar[BelongsTo["AsyncTarget"]] = BelongsTo(foreign_key="ref_id", inverse_of=None) + + # cross sync/async is caught at load time, not resolution time + desc = Owner.get_relation("bad") + model = desc.get_related_model(Owner) + assert model is AsyncTarget + with pytest.raises(TypeError, match="must be a subclass of IActiveRecord"): + desc._ensure_model_capability() + + def test_async_descriptor_target_must_be_async_model(self): + from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord + + class SyncTarget(ActiveRecord): + @classmethod + def table_name(cls): + return "sync_target_check" + + id: Optional[int] = None + + class Owner(AsyncActiveRecord): + @classmethod + def table_name(cls): + return "owner_check2" + + id: Optional[int] = None + ref_id: int + bad: ClassVar[AsyncBelongsTo["SyncTarget"]] = AsyncBelongsTo(foreign_key="ref_id", inverse_of=None) + + desc = Owner.get_relation("bad") + model = desc.get_related_model(Owner) + assert model is SyncTarget + with pytest.raises(TypeError, match="must be a subclass of IAsyncActiveRecord"): + desc._ensure_model_capability() + + def test_sync_descriptor_target_not_activerecord_raises(self): + class PlainClass: + pass + + class Owner(RelationManagementMixin, BaseModel): + id: int + ref_id: int + rel: ClassVar[BelongsTo["PlainClass"]] = BelongsTo(foreign_key="ref_id", inverse_of=None) + + desc = Owner.get_relation("rel") + with pytest.raises(TypeError, match="must support relation management"): + desc.get_related_model(Owner) + + def test_async_descriptor_target_not_activerecord_raises(self): + class PlainClass: + pass + + from rhosocial.activerecord.model import AsyncActiveRecord + + class Owner(AsyncActiveRecord): + @classmethod + def table_name(cls): + return "owner_check3" + + id: Optional[int] = None + ref_id: int + rel: ClassVar[AsyncBelongsTo["PlainClass"]] = AsyncBelongsTo(foreign_key="ref_id", inverse_of=None) + + desc = Owner.get_relation("rel") + with pytest.raises(TypeError, match="must support relation management"): + desc.get_related_model(Owner) + + def test_sync_descriptor_target_is_sync_model_passes(self): + from rhosocial.activerecord.model import ActiveRecord + + class SyncTarget(ActiveRecord): + @classmethod + def table_name(cls): + return "sync_target3" + + id: Optional[int] = None + + class Owner(ActiveRecord): + @classmethod + def table_name(cls): + return "owner_check4" + + id: Optional[int] = None + ref_id: int + good: ClassVar[BelongsTo["SyncTarget"]] = BelongsTo(foreign_key="ref_id", inverse_of=None) + + desc = Owner.get_relation("good") + result = desc.get_related_model(Owner) + assert result is SyncTarget + # load-level check also passes + desc._ensure_model_capability() + + def test_async_descriptor_target_is_async_model_passes(self): + from rhosocial.activerecord.model import AsyncActiveRecord + + class AsyncTarget(AsyncActiveRecord): + @classmethod + def table_name(cls): + return "async_target3" + + id: Optional[int] = None + + class Owner(AsyncActiveRecord): + @classmethod + def table_name(cls): + return "owner_check5" + + id: Optional[int] = None + ref_id: int + good: ClassVar[AsyncBelongsTo["AsyncTarget"]] = AsyncBelongsTo(foreign_key="ref_id", inverse_of=None) + + desc = Owner.get_relation("good") + result = desc.get_related_model(Owner) + assert result is AsyncTarget + # load-level check also passes + desc._ensure_model_capability() \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py new file mode 100644 index 00000000..5fa99a3d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py @@ -0,0 +1,472 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_with_modifier.py +""" +Tests for with_() method modifier behavior. + +These tests specifically cover: +1. Parameter expansion rule - modifier only applies to target relation +2. Later parameters overwrite earlier ones +3. Warning is issued when modifier is overwritten +""" + +import logging +from typing import List, Optional, Any, Union, Tuple, Dict, Set +from unittest.mock import MagicMock + +import pytest + +from rhosocial.activerecord.interface import IQuery +from rhosocial.activerecord.query.relational import RelationalQueryMixin + + +class MockQueryBase(IQuery): + """Mock base class that implements IQuery interface.""" + + def __init__(self): + self.model_class = MagicMock() + self.condition_groups = [[]] + self.current_group = 0 + self.order_clauses = [] + self.join_clauses = [] + self.limit_count = None + self.offset_count = None + from rhosocial.activerecord.backend.expression import AllColumnsWildcard + from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect + + self.select_columns = [AllColumnsWildcard(SQLiteDialect())] + self._explain_enabled = False + self._explain_options = None + + def all(self) -> List[Any]: + return [] + + def one(self) -> Optional[Any]: + return None + + def one_or_fail(self) -> Any: + return None + + def where(self, condition: str, params: Optional[Union[tuple, List[Any]]] = None) -> "IQuery": + return self + + def or_where(self, condition: str, params: Optional[Union[tuple, List[Any]]] = None) -> "IQuery": + return self + + def order_by(self, *clauses: str) -> "IQuery": + return self + + def join(self, join_clause: str) -> "IQuery": + return self + + def limit(self, count: int) -> "IQuery": + return self + + def offset(self, count: int) -> "IQuery": + return self + + def select(self, *columns: str, append: bool = False) -> "IQuery": + return self + + def count(self) -> int: + return 0 + + def exists(self) -> bool: + return False + + def build(self) -> Tuple[str, tuple]: + return "", () + + def to_sql(self) -> Tuple[str, tuple]: + return "", () + + def explain(self, *args, **kwargs) -> "IQuery": + return self + + def between(self, column: str, start: Any, end: Any) -> "IQuery[ModelT]": # noqa: F821 + return self + + def not_between(self, column: str, start: Any, end: Any) -> "IQuery[ModelT]": # noqa: F821 + return self + + def start_or_group(self) -> "IQuery[ModelT]": # noqa: F821 + return self + + def end_or_group(self) -> "IQuery[ModelT]": # noqa: F821 + return self + + def in_list( + self, column: str, values: Union[List[Any], Tuple[Any, ...]], empty_result: bool = True + ) -> "IQuery[ModelT]": # noqa: F821 + return self + + def is_not_null(self, column: str) -> "IQuery[ModelT]": # noqa: F821 + return self + + def is_null(self, column: str) -> "IQuery[ModelT]": # noqa: F821 + return self + + def like(self, column: str, pattern: str) -> "IQuery[ModelT]": # noqa: F821 + return self + + def not_like(self, column: str, pattern: str) -> "IQuery[ModelT]": # noqa: F821 + return self + + def not_in( + self, column: str, values: Union[List[Any], Tuple[Any, ...]], empty_result: bool = False + ) -> "IQuery[ModelT]": # noqa: F821 + return self + + def query(self, conditions: Optional[Dict[str, Any]] = None) -> "IQuery[ModelT]": # noqa: F821 + return self + + def to_dict(self, include: Optional[Set[str]] = None, exclude: Optional[Set[str]] = None) -> "IDictQuery[ModelT]": # noqa: F821 + return self + + +class MockQuery(RelationalQueryMixin, MockQueryBase): + """Mock query class for testing.""" + + def __init__(self): + super().__init__() + self._log = MagicMock() + + +class TestModifierExpansionRule: + """Tests for parameter expansion rule - modifier only applies to target relation.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_modifier_only_on_target_not_intermediate(self, query): + """Test that modifier is only applied to target relation, not intermediate ones. + + When processing ('posts.comments', modifier), the expansion should be: + - 'posts' -> None (intermediate, no modifier) + - 'posts.comments' -> modifier (target, has modifier) + """ + + def my_modifier(q): + return q.where("status = 'published'") + + query.with_(("posts.comments", my_modifier)) + + configs = query.get_relation_configs() + + assert "posts" in configs + assert "posts.comments" in configs + + assert configs["posts"].query_modifier is None + assert configs["posts.comments"].query_modifier == my_modifier + + def test_deep_nested_modifier_only_on_leaf(self, query): + """Test deeply nested path - modifier only on the leaf.""" + + def deep_modifier(q): + return q.where("id > 0") + + query.with_(("user.posts.comments.author", deep_modifier)) + + configs = query.get_relation_configs() + + assert configs["user"].query_modifier is None + assert configs["user.posts"].query_modifier is None + assert configs["user.posts.comments"].query_modifier is None + assert configs["user.posts.comments.author"].query_modifier == deep_modifier + + def test_multiple_relations_each_with_own_modifier(self, query): + """Test multiple relations each with their own modifier.""" + + def modifier_a(q): + q.name = "a" + return q + + def modifier_b(q): + q.name = "b" + return q + + query.with_( + ("posts", modifier_a), + ("comments", modifier_b), + ) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier == modifier_a + assert configs["comments"].query_modifier == modifier_b + + def test_simple_path_with_modifier(self, query): + """Test simple path - modifier applies to the only relation.""" + + def filter_modifier(q): + return q.where("active = true") + + query.with_(("posts", filter_modifier)) + + configs = query.get_relation_configs() + + assert "posts" in configs + assert configs["posts"].query_modifier == filter_modifier + + +class TestLaterParameterOverwritesEarlier: + """Tests for later parameters overwriting earlier ones.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_later_modifier_overwrites_same_path(self, query): + """Test that later modifier overwrites earlier one for the same path.""" + + def modifier_v1(q): + q.version = 1 + return q + + def modifier_v2(q): + q.version = 2 + return q + + query.with_( + ("posts", modifier_v1), + ("posts", modifier_v2), + ) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier == modifier_v2 + + def test_longer_path_overwrites_shorter_path(self, query): + """Test that ('posts.comments', m1) + ('posts.comments.user', m2) overwrites correctly. + + After expansion: + - First param: 'posts' -> None, 'posts.comments' -> m1 + - Second param: 'posts' -> None, 'posts.comments' -> m2, 'posts.comments.user' -> m2 + + Final result: + - 'posts' -> None + - 'posts.comments' -> m2 (overwritten!) + - 'posts.comments.user' -> m2 + """ + + def modifier_1(q): + q.filter = "draft" + return q + + def modifier_2(q): + q.filter = "published" + return q + + query.with_( + ("posts.comments", modifier_1), + ("posts.comments.user", modifier_2), + ) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier is None + assert configs["posts.comments"].query_modifier == modifier_2 + assert configs["posts.comments.user"].query_modifier == modifier_2 + + def test_correct_order_preserves_modifiers(self, query): + """Test that correct order preserves both modifiers. + + To keep 'posts.comments' modifier, put it AFTER 'posts.comments.user': + - First: ('posts.comments.user', m2) + - Second: ('posts.comments', m1) + + Result: + - 'posts' -> None + - 'posts.comments' -> m1 (not overwritten because shorter path comes later) + - 'posts.comments.user' -> m2 + """ + + def modifier_1(q): + q.filter = "draft" + return q + + def modifier_2(q): + q.filter = "published" + return q + + query.with_( + ("posts.comments.user", modifier_2), + ("posts.comments", modifier_1), + ) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier is None + assert configs["posts.comments"].query_modifier == modifier_1 + assert configs["posts.comments.user"].query_modifier == modifier_2 + + +class TestModifierOverwriteWarning: + """Tests for warning when modifier is overwritten.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_warning_when_modifier_overwritten(self, query): + """Test that warning is issued when modifier is overwritten.""" + + def modifier_v1(q): + return q.where("status = 'draft'") + + def modifier_v2(q): + return q.where("status = 'published'") + + query.with_( + ("posts", modifier_v1), + ("posts", modifier_v2), + ) + + # Check that _log was called with warning about overwritten modifier + log_calls = [str(call) for call in query._log.call_args_list] + assert any("modifier is being overwritten" in call for call in log_calls) + + def test_warning_shows_function_names(self, query): + """Test that warning shows function names for named functions.""" + + def filter_draft(q): + return q.where("status = 'draft'") + + def filter_published(q): + return q.where("status = 'published'") + + query.with_( + ("posts", filter_draft), + ("posts", filter_published), + ) + + log_calls = [str(call) for call in query._log.call_args_list] + log_messages = " ".join(log_calls) + assert "filter_draft" in log_messages + assert "filter_published" in log_messages + + def test_no_warning_when_same_modifier(self, query): + """Test that no warning is issued when same modifier is used.""" + + def same_modifier(q): + return q.where("status = 'published'") + + query.with_( + ("posts", same_modifier), + ("posts", same_modifier), + ) + + log_calls = [str(call) for call in query._log.call_args_list] + assert not any("modifier is being overwritten" in call for call in log_calls) + + def test_no_warning_when_overwriting_with_none(self, query): + """Test that no warning when overwriting with None (explicit clear).""" + + def some_modifier(q): + return q.where("status = 'published'") + + query.with_( + ("posts", some_modifier), + ("posts", None), + ) + + log_calls = [str(call) for call in query._log.call_args_list] + assert not any("modifier is being overwritten" in call for call in log_calls) + + def test_warning_for_nested_path_overwrite(self, query): + """Test warning when nested path overwrites parent path modifier.""" + + def parent_modifier(q): + return q.where("parent = true") + + def child_modifier(q): + return q.where("child = true") + + query.with_( + ("posts.comments", parent_modifier), + ("posts.comments.user", child_modifier), + ) + + log_calls = [str(call) for call in query._log.call_args_list] + assert any("modifier is being overwritten" in call for call in log_calls) + + def test_no_warning_for_different_paths(self, query, caplog): + """Test that no warning for different relation paths.""" + with caplog.at_level(logging.WARNING): + + def modifier_a(q): + return q.where("a = 1") + + def modifier_b(q): + return q.where("b = 2") + + query.with_( + ("posts", modifier_a), + ("comments", modifier_b), + ) + + assert not any("modifier is being overwritten" in record.message for record in caplog.records) + + +class TestDocumentationExamples: + """Test cases that match the documentation examples.""" + + @pytest.fixture + def query(self): + return MockQuery() + + def test_documentation_example_expansion(self, query): + """Test the documentation example: ('posts.comments', modifier1) expands correctly.""" + + def modifier1(q): + return q.where("published = true") + + query.with_(("posts.comments", modifier1)) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier is None + assert configs["posts.comments"].query_modifier == modifier1 + + def test_documentation_example_overwrite(self, query): + """Test the documentation example: m2 overwrites m1 for posts.comments.""" + + def m1(q): + q.filter = "draft" + return q + + def m2(q): + q.filter = "published" + return q + + query.with_( + ("posts.comments", m1), + ("posts.comments.user", m2), + ) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier is None + assert configs["posts.comments"].query_modifier == m2 + assert configs["posts.comments.user"].query_modifier == m2 + + def test_documentation_correct_order(self, query): + """Test the documentation correct order example.""" + + def m1(q): + q.filter = "draft" + return q + + def m2(q): + q.filter = "published" + return q + + query.with_( + ("posts.comments.user", m2), + ("posts.comments", m1), + ) + + configs = query.get_relation_configs() + + assert configs["posts"].query_modifier is None + assert configs["posts.comments"].query_modifier == m1 + assert configs["posts.comments.user"].query_modifier == m2 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py new file mode 100644 index 00000000..93aefbc3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py @@ -0,0 +1,281 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py +"""L2 environment for the merged ``query/relations`` bridge tests. + +This is the sqlite bridge's local environment for ``test_with_integration.py`` +(the real-database ``with_()`` integration tests carried over from the old +``query/relations`` directory). It is deliberately self-contained: the DDL +definitions are inlined so this directory does not import any model module from +the (concurrently restructured) query topic. + +Each table definition receives only a dialect and produces ``to_sql()`` DDL; +the ``schema`` fixture drops and recreates all tables before every test so +sequence/identity state is reset. +""" + +from pathlib import Path + +import pytest + +from rhosocial.activerecord.backend.expression import ColumnConstraint as Constraint +from rhosocial.activerecord.backend.expression import ColumnDefinition as Column +from rhosocial.activerecord.backend.expression import CreateTableStatement as CreateTable +from rhosocial.activerecord.backend.expression import DropTableStatement as DropTable +from rhosocial.activerecord.backend.expression import TableConstraint +from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.statements import ( + ColumnDefaultConstraint as Default, +) +from rhosocial.activerecord.backend.expression.statements import ( + ColumnNotNullConstraint as NotNull, +) +from rhosocial.activerecord.backend.expression.statements import ( + ColumnPrimaryKeyConstraint as PrimaryKey, +) +from rhosocial.activerecord.backend.expression.statements import TableUniqueConstraint as TableUnique +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts +from rhosocial.activerecord.backend.expression.types import BooleanType as Bool +from rhosocial.activerecord.backend.expression.types import DecimalType as Numeric +from rhosocial.activerecord.backend.expression.types import FloatType as Float +from rhosocial.activerecord.backend.expression.types import IntegerType as Int +from rhosocial.activerecord.backend.expression.types import TextType, TimestampType +from rhosocial.activerecord.backend.expression.types import VarCharType as VarChar +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose="Directory-owned database for query/relation/legacy bridge tests.", + passes_means="the directory's tests run on one worker per scenario", + fails_means="two workers share the same database file", +) + +DDL = ExecutionOptions(stmt_type=StatementType.DDL) + +PLACEHOLDER_TEXT = "-" + + +def _require_data_type(dialect, concept): + probe = getattr(dialect, "supports_data_types", None) + if not callable(probe): + return + supported = probe() or {} + if concept not in supported: + import pytest as _pytest + + _pytest.skip(f"dialect does not support data type {concept!r}") + + +def _short_text(dialect): + _require_data_type(dialect, "varchar") + return VarChar(dialect, 255) + + +def _long_text(dialect): + return TextType(dialect) + + +def _timestamp(dialect): + probe = getattr(dialect, "supports_microsecond_timestamp", None) + keeps = bool(probe()) if callable(probe) else bool(probe) + return TimestampType(dialect, precision=6 if keeps else None) + + +def _supports_drop_if_exists(dialect): + probe = getattr(dialect, "supports_if_exists_table", None) + return True if probe is None else bool(probe()) + + +class Definition: + """Minimal DDL-only table definition (no model imports).""" + + table_name = "" + + def __init__(self, dialect, table_name=None): + self.dialect = dialect + self.name = table_name or type(self).table_name + self.create_table = CreateTable( + dialect, + table=Table(dialect, self.name), + columns=self.columns(), + table_constraints=self.table_constraints(), + ) + self.drop_table = DropTable( + dialect, + table=Table(dialect, self.name), + if_exists=_supports_drop_if_exists(dialect), + ) + + def columns(self): + raise NotImplementedError + + def table_constraints(self): + return [] + + def column(self, name, sql_type, constraints=None): + return Column(self.dialect, name, sql_type, constraints=constraints or []) + + def auto_pk(self, name="id"): + data_type, attributes = auto_increment_parts(self.dialect, Int(self.dialect)) + return Column( + self.dialect, + name, + data_type, + constraints=[Constraint(self.dialect, branch=PrimaryKey(self.dialect))], + attributes=attributes, + ) + + def text(self, name): + return self.column(name, _short_text(self.dialect)) + + def longtext(self, name): + return self.column(name, _long_text(self.dialect)) + + def timestamp(self, name): + return self.column(name, _timestamp(self.dialect)) + + def required_text(self, name): + return self.column( + name, + VarChar(self.dialect, 255), + [ + Constraint(self.dialect, branch=Default(self.dialect, PLACEHOLDER_TEXT)), + Constraint(self.dialect, branch=NotNull(self.dialect)), + ], + ) + + +class UsersDefinition(Definition): + table_name = "users" + + def columns(self): + return [ + self.auto_pk(), + self.text("username"), + self.text("email"), + self.column("age", Int(self.dialect)), + self.column("balance", Float(self.dialect)), + self.column("is_active", Bool(self.dialect)), + self.timestamp("created_at"), + self.timestamp("updated_at"), + ] + + +class PostsDefinition(Definition): + table_name = "posts" + + def columns(self): + return [ + self.auto_pk(), + self.column("user_id", Int(self.dialect)), + self.text("title"), + self.longtext("content"), + self.text("status"), + self.timestamp("created_at"), + self.timestamp("updated_at"), + ] + + +class CommentsDefinition(Definition): + table_name = "comments" + + def columns(self): + return [ + self.auto_pk(), + self.column("user_id", Int(self.dialect)), + self.column("post_id", Int(self.dialect)), + self.longtext("content"), + self.column("is_hidden", Bool(self.dialect)), + self.timestamp("created_at"), + self.timestamp("updated_at"), + ] + + +class OrdersDefinition(Definition): + table_name = "orders" + + def columns(self): + return [ + self.auto_pk(), + self.column("user_id", Int(self.dialect)), + self.text("order_number"), + self.column("total_amount", Numeric(self.dialect, 12, 4)), + self.text("status"), + self.timestamp("created_at"), + self.timestamp("updated_at"), + ] + + +class OrderItemsDefinition(Definition): + table_name = "order_items" + + def columns(self): + return [ + self.auto_pk(), + self.column("order_id", Int(self.dialect)), + self.column("product_id", Int(self.dialect)), + self.required_text("product_name"), + self.column("quantity", Int(self.dialect)), + self.column("unit_price", Numeric(self.dialect, 12, 4)), + self.column("subtotal", Numeric(self.dialect, 12, 4)), + self.timestamp("created_at"), + self.timestamp("updated_at"), + ] + + def table_constraints(self): + return [ + TableConstraint( + self.dialect, + branch=TableUnique( + self.dialect, + ["order_id", "product_id", "product_name"], + ), + ) + ] + + +DEFINITIONS = ( + UsersDefinition, + PostsDefinition, + CommentsDefinition, + OrdersDefinition, + OrderItemsDefinition, +) + + +def _database_name() -> str: + """Database name from this conftest's namespace (below ``feature``).""" + parts = Path(__file__).parent.parts + start = parts.index("feature") + 1 + return "test_" + "_".join(parts[start:]) + + +@pytest.fixture(scope="session") +def database_config(backend_scenario): + """The scenario, its connection configuration, and the directory database name.""" + name = _database_name() + return backend_scenario, backend_scenario.make_config(name), name + + +@pytest.fixture(scope="session") +def database(database_config): + """The directory's database, prepared once and left for later files.""" + scenario, config, name = database_config + scenario.reset_database(name) + backend = scenario.backend_class(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + yield backend + backend.disconnect() + + +@pytest.fixture(scope="function", autouse=True) +def schema(database): + """Drop and recreate the tables this directory uses, before every test.""" + fixtures = [definition(database.dialect) for definition in DEFINITIONS] + for fixture in fixtures: + database.execute(*fixture.create_table.to_sql(), options=DDL) + yield + for fixture in reversed(fixtures): + database.execute(*fixture.drop_table.to_sql(), options=DDL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py new file mode 100644 index 00000000..0849e631 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py @@ -0,0 +1,242 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py +""" +Integration tests for with_() method using real SQLite database. + +These tests use real ActiveRecord models with SQLite backend to verify +the actual behavior of the with_() method, including: +- Eager loading of related data +- Query modifier application +- Cache behavior with modifiers +""" + +import pytest + + +class TestWithIntegration: + """Integration tests for with_() method using real database.""" + + def test_simple_with_loads_relations(self, blog_fixtures): + """Test that with_() actually loads related data from database.""" + User, Post, Comment = blog_fixtures + + user = User(username="testuser", email="test@example.com", age=25) + user.save() + + post = Post(title="Test Post", content="Test content", user_id=user.id, status="published") + post.save() + + posts = Post.query().with_("user").all() + + assert len(posts) == 1 + user_loader = posts[0].user + assert callable(user_loader) + loaded_user = user_loader() + assert loaded_user is not None + + def test_nested_with_loads_deep_relations(self, blog_fixtures): + """Test that nested with_() loads deeply nested relations.""" + User, Post, Comment = blog_fixtures + + user = User(username="testuser", email="test@example.com", age=25) + user.save() + + post = Post(title="Test Post", content="Test content", user_id=user.id, status="published") + post.save() + + comment = Comment(content="Test comment", post_id=post.id, user_id=user.id) + comment.save() + + comments = Comment.query().with_("post.user").all() + + assert len(comments) == 1 + post_loader = comments[0].post + assert callable(post_loader) + loaded_post = post_loader() + assert loaded_post is not None + user_loader = loaded_post.user + assert callable(user_loader) + + def test_with_modifier_filters_data(self, blog_fixtures): + """Test that query modifier actually filters the loaded data.""" + User, Post, Comment = blog_fixtures + + user = User(username="testuser", email="test@example.com", age=25) + user.save() + + def filter_published(q): + return q.where(Post.c.status == "published") + + posts = Post.query().with_(("user", filter_published)).all() + + assert len(posts) >= 0 + for post in posts: + assert post.status == "published" + + def test_with_modifier_orders_data(self, blog_fixtures): + """Test that query modifier can order the loaded data.""" + User, Post, Comment = blog_fixtures + + user = User(username="testuser", email="test@example.com", age=25) + user.save() + + post1 = Post(title="First Post", content="First", user_id=user.id, status="published") + post1.save() + + post2 = Post(title="Second Post", content="Second", user_id=user.id, status="published") + post2.save() + + posts = Post.query().with_("user").order_by((Post.c.title, "DESC")).all() + + assert len(posts) == 2 + assert posts[0].title == "Second Post" + assert posts[1].title == "First Post" + + def test_with_cache_not_used_when_modifier_changes(self, blog_fixtures): + """Test that cache is properly cleared when modifier changes.""" + User, Post, Comment = blog_fixtures + + user = User(username="testuser", email="test@example.com", age=25) + user.save() + + post1 = Post(title="Draft Post", content="Draft", user_id=user.id, status="draft") + post1.save() + + def filter_draft(q): + return q.where(Post.c.status == "draft") + + posts_draft = Post.query().with_(("user", filter_draft)).all() + assert len(posts_draft) >= 1 + + def test_with_empty_result_set(self, blog_fixtures): + """Test that with_() handles empty result set correctly.""" + User, Post, Comment = blog_fixtures + + posts = Post.query().with_("user").all() + assert len(posts) == 0 + + +class TestWithAsyncIntegration: + """Async integration tests for with_() method using real database.""" + + @pytest.mark.asyncio + async def test_async_with_loads_relations(self, async_blog_fixtures): + """Test async with_() loads related data.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + user = AsyncUser(username="async_user", email="async@test.com", age=30) + await user.save() + + post = AsyncPost(title="Async Post", content="Async content", user_id=user.id, status="published") + await post.save() + + posts = await AsyncPost.query().with_("author").all() + + assert len(posts) == 1 + user_loader = posts[0].author + assert callable(user_loader) + loaded_user = await user_loader() + assert loaded_user is not None + + @pytest.mark.asyncio + async def test_async_with_modifier(self, async_blog_fixtures): + """Test async with_() with query modifier.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + user = AsyncUser(username="async_user", email="async@test.com", age=30) + await user.save() + + post1 = AsyncPost(title="Draft", content="Draft", user_id=user.id, status="draft") + await post1.save() + + post2 = AsyncPost(title="Published", content="Published", user_id=user.id, status="published") + await post2.save() + + def filter_published(q): + return q.where(AsyncPost.c.status == "published") + + posts = await AsyncPost.query().with_(("author", filter_published)).all() + + assert len(posts) == 2 + for post in posts: + author_loader = post.author + assert callable(author_loader) + + @pytest.mark.asyncio + async def test_async_nested_with_loads_deep_relations(self, async_blog_fixtures): + """Test that nested with_() loads deeply nested relations in async context.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + user = AsyncUser(username="async_user", email="async@test.com", age=30) + await user.save() + + post = AsyncPost(title="Async Post", content="Async content", user_id=user.id, status="published") + await post.save() + + comment = AsyncComment(content="Async comment", post_id=post.id, user_id=user.id) + await comment.save() + + comments = await AsyncComment.query().with_("post.author").all() + + assert len(comments) == 1 + post_loader = comments[0].post + assert callable(post_loader) + + @pytest.mark.asyncio + async def test_async_with_modifier_filters_data(self, async_blog_fixtures): + """Test that query modifier filters the loaded relation data in async context.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + user = AsyncUser(username="async_user", email="async@test.com", age=30) + await user.save() + + def filter_published(q): + return q.where(AsyncPost.c.status == "published") + + posts = await AsyncPost.query().with_(("author", filter_published)).all() + + assert len(posts) >= 0 + + @pytest.mark.asyncio + async def test_async_with_modifier_orders_data(self, async_blog_fixtures): + """Test that query modifier can order the loaded data in async context.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + user = AsyncUser(username="async_user", email="async@test.com", age=30) + await user.save() + + post1 = AsyncPost(title="First Post", content="First", user_id=user.id, status="published") + await post1.save() + + post2 = AsyncPost(title="Second Post", content="Second", user_id=user.id, status="published") + await post2.save() + + posts = await AsyncPost.query().with_("author").order_by((AsyncPost.c.title, "DESC")).all() + + assert len(posts) == 2 + assert posts[0].title == "Second Post" + assert posts[1].title == "First Post" + + @pytest.mark.asyncio + async def test_async_with_cache_not_used_when_modifier_changes(self, async_blog_fixtures): + """Test that cache is properly cleared when modifier changes in async context.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + user = AsyncUser(username="async_user", email="async@test.com", age=30) + await user.save() + + post1 = AsyncPost(title="Draft Post", content="Draft", user_id=user.id, status="draft") + await post1.save() + + def filter_draft(q): + return q.where(AsyncPost.c.status == "draft") + + posts_draft = await AsyncPost.query().with_(("author", filter_draft)).all() + assert len(posts_draft) >= 1 + + @pytest.mark.asyncio + async def test_async_with_empty_result_set(self, async_blog_fixtures): + """Test that with_() handles empty result set correctly in async context.""" + AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures + + posts = await AsyncPost.query().with_("author").all() + assert len(posts) == 0 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py new file mode 100644 index 00000000..36582d90 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py +"""Use the shared ``relation/ordering`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.ordering.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py new file mode 100644 index 00000000..77082e5a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py @@ -0,0 +1,460 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py +""" +Unit tests for the optional ``order_by`` argument on HasMany / AsyncHasMany. + +These tests do not execute SQL: the SQLite in-memory backend is only used to +build queries. They pin the descriptor API (normalization, validation, the +``None`` default, the apply_order hook) and the generated SQL text (field-name +mapping, tie-breakers, ordering). +""" + +import asyncio +from typing import ClassVar, Optional + +from typing_extensions import Annotated + +import pytest +from pydantic import BaseModel + +from rhosocial.activerecord.backend.expression.functions import length +from rhosocial.activerecord.backend.expression.query_parts import SortDirection +from rhosocial.activerecord.backend.impl.sqlite.backend import ( + AsyncSQLiteBackend, + SQLiteBackend, +) +from rhosocial.activerecord.backend.impl.sqlite.config import SQLiteInMemoryConfig +from rhosocial.activerecord.base import DerivedField, FieldProxy +from rhosocial.activerecord.base.fields import UseColumn +from rhosocial.activerecord.field.composite_pk import CompositePKMixin +from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord +from rhosocial.activerecord.relation import ( + AsyncBelongsTo, + AsyncHasMany, + BelongsTo, + HasMany, + HasOne, + RelationManagementMixin, +) + + +# ============================================================================== +# Models used for SQL-text checks (sync) +# ============================================================================== + + +class OrderingAuthor(ActiveRecord): + __primary_key__ = "id" + """Author with an ordered HasMany whose sort field uses a custom column.""" + + @classmethod + def table_name(cls): + return "ordering_authors" + + c: ClassVar[FieldProxy] = FieldProxy() + + id: Optional[int] = None + name: str + + books: ClassVar[HasMany["OrderingBook"]] = HasMany( + foreign_key="author_id", + inverse_of="author", + order_by=[("title", "DESC")], + ) + + +class OrderingBook(ActiveRecord): + __primary_key__ = "id" + """Book whose Python field ``title`` maps to the column ``book_title``.""" + + @classmethod + def table_name(cls): + return "ordering_books" + + id: Optional[int] = None + title: Annotated[str, UseColumn("book_title")] + author_id: int + + author: ClassVar[BelongsTo["OrderingAuthor"]] = BelongsTo( + foreign_key="author_id", + inverse_of="books", + ) + + +class PlainOrderingAuthor(ActiveRecord): + __primary_key__ = "id" + """Author whose HasMany keeps the old un-ordered behaviour.""" + + @classmethod + def table_name(cls): + return "ordering_authors" + + id: Optional[int] = None + name: str + + books: ClassVar[HasMany["OrderingBook"]] = HasMany( + foreign_key="author_id", + inverse_of="author", + order_by=None, + ) + + +class BadOrderAuthor(ActiveRecord): + __primary_key__ = "id" + """Author with a relation that names a field that does not exist.""" + + @classmethod + def table_name(cls): + return "ordering_authors" + + id: Optional[int] = None + name: str + + books: ClassVar[HasMany["OrderingBook"]] = HasMany( + foreign_key="author_id", + inverse_of="author", + order_by="does_not_exist", + ) + + +class DerivedBook(ActiveRecord): + __primary_key__ = "id" + """Book with a derived field that must not be accepted as an order key.""" + + @classmethod + def table_name(cls): + return "ordering_books" + + id: Optional[int] = None + title: str + author_id: int + + title_length: ClassVar[Annotated[int, DerivedField( + lambda d: length(d, DerivedBook.c.title), + )]] + + author: ClassVar[BelongsTo["DerivedAuthor"]] = BelongsTo( + foreign_key="author_id", + inverse_of="books", + ) + + +class DerivedAuthor(ActiveRecord): + __primary_key__ = "id" + """Author ordering by a derived field (rejected on first query build).""" + + @classmethod + def table_name(cls): + return "ordering_authors" + + id: Optional[int] = None + name: str + + books: ClassVar[HasMany["DerivedBook"]] = HasMany( + foreign_key="author_id", + inverse_of="author", + order_by="title_length", + ) + + +class OrderingPart(CompositePKMixin, ActiveRecord): + """Composite-primary-key child used for tie-breaker checks.""" + + @classmethod + def table_name(cls): + return "ordering_parts" + + @classmethod + def primary_key(cls): + return ("order_id", "line_no") + + order_id: int + line_no: int + label: str + owner_id: int + + +class OrderingOwner(ActiveRecord): + __primary_key__ = "id" + """Owner of composite-key parts ordered by ``label``.""" + + @classmethod + def table_name(cls): + return "ordering_owners" + + id: Optional[int] = None + name: str + + parts: ClassVar[HasMany["OrderingPart"]] = HasMany( + foreign_key="owner_id", + order_by="label", + ) + + +# ============================================================================== +# Async models used for SQL-text checks +# ============================================================================== + + +class AsyncOrderingAuthor(AsyncActiveRecord): + __primary_key__ = "id" + """Async mirror of OrderingAuthor.""" + + @classmethod + def table_name(cls): + return "ordering_authors" + + id: Optional[int] = None + name: str + + books: ClassVar[AsyncHasMany["AsyncOrderingBook"]] = AsyncHasMany( + foreign_key="author_id", + inverse_of="author", + order_by=[("title", "DESC")], + ) + + +class AsyncOrderingBook(AsyncActiveRecord): + __primary_key__ = "id" + """Async mirror of OrderingBook.""" + + @classmethod + def table_name(cls): + return "ordering_books" + + id: Optional[int] = None + title: str + author_id: int + + author: ClassVar[AsyncBelongsTo["AsyncOrderingAuthor"]] = AsyncBelongsTo( + foreign_key="author_id", + inverse_of="books", + ) + + +# ============================================================================== +# Descriptor-only (memory-based) models +# ============================================================================== + + +class MemoryEmp(RelationManagementMixin, BaseModel): + """Memory-based child for inverse-pair validation (no database access).""" + + id: int + name: str + dept_id: int + + department: ClassVar[BelongsTo["MemoryDept"]] = BelongsTo( + foreign_key="dept_id", + inverse_of="ordered_emps", + ) + + +class MemoryDept(RelationManagementMixin, BaseModel): + """Memory-based parent declaring a HasMany with order_by.""" + + id: int + name: str + + ordered_emps: ClassVar[HasMany["MemoryEmp"]] = HasMany( + foreign_key="dept_id", + inverse_of="department", + order_by="name", + ) + + +# ============================================================================== +# Fixtures +# ============================================================================== + + +@pytest.fixture(scope="module", autouse=True) +def configured_backends(): + """Bind the in-memory backend so queries can be built (no tables needed).""" + models = ( + OrderingAuthor, + OrderingBook, + PlainOrderingAuthor, + BadOrderAuthor, + DerivedAuthor, + DerivedBook, + OrderingOwner, + OrderingPart, + ) + for model in models: + model.configure(SQLiteInMemoryConfig(), SQLiteBackend) + + loop = asyncio.new_event_loop() + try: + loop.run_until_complete(AsyncOrderingAuthor.configure(SQLiteInMemoryConfig(), AsyncSQLiteBackend)) + loop.run_until_complete(AsyncOrderingBook.configure(SQLiteInMemoryConfig(), AsyncSQLiteBackend)) + finally: + loop.close() + yield + + loop = asyncio.new_event_loop() + try: + loop.run_until_complete(AsyncOrderingAuthor.backend().disconnect()) + loop.run_until_complete(AsyncOrderingBook.backend().disconnect()) + finally: + loop.close() + for model in models: + model.backend().disconnect() + + +# ============================================================================== +# Constructor / normalization +# ============================================================================== + + +class TestHasManyOrderByConstructor: + """Pin the accepted ``order_by`` forms and their normalization.""" + + def test_none_is_the_default_plain_behavior(self): + relation = HasMany(foreign_key="author_id") + assert relation._order_by is None + + def test_explicit_none_is_plain_behavior(self): + relation = HasMany(foreign_key="author_id", order_by=None) + assert relation._order_by is None + + def test_single_field_string_defaults_to_no_direction(self): + relation = HasMany(foreign_key="author_id", order_by="created_at") + assert relation._order_by == (("created_at", None),) + + def test_single_field_tuple_with_direction(self): + relation = HasMany(foreign_key="author_id", order_by=("created_at", "DESC")) + assert relation._order_by == (("created_at", SortDirection.DESC),) + + def test_sequence_mixes_directions(self): + relation = HasMany( + foreign_key="author_id", + order_by=["name", ("created_at", "DESC")], + ) + assert relation._order_by == (("name", None), ("created_at", SortDirection.DESC)) + + def test_empty_sequence_is_rejected(self): + with pytest.raises(ValueError, match="non-empty"): + HasMany(foreign_key="author_id", order_by=[]) + + def test_invalid_direction_is_rejected(self): + with pytest.raises(ValueError, match="Invalid ORDER BY direction"): + HasMany(foreign_key="author_id", order_by=("name", "UP")) + + def test_non_string_entry_is_rejected(self): + with pytest.raises(TypeError, match="field name"): + HasMany(foreign_key="author_id", order_by=[123]) + + def test_async_relation_normalizes_the_same_way(self): + relation = AsyncHasMany(foreign_key="author_id", order_by=["name", ("id", "DESC")]) + assert relation._order_by == (("name", None), ("id", SortDirection.DESC)) + + def test_async_none_is_plain_behavior(self): + relation = AsyncHasMany(foreign_key="author_id", order_by=None) + assert relation._order_by is None + + +# ============================================================================== +# Inverse validation / metaclass compatibility +# ============================================================================== + + +class TestHasManyOrderByCompatibility: + """HasMany(order_by=...) must pass every check plain HasMany passes.""" + + def test_valid_inverse_with_belongs_to(self): + descriptor = MemoryDept.__dict__["ordered_emps"] + assert descriptor.get_related_model(MemoryDept) is MemoryEmp + + def test_has_one_inverse_is_rejected(self): + class Dept(RelationManagementMixin, BaseModel): + id: int + items: ClassVar[HasMany["Item"]] = HasMany( + foreign_key="dept_id", + inverse_of="department", + order_by="name", + ) + + class Item(RelationManagementMixin, BaseModel): + id: int + dept_id: int + department: ClassVar[HasOne["Dept"]] = HasOne( + foreign_key="dept_id", + inverse_of="items", + ) + + with pytest.raises(ValueError, match="Invalid relationship pair"): + Dept.__dict__["items"].get_related_model(Dept) + + def test_sync_model_rejects_async_has_many_with_order_by(self): + with pytest.raises(TypeError, match="Async relation descriptor"): + class BadSyncModel(ActiveRecord): + id: int + items: ClassVar[AsyncHasMany] = AsyncHasMany( + foreign_key="owner_id", + order_by="id", + ) + + def test_async_model_rejects_sync_has_many_with_order_by(self): + with pytest.raises(TypeError, match="Sync relation descriptor"): + class BadAsyncModel(AsyncActiveRecord): + id: int + items: ClassVar[HasMany] = HasMany( + foreign_key="owner_id", + order_by="id", + ) + + +# ============================================================================== +# SQL text +# ============================================================================== + + +class TestHasManyOrderBySql: + """Pin the generated ORDER BY clause.""" + + def test_relation_query_maps_field_to_column_and_appends_pk(self): + author = OrderingAuthor(id=1, name="Ada") + sql, _params = author.books_query().to_sql() + assert 'ORDER BY "book_title" DESC, "id" ASC' in sql + + def test_none_keeps_plain_has_many_sql(self): + author = PlainOrderingAuthor(id=1, name="Plain") + sql, _params = author.books_query().to_sql() + assert "ORDER BY" not in sql + assert 'WHERE "ordering_books"."author_id" = ?' in sql + + def test_explicit_primary_key_is_not_duplicated(self): + relation = HasMany( + foreign_key="author_id", + order_by=[("id", "DESC")], + ) + relation.name = "pk_books" + query = relation.apply_order(OrderingBook.query(), OrderingBook) + sql, _params = query.to_sql() + assert 'ORDER BY "id" DESC' in sql + assert sql.count('"id"') == 1 + + def test_composite_primary_key_appends_every_key_column(self): + owner = OrderingOwner(id=1, name="Owner") + sql, _params = owner.parts_query().to_sql() + assert 'ORDER BY "label" ASC, "order_id" ASC, "line_no" ASC' in sql + + def test_unknown_field_fails_when_query_is_built(self): + author = BadOrderAuthor(id=1, name="Bad") + with pytest.raises(ValueError, match="does_not_exist"): + author.books_query() + + def test_derived_field_fails_when_query_is_built(self): + author = DerivedAuthor(id=1, name="Derived") + with pytest.raises(ValueError, match="title_length"): + author.books_query() + + def test_async_relation_query_matches_sync_sql(self): + author = AsyncOrderingAuthor(id=1, name="Async Ada") + sql, _params = author.books_query().to_sql() + assert 'ORDER BY "title" DESC, "id" ASC' in sql + + def test_chain_order_by_appends_after_default(self): + author = OrderingAuthor(id=1, name="Ada") + sql, _params = author.books_query().order_by("author_id").to_sql() + assert 'ORDER BY "book_title" DESC, "id" ASC, "author_id" ASC' in sql diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py new file mode 100644 index 00000000..87988fd2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py +"""Use the shared ``query_integration`` combination fixture set.""" +from rhosocial.activerecord.testsuite.feature.query_integration.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py new file mode 100644 index 00000000..97198cc0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py +""" +Bridge file for ActiveQuery + SetOperationQuery combination tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query_integration.test_active_query_set_operation import * # noqa: F403 +except ImportError: + pytest.skip("ActiveQuery + SetOperationQuery testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py new file mode 100644 index 00000000..204ae10f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py +""" +Bridge file for async ActiveQuery + SetOperationQuery combination tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query_integration.test_active_query_set_operation_async import * # noqa: F403 +except ImportError: + pytest.skip("async ActiveQuery + SetOperationQuery testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py new file mode 100644 index 00000000..38080e2a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py +""" +Bridge file for CTEQuery + ActiveQuery combination tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_active_query import * # noqa: F403 +except ImportError: + pytest.skip("CTEQuery + ActiveQuery testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py new file mode 100644 index 00000000..cf4a17e8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py +""" +Bridge file for async CTEQuery + ActiveQuery combination tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_active_query_async import * # noqa: F403 +except ImportError: + pytest.skip("async CTEQuery + ActiveQuery testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py new file mode 100644 index 00000000..91893bd5 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py +""" +Bridge file for CTEQuery + SetOperationQuery combination tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_set_operation import * # noqa: F403 +except ImportError: + pytest.skip("CTEQuery + SetOperationQuery testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py new file mode 100644 index 00000000..80776fc2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py +""" +Bridge file for async CTEQuery + SetOperationQuery combination tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_set_operation_async import * # noqa: F403 +except ImportError: + pytest.skip("async CTEQuery + SetOperationQuery testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py new file mode 100644 index 00000000..30262f20 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py +"""Use the shared ``setop`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.setop.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py new file mode 100644 index 00000000..24ed5f06 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py +""" +Bridge file for composite PK sync set operation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.setop.test_composite_pk_set_operation import * # noqa: F403 +except ImportError: + pytest.skip("composite_pk testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py new file mode 100644 index 00000000..87348f0a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py +""" +Bridge file for composite PK async set operation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.setop.test_composite_pk_set_operation_async import * # noqa: F403 +except ImportError: + pytest.skip("composite_pk testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py new file mode 100644 index 00000000..35a7809f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py +""" +Bridge file for sync set operation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.setop.test_set_operation import * # noqa: F403 +except ImportError: + pytest.skip("setop testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py new file mode 100644 index 00000000..d3d071c1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py +""" +Bridge file for async set operation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.setop.test_set_operation_async import * # noqa: F403 +except ImportError: + pytest.skip("setop testsuite not available", allow_module_level=True) From f382677def93a7bc041d4e871e8e52d78bed1902 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 11:50:08 +0800 Subject: [PATCH 54/81] ci: include restructured query/cte/setop/query_integration dirs in test scope --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1e626dec..b21f221f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -326,7 +326,7 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration test: name: Python ${{ matrix.python-version }} / postgres ${{ matrix.postgres-version }} @@ -439,14 +439,14 @@ jobs: if: matrix.postgres-version != '18' run: | export PYTHONPATH=src:tests - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration - name: Run tests with coverage (only for postgres 18 on Python 3.14) if: matrix.postgres-version == '18' && matrix.python-version == '3.14' run: | export PYTHONPATH=src:tests pip install codecov - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration - name: Upload coverage to Codecov if: matrix.postgres-version == '18' && matrix.python-version == '3.14' @@ -525,4 +525,4 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup + python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration From a75258fdf004c68c848028feb417d315f75d261d Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 12:09:46 +0800 Subject: [PATCH 55/81] fix(test): remove core-local test artifacts from query bridges --- .../basic/test_placeholder_conversion.py | 166 ---- .../feature/query/column_helpers.py | 93 --- .../core/test_aggregate_window_families.py | 242 ------ .../query/core/test_boolean_connectives.py | 82 -- .../query/core/test_column_type_support.py | 785 ------------------ .../test_document_and_conversion_families.py | 489 ----------- .../query/core/test_operation_boundaries.py | 390 --------- .../query/core/test_operation_symmetry.py | 113 --- .../query/core/test_predicate_alias.py | 166 ---- .../test_string_concatenation_operator.py | 164 ---- .../core/test_string_value_operations.py | 209 ----- .../core/test_surface_only_column_types.py | 200 ----- .../core/test_temporal_value_families.py | 283 ------- .../feature/query/core/test_typed_columns.py | 418 ---------- .../query/core/test_value_family_inference.py | 226 ----- .../query/core/test_value_type_lattice.py | 214 ----- .../query/joins/test_join_on_params.py | 232 ------ .../joins/test_join_right_table_resolution.py | 178 ---- .../relation/core/test_async_descriptors.py | 242 ------ .../query/relation/core/test_batch_loading.py | 218 ----- .../query/relation/core/test_cache_result.py | 106 --- .../relation/core/test_cache_serialization.py | 462 ----------- .../relation/core/test_descriptor_coverage.py | 650 --------------- .../core/test_descriptor_db_coverage.py | 352 -------- .../relation/core/test_instance_cache.py | 281 ------- .../query/relation/core/test_redis_cache.py | 279 ------- .../relation/core/test_relation_management.py | 238 ------ .../core/test_relation_modifier_cache.py | 350 -------- .../relation/core/test_relation_validation.py | 402 --------- .../query/relation/core/test_type_resolver.py | 269 ------ .../query/relation/core/test_with_modifier.py | 472 ----------- .../feature/query/relation/legacy/conftest.py | 281 ------- .../relation/legacy/test_with_integration.py | 242 ------ .../ordering/test_has_many_order_by_unit.py | 460 ---------- 34 files changed, 9954 deletions(-) delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py delete mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py deleted file mode 100644 index 5e2797d0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py +++ /dev/null @@ -1,166 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_placeholder_conversion.py -"""Unit tests for convert_qmark_placeholder utility function.""" - -import pytest -from unittest.mock import MagicMock - -from rhosocial.activerecord.query.utils import convert_qmark_placeholder - - -@pytest.fixture -def sqlite_dialect(): - """Create a mock SQLite dialect that uses '?' as placeholder.""" - dialect = MagicMock() - dialect.get_parameter_placeholder.return_value = "?" - return dialect - - -@pytest.fixture -def mysql_dialect(): - """Create a mock MySQL dialect that uses '%s' as placeholder.""" - dialect = MagicMock() - dialect.get_parameter_placeholder.return_value = "%s" - return dialect - - -@pytest.fixture -def postgres_dialect(): - """Create a mock PostgreSQL dialect that uses '%s' as placeholder.""" - dialect = MagicMock() - dialect.get_parameter_placeholder.return_value = "%s" - return dialect - - -class TestSQLiteDialect: - """Tests for SQLite dialect ('?' placeholder — no conversion needed).""" - - def test_no_conversion_needed(self, sqlite_dialect): - """SQLite uses '?' natively, so '?' should remain unchanged.""" - sql = "SELECT * FROM users WHERE name = ? AND age > ?" - assert convert_qmark_placeholder(sqlite_dialect, sql) == sql - - def test_escape_reduces_to_literal(self, sqlite_dialect): - """Escaped \\? should be reduced to literal ? for SQLite.""" - sql = r"col \? 'key'" - assert convert_qmark_placeholder(sqlite_dialect, sql) == "col ? 'key'" - - def test_double_backslash_reduces_to_single(self, sqlite_dialect): - """Escaped \\\\ should be reduced to literal \\ for SQLite.""" - sql = r"path \\?" - assert convert_qmark_placeholder(sqlite_dialect, sql) == "path \\?" - - def test_no_placeholders(self, sqlite_dialect): - """SQL without placeholders should pass through unchanged.""" - sql = "SELECT * FROM users" - assert convert_qmark_placeholder(sqlite_dialect, sql) == sql - - -class TestMySQLDialect: - """Tests for MySQL dialect ('%s' placeholder).""" - - def test_single_placeholder(self, mysql_dialect): - """Single '?' should be converted to '%s'.""" - sql = "SELECT * FROM users WHERE name = ?" - assert convert_qmark_placeholder(mysql_dialect, sql) == "SELECT * FROM users WHERE name = %s" - - def test_multiple_placeholders(self, mysql_dialect): - """Multiple '?' should all be converted to '%s'.""" - sql = "SELECT * FROM users WHERE name = ? AND age > ?" - expected = "SELECT * FROM users WHERE name = %s AND age > %s" - assert convert_qmark_placeholder(mysql_dialect, sql) == expected - - def test_no_placeholders(self, mysql_dialect): - """SQL without placeholders should pass through unchanged.""" - sql = "SELECT * FROM users" - assert convert_qmark_placeholder(mysql_dialect, sql) == sql - - def test_escape_produces_literal_qmark(self, mysql_dialect): - """Escaped \\? should produce literal ? (not %s).""" - sql = r"col \? 'key'" - assert convert_qmark_placeholder(mysql_dialect, sql) == "col ? 'key'" - - -class TestPostgreSQLDialect: - """Tests for PostgreSQL dialect ('%s' placeholder, same as MySQL).""" - - def test_single_placeholder(self, postgres_dialect): - """Single '?' should be converted to '%s'.""" - sql = "SELECT * FROM users WHERE name = ?" - assert convert_qmark_placeholder(postgres_dialect, sql) == "SELECT * FROM users WHERE name = %s" - - def test_multiple_placeholders(self, postgres_dialect): - """Multiple '?' should all be converted to '%s'.""" - sql = "INSERT INTO users (name, age) VALUES (?, ?)" - expected = "INSERT INTO users (name, age) VALUES (%s, %s)" - assert convert_qmark_placeholder(postgres_dialect, sql) == expected - - def test_escape_hstore_operator(self, postgres_dialect): - """Escaped \\? should produce literal ? for PostgreSQL hstore/jsonb operators.""" - sql = r"hstore_col \? 'key'" - assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col ? 'key'" - - def test_escape_pipe_operator(self, postgres_dialect): - """Escaped \\? before | should preserve ?| operator.""" - sql = r"hstore_col \?| array['x']" - assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col ?| array['x']" - - def test_escape_ampersand_operator(self, postgres_dialect): - """Escaped \\? before & should preserve ?& operator.""" - sql = r"hstore_col \?& array['x', 'y']" - assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col ?& array['x', 'y']" - - def test_mixed_placeholders_and_operators(self, postgres_dialect): - """Mix of placeholders and escaped operators should convert correctly.""" - sql = r"SELECT * FROM t WHERE a = ? AND h \?| array['x']" - expected = "SELECT * FROM t WHERE a = %s AND h ?| array['x']" - assert convert_qmark_placeholder(postgres_dialect, sql) == expected - - def test_unescaped_qmark_pipe_is_converted(self, postgres_dialect): - """Unescaped ?| should have ? converted to %s (no special handling).""" - sql = "hstore_col ?| array['x']" - # ? is converted to %s, | stays - assert convert_qmark_placeholder(postgres_dialect, sql) == "hstore_col %s| array['x']" - - -class TestEdgeCases: - """Edge case tests.""" - - def test_empty_string(self, mysql_dialect): - """Empty string should return empty string.""" - assert convert_qmark_placeholder(mysql_dialect, "") == "" - - def test_only_placeholder(self, mysql_dialect): - """String with only '?' should become '%s'.""" - assert convert_qmark_placeholder(mysql_dialect, "?") == "%s" - - def test_only_escaped(self, mysql_dialect): - """String with only '\\?' should become '?'.""" - assert convert_qmark_placeholder(mysql_dialect, "\\?") == "?" - - def test_consecutive_placeholders(self, mysql_dialect): - """Consecutive '?' should all be converted.""" - assert convert_qmark_placeholder(mysql_dialect, "??") == "%s%s" - - def test_escape_at_end(self, mysql_dialect): - """\\ at end of string without following ? should be preserved.""" - assert convert_qmark_placeholder(mysql_dialect, "test\\") == "test\\" - - def test_double_escape(self, mysql_dialect): - """\\\\? should produce literal \\ followed by placeholder %s.""" - # In Python raw string: r"\\?" = two chars: \, ? - # But in regular string: "\\\\?" = three chars: \, \, ? - # The scanner sees \\ → \, then ? → %s - result = convert_qmark_placeholder(mysql_dialect, "\\\\?") - assert result == "\\%s" - - def test_double_backslash_then_escaped_qmark(self, mysql_dialect): - """\\\\\\? should produce literal \\ followed by literal ?.""" - # Scanner: \\ → \, \? → ? - result = convert_qmark_placeholder(mysql_dialect, "\\\\\\?") - assert result == "\\?" - - def test_placeholder_in_string_literal(self, mysql_dialect): - """The function does NOT parse SQL semantics — ? inside quotes is also converted. - This is by design: users must escape literal ? characters.""" - sql = "SELECT * FROM t WHERE col = '?'" - assert convert_qmark_placeholder(mysql_dialect, sql) == "SELECT * FROM t WHERE col = '%s'" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py b/tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py deleted file mode 100644 index 777a48ca..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py +++ /dev/null @@ -1,93 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/column_helpers.py -"""Test-side helpers for the column-class selection path, and its canonical list. - -The production path is ``base/field_proxy.py``: ``Model.c.`` asks the -model for the field's column-type declaration (dialect-free), then -``FieldAccessor`` selects the class the model's backend answers. This module -mirrors that selection step for a bare annotation, so a test can build a column -without declaring a model. - -``COMMON_TYPES`` is the test-side name for the framework-modelled Python types -every backend must answer for. The list itself now lives in the framework -(``base/framework_types.FRAMEWORK_PYTHON_TYPES``) because two dialect tables -- -the column-class table and the suggested storage-type table -- are keyed by it, -and stating it twice is how the two would drift. The tests hold each backend to -the framework's list, not to a second copy of it. - -Deliberately **not** a fallback: an annotation the selection cannot classify -raises :class:`ColumnTypeResolutionError` exactly as ``Model.c.`` -would, so a test that builds a column from a bad annotation fails here for the -same reason the model would, and the two cannot drift apart. -""" - -from typing import Any, Optional, Tuple, Type - -from rhosocial.activerecord.backend.expression.column_types import ColumnBase -from rhosocial.activerecord.backend.expression.core import Column -from rhosocial.activerecord.base.framework_types import FRAMEWORK_PYTHON_TYPES -from rhosocial.activerecord.base.field_proxy import ( - ColumnTypeResolutionError, - FieldAccessor, -) - -#: The framework-modelled Python types, in declared reading order. The order -#: matters where a subclass walk meets an ambiguous annotation: ``bool`` ahead -#: of ``int``, and ``enum.Enum`` tested before the walk (a ``(int, Enum)`` stays -#: an enum). The list lives in the framework because both dialect tables are -#: keyed by it; this name is the test-side alias. -COMMON_TYPES: Tuple[Any, ...] = FRAMEWORK_PYTHON_TYPES - - -def resolve_column_class(dialect: Any, annotation: Any, declared: Any = None) -> Type[ColumnBase]: - """The class *dialect* selects for *annotation*. - - The field accessor's own selection step, invoked without a model. *declared* - is the field's column-type declaration when a test exercises one; ``None`` - asks the backend's tables. - """ - return FieldAccessor._select_column_class(dialect, annotation, declared) - - -def build_column( - dialect: Any, - column_name: str, - annotation: Any, - table: Optional[str] = None, - schema_name: Optional[str] = None, - column_type: Any = None, -) -> ColumnBase: - """Build the column expression *dialect* selects for *annotation*. - - Args: - dialect: The dialect to select through. Selection is per-backend by - design, so a test that wants a specific column class must say which - backend's answer it is asking for. - column_name: The SQL name to render. - annotation: The Python annotation, ``Annotated`` / ``Optional`` included. - table: Optional table qualifier. - schema_name: Optional schema qualifier. - column_type: A ``UseColumnType`` when the test is exercising an explicit - declaration; ``None`` asks the backend's tables. - - Returns: - The constructed column expression. - - Raises: - ColumnTypeResolutionError: The backend's tables have no column class for - *annotation*, or answered ``None`` for its entry. - """ - column_class = resolve_column_class(dialect, annotation, column_type) - if column_class is Column: - # The untyped column keeps its own narrower constructor and can only - # arrive by being declared explicitly, so this is a shape difference - # rather than a fallback. - return Column(dialect, column_name, table=table, schema_name=schema_name) - return column_class(dialect, column_name, table=table, schema_name=schema_name) - - -__all__ = [ - "COMMON_TYPES", - "ColumnTypeResolutionError", - "build_column", - "resolve_column_class", -] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py deleted file mode 100644 index 19e7dfbd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_aggregate_window_families.py +++ /dev/null @@ -1,242 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_aggregate_window_families.py -"""What aggregating and windowing a value gives back. - -Each aggregate is its own node class now, so the identity of the function -travels on the node instead of inside a generic name string: COUNT is a -CountFunction, SUM a SumFunction, and so on. A count is a whole number however -wide the thing counted is; an average is numeric whatever it averages; MIN and -MAX hand back something of the operand's kind, which the node cannot know, so -they offer only the operations every value has. - -A window function is either a count or a value from another row, and confusing -the two is how a name column ends up arithmetic. ROW_NUMBER counts; LAG -borrows. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_aggregate_window_families.py -import pytest - -from rhosocial.activerecord.backend.expression.declared import ( - IntegerAnnotation, - NumberAnnotation, - TextAnnotation, -) -from rhosocial.activerecord.backend.expression import ( - AvgFunction, - CountFunction, - FunctionCall, - MaxFunction, - MinFunction, - SumFunction, -) -from rhosocial.activerecord.backend.expression.value_types import ( - ArrayValue, - BooleanValue, - JSONValue, - NumericValue, - OpaqueValue, - TemporalValue, - TextValue, -) -from rhosocial.activerecord.backend.expression import functions as F - - -@pytest.fixture -def dialect(): - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - d = SQLiteDialect() - d._version = (3, 46, 1) - return d - - -@pytest.fixture -def columns(dialect): - from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column - - return { - "int": build_column(dialect, "i", int), - "float": build_column(dialect, "f", float), - "str": build_column(dialect, "s", str), - "json": build_column(dialect, "j", dict), - } - - -# --------------------------------------------------------------------------- -# Counting -# --------------------------------------------------------------------------- - - -def test_count_is_always_a_whole_number(dialect, columns): - """However wide the thing counted, the answer is a number of rows.""" - for column in columns.values(): - assert isinstance(F.count(dialect, column), CountFunction) - - -def test_count_takes_arithmetic_and_not_string_operations(dialect, columns): - count = F.count(dialect, columns["int"]) - assert hasattr(count, "__add__") - assert not hasattr(count, "upper") - - -# --------------------------------------------------------------------------- -# Averaging widens -# --------------------------------------------------------------------------- - - -def test_avg_is_numeric_whatever_it_averages(dialect, columns): - """Averaging whole numbers gives a fraction, so the family has to allow - one. SQL Server is the exception that returns an integer here, which is - exactly why it is not something to build an operation surface on.""" - for column in columns.values(): - assert isinstance(F.avg(dialect, column), AvgFunction) - - -# --------------------------------------------------------------------------- -# Adding, minimising and maximising are their own node classes -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "factory, node_class", - [("sum_", SumFunction), ("min_", MinFunction), ("max_", MaxFunction)], -) -def test_a_reduction_is_its_own_node_class(dialect, columns, factory, node_class): - """The reduction's identity is the node class, not a name string. - - SUM / MIN / MAX used to be guessed into a value family from the operand's - column class; now each is its own node, and the operand kind does not - change which node comes back. - """ - reduce_it = getattr(F, factory) - for column in columns.values(): - assert isinstance(reduce_it(dialect, column), node_class) - - -@pytest.mark.parametrize( - "factory, node_class", - [("sum_", SumFunction), ("min_", MinFunction), ("max_", MaxFunction)], -) -def test_a_literal_input_is_still_the_classed_node(dialect, factory, node_class): - """A literal operand does not change which node comes back. - - The reduction is classed by the function, not inferred from the operand - kind, so a literal -- which declares no kind -- yields the same node a - column would. - """ - result = getattr(F, factory)(dialect, 1) - assert isinstance(result, node_class) - - -def test_min_does_not_guess_the_operand_family(dialect, columns): - """MIN hands back something of the operand's kind, which the node cannot - know, so it offers only the operations every value has rather than - guessing a family from the operand.""" - result = F.min_(dialect, columns["str"]) - assert isinstance(result, MinFunction) - assert not isinstance(result, (NumberAnnotation, TextAnnotation)) - assert hasattr(result, "is_null") - - -# --------------------------------------------------------------------------- -# Building a document or a sequence -# --------------------------------------------------------------------------- - - -def test_building_a_json_aggregate_gives_json(dialect, columns): - assert isinstance(F.json_objectagg(dialect, columns["int"], columns["str"]), JSONValue) - assert isinstance(F.json_arrayagg(dialect, columns["json"]), JSONValue) - - -def test_collecting_into_an_array_gives_an_array(dialect, columns): - assert isinstance(F.array_agg(dialect, columns["int"]), ArrayValue) - - -# --------------------------------------------------------------------------- -# Windowing: a count, or a value from another row -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize("factory", ["row_number", "rank", "dense_rank"]) -def test_a_rank_is_a_whole_number(dialect, factory): - for windowed in (getattr(F, factory)(dialect),): - assert isinstance(windowed, NumericValue) - assert hasattr(windowed, "__add__") - assert not hasattr(windowed, "upper") - - -@pytest.mark.parametrize( - "factory, extra", - [("lag", ()), ("lead", ()), ("first_value", ()), ("last_value", ()), ("nth_value", (2,))], -) -def test_a_value_from_another_row_keeps_its_family(dialect, columns, factory, extra): - """LAG over a name column is a name, not a count. - - Which is asserted by the arithmetic that is *absent*: a name is not a - number, so no ``sqrt``. The string operations are present, because the - result genuinely is a string -- it was ``not hasattr(windowed, "upper")`` - before the class replaced the tag, and that assertion is what the tag was - costing: the node carried ``family="string"`` while offering none of the - string surface, so a caller could not tell from the object which operations - it had. Now the class says it, and the operations come with it. - """ - windowed = getattr(F, factory)(dialect, columns["str"], *extra) - assert isinstance(windowed, TextAnnotation) - assert hasattr(windowed, "like") - assert not hasattr(windowed, "sqrt") - - -def test_lag_over_a_float_column_is_fractional(dialect, columns): - assert isinstance(F.lag(dialect, columns["float"]), NumberAnnotation) - - -# --------------------------------------------------------------------------- -# The node states its family, and the round trip survives it -# --------------------------------------------------------------------------- - - -def test_a_typed_aggregate_reports_its_family_for_introspection(dialect, columns): - """Introspection has to see what a result is, or nothing downstream can - read it. - - It used to read ``get_params()["family"]``. That keyword is gone: it - duplicated the class, and a tag that can disagree with the class it sits on - is worse than no tag at all. The class is the introspection surface now, so - this asserts the class -- which is what a caller would have branched on - anyway. - """ - result = F.count(dialect, columns["int"]) - assert isinstance(result, CountFunction) - - -def test_a_typed_window_reports_its_family_for_introspection(dialect, columns): - """Same for a window function: the class, not the removed ``family`` tag.""" - result = F.lag(dialect, columns["int"]) - assert isinstance(result, IntegerAnnotation) - - -def test_an_untyped_aggregate_reports_no_family(dialect, columns): - """A node constructed directly is the untyped one, and says so by being it. - - ``get_params()["family"] is None`` was how this used to be checked. There is - no ``family`` parameter to be ``None`` now, so the assertion is the class: - a bare ``FunctionCall`` is not a typed value, which is the same - statement without the tag that could contradict it. - """ - result = FunctionCall(dialect, "COUNT", columns["int"], is_aggregate=True) - assert not isinstance( - result, - ( - ArrayValue, - BooleanValue, - JSONValue, - NumericValue, - OpaqueValue, - TemporalValue, - TextValue, - ), - ) -def test_declaring_a_family_does_not_change_the_sql(dialect, columns): - """Typing is a surface decision, never a rendering one.""" - assert F.count(dialect, columns["int"]).to_sql()[0] == "COUNT(\"i\")" - assert F.lag(dialect, columns["int"]).to_sql()[0] == "LAG(\"i\", ?)" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py deleted file mode 100644 index c3957152..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_boolean_connectives.py +++ /dev/null @@ -1,82 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_boolean_connectives.py -"""A value's connectives keep the value type; a predicate's stay predicates. - -``p1 & p2`` combines predicates for a WHERE clause. A truth *value* needs the -same three operators with a different result: ``(flag & other)`` must be -something a SELECT list can carry, so it stays a boolean value -(:class:`LogicalValue`) with the same SQL. One implementation, -dispatched by the receiver, which is what these tests pin. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_boolean_connectives.py -import pytest - -from rhosocial.activerecord.backend.expression import BooleanColumn -from rhosocial.activerecord.backend.expression.bases import SQLPredicate, SQLValue -from rhosocial.activerecord.backend.expression.core import LogicalValue -from rhosocial.activerecord.backend.expression.predicates import LogicalPredicate - - -@pytest.fixture -def dialect(): - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - return SQLiteDialect() - - -def test_a_boolean_values_connectives_keep_the_value_type(dialect): - flag = BooleanColumn(dialect, "flag") - other = BooleanColumn(dialect, "other") - - combined = flag & other - assert isinstance(combined, LogicalValue) - assert isinstance(combined, SQLValue) - assert not isinstance(combined, SQLPredicate) - - sql, params = combined.to_sql() - assert "AND" in sql and params == () - - -def test_a_value_can_be_negated_and_chained(dialect): - flag = BooleanColumn(dialect, "flag") - other = BooleanColumn(dialect, "other") - - assert isinstance(~flag, LogicalValue) - - chained = (flag & other) | flag - assert isinstance(chained, LogicalValue) - assert "OR" in chained.to_sql()[0] - - -def test_a_predicate_combination_stays_a_predicate(dialect): - flag = BooleanColumn(dialect, "flag") - other = BooleanColumn(dialect, "other") - - combined = flag.is_true() & other.is_true() - assert isinstance(combined, LogicalPredicate) - assert isinstance(combined, SQLPredicate) - assert not isinstance(combined, SQLValue) - - assert isinstance(~flag.is_true(), LogicalPredicate) - - -def test_a_value_expression_can_be_aliased_into_a_select_list(dialect): - flag = BooleanColumn(dialect, "flag") - aliased = (flag & flag).as_("both") - sql, params = aliased.to_sql() - assert "AND" in sql and "both" in sql - - -def test_a_boolean_value_can_be_compared(dialect): - flag = BooleanColumn(dialect, "flag") - predicate = (flag & flag) == flag - assert isinstance(predicate, SQLPredicate) - - -def test_both_receivers_render_the_same_connective(dialect): - flag = BooleanColumn(dialect, "flag") - other = BooleanColumn(dialect, "other") - - value_sql = (flag & other).to_sql()[0] - predicate_sql = (flag.is_true() & other.is_true()).to_sql()[0] - assert "AND" in value_sql and "AND" in predicate_sql diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py deleted file mode 100644 index 52e90bb0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_column_type_support.py +++ /dev/null @@ -1,785 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_column_type_support.py -"""The column-type support protocol: entry contract, backend authority, failures. - -Four questions, and nothing here needs a database to answer them: - -1. **Is the entry contract kept?** Every backend answers the common Python - types the tests enumerate, so a model never meets a table with a hole. -2. **Whose answer is it?** The backend's own tables, always: a dialect that - overrides one entry changes exactly that entry, and a backend's extra table - carries its own Python types without touching the common ones. -3. **What does a declared column type look like, and what fails loudly?** - ``Model.column_type()`` presents the declaration as written (a - ``UseColumnType`` marker, a class, or a sequence); the field accessor - selects from it; ``Any``, a bare ``Union``, an unregistered custom class - and a ``None`` table entry all raise. -4. **What do the declaration accessors present?** ``column_type`` and - ``column_data_type`` are dialect-free declarations -- no fallback, no - selection -- and the batch method mirrors the data-type one. - -Plus the boolean algebra surface and its literal discipline: ``TRUE``/``FALSE`` -as keywords, never ``1``/``0``, which PostgreSQL rejects outright -(``operator does not exist: boolean = integer``). -""" - -import datetime -import decimal -import enum -import typing -import uuid -from typing import Any, ClassVar, Dict, List, Optional, Union - -import pytest - -from rhosocial.activerecord.backend.adapters import ( - BitString, - Geometry, - MacAddress, - Multirange, - Range, - Vector, -) -from rhosocial.activerecord.backend.dialect.mixins import ColumnTypeMixin -from rhosocial.activerecord.backend.dialect.protocols import ColumnTypeSupport -from rhosocial.activerecord.backend.expression.column_types import ( - ArrayColumn, - ColumnBase, - TimestampColumn, - IntegerColumn, - JSONColumn, - NumericColumn, - StringColumn, - UUIDColumn, -) -from rhosocial.activerecord.backend.expression.types import JsonType -from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect -from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect -from rhosocial.activerecord.backend.impl.sqlite.mixins.column_type import ( - SQLITE_COLUMN_TYPES, -) -from rhosocial.activerecord.base.field_proxy import ( - ColumnTypeResolutionError, - FieldProxy, -) -from rhosocial.activerecord.base.fields import DDLAnnotation, UseColumnType, UseSqlType -from rhosocial.activerecord.model import ActiveRecord - -from rhosocial.activerecord_postgres_test.feature.query.column_helpers import ( - COMMON_TYPES, - build_column, - resolve_column_class, -) - - -def sqlite_dialect(version=(3, 46, 1)): - """A version-adapted SQLite dialect. - - ``supports_json_type`` reads ``self.version``, and an unadapted dialect - raises rather than answering -- so every test that renders needs a version. - 3.46 is a real release well past the 3.38.0 line where the JSON functions - became part of SQLite proper. - """ - return SQLiteDialect(version=version) - - -def dummy_dialect(): - """An adapted dummy dialect: the dialect-less baseline, not a server.""" - dialect = DummyDialect() - dialect._version = (3, 46, 1) - return dialect - - -def resolve(dialect, annotation, declared=None): - """The selection step, for the cases below that read as "resolve this".""" - return resolve_column_class(dialect, annotation, declared) - - -_ENTRY_IDS = [getattr(entry, "__name__", str(entry)) for entry in COMMON_TYPES] - - -# --------------------------------------------------------------------------- -# 1. The entry contract -# --------------------------------------------------------------------------- - - -def test_the_canonical_entry_list_is_the_declared_order(): - """Order is the protocol's reading order, and the list lives in the framework. - - Both dialect tables are keyed by ``FRAMEWORK_PYTHON_TYPES``, so the order - stated here is the one both lookups walk. The six complex families come last - because the subclass walk must meet ``bool`` before ``int`` and must meet - ``Geometry`` only for a geometry annotation. - """ - assert _ENTRY_IDS == [ - "bool", - "int", - "float", - "Decimal", - "str", - "bytes", - "bytearray", - "date", - "time", - "datetime", - "timedelta", - "UUID", - "dict", - "list", - "tuple", - "set", - "frozenset", - "Enum", - "Geometry", - "Vector", - "BitString", - "Range", - "Multirange", - "MacAddress", - ] - - -def test_entry_list_has_no_duplicates(): - """A duplicate would make 'answer every entry' ambiguous.""" - assert len(set(COMMON_TYPES)) == len(COMMON_TYPES) - - -def test_the_protocol_is_structural(): - """A dialect satisfies it by answering the two tables, nothing else.""" - dialect = sqlite_dialect() - assert isinstance(dialect, ColumnTypeSupport) - assert callable(dialect.suggested_column_types) - assert callable(dialect.suggested_extra_column_types) - - -def _assert_answered_or_refused(dialect, entry): - """Every framework type is either answered with a class or refused with None. - - ``None`` is the protocol's stated answer for "no column class for this value - family", so the resolution must fail with that message rather than fall - through to another table or pick a class anyway. - """ - if dialect.suggested_column_types()[entry] is None: - with pytest.raises(ColumnTypeResolutionError, match="has no column class"): - resolve(dialect, entry) - else: - assert issubclass(resolve(dialect, entry), ColumnBase) - - -@pytest.mark.parametrize("entry", COMMON_TYPES, ids=_ENTRY_IDS) -def test_every_entry_resolves_or_is_refused_by_sqlite(entry): - _assert_answered_or_refused(sqlite_dialect(), entry) - - -@pytest.mark.parametrize("entry", COMMON_TYPES, ids=_ENTRY_IDS) -def test_every_entry_resolves_or_is_refused_by_the_dummy_baseline(entry): - _assert_answered_or_refused(dummy_dialect(), entry) - - -def test_boolean_is_its_own_entry_not_an_integer(): - """``bool`` is an ``int`` subclass; the entry order is what keeps them apart. - - Without the order, ``bool`` would walk to ``int`` and a truth-value field - would offer integer arithmetic -- which MySQL and SQLite would happily - execute on a column holding 0/1. - """ - assert COMMON_TYPES.index(bool) < COMMON_TYPES.index(int) - assert resolve(sqlite_dialect(), bool) is not resolve(sqlite_dialect(), int) - - -def test_date_and_time_are_separate_entries_sharing_a_column_class(): - """They are distinct entries because the framework asks about each of them. - - They answer the same column class today, which is a modelling gap the entry - list is what will eventually close (splitting ``TimestampColumn`` by operation - set). Asserting the shared answer keeps that gap visible: when one of them - splits, this test is what notices. - """ - assert resolve(sqlite_dialect(), datetime.date) is TimestampColumn - assert resolve(sqlite_dialect(), datetime.time) is TimestampColumn - - -# --------------------------------------------------------------------------- -# 2. The backend is the authority -# --------------------------------------------------------------------------- - - -class OverridingDialect(SQLiteDialect): - """A backend that disagrees with SQLite about exactly one entry. - - Its table is SQLite's own with one entry replaced, so "the seventeen other - answers are untouched" is a statement about this dialect versus the backend - it extends. ``str`` answers with a class neither would have picked, which is - what makes the authority observable: a core-side table consulted first would - ignore this. - """ - - def suggested_column_types(self): - table = super().suggested_column_types() - table[str] = NumericColumn - return table - - -class RefusingDialect(SQLiteDialect): - """A backend with no column class for one entry. - - The honest "this backend has none", which is what MySQL 5.6 and Firebird - would have to say about a value family they cannot carry. It must reach the - caller as a failure rather than as a fallback to another table. - """ - - def suggested_column_types(self): - table = super().suggested_column_types() - table[dict] = None - return table - - -class Complex: - """A user type the framework does not model; carried by the extra table.""" - - -class ExtendingDialect(SQLiteDialect): - """A backend with a Python type of its own, in its own table.""" - - def suggested_extra_column_types(self): - return {Complex: JSONColumn} - - -def test_backend_override_changes_only_its_own_entry(): - """One overridden entry, one changed answer, seventeen untouched.""" - dialect = OverridingDialect(version=(3, 46, 1)) - - assert resolve(dialect, str) is NumericColumn - assert resolve(sqlite_dialect(), str) is StringColumn - - for entry in COMMON_TYPES: - if entry is str: - continue - _assert_answered_or_refused(dialect, entry) - _assert_answered_or_refused(sqlite_dialect(), entry) - - -def test_a_backend_may_extend_with_an_entry_of_its_own(): - """The extension path for a Python type the framework does not model.""" - dialect = ExtendingDialect(version=(3, 46, 1)) - - assert resolve(dialect, Complex) is JSONColumn - assert resolve(dialect, Optional[Complex]) is JSONColumn - # ...and the common entries keep working alongside it. - assert resolve(dialect, int) is IntegerColumn - - -def test_the_returned_tables_are_copies(): - """A caller walking a table must not mutate what the next field reads.""" - dialect = sqlite_dialect() - table = dialect.suggested_column_types() - table.clear() - assert set(dialect.suggested_column_types()) == set(COMMON_TYPES) - - -def test_the_mixin_withholds_the_common_table(): - """There is no inherited table: a dialect that does not answer is told so.""" - - class Bare(ColumnTypeMixin): - pass - - with pytest.raises(NotImplementedError): - Bare().suggested_column_types() - assert Bare().suggested_extra_column_types() == {} - - -def test_sqlite_answers_exactly_the_framework_types(): - """Its table is complete, and none of the twenty-four entries is refused. - - The six complex families used to be ``None`` for a real reason -- SQLite - has no spatial or vector operation -- but the core classes they now name - promise only the column surface (alias, null tests, casting, collation), - which SQLite does execute on a value it stores as text or JSON. - """ - from rhosocial.activerecord.backend.expression.column_types import ( - BitStringColumn, - GeometryColumn, - IntervalColumn, - MacAddressColumn, - MultirangeColumn, - RangeColumn, - VectorColumn, - ) - - assert set(SQLITE_COLUMN_TYPES) == set(COMMON_TYPES) - assert all(value is not None for value in SQLITE_COLUMN_TYPES.values()) - assert resolve(sqlite_dialect(), Geometry) is GeometryColumn - assert resolve(sqlite_dialect(), Vector) is VectorColumn - assert resolve(sqlite_dialect(), BitString) is BitStringColumn - assert resolve(sqlite_dialect(), Range) is RangeColumn - assert resolve(sqlite_dialect(), Multirange) is MultirangeColumn - assert resolve(sqlite_dialect(), MacAddress) is MacAddressColumn - assert resolve(sqlite_dialect(), datetime.timedelta) is IntervalColumn - - -def test_the_dummy_dialect_states_its_own_baseline(): - """It stands for no server, so it states no backend's answers. - - SQLite is built into core and the dummy is the other dialect core ships, so - the two are easy to conflate. They are deliberately different: the dummy is - the dialect-less default a test reads, and copying a real backend's table - into it would make "what does the portable baseline say" unanswerable. - """ - dummy = dummy_dialect() - assert set(dummy.suggested_column_types()) == set(COMMON_TYPES) - assert resolve(dummy, list) is ArrayColumn - assert resolve(sqlite_dialect(), list) is JSONColumn - # ``Decimal`` was merged into NumericColumn on both sides; asserting the - # shared answer keeps the merge deliberate. - assert resolve(dummy, decimal.Decimal) is NumericColumn - assert resolve(sqlite_dialect(), decimal.Decimal) is NumericColumn - - -# --------------------------------------------------------------------------- -# 3. Declared column types: three forms, and what is refused -# --------------------------------------------------------------------------- - - -def test_use_column_type_overrides_the_tables(): - """Naming a class bypasses the recommendation, and only the recommendation.""" - assert resolve(sqlite_dialect(), int, UseColumnType(StringColumn)) is StringColumn - - -def test_a_bare_class_declaration_answers(): - """``column_type`` may present a class directly; the selector accepts it.""" - assert resolve(sqlite_dialect(), int, StringColumn) is StringColumn - - -def test_a_single_candidate_sequence_answers(): - """A one-element sequence is a declaration with one candidate.""" - assert resolve(sqlite_dialect(), int, [StringColumn]) is StringColumn - - -def test_a_multi_candidate_sequence_is_refused(): - """Choosing among candidates needs the capability declaration, which is not here. - - Taking the first silently would make the declaration a lie the caller - cannot see. - """ - with pytest.raises(ColumnTypeResolutionError, match="capability"): - resolve(sqlite_dialect(), int, [StringColumn, JSONColumn]) - - -def test_an_empty_sequence_is_refused(): - with pytest.raises(ColumnTypeResolutionError, match="empty sequence"): - resolve(sqlite_dialect(), int, []) - - -def test_a_non_declaration_is_refused(): - with pytest.raises(ColumnTypeResolutionError, match="not a column-type declaration"): - resolve(sqlite_dialect(), int, "StringColumn") - - -def test_use_column_type_saves_an_annotation_no_table_could_classify(): - """The escape hatch is what makes every other failure actionable.""" - assert resolve(sqlite_dialect(), Any, UseColumnType(StringColumn)) is StringColumn - - -def test_use_column_type_with_several_classes_is_refused(): - """Multi-candidate selection needs the capability declaration, which is not here. - - Declaring two classes is a request to negotiate with the backend, and there - is nothing to ask yet. Taking the first silently would make the declaration - a lie the caller cannot see. - """ - with pytest.raises(TypeError, match="capability"): - UseColumnType(StringColumn, JSONColumn) - - -def test_use_column_type_with_no_classes_is_refused(): - with pytest.raises(TypeError, match="at least one"): - UseColumnType() - - -@pytest.mark.parametrize( - "bad_factory, why", - [ - (str, "builtin"), - (lambda: "StringColumn", "name"), - (lambda: StringColumn(sqlite_dialect(), "x"), "instance"), - ], - ids=["builtin", "string", "instance"], -) -def test_use_column_type_rejects_non_column_classes(bad_factory, why): - """A column class is a type, never an instance -- an instance carries state. - - Built through factories because a column instance needs a dialect, and - constructing one at collection time would put a database-free object in the - module preamble. - """ - with pytest.raises(TypeError, match="ColumnBase"): - UseColumnType(bad_factory()) - - -def test_use_column_type_is_not_a_ddl_annotation(): - """Strict independence: the DDL collector must never see it. - - ``UseSqlType`` is a ``DDLAnnotation``; this one deliberately is not. If it - were, the DDL layer would be one refactor away from inferring a storage type - from a column declaration -- the exact coupling the independence ruling - forbids. - """ - assert not isinstance(UseColumnType(StringColumn), DDLAnnotation) - - -def test_use_column_type_is_independent_of_use_sql_type(): - """Both declared, and neither is inferred from the other.""" - Annotated = getattr(typing, "Annotated", None) - if Annotated is None: - pytest.skip("typing.Annotated requires Python 3.9+") - - annotation = Annotated[int, UseSqlType(JsonType()), UseColumnType(StringColumn)] - declared = [m for m in annotation.__metadata__ if isinstance(m, UseColumnType)][0] - - assert resolve(sqlite_dialect(), annotation, declared) is StringColumn - # The DDL side still sees only its own candidate. - assert [type(d).__name__ for d in annotation.__metadata__] == [ - "UseSqlType", - "UseColumnType", - ] - assert UseSqlType(JsonType()).data_type.name == "json" - - -# --------------------------------------------------------------------------- -# 4. The model-side declaration accessors (dialect-free) -# --------------------------------------------------------------------------- - - -def _declared_model(dialect): - Annotated = getattr(typing, "Annotated", None) - if Annotated is None: - pytest.skip("typing.Annotated requires Python 3.9+") - - class Declared(ActiveRecord): - @classmethod - def table_name(cls): - return "declared_types" - - @classmethod - def primary_key(cls): - return "id" - - c: ClassVar[FieldProxy] = FieldProxy() - - id: int - label: Annotated[str, UseColumnType(JSONColumn)] - payload: Annotated[dict, UseSqlType(JsonType())] - - Declared.__backend__ = type("B", (), {"dialect": dialect})() - return Declared - - -def test_column_type_presents_the_declaration_or_none(): - """``column_type`` presents; it does not resolve and does not fall back.""" - Model = _declared_model(sqlite_dialect()) - - declared = Model.column_type("label") - assert isinstance(declared, UseColumnType) - assert declared.column_class is JSONColumn - assert Model.column_type("id") is None - - -def test_two_column_type_declarations_on_one_field_are_refused(): - Annotated = getattr(typing, "Annotated", None) - if Annotated is None: - pytest.skip("typing.Annotated requires Python 3.9+") - - class Bad(ActiveRecord): - @classmethod - def table_name(cls): - return "bad_declarations" - - @classmethod - def primary_key(cls): - return "id" - - c: ClassVar[FieldProxy] = FieldProxy() - - id: int - broken: Annotated[ - Any, - UseColumnType(StringColumn), - UseColumnType(JSONColumn), - ] - - Bad.__backend__ = type("B", (), {"dialect": sqlite_dialect()})() - with pytest.raises(TypeError, match="UseColumnType declarations"): - Bad.column_type("broken") - - -def test_column_data_type_presents_the_declaration_or_none(): - """The renamed accessor: dialect-free declaration, no inference.""" - Model = _declared_model(sqlite_dialect()) - - assert Model.column_data_type("id") is None - marker = Model.column_data_type("payload") - assert isinstance(marker, UseSqlType) - assert isinstance(marker.data_types[0], JsonType) - - -def test_columns_data_type_batches(): - Model = _declared_model(sqlite_dialect()) - - batch = Model.columns_data_type() - assert set(batch) == {"id", "label", "payload"} - assert batch["payload"] is Model.column_data_type("payload") - - -def test_the_accessor_path_end_to_end(): - """The declared class wins where the table would have answered otherwise.""" - Model = _declared_model(sqlite_dialect()) - - assert type(Model.c.label) is JSONColumn # declared - assert type(Model.c.id) is IntegerColumn # selected from the table - assert type(Model.c.payload) is JSONColumn # table, not the DDL declaration - - -# --------------------------------------------------------------------------- -# 5. Failures: tables with holes, refused entries, unclassifiable annotations -# --------------------------------------------------------------------------- - - -def test_a_missing_entry_is_reported_against_the_backends_table(): - class PartialDialect(SQLiteDialect): - def suggested_column_types(self): - return {str: StringColumn} - - with pytest.raises(ColumnTypeResolutionError, match="Cannot choose a column class"): - resolve(PartialDialect(version=(3, 46, 1)), int) - - -def test_a_none_entry_fails_and_names_the_declaration_that_fixes_it(): - with pytest.raises(ColumnTypeResolutionError) as excinfo: - resolve(RefusingDialect(version=(3, 46, 1)), dict) - message = str(excinfo.value) - assert "no column class for" in message - assert "UseColumnType" in message - - -def test_a_none_entry_does_not_leak_into_other_entries(): - """One refusal must not make the whole backend unusable.""" - dialect = RefusingDialect(version=(3, 46, 1)) - assert resolve(dialect, str) is StringColumn - assert resolve(dialect, int) is IntegerColumn - - -def test_a_table_entry_that_is_not_a_column_class_raises(): - """A malformed table is a backend bug, caught where it is written down.""" - - class WrongDialect(SQLiteDialect): - def suggested_column_types(self): - table = super().suggested_column_types() - table[str] = "StringColumn" - return table - - with pytest.raises(ColumnTypeResolutionError, match="not a ColumnBase subclass"): - resolve(WrongDialect(version=(3, 46, 1)), str) - - -@pytest.mark.parametrize( - "annotation", - [Any, Union[int, str], List[int], Dict[str, int]], - ids=["Any", "bare-union", "parameterised-list", "parameterised-dict"], -) -def test_unclassifiable_annotations_fail(annotation): - """``Any``, a bare ``Union``, a parameterised container: no entry, no answer. - - Each of these used to become the permissive ``Column``. Now it is a - definition-time failure naming what to write instead, which is the change - the ruling asked for: a field the framework cannot type is a mistake in the - model, and a silent fallback hides it until the database complains. - """ - with pytest.raises(ColumnTypeResolutionError) as excinfo: - resolve(sqlite_dialect(), annotation) - assert "UseColumnType" in str(excinfo.value) - - -def test_an_unregistered_custom_class_fails(): - """A class the framework does not model is unclassifiable, not a string.""" - - class Money: - pass - - with pytest.raises(ColumnTypeResolutionError, match="Cannot choose a column class"): - resolve(sqlite_dialect(), Money) - - -def test_a_subclass_of_an_entry_resolves_through_the_walk(): - """``class MyStr(str)`` is a string; the walk is what says so.""" - assert resolve(sqlite_dialect(), type("Code", (str,), {})) is StringColumn - - -def test_an_enum_subclass_resolves_to_the_enum_entry(): - """Before the subclass walk, so a ``(int, Enum)`` is not filed as an int.""" - assert resolve(sqlite_dialect(), enum.Enum) is StringColumn - - class Weekday(enum.IntEnum): - MONDAY = 1 - - assert resolve(sqlite_dialect(), Weekday) is StringColumn - - -def test_optional_and_annotated_still_resolve(): - Annotated = getattr(typing, "Annotated", None) - if Annotated is None: - pytest.skip("typing.Annotated requires Python 3.9+") - - assert resolve(sqlite_dialect(), Optional[dict]) is JSONColumn - # An unrelated marker is simply not a UseColumnType; the selector resolves - # from the peeled annotation and the declaration is read by the model layer. - assert resolve(sqlite_dialect(), Annotated[str, "marker"]) is StringColumn - - -# --------------------------------------------------------------------------- -# 6. Boolean algebra and the literal discipline -# --------------------------------------------------------------------------- - - -def _flag(name="flag"): - return build_column(sqlite_dialect(), name, bool) - - -def test_is_true_and_is_false_render_keywords(): - """``IS TRUE`` / ``IS FALSE``, three-valued-logic correct. - - ``= TRUE`` would match differently under three-valued logic, and ``= 1`` - is not portable at all: PostgreSQL rejects ``boolean = integer`` outright. - """ - assert _flag().is_true().to_sql() == ('"flag" IS TRUE', ()) - assert _flag().is_false().to_sql() == ('"flag" IS FALSE', ()) - - -def test_and_or_not_render_connectives_not_bitwise_operators(): - """``AND`` / ``OR`` / ``NOT`` — MySQL accepts bitwise ``&`` / ``|`` too, and - on a boolean column those compute something else entirely.""" - column = _flag() - assert (column.is_true() & column.is_false()).to_sql() == ( - '"flag" IS TRUE AND "flag" IS FALSE', - (), - ) - assert (column.is_true() | column.is_false()).to_sql() == ( - '"flag" IS TRUE OR "flag" IS FALSE', - (), - ) - assert (~column.is_true()).to_sql() == ('NOT ("flag" IS TRUE)', ()) - - -def test_boolean_algebra_never_renders_one_or_zero(): - """The rendering discipline, asserted rather than described. - - ``1`` / ``0`` as a boolean literal is the one thing that works on SQLite and - MySQL and fails on PostgreSQL, so a regression that renders it would pass on - two backends and break on a third. The literal has to be the keyword. - """ - column = _flag() - rendered = [ - column.is_true().to_sql()[0], - column.is_false().to_sql()[0], - (column.is_true() & column.is_false()).to_sql()[0], - (column.is_true() | column.is_false()).to_sql()[0], - (~column.is_true()).to_sql()[0], - ] - for sql in rendered: - assert " TRUE" in sql or "FALSE" in sql - # No integer literal standing in for the value. - assert " IS 1" not in sql - assert " IS 0" not in sql - assert "= 1" not in sql - assert "= 0" not in sql - - -def test_boolean_columns_only_carry_the_boolean_surface(): - """``str`` has no ``AND``; that is what the narrow classes are for. - - The mixin is composed into :class:`BooleanColumn` rather than inherited - from :class:`ColumnBase` precisely so that these three operators stay off - every other family — giving ``str`` an ``AND`` would be the guess the narrow - classes exist to avoid. - """ - assert hasattr(build_column(sqlite_dialect(), "f", bool), "__and__") - assert hasattr(build_column(sqlite_dialect(), "f", bool), "__or__") - assert hasattr(build_column(sqlite_dialect(), "f", bool), "__invert__") - assert not hasattr(build_column(sqlite_dialect(), "s", str), "__and__") - assert not hasattr(build_column(sqlite_dialect(), "n", int), "__invert__") - - -def test_negating_the_column_is_not_the_same_as_is_false(): - """``~flag`` is NOT; three-valued logic makes ``NOT NULL`` unknown. - - Callers asking "is it false?" say ``is_false()``. ``~`` is the connective. - """ - column = _flag() - assert column.is_false().to_sql()[0] != f"NOT ({column.to_sql()[0]})" - - -def test_boolean_algebra_composes_with_other_predicates(): - """The connectives are the same ones predicates use, so they interleave.""" - column = _flag() - name = build_column(sqlite_dialect(), "name", str) - combined = (column.is_true() & name.like("a%")) | column.is_false() - sql, params = combined.to_sql() - assert " AND " in sql and " OR " in sql - assert params == ("a%",) - - -# --------------------------------------------------------------------------- -# 7. Two backends, one contract -- and no free resolvers -# --------------------------------------------------------------------------- - - -def test_two_dialects_differ_only_where_stated(): - """The dummy and SQLite differ exactly in the sequence entries. - - SQLite has no array type, so its four sequence entries are JSON documents; - the dummy keeps the portable ``ArrayColumn``. Every other entry agrees — - ``float`` and ``Decimal`` are ``NumericColumn`` on both sides, and - ``timedelta`` is ``IntervalColumn`` on both. A backend that deviated - anywhere else would be changing an answer no decision asked it to change. - """ - dummy, sqlite = dummy_dialect(), sqlite_dialect() - deviated = {list, tuple, set, frozenset} - for entry in COMMON_TYPES: - if entry in deviated: - continue - if sqlite.suggested_column_types()[entry] is None: - assert dummy.suggested_column_types()[entry] is None - continue - assert resolve(dummy, entry) is resolve(sqlite, entry) - assert resolve(sqlite, list) is JSONColumn - assert resolve(dummy, list) is ArrayColumn - - -def test_the_public_surface_has_no_free_resolvers(): - """Resolution belongs to the field accessor; there is no module function.""" - import rhosocial.activerecord.base as base_package - - assert not hasattr(base_package, "build_column") - assert not hasattr(base_package, "column_class_for") - assert not hasattr(base_package, "column_dispatch") - - -def test_the_permissive_column_is_still_constructible_by_hand(): - """Retiring the fallback did not retire the class. - - ``Column(dialect, "x")`` is how a caller with a bare column name gets an - expression; what is gone is the framework deciding that an unclassifiable - annotation becomes one. - """ - from rhosocial.activerecord.backend.expression import Column - - column = Column(sqlite_dialect(), "anything") - assert column.to_sql() == ('"anything"', ()) - - -def test_uuid_stays_its_own_column_family(): - """A UUID has no portable operator, but it is still not a string.""" - assert resolve(sqlite_dialect(), uuid.UUID) is UUIDColumn - assert resolve(sqlite_dialect(), uuid.UUID) is not StringColumn - - -def test_decimal_is_a_number_and_not_a_string(): - assert issubclass(resolve(sqlite_dialect(), decimal.Decimal), NumericColumn) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py deleted file mode 100644 index f7cd2f5a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_document_and_conversion_families.py +++ /dev/null @@ -1,489 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_document_and_conversion_families.py -"""The families that carry documents, sequences, casts and XML. - -A JSON extraction is not always a document: `->` hands back JSON and `->>` -hands back text, so the same node class reports two families and the chain -narrows. A cast states its result in the target type, which is the only place -it can come from. And an operation over several values — GREATEST, a CASE — -answers with their common kind, or with nothing when they disagree. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_document_and_conversion_families.py -import pytest - -from rhosocial.activerecord.backend.expression import functions as F, FunctionCall, Literal, XMLColumn -from rhosocial.activerecord.backend.expression.bases import SQLValue -from rhosocial.activerecord.backend.expression.column_types import annotation_for -from rhosocial.activerecord.backend.expression.type_name import is_valid_type_name -from rhosocial.activerecord.backend.expression.types import ( - CustomType, - JsonType, - VarCharType, - XmlType, -) -from rhosocial.activerecord.backend.expression.advanced_functions import CaseExpression -from rhosocial.activerecord.backend.expression.declared import ( - ArrayAnnotation, - BinaryAnnotation, - BooleanAnnotation, - IntegerAnnotation, - JSONAnnotation, - NumberAnnotation, - TemporalAnnotation, - TextAnnotation, - UUIDAnnotation, - XMLAnnotation, -) -from rhosocial.activerecord.backend.expression.value_types import ( - ArrayValue, - JSONValue, - NumericValue, - TemporalValue, - TextValue, - XMLValue, -) - -#: Every value class the lattice holds. "No typed result" is asserted by saying -#: the result is none of these, so the list has to be the whole set: an -#: assertion that forgets a class would pass for the wrong reason. -TYPED_VALUE_CLASSES = ( - ArrayAnnotation, - BinaryAnnotation, - BooleanAnnotation, - IntegerAnnotation, - JSONAnnotation, - NumberAnnotation, - TemporalAnnotation, - TextAnnotation, - UUIDAnnotation, - XMLAnnotation, -) - - -def is_typed_as_one_of_these(result): - """Whether *result* is any of the typed value classes. - - A node that declares no type is honest about it: it is none of these. This - is the shape the tests that want "unknown" assert, and it is why the list - above is spelled out rather than imported wholesale -- a class added to the - lattice has to be added here too, or these assertions would go on passing - while the answer they are about became possible. - """ - return isinstance(result, TYPED_VALUE_CLASSES) - - -@pytest.fixture -def dialect(): - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - d = SQLiteDialect() - d._version = (3, 46, 1) - return d - - -@pytest.fixture -def columns(dialect): - from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column - - return { - "int": build_column(dialect, "i", int), - "float": build_column(dialect, "f", float), - "str": build_column(dialect, "s", str), - "json": build_column(dialect, "j", dict), - "array": build_column(dialect, "l", list), - } - - -# --------------------------------------------------------------------------- -# The same node, two families -# --------------------------------------------------------------------------- - - -def test_arrow_extraction_gives_a_document(dialect, columns): - assert isinstance(F.json_extract(dialect, columns["json"], Literal(dialect, "$.a")), JSONValue) - - -def test_double_arrow_extraction_gives_text(dialect, columns): - """`->>` is a narrowing: a document becomes a string and cannot widen back.""" - assert isinstance(F.json_extract_text(dialect, columns["json"], "$.a"), TextValue) - - -def test_a_built_document_is_a_document(dialect, columns): - assert isinstance(F.json_build_object(dialect, "k", 1), JSONValue) - assert isinstance(F.json_array_elements(dialect, columns["json"]), JSONValue) - - -def test_a_document_offers_the_json_accessors(dialect, columns): - built = F.json_build_object(dialect, "k", 1) - assert isinstance(built, JSONValue) - assert hasattr(built, "json_path") - assert not hasattr(built, "upper") - - -def test_text_reports_a_string_family(dialect, columns): - """Narrowing is reported, which is what propagation reads. - - The JSON accessors stay, because one node class serves both arrow - directions and the wrapper cannot hide what it forwards — that is a known - over-offer on this one class, not a claim that text is a document. - """ - text = F.json_extract_text(dialect, columns["json"], "$.a") - assert isinstance(text, TextValue) - assert text.to_sql()[0].endswith("->>'$.a'") - - -# --------------------------------------------------------------------------- -# Sequences -# --------------------------------------------------------------------------- - - -def test_a_sequence_is_a_sequence(dialect, columns): - assert isinstance(F.unnest(dialect, columns["array"]), ArrayValue) - - -def test_measuring_a_sequence_gives_a_whole_number(dialect, columns): - assert isinstance(F.array_length(dialect, columns["array"], 1), NumericValue) - - -# --------------------------------------------------------------------------- -# Operations over several values -# --------------------------------------------------------------------------- - - -def test_greatest_answers_with_what_its_arguments_answer_with(dialect, columns): - assert isinstance(F.greatest(dialect, columns["int"], columns["int"]), IntegerAnnotation) - - -def test_greatest_of_mixed_kinds_is_unknown(dialect, columns): - """The comparison is legal SQL and the answer is neither kind, so neither - surface may be offered. Guessing the first or the widest would be wrong.""" - assert not is_typed_as_one_of_these(F.greatest(dialect, columns["int"], columns["str"])) - - -def test_least_agrees_with_greatest(dialect, columns): - assert isinstance(F.least(dialect, columns["float"], columns["float"]), NumberAnnotation) - - -def test_nullif_keeps_the_value_it_tests(dialect, columns): - assert isinstance(F.nullif(dialect, columns["str"], None), TextAnnotation) - - -# --------------------------------------------------------------------------- -# what an operation over several values keeps -# --------------------------------------------------------------------------- - - -def test_a_consensus_needs_exactly_one(dialect, columns): - """A CASE over disagreeing branches is legal SQL that answers with neither - kind, so neither surface may be offered.""" - mixed = CaseExpression(dialect, cases=[(columns["int"], columns["int"])], - else_result=columns["float"]) - assert not is_typed_as_one_of_these(mixed) - - -def test_an_argument_without_a_family_does_not_break_a_consensus(dialect, columns): - """A literal says nothing, so it neither agrees nor disagrees.""" - with_literal = CaseExpression(dialect, cases=[(columns["int"], Literal(dialect, 1))], - else_result=columns["int"]) - assert isinstance(with_literal, NumericValue) - - -# --------------------------------------------------------------------------- -# A cast states its result in the target type -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "sql_type", - [ - "VARCHAR(255)", - "TEXT", - "NVARCHAR2(10)", - "INTEGER", - "BIGINT", - "DECIMAL(10,2)", - "DOUBLE PRECISION", - "BOOLEAN", - "TIMESTAMP", - "JSONB", - "BLOB", - "UUID", - "XML", - ], -) -def test_real_sql_type_names_are_names(sql_type): - """These are all type names a database has. - - They used to be pinned to the value family a cast to them produces. There is - no such table now: ``cast`` answers with the class of the ``DataType`` it - was handed, so the name carries no type of its own to be right about. What - remains is that the name is recognised -- the grammar, not a meaning. - """ - assert is_valid_type_name(sql_type) - - -def test_an_unknown_sql_type_is_still_a_name(): - """A name nobody here knows is still shaped like a name. - - What it means is the dialect's business, decided when the dialect is - asked to render it, not something this package guesses at here. - """ - assert is_valid_type_name("GEOMETRY") - assert is_valid_type_name("POINT") - assert not is_valid_type_name(None) - - -def test_cast_takes_its_type_from_the_target_type(dialect, columns): - """The cast answers with the surface of the type it was handed.""" - assert isinstance( - F.cast(dialect, columns["int"], VarCharType(dialect, length=10)), - TextValue, - ) - assert isinstance( - F.cast(dialect, columns["int"], JsonType(dialect)), JSONValue - ) - - -def test_an_unmodelled_target_type_yields_no_typed_result(dialect, columns): - """A user-defined type has no value class to answer with. - - Offering JSON navigation on a type nobody here has heard of would be worse - than saying nothing, so the cast comes back untyped and the caller says what - they meant with ``as_*``. - """ - result = F.cast(dialect, columns["int"], CustomType(dialect, raw="GEOMETRY")) - assert not is_typed_as_one_of_these(result) - - -# --------------------------------------------------------------------------- -# Formatting and parsing -# --------------------------------------------------------------------------- - - -def test_to_char_gives_text(dialect, columns): - assert isinstance(F.to_char(dialect, columns["int"]), TextValue) - - -def test_to_number_gives_a_number(dialect, columns): - assert isinstance(F.to_number(dialect, columns["int"]), NumericValue) - - -def test_to_date_gives_a_date(dialect, columns): - """``TO_DATE`` answers with a **date**, not a timestamp. - - Every backend's ``TO_DATE`` produces a calendar date, so typing it as a - timestamp offered the time-of-day operations on a value that has no time of - day. Asserting the date here is what stops that coming back. - """ - node = F.to_date(dialect, columns["int"]) - assert isinstance(node, TemporalValue) - # A date and a date-time carry the same surface -- the operations are the - # same -- so "not a timestamp" is a statement about the node's class, which - # is where the distinction now lives. - assert type(node).__name__ == "ToDateFunction" - - -# --------------------------------------------------------------------------- -# Session identity is a name -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize("factory", ["current_user", "session_user", "system_user"]) -def test_the_session_identity_is_a_name(dialect, factory): - result = getattr(F, factory)(dialect) - # What makes it a *name* is the surface it carries, not the class it is: - # a node is its own class now, so the old ``isinstance(result, - # StringValue)`` would be asserting the wrapper this family no longer has. - # Text answers text operations and refuses numeric ones. - assert hasattr(result, "upper") - assert not hasattr(result, "sqrt") - - -# --------------------------------------------------------------------------- -# XML -# --------------------------------------------------------------------------- - - -def test_the_xml_document_nodes_are_xml_values(dialect): - """An XML constructor declares the XML value class, and nothing else. - - This used to assert the opposite -- that no class in the lattice covered - XML -- because the value family was a tag in a closed table and no tag - existed. The class is the statement now: every constructor that builds a - document derives from ``XMLValue``, so ``isinstance`` answers - from the object. What the class carries is the XML surface — the null - tests and casting, and no comparison (see the refusal test below). - """ - from rhosocial.activerecord.backend.expression import xml as X - - document_nodes = ( - X.XMLParseExpression, - X.XMLElementExpression, - X.XMLForestExpression, - X.XMLConcatExpression, - X.XMLCommentExpression, - X.XMLPIExpression, - X.XMLRootExpression, - X.XMLAggExpression, - X.XMLQueryExpression, - ) - other_families = tuple( - cls for cls in TYPED_VALUE_CLASSES if cls is not XMLValue - ) - for cls in document_nodes: - assert issubclass(cls, XMLValue), cls.__name__ - assert issubclass(cls, SQLValue), cls.__name__ - # It is an XML value and none of the other typed classes: a document - # is not text that can be upper-cased, not JSON to navigate, not a - # sequence to unnest. - assert not issubclass(cls, other_families), cls.__name__ - - -def test_xmlserialize_yields_the_character_value_it_names(dialect): - """Serialization leaves the XML family: the result is the text asked for. - - ``XMLSERIALIZE(... AS VARCHAR(100))`` answers with a character value, so - the node declares ``StringValue`` and the string operations - follow it out of the XML surface. - """ - from rhosocial.activerecord.backend.expression import xml as X - - assert issubclass(X.XMLSerializeExpression, TextValue) - serialized = F.xmlserialize(dialect, "", "VARCHAR(100)") - assert isinstance(serialized, TextValue) - assert not isinstance(serialized, XMLValue) - - -def test_xmlexists_is_a_predicate_not_a_value(): - """It answers a WHERE clause, so it has no value family to declare.""" - from rhosocial.activerecord.backend.expression import xml as X - from rhosocial.activerecord.backend.expression.bases import SQLPredicate - - assert issubclass(X.XMLExistsPredicate, SQLPredicate) - assert not issubclass(X.XMLExistsPredicate, XMLValue) - - -def test_a_cast_to_xml_is_an_xml_value(dialect, columns): - """The cast takes its type from the target: ``CAST(x AS XML)`` is XML.""" - result = F.cast(dialect, columns["str"], XmlType(dialect)) - assert isinstance(result, XMLValue) - assert not isinstance(result, TextValue) - - -def test_a_function_that_declares_no_result_can_say_xml(dialect): - """``as_xml()`` is how a caller states what a generic call yields. - - It returns an *annotation*: the XML surface, and nothing else. The text - surface is not merely unused here, it is gone -- which is the point of - stating the type, since ``.like()`` on an XML document is not a question any - backend answers. The SQL is untouched: only the declared type moved. - """ - from rhosocial.activerecord.backend.expression.declared import XMLAnnotation - - call = FunctionCall(dialect, "MYSTERY_FUNC") - typed = call.as_xml() - assert isinstance(typed, XMLAnnotation) - assert not hasattr(typed, "like") - assert typed.to_sql() == call.to_sql() - - -def test_an_xml_column_refuses_comparison_and_keeps_the_null_tests(dialect): - """The XML column surface, exactly as every XML backend defines it. - - PostgreSQL refuses ``xml = xml`` ("operator does not exist: xml = xml"), - SQL Server documents that the xml data type "cannot be compared or - sorted", and Oracle's ``XMLType`` has no comparison operators. Refusing - here names the operation at the call; without the declaration Python - would silently answer with identity equality. ``IS NULL`` is accepted by - all three, so the null tests stay. - """ - column = XMLColumn(dialect, "doc") - - for operation, dunder in [ - (lambda c: c == 1, "__eq__"), - (lambda c: c != 1, "__ne__"), - (lambda c: c < 1, "__lt__"), - (lambda c: c <= 1, "__le__"), - (lambda c: c > 1, "__gt__"), - (lambda c: c >= 1, "__ge__"), - ]: - with pytest.raises(AttributeError, match=dunder): - operation(column) - - assert "IS NULL" in column.is_null().to_sql()[0] - assert "IS NOT NULL" in column.is_not_null().to_sql()[0] - - -# --------------------------------------------------------------------------- -# Every family has a wrapper -# --------------------------------------------------------------------------- - - -def test_a_type_the_core_does_not_hold_is_reported_unknown(): - """The lattice is closed. An extension type a backend models fully is still - unknown here, because the core does not know which backends exist and cannot - say what such a type means for the operations its own results offer. - - Declaring one used to look like it worked -- the attribute was there, and - reading it gave the name back -- so nothing pinned the difference between a - type that is honoured and one that is quietly dropped. A tag could claim a - name the core held no class for; a class cannot, because the operations it - offers come with it. - """ - class ExtensionValue(SQLValue): - # A name on the class, which is what declaring a type used to mean. It - # confers nothing: nothing reads it, and annotation_for answers from the - # MRO, where this class appears under no mapped name. - declared_type = "network" - - instance = ExtensionValue.__new__(ExtensionValue) - assert ExtensionValue.declared_type == "network" - assert annotation_for(instance) is None - assert not is_typed_as_one_of_these(instance) - - -def test_every_typed_value_declares_a_family_from_the_lattice(): - """Each result class states its own family, and it has to be one the - lattice knows -- otherwise it offers operations nothing downstream expects. - - This replaced a test that every family but XML had a wrapper in a registry. - There is no registry now: a factory constructs the class it means, so there - is no table left to be complete. The family is named by the ``Value`` - suffix (规范 4.9), and the scan follows that suffix -- so a rename that - moves the family fails here rather than quietly emptying the set.""" - import inspect - - from rhosocial.activerecord.backend.expression import core - - declared = { - name: cls - for name, cls in inspect.getmembers(core, inspect.isclass) - if name.endswith("Value") and name != "SQLValue" - } - assert declared, "the typed values moved" - # Every typed value declares its type by being a class, so the only - # thing left to check is that each one is still reachable and distinct. - assert len(set(declared.values())) == len(declared), "two names bind one class" - - -def test_every_temporal_type_is_reachable(): - """The four temporal kinds exist and are distinct. - - They were one class with a label saying which it was, then four classes, and - now four members of :class:`LiteralKind` -- one closed vocabulary rather than - one class per type. This pins that a timestamp, a date, a time and an - interval are still told apart, because ``datetime`` is a subclass of ``date`` - and matching them in the wrong order would fold the first three together. - """ - - from rhosocial.activerecord.backend.expression.values import LiteralKind - - for name, sample in ( - ("TIMESTAMP", __import__("datetime").datetime(2026, 10, 18, 1, 2, 3)), - ("DATE", __import__("datetime").date(2026, 10, 18)), - ("TIME", __import__("datetime").time(1, 2, 3)), - ("INTERVAL", __import__("datetime").timedelta(days=1)), - ): - kind = LiteralKind[name] - assert LiteralKind.match(sample) is kind, name - assert kind.wire.endswith("_value"), name diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py deleted file mode 100644 index fd1ca495..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_boundaries.py +++ /dev/null @@ -1,390 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_operation_boundaries.py -"""The four string boundaries the 2026-10-09 ruling settled, plus the NULL-safe -comparison it added to the surface. - -``operation-groups-matrix.md`` section F records the measurement: what the ten -backends answer for a negative count, an empty pad, a position below 1 and a -multi-character trim set, and which answer -- if any -- is common ground. This -file pins the outcome. Edges every backend agrees on render; the rest are -refused at construction instead of rendered into whatever the dialect happens -to do. ``is_distinct_from`` is here too: its spelling varies by backend, so it -is a dialect hook with a gate, and the gate refuses rather than substitutes a -different question. So are the function version floors SQLite records: they -used to be answerable through ``supports_functions()`` and ignorable at render -time, and now rendering a call the dialect's version predates refuses. -""" - -import pytest - -from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError -from rhosocial.activerecord.backend.expression.column_types import NumericColumn, StringColumn -from rhosocial.activerecord.backend.expression.core import FunctionCall, Literal -from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect -from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - -@pytest.fixture -def sqlite_dialect(): - dialect = SQLiteDialect() - dialect.version = (3, 46, 1) - return dialect - - -@pytest.fixture -def name(sqlite_dialect): - return StringColumn(sqlite_dialect, "name") - - -@pytest.fixture -def portable_name(): - """A column on the portable baseline, where the common spellings render.""" - return StringColumn(DummyDialect(), "name") - - -REFUSALS = [ - ("left", (-1,)), - ("right", (-1,)), - ("lpad", (-1,)), - ("lpad", (5, "")), - ("rpad", (-1,)), - ("rpad", (5, "")), - ("substr", (0,)), - ("substr", (-2, 3)), - ("substr", (1, -1)), - ("trim", ("xy",)), - ("trim", ("",)), -] - - -@pytest.mark.parametrize( - "method,args", - [("left", (-1,)), ("right", (-1,)), ("lpad", (-1,)), ("lpad", (5, "")), - ("rpad", (-1,)), ("rpad", (5, "")), ("substr", (0,)), ("substr", (-2, 3)), - ("substr", (1, -1)), ("trim", ("xy",)), ("trim", ("",))], - ids=("left", "right", "lpad_negative", "lpad_empty_pad", - "rpad_negative", "rpad_empty_pad", "substr_start0", "substr_negative_start", - "substr_negative_length", "trim_two_chars", "trim_empty_set"), -) -def test_the_edge_where_the_backends_disagree_is_refused(name, method, args): - """No two backends answer these the same way, so the answer is a refusal - at construction rather than a silent coin flip at render time.""" - with pytest.raises(ValueError): - getattr(name, method)(*args) - - -@pytest.mark.parametrize( - "method,args,expected_sql,expected_params", - [ - ("left", (0,), 'LEFT("name", ?)', (0,)), - ("repeat", (0,), 'REPEAT("name", ?)', (0,)), - ("substr", (1, 0), 'SUBSTRING("name", ?, ?)', (1, 0)), - ], -) -def test_the_edge_every_backend_agrees_on_renders(portable_name, method, args, expected_sql, expected_params): - """The inside of the contract: zero-length results, the empty substring, - the whole-string over-length read and a one-character trim set behave the - same on every backend, so they render. Asserted on the portable baseline - because what is under test is the core spelling, not a dialect's.""" - sql, params = getattr(portable_name, method)(*args).to_sql() - assert sql == expected_sql - assert params == expected_params - - -@pytest.mark.parametrize( - "direction,expected_sql,expected_params", - [ - ("BOTH", 'TRIM("name", ?)', ("x",)), - ("LEADING", 'LTRIM("name", ?)', ("x",)), - ("TRAILING", 'RTRIM("name", ?)', ("x",)), - ], -) -def test_sqlite_spells_trim_as_its_function_form(direction, expected_sql, expected_params): - """SQLite parses no ``trim( from )`` syntax, so the node - renders as the function form there. Same node, dialect-chosen spelling -- - which is why the factory builds a TrimExpression and not a SQL string.""" - dialect = SQLiteDialect() - dialect.version = (3, 46, 1) - column = StringColumn(dialect, "name") - sql, params = column.trim("x", direction).to_sql() - assert sql == expected_sql - assert params == expected_params - - -def test_the_default_spelling_is_the_standard_form(): - """A dialect that speaks the standard form renders it, unchanged from what - the raw SQL used to produce.""" - column = StringColumn(DummyDialect(), "name") - assert column.trim().to_sql() == ('TRIM(BOTH FROM "name")', ()) - assert column.trim("x").to_sql() == ('TRIM(BOTH ? FROM "name")', ("x",)) - - -def test_lpad_defaults_to_a_space_and_passes_it_explicitly(portable_name): - """MySQL raises 1582 without a pad and MariaDB supplies one, so the core - always spells it out instead of letting the backend choose.""" - sql, params = portable_name.lpad(3).to_sql() - assert sql == 'LPAD("name", ?, ?)' - assert params == (3, " ") - - -def test_a_negative_repeat_is_the_empty_string(name): - """PostgreSQL, MySQL, MariaDB and ClickHouse all answer ``''`` for a - negative count; SQL Server answers NULL and Oracle, Firebird and SQLite - lack the function, so the core answers once instead of four times.""" - expr = name.repeat(-1) - assert "REPEAT" not in expr.to_sql()[0] - assert expr.to_sql() == ("?", ("",)) - - -def test_is_distinct_from_renders_the_null_safe_comparison(): - """The default rendering is the standard spelling; backends that spell it - differently override the hook instead of every call site writing dialect - SQL.""" - column = StringColumn(DummyDialect(), "age") - assert column.is_distinct_from(0).to_sql() == ('"age" IS DISTINCT FROM ?', (0,)) - assert column.is_not_distinct_from(0).to_sql() == ('"age" IS NOT DISTINCT FROM ?', (0,)) - - -@pytest.mark.parametrize("version,expected", [((3, 39, 0), True), ((3, 38, 0), False)]) -def test_sqlite_gates_the_spelling_on_its_version(version, expected): - dialect = SQLiteDialect() - dialect.version = version - assert dialect.supports_distinct_from() is expected - - -def test_sqlite_below_the_gate_refuses_rather_than_substituting(): - dialect = SQLiteDialect() - dialect.version = (3, 38, 0) - column = StringColumn(dialect, "age") - with pytest.raises(UnsupportedFeatureError): - column.is_distinct_from(0).to_sql() - - -# --------------------------------------------------------------------------- -# A recorded function version floor is a gate, not a footnote -# --------------------------------------------------------------------------- - - -SQLITE_FUNCTION_FLOORS = [ - ("iif", (3, 32, 0)), - ("pow", (3, 35, 0)), - # json_extract is deliberately absent: the JSON1 functions predate their - # 3.38.0 promotion into core (they exist since 3.9.0 behind a compile-time - # option), so availability depends on how SQLite was built, not on the - # version -- CI's own 3.35.0 server executes json_extract. A recorded floor - # there would refuse SQL the server accepts. - ("unhex", (3, 45, 0)), - ("json_array_insert", (3, 53, 0)), - ("jsonb_array_insert", (3, 53, 0)), -] - - -def _gated_call(dialect, func_name): - """One call to *func_name*, as the renderer meets it: the name the caller - handed over, spelled upper-case in the SQL.""" - return FunctionCall(dialect, func_name, Literal(dialect, "x")) - - -def _one_patch_below(floor): - """The release before *floor*: same major and minor, one patch short.""" - return (floor[0], floor[1], floor[2] - 1) - - -@pytest.mark.parametrize( - "func_name,floor", - SQLITE_FUNCTION_FLOORS, - ids=[func_name for func_name, _floor in SQLITE_FUNCTION_FLOORS], -) -def test_a_floor_the_dialect_is_below_refuses_instead_of_rendering(func_name, floor): - """SQLite records when each function arrived. Rendering one anyway emits - SQL this SQLite will reject, so the floor is a refusal at render time - rather than an observation in a table nobody reads.""" - dialect = SQLiteDialect() - dialect.version = _one_patch_below(floor) - with pytest.raises(UnsupportedFeatureError): - _gated_call(dialect, func_name).to_sql() - - -@pytest.mark.parametrize( - "func_name,floor", - SQLITE_FUNCTION_FLOORS, - ids=[func_name for func_name, _floor in SQLITE_FUNCTION_FLOORS], -) -def test_a_floor_the_dialect_meets_renders(func_name, floor): - """The gate is a floor, not a ban: at the recorded version the same call - renders exactly as it does on a newer one -- the version changes what is - refused, never what is spelled.""" - dialect = SQLiteDialect() - dialect.version = floor - assert _gated_call(dialect, func_name).to_sql() == (f"{func_name.upper()}(?)", ("x",)) - - -def test_the_refusal_names_the_function_the_floor_and_the_version(): - """A refusal the caller cannot act on is only a different way of failing, - so the message says which function, which version it arrived in and which - one is in force: the choice is between a newer server and another - spelling.""" - dialect = SQLiteDialect() - dialect.version = (3, 52, 0) - call = FunctionCall( - dialect, - "json_array_insert", - Literal(dialect, "[]"), - Literal(dialect, "$[0]"), - Literal(dialect, 1), - ) - with pytest.raises(UnsupportedFeatureError) as excinfo: - call.to_sql() - message = str(excinfo.value) - assert "JSON_ARRAY_INSERT" in message - assert "3.53.0" in message - assert "3.52.0" in message - - -def test_the_query_surface_and_the_gate_answer_the_same_thing(): - """``supports_functions`` keeps its shape and stays the query surface; what - changed is that a False in it is no longer advisory. Below the floor both - answer no, at it both answer yes.""" - for version, expected in ((3, 52, 0), False), ((3, 53, 0), True): - dialect = SQLiteDialect() - dialect.version = version - assert dialect.supports_functions()["json_array_insert"] is expected - call = _gated_call(dialect, "json_array_insert") - if expected: - assert call.to_sql() == ("JSON_ARRAY_INSERT(?)", ("x",)) - else: - with pytest.raises(UnsupportedFeatureError): - call.to_sql() - - -def test_a_name_no_floor_is_recorded_for_renders_on_the_oldest_dialect(): - """No floor is not a floor of zero. A name nobody has measured is not - gated here, so it renders on a dialect that predates every gate in the - table -- the gate only ever refuses what a backend declared.""" - dialect = SQLiteDialect() - dialect.version = (3, 8, 0) - assert dialect.function_version_floor("lower") is None - column = StringColumn(dialect, "name") - assert column.lower().to_sql() == ('LOWER("name")', ()) - assert dialect.function_version_floor("pow") == (3, 35, 0) - - -# --------------------------------------------------------------------------- -# The per-dialect spellings, and the emulations behind them -# --------------------------------------------------------------------------- - - -SQLITE_SPELLINGS = [ - ("left", (2,), 'SUBSTR("name", ?, ?)', (1, 2)), - ("right", (2,), 'SUBSTR("name", MAX(LENGTH("name") - ? + ?, ?), ?)', (2, 1, 1, 2)), - ( - "lpad", - (4, "xy"), - 'CASE WHEN ? <= LENGTH("name") THEN SUBSTR("name", ?, ?) ' - 'ELSE SUBSTR(REPLACE(HEX(ZEROBLOB(?)), ?, ?) || "name", - ?) END', - (4, 1, 4, 4, "00", "xy", 4), - ), - ( - "rpad", - (4, "-"), - 'SUBSTR("name" || REPLACE(HEX(ZEROBLOB(?)), ?, ?), ?, ?)', - (4, "00", "-", 1, 4), - ), - ("repeat", (3,), 'REPLACE(HEX(ZEROBLOB(?)), ?, "name")', (3, "00")), - ("ascii", (), 'UNICODE("name")', ()), - ("strpos", ("cd",), 'INSTR("name", ?)', ("cd",)), - ("position", ("cd",), 'INSTR("name", ?)', ("cd",)), -] - - -@pytest.mark.parametrize("method,args,expected_sql,expected_params", SQLITE_SPELLINGS) -def test_sqlite_spells_what_it_lacks(sqlite_dialect, method, args, expected_sql, expected_params): - """SQLite has none of these functions and no ``trim(... from ...)`` syntax, - so each is either renamed, reordered, or emulated out of ordinary nodes -- - measured 2026-10-09 and verified against a real database below. Nothing - here is assembled as a SQL string.""" - column = StringColumn(sqlite_dialect, "name") - sql, params = getattr(column, method)(*args).to_sql() - assert sql == expected_sql - assert params == expected_params - - -def test_sqlite_truncates_with_arithmetic_because_trunc_takes_one_argument(sqlite_dialect): - """SQLite's ``TRUNC`` is unary, so a precision is carried by scaling, - truncating toward zero, and scaling back -- exact for negatives, which - rounding would not be.""" - column = NumericColumn(sqlite_dialect, "n") - sql, params = column.truncate(2).to_sql() - assert sql == 'TRUNC("n" * POW(?, ?)) / POW(?, ?)' - assert params == (10, 2, 10, 2) - assert column.truncate().to_sql() == ('TRUNC("n")', ()) - - -def test_sqlite_takes_the_log_base_first(sqlite_dialect): - """SQLite spells ``log(base, x)`` where the core order is ``log(x, base)``; - the one-argument form is the natural logarithm on both.""" - column = NumericColumn(sqlite_dialect, "n") - assert column.log(10).to_sql() == ("LOG(?, \"n\")", (10,)) - assert column.log().to_sql() == ('LOG("n")', ()) - - -STRING_ROUNDTRIPS = [ - ("left(2)", lambda c: c.left(2), "abcdef", "ab"), - ("left(0)", lambda c: c.left(0), "abcdef", ""), - ("left(99)", lambda c: c.left(99), "abcdef", "abcdef"), - ("right(2)", lambda c: c.right(2), "abcdef", "ef"), - ("right(0)", lambda c: c.right(0), "abcdef", ""), - ("right(99)", lambda c: c.right(99), "abcdef", "abcdef"), - ("lpad(8, 'xy')", lambda c: c.lpad(8, "xy"), "abcdef", "xyabcdef"), - ("lpad(3, 'xy')", lambda c: c.lpad(3, "xy"), "abcdef", "abc"), - ("lpad(4)", lambda c: c.lpad(4), "ab", " ab"), - ("rpad(8, '-')", lambda c: c.rpad(8, "-"), "abcdef", "abcdef--"), - ("rpad(3, '-')", lambda c: c.rpad(3, "-"), "abcdef", "abc"), - ("repeat(3)", lambda c: c.repeat(3), "ab", "ababab"), - ("repeat(0)", lambda c: c.repeat(0), "ab", ""), - ("trim('f')", lambda c: c.trim("f"), "abcdef", "abcde"), - ("trim()", lambda c: c.trim(), " abc ", "abc"), -] - -NUMERIC_ROUNDTRIPS = [ - ("truncate(2)", lambda c: c.truncate(2), 3.14159, 3.14), - ("truncate(2) negative", lambda c: c.truncate(2), -3.14159, -3.14), - ("truncate(0)", lambda c: c.truncate(0), 3.7, 3.0), - ("truncate()", lambda c: c.truncate(), -3.7, -3.0), -] - - -@pytest.mark.parametrize( - "label,build,value,expected", - STRING_ROUNDTRIPS, - ids=[label for label, _build, _value, _expected in STRING_ROUNDTRIPS], -) -def test_the_sqlite_emulation_answers_what_the_function_answers(sqlite_dialect, label, build, value, expected): - """The spelling checks above prove the SQL is *shaped* right; this proves it - *means* right -- each expression is executed against a real SQLite and must - produce the answer PostgreSQL, MySQL and ClickHouse give for the same call. - A spelling that looks correct and answers something else is the failure this - test exists for.""" - import sqlite3 - - connection = sqlite3.connect(":memory:") - connection.execute("CREATE TABLE t (s TEXT)") - connection.execute("INSERT INTO t VALUES (?)", (value,)) - column = StringColumn(sqlite_dialect, "s") - sql, params = build(column).to_sql() - got = connection.execute(f"SELECT {sql} FROM t", tuple(params)).fetchone()[0] - assert got == expected, f"{label}: SQLite answered {got!r}, the function answers {expected!r}" - - -@pytest.mark.parametrize("label,build,value,expected", NUMERIC_ROUNDTRIPS) -def test_the_sqlite_numeric_emulation_answers_what_the_function_answers( - sqlite_dialect, label, build, value, expected -): - import sqlite3 - - connection = sqlite3.connect(":memory:") - connection.execute("CREATE TABLE t (n REAL)") - connection.execute("INSERT INTO t VALUES (?)", (value,)) - column = NumericColumn(sqlite_dialect, "n") - sql, params = build(column).to_sql() - got = connection.execute(f"SELECT {sql} FROM t", tuple(params)).fetchone()[0] - assert got == expected, f"{label}: SQLite answered {got!r}, the function answers {expected!r}" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py deleted file mode 100644 index 66fab5dd..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_operation_symmetry.py +++ /dev/null @@ -1,113 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_operation_symmetry.py -"""Same-family column and value classes must offer the same operations. - -The P1 unification says a family is one thing on both sides: the class a -``Model.c.`` builds (a column) and the class an operation result builds -(a value) attach the same operation groups, so a value that came out of an -expression can be used exactly like the column it came from. Drift between the -two sides is invisible until a caller hits it -- ``name.length()`` returning a -number that lost an operation the string column still has, say -- so the sets -are asserted equal here. - -Definition of the compared set: - -* public callables plus the operator dunders (``__add__`` ... ``__and__``); -* minus the names provided by :class:`NotANumberMixin`. The refusal set is a - separate axis -- it answers "is this family a number", and whether a side - declares the refusal or merely lacks the operator is pinned where it - belongs (the family's own tests). Comparing the *offered* operations is - what "same family, same groups" means. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_operation_symmetry.py -import pytest - -from rhosocial.activerecord.backend.expression import ( - ArrayColumn, - BinaryColumn, - BooleanColumn, - TimestampColumn, - IntegerColumn, - JSONColumn, - NumericColumn, - StringColumn, - UUIDColumn, - XMLColumn, -) -from rhosocial.activerecord.backend.expression.declared import ( - ArrayAnnotation, - BinaryAnnotation, - BooleanAnnotation, - IntegerAnnotation, - JSONAnnotation, - NumberAnnotation, - TextAnnotation, - TemporalAnnotation, - UUIDAnnotation, - XMLAnnotation, -) -from rhosocial.activerecord.backend.expression.mixins import NotANumberMixin - -OPERATORS = { - "__add__", - "__sub__", - "__mul__", - "__truediv__", - "__mod__", - "__and__", - "__or__", - "__invert__", - "__eq__", - "__ne__", - "__lt__", - "__le__", - "__gt__", - "__ge__", -} - -_REFUSALS = {name for name, value in vars(NotANumberMixin).items() if callable(value)} - -#: Not operations on a value, so not part of what "the same operations" means. -#: ``collate`` and ``validate`` are a column's storage; ``get_params`` belongs to -#: the artifact rather than to the type; ``surface`` is the declaration of -#: which operations a node carries, which is the thing being compared here and so -#: cannot also be one of the things compared; and ``kind`` is a node's identity -#: on the wire (§4.9.2) -- defined once on the expression base, which an -#: annotation is not. -_NOT_OPERATIONS = {"collate", "validate", "get_params", "value_type_of", "kind"} - - -def _operations(cls): - """The operation names *cls* offers: public callables + operator dunders.""" - names = set() - for name in dir(cls): - if name.startswith("_") and name not in OPERATORS: - continue - if callable(getattr(cls, name, None)): - names.add(name) - return names - _REFUSALS - _NOT_OPERATIONS - - -FAMILIES = [ - (StringColumn, TextAnnotation), - (NumericColumn, NumberAnnotation), - (IntegerColumn, IntegerAnnotation), - (BooleanColumn, BooleanAnnotation), - (TimestampColumn, TemporalAnnotation), - (BinaryColumn, BinaryAnnotation), - (UUIDColumn, UUIDAnnotation), - (JSONColumn, JSONAnnotation), - (ArrayColumn, ArrayAnnotation), - (XMLColumn, XMLAnnotation), -] - - -@pytest.mark.parametrize("column_class, value_class", FAMILIES, ids=lambda c: c.__name__) -def test_the_two_sides_of_a_family_offer_the_same_operations(column_class, value_class): - column_ops = _operations(column_class) - value_ops = _operations(value_class) - assert column_ops == value_ops, ( - f"{column_class.__name__} and {value_class.__name__} drifted apart:\n" - f" only on the column: {sorted(column_ops - value_ops)}\n" - f" only on the value: {sorted(value_ops - column_ops)}" - ) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py deleted file mode 100644 index 23449d00..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_predicate_alias.py +++ /dev/null @@ -1,166 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_predicate_alias.py -"""Predicates must be able to carry an alias. - -A predicate is not confined to a WHERE clause. ``LIKE`` and its relatives also -appear in a SELECT list, inside ``CASE WHEN``, in a ``JOIN ... ON`` condition, -and in DDL as a ``CHECK`` constraint or a partial-index predicate. In the -projection case the boolean is a column like any other and needs a name. - -None of the predicate formatters honoured an alias, and ``SQLPredicate`` did -not even offer ``as_()``, so an aliased predicate silently rendered a bare -boolean — or could not be aliased at all. These tests pin the behaviour for -every predicate family, and pin the equally important inverse: no alias means -no ``AS`` in the output. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_predicate_alias.py -import pytest - -from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect -from rhosocial.activerecord.backend.expression import Column, Literal, NumericColumn, StringColumn -from rhosocial.activerecord.backend.expression.predicates import ( - IsBooleanPredicate, - IsNullPredicate, -) - - -@pytest.fixture -def dialect(): - d = SQLiteDialect() - d._version = (3, 46, 1) - return d - - -@pytest.fixture -def name(dialect): - # Typed: the families below are exercised through the capability mixins - # (``LIKE`` / ``ILIKE``), which live on the typed classes only. - return StringColumn(dialect, "name", table="t") - - -@pytest.fixture -def qty(dialect): - return NumericColumn(dialect, "qty", table="t") - - -def ident(dialect, alias): - return dialect.format_identifier(alias) - - -# --------------------------------------------------------------------------- -# Every predicate family honours the alias -# --------------------------------------------------------------------------- - - -def _families(dialect, name, qty): - """One aliased predicate per family, keyed by name.""" - return { - "comparison": (name == Literal(dialect, "x")).as_("a"), - "like": name.like("a%").as_("a"), - "ilike": name.ilike("a%").as_("a"), - "logical_and": ((name == Literal(dialect, "x")) & (qty > Literal(dialect, 0))).as_("a"), - "logical_or": ((name == Literal(dialect, "x")) | (qty > Literal(dialect, 0))).as_("a"), - "not": (~(name == Literal(dialect, "x"))).as_("a"), - "in": name.in_([1, 2]).as_("a"), - "between": name.between(Literal(dialect, "a"), Literal(dialect, "z")).as_("a"), - "is_null": IsNullPredicate(dialect, name).as_("a"), - "is_boolean": IsBooleanPredicate(dialect, name, True).as_("a"), - } - - -@pytest.mark.parametrize( - "family", - [ - "comparison", - "like", - "ilike", - "logical_and", - "logical_or", - "not", - "in", - "between", - "is_null", - "is_boolean", - ], -) -def test_predicate_alias_reaches_the_sql(dialect, name, qty, family): - """The alias must appear in the rendered statement.""" - expr = _families(dialect, name, qty)[family] - sql, _ = expr.to_sql() - assert sql.endswith(f"AS {ident(dialect, 'a')}") - assert sql.count("AS ") == 1, f"alias applied more than once: {sql!r}" - - -@pytest.mark.parametrize( - "family", - [ - "comparison", - "like", - "ilike", - "logical_and", - "logical_or", - "not", - "in", - "between", - "is_null", - "is_boolean", - ], -) -def test_unaliased_predicate_has_no_as_clause(dialect, name, qty, family): - """The inverse: no alias must not introduce a stray ``AS``. - - A formatter that appended an empty ``AS`` would be just as broken as one - that dropped the alias, and the regression is invisible unless it is - pinned separately. - """ - expr = _families(dialect, name, qty)[family] - expr = type(expr).as_(expr, expr.alias) - expr.alias = None - sql, _ = expr.to_sql() - assert " AS " not in sql, f"unexpected AS without an alias: {sql!r}" - - -# --------------------------------------------------------------------------- -# The reason this matters: a predicate used as a projected column -# --------------------------------------------------------------------------- - - -def test_projected_predicate_is_named_like_a_column(dialect, name): - """``SELECT name LIKE 'a%' AS is_apple`` is the motivating case.""" - sql, params = name.like("a%").as_("is_apple").to_sql() - assert sql == f'"t"."name" LIKE {dialect.get_parameter_placeholder()} AS {ident(dialect, "is_apple")}' - assert params == ("a%",) - - -def test_alias_works_for_a_bare_column_too(dialect): - """The base behaviour must be unchanged by the predicate change. - - Deliberately a bare ``Column``: the ``name`` fixture is typed now, and this - case is specifically about the untyped reference still aliasing. - """ - sql, _ = Column(dialect, "name", table="t").as_("n").to_sql() - assert sql == f'"t"."name" AS {ident(dialect, "n")}' - - -# --------------------------------------------------------------------------- -# Empty value list: a branch of the IN formatter with its own return -# --------------------------------------------------------------------------- - - -def test_empty_in_list_keeps_its_alias(dialect, name): - """``IN ()`` is a separate return path in the IN formatter.""" - sql, params = name.in_([]).as_("none").to_sql() - assert sql.endswith(f"AS {ident(dialect, 'none')}") - assert params == () - - -# --------------------------------------------------------------------------- -# Parameters are unaffected by aliasing -# --------------------------------------------------------------------------- - - -def test_aliasing_preserves_parameters(dialect, name, qty): - """The alias is pure SQL decoration; bind order must not shift.""" - expr = (name.like("a%") & (qty > Literal(dialect, 5))).as_("both") - _, params = expr.to_sql() - assert params == ("a%", 5) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py deleted file mode 100644 index 0639f1ef..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_concatenation_operator.py +++ /dev/null @@ -1,164 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_concatenation_operator.py -"""``||`` is concatenation in SQL and logical OR in several backends. - -PostgreSQL, Oracle, Snowflake, Firebird and ClickHouse read ``||`` as string -concatenation. MySQL and MariaDB read it as logical OR unless the server runs -with ``PIPES_AS_CONCAT``, and SQL Server reads it as logical OR outright. -Emitting the bare token on those backends returns a boolean where a string was -meant — a wrong answer rather than a syntax error, which is why it can survive -a test suite. - -So the node records the *intent* and the dialect picks the spelling. These -tests pin the contract: the intent survives the round trip, the default is the -standard operator, and a dialect that declares a function gets one. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_concatenation_operator.py -import pytest - -from rhosocial.activerecord.backend.expression import StringColumn -from rhosocial.activerecord.backend.expression import functions as string_functions -from rhosocial.activerecord.backend.expression.operators import ( - BinaryExpression, - ConcatenationOperation, -) - - -@pytest.fixture -def dialect(): - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - d = SQLiteDialect() - d._version = (3, 46, 1) - return d - - -@pytest.fixture -def operands(dialect): - """Two string columns. - - StringColumn rather than Column: the point of the round trip is that the - result is still a string, and a bare Column carries no string surface to - lose. - """ - return ( - StringColumn(dialect, "a", table="t"), - StringColumn(dialect, "b", table="t"), - ) - - -# --------------------------------------------------------------------------- -# The node carries intent, not an operator -# --------------------------------------------------------------------------- - - -def test_concat_op_builds_an_intent_node(dialect, operands): - left, right = operands - expr = string_functions.concat_op(dialect, left, right) - assert isinstance(expr, ConcatenationOperation) - - -def test_the_intent_node_is_not_a_bare_binary_expression(dialect, operands): - """The node is its own kind, not a BinaryExpression with a token. - - A bare BinaryExpression with op ``||`` says nothing about intent, which is - exactly why concat_op stopped producing one. - """ - left, right = operands - expr = string_functions.concat_op(dialect, left, right) - assert not isinstance(expr, BinaryExpression) - assert expr.left is left and expr.right is right - - -def test_the_operator_is_not_a_parameter(dialect, operands): - """Concatenation carries no ``op``: the kind is the intent. - - ``left`` and ``right`` are the node's only construction parameters, so - nothing about the operator token travels in the artifact. - """ - left, right = operands - expr = ConcatenationOperation(dialect, left, right) - assert not hasattr(expr, "op") - assert set(expr.get_params()) == {"left", "right"} - - -# --------------------------------------------------------------------------- -# The default spelling -# --------------------------------------------------------------------------- - - -def test_default_dialect_uses_the_standard_operator(dialect, operands): - """SQLite and PostgreSQL both read ``||`` as concatenation.""" - left, right = operands - assert dialect.string_concatenation_function() is None - assert string_functions.concat_op(dialect, left, right).to_sql()[ - 0 - ] == '"t"."a" || "t"."b"' - - -def test_a_declared_function_replaces_the_operator(dialect, operands): - """The declaration is consulted, so the same node renders differently.""" - left, right = operands - dialect.STRING_CONCATENATION = "CONCAT" - assert dialect.string_concatenation_function() == "CONCAT" - assert string_functions.concat_op(dialect, left, right).to_sql()[0] == ( - 'CONCAT("t"."a", "t"."b")' - ) - - -def test_declaration_must_be_a_string(dialect): - """A non-string declaration is ignored rather than interpolated.""" - dialect.STRING_CONCATENATION = None - assert dialect.string_concatenation_function() is None - dialect.STRING_CONCATENATION = 42 - assert dialect.string_concatenation_function() is None - - -# --------------------------------------------------------------------------- -# Chaining: the result is a string -# --------------------------------------------------------------------------- - - -def test_result_keeps_the_string_value_surface(operands): - left, _ = operands - result = left.concat_using_operator("x") - for method in ("upper", "substr", "like", "trim", "concat_using_operator"): - assert hasattr(result, method), f"concatenation lost {method}" - - -def test_chaining_after_concatenation(operands): - left, right = operands - sql, _ = left.concat_using_operator(right).upper().to_sql() - assert "UPPER" in sql - assert "||" in sql or "CONCAT" in sql - - -def test_alias_reaches_the_sql(operands): - left, right = operands - sql, _ = left.concat_using_operator(right).as_("joined").to_sql() - assert " AS " in sql - - -def test_no_alias_means_no_as(operands): - left, right = operands - sql, _ = left.concat_using_operator(right).to_sql() - assert " AS " not in sql - - -def test_parameters_are_preserved(operands): - left, right = operands - _, params = left.concat_using_operator(right).to_sql() - assert params == () - - -# --------------------------------------------------------------------------- -# concat_op is not the path for logical OR -# --------------------------------------------------------------------------- - - -def test_logical_or_does_not_go_through_concatenation(operands): - """OR has its own node and formatter, so the two never meet.""" - left, _ = operands - predicate = left.like("a%") | left.like("b%") - assert not isinstance(predicate, ConcatenationOperation) - assert " OR " in predicate.to_sql()[0] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py deleted file mode 100644 index 54a9347a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_string_value_operations.py +++ /dev/null @@ -1,209 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_value_operations.py -"""String value operations belong on the string column, and chain. - -``StringMixin`` used to hold exactly two methods, ``like`` and ``ilike``, and -both returned a predicate. A class named ``StringColumn`` therefore offered no -string operations at all — only the ability to be LIKE-matched — while the 26 -string functions that did exist sat unused in ``functions/string.py``. - -The split this file pins: - -- :class:`StringValueMixin` derives new strings and chains. -- :class:`StringPatternPredicateMixin` answers questions and ends the chain. -- Numeric results stay off the string surface, because ``LENGTH(x) LIKE '3'`` - is a type error in every backend. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_string_value_operations.py -import pytest - -from rhosocial.activerecord.backend.expression.value_types import TextValue - -from rhosocial.activerecord.backend.expression import ( - LikePredicate, - UpperFunction, - build_json_path, -) -from rhosocial.activerecord.backend.expression import functions as string_functions - -from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column - - -@pytest.fixture -def dialect(): - # The portable baseline dialect, not SQLite: what this file pins is the - # *core* layer -- each operation reaches its factory and the result is a - # typed string. Which spelling a given backend then writes is a per-dialect - # question and lives in test_operation_boundaries.py, where SQLite's - # INSTR/SUBSTR/TRUNC and its pad and repeat emulations are checked against - # a real database. - from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect - - return DummyDialect() - - -@pytest.fixture -def name(dialect): - return build_column(dialect, "name", str) - - -# --------------------------------------------------------------------------- -# The string surface exists and derives -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "method, args, expected_function", - [ - ("upper", (), "UPPER"), - ("lower", (), "LOWER"), - ("initcap", (), "INITCAP"), - ("reverse", (), "REVERSE"), - ("left", (2,), "LEFT"), - ("right", (2,), "RIGHT"), - ("lpad", (5,), "LPAD"), - ("rpad", (5,), "RPAD"), - ("repeat", (2,), "REPEAT"), - ("trim", (), "TRIM"), - ("substr", (1, 3), "SUBSTRING"), - ("replace", ("a", "b"), "REPLACE"), - ("translate", ("ab", "cd"), "TRANSLATE"), - ("overlay", ("x", 2), "OVERLAY"), - ], - ids=lambda v: v if isinstance(v, str) else "", -) -def test_string_operation_renders_its_function( - name, method, args, expected_function -): - """Each operation must reach the factory that already existed.""" - result = getattr(name, method)(*args) - sql, _ = result.to_sql() - assert expected_function in sql - - -def test_string_operations_return_a_typed_string_value(name): - """The result must be a string-valued node, not a bare function call.""" - assert isinstance(name.upper(), UpperFunction) - - -# --------------------------------------------------------------------------- -# Chaining — the reason the result is typed -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "build, expected_functions", - [ - (lambda c: c.upper(), ["UPPER"]), - (lambda c: c.upper().substr(1, 3), ["UPPER", "SUBSTRING"]), - (lambda c: c.upper().left(2).lower(), ["UPPER", "LEFT", "LOWER"]), - (lambda c: c.trim().replace("a", "b"), ["TRIM", "REPLACE"]), - (lambda c: c.substr(1, 2).upper().lower(), ["SUBSTRING", "UPPER", "LOWER"]), - ], - ids=["one", "two", "three", "trim-replace", "substr-upper-lower"], -) -def test_string_operations_chain(name, build, expected_functions): - """A derived string is still a string, so the next operation exists.""" - sql, _ = build(name).to_sql() - for function in expected_functions: - assert function in sql, f"{function} missing from {sql!r}" - - -def test_chained_result_keeps_the_whole_string_surface(name): - """Three levels deep, the value operations are all still available.""" - result = name.upper().left(2).lower() - for method in ("upper", "lower", "substr", "trim", "concat", "replace"): - assert hasattr(result, method), f"chain lost {method}" - - -def test_chained_result_keeps_the_pattern_predicates(name): - """String-ness is what makes LIKE legal on the result.""" - result = name.upper().left(2) - sql, _ = result.like("A%").to_sql() - assert "LIKE" in sql - assert "UPPER" in sql - - -# --------------------------------------------------------------------------- -# Crossing into the predicate domain ends the value chain -# --------------------------------------------------------------------------- - - -def test_pattern_predicate_terminates_the_chain(name): - """A predicate is a boolean; it never becomes a string again.""" - predicate = name.upper().like("A%") - assert isinstance(predicate, LikePredicate) - for method in ("upper", "substr", "trim", "concat"): - assert not hasattr(predicate, method), ( - f"predicate wrongly offers {method}; the value chain should have ended" - ) - - -def test_predicate_still_combines(name): - """Ending the value chain does not end the predicate chain.""" - combined = (name.like("A%") | name.like("B%")) & name.ilike("%x%") - sql, _ = combined.to_sql() - assert " OR " in sql and " AND " in sql - - -# --------------------------------------------------------------------------- -# Numeric results are not on the string surface -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "factory", ["length", "ascii", "octet_length", "bit_length"] -) -def test_numeric_result_is_not_a_string_value(dialect, name, factory): - """``LENGTH(x) LIKE '3'`` is a type error; the surface must not offer it.""" - result = getattr(string_functions, factory)(dialect, name) - assert not isinstance(result, TextValue) - - -@pytest.mark.parametrize( - "method, args", - [("length", ()), ("ascii", ()), ("strpos", ("x",)), ("position", ("x",))], -) -def test_string_column_offers_them_but_the_result_is_not_a_string(name, method, args): - """A legal string operation whose *result* is a number. - - ``LENGTH(s) LIKE '3'`` is still a type error, but it is caught by the - result's type rather than by hiding the method. Hiding it would be wrong: - these are well-defined on every backend, and ``strpos`` and ``position`` - differ in availability, so "does a string offer it" is not the same - question as "is the answer a string". - """ - assert hasattr(name, method), f"StringColumn lost a legal operation {method}()" - result = getattr(name, method)(*args) - assert not isinstance(result, TextValue) - - -# --------------------------------------------------------------------------- -# Existing behaviour is preserved -# --------------------------------------------------------------------------- - - -def test_free_functions_still_work_and_are_now_typed(dialect, name): - """Existing call sites keep working; they gain a string-valued node.""" - result = string_functions.upper(dialect, name) - assert isinstance(result, UpperFunction) - assert result.like("A%").to_sql()[0].endswith("LIKE ?") - - -def test_concat_includes_the_receiver(dialect, name): - """A variadic factory must receive the column as an operand. - - Passing the operand list as a single argument would bind the whole list to - one placeholder, which is what an earlier version of the mixin did. - """ - other = build_column(dialect, "other", str) - sql, params = name.concat(other, "x").to_sql() - assert sql.count("?") == 1 - assert params == ("x",) - assert '"other"' in sql - - -def test_json_path_builder_is_untouched(): - """The integer-index rule is a separate concern and must not regress.""" - assert build_json_path("tags", 0) == "$.tags[0]" - assert build_json_path("tags", "0") == "$.tags.0" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py deleted file mode 100644 index 19c9fd95..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py +++ /dev/null @@ -1,200 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/core/test_surface_only_column_types.py -"""The seven surface-only column classes and the tables that answer them. - -These families have no operation the framework can promise on every backend -- -see ``value_types.SurfaceOnlyValue`` for the evidence -- so their column -classes take ``ColumnBase`` alone. This file checks the three things that -follows from: - -1. each class exists, is concrete, and builds a column that renders; -2. it offers the column surface (alias, null tests, casting) and no family - operation, in particular no comparison; -3. every dialect table that names it -- SQLite and the dummy baseline -- stays - complete (all twenty-four entries) and answers nothing with ``None``. -""" - -import datetime -import inspect - -import pytest - -from rhosocial.activerecord.backend.adapters import ( - BitString, - Geometry, - MacAddress, - Multirange, - Range, - Vector, -) -from rhosocial.activerecord.backend.dialect.mixins import ColumnTypeMixin -from rhosocial.activerecord.backend.expression import ( - BitStringColumn, - ColumnBase, - GeometryColumn, - IntervalColumn, - MacAddressColumn, - MultirangeColumn, - RangeColumn, - VectorColumn, -) -from rhosocial.activerecord.backend.expression.column_types import annotation_for -from rhosocial.activerecord.backend.expression.declared import SurfaceOnlyAnnotation -from rhosocial.activerecord.backend.expression.mixins import ComparisonMixin -from rhosocial.activerecord.backend.expression.value_types import SurfaceOnlyValue -from rhosocial.activerecord.backend.impl.dummy.column_type import DUMMY_COLUMN_TYPES -from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect -from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect -from rhosocial.activerecord.backend.impl.sqlite.mixins.column_type import ( - SQLITE_COLUMN_TYPES, -) -from rhosocial.activerecord.base.framework_types import FRAMEWORK_PYTHON_TYPES -from rhosocial.activerecord_postgres_test.feature.query.column_helpers import ( - resolve_column_class, -) - -#: ``{class: the framework type it answers}``, written out rather than derived: -#: a derived table would only restate the code back at itself. -SURFACE_ONLY = [ - (GeometryColumn, Geometry), - (VectorColumn, Vector), - (BitStringColumn, BitString), - (RangeColumn, Range), - (MultirangeColumn, Multirange), - (MacAddressColumn, MacAddress), - (IntervalColumn, datetime.timedelta), -] - -_IDS = [klass.__name__ for klass, _ in SURFACE_ONLY] - - -def sqlite_dialect(version=(3, 46, 1)): - return SQLiteDialect(version=version) - - -def dummy_dialect(): - dialect = DummyDialect() - dialect._version = (3, 46, 1) - return dialect - - -def test_the_value_surface_is_abstract(): - """A surface is not a node: it must not be instantiable. - - The annotation derived from it *is* a node -- it renders -- because - ``_Annotation`` supplies the ``format_method`` the surface declares. - """ - assert inspect.isabstract(SurfaceOnlyValue) - assert not inspect.isabstract(SurfaceOnlyAnnotation) - - -def test_the_value_surface_offers_no_family_operation(): - """Only alias, null tests and casting -- no comparison, no arithmetic.""" - assert ComparisonMixin not in SurfaceOnlyValue.__mro__ - assert not hasattr(SurfaceOnlyValue, "compare") - assert not hasattr(SurfaceOnlyValue, "add") - - -@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) -def test_each_class_is_concrete_and_renders(klass, entry): - """The protocol needs a class that builds; a failure here is a table hole.""" - assert inspect.isclass(klass) - assert not inspect.isabstract(klass) - assert issubclass(klass, ColumnBase) - column = klass(sqlite_dialect(), "c") - assert isinstance(column, ColumnBase) - assert column.to_sql() == ('"c"', ()) - - -@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) -def test_each_class_carries_only_the_column_surface(klass, entry): - """No comparison, no arithmetic, no string or JSON handling.""" - assert ComparisonMixin not in klass.__mro__ - column = klass(sqlite_dialect(), "c") - assert not hasattr(column, "compare") - assert not hasattr(column, "like") - assert not hasattr(column, "add") - # What it *does* carry is the shared column surface. - assert hasattr(column, "is_null") - assert hasattr(column, "is_not_null") - assert hasattr(column, "as_") - assert hasattr(column, "cast") - - -@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) -def test_each_class_is_annotated_with_the_surface_only_answer(klass, entry): - """The invariant test also asks this; asserting the exact answer pins it.""" - assert annotation_for(klass(sqlite_dialect(), "c")) is SurfaceOnlyAnnotation - - -def test_the_annotation_names_the_value_type_it_carries(): - """CASE and CAST read the value type off the annotation, so it must resolve.""" - assert SurfaceOnlyAnnotation.value_type_of() is SurfaceOnlyValue - - -def test_the_annotation_renders_its_source(): - """An annotation is a node: it wraps what it types and renders it.""" - from rhosocial.activerecord.backend.expression import Column - - dialect = sqlite_dialect() - annotated = SurfaceOnlyAnnotation(dialect, Column(dialect, "c", table="t")) - assert annotated.to_sql() == ('"t"."c"', ()) - - -def test_the_annotation_renders_an_aliasless_source(): - """The wrapped node need not expose an ``alias`` slot at all. - - A Literal renders a value and has no column-like surface, so reading - ``source.alias`` unconditionally raised AttributeError here. - """ - from rhosocial.activerecord.backend.expression import Literal - - dialect = sqlite_dialect() - annotated = SurfaceOnlyAnnotation(dialect, Literal(dialect, 1)) - assert annotated.to_sql() == ("?", (1,)) - - -@pytest.mark.parametrize( - "table, dialect_factory, expected", - [ - (SQLITE_COLUMN_TYPES, sqlite_dialect, "sqlite"), - (DUMMY_COLUMN_TYPES, dummy_dialect, "dummy"), - ], - ids=["sqlite", "dummy"], -) -def test_the_table_is_complete_and_refuses_nothing(table, dialect_factory, expected): - """Twenty-four entries, none answered with ``None``.""" - assert set(table) == set(FRAMEWORK_PYTHON_TYPES) - assert [key for key, value in table.items() if value is None] == [] - - -@pytest.mark.parametrize("klass, entry", SURFACE_ONLY, ids=_IDS) -@pytest.mark.parametrize( - "dialect_factory, expected", - [(sqlite_dialect, "sqlite"), (dummy_dialect, "dummy")], - ids=["sqlite", "dummy"], -) -def test_the_tables_resolve_to_the_new_class(klass, entry, dialect_factory, expected): - assert resolve_column_class(dialect_factory(), entry) is klass - - -@pytest.mark.parametrize( - "dialect_factory, table", - [(sqlite_dialect, SQLITE_COLUMN_TYPES), (dummy_dialect, DUMMY_COLUMN_TYPES)], - ids=["sqlite", "dummy"], -) -def test_every_answer_selects_to_a_buildable_column(dialect_factory, table): - """Table completeness is only real if every answer builds and renders.""" - dialect = dialect_factory() - for entry in FRAMEWORK_PYTHON_TYPES: - column = resolve_column_class(dialect, entry)(dialect, "c") - assert isinstance(column, ColumnBase) - assert column.to_sql() == ('"c"', ()) - - -def test_the_base_mixin_still_states_no_table(): - """Neither dialect learnt a fallback: the tables are the answers.""" - - class Bare(ColumnTypeMixin): - pass - - assert Bare().suggested_extra_column_types() == {} diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py deleted file mode 100644 index 1aab9a53..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_temporal_value_families.py +++ /dev/null @@ -1,283 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_temporal_value_families.py -"""What each temporal operation answers with. - -A datetime is not one type. ``YEAR(ts)`` is a whole number, ``EXTRACT`` is a -number, ``NOW() + interval`` is a timestamp again, and ``NOW() - NOW()`` is an -interval. Getting these confused is silent — the SQL is still valid and -the answer is simply the wrong kind of thing — so each one is pinned here. - -The result's family is what decides the next operation, so the surface is -asserted too: a year may be added to, a timestamp may not be upper-cased. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_temporal_value_families.py -import datetime - -import pytest - -from rhosocial.activerecord.backend.expression import functions as datetime_functions -from rhosocial.activerecord.backend.expression.value_types import ( - NumericValue, - TemporalValue, -) -from rhosocial.activerecord.backend.expression.datetime import ( - DatetimeAddExpression, - DatetimeSubtractExpression, -) -from rhosocial.activerecord.backend.expression.operators import ArithmeticOperation - - -@pytest.fixture -def dialect(): - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - d = SQLiteDialect() - d._version = (3, 46, 1) - return d - - -@pytest.fixture -def timestamp(dialect): - from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column - - return build_column(dialect, "ts", datetime.datetime) - - -# --------------------------------------------------------------------------- -# The present, in each of its precisions -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "factory, cls", - [ - ("now", TemporalValue), - ("current_timestamp", TemporalValue), - ("localtimestamp", TemporalValue), - ("current_date", TemporalValue), - ("current_time", TemporalValue), - ], -) -def test_the_present_keeps_its_precision(dialect, factory, cls): - """A date is not a timestamp and a time is not either. - - Four separate classes now, where there was one class and a label saying - which it was standing in for. Each factory returns the class its own - precision calls for, and that is readable off the result. - """ - assert isinstance(getattr(datetime_functions, factory)(dialect), cls) - - -# --------------------------------------------------------------------------- -# Pulling a component out of a timestamp gives a whole number -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "factory", ["year", "month", "day", "hour", "minute", "second"] -) -def test_a_component_is_a_whole_number(dialect, timestamp, factory): - """A calendar component is a whole number on every backend. - - Asserted on the node's own class: the integral node is a distinct class from - the fractional one precisely because ``EXTRACT(EPOCH FROM ts)`` is not whole, - and that distinction now lives in the node rather than in a value class whose - operations were identical anyway. - """ - node = getattr(datetime_functions, factory)(dialect, timestamp) - assert type(node).__name__ == "ExtractFieldExpression" - - -def test_a_component_takes_arithmetic_and_not_string_operations(dialect, timestamp): - """A year is a number, so the number surface follows and the string one - does not. Getting this wrong is how ``str(year(ts))`` sneaks in.""" - year = datetime_functions.year(dialect, timestamp) - assert hasattr(year, "__add__") - assert not hasattr(year, "upper") - - -# --------------------------------------------------------------------------- -# Extraction is numeric because the unit decides it -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize("factory", ["extract", "date_part"]) -def test_extraction_is_numeric(dialect, timestamp, factory): - """``EXTRACT(EPOCH FROM ts)`` is fractional, so the family is too wide to - be a whole number. Widening here is deliberate: claiming integer would - offer ``bit_length`` on a value that may be a million and a half.""" - assert isinstance(getattr(datetime_functions, factory)(dialect, "year", timestamp), NumericValue) - - -def test_date_diff_counts_whole_units(dialect): - now = datetime_functions.now(dialect) - assert isinstance(now.date_diff("day", now), NumericValue) - - -# --------------------------------------------------------------------------- -# Arithmetic on time stays time -# --------------------------------------------------------------------------- - - -def test_truncation_stays_a_timestamp(dialect): - assert isinstance(datetime_functions.now(dialect).date_trunc("day"), TemporalValue) - - -@pytest.mark.parametrize("method", ["date_add", "date_sub"]) -def test_shifting_time_stays_a_timestamp(dialect, method): - now = datetime_functions.now(dialect) - result = getattr(now, method)(1, "days") - assert isinstance(result, TemporalValue) - assert isinstance(result, (DatetimeAddExpression, DatetimeSubtractExpression)) - - -def test_an_interval_is_its_own_family(dialect): - """A span is not a point in time, which is why date_add takes one.""" - assert isinstance(datetime_functions.interval(dialect, 1, "day"), TemporalValue) - - -# --------------------------------------------------------------------------- -# The operators are interval-based; a point in time has no sum -# --------------------------------------------------------------------------- - - -def test_a_timestamp_moves_by_an_interval(dialect): - """Constructed, not rendered: SQLite has no interval node yet (the - emulation belongs to the data-type step), and what this test pins is the - gate that lets the combination through at all.""" - now = datetime_functions.now(dialect) - one_day = datetime_functions.interval(dialect, 1, "day") - expression = now + one_day - assert isinstance(expression, ArithmeticOperation) - - -def test_two_points_subtract_to_an_interval(dialect): - now = datetime_functions.now(dialect) - sql, params = (now - now).to_sql() - assert "-" in sql - - -def test_two_points_have_no_sum(dialect): - """``created_at + created_at`` used to render and fail only in SQL.""" - now = datetime_functions.now(dialect) - with pytest.raises(AttributeError, match="no sum"): - now + now - - -def test_interval_arithmetic_stays_between_intervals(dialect): - one_day = datetime_functions.interval(dialect, 1, "day") - two_days = datetime_functions.interval(dialect, 2, "day") - for expression in (one_day + two_days, one_day - two_days, one_day * 2): - assert isinstance(expression, ArithmeticOperation) - - -def test_a_number_does_not_move_a_point_in_time(dialect): - now = datetime_functions.now(dialect) - with pytest.raises(AttributeError): - now + 1 - - -def test_a_span_is_not_divided(dialect): - one_day = datetime_functions.interval(dialect, 1, "day") - with pytest.raises(AttributeError): - one_day / 2 - - -def test_a_temporal_column_follows_the_same_gate(dialect, timestamp): - """The column and the value are the same expression layer, so the gate - has to see a temporal *column* as a temporal operand too.""" - one_day = datetime_functions.interval(dialect, 1, "day") - assert isinstance(timestamp + one_day, ArithmeticOperation) - assert isinstance(timestamp - timestamp, ArithmeticOperation) - with pytest.raises(AttributeError, match="no sum"): - timestamp + timestamp - - -# --------------------------------------------------------------------------- -# A node with a class of its own is its type; there is nothing to declare -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "factory, args, result_cls", - [ - ("extract", ("year",), NumericValue), - ("date_part", ("year",), NumericValue), - ("interval", (1, "day"), TemporalValue), - ("date_diff", ("day",), NumericValue), - ("seconds_between", (), NumericValue), - ], -) -def test_a_temporal_operation_yields_its_own_type(dialect, timestamp, factory, args, result_cls): - """What a temporal operation yields is decided where it is built. - - ``EXTRACT`` yields a number and ``DATE_DIFF`` a whole number; each is - decided by the factory that builds the node, and neither needed a label to - say so afterwards. ``SECONDS_BETWEEN`` is the fractional member: seconds - are divisible, so its result is the numeric family again. - """ - if factory == "interval": - result = getattr(datetime_functions, factory)(dialect, *args) - elif factory in ("date_diff", "seconds_between"): - result = getattr(datetime_functions, factory)(dialect, *args, timestamp, timestamp) - else: - result = getattr(datetime_functions, factory)(dialect, *args, timestamp) - assert isinstance(result, result_cls) - - -def test_a_temporal_value_offers_temporal_operations(dialect): - now = datetime_functions.now(dialect) - for method in ("date_add", "date_sub", "date_diff", "seconds_between", "date_part", "extract"): - assert hasattr(now, method), f"a timestamp lost {method}" - - -def test_a_temporal_value_does_not_offer_string_operations(dialect): - assert not hasattr(datetime_functions.now(dialect), "upper") - - -@pytest.mark.parametrize( - "factory", - ["now", "current_date", "current_time", "current_timestamp", "localtimestamp"], -) -def test_each_temporal_value_is_its_own_node(dialect, factory): - """They offer the same operations, so they share a surface -- but they are - four different types, and each says so with its own class. - - A date and a date-time used to be one class with a label saying which it - was. Now the node is the statement, so this pins that a point in time is - still distinguishable from a span and from the other points by the class - the factory chose. - """ - node = getattr(datetime_functions, factory)(dialect) - assert isinstance(node, TemporalValue) - assert hasattr(node, "date_add") - - -def test_an_interval_is_a_span_and_not_a_point(dialect): - """The distinction the temporal gate asks about, stated by the node. - - ``_is_interval_value`` used to ask about a class nothing ever constructed, - which made the whole gate unreachable. The marker it asks about now is one - the interval node carries. - """ - from rhosocial.activerecord.backend.expression.mixins import IntervalMixin - - interval = datetime_functions.interval(dialect, 1, "day") - assert isinstance(interval, IntervalMixin) - assert isinstance(interval, TemporalValue) - assert not isinstance(datetime_functions.now(dialect), IntervalMixin) - - -def test_the_sql_does_not_change_when_a_type_is_stated(dialect, timestamp): - """Typing is a surface decision, never a rendering one.""" - from rhosocial.activerecord.backend.expression import FunctionCall - - call = FunctionCall(dialect, "MY_FUNC", timestamp) - assert call.as_datetime().to_sql() == call.to_sql() - - -def test_an_alias_survives_a_stated_type(dialect, timestamp): - from rhosocial.activerecord.backend.expression import FunctionCall - - call = FunctionCall(dialect, "MY_FUNC", timestamp) - assert " AS " in call.as_datetime().as_("when").to_sql()[0] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py deleted file mode 100644 index 79fbd998..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_typed_columns.py +++ /dev/null @@ -1,418 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_typed_columns.py -"""Type-narrowed column expressions. - -The column a model field resolves to depends on the field's Python -annotation, so a numeric field offers arithmetic and no ``.like()``, a JSON -field offers path access, and so on. These tests pin the selection the field -accessor makes, the narrowing it produces, and the guarantees that make it -safe to rely on. - -No database is involved — every assertion is on the expression tree or the -SQL a dialect produces from it — so no provider fixture is required. -""" - -import datetime -import decimal -import typing -import uuid -from typing import Any, ClassVar, Dict, List, Optional, Union - -import pytest - -from rhosocial.activerecord.backend.expression import ( - ArrayColumn, - BinaryColumn, - BooleanColumn, - Column, - ColumnBase, - TimestampColumn, - IntegerColumn, - IntervalColumn, - JSONColumn, - NumericColumn, - StringColumn, - UUIDColumn, - build_json_path, -) -from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect -from rhosocial.activerecord.base.field_proxy import ( - ColumnTypeResolutionError, - FieldAccessor, - FieldProxy, -) -from rhosocial.activerecord.base.fields import UseColumnType -from rhosocial.activerecord.model import ActiveRecord - -from rhosocial.activerecord_postgres_test.feature.query.column_helpers import ( - build_column, - resolve_column_class, -) - - -def column_class_for(annotation, dialect=None): - """The class the field accessor's selection picks for *annotation*. - - A one-line shim so the cases below read as "resolve this annotation" the - way ``Model.c.`` does it. The selection lives on - :class:`FieldAccessor`; a free framework-level function would have to - invent a backend or reach for a core-side table, which is the - core-authority shape the architecture removed. - """ - if dialect is None: - dialect = sqlite_dialect() - return resolve_column_class(dialect, annotation) - - -def sqlite_dialect(): - """A version-adapted SQLite dialect. - - ``supports_json_*`` reads ``self.version``, so the dialect must be - adapted before any rendering; 3.46 satisfies every gate these tests - exercise (JSON arrows need 3.38). - """ - dialect = SQLiteDialect() - dialect._version = (3, 46, 1) - return dialect - - -# --------------------------------------------------------------------------- -# Selection: annotation -> column class -# --------------------------------------------------------------------------- - -_DISPATCH = [ - (str, StringColumn), - (int, IntegerColumn), - (float, NumericColumn), - (bool, BooleanColumn), - (bytes, BinaryColumn), - (dict, JSONColumn), - # No array type exists in SQLite, so a `list` field is a JSON document here - # rather than an ArrayColumn. The same model on PostgreSQL gets a real array; - # that divergence is the protocol working, not a bug (see - # `test_column_type_support.py`). - (list, JSONColumn), - (decimal.Decimal, NumericColumn), - (datetime.datetime, TimestampColumn), - (datetime.date, TimestampColumn), - (datetime.timedelta, IntervalColumn), - (uuid.UUID, UUIDColumn), -] - - -@pytest.mark.parametrize("annotation, expected", _DISPATCH, ids=lambda v: getattr(v, "__name__", str(v))) -def test_dispatch_by_annotation(annotation, expected): - assert column_class_for(annotation) is expected - - -@pytest.mark.parametrize( - "annotation", - [ - Optional[str], - Optional[dict], - ], - ids=lambda v: str(v), -) -def test_optional_annotations_resolve_to_the_inner_entry(annotation): - assert column_class_for(annotation) in {StringColumn, JSONColumn} - - -@pytest.mark.parametrize( - "annotation", - [ - List[int], # a parameterised container is not classifiable - Dict[str, int], - Union[int, str], # genuinely ambiguous - Any, - ], - ids=lambda v: str(v), -) -def test_unclassifiable_annotations_fail(annotation): - """No guessing, and no escape: each of these raises at build time. - - This is the "全量或失败" ruling. These four used to become the permissive - ``Column``, which offered every operation to a value whose type nothing was - known about — so ``Model.c.meta.like('%x%')`` rendered happily and failed at - the database, with the error pointing at the SQL rather than at the - annotation that caused it. Narrowing exists to catch that at the point the - field is declared, so a hole in it is a hole in the guarantee. - - ``UseColumnType`` is the way through: it says which operations the value - carries, which is a statement the framework can honour on any backend. - """ - with pytest.raises(ColumnTypeResolutionError) as excinfo: - column_class_for(annotation) - assert "UseColumnType" in str(excinfo.value) - - -def test_optional_and_annotated_are_stripped(): - # typing.Annotated arrived in 3.9 and this project supports 3.8, so the - # alias is built the way the runtime marks one on every version. - Annotated = getattr(typing, "Annotated", None) - if Annotated is None: - pytest.skip("typing.Annotated requires Python 3.9+") - - strip = FieldAccessor._strip_annotation - assert strip(Optional[dict]) is dict - assert strip(Annotated[str, "some-marker"]) is str - assert strip(Optional[Annotated[str, "m"]]) is str - - -# --------------------------------------------------------------------------- -# Narrowing: each family offers only what its value type supports -# --------------------------------------------------------------------------- - - -def test_string_column_has_like_but_no_arithmetic(): - col = build_column(sqlite_dialect(), "name", str) - assert isinstance(col, StringColumn) - assert hasattr(col, "like") and hasattr(col, "ilike") - - # Arithmetic is refused explicitly rather than left absent: the operator is - # looked up on the type by the interpreter, so a missing one produces - # CPython's own TypeError instead of the package's message. hasattr is true - # because the method exists to raise, which is why the check calls it. - with pytest.raises(AttributeError): - col + 1 - with pytest.raises(AttributeError): - col * 2 - - -def test_integer_column_has_arithmetic_but_no_like(): - col = build_column(sqlite_dialect(), "age", int) - assert isinstance(col, IntegerColumn) - assert hasattr(col, "__add__") and hasattr(col, "__mul__") - assert not hasattr(col, "like") - - -def test_json_column_has_path_access_only(): - col = build_column(sqlite_dialect(), "settings", dict) - assert isinstance(col, JSONColumn) - assert hasattr(col, "json_path") and hasattr(col, "json_value") - assert not hasattr(col, "like") - assert not hasattr(col, "__add__") - - -def test_uuid_column_offers_no_uuid_specific_operator(): - """Portable SQL has none, so a UUID column is just a value column.""" - col = build_column(sqlite_dialect(), "uid", uuid.UUID) - assert isinstance(col, UUIDColumn) - assert not hasattr(col, "like") - assert not hasattr(col, "json_path") - with pytest.raises(AttributeError): - col + 1 - - -def test_bare_column_offers_no_operation(): - """The hand-built ``Column`` is a reference, and references do not guess. - - Nothing established what the column holds, so offering an operation - would be a promise the database never made — and the previous shape had - the failure the typed classes exist to prevent: comparing two of them - answered Python's identity question silently. The class renders (its one - job), the shared surface answers questions about the *reference* itself, - and predicates are built explicitly where the column's type is unknown. - """ - col = Column(sqlite_dialect(), "anything") - assert col.to_sql() == ('"anything"', ()) - for operation in ("like", "__add__", "json_path", "in_", "upper"): - assert not hasattr(col, operation), f"a bare column wrongly offers {operation}" - - -# --------------------------------------------------------------------------- -# Rendering: unchanged SQL, and a common format_column -# --------------------------------------------------------------------------- - -_RENDER_CLASSES = [ - Column, StringColumn, NumericColumn, TimestampColumn, BooleanColumn, - BinaryColumn, UUIDColumn, JSONColumn, ArrayColumn, -] - - -@pytest.mark.parametrize("column_class", _RENDER_CLASSES, ids=lambda c: c.__name__) -def test_every_column_class_renders_identically(column_class): - """Narrowing changed the API, not the SQL.""" - dialect = sqlite_dialect() - col = column_class(dialect, "settings", table="t", schema_name="s") - assert col.to_sql() == ('"s"."t"."settings"', ()) - - -@pytest.mark.parametrize("column_class", _RENDER_CLASSES, ids=lambda c: c.__name__) -def test_every_column_class_is_a_column_base(column_class): - """The 8 isinstance() consumers test for ColumnBase, so all must match.""" - assert isinstance(column_class(sqlite_dialect(), "x"), ColumnBase) - - -@pytest.mark.parametrize("column_class", _RENDER_CLASSES, ids=lambda c: c.__name__) -def test_qualified_and_aliased_rendering(column_class): - dialect = sqlite_dialect() - assert column_class(dialect, "c").to_sql() == ('"c"', ()) - assert column_class(dialect, "c", table="t").to_sql() == ('"t"."c"', ()) - assert column_class(dialect, "c", alias="a").to_sql() == ('"c" AS "a"', ()) - - -# --------------------------------------------------------------------------- -# JSON path building -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "keys, expected", - [ - ((), "$"), - (("a",), "$.a"), - (("a", "b"), "$.a.b"), - (("tags", 0), "$.tags[0]"), - (("a", 0, "b"), "$.a[0].b"), - (("tags", "[0]"), "$.tags[0]"), - ], - ids=lambda v: str(v), -) -def test_build_json_path(keys, expected): - assert build_json_path(*keys) == expected - - -def test_string_zero_is_a_key_not_an_index(): - """``"0"`` names a key; only an int is an index. - - ``$.tags.0`` is a key literally named ``0`` and matches nothing, so the - distinction is carried by the type rather than the spelling. - """ - assert build_json_path("tags", "0") == "$.tags.0" - assert build_json_path("tags", 0) == "$.tags[0]" - - -def test_bool_is_rejected_as_a_path_segment(): - """bool is an int subclass; silently treating True as index 1 is a trap.""" - with pytest.raises(TypeError, match="bool"): - build_json_path("a", True) - - -def test_json_path_renders_bracket_for_integer_index(): - dialect = sqlite_dialect() - col = build_column(dialect, "settings", dict) - assert col.json_path("tags", 0).to_sql() == ('"settings"->>\'$.tags[0]\'', ()) - - -def test_json_path_chains_without_renesting_the_path(): - """Chaining accumulates; it must not re-anchor the second path at ``$``.""" - dialect = sqlite_dialect() - col = build_column(dialect, "settings", dict) - assert col.json_value("a").json_value("b").to_sql() == ( - '"settings"->\'$.a\'->\'$.b\'', - (), - ) - - -def test_json_path_alias_lands_on_the_outermost_form(): - dialect = sqlite_dialect() - col = build_column(dialect, "settings", dict) - assert col.as_("j").json_path("a").to_sql() == ('"settings"->>\'$.a\' AS "j"', ()) - - -# --------------------------------------------------------------------------- -# End to end through FieldProxy -# --------------------------------------------------------------------------- - - -def _annotated(): - """``typing.Annotated``, or a skip — the alias is 3.9+ and this file is 3.8-safe.""" - alias = getattr(typing, "Annotated", None) - if alias is None: - pytest.skip("typing.Annotated requires Python 3.9+") - return alias - - -def _model(dialect): - Annotated = _annotated() - - class Widget(ActiveRecord): - @classmethod - def table_name(cls): - return "typed_widget" - - @classmethod - def primary_key(cls): - return "id" - - c: ClassVar[FieldProxy] = FieldProxy() - - id: int - name: str - qty: int - price: decimal.Decimal - created: datetime.datetime - settings: dict - tags: list - uid: uuid.UUID - flag: bool - # `Any` is not classifiable, so this field has to say what its value can - # do. The declaration is the whole point: without it the field does not - # resolve at all, which is the "全量或失败" ruling applied to a model. - meta: Annotated[Any, UseColumnType(JSONColumn)] - - Widget.__backend__ = type("B", (), {"dialect": dialect})() - return Widget - - -@pytest.mark.parametrize( - "field, expected", - [ - ("id", IntegerColumn), - ("name", StringColumn), - ("qty", IntegerColumn), - ("price", NumericColumn), - ("created", TimestampColumn), - ("settings", JSONColumn), - ("tags", JSONColumn), - ("uid", UUIDColumn), - ("flag", BooleanColumn), - ("meta", JSONColumn), # Any, resolved through UseColumnType - ], -) -def test_field_proxy_returns_the_matching_class(field, expected): - Widget = _model(sqlite_dialect()) - assert type(getattr(Widget.c, field)) is expected - - -def test_field_proxy_refuses_an_undeclared_any(): - """A model field typed ``Any`` with no declaration fails where it is read. - - The proxy is where a column is built, so this is the earliest point at which - the model can be told — and telling it here beats a driver error naming a - column at query time. - """ - - class Loose(ActiveRecord): - @classmethod - def table_name(cls): - return "typed_loose" - - @classmethod - def primary_key(cls): - return "id" - - c: ClassVar[FieldProxy] = FieldProxy() - - id: int - meta: Any - - Loose.__backend__ = type("B", (), {"dialect": sqlite_dialect()})() - with pytest.raises(ColumnTypeResolutionError, match="UseColumnType"): - # The proxy builds the column on attribute access, so the bare - # expression is the call under test -- the same shape as the - # AttributeError case below it. - Loose.c.meta # noqa: B018 - - -def test_field_proxy_query_uses_narrowed_operations(): - dialect = sqlite_dialect() - Widget = _model(dialect) - sql, params = Widget.query().where(Widget.c.settings.json_path("lang") == "en").to_sql() - assert sql == """SELECT * FROM "typed_widget" WHERE "typed_widget"."settings"->>'$.lang' = ?""" - assert params == ("en",) - - -def test_field_proxy_unknown_field_still_raises_attribute_error(): - Widget = _model(sqlite_dialect()) - with pytest.raises(AttributeError, match="does not exist on model"): - Widget.c.no_such_field diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py deleted file mode 100644 index d9cf0f73..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_family_inference.py +++ /dev/null @@ -1,226 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_family_inference.py -"""Result families, and the lattice they add up to. - -A family is what decides an expression's operation surface, and it has to be -accurate in both directions. Over-narrowing removes a legal operation; -over-widening offers an illegal one. Both failures are silent — the SQL is -still produced, it is just wrong — so the families are pinned here. - -The distinction that matters most is whole number against fraction. ``int`` and -``float`` share a column class, so the family has to come from the annotation -rather than the class, or "integer in, integer out" cannot be expressed and -``ceil`` of an integer claims to be fractional. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_family_inference.py -import datetime -import uuid - -import pytest - -from rhosocial.activerecord.backend.expression import Column, FunctionCall -from rhosocial.activerecord.backend.expression import functions as F -from rhosocial.activerecord.backend.expression.column_types import annotation_for -from rhosocial.activerecord.backend.expression.declared import ( - ArrayAnnotation, - BinaryAnnotation, - BooleanAnnotation, - IntegerAnnotation, - JSONAnnotation, - NumberAnnotation, - TemporalAnnotation, - TextAnnotation, - UUIDAnnotation, - XMLAnnotation, -) - -#: Every value class the lattice holds, for the "declares nothing" assertions. -TYPED_VALUE_CLASSES = ( - ArrayAnnotation, - BinaryAnnotation, - BooleanAnnotation, - IntegerAnnotation, - JSONAnnotation, - NumberAnnotation, - TemporalAnnotation, - TextAnnotation, - UUIDAnnotation, - XMLAnnotation, -) - - -@pytest.fixture -def dialect(): - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - d = SQLiteDialect() - d._version = (3, 46, 1) - return d - - -@pytest.fixture -def columns(dialect): - from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column - - return { - "string": build_column(dialect, "s", str), - "int": build_column(dialect, "i", int), - "float": build_column(dialect, "f", float), - "bool": build_column(dialect, "b", bool), - "json": build_column(dialect, "j", dict), - "bytes": build_column(dialect, "y", bytes), - "uuid": build_column(dialect, "u", uuid.UUID), - "datetime": build_column(dialect, "d", datetime.datetime), - } - - -# --------------------------------------------------------------------------- -# A column's family comes from its annotation -# --------------------------------------------------------------------------- - - -def test_every_column_class_has_an_annotation(columns): - """The map is complete, so no column class is silently untyped. - - There is no registry of family *names* to be complete any more -- a type is - a class. But there is a table from column class to value class (see - ``column_types.annotation_for``), and a column class missing from it would - make every operation over that column quietly untyped, which is the failure - this file exists to catch. So it is checked here instead of assumed. - """ - import inspect - - from rhosocial.activerecord.backend.expression import column_types as CT - - declared = { - name - for name, klass in vars(CT).items() - if inspect.isclass(klass) - and issubclass(klass, CT.ColumnBase) - and klass is not CT.ColumnBase - } - assert declared, "the typed column classes moved" - for name in sorted(declared): - column = getattr(CT, name).__new__(getattr(CT, name)) - assert annotation_for(column) is not None, f"{name} has no annotation" - # The base is now an ABC, so there is no "untyped column object" left to - # map -- not being able to build one is the stronger form of the same - # invariant. The untyped column that *can* be built is the bare ``Column``, - # which lives outside this module, and staying unmapped is still the point. - assert inspect.isabstract(CT.ColumnBase), "the typed base must not be instantiable" - from rhosocial.activerecord.backend.expression import Column as BareColumn - - assert annotation_for(BareColumn.__new__(BareColumn)) is None - - -def test_every_core_data_type_has_an_annotation_or_is_explicitly_impossible(): - """The DDL-type -> value-class map is closed, so a cast cannot go silently - untyped. - - There is a second completeness question beside the column one above, and it - is asked of the *target* side of a cast: ``cast`` answers from the class of - the ``DataType`` it was handed (``type_conversion._type_annotations()``), - so a core type missing from that table would make every cast to it come - back untyped and the operations its value supports invisible. A type added - to the core without a map entry must therefore be a test failure here, not - a quiet degradation. - - The loop walks every concrete core ``DataType`` currently loaded rather - than a hand-kept list, so a new core type file cannot dodge it by not being - imported. - - ``CustomType`` is the one deliberate exception and is asserted as such: it - is the escape hatch for a name this library does not model, so there is no - family it could honestly promise operations on (see its docstring), and the - map deliberately leaves it out. - """ - import inspect - - from rhosocial.activerecord.backend.expression import types as core_types - from rhosocial.activerecord.backend.expression.functions.type_conversion import ( - _type_annotations, - ) - - core_prefix = "rhosocial.activerecord.backend.expression.types" - seen = set() - stack = [core_types.DataType] - while stack: - klass = stack.pop() - if klass in seen: - continue - seen.add(klass) - stack.extend(klass.__subclasses__()) - declared = { - klass.__name__: klass - for klass in seen - if klass is not core_types.DataType - and not inspect.isabstract(klass) - and klass.__module__.startswith(core_prefix) - } - assert declared, "the core types moved" - - mapping = _type_annotations() - # The exception, stated rather than merely skipped. ``CustomType`` is the - # escape hatch for a type nobody here has heard of; mapping it to any value - # class would offer operations the database may reject. Asserting it stays - # unmapped is what keeps the exception the only one. - assert core_types.CustomType in declared.values() - assert core_types.CustomType not in mapping, ( - "CustomType must not map to a value class: it exists precisely because " - "nothing here knows what the type is, so no value surface can be " - "claimed for it" - ) - - for name, klass in sorted(declared.items()): - if klass is core_types.CustomType: - continue - assert any(base in mapping for base in klass.__mro__), ( - f"{name} has no annotation: add it to " - f"functions/type_conversion._type_annotations(), or add it to " - f"the deliberate-exception list here with the reason it cannot " - f"honestly have one" - ) - - -def test_a_bare_function_call_has_no_family(dialect, columns): - """It says nothing about what a database would return.""" - call = FunctionCall(dialect, "MY_FUNC", columns["string"]) - assert not isinstance(call, TYPED_VALUE_CLASSES) - - -def test_a_hand_written_column_has_no_family(dialect): - """A permissive Column means "unknown type", which is not the same as any.""" - assert not isinstance(Column(dialect, "x", table="t"), TYPED_VALUE_CLASSES) - - -@pytest.mark.parametrize( - "key, expected", - [ - ("string", TextAnnotation), - ("int", IntegerAnnotation), - ("float", NumberAnnotation), - ("bool", BooleanAnnotation), - ("json", JSONAnnotation), - ("bytes", BinaryAnnotation), - ("uuid", UUIDAnnotation), - ("datetime", TemporalAnnotation), - ], -) -def test_each_annotation_lands_in_its_type(columns, key, expected): - """The annotation picks the column class, and the class picks the annotation. - - This used to compare against a family *name* read off an attribute. The - attribute is gone and the class is the whole of it, so the assertion is the - annotation an operation over that column now returns. - """ - assert annotation_for(columns[key]) is expected - - -def test_a_disagreement_yields_no_type(dialect, columns): - """GREATEST of an integer and a string is legal SQL and is neither, so the - call stays generic rather than promising the first or the widest.""" - mixed = F.greatest(dialect, columns["int"], columns["string"]) - assert not isinstance(mixed, TYPED_VALUE_CLASSES) - assert mixed.to_sql() == FunctionCall( - dialect, "GREATEST", columns["int"], columns["string"] - ).to_sql() diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py b/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py deleted file mode 100644 index a569088e..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/core/test_value_type_lattice.py +++ /dev/null @@ -1,214 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_type_lattice.py -"""Every operation declares a result type, and the type gates the next operation. - -The rule this file pins: an operation's result determines which operations are -available next. ``upper()`` returns a string, so ``substr()`` follows. -``length()`` is a legal string operation whose result is a *number*, so -``upper()`` does not — and that falls out of the types rather than out of a -check somewhere. - -The two halves that are easy to get wrong are both pinned here: a result must -not lose its own surface, and it must not gain a surface belonging to another -family. -""" - -# tests/rhosocial/activerecord_postgres_test/feature/query/test_value_type_lattice.py -import pytest - -from rhosocial.activerecord.backend.expression import ( - CharLengthFunction, -) - - -@pytest.fixture -def dialect(): - # The portable baseline: this file pins result *types* and the core - # spellings. Which spelling a backend writes is checked in - # test_operation_boundaries.py, against SQLite and a real database. - from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect - - return DummyDialect() - - -@pytest.fixture -def name(dialect): - from rhosocial.activerecord_postgres_test.feature.query.column_helpers import build_column - - return build_column(dialect, "name", str) - - -# --------------------------------------------------------------------------- -# A string operation whose result is a number -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "method, args, function", - [ - ("length", (), "LENGTH"), - ("ascii", (), "ASCII"), - ("octet_length", (), "OCTET_LENGTH"), - ("bit_length", (), "BIT_LENGTH"), - ("strpos", ("a",), "STRPOS"), - ("position", ("a",), "POSITION"), - ], - ids=["length", "ascii", "octet_length", "bit_length", "strpos", "position"], -) -def test_number_returning_operation_yields_an_integer(name, method, args, function): - """These read a string and produce a count or a code. - - Each is now a node of its own -- ``CharLengthFunction``, - ``AsciiFunction``, ``OctetLengthFunction``, ``BitLengthFunction``, - ``PositionExpression`` -- so what the six share is asserted as the - **surface** rather than as a class: arithmetic is available and the string - surface is not. Asserting ``isinstance(result, IntegerAnnotation)`` would pin - the wrapper these operations used to be returned in, which is exactly what - the per-function classes removed. - """ - result = getattr(name, method)(*args) - assert hasattr(result, "__add__") - assert not hasattr(result, "upper") - assert function in result.to_sql()[0] - - -def test_the_whole_string_surface_offers_them(name): - """They are string operations, so they belong on the string surface. - - Their absence earlier was a gap in the surface, not a rule that only - string-to-string operations exist. - """ - for method in ("length", "ascii", "strpos", "position", "octet_length", "bit_length"): - assert hasattr(name, method), f"StringColumn is missing {method}" - - -# --------------------------------------------------------------------------- -# The result type gates the next operation -# --------------------------------------------------------------------------- - - -#: How many arguments each string operation *requires*, so the parametrized -#: test can call them all the same way. `substr` also takes an optional length -#: and `trim` optional characters and a direction; passing the minimum is -#: enough to reach the return, which is what is under test here. -#: -#: The placeholders are typed, not a repeated ``"x"``. Positions and counts are -#: integers and text operands are strings, and a call that got them wrong used -#: to pass silently -- a literal carrier accepted any value -- which is how -#: ``substr("x")`` came to mean "substring starting one character in" nowhere. -#: The typed value nodes now refuse it, which is the point of them. -_REQUIRED_ARGS = { - "upper": [], "lower": [], "trim": [], "initcap": [], - "substr": [1], "left": [1], "right": [1], - "concat": ["x"], - "replace": ["a", "b"], -} - - -def _call(name, method): - return getattr(name, method)(*_REQUIRED_ARGS[method]) - - -@pytest.mark.parametrize( - "method", ["upper", "lower", "substr", "trim", "concat", "replace", "left", "initcap"] -) -def test_string_result_keeps_the_string_surface(name, method): - """The result is a string and *says* so by offering the next operation. - - What is asserted is the surface, not one class: most of these return a - StringValue, but a node with its own dialect hook -- TRIM, whose - standard spelling is a syntax error on SQLite -- is its own class and - carries the same mixins, which is what makes ``col.trim().upper()`` legal. - """ - result = _call(name, method) - assert hasattr(result, "upper"), f"{method} did not return a string value" - assert hasattr(result, "substr"), f"{method} did not return a string value" - - -@pytest.mark.parametrize( - "chained, expected_functions", - [ - (lambda c: c.upper().substr(1, 3), ["UPPER", "SUBSTRING"]), - (lambda c: c.trim().replace("a", "b"), ["TRIM", "REPLACE"]), - (lambda c: c.upper().lower().initcap(), ["UPPER", "LOWER", "INITCAP"]), - ], - ids=["upper-substr", "trim-replace", "case-chain"], -) -def test_string_chain_stays_string(name, chained, expected_functions): - sql, _ = chained(name).to_sql() - for function in expected_functions: - assert function in sql - - -def test_number_result_loses_the_string_surface(name): - """A length has no case, so ``upper()`` must not exist on it.""" - result = name.length() - for method in ("upper", "lower", "substr", "trim", "initcap", "reverse"): - assert not hasattr(result, method), ( - f"an integer result wrongly offers {method}" - ) - - -def test_number_result_keeps_integer_operations(name): - """Arithmetic is legal on an integer, and stays an integer.""" - result = name.length() - assert hasattr(result, "__add__") - assert hasattr(result, "__sub__") - assert hasattr(result, "__mul__") - - -# --------------------------------------------------------------------------- -# The chain crosses families correctly -# --------------------------------------------------------------------------- - - -def test_string_then_number(name): - """upper() is a string, length() of it is a number.""" - result = name.upper().length() - assert isinstance(result, CharLengthFunction) - assert "LENGTH" in result.to_sql()[0] and "UPPER" in result.to_sql()[0] - - -def test_number_comparison_chains(name): - sql, _ = (name.length() > 5).to_sql() - assert "LENGTH" in sql and ">" in sql - - -def test_arithmetic_on_a_number_result(name): - """``length + 1`` is an arithmetic expression over an integer value.""" - sql, params = (name.length() + 1).to_sql() - assert "LENGTH" in sql - assert params == (1,) - - -def test_a_number_result_can_be_compared_but_not_matched(name): - """Comparison is universal; ``LIKE`` is not. - - Every value can be compared, so ``length() > 5`` is offered. ``LIKE`` is - text matching and a whole number is not text, so the operation is not - offered — it fails here, at the point of the call, rather than at the - database. This used to be the other way round and the reason the typed - column classes exist at all. - """ - result = name.length() - assert " > " in (result > 0).to_sql()[0] - with pytest.raises(AttributeError): - result.like("1%") - - -# --------------------------------------------------------------------------- -# Crossing into a predicate ends the value chain -# --------------------------------------------------------------------------- - - -def test_predicate_ends_the_chain(name): - """A predicate is the end of the value chain whatever produced it.""" - predicate = name.upper().like("A%") - for method in ("upper", "length", "substr"): - assert not hasattr(predicate, method), ( - f"predicate wrongly offers {method}; the value chain should have ended" - ) - - -def test_integer_value_can_be_aliased(name): - sql, _ = name.length().as_("n").to_sql() - assert " AS " in sql diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py deleted file mode 100644 index 46cd32e4..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py +++ /dev/null @@ -1,232 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_on_params.py -"""Tests for the on_params parameter in JOIN methods (sync and async).""" - -from decimal import Decimal - -import pytest - - -class TestSyncJoinOnParams: - """Synchronous JOIN with on_params tests.""" - - def test_inner_join_with_on_params(self, order_fixtures): - """Test inner_join with a string ON condition and on_params.""" - User, Order, OrderItem = order_fixtures - - user = User(username="on_params_user", email="op@example.com", age=30) - user.save() - - order = Order(user_id=user.id, order_number="OP-001", total_amount=Decimal("100.00")) - order.save() - - results = ( - Order.query() - .inner_join( - User, - on='"user_id" = ?', - on_params=[user.id], - ) - .where(Order.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - def test_left_join_with_on_params(self, order_fixtures): - """Test left_join with a string ON condition and on_params.""" - User, Order, OrderItem = order_fixtures - - user = User(username="left_op_user", email="lop@example.com", age=30) - user.save() - - order = Order(user_id=user.id, order_number="LOP-001", total_amount=Decimal("50.00")) - order.save() - - results = ( - Order.query() - .left_join( - User, - on='"user_id" = ?', - on_params=[user.id], - ) - .where(Order.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - def test_join_with_on_params_and_alias(self, order_fixtures): - """Test join with on_params and table alias.""" - User, Order, OrderItem = order_fixtures - - user = User(username="alias_op_user", email="aop@example.com", age=30) - user.save() - - order = Order(user_id=user.id, order_number="AOP-001", total_amount=Decimal("120.00")) - order.save() - - results = ( - Order.query() - .inner_join( - User, - on='"user_id" = ?', - on_params=[user.id], - alias="u", - ) - .where(Order.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - def test_join_with_on_params_none_and_no_placeholders(self, order_fixtures): - """Test join with on_params=None when string ON has no placeholders.""" - User, Order, OrderItem = order_fixtures - - user = User(username="nop_op_user", email="nop@example.com", age=30) - user.save() - - order = Order(user_id=user.id, order_number="NOP-001", total_amount=Decimal("80.00")) - order.save() - - # Use a string ON condition without placeholders so on_params=None is valid - import warnings - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", UserWarning) - results = ( - Order.query() - .inner_join( - User, - on='"user_id" = "users"."id"', - on_params=None, - ) - .where(Order.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - def test_join_with_multiple_on_params(self, order_fixtures): - """Test join with multiple on_params values.""" - User, Order, OrderItem = order_fixtures - - user = User(username="multi_op_user", email="mop@example.com", age=30) - user.save() - - order = Order(user_id=user.id, order_number="MOP-001", total_amount=Decimal("100.00"), status="active") - order.save() - - results = ( - Order.query() - .inner_join( - User, - on='"user_id" = ? AND "status" = ?', - on_params=[user.id, "active"], - ) - .where(Order.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - -class TestAsyncJoinOnParams: - """Asynchronous JOIN with on_params tests.""" - - @pytest.mark.asyncio - async def test_async_inner_join_with_on_params(self, async_order_fixtures): - """Test async inner_join with a string ON condition and on_params.""" - AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures - - user = AsyncUser(username="async_op_user", email="aop@example.com", age=30) - await user.save() - - order = AsyncOrder(user_id=user.id, order_number="AOP-001", total_amount=Decimal("100.00")) - await order.save() - - results = ( - await AsyncOrder.query() - .inner_join( - AsyncUser, - on='"user_id" = ?', - on_params=[user.id], - ) - .where(AsyncOrder.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - @pytest.mark.asyncio - async def test_async_left_join_with_on_params(self, async_order_fixtures): - """Test async left_join with a string ON condition and on_params.""" - AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures - - user = AsyncUser(username="async_lop_user", email="alop@example.com", age=30) - await user.save() - - order = AsyncOrder(user_id=user.id, order_number="ALOP-001", total_amount=Decimal("50.00")) - await order.save() - - results = ( - await AsyncOrder.query() - .left_join( - AsyncUser, - on='"user_id" = ?', - on_params=[user.id], - ) - .where(AsyncOrder.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - @pytest.mark.asyncio - async def test_async_join_with_on_params_and_alias(self, async_order_fixtures): - """Test async join with on_params and table alias.""" - AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures - - user = AsyncUser(username="async_aop_user", email="aaop@example.com", age=30) - await user.save() - - order = AsyncOrder(user_id=user.id, order_number="AAOP-001", total_amount=Decimal("120.00")) - await order.save() - - results = ( - await AsyncOrder.query() - .inner_join( - AsyncUser, - on='"user_id" = ?', - on_params=[user.id], - alias="u", - ) - .where(AsyncOrder.c.id == order.id) - .all() - ) - - assert len(results) >= 1 - - @pytest.mark.asyncio - async def test_async_join_with_multiple_on_params(self, async_order_fixtures): - """Test async join with multiple on_params values.""" - AsyncUser, AsyncOrder, AsyncOrderItem = async_order_fixtures - - user = AsyncUser(username="async_mop_user", email="amop@example.com", age=30) - await user.save() - - order = AsyncOrder(user_id=user.id, order_number="AMOP-001", total_amount=Decimal("100.00"), status="active") - await order.save() - - results = ( - await AsyncOrder.query() - .inner_join( - AsyncUser, - on='"user_id" = ? AND "status" = ?', - on_params=[user.id, "active"], - ) - .where(AsyncOrder.c.id == order.id) - .all() - ) - - assert len(results) >= 1 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py deleted file mode 100644 index 46f6cf42..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py +++ /dev/null @@ -1,178 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_join_right_table_resolution.py -""" -Unit tests for JoinQueryMixin._resolve_right_table / AsyncJoinQueryMixin._resolve_right_table. - -These tests lock in the alias non-contamination contract for join targets: -passing a NamedRelationRef or JoinClause with an alias must return a NEW -aliased copy and never mutate the caller's expression (regression tests for -the ``as_()`` copy semantics and the ``issubclass`` model-class guard). -""" - -from types import SimpleNamespace - -import pytest - -from rhosocial.activerecord.backend.expression import JoinExpression -from rhosocial.activerecord.backend.expression.sources import NamedRelationRef -from rhosocial.activerecord.backend.expression.query_parts import JoinClause -from rhosocial.activerecord.backend.impl.dummy.dialect import DummyDialect -from rhosocial.activerecord.query.join import JoinQueryMixin -from rhosocial.activerecord.query.async_join import AsyncJoinQueryMixin -from rhosocial.activerecord.backend.expression.objects import Table - - -@pytest.fixture -def dummy_dialect(): - """Provides a DummyDialect instance that supports all features.""" - return DummyDialect() - - -def _make_join_expression(dialect: DummyDialect) -> JoinClause: - """Build a minimal valid JoinClause for alias tests.""" - return JoinClause( - dialect, - left_table=NamedRelationRef(dialect, Table(dialect, "users")), - right_table=NamedRelationRef(dialect, Table(dialect, "items")), - join_type="INNER JOIN", - using=["id"], - ) - - -class _SyncJoinQueryStub(JoinQueryMixin): - """Minimal query double exposing only what JoinQueryMixin needs.""" - - def __init__(self, dialect: DummyDialect): - self._dialect = dialect - self.join_clause = None - - def backend(self): - return SimpleNamespace(dialect=self._dialect) - - -class _AsyncJoinQueryStub(AsyncJoinQueryMixin): - """Minimal async query double exposing only what AsyncJoinQueryMixin needs.""" - - def __init__(self, dialect: DummyDialect): - self._dialect = dialect - self.join_clause = None - - def backend(self): - return SimpleNamespace(dialect=self._dialect) - - -class TestSyncResolveRightTable: - """Sync _resolve_right_table alias resolution tests.""" - - def test_table_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): - table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) - query = _SyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table(table, alias="o") - - assert resolved is not table - assert isinstance(resolved, (NamedRelationRef, JoinExpression)) - assert resolved.alias == "o" - assert table.alias is None - assert resolved.to_sql()[0] == '"orders" AS "o"' - assert table.to_sql()[0] == '"orders"' - - def test_same_table_reused_with_two_aliases(self, dummy_dialect: DummyDialect): - """Self-join style reuse: one NamedRelationRef, two independent aliases.""" - table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) - query = _SyncJoinQueryStub(dummy_dialect) - - first = query._resolve_right_table(table, alias="o1") - second = query._resolve_right_table(table, alias="o2") - - assert first is not second - assert first.alias == "o1" - assert second.alias == "o2" - assert table.alias is None - - def test_table_expression_without_alias_is_passthrough(self, dummy_dialect: DummyDialect): - table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) - query = _SyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table(table, alias=None) - - assert resolved is table - - def test_join_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): - join_expr = _make_join_expression(dummy_dialect) - query = _SyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table(join_expr, alias="jx") - - assert resolved is not join_expr - assert isinstance(resolved, (NamedRelationRef, JoinExpression)) - assert resolved.alias == "jx" - assert join_expr.alias is None - assert resolved.to_sql()[0].endswith('AS "jx"') - - def test_string_target_with_alias(self, dummy_dialect: DummyDialect): - query = _SyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table("orders", alias="o") - - assert isinstance(resolved, NamedRelationRef) - assert resolved.alias == "o" - - def test_unsupported_type_raises_type_error(self, dummy_dialect: DummyDialect): - query = _SyncJoinQueryStub(dummy_dialect) - - with pytest.raises(TypeError): - query._resolve_right_table(42, alias="o") # type: ignore[arg-type] - - -class TestAsyncResolveRightTable: - """Async _resolve_right_table alias resolution tests.""" - - def test_table_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): - table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) - query = _AsyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table(table, alias="o") - - assert resolved is not table - assert isinstance(resolved, (NamedRelationRef, JoinExpression)) - assert resolved.alias == "o" - assert table.alias is None - assert resolved.to_sql()[0] == '"orders" AS "o"' - assert table.to_sql()[0] == '"orders"' - - def test_same_table_reused_with_two_aliases(self, dummy_dialect: DummyDialect): - table = NamedRelationRef(dummy_dialect, Table(dummy_dialect, "orders")) - query = _AsyncJoinQueryStub(dummy_dialect) - - first = query._resolve_right_table(table, alias="o1") - second = query._resolve_right_table(table, alias="o2") - - assert first is not second - assert first.alias == "o1" - assert second.alias == "o2" - assert table.alias is None - - def test_join_expression_with_alias_not_mutated(self, dummy_dialect: DummyDialect): - join_expr = _make_join_expression(dummy_dialect) - query = _AsyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table(join_expr, alias="jx") - - assert resolved is not join_expr - assert isinstance(resolved, (NamedRelationRef, JoinExpression)) - assert resolved.alias == "jx" - assert join_expr.alias is None - - def test_string_target_with_alias(self, dummy_dialect: DummyDialect): - query = _AsyncJoinQueryStub(dummy_dialect) - - resolved = query._resolve_right_table("orders", alias="o") - - assert isinstance(resolved, NamedRelationRef) - assert resolved.alias == "o" - - def test_unsupported_type_raises_type_error(self, dummy_dialect: DummyDialect): - query = _AsyncJoinQueryStub(dummy_dialect) - - with pytest.raises(TypeError): - query._resolve_right_table(42, alias="o") # type: ignore[arg-type] diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py deleted file mode 100644 index 74b202df..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_async_descriptors.py +++ /dev/null @@ -1,242 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_async_descriptors.py -""" -Async relation descriptor tests. - -These tests mirror the sync descriptor tests but use async versions -to ensure sync/async parity. -""" - -import pytest -from typing import ClassVar - -from pydantic import BaseModel - -from rhosocial.activerecord.relation.base import RelationManagementMixin -from rhosocial.activerecord.relation.async_descriptors import ( - AsyncBelongsTo, - AsyncHasOne, - AsyncHasMany, -) -from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache - - -class AsyncAuthor(RelationManagementMixin, BaseModel): - id: int - name: str - books: ClassVar[AsyncHasMany["AsyncBook"]] = AsyncHasMany(foreign_key="author_id", inverse_of="author") - - -class AsyncBook(RelationManagementMixin, BaseModel): - id: int - title: str - author_id: int - author: ClassVar[AsyncBelongsTo["AsyncAuthor"]] = AsyncBelongsTo(foreign_key="author_id", inverse_of="books") - - -class AsyncProfile(RelationManagementMixin, BaseModel): - id: int - bio: str - author_id: int - author: ClassVar[AsyncBelongsTo["AsyncAuthor"]] = AsyncBelongsTo(foreign_key="author_id", inverse_of="profile") - - -class AsyncAuthorWithProfile(RelationManagementMixin, BaseModel): - id: int - name: str - books: ClassVar[AsyncHasMany["AsyncBook"]] = AsyncHasMany(foreign_key="author_id", inverse_of="author") - profile: ClassVar[AsyncHasOne["AsyncProfile"]] = AsyncHasOne(foreign_key="author_id", inverse_of="author") - - -class TestAsyncRelationDescriptors: - """Tests for async relation descriptor functionality.""" - - def test_async_belongs_to_descriptor(self): - """Test AsyncBelongsTo descriptor functionality.""" - relation = AsyncBook.get_relation("author") - assert isinstance(relation, AsyncBelongsTo) - assert relation.foreign_key == "author_id" - assert relation.inverse_of == "books" - - def test_async_has_many_descriptor(self): - """Test AsyncHasMany descriptor functionality.""" - relation = AsyncAuthor.get_relation("books") - assert isinstance(relation, AsyncHasMany) - assert relation.foreign_key == "author_id" - assert relation.inverse_of == "author" - - def test_async_has_one_descriptor(self): - """Test AsyncHasOne descriptor functionality.""" - relation = AsyncAuthorWithProfile.get_relation("profile") - assert isinstance(relation, AsyncHasOne) - assert relation.foreign_key == "author_id" - assert relation.inverse_of == "author" - - def test_async_descriptor_set_name_callback(self): - """Test that __set_name__ is called on descriptor assignment.""" - - class AsyncTestModel(RelationManagementMixin, BaseModel): - id: int - items: ClassVar[AsyncHasMany["AsyncOtherItem"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") - - class AsyncOtherItem(RelationManagementMixin, BaseModel): - id: int - test_id: int - test: ClassVar[AsyncBelongsTo["AsyncTestModel"]] = AsyncBelongsTo(foreign_key="test_id", inverse_of="items") - - relation = AsyncTestModel.get_relation("items") - assert relation.name == "items" - assert relation._owner == AsyncTestModel - - def test_async_descriptor_invalid_foreign_key_type(self): - """Test that non-string foreign_key raises TypeError.""" - with pytest.raises(TypeError) as exc_info: - - class BadModel(RelationManagementMixin, BaseModel): - id: int - rel: ClassVar[AsyncHasMany] = AsyncHasMany(foreign_key=123, inverse_of="test") - - assert "foreign_key must be a string" in str(exc_info.value) - - def test_async_descriptor_invalid_cache_config(self): - """Test that non-CacheConfig cache_config raises TypeError at class definition.""" - - # This test verifies that invalid cache_config type would raise TypeError - # The actual error is raised at class definition time by Pydantic validation - # We just verify the descriptor accepts cache_config parameter - class AsyncModelWithCache(RelationManagementMixin, BaseModel): - id: int - rel: ClassVar[AsyncHasMany["AsyncTargetForCache"]] = AsyncHasMany( - foreign_key="test_id", inverse_of="test", cache_config=CacheConfig(ttl=60) - ) - - class AsyncTargetForCache(RelationManagementMixin, BaseModel): - id: int - test_id: int - test: ClassVar[AsyncBelongsTo["AsyncModelWithCache"]] = AsyncBelongsTo( - foreign_key="test_id", inverse_of="rel" - ) - - relation = AsyncModelWithCache.get_relation("rel") - assert relation._cache_config.ttl == 60 - - def test_async_descriptor_get_relation(self): - """Test that get_relation returns the correct descriptor.""" - relation = AsyncAuthor.get_relation("books") - assert relation is not None - assert isinstance(relation, AsyncHasMany) - - def test_async_descriptor_get_relations(self): - """Test that get_relations returns all relations.""" - relations = AsyncAuthor.get_relations() - assert "books" in relations - - def test_async_descriptor_unknown_relation(self): - """Test that get_relation returns None for unknown relation.""" - relation = AsyncAuthor.get_relation("unknown_relation") - assert relation is None - - -class TestAsyncRelationCache: - """Tests for async relation caching behavior.""" - - def test_async_instance_cache_set_get(self): - """Test basic async instance cache set and get.""" - - class AsyncTestModel(RelationManagementMixin, BaseModel): - id: int - rel: ClassVar[AsyncHasMany["AsyncTarget"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") - - class AsyncTarget(RelationManagementMixin, BaseModel): - id: int - test_id: int - test: ClassVar[AsyncBelongsTo["AsyncTestModel"]] = AsyncBelongsTo(foreign_key="test_id", inverse_of="rel") - - instance = AsyncTestModel(id=1) - config = CacheConfig(enabled=True) - - InstanceCache.set(instance, "rel", [{"id": 1, "name": "test"}], config) - - result = InstanceCache.get(instance, "rel", config) - assert result == [{"id": 1, "name": "test"}] - - def test_async_instance_cache_disabled(self): - """Test that caching is disabled when config.enabled is False.""" - - class AsyncTestModel(RelationManagementMixin, BaseModel): - id: int - rel: ClassVar[AsyncHasMany["AsyncTarget"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") - - class AsyncTarget(RelationManagementMixin, BaseModel): - id: int - test_id: int - - instance = AsyncTestModel(id=1) - config = CacheConfig(enabled=False) - - InstanceCache.set(instance, "rel", [{"id": 1}], config) - - result = InstanceCache.get(instance, "rel", config) - assert result is None - - def test_async_instance_cache_delete(self): - """Test async instance cache deletion.""" - - class AsyncTestModel(RelationManagementMixin, BaseModel): - id: int - rel: ClassVar[AsyncHasMany["AsyncTarget"]] = AsyncHasMany(foreign_key="test_id", inverse_of="test") - - class AsyncTarget(RelationManagementMixin, BaseModel): - id: int - test_id: int - - instance = AsyncTestModel(id=1) - config = CacheConfig() - - InstanceCache.set(instance, "rel", [{"id": 1}], config) - assert InstanceCache.get(instance, "rel", config) == [{"id": 1}] - - InstanceCache.delete(instance, "rel") - - assert InstanceCache.get(instance, "rel", config) is None - - -class TestAsyncRelationManagementMixin: - """Tests for async RelationManagementMixin functionality.""" - - def test_async_register_relation(self): - """Test registering async relation.""" - - class AsyncTestModel(RelationManagementMixin, BaseModel): - id: int - - from rhosocial.activerecord.relation.descriptors import RelationDescriptor - - descriptor = RelationDescriptor(foreign_key="test_id") - AsyncTestModel.register_relation("test_rel", descriptor) - - assert "test_rel" in AsyncTestModel.get_relations() - assert AsyncTestModel.get_relation("test_rel") == descriptor - - def test_async_clear_relation_cache(self): - """Test clearing async relation cache.""" - instance = AsyncAuthor(id=1, name="Test") - - InstanceCache.set(instance, "books", [{"id": 1}], CacheConfig()) - - assert InstanceCache.get(instance, "books", CacheConfig()) is not None - - instance.clear_relation_cache("books") - - assert InstanceCache.get(instance, "books", CacheConfig()) is None - - def test_async_clear_all_relations_cache(self): - """Test clearing all async relation caches.""" - instance = AsyncAuthor(id=1, name="Test") - - InstanceCache.set(instance, "books", [{"id": 1}], CacheConfig()) - - assert InstanceCache.get(instance, "books", CacheConfig()) is not None - - instance.clear_relation_cache() - - assert InstanceCache.get(instance, "books", CacheConfig()) is None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py deleted file mode 100644 index f173e2fe..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_batch_loading.py +++ /dev/null @@ -1,218 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_batch_loading.py -""" -Tests for batch loading behavior in relations. - -These tests cover the batch loading functionality which is critical for -avoiding N+1 query problems in python-activerecord. -""" - -import pytest -from typing import ClassVar, Any, Optional, List, Dict - -from pydantic import BaseModel - -from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache -from rhosocial.activerecord.relation.base import RelationManagementMixin -from rhosocial.activerecord.relation.descriptors import ( - HasMany, - BelongsTo, - HasOne, -) -from rhosocial.activerecord.relation.interfaces import IRelationLoader - - -class AuthorForBatch(RelationManagementMixin, BaseModel): - id: int - name: str - books: ClassVar[HasMany["BookForBatch"]] = HasMany(foreign_key="author_id", inverse_of="author") - - -class BookForBatch(RelationManagementMixin, BaseModel): - id: int - title: str - author_id: int - author: ClassVar[BelongsTo["AuthorForBatch"]] = BelongsTo(foreign_key="author_id", inverse_of="books") - - -class RecordingBatchLoader(IRelationLoader): - """Loader that records what instances were loaded.""" - - def __init__(self, return_value=None): - self.loaded_instances: List[Any] = [] - self.batch_loaded_instances: List[List[Any]] = [] - self.return_value = return_value or [{"id": 1, "title": "Test Book"}] - - def load(self, instance: Any) -> Optional[List[Any]]: - self.loaded_instances.append(instance) - return self.return_value - - def batch_load(self, instances: List[Any], base_query: Any) -> Dict[int, Any]: - self.batch_loaded_instances.append(instances) - return {id(inst): self.return_value for inst in instances} - - -class TestBatchLoading: - """Tests for relation batch loading functionality.""" - - @pytest.fixture - def loader(self): - return RecordingBatchLoader() - - def test_batch_load_called_with_instances(self): - """Test that batch_load receives the correct instances.""" - loader = RecordingBatchLoader() - relation = AuthorForBatch.get_relation("books") - relation._loader = loader - - author1 = AuthorForBatch(id=1, name="Author 1") - author2 = AuthorForBatch(id=2, name="Author 2") - - relation.batch_load([author1, author2], None) - - assert len(loader.batch_loaded_instances) == 1 - assert len(loader.batch_loaded_instances[0]) == 2 - assert author1 in loader.batch_loaded_instances[0] - assert author2 in loader.batch_loaded_instances[0] - - def test_batch_load_returns_dict(self): - """Test that batch_load returns a dict mapping instance IDs.""" - loader = RecordingBatchLoader() - relation = AuthorForBatch.get_relation("books") - relation._loader = loader - - author = AuthorForBatch(id=1, name="Author 1") - - result = relation.batch_load([author], None) - - assert isinstance(result, dict) - assert id(author) in result - - def test_cached_results_not_loaded_again(self): - """Test that cached results are not loaded again in batch.""" - RecordingBatchLoader() - relation = AuthorForBatch.get_relation("books") - relation._cache_config = CacheConfig() - - author1 = AuthorForBatch(id=1, name="Author 1") - author2 = AuthorForBatch(id=2, name="Author 2") - - InstanceCache.set(author1, "books", [{"id": 99, "title": "Cached"}], CacheConfig()) - - result = relation.batch_load([author1, author2], None) - - assert id(author1) in result - assert result[id(author1)][0]["id"] == 99 - - def test_batch_load_with_empty_list(self): - """Test batch_load with empty instances list.""" - loader = RecordingBatchLoader() - relation = AuthorForBatch.get_relation("books") - relation._loader = loader - - result = relation.batch_load([], None) - - assert result == {} - assert len(loader.batch_loaded_instances) == 0 - - def test_all_cached_no_batch_load(self): - """Test that if all instances are cached, batch_load is not called.""" - loader = RecordingBatchLoader() - relation = AuthorForBatch.get_relation("books") - relation._cache_config = CacheConfig() - - author1 = AuthorForBatch(id=1, name="Author 1") - author2 = AuthorForBatch(id=2, name="Author 2") - - InstanceCache.set(author1, "books", [{"id": 1, "title": "Book 1"}], CacheConfig()) - InstanceCache.set(author2, "books", [{"id": 2, "title": "Book 2"}], CacheConfig()) - - relation.batch_load([author1, author2], None) - - assert len(loader.batch_loaded_instances) == 0 - - def test_partial_cache_loads_remaining(self): - """Test that only uncached instances are loaded.""" - relation = AuthorForBatch.get_relation("books") - relation._loader = RecordingBatchLoader() - relation._cache_config = CacheConfig() - - author1 = AuthorForBatch(id=1, name="Author 1") - author2 = AuthorForBatch(id=2, name="Author 2") - - InstanceCache.set(author1, "books", [{"id": 1, "title": "Cached"}], CacheConfig()) - - result = relation.batch_load([author1, author2], None) - - assert id(author1) in result - assert result[id(author1)][0]["id"] == 1 - assert id(author2) in result - - -class TestBelongsToBatchLoading: - """Tests for BelongsTo batch loading.""" - - def test_belongs_to_batch_load(self): - """Test BelongsTo relation batch loading.""" - - class BatchLoader(IRelationLoader): - def load(self, instance: Any) -> Optional[Any]: - return {"id": instance.author_id, "name": f"Author {instance.author_id}"} - - def batch_load(self, instances: List[Any], base_query: Any) -> Dict[int, Any]: - {inst.author_id for inst in instances} - return {id(inst): {"id": inst.author_id, "name": f"Author {inst.author_id}"} for inst in instances} - - loader = BatchLoader() - relation = BookForBatch.get_relation("author") - relation._loader = loader - - book1 = BookForBatch(id=1, title="Book 1", author_id=1) - book2 = BookForBatch(id=2, title="Book 2", author_id=2) - - result = relation.batch_load([book1, book2], None) - - assert isinstance(result, dict) - assert id(book1) in result - assert id(book2) in result - - -class TestHasOneBatchLoading: - """Tests for HasOne batch loading.""" - - def test_has_one_batch_load(self): - """Test HasOne relation batch loading.""" - - class ProfileForHasOne(RelationManagementMixin, BaseModel): - id: int - bio: str - author_id: int - author: ClassVar[BelongsTo["AuthorForHasOne"]] = BelongsTo(foreign_key="author_id", inverse_of="profile") - - class AuthorForHasOne(RelationManagementMixin, BaseModel): - id: int - name: str - profile: ClassVar[HasOne["ProfileForHasOne"]] = HasOne(foreign_key="author_id", inverse_of="author") - - class HasOneBatchLoader(IRelationLoader): - def load(self, instance: Any) -> Optional[Any]: - return {"id": 1, "bio": "Bio", "author_id": instance.id} - - def batch_load(self, instances: List[Any], base_query: Any) -> Dict[int, Any]: - return { - id(inst): {"id": inst.id, "bio": f"Bio for {inst.name}", "author_id": inst.id} for inst in instances - } - - loader = HasOneBatchLoader() - relation = AuthorForHasOne.get_relation("profile") - relation._loader = loader - - author1 = AuthorForHasOne(id=1, name="Author 1") - author2 = AuthorForHasOne(id=2, name="Author 2") - - result = relation.batch_load([author1, author2], None) - - assert isinstance(result, dict) - assert id(author1) in result - assert id(author2) in result - assert result[id(author1)]["author_id"] == 1 - assert result[id(author2)]["author_id"] == 2 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py deleted file mode 100644 index bd7f2d47..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_result.py +++ /dev/null @@ -1,106 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_cache_result.py -""" -Tests for CacheResult dataclass and InstanceCache.get_with_meta(). - -Cache stampede protection and proactive refresh are intentionally -excluded from the framework. These tests verify the metadata-building -blocks that application code uses to implement its own strategy. -""" - - -from pydantic import BaseModel - -from rhosocial.activerecord.relation.cache import ( # noqa: E402 - CacheConfig, - CacheResult, - InstanceCache, -) - - -class TestCacheResult: - """CacheResult dataclass construction and defaults.""" - - def test_basic(self): - r = CacheResult(value="hello", age=10.0, origin="box-a", ttl=300) - assert r.value == "hello" - assert r.age == 10.0 - assert r.origin == "box-a" - assert r.ttl == 300 - - def test_defaults(self): - r = CacheResult(value=42) - assert r.age == 0.0 - assert r.origin is None - assert r.ttl is None - - def test_various_types(self): - r = CacheResult(value=[1, 2, 3]) - assert r.value == [1, 2, 3] - - r = CacheResult(value={"key": "val"}) - assert r.value == {"key": "val"} - - r = CacheResult(value=None) - assert r.value is None - - -class TestGetWithMeta: - """InstanceCache.get_with_meta() returns CacheResult with metadata.""" - - class _Model(BaseModel): - id: int - - def test_hit(self): - inst = self._Model(id=1) - cfg = CacheConfig(ttl=300) - InstanceCache.set(inst, "posts", ["p1", "p2"], cfg) - r = InstanceCache.get_with_meta(inst, "posts", cfg) - assert r is not None - assert r.value == ["p1", "p2"] - assert r.ttl == 300 - assert r.origin is None # InMemoryCache has no origin - assert r.age == 0.0 - - def test_miss(self): - inst = self._Model(id=2) - cfg = CacheConfig(ttl=300) - r = InstanceCache.get_with_meta(inst, "nonexistent", cfg) - assert r is None - - def test_disabled(self): - inst = self._Model(id=3) - cfg = CacheConfig(enabled=False) - InstanceCache.set(inst, "posts", ["p1"], CacheConfig()) - r = InstanceCache.get_with_meta(inst, "posts", cfg) - assert r is None - - def test_ttl_none(self): - inst = self._Model(id=4) - cfg = CacheConfig(ttl=None) - InstanceCache.set(inst, "data", "xyz", cfg) - r = InstanceCache.get_with_meta(inst, "data", cfg) - assert r is not None - assert r.value == "xyz" - assert r.ttl is None - - def test_origin_reflects_backend(self): - """get_with_meta origin matches the active backend origin.""" - orig_backend = InstanceCache._backend - try: - from rhosocial.activerecord.relation.cache_backends import InMemoryCache - - class CustomOrigin(InMemoryCache): - @property - def origin(self): - return "custom-node" - - InstanceCache.set_backend(CustomOrigin()) - - inst = self._Model(id=5) - cfg = CacheConfig(ttl=60) - InstanceCache.set(inst, "rel", "val", cfg) - r = InstanceCache.get_with_meta(inst, "rel", cfg) - assert r is not None - assert r.origin == "custom-node" - finally: - InstanceCache.set_backend(orig_backend) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py deleted file mode 100644 index f2c3dec1..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_cache_serialization.py +++ /dev/null @@ -1,462 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_cache_serialization.py -""" -Comprehensive round-trip tests for cache serialization. - -Covers JSON (default), msgpack (when available), and pickle (UNSAFE) -serializers with simple values, complex Python objects, edge cases, -and large content from the testsuite sample files. -""" - -import json -import math -import os -from datetime import date, datetime, time, timedelta -from enum import Enum, auto -from typing import Any, Dict, List, Optional - -import pytest - -from rhosocial.activerecord.relation.cache_backends._protocol import CacheSerializer # noqa: E402 - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - -_SAMPLE_DIR = None - - -def _find_samples() -> Optional[str]: - """Locate the testsuite sample directory.""" - global _SAMPLE_DIR - if _SAMPLE_DIR is not None: - return _SAMPLE_DIR - try: - import rhosocial.activerecord.testsuite as _ts - - base = os.path.dirname(_ts.__file__) - for attempt in [ - os.path.join(base, "feature", "query", "samples"), - os.path.join(base, "..", "..", "..", "..", "testsuite", "feature", "query", "samples"), - ]: - path = os.path.abspath(attempt) - if os.path.isdir(path): - _SAMPLE_DIR = path - return _SAMPLE_DIR - except Exception: - pass - return None - - -def _load_sample(name: str) -> str: - d = _find_samples() - if d is None: - pytest.skip("testsuite sample directory not found") - path = os.path.join(d, name) - if not os.path.exists(path): - pytest.skip(f"sample file not found: {path}") - with open(path, "r", encoding="utf-8") as f: - return f.read() - - -# --------------------------------------------------------------------------- -# Test data -# --------------------------------------------------------------------------- - - -class Color(Enum): - RED = auto() - GREEN = auto() - BLUE = auto() - - -SIMPLE_VALUES: List[Any] = [ - "hello", - "", - 0, - 1, - -1, - 3.14, - True, - False, - None, - [], - {}, - [1, 2, 3], - {"a": 1, "b": 2}, -] - -COMPLEX_VALUES: List[Any] = [ - {"nested": {"deeply": [1, [2, [3]]], "key": "val"}}, - [{"id": i, "name": f"Item {i}"} for i in range(100)], - {"mixed": [1, "two", 3.0, True, None, [1, 2], {"k": "v"}]}, - {"empty_nested": {"a": {}, "b": [], "c": {"d": {}}}}, -] - -EXTENDED_VALUES: List[Any] = [ - datetime(2026, 6, 2, 14, 30, 0, 123456), - date(2026, 6, 2), - time(14, 30, 0, 123456), - timedelta(days=7, hours=3, minutes=15), - Color.RED, - bytes([0x00, 0xFF, 0xAB, 0xCD]), - {1, 2, 3, 4, 5}, - complex(3, 4), - range(0, 10, 2), - {"dt": datetime.now(), "color": Color.BLUE, "data": bytes([1, 2, 3])}, - [datetime(2026, 1, 1), timedelta(hours=1), Color.GREEN], -] - -FLOAT_EPS = 1e-9 - - -# --------------------------------------------------------------------------- -# Serializer fixtures -# --------------------------------------------------------------------------- - - -@pytest.fixture(params=["json", "msgpack", "pickle"]) -def serializer(request) -> CacheSerializer: - fmt = request.param - if fmt == "msgpack": - try: - import msgpack # noqa: F401 - except ImportError: - pytest.skip("msgpack not installed") - return None - return CacheSerializer(format=fmt) - - -@pytest.fixture -def json_serializer() -> CacheSerializer: - return CacheSerializer(format="json") - - -@pytest.fixture -def pickle_serializer() -> CacheSerializer: - return CacheSerializer(format="pickle") - - -# --------------------------------------------------------------------------- -# Round-trip tests -# --------------------------------------------------------------------------- - - -class TestCacheSerializerBasic: - """Basic values round-trip through all serializer formats.""" - - @pytest.mark.parametrize("value", SIMPLE_VALUES) - def test_simple(self, serializer, value): - data = serializer.serialize(value) - restored = serializer.deserialize(data) - assert restored == value - assert type(restored) is type(value) - - def test_list_of_strings(self, serializer): - value = ["a" * 100] * 1000 - data = serializer.serialize(value) - restored = serializer.deserialize(data) - assert restored == value - assert len(restored) == 1000 - - -class TestCacheSerializerComplex: - """Complex nested values round-trip.""" - - @pytest.mark.parametrize("value", COMPLEX_VALUES) - def test_complex(self, serializer, value): - data = serializer.serialize(value) - restored = serializer.deserialize(data) - assert restored == value - - def test_large_dict(self, serializer): - value = {f"key_{i}": f"value_{i}" for i in range(5000)} - data = serializer.serialize(value) - restored = serializer.deserialize(data) - assert restored == value - assert len(restored) == 5000 - - -class TestCacheSerializerExtended: - """Extended types (datetime, Enum, bytes, etc.) through JSON (and msgpack).""" - - def _roundtrip_json(self, value): - ser = CacheSerializer(format="json") - data = ser.serialize(value) - return ser.deserialize(data) - - def test_datetime(self): - v = datetime(2026, 6, 2, 14, 30, 0, 123456) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "datetime" - assert restored["value"] == v.isoformat() - - def test_date(self): - v = date(2026, 6, 2) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "datetime" - assert restored["value"] == v.isoformat() - - def test_time(self): - v = time(14, 30, 0, 123456) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "time" - assert restored["value"] == v.isoformat() - - def test_timedelta(self): - v = timedelta(days=7, hours=3, minutes=15) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "timedelta" - assert isinstance(restored["value"], float) - assert abs(restored["value"] - v.total_seconds()) < FLOAT_EPS - - def test_enum(self): - v = Color.RED - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "enum" - assert restored["value"] == "RED" - - def test_bytes(self): - v = bytes([0x00, 0xFF, 0xAB, 0xCD]) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "bytes" - assert bytes.fromhex(restored["value"]) == v - - def test_set(self): - v = {1, 2, 3, 4, 5} - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "set" - assert set(restored["value"]) == v - - def test_complex_number(self): - v = complex(3, 4) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "complex" - assert restored["value"] == [3.0, 4.0] - - def test_range(self): - v = range(0, 10, 2) - restored = self._roundtrip_json(v) - assert isinstance(restored, dict) - assert restored["__type__"] == "range" - assert restored["value"] == [0, 10, 2] - - -class TestCacheSerializerMsgpackExtended: - """Extended types through msgpack (native support for bytes, etc.).""" - - @pytest.fixture - def msgpack_ser(self): - try: - import msgpack # noqa: F401 - except ImportError: - pytest.skip("msgpack not installed") - return CacheSerializer(format="msgpack") - - def test_bytes(self, msgpack_ser): - v = bytes([0x00, 0xFF, 0xAB]) - restored = msgpack_ser.deserialize(msgpack_ser.serialize(v)) - assert restored == v - - def test_datetime(self, msgpack_ser): - v = datetime(2026, 6, 2, 14, 30, 0) - restored = msgpack_ser.deserialize(msgpack_ser.serialize(v)) - # msgpack does not preserve datetime natively — it's treated as string - assert isinstance(restored, str) - - def test_set(self, msgpack_ser): - v = {1, 2, 3} - data = msgpack_ser.serialize(v) - with pytest.raises(TypeError): - msgpack_ser.deserialize(data) - - def test_enum(self, msgpack_ser): - v = Color.GREEN - data = msgpack_ser.serialize(v) - with pytest.raises(TypeError): - msgpack_ser.deserialize(data) - - -class TestCacheSerializerLargeContent: - """Large content round-trip using testsuite sample files.""" - - SAMPLE_FILES = [ - "jsonplaceholder_posts.json", - "python_home.html", - "plant_catalog.xml", - "unicode_multilingual.html", - "unicode_multilingual.json", - "unicode_multilingual.xml", - ] - - @pytest.mark.parametrize("filename", SAMPLE_FILES) - def test_large_content_json(self, json_serializer, filename): - content = _load_sample(filename) - data = json_serializer.serialize(content) - restored = json_serializer.deserialize(data) - assert restored == content - assert isinstance(restored, str) - assert len(restored) == len(content) - - @pytest.mark.parametrize("filename", SAMPLE_FILES) - def test_large_content_pickle(self, pickle_serializer, filename): - content = _load_sample(filename) - data = pickle_serializer.serialize(content) - restored = pickle_serializer.deserialize(data) - assert restored == content - - def test_json_placeholder_structure(self, json_serializer): - """Load a JSON file as dict, serialize and restore via JSON serializer.""" - content = _load_sample("jsonplaceholder_posts.json") - parsed = json.loads(content) - data = json_serializer.serialize(parsed) - restored = json_serializer.deserialize(data) - assert restored == parsed - assert len(restored) == len(parsed) - assert isinstance(restored, list) - - def test_multilingual_json_structure(self, json_serializer): - """Multilingual JSON with Unicode content.""" - content = _load_sample("unicode_multilingual.json") - parsed = json.loads(content) - data = json_serializer.serialize(parsed) - restored = json_serializer.deserialize(data) - assert restored == parsed - - -class TestCacheSerializerEdgeCases: - """Edge cases and error handling.""" - - def test_empty_string(self, serializer): - v = "" - data = serializer.serialize(v) - assert serializer.deserialize(data) == v - - def test_very_long_string(self, serializer): - v = "x" * 100_000 - data = serializer.serialize(v) - restored = serializer.deserialize(data) - assert restored == v - assert len(restored) == 100_000 - - def test_none_value(self, serializer): - data = serializer.serialize(None) - assert serializer.deserialize(data) is None - - def test_boolean_values(self, serializer): - for v in [True, False]: - data = serializer.serialize(v) - restored = serializer.deserialize(data) - assert restored is v or restored == v - assert isinstance(restored, bool) - - def test_integer_edge_cases(self, serializer): - for v in [0, 1, -1, 2**31 - 1, -(2**31), 2**63 - 1, -(2**63)]: - data = serializer.serialize(v) - restored = serializer.deserialize(data) - assert restored == v - assert type(restored) is type(v) - - def test_float_edge_cases(self, serializer): - for v in [0.0, -0.0, 3.141592653589793, float("inf"), float("-inf"), 1.7976931348623157e308, 5e-324]: - if math.isnan(v): - continue # NaN comparison is tricky - data = serializer.serialize(v) - restored = serializer.deserialize(data) - if isinstance(restored, float) and math.isnan(v): - assert math.isnan(restored) - else: - assert restored == v - - def test_deeply_nested_structure(self, serializer): - v = {"level1": {"level2": {"level3": {"level4": {"level5": "deep"}}}}} - data = serializer.serialize(v) - restored = serializer.deserialize(data) - assert restored == v - - def test_large_list_of_small_dicts(self, serializer): - v = [{"id": i, "val": str(i)} for i in range(10000)] - data = serializer.serialize(v) - restored = serializer.deserialize(data) - assert restored == v - assert len(restored) == 10000 - - -class TestCacheSerializerInvalidInput: - """Error handling for invalid/unsupported inputs.""" - - def test_unknown_format(self): - with pytest.raises(ValueError, match="Unknown serializer format"): - CacheSerializer(format="xml") - - def test_msgpack_not_installed(self): - - # Simulate missing msgpack by checking if we can bypass it - try: - import msgpack # noqa: F401 - - pytest.skip("msgpack is installed, can't test missing case") - except ImportError: - with pytest.raises(ImportError, match="msgpack"): - CacheSerializer(format="msgpack") - - def test_unserializable_object_json(self): - """JSON serializer can't handle arbitrary objects.""" - ser = CacheSerializer(format="json") - - class Unserializable: - pass - - with pytest.raises(TypeError): - ser.serialize(Unserializable()) - - def test_circular_reference_json(self): - """JSON serializer should raise on circular refs.""" - ser = CacheSerializer(format="json") - v: Dict[str, Any] = {"key": None} - v["key"] = v - with pytest.raises((ValueError, TypeError)): - ser.serialize(v) - - def test_pickle_serializer_warning(self): - with pytest.warns(UserWarning, match="unsafe"): - CacheSerializer(format="pickle") - - -class TestCacheSerializerCrossFormat: - """Data serialized in one format should not be expected to - deserialize correctly in another (negative testing).""" - - def test_json_data_cannot_be_read_by_pickle(self): - ser_json = CacheSerializer(format="json") - data = ser_json.serialize("hello") - ser_pickle = CacheSerializer(format="pickle") - with pytest.raises(Exception): # noqa: B017 - ser_pickle.deserialize(data) - - def test_pickle_data_cannot_be_read_by_json(self): - ser_pickle = CacheSerializer(format="pickle") - data = ser_pickle.serialize("hello") - ser_json = CacheSerializer(format="json") - with pytest.raises(Exception): # noqa: B017 - ser_json.deserialize(data) - - -class TestCacheSerializerFormatProperty: - """Serializer exposes its format.""" - - def test_format_property(self): - assert CacheSerializer(format="json").format == "json" - assert CacheSerializer(format="pickle").format == "pickle" - assert CacheSerializer().format == "json" - - def test_case_insensitive(self): - assert CacheSerializer(format="JSON").format == "json" - assert CacheSerializer(format="Pickle").format == "pickle" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py deleted file mode 100644 index c34518cb..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_coverage.py +++ /dev/null @@ -1,650 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_descriptor_coverage.py -""" -Targeted tests to cover uncovered code paths in descriptors.py and async_descriptors.py. -Also identifies dead code. -""" - -from typing import ClassVar, ForwardRef - -import pytest -from pydantic import BaseModel - -from rhosocial.activerecord.relation.base import RelationManagementMixin -from rhosocial.activerecord.relation.descriptors import ( - BelongsTo, - HasOne, - HasMany, - DefaultIRelationLoader, -) -from rhosocial.activerecord.relation.type_resolver import evaluate_annotation -from rhosocial.activerecord.relation.async_descriptors import ( - AsyncBelongsTo, - AsyncHasMany, - AsyncDefaultRelationLoader, -) -from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache -from rhosocial.activerecord.relation.interfaces import IRelationLoader - - -# ============================================================================== -# 1. __init__ validation paths -# ============================================================================== - - -class TestDescriptorInit: - """Cover __init__ validation branches.""" - - def test_sync_invalid_foreign_key_type(self): - with pytest.raises(TypeError, match="foreign_key must be a string"): - BelongsTo(foreign_key=123) - - def test_sync_invalid_cache_config_type(self): - with pytest.raises(TypeError, match="cache_config must be instance of CacheConfig"): - BelongsTo(foreign_key="x_id", cache_config="not_a_cache_config") # type: ignore - - def test_async_invalid_foreign_key_type(self): - with pytest.raises(TypeError, match="foreign_key must be a string"): - AsyncBelongsTo(foreign_key=123) - - def test_async_invalid_cache_config_type(self): - with pytest.raises(TypeError, match="cache_config must be instance of CacheConfig"): - AsyncBelongsTo(foreign_key="x_id", cache_config="not_a_cache_config") # type: ignore - - -# ============================================================================== -# 2. __get__ class-level access -# ============================================================================== - - -class TestDescriptorGetClassLevel: - """Cover __get__ with instance=None path.""" - - def test_sync_get_on_class_returns_self(self): - class Dept(RelationManagementMixin, BaseModel): - id: int - name: str - employees: ClassVar[HasMany["Emp"]] = HasMany(foreign_key="dept_id", inverse_of="department") - - class Emp(RelationManagementMixin, BaseModel): - id: int - dept_id: int - department: ClassVar[BelongsTo["Dept"]] = BelongsTo(foreign_key="dept_id", inverse_of="employees") - - descriptor = Dept.__dict__["employees"] - result = descriptor.__get__(None, Dept) - assert result is descriptor - - def test_async_get_on_class_returns_self(self): - class Dept(RelationManagementMixin, BaseModel): - id: int - name: str - employees: ClassVar[AsyncHasMany["Emp"]] = AsyncHasMany(foreign_key="dept_id", inverse_of="department") - - class Emp(RelationManagementMixin, BaseModel): - id: int - dept_id: int - department: ClassVar[AsyncBelongsTo["Dept"]] = AsyncBelongsTo(foreign_key="dept_id", inverse_of="employees") - - descriptor = Dept.__dict__["employees"] - result = descriptor.__get__(None, Dept) - assert result is descriptor - - -# ============================================================================== -# 3. __delete__ -# ============================================================================== - - -class TestDescriptorDelete: - """Cover __delete__ path.""" - - def test_sync_delete_clears_cache(self): - class Owner(RelationManagementMixin, BaseModel): - id: int - items: ClassVar[HasMany["Item"]] = HasMany(foreign_key="owner_id", inverse_of="owner") - - class Item(RelationManagementMixin, BaseModel): - id: int - owner_id: int - owner: ClassVar[BelongsTo["Owner"]] = BelongsTo(foreign_key="owner_id", inverse_of="items") - - instance = Owner(id=1) - InstanceCache.set(instance, "items", [Item(id=1, owner_id=1)], CacheConfig()) - assert InstanceCache.get(instance, "items", CacheConfig()) is not None - - descriptor = Owner.__dict__["items"] - descriptor.__delete__(instance) - assert InstanceCache.get(instance, "items", CacheConfig()) is None - - def test_async_delete_clears_cache(self): - class Owner(RelationManagementMixin, BaseModel): - id: int - items: ClassVar[AsyncHasMany["Item"]] = AsyncHasMany(foreign_key="owner_id", inverse_of="owner") - - class Item(RelationManagementMixin, BaseModel): - id: int - owner_id: int - owner: ClassVar[AsyncBelongsTo["Owner"]] = AsyncBelongsTo(foreign_key="owner_id", inverse_of="items") - - instance = Owner(id=1) - InstanceCache.set(instance, "items", [Item(id=1, owner_id=1)], CacheConfig()) - assert InstanceCache.get(instance, "items", CacheConfig()) is not None - - descriptor = Owner.__dict__["items"] - descriptor.__delete__(instance) - assert InstanceCache.get(instance, "items", CacheConfig()) is None - - -# ============================================================================== -# 4. _load_relation paths (cache hit, loader error) -# ============================================================================== - - -class FakeSyncLoader(IRelationLoader): - def __init__(self, return_value=None, raise_error=False): - self.return_value = return_value - self.raise_error = raise_error - self.load_called = False - - def load(self, instance): - self.load_called = True - if self.raise_error: - raise RuntimeError("loader failed") - return self.return_value - - def batch_load(self, instances, base_query): - return {id(instances[0]): self.return_value} - - -class TestLoadRelation: - """Cover _load_relation cache hit, miss, and error paths.""" - - def test_sync_load_cache_hit(self): - data = {"id": 1} - loader = FakeSyncLoader(return_value=data) - - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id", loader=loader) - - instance = Source(id=1, target_id=1) - # Pre-set cache - InstanceCache.set(instance, "target", data, CacheConfig()) - # Access via descriptor - result = instance.target() - assert result == data - assert not loader.load_called - - def test_sync_load_cache_miss(self): - class Target(RelationManagementMixin, BaseModel): - id: int - name: str - - data = Target(id=1, name="test") - loader = FakeSyncLoader(return_value=data) - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id", loader=loader) - - instance = Source(id=1, target_id=1) - result = instance.target() - assert result == data - assert loader.load_called - - def test_sync_load_loader_error_returns_none(self): - loader = FakeSyncLoader(raise_error=True) - - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id", loader=loader) - - instance = Source(id=1, target_id=1) - result = instance.target() - assert result is None - - @pytest.mark.asyncio - async def test_async_load_cache_hit(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - data = {"id": 1} - loader = FakeSyncLoader(return_value=data) - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id", loader=loader) - - instance = Source(id=1, target_id=1) - InstanceCache.set(instance, "target", data, CacheConfig()) - result = await instance.target() - assert result == data - - -# ============================================================================== -# 5. _create_relation_method with args — exercises dead self._query path -# ============================================================================== - - -class TestCreateRelationMethodNoArgs: - """_create_relation_method no longer accepts args (dead code removed).""" - - def test_sync_relation_method_rejects_args(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") - - instance = Source(id=1, target_id=1) - method = Source.target.__get__(instance, Source) - with pytest.raises(TypeError): - method(some_arg="value") - - @pytest.mark.asyncio - async def test_async_relation_method_rejects_args(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") - - instance = Source(id=1, target_id=1) - method = Source.target.__get__(instance, Source) - with pytest.raises(TypeError): - await method(some_arg="value") - - -# ============================================================================== -# 6. _evaluate_forward_ref -# ============================================================================== - - -class TestEvaluateForwardRef: - """Cover evaluate_annotation function from type_resolver.""" - - def test_evaluate_string_ref(self): - class DummyModel(RelationManagementMixin, BaseModel): - id: int - - result = evaluate_annotation("DummyModel", DummyModel) - assert result is DummyModel - - def test_evaluate_forward_ref_direct(self): - class DummyModel(RelationManagementMixin, BaseModel): - id: int - - ref = ForwardRef("DummyModel") - result = evaluate_annotation(ref, DummyModel) - assert result is DummyModel - - def test_evaluate_forward_ref_with_module_scope(self): - """Test that forward ref resolves using module globals.""" - - class DummyModel(RelationManagementMixin, BaseModel): - id: int - - ref = ForwardRef("BaseModel") - result = evaluate_annotation(ref, DummyModel) - assert result is BaseModel - - -# ============================================================================== -# 7. RelationshipValidator / AsyncRelationshipValidator -# ============================================================================== - - -class TestRelationshipValidatorPaths: - """Cover RelationshipValidator validation branches.""" - - def test_valid_belongs_to_has_many_pair(self): - class Dept(RelationManagementMixin, BaseModel): - id: int - employees: ClassVar[HasMany["Emp"]] = HasMany(foreign_key="dept_id", inverse_of="department") - - class Emp(RelationManagementMixin, BaseModel): - id: int - dept_id: int - department: ClassVar[BelongsTo["Dept"]] = BelongsTo(foreign_key="dept_id", inverse_of="employees") - - # Trigger validation by accessing relation - Emp(id=1, dept_id=1).department() - - def test_valid_belongs_to_has_one_pair(self): - class User(RelationManagementMixin, BaseModel): - id: int - profile: ClassVar[HasOne["Profile"]] = HasOne(foreign_key="user_id", inverse_of="user") - - class Profile(RelationManagementMixin, BaseModel): - id: int - user_id: int - user: ClassVar[BelongsTo["User"]] = BelongsTo(foreign_key="user_id", inverse_of="profile") - - # Trigger validation - Profile(id=1, user_id=1).user() - - def test_invalid_has_many_has_many_pair(self): - """HasMany↔HasMany should fail validation on relation access.""" - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - a: ClassVar[HasMany["A"]] = HasMany(foreign_key="a_id", inverse_of="bs") - - # Validation is lazy — triggered on relation access - with pytest.raises(ValueError, match="Invalid relationship pair"): - A(id=1).bs() - - def test_auto_set_inverse_of(self): - """When inverse_of is None on the related model, it should be auto-set.""" - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - a: ClassVar[BelongsTo["A"]] = BelongsTo(foreign_key="a_id") - - # Trigger validation by accessing the relation - A(id=1).bs() - assert B.get_relation("a").inverse_of == "bs" - - def test_async_valid_belongs_to_has_many_pair(self): - class Dept(RelationManagementMixin, BaseModel): - id: int - employees: ClassVar[AsyncHasMany["Emp"]] = AsyncHasMany(foreign_key="dept_id", inverse_of="department") - - class Emp(RelationManagementMixin, BaseModel): - id: int - dept_id: int - department: ClassVar[AsyncBelongsTo["Dept"]] = AsyncBelongsTo(foreign_key="dept_id", inverse_of="employees") - - def test_missing_inverse_relationship(self): - """Inverse name does not exist on related model.""" - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="nonexistent") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - - with pytest.raises(ValueError, match="Inverse relationship.*not found"): - A(id=1).bs() - - def test_non_relation_inverse(self): - """Inverse exists but is not a RelationDescriptor.""" - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - a: ClassVar[str] = "not_a_descriptor" - - with pytest.raises(ValueError, match="must be a RelationDescriptor"): - A(id=1).bs() - - def test_async_missing_inverse_relationship(self): - """Inverse name does not exist on related model.""" - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[AsyncHasMany["B"]] = AsyncHasMany(foreign_key="a_id", inverse_of="nonexistent") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - - with pytest.raises(ValueError, match="Inverse relationship.*not found"): - A(id=1).bs() - - def test_async_auto_set_inverse_of(self): - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[AsyncHasMany["B"]] = AsyncHasMany(foreign_key="a_id", inverse_of="a") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - a: ClassVar[AsyncBelongsTo["A"]] = AsyncBelongsTo(foreign_key="a_id") - - # Trigger validation via get_related_model directly (avoids coroutine) - desc = A.get_relation("bs") - desc.get_related_model(A) - assert B.get_relation("a").inverse_of == "bs" - - def test_inconsistent_inverse_wrong_owner(self): - """Trigger 'Inconsistent inverse' by validating with an unrelated owner. - - WARNING: This simulates an unnatural scenario where validate() is called - with an owner class that does NOT own the descriptor. Under normal class - definition this path is unreachable, because validate() is only invoked - from __set_name__, which always passes the actual owner class. - Do NOT replicate this pattern in application code. - """ - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[HasMany["B"]] = HasMany(foreign_key="a_id", inverse_of="a") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - a: ClassVar[BelongsTo["A"]] = BelongsTo(foreign_key="a_id", inverse_of="bs") - - # After B's validation, A.bs.inverse_of was auto-set to 'a'. - # Now call A.bs's validator with an unrelated owner class C. - class C(RelationManagementMixin, BaseModel): - id: int - - with pytest.raises(ValueError, match="Inconsistent inverse"): - A.get_relation("bs")._validator.validate(C, B) - - def test_async_inconsistent_inverse_wrong_owner(self): - """Async: trigger 'Inconsistent inverse' via unrelated owner. - - WARNING: Same unnatural scenario as the sync version. Do NOT replicate - in application code. - """ - - class A(RelationManagementMixin, BaseModel): - id: int - bs: ClassVar[AsyncHasMany["B"]] = AsyncHasMany(foreign_key="a_id", inverse_of="a") - - class B(RelationManagementMixin, BaseModel): - id: int - a_id: int - a: ClassVar[AsyncBelongsTo["A"]] = AsyncBelongsTo(foreign_key="a_id", inverse_of="bs") - - class C(RelationManagementMixin, BaseModel): - id: int - - with pytest.raises(ValueError, match="Inconsistent inverse"): - A.get_relation("bs")._validator.validate(C, B) - - -# ============================================================================== -# 8. DefaultIRelationLoader & AsyncDefaultRelationLoader — basic init -# ============================================================================== - - -class TestDefaultLoadersInit: - """Default loaders are created internally; verify existence.""" - - def test_sync_default_loader_created(self): - desc = BelongsTo(foreign_key="x_id") - loader = desc._loader - assert isinstance(loader, DefaultIRelationLoader) - assert loader.descriptor is desc - - def test_async_default_loader_created(self): - desc = AsyncBelongsTo(foreign_key="x_id") - loader = desc._loader - assert isinstance(loader, AsyncDefaultRelationLoader) - assert loader.descriptor is desc - - -# ============================================================================== -# 9. _create_query_method coverage via descriptor -# ============================================================================== - - -class TestCreateQueryMethod: - """Cover _create_query_method for both BelongsTo and HasOne/HasMany.""" - - def test_query_method_exists(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") - - assert hasattr(Source, "target_query") - # Calling requires a proper instance with backend → skip call, just check existence. - - def test_async_query_method_exists(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") - - assert hasattr(Source, "target_query") - - -# ============================================================================== -# 10. batch_load on RelationDescriptor / AsyncRelationDescriptor -# ============================================================================== - - -class TestDescriptorBatchLoad: - """Cover RelationDescriptor.batch_load with empty records.""" - - def test_sync_batch_load_empty_records(self): - desc = BelongsTo(foreign_key="x_id") - desc.name = "test_rel" - result = desc.batch_load([], None) - assert result == {} - - @pytest.mark.asyncio - async def test_async_batch_load_empty_records(self): - desc = AsyncBelongsTo(foreign_key="x_id") - desc.name = "test_rel" - result = await desc.batch_load([], None) - assert result == {} - - -# ============================================================================== -# 11. log method with offset -# ============================================================================== - - -class TestLogMethod: - """Cover the log method's offset handling.""" - - def test_log_with_offset(self): - desc = BelongsTo(foreign_key="x_id") - # Should not crash even without _owner - desc.log(10, "test message", offset=2) - - -# ============================================================================== -# 12. Resolve model type from annotations with ClassVar -# ============================================================================== - - -class TestResolveModel: - """Cover _resolve_model with different annotation patterns.""" - - def test_sync_resolve_belongs_to(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") - - desc = Source.get_relation("target") - model = desc.get_related_model(Source) - assert model is Target - - def test_async_resolve_belongs_to(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") - - desc = Source.get_relation("target") - model = desc.get_related_model(Source) - assert model is Target - - -# ============================================================================== -# 13. clear_cache on the bound relation method -# ============================================================================== - - -class TestRelationMethodClearCache: - """Cover the clear_cache lambda on relation methods.""" - - def test_sync_clear_cache(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[BelongsTo["Target"]] = BelongsTo(foreign_key="target_id") - - instance = Source(id=1, target_id=1) - InstanceCache.set(instance, "target", Target(id=1), CacheConfig()) - method = Source.target.__get__(instance, Source) - method.clear_cache() - assert InstanceCache.get(instance, "target", CacheConfig()) is None - - def test_async_clear_cache(self): - class Target(RelationManagementMixin, BaseModel): - id: int - - class Source(RelationManagementMixin, BaseModel): - id: int - target_id: int - target: ClassVar[AsyncBelongsTo["Target"]] = AsyncBelongsTo(foreign_key="target_id") - - instance = Source(id=1, target_id=1) - InstanceCache.set(instance, "target", Target(id=1), CacheConfig()) - method = Source.target.__get__(instance, Source) - method.clear_cache() - assert InstanceCache.get(instance, "target", CacheConfig()) is None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py deleted file mode 100644 index 30764da9..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_descriptor_db_coverage.py +++ /dev/null @@ -1,352 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_descriptor_db_coverage.py -""" -Database-backed tests covering descriptor code paths that require SQLite. - -Covers: _create_query_method, _load_relation, DefaultIRelationLoader.load/batch_load, -RelationDescriptor.batch_load, cache interaction, HasOne path. -""" - -import pytest - -from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache - - -# ============================================================================== -# _create_query_method — calls model_class.query() with FK/PK filter -# ============================================================================== - - -class TestCreateQueryMethod: - """Cover _create_query_method for BelongsTo, HasMany, HasOne.""" - - def _save(self, model): - model.save() - return model - - def test_belongs_to_query_method(self, user_post_comment_classes): - """BelongsTo query filters by FK matching instance PK.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Alice") - user.save() - post = post_class(title="Post", body="Body", user_id=user.id) - post.save() - - query = post.user_query() - assert user.id is not None - results = query.all() - assert len(results) == 1 - assert results[0].id == user.id - - def test_has_many_query_method(self, user_post_comment_classes): - """HasMany query filters by FK matching instance PK.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Bob") - user.save() - p1 = post_class(title="Post A", body="Body", user_id=user.id) - p1.save() - p2 = post_class(title="Post B", body="Body", user_id=user.id) - p2.save() - - query = user.posts_query() - results = query.all() - assert len(results) == 2 - - def test_has_one_query_method(self, user_post_comment_classes): - """HasOne query method exists and can be called.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Carol") - user.save() - query = user.posts_query() - assert query is not None - assert user.id is not None - - -# ============================================================================== -# DefaultIRelationLoader.batch_load — BelongsTo path -# ============================================================================== - - -class TestDefaultLoaderBelongsTo: - """Cover DefaultIRelationLoader.batch_load for BelongsTo.""" - - def test_belongs_to_load_single(self, user_post_comment_classes): - """BelongsTo: comment loads its post.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Dave") - user.save() - post = post_class(title="Test", body="Body", user_id=user.id) - post.save() - comment = comment_class(body="Nice!", post_id=post.id) - comment.save() - - result = comment.post() - assert result is not None - assert result.id == post.id - assert result.title == "Test" - - def test_belongs_to_batch_load(self, user_post_comment_classes): - """BelongsTo batch_load: multiple comments share/span posts.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Eve") - user.save() - post1 = post_class(title="P1", body="B1", user_id=user.id) - post1.save() - post2 = post_class(title="P2", body="B2", user_id=user.id) - post2.save() - - c1 = comment_class(body="C1", post_id=post1.id) - c1.save() - c2 = comment_class(body="C2", post_id=post1.id) - c2.save() - c3 = comment_class(body="C3", post_id=post2.id) - c3.save() - - result = c2.post() - assert result is not None - assert result.id == post1.id - - -# ============================================================================== -# DefaultIRelationLoader.batch_load — HasMany path -# ============================================================================== - - -class TestDefaultLoaderHasMany: - """Cover DefaultIRelationLoader.batch_load for HasMany.""" - - def test_has_many_load(self, user_post_comment_classes): - """HasMany: user loads posts.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Heidi") - user.save() - p1 = post_class(title="A", body="B1", user_id=user.id) - p1.save() - p2 = post_class(title="B", body="B2", user_id=user.id) - p2.save() - - results = user.posts() - assert len(results) == 2 - - def test_has_many_empty(self, user_post_comment_classes): - """HasMany: user with no posts returns [].""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Ivan") - user.save() - - results = user.posts() - assert results == [] - - def test_has_many_batch_multiple_users(self, user_post_comment_classes): - """HasMany: multiple users with posts.""" - user_class, post_class, comment_class = user_post_comment_classes - u1 = user_class(name="Judy") - u1.save() - u2 = user_class(name="Karl") - u2.save() - p1 = post_class(title="U1P1", body="B", user_id=u1.id) - p1.save() - p2 = post_class(title="U2P1", body="B", user_id=u2.id) - p2.save() - p3 = post_class(title="U2P2", body="B", user_id=u2.id) - p3.save() - - r1 = u1.posts() - assert len(r1) == 1 - r2 = u2.posts() - assert len(r2) == 2 - - -# ============================================================================== -# DefaultIRelationLoader.batch_load — HasOne path -# ============================================================================== - - -class TestDefaultLoaderHasOne: - """Cover DefaultIRelationLoader.batch_load for HasOne.""" - - def test_has_one_load(self, user_post_comment_classes): - """HasOne — default loader branching is identical to HasMany for WHERE. - - The actual HasOne-vs-HasMany distinction in batch_load is just - taking result[0] vs result list. Verify HasMany path works. - """ - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Leo") - user.save() - p1 = post_class(title="H1", body="B", user_id=user.id) - p1.save() - results = user.posts() - assert len(results) == 1 - - -# ============================================================================== -# _load_relation — cache interaction -# ============================================================================== - - -class TestLoadRelationDb: - """Cover _load_relation with cache hit/miss/error using DB loader.""" - - def test_cache_hit_after_initial_load(self, user_post_comment_classes): - """Second access uses cache.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Mallory") - user.save() - p = post_class(title="Cached", body="B", user_id=user.id) - p.save() - - results = user.posts() - assert len(results) == 1 - - results2 = user.posts() - assert len(results2) == 1 - - def test_cache_bypass_with_disabled_cache(self, user_post_comment_classes): - """When cache is disabled, each access reloads.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Nina") - user.save() - - desc = user_class.get_relation("posts") - config = desc._cache_config - desc._cache_config = CacheConfig(enabled=False) - - p = post_class(title="NoCache", body="B", user_id=user.id) - p.save() - r1 = user.posts() - assert len(r1) == 1 - - desc._cache_config = config - - def test_cache_cleared_on_delete(self, user_post_comment_classes): - """__delete__ clears the instance cache.""" - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Oscar") - user.save() - post = post_class(title="Del", body="B", user_id=user.id) - post.save() - c = comment_class(body="C", post_id=post.id) - c.save() - - _ = post.comments() - - desc = post_class.get_relation("comments") - desc.__delete__(post) - - results = post.comments() - assert len(results) == 1 - - def test_cache_write_failure_still_returns_loaded_data(self, user_post_comment_classes, mocker): - user_class, post_class, comment_class = user_post_comment_classes - user = user_class(name="Peggy") - user.save() - post = post_class(title="CacheWriteFail", body="B", user_id=user.id) - post.save() - - mocker.patch.object(InstanceCache, "set", side_effect=TypeError("cache write failed")) - - results = user.posts() - assert len(results) == 1 - assert results[0].id == post.id - - -# ============================================================================== -# Async DefaultIRelationLoader -# ============================================================================== - - -class TestAsyncDefaultLoader: - """Cover AsyncDefaultRelationLoader with DB.""" - - @pytest.mark.asyncio - async def test_async_belongs_to_load(self, async_user_post_comment_classes): - user_class, post_class, comment_class = async_user_post_comment_classes - user = user_class(name="AsyncAlice") - await user.save() - post = post_class(title="AsyncPost", body="Body", user_id=user.id) - await post.save() - comment = comment_class(body="Nice", post_id=post.id) - await comment.save() - - result = await comment.post() - assert result is not None - assert result.id == post.id - - @pytest.mark.asyncio - async def test_async_has_many_load(self, async_user_post_comment_classes): - user_class, post_class, comment_class = async_user_post_comment_classes - user = user_class(name="AsyncBob") - await user.save() - p1 = post_class(title="A1", body="B1", user_id=user.id) - await p1.save() - p2 = post_class(title="A2", body="B2", user_id=user.id) - await p2.save() - - results = await user.posts() - assert len(results) == 2 - - @pytest.mark.asyncio - async def test_async_has_many_empty(self, async_user_post_comment_classes): - user_class, post_class, comment_class = async_user_post_comment_classes - user = user_class(name="AsyncCarol") - await user.save() - - results = await user.posts() - assert results == [] - - @pytest.mark.asyncio - async def test_async_cache_hit(self, async_user_post_comment_classes): - user_class, post_class, comment_class = async_user_post_comment_classes - user = user_class(name="AsyncEve") - await user.save() - p = post_class(title="Cached", body="B", user_id=user.id) - await p.save() - - r1 = await user.posts() - r2 = await user.posts() - assert len(r1) == 1 - assert len(r2) == 1 - - @pytest.mark.asyncio - async def test_async_batch_load_empty_records(self, async_user_post_comment_classes): - """AsyncRelationDescriptor.batch_load with empty records.""" - user_class, post_class, comment_class = async_user_post_comment_classes - desc = user_class.get_relation("posts") - result = await desc.batch_load([], None) - assert result == {} - - -# ============================================================================== -# Async _create_query_method -# ============================================================================== - - -class TestAsyncCreateQueryMethod: - """Cover async _create_query_method.""" - - @pytest.mark.asyncio - async def test_async_belongs_to_query(self, async_user_post_comment_classes): - user_class, post_class, comment_class = async_user_post_comment_classes - user = user_class(name="Alice") - await user.save() - post = post_class(title="P", body="B", user_id=user.id) - await post.save() - - query = post.user_query() - results = await query.all() - assert len(results) == 1 - assert results[0].id == user.id - - @pytest.mark.asyncio - async def test_async_has_many_query(self, async_user_post_comment_classes): - user_class, post_class, comment_class = async_user_post_comment_classes - user = user_class(name="Bob") - await user.save() - p1 = post_class(title="A", body="B1", user_id=user.id) - await p1.save() - p2 = post_class(title="B", body="B2", user_id=user.id) - await p2.save() - - query = user.posts_query() - results = await query.all() - assert len(results) == 2 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py deleted file mode 100644 index 97467851..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_instance_cache.py +++ /dev/null @@ -1,281 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_instance_cache.py -""" -Granular tests for InstanceCache functionality. - -These tests cover the instance-level caching mechanism specific to python-activerecord, -which is distinct from the RelationCache (class-level cache). -""" - -import time - -from pydantic import BaseModel - -from rhosocial.activerecord.relation.cache import ( - CacheConfig, - InstanceCache, - CacheEntry, -) - - -class TestInstanceCache: - """Tests for the InstanceCache functionality.""" - - def test_get_cache_attr_name(self): - """Test cache attribute name generation.""" - attr_name = InstanceCache.get_cache_attr_name("posts") - assert attr_name == "_relation_cache_posts" - - attr_name = InstanceCache.get_cache_attr_name("user") - assert attr_name == "_relation_cache_user" - - def test_get_instance_cache_creates_cache(self): - """Test that get_instance_cache creates cache dict if not exists.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - - cache = InstanceCache.get_instance_cache(instance, "test_relation") - assert isinstance(cache, dict) - assert "entry" not in cache - - def test_get_instance_cache_returns_existing(self): - """Test that get_instance_cache returns existing cache.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - - cache1 = InstanceCache.get_instance_cache(instance, "test_relation") - cache1["custom_key"] = "custom_value" - - cache2 = InstanceCache.get_instance_cache(instance, "test_relation") - assert cache2["custom_key"] == "custom_value" - - def test_instance_cache_isolation_between_relations(self): - """Test that different relations have isolated caches.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - - cache1 = InstanceCache.get_instance_cache(instance, "relation_a") - cache1["entry"] = CacheEntry("value_a") - - cache2 = InstanceCache.get_instance_cache(instance, "relation_b") - cache2["entry"] = CacheEntry("value_b") - - result_a = InstanceCache.get(instance, "relation_a", CacheConfig()) - result_b = InstanceCache.get(instance, "relation_b", CacheConfig()) - - assert result_a == "value_a" - assert result_b == "value_b" - - def test_instance_cache_isolation_between_instances(self): - """Test that different instances have isolated caches.""" - - class TestModel(BaseModel): - id: int - - instance1 = TestModel(id=1) - instance2 = TestModel(id=2) - - InstanceCache.set(instance1, "test_relation", "value1", CacheConfig()) - InstanceCache.set(instance2, "test_relation", "value2", CacheConfig()) - - result1 = InstanceCache.get(instance1, "test_relation", CacheConfig()) - result2 = InstanceCache.get(instance2, "test_relation", CacheConfig()) - - assert result1 == "value1" - assert result2 == "value2" - - def test_instance_cache_set_and_get(self): - """Test basic set and get operations.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig(enabled=True) - - InstanceCache.set(instance, "test_relation", "test_value", config) - - result = InstanceCache.get(instance, "test_relation", config) - assert result == "test_value" - - def test_instance_cache_disabled(self): - """Test that caching is disabled when config.enabled is False.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig(enabled=False) - - InstanceCache.set(instance, "test_relation", "test_value", config) - - result = InstanceCache.get(instance, "test_relation", config) - assert result is None - - def test_instance_cache_get_no_entry(self): - """Test get returns None when no entry exists.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig() - - result = InstanceCache.get(instance, "nonexistent", config) - assert result is None - - def test_instance_cache_expiration(self): - """Test cache entry expiration.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig(ttl=1) - - InstanceCache.set(instance, "test_relation", "test_value", config) - - result = InstanceCache.get(instance, "test_relation", config) - assert result == "test_value" - - time.sleep(1.1) - - result = InstanceCache.get(instance, "test_relation", config) - assert result is None - - def test_instance_cache_expiration_disabled(self): - """Test that entries with no TTL never expire.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig(ttl=None) - - InstanceCache.set(instance, "test_relation", "test_value", config) - - time.sleep(0.5) - - result = InstanceCache.get(instance, "test_relation", config) - assert result == "test_value" - - def test_instance_cache_delete(self): - """Test cache entry deletion.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig() - - InstanceCache.set(instance, "test_relation", "test_value", config) - assert InstanceCache.get(instance, "test_relation", config) == "test_value" - - InstanceCache.delete(instance, "test_relation") - - result = InstanceCache.get(instance, "test_relation", config) - assert result is None - - def test_instance_cache_delete_nonexistent(self): - """Test delete on nonexistent entry doesn't raise.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - - InstanceCache.delete(instance, "nonexistent") - - def test_instance_cache_clear(self): - """Test clearing cache for a specific relation.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig() - - InstanceCache.set(instance, "relation_a", "value_a", config) - InstanceCache.set(instance, "relation_b", "value_b", config) - - InstanceCache.delete(instance, "relation_a", config) - - result_a = InstanceCache.get(instance, "relation_a", config) - result_b = InstanceCache.get(instance, "relation_b", config) - - assert result_a is None - assert result_b == "value_b" - - def test_instance_cache_clear_disabled(self): - """Test that clear does nothing when caching is disabled.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig(enabled=False) - - InstanceCache.set(instance, "test_relation", "test_value", config) - InstanceCache.delete(instance, "test_relation", config) - - def test_instance_cache_with_complex_values(self): - """Test caching complex objects like lists and dicts.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig() - - complex_value = [ - {"id": 1, "name": "Item 1"}, - {"id": 2, "name": "Item 2"}, - ] - InstanceCache.set(instance, "items", complex_value, config) - - result = InstanceCache.get(instance, "items", config) - assert result == complex_value - - def test_instance_cache_with_none_value(self): - """Test caching None values.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - config = CacheConfig() - - InstanceCache.set(instance, "optional", None, config) - - result = InstanceCache.get(instance, "optional", config) - assert result is None - - def test_multiple_relations_on_same_instance(self): - """Test multiple relations with different configs.""" - - class TestModel(BaseModel): - id: int - - instance = TestModel(id=1) - - config_a = CacheConfig(ttl=1) - config_b = CacheConfig(ttl=None) - - InstanceCache.set(instance, "short_ttl", "value_a", config_a) - InstanceCache.set(instance, "no_ttl", "value_b", config_b) - - assert InstanceCache.get(instance, "short_ttl", config_a) == "value_a" - assert InstanceCache.get(instance, "no_ttl", config_b) == "value_b" - - time.sleep(1.1) - - assert InstanceCache.get(instance, "short_ttl", config_a) is None - assert InstanceCache.get(instance, "no_ttl", config_b) == "value_b" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py deleted file mode 100644 index b8a3e1e0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_redis_cache.py +++ /dev/null @@ -1,279 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_redis_cache.py -""" -Tests for RedisCache backend. - -Requires a running Redis instance reachable via the REDIS_HOST / REDIS_PORT -environment variables (defaults: localhost:6379, no password). If unavailable, -Redis-dependent tests are skipped — the RedisCache instance is real but the -fixture verifies connectivity at module scope. - -The pytest ``redis`` marker remains defined for callers that prefer to exclude -Redis tests explicitly (``pytest -m 'not redis'``). -""" - -import pytest -import time - -from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache -from rhosocial.activerecord.relation.cache_backends import ( # noqa: E402 - RedisCache, - RedisConfig, - CacheSerializer, - InMemoryCache, -) - -pytestmark = [pytest.mark.redis, pytest.mark.xdist_group("redis_cache")] - - -class _DummyModel: - """Minimal model stub for cache key unit tests.""" - - primary_key_name = "id" - - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - - def primary_key(self): - return self.primary_key_name - - -class _DummyNoPK(_DummyModel): - primary_key_name = "id" - - def __init__(self, **kwargs): - super().__init__(**kwargs) - # deliberately not setting "id" - - -@pytest.fixture(scope="module") -def redis_client(): - redis = pytest.importorskip("redis") - config = RedisConfig.from_env() - try: - client = redis.Redis( - host=config.host, - port=config.port, - password=config.password or None, - db=config.db, - socket_connect_timeout=config.socket_connect_timeout, - ) - client.ping() - yield client - client.flushdb() - except Exception as e: - pytest.skip(f"Redis not available ({e})") - yield None - finally: - try: - client.close() - except Exception: - pass - - -@pytest.fixture -def redis_cache(redis_client): - """Create RedisCache with a clean DB per test.""" - redis_client.flushdb() - return RedisCache(redis_client, prefix="test:cache:") - - -@pytest.fixture -def config(): - return CacheConfig(enabled=True, ttl=300) - - -class TestRedisCacheKey: - """Key generation and format.""" - - def test_key_format(self, redis_cache, config): - """Key follows {prefix}ModelName:pk:relation.""" - instance = _DummyModel(id=42) - key = redis_cache._make_key(instance, "posts") - assert key == "test:cache:_DummyModel:42:posts" - - def test_missing_pk_raises(self, redis_cache): - """Instance without PK raises ValueError.""" - instance = _DummyNoPK() - with pytest.raises(ValueError, match="no primary key"): - redis_cache._make_key(instance, "posts") - - -class TestRedisCacheBasic: - """Basic get/set/delete operations.""" - - def test_set_and_get(self, redis_cache, config, redis_client): - inst = _DummyModel(id=1) - value = ["item1", "item2"] - - redis_cache.set(inst, "items", value, config) - key = redis_cache._make_key(inst, "items") - assert redis_client.exists(key) - - result = redis_cache.get(inst, "items", config) - assert result == value - - def test_get_miss(self, redis_cache, config): - inst = _DummyModel(id=1) - result = redis_cache.get(inst, "items", config) - assert result is None - - def test_delete(self, redis_cache, config, redis_client): - inst = _DummyModel(id=1) - redis_cache.set(inst, "items", "data", config) - key = redis_cache._make_key(inst, "items") - assert redis_client.exists(key) - - redis_cache.delete(inst, "items") - assert not redis_client.exists(key) - assert redis_cache.get(inst, "items", config) is None - - def test_disabled_config_skips(self, redis_cache): - inst = _DummyModel(id=1) - disabled = CacheConfig(enabled=False) - - redis_cache.set(inst, "items", "data", disabled) - assert redis_cache.get(inst, "items", disabled) is None - - redis_cache.delete(inst, "items", disabled) - - def test_ttl_expiry(self, redis_cache, config, redis_client): - inst = _DummyModel(id=1) - ttl_config = CacheConfig(enabled=True, ttl=1) - - redis_cache.set(inst, "items", "expirable", ttl_config) - assert redis_cache.get(inst, "items", ttl_config) == "expirable" - - time.sleep(1.5) - assert redis_cache.get(inst, "items", ttl_config) is None - - def test_no_ttl_persists(self, redis_cache, redis_client): - inst = _DummyModel(id=1) - no_ttl = CacheConfig(enabled=True, ttl=None) - - redis_cache.set(inst, "items", "persistent", no_ttl) - key = redis_cache._make_key(inst, "items") - ttl = redis_client.ttl(key) - assert ttl == -1 # no expiry - - -class UpperSerializer(CacheSerializer): - """A serializer that uppercases string values before pickle.""" - - def __init__(self): - super().__init__(format="pickle") - - def serialize(self, value): - return super().serialize(value.upper()) - - -class TestRedisCacheSerialization: - """Custom serialization support.""" - - def test_custom_serializer(self, redis_cache, config, redis_client): - cache = RedisCache(redis_client, prefix="test:ser:", serializer=UpperSerializer()) - inst = _DummyModel(id=1) - - cache.set(inst, "name", "hello", config) - result = cache.get(inst, "name", config) - assert result == "HELLO" - - -class TestRedisCacheOrigin: - """Origin metadata (observability).""" - - def test_record_origin(self, redis_cache, config, redis_client, caplog): - caplog.set_level("DEBUG", logger="rhosocial.activerecord.relation.cache_backends.redis") - cache = RedisCache(redis_client, prefix="test:origin:", record_origin=True, origin_name="test-host") - inst = _DummyModel(id=1) - - cache.set(inst, "items", "data", config) - result = cache.get(inst, "items", config) - assert result == "data" - - assert any("origin=test-host" in msg for msg in caplog.messages) - - def test_origin_default_off(self, redis_cache, config, redis_client): - """record_origin=False stores raw serialized bytes, not JSON wrapper.""" - import json - - inst = _DummyModel(id=1) - redis_cache.set(inst, "items", "plain", config) - key = redis_cache._make_key(inst, "items") - raw = redis_client.get(key) - assert isinstance(raw, bytes) - assert json.loads(raw) == "plain" - - -class TestRedisInMemorySwitch: - """Switching backends via InstanceCache.set_backend.""" - - def test_switch_to_redis_and_back(self, redis_cache): - inst = _DummyModel(id=1) - config = CacheConfig(enabled=True, ttl=300) - - original = InstanceCache._backend - try: - InstanceCache.set_backend(redis_cache) - InstanceCache.set(inst, "data", "from-redis", config) - assert InstanceCache.get(inst, "data", config) == "from-redis" - - InstanceCache.set_backend(InMemoryCache()) - InstanceCache.set(inst, "data", "from-memory", config) - assert InstanceCache.get(inst, "data", config) == "from-memory" - finally: - InstanceCache.set_backend(original) - - def test_after_switch_redis_persists(self, redis_client): - """Data set via RedisCache remains accessible to a fresh RedisCache instance.""" - inst = _DummyModel(id=1) - config = CacheConfig(enabled=True, ttl=300) - - redis_client.flushdb() - c1 = RedisCache(redis_client, prefix="test:switch:") - c1.set(inst, "items", "persisted", config) - - c2 = RedisCache(redis_client, prefix="test:switch:") - assert c2.get(inst, "items", config) == "persisted" - - -class TestRedisInconsistency: - """Stale/inconsistent data scenario (read-only).""" - - def test_stale_data_returned(self, redis_cache, config, redis_client): - """If data is changed in DB but cache is not invalidated, stale value is returned.""" - inst = _DummyModel(id=1) - redis_cache.set(inst, "count", 10, config) - - # Simulate DB update without cache invalidation - redis_cache.set(inst, "count", 99, config) - - assert redis_cache.get(inst, "count", config) == 99 - - -class TestRedisInstanceInvalidation: - """invalidate_instance clears all cached relations for an instance.""" - - def test_invalidate_instance(self, redis_cache, config, redis_client): - inst = _DummyModel(id=1) - redis_cache.set(inst, "posts", ["p1", "p2"], config) - redis_cache.set(inst, "comments", ["c1"], config) - - assert redis_cache.get(inst, "posts", config) is not None - assert redis_cache.get(inst, "comments", config) is not None - - redis_cache.invalidate_instance(inst) - - assert redis_cache.get(inst, "posts", config) is None - assert redis_cache.get(inst, "comments", config) is None - - def test_invalidate_instance_other_untouched(self, redis_cache, config, redis_client): - inst1 = _DummyModel(id=1) - inst2 = _DummyModel(id=2) - - redis_cache.set(inst1, "data", "a", config) - redis_cache.set(inst2, "data", "b", config) - - redis_cache.invalidate_instance(inst1) - assert redis_cache.get(inst1, "data", config) is None - assert redis_cache.get(inst2, "data", config) == "b" diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py deleted file mode 100644 index b482ae53..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_management.py +++ /dev/null @@ -1,238 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_relation_management.py -""" -Tests for RelationManagementMixin methods. - -These tests cover the relation management functionality provided by the -RelationManagementMixin class in python-activerecord. -""" - -import pytest -from typing import ClassVar - -from pydantic import BaseModel - -from rhosocial.activerecord.relation.base import RelationManagementMixin -from rhosocial.activerecord.relation.cache import CacheConfig, InstanceCache -from rhosocial.activerecord.relation.descriptors import ( - HasMany, - BelongsTo, - HasOne, - RelationDescriptor, -) - - -class Department(RelationManagementMixin, BaseModel): - id: int - name: str - employees: ClassVar[HasMany["Employee"]] = HasMany(foreign_key="department_id", inverse_of="department") - - -class Employee(RelationManagementMixin, BaseModel): - id: int - name: str - department_id: int - department: ClassVar[BelongsTo["Department"]] = BelongsTo(foreign_key="department_id", inverse_of="employees") - - -class Profile(RelationManagementMixin, BaseModel): - id: int - bio: str - author_id: int - author: ClassVar[BelongsTo["Author"]] = BelongsTo(foreign_key="author_id", inverse_of="profile") - - -class Author(RelationManagementMixin, BaseModel): - id: int - name: str - books: ClassVar[HasMany["Book"]] = HasMany(foreign_key="author_id", inverse_of="author") - profile: ClassVar[HasOne["Profile"]] = HasOne(foreign_key="author_id", inverse_of="author") - - -class Book(RelationManagementMixin, BaseModel): - id: int - title: str - author_id: int - author: ClassVar[BelongsTo["Author"]] = BelongsTo(foreign_key="author_id", inverse_of="books") - - -class TestRelationManagementMixin: - """Tests for RelationManagementMixin functionality.""" - - def test_ensure_relations_creates_dict(self): - """Test that _ensure_relations creates the relations dict if not exists.""" - - class NewModel(RelationManagementMixin, BaseModel): - id: int - - relations = NewModel._ensure_relations() - assert isinstance(relations, dict) - assert "_relations_dict" in NewModel.__dict__ - - def test_ensure_relations_returns_existing(self): - """Test that _ensure_relations returns existing dict.""" - relations1 = Department._ensure_relations() - relations2 = Department._ensure_relations() - assert relations1 is relations2 - - def test_register_relation(self): - """Test registering a new relation.""" - - class TestModel(RelationManagementMixin, BaseModel): - id: int - - class TestRelation(HasMany): - pass - - class TestDescriptor(RelationDescriptor): - pass - - descriptor = RelationDescriptor(foreign_key="test_id") - TestModel.register_relation("test_rel", descriptor) - - assert "test_rel" in TestModel.get_relations() - assert TestModel.get_relation("test_rel") == descriptor - - def test_register_relation_overwrites(self): - """Test that registering a relation with same name overwrites.""" - - class TestModel(RelationManagementMixin, BaseModel): - id: int - - descriptor1 = RelationDescriptor(foreign_key="test_id") - descriptor2 = RelationDescriptor(foreign_key="other_id") - - TestModel.register_relation("test_rel", descriptor1) - TestModel.register_relation("test_rel", descriptor2) - - assert TestModel.get_relation("test_rel") == descriptor2 - - def test_get_relation_returns_none_for_unknown(self): - """Test that get_relation returns None for unknown relation.""" - result = Department.get_relation("unknown_relation") - assert result is None - - def test_get_relations_returns_all(self): - """Test that get_relations returns all registered relations.""" - relations = Department.get_relations() - assert "employees" in relations - - def test_get_relations_excludes_inherited(self): - """Test that get_relations only returns own relations, not inherited.""" - - class Parent(RelationManagementMixin, BaseModel): - id: int - parent_rel: ClassVar[HasMany["Other"]] = HasMany(foreign_key="parent_id", inverse_of="parent") - - class Child(Parent): - pass - - class Other(RelationManagementMixin, BaseModel): - id: int - parent_id: int - parent: ClassVar[BelongsTo["Parent"]] = BelongsTo(foreign_key="parent_id", inverse_of="parent_rel") - - parent_relations = Parent.get_relations() - assert "parent_rel" in parent_relations - - def test_clear_relation_cache_specific(self): - """Test clearing specific relation cache.""" - employee = Employee(id=1, name="Test", department_id=1) - - InstanceCache.set(employee, "department", {"id": 1, "name": "Dept"}, CacheConfig()) - - assert InstanceCache.get(employee, "department", CacheConfig()) is not None - - employee.clear_relation_cache("department") - - assert InstanceCache.get(employee, "department", CacheConfig()) is None - - def test_clear_relation_cache_all(self): - """Test clearing all relation caches.""" - employee = Employee(id=1, name="Test", department_id=1) - - InstanceCache.set(employee, "department", {"id": 1, "name": "Dept"}, CacheConfig()) - - assert InstanceCache.get(employee, "department", CacheConfig()) is not None - - employee.clear_relation_cache() - - assert InstanceCache.get(employee, "department", CacheConfig()) is None - - def test_clear_relation_cache_invalid_name_raises(self): - """Test that clearing invalid relation name raises ValueError.""" - employee = Employee(id=1, name="Test", department_id=1) - - with pytest.raises(ValueError) as exc_info: - employee.clear_relation_cache("invalid_relation") - - assert "Unknown relation" in str(exc_info.value) - - -class TestRelationInheritance: - """Tests for relation inheritance behavior.""" - - def test_child_class_can_override_relation(self): - """Test that child class can override parent relation.""" - - class ParentModel(RelationManagementMixin, BaseModel): - id: int - related: ClassVar[HasOne["OtherModel"]] = HasOne(foreign_key="parent_id", inverse_of="parent") - - class OtherModel(RelationManagementMixin, BaseModel): - id: int - parent_id: int - parent: ClassVar[BelongsTo["ParentModel"]] = BelongsTo(foreign_key="parent_id", inverse_of="related") - - parent_rel = ParentModel.get_relation("related") - assert isinstance(parent_rel, HasOne) - - def test_relations_dict_is_class_specific(self): - """Test that each class has its own relations dict.""" - - class Parent(RelationManagementMixin, BaseModel): - id: int - - class Child(Parent): - pass - - Parent.register_relation("test", RelationDescriptor(foreign_key="test_id")) - - child_relations = Child._ensure_relations() - - assert "test" not in child_relations or "_relations_dict" not in Child.__dict__ - - -class TestRelationValidation: - """Tests for relation validation behavior.""" - - def test_inverse_validation(self): - """Test that inverse relationships are validated.""" - - class AuthorWithValidation(RelationManagementMixin, BaseModel): - id: int - books: ClassVar[HasMany["BookWithValidation"]] = HasMany(foreign_key="author_id", inverse_of="author") - - class BookWithValidation(RelationManagementMixin, BaseModel): - id: int - author_id: int - author: ClassVar[BelongsTo["AuthorWithValidation"]] = BelongsTo(foreign_key="author_id", inverse_of="books") - - author_rel = AuthorWithValidation.get_relation("books") - book_rel = BookWithValidation.get_relation("author") - - assert author_rel is not None - assert book_rel is not None - - def test_missing_inverse_does_not_raise(self): - """Test that missing inverse doesn't raise during registration.""" - - class ModelWithoutInverse(RelationManagementMixin, BaseModel): - id: int - related: ClassVar[HasMany["Target"]] = HasMany(foreign_key="model_id", inverse_of=None) - - class Target(RelationManagementMixin, BaseModel): - id: int - model_id: int - - relation = ModelWithoutInverse.get_relation("related") - assert relation is not None diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py deleted file mode 100644 index 8931ec61..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_modifier_cache.py +++ /dev/null @@ -1,350 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_relation_modifier_cache.py -""" -Database-backed relation cache tests using real SQLite with SQL query counting. - -Verifies that the instance-level cache (InstanceCache) correctly prevents -redundant SQL queries on repeated relation access, and that cache invalidation -(for delete, TTL expiry, disabled cache, etc.) re-queries the database. -""" - -import pytest -import time -from typing import ClassVar, Dict, Any, Tuple - -from pydantic import BaseModel - -from rhosocial.activerecord.relation.base import RelationManagementMixin -from rhosocial.activerecord.relation.cache import CacheConfig -from rhosocial.activerecord.relation.descriptors import HasMany, BelongsTo - - -class QueryCounter: - """Wraps backend fetch methods to count executed SQL queries.""" - - def __init__(self, backends: Dict[str, Any]): - self.count = 0 - self._originals: Dict[str, Tuple] = {} - for name, backend in backends.items(): - self._originals[name] = (backend.fetch_all, backend.fetch_one) - backend.fetch_all = self._wrap(backend.fetch_all) - backend.fetch_one = self._wrap(backend.fetch_one) - - def _wrap(self, original): - def wrapper(sql, params=None, column_adapters=None, **kwargs): - self.count += 1 - return original( - sql, - params, - column_adapters=column_adapters, - **kwargs, - ) - - return wrapper - - def reset(self): - self.count = 0 - - -@pytest.fixture -def cache_test_env(user_post_comment_classes): - """Set up test data and wrap backends with a query counter. - - Returns (user_class, post_class, comment_class, user, post, counter). - """ - user_class, post_class, comment_class = user_post_comment_classes - - backends = {} - for cls in (user_class, post_class, comment_class): - try: - backends[cls.__name__] = cls.backend() - except Exception: - pass - counter = QueryCounter(backends) - - user = user_class(name="Cache User", email="cache@example.com") - user.save() - post = post_class(title="Cache Post", body="Content", user_id=user.id) - post.save() - - counter.reset() - yield user_class, post_class, comment_class, user, post, counter - - for name, backend in backends.items(): - orig_all, orig_one = counter._originals.get(name, (None, None)) - if orig_all is not None: - backend.fetch_all = orig_all - if orig_one is not None: - backend.fetch_one = orig_one - - -class TestRelationCacheFirstAccess: - """First relation access should query the database.""" - - def test_first_access_queries_db(self, cache_test_env): - """First access to a relation executes SQL.""" - _, _, _, user, _, counter = cache_test_env - results = user.posts() - assert len(results) == 1 - assert counter.count > 0 - - def test_first_access_has_many_empty(self, cache_test_env): - """HasMany with no related records still executes a query.""" - user_class, _, _, _, _, counter = cache_test_env - user2 = user_class(name="Empty User", email="empty@example.com") - user2.save() - counter.reset() - - results = user2.posts() - assert results == [] - assert counter.count > 0 - - def test_first_access_belongs_to(self, cache_test_env): - """BelongsTo first access executes SQL.""" - _, _, _, _, post, counter = cache_test_env - result = post.user() - assert result is not None - assert counter.count > 0 - - -class TestRelationCacheSecondAccess: - """Second (and subsequent) accesses should hit the cache.""" - - def test_second_access_has_many_uses_cache(self, cache_test_env): - """Second HasMany access uses cache (no SQL).""" - _, _, _, user, _, counter = cache_test_env - r1 = user.posts() - q1 = counter.count - - r2 = user.posts() - assert counter.count == q1 - assert len(r1) == len(r2) - - def test_second_access_belongs_to_uses_cache(self, cache_test_env): - """Second BelongsTo access uses cache (no SQL).""" - _, _, _, _, post, counter = cache_test_env - r1 = post.user() - q1 = counter.count - - r2 = post.user() - assert counter.count == q1 - assert r1.id == r2.id - - def test_multiple_accesses_no_extra_queries(self, cache_test_env): - """Three accesses cause only one SQL query total.""" - _, _, _, user, _, counter = cache_test_env - user.posts() - q1 = counter.count - - for _ in range(5): - user.posts() - - assert counter.count == q1 - - -class TestRelationCacheInvalidation: - """Cache invalidation scenarios (delete, clear, TTL, disabled).""" - - def test_cache_cleared_on_delete(self, cache_test_env): - """__delete__ clears cache; next access re-queries.""" - user_class, _, _, user, _, counter = cache_test_env - user.posts() - counter.reset() - - desc = user_class.get_relation("posts") - desc.__delete__(user) - - results = user.posts() - assert len(results) == 1 - assert counter.count > 0 - - def test_clear_relation_cache_method(self, cache_test_env): - """clear_relation_cache(name) forces a new query.""" - _, _, _, user, _, counter = cache_test_env - user.posts() - counter.reset() - - user.clear_relation_cache("posts") - - results = user.posts() - assert len(results) == 1 - assert counter.count > 0 - - def test_clear_all_relations_cache(self, cache_test_env): - """clear_relation_cache() without args clears all caches.""" - _, _, _, user, _, counter = cache_test_env - user.posts() - counter.reset() - - user.clear_relation_cache() - - results = user.posts() - assert len(results) == 1 - assert counter.count > 0 - - def test_cache_with_disabled_config(self, cache_test_env): - """disabled cache executes a query on every access.""" - user_class, _, _, user, _, counter = cache_test_env - - desc = user_class.get_relation("posts") - orig_config = desc._cache_config - desc._cache_config = CacheConfig(enabled=False) - - try: - user.posts() - counter.reset() - - user.posts() - q1 = counter.count - - user.posts() - assert counter.count > q1 - finally: - desc._cache_config = orig_config - - def test_cache_with_expired_ttl(self, cache_test_env): - """Expired TTL causes a new query.""" - user_class, _, _, user, _, counter = cache_test_env - - desc = user_class.get_relation("posts") - orig_config = desc._cache_config - desc._cache_config = CacheConfig(ttl=1) - - try: - user.posts() - counter.reset() - - time.sleep(1.1) - - results = user.posts() - assert len(results) == 1 - assert counter.count > 0 - finally: - desc._cache_config = orig_config - - -class TestRelationCacheIsolation: - """Cache isolation between instances and relations.""" - - def test_cache_isolation_between_instances(self, cache_test_env): - """Different instances have independent caches.""" - user_class, post_class, _, user, _, counter = cache_test_env - - user2 = user_class(name="Second User", email="u2@example.com") - user2.save() - post2 = post_class(title="Second Post", body="Content", user_id=user2.id) - post2.save() - - user.posts() - user2.posts() - counter.reset() - - r1 = user.posts() - r2 = user2.posts() - assert counter.count == 0 - assert len(r1) == 1 - assert len(r2) == 1 - - def test_different_relations_independent_cache(self, cache_test_env): - """Different relation types on the same instance cache independently.""" - _, _, _, user, post, counter = cache_test_env - - _ = post.user() - counter.reset() - - post.user() - assert counter.count == 0 # BelongsTo cached - - _ = user.posts() - assert counter.count > 0 # HasMany not cached on post instance - - -class TestRelationCacheBulk: - """Bulk / edge-case scenarios.""" - - def test_reload_same_data_idempotent(self, cache_test_env): - """Adding more related data after caching is not visible until cache cleared.""" - user_class, post_class, _, user, _, counter = cache_test_env - - user.posts() - counter.reset() - - extra = post_class(title="Extra Post", body="Extra", user_id=user.id) - extra.save() - - results = user.posts() - assert len(results) == 1 - assert counter.count == 0 # Cache returns stale data - - user.clear_relation_cache("posts") - counter.reset() - - results = user.posts() - assert len(results) == 2 - assert counter.count > 0 - - -# ── Non-DB protocol tests (kept from original mock-based file) ───── - - -class TestRelationDescriptorProtocol: - """Tests for relation descriptor protocol methods.""" - - def test_get_descriptor_from_class(self): - """Test accessing descriptor from class returns descriptor itself.""" - - class _Author(RelationManagementMixin, BaseModel): - id: int - books: ClassVar[HasMany["_Book"]] = HasMany(foreign_key="author_id") - - class _Book(RelationManagementMixin, BaseModel): - id: int - author_id: int - author: ClassVar[BelongsTo["_Author"]] = BelongsTo(foreign_key="author_id") - - relation = _Author.get_relation("books") - assert isinstance(relation, HasMany) - assert relation.foreign_key == "author_id" - - def test_get_descriptor_from_instance_returns_method(self): - """Test accessing descriptor from instance returns bound method.""" - - class _Author(RelationManagementMixin, BaseModel): - id: int - books: ClassVar[HasMany["_Book"]] = HasMany(foreign_key="author_id") - - class _Book(RelationManagementMixin, BaseModel): - id: int - author_id: int - - author = _Author(id=1) - books_relation = author.books - assert callable(books_relation) - - def test_set_name_callback(self): - """Test that __set_name__ is called on descriptor assignment.""" - - class _OtherItem(RelationManagementMixin, BaseModel): - id: int - test_id: int - - class _TestModel(RelationManagementMixin, BaseModel): - id: int - items: ClassVar[HasMany["_OtherItem"]] = HasMany(foreign_key="test_id", inverse_of="test") - - relation = _TestModel.get_relation("items") - assert relation.name == "items" - assert relation._owner == _TestModel - - def test_query_method_created(self): - """Test that query method is created for relation.""" - - class _Author(RelationManagementMixin, BaseModel): - id: int - books: ClassVar[HasMany["_Book"]] = HasMany(foreign_key="author_id") - - class _Book(RelationManagementMixin, BaseModel): - id: int - author_id: int - - assert hasattr(_Author, "books_query") - assert callable(_Author.books_query) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py deleted file mode 100644 index 316d50d0..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_relation_validation.py +++ /dev/null @@ -1,402 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_relational_validation.py -""" -Tests for relational query validation and error handling. - -These tests cover: -1. Invalid relation path format validation -2. Relation not found error handling -3. Edge cases and boundary conditions -""" - -import pytest -from unittest.mock import MagicMock - -from rhosocial.activerecord.interface import IQuery -from rhosocial.activerecord.query.relational import ( - RelationalQueryMixin, - InvalidRelationPathError, - RelationNotFoundError, -) - - -class MockQueryBase(IQuery): - """Mock base class for testing.""" - - def __init__(self): - self.model_class = MagicMock() - self.model_class.__name__ = "MockModel" - self.condition_groups = [[]] - self.current_group = 0 - self.order_clauses = [] - self.join_clauses = [] - self.limit_count = None - self.offset_count = None - from rhosocial.activerecord.backend.expression import AllColumnsWildcard - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - self.select_columns = [AllColumnsWildcard(SQLiteDialect())] - self._explain_enabled = False - self._explain_options = None - - def all(self): - return [] - - def one(self): - return None - - def one_or_fail(self): - return None - - def where(self, condition, params=None): - return self - - def or_where(self, condition, params=None): - return self - - def order_by(self, *clauses): - return self - - def join(self, join_clause): - return self - - def limit(self, count): - return self - - def offset(self, count): - return self - - def select(self, *columns, append=False): - return self - - def count(self): - return 0 - - def exists(self): - return False - - def build(self): - return "", () - - def to_sql(self): - return "", () - - def explain(self, *args, **kwargs): - return self - - def between(self, column, start, end): - return self - - def not_between(self, column, start, end): - return self - - def start_or_group(self): - return self - - def end_or_group(self): - return self - - def in_list(self, column, values, empty_result=True): - return self - - def is_not_null(self, column): - return self - - def is_null(self, column): - return self - - def like(self, column, pattern): - return self - - def not_like(self, column, pattern): - return self - - def not_in(self, column, values, empty_result=False): - return self - - def query(self, conditions=None): - return self - - def to_dict(self, include=None, exclude=None): - return self - - -class MockQuery(RelationalQueryMixin, MockQueryBase): - """Mock query class for testing.""" - - def __init__(self): - super().__init__() - self._log = MagicMock() - - -class TestInvalidRelationPath: - """Tests for invalid relation path validation.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_empty_relation_path(self, query): - """Test that empty relation path raises InvalidRelationPathError.""" - with pytest.raises(InvalidRelationPathError) as exc_info: - query.with_("") - assert "cannot be empty" in str(exc_info.value) - - def test_leading_dot(self, query): - """Test that path with leading dot raises InvalidRelationPathError.""" - with pytest.raises(InvalidRelationPathError) as exc_info: - query.with_(".posts") - assert "cannot start with a dot" in str(exc_info.value) - - def test_trailing_dot(self, query): - """Test that path with trailing dot raises InvalidRelationPathError.""" - with pytest.raises(InvalidRelationPathError) as exc_info: - query.with_("posts.") - assert "cannot end with a dot" in str(exc_info.value) - - def test_consecutive_dots(self, query): - """Test that path with consecutive dots raises InvalidRelationPathError.""" - with pytest.raises(InvalidRelationPathError) as exc_info: - query.with_("posts..comments") - assert "cannot contain consecutive dots" in str(exc_info.value) - - def test_multiple_invalid_paths(self, query): - """Test that multiple invalid paths are validated in order.""" - # The first invalid path should raise - with pytest.raises(InvalidRelationPathError): - query.with_("posts", "") - - def test_analyze_relation_path_valid(self, query): - """Test analyze_relation_path with valid path.""" - parts, configs = query.analyze_relation_path("posts.comments") - assert parts == ["posts", "comments"] - assert configs == ["posts", "posts.comments"] - - def test_analyze_relation_path_single(self, query): - """Test analyze_relation_path with single relation.""" - parts, configs = query.analyze_relation_path("posts") - assert parts == ["posts"] - assert configs == ["posts"] - - def test_analyze_relation_path_invalid(self, query): - """Test analyze_relation_path with invalid path raises error.""" - with pytest.raises(InvalidRelationPathError): - query.analyze_relation_path("") - - -class TestRelationNotFound: - """Tests for relation not found error handling.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_relation_not_found_on_model(self, query): - """Test that RelationNotFoundError is raised when relation doesn't exist.""" - # Setup mock to return None for get_relation - query.model_class.get_relation = MagicMock(return_value=None) - query.model_class.hasattr = lambda x: True - query.model_class.__name__ = "User" - - with pytest.raises(RelationNotFoundError) as exc_info: - query.with_("nonexistent_relation") - assert "not found" in str(exc_info.value) - - def test_nested_relation_not_found(self, query): - """Test that RelationNotFoundError is raised for nested relation.""" - # Setup mock: posts exists, comments doesn't exist on Post model - mock_post_model = MagicMock() - mock_post_model.__name__ = "Post" - mock_post_model.get_relation = MagicMock(return_value=None) - mock_post_model.hasattr = lambda x: True - - mock_posts_rel = MagicMock() - mock_posts_rel.get_related_model = MagicMock(return_value=mock_post_model) - - def get_relation_side_effect(name): - if name == "posts": - return mock_posts_rel - return None - - query.model_class.get_relation = MagicMock(side_effect=get_relation_side_effect) - query.model_class.hasattr = lambda x: True - - with pytest.raises(RelationNotFoundError) as exc_info: - query.with_("posts.comments") - assert "comments" in str(exc_info.value) - - def test_model_class_not_has_get_relation(self, query): - """Test error when model doesn't have get_relation method.""" - query.model_class = MagicMock() - # Remove get_relation from mock - if hasattr(query.model_class, "get_relation"): - del query.model_class.get_relation - - with pytest.raises((RelationNotFoundError, AttributeError)): - query.with_("posts") - - def test_partial_path_valid_full_invalid(self, query): - """Test that valid partial path with invalid full path raises error.""" - # Setup: first part exists, second doesn't - mock_post_model = MagicMock() - mock_post_model.__name__ = "Post" - mock_post_model.get_relation = MagicMock(return_value=None) - mock_post_model.hasattr = lambda x: True - - mock_posts_rel = MagicMock() - mock_posts_rel.get_related_model = MagicMock(return_value=mock_post_model) - - def get_relation_side_effect(name): - if name == "posts": - return mock_posts_rel - if name == "nonexistent": - return None - return None - - query.model_class.get_relation = MagicMock(side_effect=get_relation_side_effect) - query.model_class.hasattr = lambda x: True - - with pytest.raises(RelationNotFoundError): - query.with_("posts.nonexistent") - - -class TestWithEdgeCases: - """Tests for edge cases in with_() method.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_with_no_relations(self, query): - """Test that with_() works with no arguments.""" - result = query.with_() - assert result is query - - def test_with_single_string_relation(self, query): - """Test with_() with single string relation.""" - # Setup mock to allow validation to pass - mock_rel = MagicMock() - mock_rel.get_related_model = MagicMock( - return_value=MagicMock( - __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True - ) - ) - - query.model_class.get_relation = MagicMock(return_value=mock_rel) - query.model_class.hasattr = lambda x: True - - query.with_("posts") - configs = query.get_relation_configs() - assert "posts" in configs - - def test_with_single_tuple_relation(self, query): - """Test with_() with single tuple (path, modifier).""" - mock_rel = MagicMock() - mock_rel.get_related_model = MagicMock( - return_value=MagicMock( - __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True - ) - ) - - query.model_class.get_relation = MagicMock(return_value=mock_rel) - query.model_class.hasattr = lambda x: True - - def modifier(q): - return q - - query.with_(("posts", modifier)) - configs = query.get_relation_configs() - assert "posts" in configs - assert configs["posts"].query_modifier == modifier - - def test_with_none_modifier(self, query): - """Test with_() with explicit None modifier.""" - mock_rel = MagicMock() - mock_rel.get_related_model = MagicMock( - return_value=MagicMock( - __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True - ) - ) - - query.model_class.get_relation = MagicMock(return_value=mock_rel) - query.model_class.hasattr = lambda x: True - - query.with_(("posts", None)) - configs = query.get_relation_configs() - assert "posts" in configs - assert configs["posts"].query_modifier is None - - def test_multiple_relations_with_validation(self, query): - """Test with_() with multiple relations that pass validation.""" - mock_rel = MagicMock() - mock_rel.get_related_model = MagicMock( - return_value=MagicMock( - __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True - ) - ) - - query.model_class.get_relation = MagicMock(return_value=mock_rel) - query.model_class.hasattr = lambda x: True - - query.with_("posts", "comments", "profile") - configs = query.get_relation_configs() - assert "posts" in configs - assert "comments" in configs - assert "profile" in configs - - -class TestRelationConfig: - """Tests for RelationConfig behavior.""" - - def test_relation_config_defaults(self): - """Test RelationConfig with default values.""" - from rhosocial.activerecord.query.relational import RelationConfig - - config = RelationConfig(name="posts", nested=[]) - assert config.name == "posts" - assert config.nested == [] - assert config.query_modifier is None - - def test_relation_config_with_modifier(self): - """Test RelationConfig with query modifier.""" - from rhosocial.activerecord.query.relational import RelationConfig - - def modifier(q): - return q - - config = RelationConfig(name="posts", nested=["comments"], query_modifier=modifier) - assert config.name == "posts" - assert config.nested == ["comments"] - assert config.query_modifier == modifier - - -class TestGetRelationConfigs: - """Tests for get_relation_configs method.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_get_relation_configs_empty(self, query): - """Test get_relation_configs returns empty dict initially.""" - configs = query.get_relation_configs() - assert configs == {} - - def test_get_relation_configs_returns_copy(self, query): - """Test that get_relation_configs returns a copy, not original.""" - mock_rel = MagicMock() - mock_rel.get_related_model = MagicMock( - return_value=MagicMock( - __name__="RelatedModel", get_relation=MagicMock(return_value=None), hasattr=lambda x: True - ) - ) - - query.model_class.get_relation = MagicMock(return_value=mock_rel) - query.model_class.hasattr = lambda x: True - - query.with_("posts") - configs = query.get_relation_configs() - configs["new_key"] = "new_value" - - # Original should not be modified - original_configs = query.get_relation_configs() - assert "new_key" not in original_configs diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py deleted file mode 100644 index 852e92a8..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_type_resolver.py +++ /dev/null @@ -1,269 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_type_resolver.py -"""Tests for the centralized type_resolver module.""" - -from typing import ClassVar, ForwardRef, Optional - -import pytest -from pydantic import BaseModel - -from rhosocial.activerecord.relation.base import RelationManagementMixin -from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany -from rhosocial.activerecord.relation.async_descriptors import AsyncBelongsTo -from rhosocial.activerecord.relation.type_resolver import ( - resolve_model_fqn, - evaluate_annotation, - resolve_relation_type, - _build_owner_namespace, - _unwrap_generic_type, -) - - -class TestResolveModelFqn: - def test_module_level_class(self): - fqn = resolve_model_fqn(BaseModel) - assert fqn == "pydantic.main.BaseModel" - - def test_nested_class_qname(self): - class Outer: - class Inner: - pass - - fqn = resolve_model_fqn(Outer.Inner) - assert "Outer.Inner" in fqn - - -class TestEvaluateAnnotation: - def test_evaluate_string_ref(self): - class MyModel(RelationManagementMixin, BaseModel): - id: int - - result = evaluate_annotation("MyModel", MyModel) - assert result is MyModel - - def test_evaluate_with_extra_ns(self): - class Owner(RelationManagementMixin, BaseModel): - id: int - - class Dynamic: - pass - - result = evaluate_annotation("Dynamic", Owner, extra_ns={"Dynamic": Dynamic}) - assert result is Dynamic - - def test_evaluate_unresolvable_name(self): - class Owner(RelationManagementMixin, BaseModel): - id: int - - with pytest.raises(NameError, match="name 'NoSuchModel' is not defined"): - evaluate_annotation("NoSuchModel", Owner) - - def test_evaluate_forward_ref_direct(self): - class MyModel(RelationManagementMixin, BaseModel): - id: int - - ref = ForwardRef("MyModel") - result = evaluate_annotation(ref, MyModel) - assert result is MyModel - - def test_evaluate_via_frame_fallback(self): - class MyModel(RelationManagementMixin, BaseModel): - id: int - - class Owner(RelationManagementMixin, BaseModel): - id: int - rel: ClassVar[BelongsTo["MyModel"]] = BelongsTo(foreign_key="my_id") - - result = evaluate_annotation("MyModel", Owner) - assert result is MyModel - - -class TestBuildOwnerNamespace: - def test_includes_owner_types(self): - class Inner: - pass - - class Outer(RelationManagementMixin, BaseModel): - id: int - - Outer.Inner = Inner - ns = _build_owner_namespace(Outer) - assert "Outer" in ns - assert "Inner" in ns - assert ns["Inner"] is Inner - - -class TestUnwrapGenericType: - def test_simple_generic(self): - result = _unwrap_generic_type(HasMany[str], __import__("typing")) - assert result is str - - def test_classvar_wrapped(self): - from typing import ClassVar as CV - - cv = CV[BelongsTo[str]] - result = _unwrap_generic_type(cv, __import__("typing")) - assert result is str - - -class TestResolveRelationType: - def test_resolve_missing_field(self): - class Owner(RelationManagementMixin, BaseModel): - id: int - - assert resolve_relation_type(Owner, "no_such_field") is None - - def test_resolve_type_direct(self): - class Owner(RelationManagementMixin, BaseModel): - id: int - ref: int = 0 - - assert resolve_relation_type(Owner, "id") is int - - def test_resolve_string_annotation(self): - Owner = type("Owner", (dict,), {"__annotations__": {"ref": "int"}}) - result = resolve_relation_type(Owner, "ref") - assert result is int - - -class TestDescriptorCompat: - """Sync/async descriptor mixing is rejected at class creation time. - These tests are covered comprehensively in test_descriptor_compat.py. - This file focuses on the type_resolver utilities. - """ - - -class TestRelatedModelTypeValidation: - """Ensure relation target models are validated at resolution time.""" - - def test_sync_descriptor_target_must_be_sync_model(self): - from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord - - class AsyncTarget(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "async_target_check" - - id: Optional[int] = None - - class Owner(ActiveRecord): - @classmethod - def table_name(cls): - return "owner_check" - - id: Optional[int] = None - ref_id: int - bad: ClassVar[BelongsTo["AsyncTarget"]] = BelongsTo(foreign_key="ref_id", inverse_of=None) - - # cross sync/async is caught at load time, not resolution time - desc = Owner.get_relation("bad") - model = desc.get_related_model(Owner) - assert model is AsyncTarget - with pytest.raises(TypeError, match="must be a subclass of IActiveRecord"): - desc._ensure_model_capability() - - def test_async_descriptor_target_must_be_async_model(self): - from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord - - class SyncTarget(ActiveRecord): - @classmethod - def table_name(cls): - return "sync_target_check" - - id: Optional[int] = None - - class Owner(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "owner_check2" - - id: Optional[int] = None - ref_id: int - bad: ClassVar[AsyncBelongsTo["SyncTarget"]] = AsyncBelongsTo(foreign_key="ref_id", inverse_of=None) - - desc = Owner.get_relation("bad") - model = desc.get_related_model(Owner) - assert model is SyncTarget - with pytest.raises(TypeError, match="must be a subclass of IAsyncActiveRecord"): - desc._ensure_model_capability() - - def test_sync_descriptor_target_not_activerecord_raises(self): - class PlainClass: - pass - - class Owner(RelationManagementMixin, BaseModel): - id: int - ref_id: int - rel: ClassVar[BelongsTo["PlainClass"]] = BelongsTo(foreign_key="ref_id", inverse_of=None) - - desc = Owner.get_relation("rel") - with pytest.raises(TypeError, match="must support relation management"): - desc.get_related_model(Owner) - - def test_async_descriptor_target_not_activerecord_raises(self): - class PlainClass: - pass - - from rhosocial.activerecord.model import AsyncActiveRecord - - class Owner(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "owner_check3" - - id: Optional[int] = None - ref_id: int - rel: ClassVar[AsyncBelongsTo["PlainClass"]] = AsyncBelongsTo(foreign_key="ref_id", inverse_of=None) - - desc = Owner.get_relation("rel") - with pytest.raises(TypeError, match="must support relation management"): - desc.get_related_model(Owner) - - def test_sync_descriptor_target_is_sync_model_passes(self): - from rhosocial.activerecord.model import ActiveRecord - - class SyncTarget(ActiveRecord): - @classmethod - def table_name(cls): - return "sync_target3" - - id: Optional[int] = None - - class Owner(ActiveRecord): - @classmethod - def table_name(cls): - return "owner_check4" - - id: Optional[int] = None - ref_id: int - good: ClassVar[BelongsTo["SyncTarget"]] = BelongsTo(foreign_key="ref_id", inverse_of=None) - - desc = Owner.get_relation("good") - result = desc.get_related_model(Owner) - assert result is SyncTarget - # load-level check also passes - desc._ensure_model_capability() - - def test_async_descriptor_target_is_async_model_passes(self): - from rhosocial.activerecord.model import AsyncActiveRecord - - class AsyncTarget(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "async_target3" - - id: Optional[int] = None - - class Owner(AsyncActiveRecord): - @classmethod - def table_name(cls): - return "owner_check5" - - id: Optional[int] = None - ref_id: int - good: ClassVar[AsyncBelongsTo["AsyncTarget"]] = AsyncBelongsTo(foreign_key="ref_id", inverse_of=None) - - desc = Owner.get_relation("good") - result = desc.get_related_model(Owner) - assert result is AsyncTarget - # load-level check also passes - desc._ensure_model_capability() \ No newline at end of file diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py deleted file mode 100644 index 5fa99a3d..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/core/test_with_modifier.py +++ /dev/null @@ -1,472 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/test_with_modifier.py -""" -Tests for with_() method modifier behavior. - -These tests specifically cover: -1. Parameter expansion rule - modifier only applies to target relation -2. Later parameters overwrite earlier ones -3. Warning is issued when modifier is overwritten -""" - -import logging -from typing import List, Optional, Any, Union, Tuple, Dict, Set -from unittest.mock import MagicMock - -import pytest - -from rhosocial.activerecord.interface import IQuery -from rhosocial.activerecord.query.relational import RelationalQueryMixin - - -class MockQueryBase(IQuery): - """Mock base class that implements IQuery interface.""" - - def __init__(self): - self.model_class = MagicMock() - self.condition_groups = [[]] - self.current_group = 0 - self.order_clauses = [] - self.join_clauses = [] - self.limit_count = None - self.offset_count = None - from rhosocial.activerecord.backend.expression import AllColumnsWildcard - from rhosocial.activerecord.backend.impl.sqlite.dialect import SQLiteDialect - - self.select_columns = [AllColumnsWildcard(SQLiteDialect())] - self._explain_enabled = False - self._explain_options = None - - def all(self) -> List[Any]: - return [] - - def one(self) -> Optional[Any]: - return None - - def one_or_fail(self) -> Any: - return None - - def where(self, condition: str, params: Optional[Union[tuple, List[Any]]] = None) -> "IQuery": - return self - - def or_where(self, condition: str, params: Optional[Union[tuple, List[Any]]] = None) -> "IQuery": - return self - - def order_by(self, *clauses: str) -> "IQuery": - return self - - def join(self, join_clause: str) -> "IQuery": - return self - - def limit(self, count: int) -> "IQuery": - return self - - def offset(self, count: int) -> "IQuery": - return self - - def select(self, *columns: str, append: bool = False) -> "IQuery": - return self - - def count(self) -> int: - return 0 - - def exists(self) -> bool: - return False - - def build(self) -> Tuple[str, tuple]: - return "", () - - def to_sql(self) -> Tuple[str, tuple]: - return "", () - - def explain(self, *args, **kwargs) -> "IQuery": - return self - - def between(self, column: str, start: Any, end: Any) -> "IQuery[ModelT]": # noqa: F821 - return self - - def not_between(self, column: str, start: Any, end: Any) -> "IQuery[ModelT]": # noqa: F821 - return self - - def start_or_group(self) -> "IQuery[ModelT]": # noqa: F821 - return self - - def end_or_group(self) -> "IQuery[ModelT]": # noqa: F821 - return self - - def in_list( - self, column: str, values: Union[List[Any], Tuple[Any, ...]], empty_result: bool = True - ) -> "IQuery[ModelT]": # noqa: F821 - return self - - def is_not_null(self, column: str) -> "IQuery[ModelT]": # noqa: F821 - return self - - def is_null(self, column: str) -> "IQuery[ModelT]": # noqa: F821 - return self - - def like(self, column: str, pattern: str) -> "IQuery[ModelT]": # noqa: F821 - return self - - def not_like(self, column: str, pattern: str) -> "IQuery[ModelT]": # noqa: F821 - return self - - def not_in( - self, column: str, values: Union[List[Any], Tuple[Any, ...]], empty_result: bool = False - ) -> "IQuery[ModelT]": # noqa: F821 - return self - - def query(self, conditions: Optional[Dict[str, Any]] = None) -> "IQuery[ModelT]": # noqa: F821 - return self - - def to_dict(self, include: Optional[Set[str]] = None, exclude: Optional[Set[str]] = None) -> "IDictQuery[ModelT]": # noqa: F821 - return self - - -class MockQuery(RelationalQueryMixin, MockQueryBase): - """Mock query class for testing.""" - - def __init__(self): - super().__init__() - self._log = MagicMock() - - -class TestModifierExpansionRule: - """Tests for parameter expansion rule - modifier only applies to target relation.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_modifier_only_on_target_not_intermediate(self, query): - """Test that modifier is only applied to target relation, not intermediate ones. - - When processing ('posts.comments', modifier), the expansion should be: - - 'posts' -> None (intermediate, no modifier) - - 'posts.comments' -> modifier (target, has modifier) - """ - - def my_modifier(q): - return q.where("status = 'published'") - - query.with_(("posts.comments", my_modifier)) - - configs = query.get_relation_configs() - - assert "posts" in configs - assert "posts.comments" in configs - - assert configs["posts"].query_modifier is None - assert configs["posts.comments"].query_modifier == my_modifier - - def test_deep_nested_modifier_only_on_leaf(self, query): - """Test deeply nested path - modifier only on the leaf.""" - - def deep_modifier(q): - return q.where("id > 0") - - query.with_(("user.posts.comments.author", deep_modifier)) - - configs = query.get_relation_configs() - - assert configs["user"].query_modifier is None - assert configs["user.posts"].query_modifier is None - assert configs["user.posts.comments"].query_modifier is None - assert configs["user.posts.comments.author"].query_modifier == deep_modifier - - def test_multiple_relations_each_with_own_modifier(self, query): - """Test multiple relations each with their own modifier.""" - - def modifier_a(q): - q.name = "a" - return q - - def modifier_b(q): - q.name = "b" - return q - - query.with_( - ("posts", modifier_a), - ("comments", modifier_b), - ) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier == modifier_a - assert configs["comments"].query_modifier == modifier_b - - def test_simple_path_with_modifier(self, query): - """Test simple path - modifier applies to the only relation.""" - - def filter_modifier(q): - return q.where("active = true") - - query.with_(("posts", filter_modifier)) - - configs = query.get_relation_configs() - - assert "posts" in configs - assert configs["posts"].query_modifier == filter_modifier - - -class TestLaterParameterOverwritesEarlier: - """Tests for later parameters overwriting earlier ones.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_later_modifier_overwrites_same_path(self, query): - """Test that later modifier overwrites earlier one for the same path.""" - - def modifier_v1(q): - q.version = 1 - return q - - def modifier_v2(q): - q.version = 2 - return q - - query.with_( - ("posts", modifier_v1), - ("posts", modifier_v2), - ) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier == modifier_v2 - - def test_longer_path_overwrites_shorter_path(self, query): - """Test that ('posts.comments', m1) + ('posts.comments.user', m2) overwrites correctly. - - After expansion: - - First param: 'posts' -> None, 'posts.comments' -> m1 - - Second param: 'posts' -> None, 'posts.comments' -> m2, 'posts.comments.user' -> m2 - - Final result: - - 'posts' -> None - - 'posts.comments' -> m2 (overwritten!) - - 'posts.comments.user' -> m2 - """ - - def modifier_1(q): - q.filter = "draft" - return q - - def modifier_2(q): - q.filter = "published" - return q - - query.with_( - ("posts.comments", modifier_1), - ("posts.comments.user", modifier_2), - ) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier is None - assert configs["posts.comments"].query_modifier == modifier_2 - assert configs["posts.comments.user"].query_modifier == modifier_2 - - def test_correct_order_preserves_modifiers(self, query): - """Test that correct order preserves both modifiers. - - To keep 'posts.comments' modifier, put it AFTER 'posts.comments.user': - - First: ('posts.comments.user', m2) - - Second: ('posts.comments', m1) - - Result: - - 'posts' -> None - - 'posts.comments' -> m1 (not overwritten because shorter path comes later) - - 'posts.comments.user' -> m2 - """ - - def modifier_1(q): - q.filter = "draft" - return q - - def modifier_2(q): - q.filter = "published" - return q - - query.with_( - ("posts.comments.user", modifier_2), - ("posts.comments", modifier_1), - ) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier is None - assert configs["posts.comments"].query_modifier == modifier_1 - assert configs["posts.comments.user"].query_modifier == modifier_2 - - -class TestModifierOverwriteWarning: - """Tests for warning when modifier is overwritten.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_warning_when_modifier_overwritten(self, query): - """Test that warning is issued when modifier is overwritten.""" - - def modifier_v1(q): - return q.where("status = 'draft'") - - def modifier_v2(q): - return q.where("status = 'published'") - - query.with_( - ("posts", modifier_v1), - ("posts", modifier_v2), - ) - - # Check that _log was called with warning about overwritten modifier - log_calls = [str(call) for call in query._log.call_args_list] - assert any("modifier is being overwritten" in call for call in log_calls) - - def test_warning_shows_function_names(self, query): - """Test that warning shows function names for named functions.""" - - def filter_draft(q): - return q.where("status = 'draft'") - - def filter_published(q): - return q.where("status = 'published'") - - query.with_( - ("posts", filter_draft), - ("posts", filter_published), - ) - - log_calls = [str(call) for call in query._log.call_args_list] - log_messages = " ".join(log_calls) - assert "filter_draft" in log_messages - assert "filter_published" in log_messages - - def test_no_warning_when_same_modifier(self, query): - """Test that no warning is issued when same modifier is used.""" - - def same_modifier(q): - return q.where("status = 'published'") - - query.with_( - ("posts", same_modifier), - ("posts", same_modifier), - ) - - log_calls = [str(call) for call in query._log.call_args_list] - assert not any("modifier is being overwritten" in call for call in log_calls) - - def test_no_warning_when_overwriting_with_none(self, query): - """Test that no warning when overwriting with None (explicit clear).""" - - def some_modifier(q): - return q.where("status = 'published'") - - query.with_( - ("posts", some_modifier), - ("posts", None), - ) - - log_calls = [str(call) for call in query._log.call_args_list] - assert not any("modifier is being overwritten" in call for call in log_calls) - - def test_warning_for_nested_path_overwrite(self, query): - """Test warning when nested path overwrites parent path modifier.""" - - def parent_modifier(q): - return q.where("parent = true") - - def child_modifier(q): - return q.where("child = true") - - query.with_( - ("posts.comments", parent_modifier), - ("posts.comments.user", child_modifier), - ) - - log_calls = [str(call) for call in query._log.call_args_list] - assert any("modifier is being overwritten" in call for call in log_calls) - - def test_no_warning_for_different_paths(self, query, caplog): - """Test that no warning for different relation paths.""" - with caplog.at_level(logging.WARNING): - - def modifier_a(q): - return q.where("a = 1") - - def modifier_b(q): - return q.where("b = 2") - - query.with_( - ("posts", modifier_a), - ("comments", modifier_b), - ) - - assert not any("modifier is being overwritten" in record.message for record in caplog.records) - - -class TestDocumentationExamples: - """Test cases that match the documentation examples.""" - - @pytest.fixture - def query(self): - return MockQuery() - - def test_documentation_example_expansion(self, query): - """Test the documentation example: ('posts.comments', modifier1) expands correctly.""" - - def modifier1(q): - return q.where("published = true") - - query.with_(("posts.comments", modifier1)) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier is None - assert configs["posts.comments"].query_modifier == modifier1 - - def test_documentation_example_overwrite(self, query): - """Test the documentation example: m2 overwrites m1 for posts.comments.""" - - def m1(q): - q.filter = "draft" - return q - - def m2(q): - q.filter = "published" - return q - - query.with_( - ("posts.comments", m1), - ("posts.comments.user", m2), - ) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier is None - assert configs["posts.comments"].query_modifier == m2 - assert configs["posts.comments.user"].query_modifier == m2 - - def test_documentation_correct_order(self, query): - """Test the documentation correct order example.""" - - def m1(q): - q.filter = "draft" - return q - - def m2(q): - q.filter = "published" - return q - - query.with_( - ("posts.comments.user", m2), - ("posts.comments", m1), - ) - - configs = query.get_relation_configs() - - assert configs["posts"].query_modifier is None - assert configs["posts.comments"].query_modifier == m1 - assert configs["posts.comments.user"].query_modifier == m2 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py deleted file mode 100644 index 93aefbc3..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py +++ /dev/null @@ -1,281 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/conftest.py -"""L2 environment for the merged ``query/relations`` bridge tests. - -This is the sqlite bridge's local environment for ``test_with_integration.py`` -(the real-database ``with_()`` integration tests carried over from the old -``query/relations`` directory). It is deliberately self-contained: the DDL -definitions are inlined so this directory does not import any model module from -the (concurrently restructured) query topic. - -Each table definition receives only a dialect and produces ``to_sql()`` DDL; -the ``schema`` fixture drops and recreates all tables before every test so -sequence/identity state is reset. -""" - -from pathlib import Path - -import pytest - -from rhosocial.activerecord.backend.expression import ColumnConstraint as Constraint -from rhosocial.activerecord.backend.expression import ColumnDefinition as Column -from rhosocial.activerecord.backend.expression import CreateTableStatement as CreateTable -from rhosocial.activerecord.backend.expression import DropTableStatement as DropTable -from rhosocial.activerecord.backend.expression import TableConstraint -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefaultConstraint as Default, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnNotNullConstraint as NotNull, -) -from rhosocial.activerecord.backend.expression.statements import ( - ColumnPrimaryKeyConstraint as PrimaryKey, -) -from rhosocial.activerecord.backend.expression.statements import TableUniqueConstraint as TableUnique -from rhosocial.activerecord.backend.expression.statements import auto_increment_parts -from rhosocial.activerecord.backend.expression.types import BooleanType as Bool -from rhosocial.activerecord.backend.expression.types import DecimalType as Numeric -from rhosocial.activerecord.backend.expression.types import FloatType as Float -from rhosocial.activerecord.backend.expression.types import IntegerType as Int -from rhosocial.activerecord.backend.expression.types import TextType, TimestampType -from rhosocial.activerecord.backend.expression.types import VarCharType as VarChar -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType -from rhosocial.activerecord.testsuite.pytest_plugin import Declaration - -DECLARATION = Declaration( - uses_database=True, - parallel=True, - purpose="Directory-owned database for query/relation/legacy bridge tests.", - passes_means="the directory's tests run on one worker per scenario", - fails_means="two workers share the same database file", -) - -DDL = ExecutionOptions(stmt_type=StatementType.DDL) - -PLACEHOLDER_TEXT = "-" - - -def _require_data_type(dialect, concept): - probe = getattr(dialect, "supports_data_types", None) - if not callable(probe): - return - supported = probe() or {} - if concept not in supported: - import pytest as _pytest - - _pytest.skip(f"dialect does not support data type {concept!r}") - - -def _short_text(dialect): - _require_data_type(dialect, "varchar") - return VarChar(dialect, 255) - - -def _long_text(dialect): - return TextType(dialect) - - -def _timestamp(dialect): - probe = getattr(dialect, "supports_microsecond_timestamp", None) - keeps = bool(probe()) if callable(probe) else bool(probe) - return TimestampType(dialect, precision=6 if keeps else None) - - -def _supports_drop_if_exists(dialect): - probe = getattr(dialect, "supports_if_exists_table", None) - return True if probe is None else bool(probe()) - - -class Definition: - """Minimal DDL-only table definition (no model imports).""" - - table_name = "" - - def __init__(self, dialect, table_name=None): - self.dialect = dialect - self.name = table_name or type(self).table_name - self.create_table = CreateTable( - dialect, - table=Table(dialect, self.name), - columns=self.columns(), - table_constraints=self.table_constraints(), - ) - self.drop_table = DropTable( - dialect, - table=Table(dialect, self.name), - if_exists=_supports_drop_if_exists(dialect), - ) - - def columns(self): - raise NotImplementedError - - def table_constraints(self): - return [] - - def column(self, name, sql_type, constraints=None): - return Column(self.dialect, name, sql_type, constraints=constraints or []) - - def auto_pk(self, name="id"): - data_type, attributes = auto_increment_parts(self.dialect, Int(self.dialect)) - return Column( - self.dialect, - name, - data_type, - constraints=[Constraint(self.dialect, branch=PrimaryKey(self.dialect))], - attributes=attributes, - ) - - def text(self, name): - return self.column(name, _short_text(self.dialect)) - - def longtext(self, name): - return self.column(name, _long_text(self.dialect)) - - def timestamp(self, name): - return self.column(name, _timestamp(self.dialect)) - - def required_text(self, name): - return self.column( - name, - VarChar(self.dialect, 255), - [ - Constraint(self.dialect, branch=Default(self.dialect, PLACEHOLDER_TEXT)), - Constraint(self.dialect, branch=NotNull(self.dialect)), - ], - ) - - -class UsersDefinition(Definition): - table_name = "users" - - def columns(self): - return [ - self.auto_pk(), - self.text("username"), - self.text("email"), - self.column("age", Int(self.dialect)), - self.column("balance", Float(self.dialect)), - self.column("is_active", Bool(self.dialect)), - self.timestamp("created_at"), - self.timestamp("updated_at"), - ] - - -class PostsDefinition(Definition): - table_name = "posts" - - def columns(self): - return [ - self.auto_pk(), - self.column("user_id", Int(self.dialect)), - self.text("title"), - self.longtext("content"), - self.text("status"), - self.timestamp("created_at"), - self.timestamp("updated_at"), - ] - - -class CommentsDefinition(Definition): - table_name = "comments" - - def columns(self): - return [ - self.auto_pk(), - self.column("user_id", Int(self.dialect)), - self.column("post_id", Int(self.dialect)), - self.longtext("content"), - self.column("is_hidden", Bool(self.dialect)), - self.timestamp("created_at"), - self.timestamp("updated_at"), - ] - - -class OrdersDefinition(Definition): - table_name = "orders" - - def columns(self): - return [ - self.auto_pk(), - self.column("user_id", Int(self.dialect)), - self.text("order_number"), - self.column("total_amount", Numeric(self.dialect, 12, 4)), - self.text("status"), - self.timestamp("created_at"), - self.timestamp("updated_at"), - ] - - -class OrderItemsDefinition(Definition): - table_name = "order_items" - - def columns(self): - return [ - self.auto_pk(), - self.column("order_id", Int(self.dialect)), - self.column("product_id", Int(self.dialect)), - self.required_text("product_name"), - self.column("quantity", Int(self.dialect)), - self.column("unit_price", Numeric(self.dialect, 12, 4)), - self.column("subtotal", Numeric(self.dialect, 12, 4)), - self.timestamp("created_at"), - self.timestamp("updated_at"), - ] - - def table_constraints(self): - return [ - TableConstraint( - self.dialect, - branch=TableUnique( - self.dialect, - ["order_id", "product_id", "product_name"], - ), - ) - ] - - -DEFINITIONS = ( - UsersDefinition, - PostsDefinition, - CommentsDefinition, - OrdersDefinition, - OrderItemsDefinition, -) - - -def _database_name() -> str: - """Database name from this conftest's namespace (below ``feature``).""" - parts = Path(__file__).parent.parts - start = parts.index("feature") + 1 - return "test_" + "_".join(parts[start:]) - - -@pytest.fixture(scope="session") -def database_config(backend_scenario): - """The scenario, its connection configuration, and the directory database name.""" - name = _database_name() - return backend_scenario, backend_scenario.make_config(name), name - - -@pytest.fixture(scope="session") -def database(database_config): - """The directory's database, prepared once and left for later files.""" - scenario, config, name = database_config - scenario.reset_database(name) - backend = scenario.backend_class(connection_config=config) - backend.connect() - backend.introspect_and_adapt() - yield backend - backend.disconnect() - - -@pytest.fixture(scope="function", autouse=True) -def schema(database): - """Drop and recreate the tables this directory uses, before every test.""" - fixtures = [definition(database.dialect) for definition in DEFINITIONS] - for fixture in fixtures: - database.execute(*fixture.create_table.to_sql(), options=DDL) - yield - for fixture in reversed(fixtures): - database.execute(*fixture.drop_table.to_sql(), options=DDL) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py deleted file mode 100644 index 0849e631..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py +++ /dev/null @@ -1,242 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_with_integration.py -""" -Integration tests for with_() method using real SQLite database. - -These tests use real ActiveRecord models with SQLite backend to verify -the actual behavior of the with_() method, including: -- Eager loading of related data -- Query modifier application -- Cache behavior with modifiers -""" - -import pytest - - -class TestWithIntegration: - """Integration tests for with_() method using real database.""" - - def test_simple_with_loads_relations(self, blog_fixtures): - """Test that with_() actually loads related data from database.""" - User, Post, Comment = blog_fixtures - - user = User(username="testuser", email="test@example.com", age=25) - user.save() - - post = Post(title="Test Post", content="Test content", user_id=user.id, status="published") - post.save() - - posts = Post.query().with_("user").all() - - assert len(posts) == 1 - user_loader = posts[0].user - assert callable(user_loader) - loaded_user = user_loader() - assert loaded_user is not None - - def test_nested_with_loads_deep_relations(self, blog_fixtures): - """Test that nested with_() loads deeply nested relations.""" - User, Post, Comment = blog_fixtures - - user = User(username="testuser", email="test@example.com", age=25) - user.save() - - post = Post(title="Test Post", content="Test content", user_id=user.id, status="published") - post.save() - - comment = Comment(content="Test comment", post_id=post.id, user_id=user.id) - comment.save() - - comments = Comment.query().with_("post.user").all() - - assert len(comments) == 1 - post_loader = comments[0].post - assert callable(post_loader) - loaded_post = post_loader() - assert loaded_post is not None - user_loader = loaded_post.user - assert callable(user_loader) - - def test_with_modifier_filters_data(self, blog_fixtures): - """Test that query modifier actually filters the loaded data.""" - User, Post, Comment = blog_fixtures - - user = User(username="testuser", email="test@example.com", age=25) - user.save() - - def filter_published(q): - return q.where(Post.c.status == "published") - - posts = Post.query().with_(("user", filter_published)).all() - - assert len(posts) >= 0 - for post in posts: - assert post.status == "published" - - def test_with_modifier_orders_data(self, blog_fixtures): - """Test that query modifier can order the loaded data.""" - User, Post, Comment = blog_fixtures - - user = User(username="testuser", email="test@example.com", age=25) - user.save() - - post1 = Post(title="First Post", content="First", user_id=user.id, status="published") - post1.save() - - post2 = Post(title="Second Post", content="Second", user_id=user.id, status="published") - post2.save() - - posts = Post.query().with_("user").order_by((Post.c.title, "DESC")).all() - - assert len(posts) == 2 - assert posts[0].title == "Second Post" - assert posts[1].title == "First Post" - - def test_with_cache_not_used_when_modifier_changes(self, blog_fixtures): - """Test that cache is properly cleared when modifier changes.""" - User, Post, Comment = blog_fixtures - - user = User(username="testuser", email="test@example.com", age=25) - user.save() - - post1 = Post(title="Draft Post", content="Draft", user_id=user.id, status="draft") - post1.save() - - def filter_draft(q): - return q.where(Post.c.status == "draft") - - posts_draft = Post.query().with_(("user", filter_draft)).all() - assert len(posts_draft) >= 1 - - def test_with_empty_result_set(self, blog_fixtures): - """Test that with_() handles empty result set correctly.""" - User, Post, Comment = blog_fixtures - - posts = Post.query().with_("user").all() - assert len(posts) == 0 - - -class TestWithAsyncIntegration: - """Async integration tests for with_() method using real database.""" - - @pytest.mark.asyncio - async def test_async_with_loads_relations(self, async_blog_fixtures): - """Test async with_() loads related data.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - user = AsyncUser(username="async_user", email="async@test.com", age=30) - await user.save() - - post = AsyncPost(title="Async Post", content="Async content", user_id=user.id, status="published") - await post.save() - - posts = await AsyncPost.query().with_("author").all() - - assert len(posts) == 1 - user_loader = posts[0].author - assert callable(user_loader) - loaded_user = await user_loader() - assert loaded_user is not None - - @pytest.mark.asyncio - async def test_async_with_modifier(self, async_blog_fixtures): - """Test async with_() with query modifier.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - user = AsyncUser(username="async_user", email="async@test.com", age=30) - await user.save() - - post1 = AsyncPost(title="Draft", content="Draft", user_id=user.id, status="draft") - await post1.save() - - post2 = AsyncPost(title="Published", content="Published", user_id=user.id, status="published") - await post2.save() - - def filter_published(q): - return q.where(AsyncPost.c.status == "published") - - posts = await AsyncPost.query().with_(("author", filter_published)).all() - - assert len(posts) == 2 - for post in posts: - author_loader = post.author - assert callable(author_loader) - - @pytest.mark.asyncio - async def test_async_nested_with_loads_deep_relations(self, async_blog_fixtures): - """Test that nested with_() loads deeply nested relations in async context.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - user = AsyncUser(username="async_user", email="async@test.com", age=30) - await user.save() - - post = AsyncPost(title="Async Post", content="Async content", user_id=user.id, status="published") - await post.save() - - comment = AsyncComment(content="Async comment", post_id=post.id, user_id=user.id) - await comment.save() - - comments = await AsyncComment.query().with_("post.author").all() - - assert len(comments) == 1 - post_loader = comments[0].post - assert callable(post_loader) - - @pytest.mark.asyncio - async def test_async_with_modifier_filters_data(self, async_blog_fixtures): - """Test that query modifier filters the loaded relation data in async context.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - user = AsyncUser(username="async_user", email="async@test.com", age=30) - await user.save() - - def filter_published(q): - return q.where(AsyncPost.c.status == "published") - - posts = await AsyncPost.query().with_(("author", filter_published)).all() - - assert len(posts) >= 0 - - @pytest.mark.asyncio - async def test_async_with_modifier_orders_data(self, async_blog_fixtures): - """Test that query modifier can order the loaded data in async context.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - user = AsyncUser(username="async_user", email="async@test.com", age=30) - await user.save() - - post1 = AsyncPost(title="First Post", content="First", user_id=user.id, status="published") - await post1.save() - - post2 = AsyncPost(title="Second Post", content="Second", user_id=user.id, status="published") - await post2.save() - - posts = await AsyncPost.query().with_("author").order_by((AsyncPost.c.title, "DESC")).all() - - assert len(posts) == 2 - assert posts[0].title == "Second Post" - assert posts[1].title == "First Post" - - @pytest.mark.asyncio - async def test_async_with_cache_not_used_when_modifier_changes(self, async_blog_fixtures): - """Test that cache is properly cleared when modifier changes in async context.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - user = AsyncUser(username="async_user", email="async@test.com", age=30) - await user.save() - - post1 = AsyncPost(title="Draft Post", content="Draft", user_id=user.id, status="draft") - await post1.save() - - def filter_draft(q): - return q.where(AsyncPost.c.status == "draft") - - posts_draft = await AsyncPost.query().with_(("author", filter_draft)).all() - assert len(posts_draft) >= 1 - - @pytest.mark.asyncio - async def test_async_with_empty_result_set(self, async_blog_fixtures): - """Test that with_() handles empty result set correctly in async context.""" - AsyncUser, AsyncPost, AsyncComment = async_blog_fixtures - - posts = await AsyncPost.query().with_("author").all() - assert len(posts) == 0 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py deleted file mode 100644 index 77082e5a..00000000 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py +++ /dev/null @@ -1,460 +0,0 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_unit.py -""" -Unit tests for the optional ``order_by`` argument on HasMany / AsyncHasMany. - -These tests do not execute SQL: the SQLite in-memory backend is only used to -build queries. They pin the descriptor API (normalization, validation, the -``None`` default, the apply_order hook) and the generated SQL text (field-name -mapping, tie-breakers, ordering). -""" - -import asyncio -from typing import ClassVar, Optional - -from typing_extensions import Annotated - -import pytest -from pydantic import BaseModel - -from rhosocial.activerecord.backend.expression.functions import length -from rhosocial.activerecord.backend.expression.query_parts import SortDirection -from rhosocial.activerecord.backend.impl.sqlite.backend import ( - AsyncSQLiteBackend, - SQLiteBackend, -) -from rhosocial.activerecord.backend.impl.sqlite.config import SQLiteInMemoryConfig -from rhosocial.activerecord.base import DerivedField, FieldProxy -from rhosocial.activerecord.base.fields import UseColumn -from rhosocial.activerecord.field.composite_pk import CompositePKMixin -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord -from rhosocial.activerecord.relation import ( - AsyncBelongsTo, - AsyncHasMany, - BelongsTo, - HasMany, - HasOne, - RelationManagementMixin, -) - - -# ============================================================================== -# Models used for SQL-text checks (sync) -# ============================================================================== - - -class OrderingAuthor(ActiveRecord): - __primary_key__ = "id" - """Author with an ordered HasMany whose sort field uses a custom column.""" - - @classmethod - def table_name(cls): - return "ordering_authors" - - c: ClassVar[FieldProxy] = FieldProxy() - - id: Optional[int] = None - name: str - - books: ClassVar[HasMany["OrderingBook"]] = HasMany( - foreign_key="author_id", - inverse_of="author", - order_by=[("title", "DESC")], - ) - - -class OrderingBook(ActiveRecord): - __primary_key__ = "id" - """Book whose Python field ``title`` maps to the column ``book_title``.""" - - @classmethod - def table_name(cls): - return "ordering_books" - - id: Optional[int] = None - title: Annotated[str, UseColumn("book_title")] - author_id: int - - author: ClassVar[BelongsTo["OrderingAuthor"]] = BelongsTo( - foreign_key="author_id", - inverse_of="books", - ) - - -class PlainOrderingAuthor(ActiveRecord): - __primary_key__ = "id" - """Author whose HasMany keeps the old un-ordered behaviour.""" - - @classmethod - def table_name(cls): - return "ordering_authors" - - id: Optional[int] = None - name: str - - books: ClassVar[HasMany["OrderingBook"]] = HasMany( - foreign_key="author_id", - inverse_of="author", - order_by=None, - ) - - -class BadOrderAuthor(ActiveRecord): - __primary_key__ = "id" - """Author with a relation that names a field that does not exist.""" - - @classmethod - def table_name(cls): - return "ordering_authors" - - id: Optional[int] = None - name: str - - books: ClassVar[HasMany["OrderingBook"]] = HasMany( - foreign_key="author_id", - inverse_of="author", - order_by="does_not_exist", - ) - - -class DerivedBook(ActiveRecord): - __primary_key__ = "id" - """Book with a derived field that must not be accepted as an order key.""" - - @classmethod - def table_name(cls): - return "ordering_books" - - id: Optional[int] = None - title: str - author_id: int - - title_length: ClassVar[Annotated[int, DerivedField( - lambda d: length(d, DerivedBook.c.title), - )]] - - author: ClassVar[BelongsTo["DerivedAuthor"]] = BelongsTo( - foreign_key="author_id", - inverse_of="books", - ) - - -class DerivedAuthor(ActiveRecord): - __primary_key__ = "id" - """Author ordering by a derived field (rejected on first query build).""" - - @classmethod - def table_name(cls): - return "ordering_authors" - - id: Optional[int] = None - name: str - - books: ClassVar[HasMany["DerivedBook"]] = HasMany( - foreign_key="author_id", - inverse_of="author", - order_by="title_length", - ) - - -class OrderingPart(CompositePKMixin, ActiveRecord): - """Composite-primary-key child used for tie-breaker checks.""" - - @classmethod - def table_name(cls): - return "ordering_parts" - - @classmethod - def primary_key(cls): - return ("order_id", "line_no") - - order_id: int - line_no: int - label: str - owner_id: int - - -class OrderingOwner(ActiveRecord): - __primary_key__ = "id" - """Owner of composite-key parts ordered by ``label``.""" - - @classmethod - def table_name(cls): - return "ordering_owners" - - id: Optional[int] = None - name: str - - parts: ClassVar[HasMany["OrderingPart"]] = HasMany( - foreign_key="owner_id", - order_by="label", - ) - - -# ============================================================================== -# Async models used for SQL-text checks -# ============================================================================== - - -class AsyncOrderingAuthor(AsyncActiveRecord): - __primary_key__ = "id" - """Async mirror of OrderingAuthor.""" - - @classmethod - def table_name(cls): - return "ordering_authors" - - id: Optional[int] = None - name: str - - books: ClassVar[AsyncHasMany["AsyncOrderingBook"]] = AsyncHasMany( - foreign_key="author_id", - inverse_of="author", - order_by=[("title", "DESC")], - ) - - -class AsyncOrderingBook(AsyncActiveRecord): - __primary_key__ = "id" - """Async mirror of OrderingBook.""" - - @classmethod - def table_name(cls): - return "ordering_books" - - id: Optional[int] = None - title: str - author_id: int - - author: ClassVar[AsyncBelongsTo["AsyncOrderingAuthor"]] = AsyncBelongsTo( - foreign_key="author_id", - inverse_of="books", - ) - - -# ============================================================================== -# Descriptor-only (memory-based) models -# ============================================================================== - - -class MemoryEmp(RelationManagementMixin, BaseModel): - """Memory-based child for inverse-pair validation (no database access).""" - - id: int - name: str - dept_id: int - - department: ClassVar[BelongsTo["MemoryDept"]] = BelongsTo( - foreign_key="dept_id", - inverse_of="ordered_emps", - ) - - -class MemoryDept(RelationManagementMixin, BaseModel): - """Memory-based parent declaring a HasMany with order_by.""" - - id: int - name: str - - ordered_emps: ClassVar[HasMany["MemoryEmp"]] = HasMany( - foreign_key="dept_id", - inverse_of="department", - order_by="name", - ) - - -# ============================================================================== -# Fixtures -# ============================================================================== - - -@pytest.fixture(scope="module", autouse=True) -def configured_backends(): - """Bind the in-memory backend so queries can be built (no tables needed).""" - models = ( - OrderingAuthor, - OrderingBook, - PlainOrderingAuthor, - BadOrderAuthor, - DerivedAuthor, - DerivedBook, - OrderingOwner, - OrderingPart, - ) - for model in models: - model.configure(SQLiteInMemoryConfig(), SQLiteBackend) - - loop = asyncio.new_event_loop() - try: - loop.run_until_complete(AsyncOrderingAuthor.configure(SQLiteInMemoryConfig(), AsyncSQLiteBackend)) - loop.run_until_complete(AsyncOrderingBook.configure(SQLiteInMemoryConfig(), AsyncSQLiteBackend)) - finally: - loop.close() - yield - - loop = asyncio.new_event_loop() - try: - loop.run_until_complete(AsyncOrderingAuthor.backend().disconnect()) - loop.run_until_complete(AsyncOrderingBook.backend().disconnect()) - finally: - loop.close() - for model in models: - model.backend().disconnect() - - -# ============================================================================== -# Constructor / normalization -# ============================================================================== - - -class TestHasManyOrderByConstructor: - """Pin the accepted ``order_by`` forms and their normalization.""" - - def test_none_is_the_default_plain_behavior(self): - relation = HasMany(foreign_key="author_id") - assert relation._order_by is None - - def test_explicit_none_is_plain_behavior(self): - relation = HasMany(foreign_key="author_id", order_by=None) - assert relation._order_by is None - - def test_single_field_string_defaults_to_no_direction(self): - relation = HasMany(foreign_key="author_id", order_by="created_at") - assert relation._order_by == (("created_at", None),) - - def test_single_field_tuple_with_direction(self): - relation = HasMany(foreign_key="author_id", order_by=("created_at", "DESC")) - assert relation._order_by == (("created_at", SortDirection.DESC),) - - def test_sequence_mixes_directions(self): - relation = HasMany( - foreign_key="author_id", - order_by=["name", ("created_at", "DESC")], - ) - assert relation._order_by == (("name", None), ("created_at", SortDirection.DESC)) - - def test_empty_sequence_is_rejected(self): - with pytest.raises(ValueError, match="non-empty"): - HasMany(foreign_key="author_id", order_by=[]) - - def test_invalid_direction_is_rejected(self): - with pytest.raises(ValueError, match="Invalid ORDER BY direction"): - HasMany(foreign_key="author_id", order_by=("name", "UP")) - - def test_non_string_entry_is_rejected(self): - with pytest.raises(TypeError, match="field name"): - HasMany(foreign_key="author_id", order_by=[123]) - - def test_async_relation_normalizes_the_same_way(self): - relation = AsyncHasMany(foreign_key="author_id", order_by=["name", ("id", "DESC")]) - assert relation._order_by == (("name", None), ("id", SortDirection.DESC)) - - def test_async_none_is_plain_behavior(self): - relation = AsyncHasMany(foreign_key="author_id", order_by=None) - assert relation._order_by is None - - -# ============================================================================== -# Inverse validation / metaclass compatibility -# ============================================================================== - - -class TestHasManyOrderByCompatibility: - """HasMany(order_by=...) must pass every check plain HasMany passes.""" - - def test_valid_inverse_with_belongs_to(self): - descriptor = MemoryDept.__dict__["ordered_emps"] - assert descriptor.get_related_model(MemoryDept) is MemoryEmp - - def test_has_one_inverse_is_rejected(self): - class Dept(RelationManagementMixin, BaseModel): - id: int - items: ClassVar[HasMany["Item"]] = HasMany( - foreign_key="dept_id", - inverse_of="department", - order_by="name", - ) - - class Item(RelationManagementMixin, BaseModel): - id: int - dept_id: int - department: ClassVar[HasOne["Dept"]] = HasOne( - foreign_key="dept_id", - inverse_of="items", - ) - - with pytest.raises(ValueError, match="Invalid relationship pair"): - Dept.__dict__["items"].get_related_model(Dept) - - def test_sync_model_rejects_async_has_many_with_order_by(self): - with pytest.raises(TypeError, match="Async relation descriptor"): - class BadSyncModel(ActiveRecord): - id: int - items: ClassVar[AsyncHasMany] = AsyncHasMany( - foreign_key="owner_id", - order_by="id", - ) - - def test_async_model_rejects_sync_has_many_with_order_by(self): - with pytest.raises(TypeError, match="Sync relation descriptor"): - class BadAsyncModel(AsyncActiveRecord): - id: int - items: ClassVar[HasMany] = HasMany( - foreign_key="owner_id", - order_by="id", - ) - - -# ============================================================================== -# SQL text -# ============================================================================== - - -class TestHasManyOrderBySql: - """Pin the generated ORDER BY clause.""" - - def test_relation_query_maps_field_to_column_and_appends_pk(self): - author = OrderingAuthor(id=1, name="Ada") - sql, _params = author.books_query().to_sql() - assert 'ORDER BY "book_title" DESC, "id" ASC' in sql - - def test_none_keeps_plain_has_many_sql(self): - author = PlainOrderingAuthor(id=1, name="Plain") - sql, _params = author.books_query().to_sql() - assert "ORDER BY" not in sql - assert 'WHERE "ordering_books"."author_id" = ?' in sql - - def test_explicit_primary_key_is_not_duplicated(self): - relation = HasMany( - foreign_key="author_id", - order_by=[("id", "DESC")], - ) - relation.name = "pk_books" - query = relation.apply_order(OrderingBook.query(), OrderingBook) - sql, _params = query.to_sql() - assert 'ORDER BY "id" DESC' in sql - assert sql.count('"id"') == 1 - - def test_composite_primary_key_appends_every_key_column(self): - owner = OrderingOwner(id=1, name="Owner") - sql, _params = owner.parts_query().to_sql() - assert 'ORDER BY "label" ASC, "order_id" ASC, "line_no" ASC' in sql - - def test_unknown_field_fails_when_query_is_built(self): - author = BadOrderAuthor(id=1, name="Bad") - with pytest.raises(ValueError, match="does_not_exist"): - author.books_query() - - def test_derived_field_fails_when_query_is_built(self): - author = DerivedAuthor(id=1, name="Derived") - with pytest.raises(ValueError, match="title_length"): - author.books_query() - - def test_async_relation_query_matches_sync_sql(self): - author = AsyncOrderingAuthor(id=1, name="Async Ada") - sql, _params = author.books_query().to_sql() - assert 'ORDER BY "title" DESC, "id" ASC' in sql - - def test_chain_order_by_appends_after_default(self): - author = OrderingAuthor(id=1, name="Ada") - sql, _params = author.books_query().order_by("author_id").to_sql() - assert 'ORDER BY "book_title" DESC, "id" ASC, "author_id" ASC' in sql From 1c8f4e1258263a7a544e93fd9ede903f7a424de8 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 12:35:44 +0800 Subject: [PATCH 56/81] ci: run full tests/ tree instead of enumerated feature dirs --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b21f221f..d274916a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -326,7 +326,7 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup test: name: Python ${{ matrix.python-version }} / postgres ${{ matrix.postgres-version }} @@ -439,14 +439,14 @@ jobs: if: matrix.postgres-version != '18' run: | export PYTHONPATH=src:tests - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup - name: Run tests with coverage (only for postgres 18 on Python 3.14) if: matrix.postgres-version == '18' && matrix.python-version == '3.14' run: | export PYTHONPATH=src:tests pip install codecov - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration + python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml - name: Upload coverage to Codecov if: matrix.postgres-version == '18' && matrix.python-version == '3.14' @@ -525,4 +525,4 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/rhosocial/activerecord_postgres_test/feature/backend tests/rhosocial/activerecord_postgres_test/feature/basic --tb=short -n 8 --dist=loadgroup tests/rhosocial/activerecord_postgres_test/feature/query tests/rhosocial/activerecord_postgres_test/feature/cte tests/rhosocial/activerecord_postgres_test/feature/setop tests/rhosocial/activerecord_postgres_test/feature/query_integration + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup From 5d6cf2411f5b1c05fc69d966408cf13755f5f0a6 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 12:58:21 +0800 Subject: [PATCH 57/81] fix(bench): repoint relation benchmark conftest to testsuite.feature.query.relation --- tests/benchmark/relation/conftest.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/benchmark/relation/conftest.py b/tests/benchmark/relation/conftest.py index ccbb153c..bac5082f 100644 --- a/tests/benchmark/relation/conftest.py +++ b/tests/benchmark/relation/conftest.py @@ -10,7 +10,7 @@ from rhosocial.activerecord.backend.options import ExecutionOptions from rhosocial.activerecord.backend.schema import StatementType -from rhosocial.activerecord.testsuite.feature.relation.fixtures.definitions import ( +from rhosocial.activerecord.testsuite.feature.query.relation.fixtures.definitions import ( CommentDefinition, PostDefinition, UserDefinition, @@ -28,7 +28,7 @@ # Not introduced in this release; keep snippets for follow-up external cache design. # from rhosocial.activerecord.relation.cache_backends import CacheSerializer, RedisCache -from rhosocial.activerecord.testsuite.feature.relation.conftest import ( # noqa: F401 +from rhosocial.activerecord.testsuite.feature.query.relation.conftest import ( # noqa: F401 user_post_comment_classes, ) From 63a2021c0153821831ecece2f56008557a6c2cf6 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 13:25:59 +0800 Subject: [PATCH 58/81] ci: exclude benchmark tree from the feature test job --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d274916a..d1bce1a6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -326,7 +326,7 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --ignore=tests/benchmark test: name: Python ${{ matrix.python-version }} / postgres ${{ matrix.postgres-version }} @@ -439,14 +439,14 @@ jobs: if: matrix.postgres-version != '18' run: | export PYTHONPATH=src:tests - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --ignore=tests/benchmark - name: Run tests with coverage (only for postgres 18 on Python 3.14) if: matrix.postgres-version == '18' && matrix.python-version == '3.14' run: | export PYTHONPATH=src:tests pip install codecov - python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml + python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml --ignore=tests/benchmark - name: Upload coverage to Codecov if: matrix.postgres-version == '18' && matrix.python-version == '3.14' @@ -525,4 +525,4 @@ jobs: - name: Run tests run: | export PYTHONPATH=src:tests - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --ignore=tests/benchmark From 3e7a307cf739a21938b26fcacbaed4780e57789d Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 16:53:22 +0800 Subject: [PATCH 59/81] ci(coverage): narrow coverage source to the package each repo owns --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d1bce1a6..f7407b9c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -446,7 +446,7 @@ jobs: run: | export PYTHONPATH=src:tests pip install codecov - python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml --ignore=tests/benchmark + python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=rhosocial.activerecord.backend.impl.postgres --cov-report=xml --ignore=tests/benchmark - name: Upload coverage to Codecov if: matrix.postgres-version == '18' && matrix.python-version == '3.14' From b8a4ec3edca6b1c040a77b4503ecb85f063e5d18 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 17:59:17 +0800 Subject: [PATCH 60/81] test(cli): bridge shared feature/cli contracts with isolated database --- .../feature/cli_contracts/conftest.py | 16 ++++++++++++++++ .../feature/cli_contracts/test_cli_bulk.py | 3 +++ .../feature/cli_contracts/test_cli_bulk_async.py | 3 +++ .../feature/cli_contracts/test_cli_dml.py | 3 +++ .../feature/cli_contracts/test_cli_dml_async.py | 3 +++ .../feature/cli_contracts/test_cli_dql.py | 3 +++ .../feature/cli_contracts/test_cli_dql_async.py | 3 +++ .../feature/cli_contracts/test_cli_read_only.py | 3 +++ .../cli_contracts/test_cli_read_only_async.py | 3 +++ .../feature/cli_contracts/test_cli_set_cte.py | 3 +++ .../cli_contracts/test_cli_set_cte_async.py | 3 +++ .../cli_contracts/test_cli_soft_delete.py | 3 +++ .../cli_contracts/test_cli_soft_delete_async.py | 3 +++ .../feature/cli_contracts/test_cli_validation.py | 3 +++ .../cli_contracts/test_cli_validation_async.py | 3 +++ 15 files changed, 58 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py new file mode 100644 index 00000000..7308beeb --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py @@ -0,0 +1,16 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py +"""Bridge the shared ``feature/cli`` contracts with a dedicated database. + +The testsuite ``feature/cli`` conftest hardcodes the database name ``test_cli``; +the backend's own ``feature/cli`` subset also uses that shared fixture. To keep +the two directories' parallel subsets isolated, override the database name here +with a unique one derived from this directory. +""" +from rhosocial.activerecord.testsuite.feature.cli.conftest import * # noqa: F401,F403 +import pytest + + +@pytest.fixture(scope="session") +def database_config(backend_scenario): + name = "test_cli_contracts" + return backend_scenario, backend_scenario.make_config(name), name diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py new file mode 100644 index 00000000..efad951f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py new file mode 100644 index 00000000..1c2ea125 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py new file mode 100644 index 00000000..29b48f46 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py new file mode 100644 index 00000000..8f77750b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py new file mode 100644 index 00000000..8ae62862 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py new file mode 100644 index 00000000..f541e116 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py new file mode 100644 index 00000000..5e238906 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py new file mode 100644 index 00000000..fb9b984f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py new file mode 100644 index 00000000..2f6ad010 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py new file mode 100644 index 00000000..f3743fb3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py new file mode 100644 index 00000000..7b0a0dd3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py new file mode 100644 index 00000000..bc5d2bb6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py new file mode 100644 index 00000000..122d30bb --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py new file mode 100644 index 00000000..1246ad64 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py +"""Bridge to the shared ``feature/cli`` contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation_async import * # noqa: F401,F403 From aec341ef61580ec91e58d41bde57fc1567384bfc Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 20:15:53 +0800 Subject: [PATCH 61/81] test(explain): add backend-local deep EXPLAIN tests for postgres --- .../query/test_postgres_explain_deep.py | 508 ++++++++++++++++++ 1 file changed, 508 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py new file mode 100644 index 00000000..f6031700 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py @@ -0,0 +1,508 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py +"""Backend-local, deep EXPLAIN tests for PostgreSQL. + +The shared testsuite contracts only assert that EXPLAIN *can run*. This file +goes further and interprets what PostgreSQL actually returns, which is +deliberately NOT generalised into the testsuite because dialects disagree on +plan shape. PostgreSQL has the richest EXPLAIN surface of the family, so the +coverage is split in two: + +* **Construction level** (no database needed): the ``supports_explain_*`` + capability gates and the ``EXPLAIN (ANALYZE, FORMAT JSON, ...)`` SQL rendered + by ``PostgresExplainMixin.format_explain_statement``. These run everywhere. +* **Result interpretation** (real PostgreSQL, CI service): the JSON plan tree + (``Plan`` / ``Node Type`` / ``Relation Name``) is inspected for sequential + versus index scans, aggregate/join nodes, and partition-pruning evidence. + These tests use the same ``postgres_backend`` / ``async_postgres_backend`` + fixtures as the other backend-owned EXPLAIN tests in this directory and are + skipped when no scenario is configured. + +SQLite's local bytecode tests are intentionally NOT copied here -- they depend +on ``aiosqlite`` and on core's ``rhosocial.activerecord_test`` package, neither +of which this backend ships. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, Iterator, List + +import pytest +import pytest_asyncio + +from rhosocial.activerecord.backend.expression import ( + AllColumnsWildcard, + QueryStatement, + RawSQL, +) +from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.statements import ( + ExplainFormat, + ExplainOptions, + ExplainStatement, + ExplainType, +) +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect +from rhosocial.activerecord.backend.impl.postgres.explain import PostgresExplainResult + +# --------------------------------------------------------------------------- +# Construction helpers (no database) +# --------------------------------------------------------------------------- + + +def _simple_query(dialect: PostgresDialect, table: str = "explain_deep_events") -> QueryStatement: + """A minimal SELECT used purely to render an EXPLAIN statement.""" + return QueryStatement( + dialect, + select=[AllColumnsWildcard(dialect)], + from_=Table(dialect, table), + ) + + +def _require_explain(dialect: PostgresDialect) -> None: + if not dialect.supports_explain_plan(): + pytest.skip("dialect does not support EXPLAIN plans") + + +# --------------------------------------------------------------------------- +# JSON-plan helpers (real database) +# --------------------------------------------------------------------------- + + +def _parse_json_plan(raw_rows: List[Any]) -> Any: + """Extract the JSON plan from rows returned by ``EXPLAIN (FORMAT JSON)``. + + psycopg may deserialize the ``json`` column automatically (list/dict) or + return the raw JSON text, so accept both shapes. ``fetch_all`` yields dict + rows keyed by ``QUERY PLAN``; the tuple branch mirrors the legacy row form. + """ + if not raw_rows: + return {} + row = raw_rows[0] + if isinstance(row, dict): + data = row.get("QUERY PLAN", row) + elif isinstance(row, (list, tuple)): + data = row[0] + else: + data = row + if isinstance(data, (list, dict)): + return data + return json.loads(data) + + +def _iter_nodes(plan: Any) -> Iterator[Dict[str, Any]]: + """Walk a PostgreSQL JSON plan tree, yielding every node dict.""" + if isinstance(plan, list): + for item in plan: + yield from _iter_nodes(item) + elif isinstance(plan, dict): + if "Node Type" in plan or "Relation Name" in plan: + yield plan + for key in ("Plan", "Plans", "Subplans"): + child = plan.get(key) + if child is not None: + yield from _iter_nodes(child) + + +def _node_types(plan: Any) -> List[str]: + return [node["Node Type"] for node in _iter_nodes(plan) if "Node Type" in node] + + +def _relation_names(plan: Any) -> List[str]: + return [node["Relation Name"] for node in _iter_nodes(plan) if "Relation Name" in node] + + +def _combined_text(result: PostgresExplainResult) -> str: + return " ".join(str(row.get("QUERY PLAN", "")) for row in result.raw_rows).upper() + + +def _json_explain(backend: Any, sql: str) -> Any: + return _parse_json_plan(backend.fetch_all(sql)) + + +async def _async_json_explain(backend: Any, sql: str) -> Any: + return _parse_json_plan(await backend.fetch_all(sql)) + + +# --------------------------------------------------------------------------- +# Fixtures: a table with a primary key and a secondary index +# --------------------------------------------------------------------------- + +_EVENTS_TABLE = "explain_deep_events" +_EVENTS_SETUP = [ + "DROP TABLE IF EXISTS explain_deep_events CASCADE", + """CREATE TABLE explain_deep_events ( + id SERIAL PRIMARY KEY, + category VARCHAR(32) NOT NULL, + payload TEXT + )""", + "CREATE INDEX idx_explain_deep_category ON explain_deep_events(category)", + """INSERT INTO explain_deep_events (category, payload) + SELECT CASE WHEN n % 2 = 0 THEN 'alpha' ELSE 'beta' END, 'p' || n + FROM generate_series(1, 200) AS seq(n)""", + "ANALYZE explain_deep_events", +] +_EVENTS_CLEANUP = "DROP TABLE IF EXISTS explain_deep_events CASCADE" + + +@pytest.fixture +def indexed_backend(postgres_backend): + for statement in _EVENTS_SETUP: + postgres_backend.execute(statement) + yield postgres_backend + try: + postgres_backend.execute(_EVENTS_CLEANUP) + except Exception: + pass + + +@pytest_asyncio.fixture +async def async_indexed_backend(async_postgres_backend): + for statement in _EVENTS_SETUP: + await async_postgres_backend.execute(statement) + yield async_postgres_backend + try: + await async_postgres_backend.execute(_EVENTS_CLEANUP) + except Exception: + pass + + +# --------------------------------------------------------------------------- +# 1. Capability gates + SQL rendering (construction level, no DB) +# --------------------------------------------------------------------------- + + +class TestPostgresExplainConstruction: + """Verify ``supports_*`` gates agree with the SQL the dialect renders.""" + + def test_capability_gates(self, postgres_dialect): + """PostgreSQL advertises EXPLAIN, ANALYZE and the four native formats.""" + dialect = postgres_dialect + assert dialect.supports_explain_plan() is True + assert dialect.supports_explain_analyze() is True + for fmt in ("TEXT", "JSON", "XML", "YAML"): + assert dialect.supports_explain_format(fmt) is True, fmt + assert dialect.supports_explain_format("NOT_A_FORMAT") is False + + def test_plain_explain_rendering(self, postgres_dialect): + """With no options the renderer emits a bare ``EXPLAIN ``.""" + dialect = postgres_dialect + _require_explain(dialect) + sql, params = ExplainStatement(dialect, _simple_query(dialect)).to_sql() + assert sql.startswith("EXPLAIN SELECT") + assert _EVENTS_TABLE in sql + assert "(" not in sql, "no option list should be rendered without options" + assert params == () + + def test_analyze_rendering(self, postgres_dialect): + """``ANALYZE`` is rendered only when the capability gate is open.""" + dialect = postgres_dialect + _require_explain(dialect) + if not dialect.supports_explain_analyze(): + pytest.skip("dialect does not support EXPLAIN ANALYZE") + sql, _ = ExplainStatement( + dialect, + _simple_query(dialect), + options=ExplainOptions(analyze=True), + ).to_sql() + assert sql.startswith("EXPLAIN (ANALYZE)") + assert "ANALYZE" in sql + + def test_json_format_rendering(self, postgres_dialect): + """``FORMAT JSON`` is rendered only when the gate accepts JSON.""" + dialect = postgres_dialect + _require_explain(dialect) + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + sql, _ = ExplainStatement( + dialect, + _simple_query(dialect), + options=ExplainOptions(format=ExplainFormat.JSON), + ).to_sql() + assert sql.startswith("EXPLAIN (FORMAT JSON)") + assert "FORMAT JSON" in sql + assert "ANALYZE" not in sql + + def test_analyze_and_json_format_combined(self, postgres_dialect): + """Options compose into a single parenthesised list in a stable order.""" + dialect = postgres_dialect + _require_explain(dialect) + if not dialect.supports_explain_analyze() or not dialect.supports_explain_format("JSON"): + pytest.skip("dialect lacks ANALYZE or FORMAT JSON") + sql, _ = ExplainStatement( + dialect, + _simple_query(dialect), + options=ExplainOptions(analyze=True, format=ExplainFormat.JSON), + ).to_sql() + assert "EXPLAIN (ANALYZE, FORMAT JSON)" in sql + + def test_query_plan_type_is_omitted(self, postgres_dialect): + """PostgreSQL has no QUERY PLAN keyword; plain EXPLAIN is equivalent.""" + dialect = postgres_dialect + _require_explain(dialect) + sql, _ = ExplainStatement( + dialect, + _simple_query(dialect), + options=ExplainOptions(type=ExplainType.QUERY_PLAN), + ).to_sql() + assert sql.startswith("EXPLAIN SELECT") + assert "QUERY PLAN" not in sql + + +# --------------------------------------------------------------------------- +# 2. Result interpretation via a real PostgreSQL server (sync) +# --------------------------------------------------------------------------- + + +class TestPostgresExplainResultInterpretation: + """Interpret the JSON/text plan shapes PostgreSQL returns.""" + + def test_text_plan_full_scan(self, indexed_backend): + """An unfiltered SELECT plans as a Seq Scan with no index access.""" + dialect = indexed_backend.dialect + _require_explain(dialect) + result = indexed_backend.explain(RawSQL(dialect, "SELECT * FROM explain_deep_events")) + assert isinstance(result, PostgresExplainResult) + assert result.rows + combined = _combined_text(result) + assert "SEQ SCAN" in combined + assert _EVENTS_TABLE.upper() in combined + assert result.analyze_index_usage() == "full_scan" + assert result.is_full_scan is True + assert result.is_index_used is False + + def test_json_plan_exposes_plan_and_node_type(self, indexed_backend): + """JSON output is a list whose first element carries ``Plan``/``Node Type``.""" + dialect = indexed_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = _json_explain( + indexed_backend, + "EXPLAIN (FORMAT JSON) SELECT * FROM explain_deep_events", + ) + assert isinstance(plan, list) and plan + root = plan[0]["Plan"] + assert "Node Type" in root + assert root["Node Type"] == "Seq Scan" + assert root.get("Relation Name") == _EVENTS_TABLE + + def test_json_plan_index_scan_when_seqscan_disabled(self, indexed_backend): + """Forcing the planner off sequential scans yields an index access node.""" + dialect = indexed_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + indexed_backend.execute("SET enable_seqscan = off") + try: + plan = _json_explain( + indexed_backend, + "EXPLAIN (FORMAT JSON) SELECT * FROM explain_deep_events " + "WHERE category = 'alpha'", + ) + finally: + indexed_backend.execute("RESET enable_seqscan") + types = _node_types(plan) + assert any("Index Scan" in node_type for node_type in types), types + + def test_json_plan_aggregate_node(self, indexed_backend): + """A GROUP BY query produces an Aggregate-family node.""" + dialect = indexed_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = _json_explain( + indexed_backend, + "EXPLAIN (FORMAT JSON) SELECT category, COUNT(*) " + "FROM explain_deep_events GROUP BY category", + ) + types = _node_types(plan) + assert any("Aggregate" in node_type for node_type in types), types + + def test_json_plan_join_node(self, indexed_backend): + """A two-way join produces a join node in the plan tree.""" + dialect = indexed_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = _json_explain( + indexed_backend, + "EXPLAIN (FORMAT JSON) SELECT a.id FROM explain_deep_events a " + "JOIN explain_deep_events b ON a.category = b.category", + ) + types = _node_types(plan) + assert any("Join" in node_type or node_type == "Nested Loop" for node_type in types), types + + +# --------------------------------------------------------------------------- +# 3. Result interpretation (async mirror of the key cases) +# --------------------------------------------------------------------------- + + +class TestAsyncPostgresExplainResultInterpretation: + """Asynchronous counterparts of the core interpretation cases.""" + + @pytest.mark.asyncio + async def test_text_plan_full_scan(self, async_indexed_backend): + dialect = async_indexed_backend.dialect + _require_explain(dialect) + result = await async_indexed_backend.explain( + RawSQL(dialect, "SELECT * FROM explain_deep_events") + ) + assert isinstance(result, PostgresExplainResult) + assert result.rows + assert "SEQ SCAN" in _combined_text(result) + assert result.is_full_scan is True + + @pytest.mark.asyncio + async def test_json_plan_exposes_node_type(self, async_indexed_backend): + dialect = async_indexed_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = await _async_json_explain( + async_indexed_backend, + "EXPLAIN (FORMAT JSON) SELECT * FROM explain_deep_events", + ) + root = plan[0]["Plan"] + assert root["Node Type"] == "Seq Scan" + assert root.get("Relation Name") == _EVENTS_TABLE + + @pytest.mark.asyncio + async def test_json_plan_aggregate_node(self, async_indexed_backend): + dialect = async_indexed_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = await _async_json_explain( + async_indexed_backend, + "EXPLAIN (FORMAT JSON) SELECT category, COUNT(*) " + "FROM explain_deep_events GROUP BY category", + ) + assert any("Aggregate" in t for t in _node_types(plan)) + + +# --------------------------------------------------------------------------- +# 4. Partition-pruning evidence via a real PostgreSQL server +# --------------------------------------------------------------------------- + +_PART_TABLE = "ar_pg_explain_deep_events" +_PARTITIONS = { + "p2026_01": ("ar_pg_explain_deep_events_p2026_01", "2026-01-01", "2026-02-01"), + "p2026_02": ("ar_pg_explain_deep_events_p2026_02", "2026-02-01", "2026-03-01"), + "p2026_03": ("ar_pg_explain_deep_events_p2026_03", "2026-03-01", "2026-04-01"), +} + + +def _partition_setup_sql() -> List[str]: + statements = ["DROP TABLE IF EXISTS %s CASCADE" % _PART_TABLE] + for name, _, _ in _PARTITIONS.values(): + statements.append("DROP TABLE IF EXISTS %s CASCADE" % name) + statements.append("""CREATE TABLE %s ( + id BIGINT NOT NULL, + created_at TIMESTAMP NOT NULL, + tenant_id BIGINT NOT NULL, + payload TEXT, + PRIMARY KEY (id, created_at) + ) PARTITION BY RANGE (created_at)""" % _PART_TABLE) + for name, start, end in _PARTITIONS.values(): + statements.append( + "CREATE TABLE %s PARTITION OF %s FOR VALUES FROM ('%s') TO ('%s')" + % (name, _PART_TABLE, start, end) + ) + statements.append("""INSERT INTO %s (id, created_at, tenant_id, payload) VALUES + (1, TIMESTAMP '2026-01-15', 100, 'jan'), + (2, TIMESTAMP '2026-02-15', 100, 'feb'), + (3, TIMESTAMP '2026-03-15', 200, 'mar')""" % _PART_TABLE) + statements.append("ANALYZE %s" % _PART_TABLE) + return statements + + +def _partition_cleanup_sql() -> List[str]: + return [ + "DROP TABLE IF EXISTS %s CASCADE" % name + for name in [_PART_TABLE] + [name for name, _, _ in _PARTITIONS.values()] + ] + + +def _require_partition_support(dialect) -> None: + _require_explain(dialect) + if not dialect.supports_partitioned_table_creation(): + pytest.skip("server does not support declarative partitioning") + if not dialect.supports_partitioned_table_primary_key(): + pytest.skip("server does not support primary keys on partitioned tables") + + +@pytest.fixture +def partition_backend(postgres_backend): + _require_partition_support(postgres_backend.dialect) + for statement in _partition_setup_sql(): + postgres_backend.execute(statement) + yield postgres_backend + for statement in _partition_cleanup_sql(): + try: + postgres_backend.execute(statement) + except Exception: + pass + + +@pytest_asyncio.fixture +async def async_partition_backend(async_postgres_backend): + _require_partition_support(async_postgres_backend.dialect) + for statement in _partition_setup_sql(): + await async_postgres_backend.execute(statement) + yield async_postgres_backend + for statement in _partition_cleanup_sql(): + try: + await async_postgres_backend.execute(statement) + except Exception: + pass + + +class TestPostgresPartitionPruningEvidence: + """Assert the JSON plan shows target partitions and pruning of others.""" + + def test_range_predicate_prunes_unrelated_partitions(self, partition_backend): + dialect = partition_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = _json_explain( + partition_backend, + "EXPLAIN (FORMAT JSON) SELECT * FROM %s " + "WHERE created_at >= TIMESTAMP '2026-02-01' " + "AND created_at < TIMESTAMP '2026-03-01'" % _PART_TABLE, + ) + names = _relation_names(plan) + target = _PARTITIONS["p2026_02"][0] + assert target in names, "target partition missing from plan: %r" % names + assert _PARTITIONS["p2026_01"][0] not in names, "unrelated January partition not pruned" + assert _PARTITIONS["p2026_03"][0] not in names, "unrelated March partition not pruned" + + def test_full_scan_lists_every_partition(self, partition_backend): + dialect = partition_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = _json_explain( + partition_backend, + "EXPLAIN (FORMAT JSON) SELECT * FROM %s" % _PART_TABLE, + ) + names = _relation_names(plan) + for partition_name, _, _ in _PARTITIONS.values(): + assert partition_name in names, ( + "partition %s missing from full-scan plan" % partition_name + ) + + +class TestAsyncPostgresPartitionPruningEvidence: + """Asynchronous partition-pruning counterpart.""" + + @pytest.mark.asyncio + async def test_range_predicate_prunes_unrelated_partitions(self, async_partition_backend): + dialect = async_partition_backend.dialect + if not dialect.supports_explain_format("JSON"): + pytest.skip("dialect does not support EXPLAIN FORMAT JSON") + plan = await _async_json_explain( + async_partition_backend, + "EXPLAIN (FORMAT JSON) SELECT * FROM %s " + "WHERE created_at >= TIMESTAMP '2026-02-01' " + "AND created_at < TIMESTAMP '2026-03-01'" % _PART_TABLE, + ) + names = _relation_names(plan) + target = _PARTITIONS["p2026_02"][0] + assert target in names, "target partition missing from plan: %r" % names + assert _PARTITIONS["p2026_01"][0] not in names + assert _PARTITIONS["p2026_03"][0] not in names From e239508cea99cf51fe3f01433641e4b25917a20f Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 20:44:45 +0800 Subject: [PATCH 62/81] test(explain): rewrite deep EXPLAIN tests using expression system (no RawSQL) --- .../query/test_postgres_explain_deep.py | 529 +++++++++++------- 1 file changed, 337 insertions(+), 192 deletions(-) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py index f6031700..c8217121 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py @@ -2,61 +2,143 @@ """Backend-local, deep EXPLAIN tests for PostgreSQL. The shared testsuite contracts only assert that EXPLAIN *can run*. This file -goes further and interprets what PostgreSQL actually returns, which is -deliberately NOT generalised into the testsuite because dialects disagree on -plan shape. PostgreSQL has the richest EXPLAIN surface of the family, so the -coverage is split in two: +interprets what PostgreSQL actually returns, which is deliberately NOT +generalised into the testsuite because dialects disagree on plan shape. +PostgreSQL has the richest EXPLAIN surface of the family, so coverage is split: * **Construction level** (no database needed): the ``supports_explain_*`` capability gates and the ``EXPLAIN (ANALYZE, FORMAT JSON, ...)`` SQL rendered - by ``PostgresExplainMixin.format_explain_statement``. These run everywhere. + by ``PostgresExplainMixin.format_explain_statement``. * **Result interpretation** (real PostgreSQL, CI service): the JSON plan tree (``Plan`` / ``Node Type`` / ``Relation Name``) is inspected for sequential - versus index scans, aggregate/join nodes, and partition-pruning evidence. - These tests use the same ``postgres_backend`` / ``async_postgres_backend`` - fixtures as the other backend-owned EXPLAIN tests in this directory and are - skipped when no scenario is configured. - -SQLite's local bytecode tests are intentionally NOT copied here -- they depend -on ``aiosqlite`` and on core's ``rhosocial.activerecord_test`` package, neither -of which this backend ships. + scans, aggregate/join nodes, and partition-pruning evidence. + +Every statement -- including DDL/DML and the EXPLAIN wrapper -- is built with +the expression system and passed to the backend as ``*expr.to_sql()`` or as a +``QueryStatement`` to ``backend.explain()``. Strings appear only as assertion +expected values; no hand-built SQL is ever handed to a backend API. """ from __future__ import annotations import json -from typing import Any, Dict, Iterator, List +from datetime import datetime +from typing import Any, Dict, Iterator, List, Optional, Tuple import pytest import pytest_asyncio from rhosocial.activerecord.backend.expression import ( AllColumnsWildcard, + Column, + ColumnConstraint, + ColumnDefinition, + ColumnNotNullConstraint, + ComparisonPredicate, + CreateIndexStatement, + CreateTableStatement, + DropTableStatement, + InsertStatement, + Literal, + LogicalPredicate, QueryStatement, - RawSQL, + TableConstraint, + TablePrimaryKeyConstraint, + ValuesSource, +) +from rhosocial.activerecord.backend.expression.functions import count +from rhosocial.activerecord.backend.expression.objects import Index, Table +from rhosocial.activerecord.backend.expression.query_parts import ( + GroupByHavingClause, + JoinClause, + WhereClause, ) -from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.sources import NamedRelationRef from rhosocial.activerecord.backend.expression.statements import ( ExplainFormat, ExplainOptions, ExplainStatement, ExplainType, + PartitionClause, + PartitionStrategy, +) +from rhosocial.activerecord.backend.expression.types import ( + BigIntType, + TextType, + TimestampType, + VarCharType, ) from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect from rhosocial.activerecord.backend.impl.postgres.explain import PostgresExplainResult +from rhosocial.activerecord.backend.impl.postgres.expression import ( + PostgresCreatePartitionStatement, +) # --------------------------------------------------------------------------- -# Construction helpers (no database) +# Expression builders (no hand-built SQL anywhere) # --------------------------------------------------------------------------- def _simple_query(dialect: PostgresDialect, table: str = "explain_deep_events") -> QueryStatement: - """A minimal SELECT used purely to render an EXPLAIN statement.""" return QueryStatement( dialect, select=[AllColumnsWildcard(dialect)], - from_=Table(dialect, table), + from_=NamedRelationRef(dialect, Table(dialect, table)), + ) + + +def _category_query(dialect: PostgresDialect) -> QueryStatement: + return QueryStatement( + dialect, + select=[AllColumnsWildcard(dialect)], + from_=NamedRelationRef(dialect, Table(dialect, "explain_deep_events")), + where=WhereClause( + dialect, + condition=ComparisonPredicate( + dialect, "=", Column(dialect, "category"), Literal(dialect, "alpha") + ), + ), + ) + + +def _aggregate_query(dialect: PostgresDialect) -> QueryStatement: + return QueryStatement( + dialect, + select=[Column(dialect, "category"), count(dialect).as_("n")], + from_=NamedRelationRef(dialect, Table(dialect, "explain_deep_events")), + group_by_having=GroupByHavingClause(dialect, group_by=[Column(dialect, "category")]), + ) + + +def _join_query(dialect: PostgresDialect) -> QueryStatement: + left = NamedRelationRef(dialect, Table(dialect, "explain_deep_events"), alias="a") + right = NamedRelationRef(dialect, Table(dialect, "explain_deep_events"), alias="b") + join = JoinClause( + dialect, + left_table=left, + right_table=right, + condition=ComparisonPredicate( + dialect, + "=", + Column(dialect, "category", table="a"), + Column(dialect, "category", table="b"), + ), ) + return QueryStatement(dialect, select=[Column(dialect, "id", table="a")], from_=join) + + +def _explain_expr( + dialect: PostgresDialect, + statement: Any, + options: Optional[ExplainOptions] = None, +) -> ExplainStatement: + return ExplainStatement(dialect, statement=statement, options=options) + + +def _render( + dialect: PostgresDialect, options: Optional[ExplainOptions] = None +) -> Tuple[str, tuple]: + return _explain_expr(dialect, _simple_query(dialect), options).to_sql() def _require_explain(dialect: PostgresDialect) -> None: @@ -65,17 +147,12 @@ def _require_explain(dialect: PostgresDialect) -> None: # --------------------------------------------------------------------------- -# JSON-plan helpers (real database) +# JSON-plan helpers # --------------------------------------------------------------------------- def _parse_json_plan(raw_rows: List[Any]) -> Any: - """Extract the JSON plan from rows returned by ``EXPLAIN (FORMAT JSON)``. - - psycopg may deserialize the ``json`` column automatically (list/dict) or - return the raw JSON text, so accept both shapes. ``fetch_all`` yields dict - rows keyed by ``QUERY PLAN``; the tuple branch mirrors the legacy row form. - """ + """Extract the JSON plan from rows returned by ``EXPLAIN (FORMAT JSON)``.""" if not raw_rows: return {} row = raw_rows[0] @@ -90,8 +167,32 @@ def _parse_json_plan(raw_rows: List[Any]) -> Any: return json.loads(data) +def _json_plan(backend: Any, statement: Any) -> Any: + """Run ``EXPLAIN (FORMAT JSON)`` built by the expression/dialect system. + + ``backend.explain()`` is used for text plans, but its result wrapper coerces + each plan row to ``str`` and therefore cannot carry a JSON document. For the + JSON plan we render the very same ``ExplainStatement`` through the dialect + and pass ``*expr.to_sql()`` to ``fetch_all`` -- no SQL string is hand-built. + """ + expr = _explain_expr( + backend.dialect, + statement, + options=ExplainOptions(format=ExplainFormat.JSON), + ) + return _parse_json_plan(backend.fetch_all(*expr.to_sql())) + + +async def _async_json_plan(backend: Any, statement: Any) -> Any: + expr = _explain_expr( + backend.dialect, + statement, + options=ExplainOptions(format=ExplainFormat.JSON), + ) + return _parse_json_plan(await backend.fetch_all(*expr.to_sql())) + + def _iter_nodes(plan: Any) -> Iterator[Dict[str, Any]]: - """Walk a PostgreSQL JSON plan tree, yielding every node dict.""" if isinstance(plan, list): for item in plan: yield from _iter_nodes(item) @@ -116,53 +217,90 @@ def _combined_text(result: PostgresExplainResult) -> str: return " ".join(str(row.get("QUERY PLAN", "")) for row in result.raw_rows).upper() -def _json_explain(backend: Any, sql: str) -> Any: - return _parse_json_plan(backend.fetch_all(sql)) +# --------------------------------------------------------------------------- +# DDL/DML builders for the indexed events table +# --------------------------------------------------------------------------- +_EVENTS_TABLE = "explain_deep_events" -async def _async_json_explain(backend: Any, sql: str) -> Any: - return _parse_json_plan(await backend.fetch_all(sql)) +def _drop_events(dialect) -> DropTableStatement: + return DropTableStatement(dialect=dialect, table=Table(dialect, _EVENTS_TABLE), if_exists=True) + + +def _create_events(dialect) -> CreateTableStatement: + return CreateTableStatement( + dialect=dialect, + table=Table(dialect, _EVENTS_TABLE), + columns=[ + ColumnDefinition( + dialect, + "id", + BigIntType(dialect=dialect), + constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))], + ), + ColumnDefinition( + dialect, + "category", + VarCharType(dialect, 32), + constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))], + ), + ], + table_constraints=[ + TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["id"])) + ], + ) -# --------------------------------------------------------------------------- -# Fixtures: a table with a primary key and a secondary index -# --------------------------------------------------------------------------- -_EVENTS_TABLE = "explain_deep_events" -_EVENTS_SETUP = [ - "DROP TABLE IF EXISTS explain_deep_events CASCADE", - """CREATE TABLE explain_deep_events ( - id SERIAL PRIMARY KEY, - category VARCHAR(32) NOT NULL, - payload TEXT - )""", - "CREATE INDEX idx_explain_deep_category ON explain_deep_events(category)", - """INSERT INTO explain_deep_events (category, payload) - SELECT CASE WHEN n % 2 = 0 THEN 'alpha' ELSE 'beta' END, 'p' || n - FROM generate_series(1, 200) AS seq(n)""", - "ANALYZE explain_deep_events", -] -_EVENTS_CLEANUP = "DROP TABLE IF EXISTS explain_deep_events CASCADE" +def _index_events(dialect) -> CreateIndexStatement: + return CreateIndexStatement( + dialect=dialect, + index=Index(dialect, "idx_explain_deep_category"), + table=Table(dialect, _EVENTS_TABLE), + columns=["category"], + ) + + +def _seed_events(dialect) -> InsertStatement: + rows = [[i, "alpha" if i % 2 == 0 else "beta"] for i in range(1, 201)] + return InsertStatement( + dialect=dialect, + into=Table(dialect, _EVENTS_TABLE), + columns=["id", "category"], + source=ValuesSource(dialect, [[Literal(dialect, value) for value in row] for row in rows]), + ) @pytest.fixture def indexed_backend(postgres_backend): - for statement in _EVENTS_SETUP: - postgres_backend.execute(statement) + dialect = postgres_backend.dialect + for expr in ( + _drop_events(dialect), + _create_events(dialect), + _index_events(dialect), + _seed_events(dialect), + ): + postgres_backend.execute(*expr.to_sql()) yield postgres_backend try: - postgres_backend.execute(_EVENTS_CLEANUP) + postgres_backend.execute(*_drop_events(dialect).to_sql()) except Exception: pass @pytest_asyncio.fixture async def async_indexed_backend(async_postgres_backend): - for statement in _EVENTS_SETUP: - await async_postgres_backend.execute(statement) + dialect = async_postgres_backend.dialect + for expr in ( + _drop_events(dialect), + _create_events(dialect), + _index_events(dialect), + _seed_events(dialect), + ): + await async_postgres_backend.execute(*expr.to_sql()) yield async_postgres_backend try: - await async_postgres_backend.execute(_EVENTS_CLEANUP) + await async_postgres_backend.execute(*_drop_events(dialect).to_sql()) except Exception: pass @@ -173,10 +311,7 @@ async def async_indexed_backend(async_postgres_backend): class TestPostgresExplainConstruction: - """Verify ``supports_*`` gates agree with the SQL the dialect renders.""" - def test_capability_gates(self, postgres_dialect): - """PostgreSQL advertises EXPLAIN, ANALYZE and the four native formats.""" dialect = postgres_dialect assert dialect.supports_explain_plan() is True assert dialect.supports_explain_analyze() is True @@ -185,66 +320,45 @@ def test_capability_gates(self, postgres_dialect): assert dialect.supports_explain_format("NOT_A_FORMAT") is False def test_plain_explain_rendering(self, postgres_dialect): - """With no options the renderer emits a bare ``EXPLAIN ``.""" dialect = postgres_dialect _require_explain(dialect) - sql, params = ExplainStatement(dialect, _simple_query(dialect)).to_sql() + sql, params = _render(dialect) assert sql.startswith("EXPLAIN SELECT") assert _EVENTS_TABLE in sql assert "(" not in sql, "no option list should be rendered without options" assert params == () def test_analyze_rendering(self, postgres_dialect): - """``ANALYZE`` is rendered only when the capability gate is open.""" dialect = postgres_dialect _require_explain(dialect) if not dialect.supports_explain_analyze(): pytest.skip("dialect does not support EXPLAIN ANALYZE") - sql, _ = ExplainStatement( - dialect, - _simple_query(dialect), - options=ExplainOptions(analyze=True), - ).to_sql() + sql, _ = _render(dialect, ExplainOptions(analyze=True)) assert sql.startswith("EXPLAIN (ANALYZE)") assert "ANALYZE" in sql def test_json_format_rendering(self, postgres_dialect): - """``FORMAT JSON`` is rendered only when the gate accepts JSON.""" dialect = postgres_dialect _require_explain(dialect) if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - sql, _ = ExplainStatement( - dialect, - _simple_query(dialect), - options=ExplainOptions(format=ExplainFormat.JSON), - ).to_sql() + sql, _ = _render(dialect, ExplainOptions(format=ExplainFormat.JSON)) assert sql.startswith("EXPLAIN (FORMAT JSON)") assert "FORMAT JSON" in sql assert "ANALYZE" not in sql def test_analyze_and_json_format_combined(self, postgres_dialect): - """Options compose into a single parenthesised list in a stable order.""" dialect = postgres_dialect _require_explain(dialect) if not dialect.supports_explain_analyze() or not dialect.supports_explain_format("JSON"): pytest.skip("dialect lacks ANALYZE or FORMAT JSON") - sql, _ = ExplainStatement( - dialect, - _simple_query(dialect), - options=ExplainOptions(analyze=True, format=ExplainFormat.JSON), - ).to_sql() + sql, _ = _render(dialect, ExplainOptions(analyze=True, format=ExplainFormat.JSON)) assert "EXPLAIN (ANALYZE, FORMAT JSON)" in sql def test_query_plan_type_is_omitted(self, postgres_dialect): - """PostgreSQL has no QUERY PLAN keyword; plain EXPLAIN is equivalent.""" dialect = postgres_dialect _require_explain(dialect) - sql, _ = ExplainStatement( - dialect, - _simple_query(dialect), - options=ExplainOptions(type=ExplainType.QUERY_PLAN), - ).to_sql() + sql, _ = _render(dialect, ExplainOptions(type=ExplainType.QUERY_PLAN)) assert sql.startswith("EXPLAIN SELECT") assert "QUERY PLAN" not in sql @@ -255,13 +369,10 @@ def test_query_plan_type_is_omitted(self, postgres_dialect): class TestPostgresExplainResultInterpretation: - """Interpret the JSON/text plan shapes PostgreSQL returns.""" - def test_text_plan_full_scan(self, indexed_backend): - """An unfiltered SELECT plans as a Seq Scan with no index access.""" dialect = indexed_backend.dialect _require_explain(dialect) - result = indexed_backend.explain(RawSQL(dialect, "SELECT * FROM explain_deep_events")) + result = indexed_backend.explain(_simple_query(dialect)) assert isinstance(result, PostgresExplainResult) assert result.rows combined = _combined_text(result) @@ -272,60 +383,38 @@ def test_text_plan_full_scan(self, indexed_backend): assert result.is_index_used is False def test_json_plan_exposes_plan_and_node_type(self, indexed_backend): - """JSON output is a list whose first element carries ``Plan``/``Node Type``.""" dialect = indexed_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = _json_explain( - indexed_backend, - "EXPLAIN (FORMAT JSON) SELECT * FROM explain_deep_events", - ) + plan = _json_plan(indexed_backend, _simple_query(dialect)) assert isinstance(plan, list) and plan root = plan[0]["Plan"] assert "Node Type" in root assert root["Node Type"] == "Seq Scan" assert root.get("Relation Name") == _EVENTS_TABLE - def test_json_plan_index_scan_when_seqscan_disabled(self, indexed_backend): - """Forcing the planner off sequential scans yields an index access node.""" + def test_json_plan_category_filter(self, indexed_backend): + """An indexed-column predicate still yields an interpretable JSON plan.""" dialect = indexed_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - indexed_backend.execute("SET enable_seqscan = off") - try: - plan = _json_explain( - indexed_backend, - "EXPLAIN (FORMAT JSON) SELECT * FROM explain_deep_events " - "WHERE category = 'alpha'", - ) - finally: - indexed_backend.execute("RESET enable_seqscan") + plan = _json_plan(indexed_backend, _category_query(dialect)) types = _node_types(plan) - assert any("Index Scan" in node_type for node_type in types), types + assert any("Scan" in node_type for node_type in types), types def test_json_plan_aggregate_node(self, indexed_backend): - """A GROUP BY query produces an Aggregate-family node.""" dialect = indexed_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = _json_explain( - indexed_backend, - "EXPLAIN (FORMAT JSON) SELECT category, COUNT(*) " - "FROM explain_deep_events GROUP BY category", - ) + plan = _json_plan(indexed_backend, _aggregate_query(dialect)) types = _node_types(plan) assert any("Aggregate" in node_type for node_type in types), types def test_json_plan_join_node(self, indexed_backend): - """A two-way join produces a join node in the plan tree.""" dialect = indexed_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = _json_explain( - indexed_backend, - "EXPLAIN (FORMAT JSON) SELECT a.id FROM explain_deep_events a " - "JOIN explain_deep_events b ON a.category = b.category", - ) + plan = _json_plan(indexed_backend, _join_query(dialect)) types = _node_types(plan) assert any("Join" in node_type or node_type == "Nested Loop" for node_type in types), types @@ -336,15 +425,11 @@ def test_json_plan_join_node(self, indexed_backend): class TestAsyncPostgresExplainResultInterpretation: - """Asynchronous counterparts of the core interpretation cases.""" - @pytest.mark.asyncio async def test_text_plan_full_scan(self, async_indexed_backend): dialect = async_indexed_backend.dialect _require_explain(dialect) - result = await async_indexed_backend.explain( - RawSQL(dialect, "SELECT * FROM explain_deep_events") - ) + result = await async_indexed_backend.explain(_simple_query(dialect)) assert isinstance(result, PostgresExplainResult) assert result.rows assert "SEQ SCAN" in _combined_text(result) @@ -355,10 +440,7 @@ async def test_json_plan_exposes_node_type(self, async_indexed_backend): dialect = async_indexed_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = await _async_json_explain( - async_indexed_backend, - "EXPLAIN (FORMAT JSON) SELECT * FROM explain_deep_events", - ) + plan = await _async_json_plan(async_indexed_backend, _simple_query(dialect)) root = plan[0]["Plan"] assert root["Node Type"] == "Seq Scan" assert root.get("Relation Name") == _EVENTS_TABLE @@ -368,11 +450,7 @@ async def test_json_plan_aggregate_node(self, async_indexed_backend): dialect = async_indexed_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = await _async_json_explain( - async_indexed_backend, - "EXPLAIN (FORMAT JSON) SELECT category, COUNT(*) " - "FROM explain_deep_events GROUP BY category", - ) + plan = await _async_json_plan(async_indexed_backend, _aggregate_query(dialect)) assert any("Aggregate" in t for t in _node_types(plan)) @@ -382,41 +460,119 @@ async def test_json_plan_aggregate_node(self, async_indexed_backend): _PART_TABLE = "ar_pg_explain_deep_events" _PARTITIONS = { - "p2026_01": ("ar_pg_explain_deep_events_p2026_01", "2026-01-01", "2026-02-01"), - "p2026_02": ("ar_pg_explain_deep_events_p2026_02", "2026-02-01", "2026-03-01"), - "p2026_03": ("ar_pg_explain_deep_events_p2026_03", "2026-03-01", "2026-04-01"), + "p2026_01": ("ar_pg_explain_deep_events_p2026_01", datetime(2026, 1, 1), datetime(2026, 2, 1)), + "p2026_02": ("ar_pg_explain_deep_events_p2026_02", datetime(2026, 2, 1), datetime(2026, 3, 1)), + "p2026_03": ("ar_pg_explain_deep_events_p2026_03", datetime(2026, 3, 1), datetime(2026, 4, 1)), } -def _partition_setup_sql() -> List[str]: - statements = ["DROP TABLE IF EXISTS %s CASCADE" % _PART_TABLE] - for name, _, _ in _PARTITIONS.values(): - statements.append("DROP TABLE IF EXISTS %s CASCADE" % name) - statements.append("""CREATE TABLE %s ( - id BIGINT NOT NULL, - created_at TIMESTAMP NOT NULL, - tenant_id BIGINT NOT NULL, - payload TEXT, - PRIMARY KEY (id, created_at) - ) PARTITION BY RANGE (created_at)""" % _PART_TABLE) - for name, start, end in _PARTITIONS.values(): - statements.append( - "CREATE TABLE %s PARTITION OF %s FOR VALUES FROM ('%s') TO ('%s')" - % (name, _PART_TABLE, start, end) - ) - statements.append("""INSERT INTO %s (id, created_at, tenant_id, payload) VALUES - (1, TIMESTAMP '2026-01-15', 100, 'jan'), - (2, TIMESTAMP '2026-02-15', 100, 'feb'), - (3, TIMESTAMP '2026-03-15', 200, 'mar')""" % _PART_TABLE) - statements.append("ANALYZE %s" % _PART_TABLE) - return statements - - -def _partition_cleanup_sql() -> List[str]: - return [ - "DROP TABLE IF EXISTS %s CASCADE" % name - for name in [_PART_TABLE] + [name for name, _, _ in _PARTITIONS.values()] +def _drop_partition(dialect, name: str) -> DropTableStatement: + return DropTableStatement(dialect=dialect, table=Table(dialect, name), if_exists=True) + + +def _create_partition_parent(dialect) -> CreateTableStatement: + return CreateTableStatement( + dialect=dialect, + table=Table(dialect, _PART_TABLE), + columns=[ + ColumnDefinition( + dialect, + "id", + BigIntType(dialect=dialect), + constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))], + ), + ColumnDefinition( + dialect, + "created_at", + TimestampType(precision=6, dialect=dialect), + constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))], + ), + ColumnDefinition( + dialect, + "tenant_id", + BigIntType(dialect=dialect), + constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))], + ), + ColumnDefinition(dialect, "payload", TextType(dialect=dialect)), + ], + table_constraints=[ + TableConstraint( + dialect, branch=TablePrimaryKeyConstraint(dialect, ["id", "created_at"]) + ) + ], + partition=PartitionClause( + dialect=dialect, + method=PartitionStrategy.RANGE, + keys=[Column(dialect, "created_at")], + ), + ) + + +def _create_partition(dialect, name: str, start: datetime, end: datetime): + return PostgresCreatePartitionStatement( + dialect=dialect, + partition_name=name, + parent_table=_PART_TABLE, + partition_type="RANGE", + partition_values={ + "from": start.strftime("%Y-%m-%d"), + "to": end.strftime("%Y-%m-%d"), + }, + ) + + +def _seed_partition_rows(dialect) -> InsertStatement: + rows = [ + [1, datetime(2026, 1, 15), 100, "jan"], + [2, datetime(2026, 2, 15), 100, "feb"], + [3, datetime(2026, 3, 15), 200, "mar"], ] + return InsertStatement( + dialect=dialect, + into=Table(dialect, _PART_TABLE), + columns=["id", "created_at", "tenant_id", "payload"], + source=ValuesSource(dialect, [[Literal(dialect, value) for value in row] for row in rows]), + ) + + +def _partition_range_query(dialect, start: datetime, end: datetime) -> QueryStatement: + condition = LogicalPredicate( + dialect, + "AND", + ComparisonPredicate(dialect, ">=", Column(dialect, "created_at"), Literal(dialect, start)), + ComparisonPredicate(dialect, "<", Column(dialect, "created_at"), Literal(dialect, end)), + ) + return QueryStatement( + dialect, + select=[AllColumnsWildcard(dialect)], + from_=NamedRelationRef(dialect, Table(dialect, _PART_TABLE)), + where=WhereClause(dialect, condition=condition), + ) + + +def _partition_full_scan_query(dialect) -> QueryStatement: + return QueryStatement( + dialect, + select=[AllColumnsWildcard(dialect)], + from_=NamedRelationRef(dialect, Table(dialect, _PART_TABLE)), + ) + + +def _partition_ddl(dialect): + exprs = [_drop_partition(dialect, _PART_TABLE)] + exprs.extend(_drop_partition(dialect, name) for name, _, _ in _PARTITIONS.values()) + exprs.append(_create_partition_parent(dialect)) + exprs.extend( + _create_partition(dialect, name, start, end) for name, start, end in _PARTITIONS.values() + ) + exprs.append(_seed_partition_rows(dialect)) + return exprs + + +def _partition_cleanup(dialect): + exprs = [_drop_partition(dialect, name) for name, _, _ in _PARTITIONS.values()] + exprs.append(_drop_partition(dialect, _PART_TABLE)) + return exprs def _require_partition_support(dialect) -> None: @@ -429,42 +585,40 @@ def _require_partition_support(dialect) -> None: @pytest.fixture def partition_backend(postgres_backend): - _require_partition_support(postgres_backend.dialect) - for statement in _partition_setup_sql(): - postgres_backend.execute(statement) + dialect = postgres_backend.dialect + _require_partition_support(dialect) + for expr in _partition_ddl(dialect): + postgres_backend.execute(*expr.to_sql()) yield postgres_backend - for statement in _partition_cleanup_sql(): + for expr in _partition_cleanup(dialect): try: - postgres_backend.execute(statement) + postgres_backend.execute(*expr.to_sql()) except Exception: pass @pytest_asyncio.fixture async def async_partition_backend(async_postgres_backend): - _require_partition_support(async_postgres_backend.dialect) - for statement in _partition_setup_sql(): - await async_postgres_backend.execute(statement) + dialect = async_postgres_backend.dialect + _require_partition_support(dialect) + for expr in _partition_ddl(dialect): + await async_postgres_backend.execute(*expr.to_sql()) yield async_postgres_backend - for statement in _partition_cleanup_sql(): + for expr in _partition_cleanup(dialect): try: - await async_postgres_backend.execute(statement) + await async_postgres_backend.execute(*expr.to_sql()) except Exception: pass class TestPostgresPartitionPruningEvidence: - """Assert the JSON plan shows target partitions and pruning of others.""" - def test_range_predicate_prunes_unrelated_partitions(self, partition_backend): dialect = partition_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = _json_explain( + plan = _json_plan( partition_backend, - "EXPLAIN (FORMAT JSON) SELECT * FROM %s " - "WHERE created_at >= TIMESTAMP '2026-02-01' " - "AND created_at < TIMESTAMP '2026-03-01'" % _PART_TABLE, + _partition_range_query(dialect, datetime(2026, 2, 1), datetime(2026, 3, 1)), ) names = _relation_names(plan) target = _PARTITIONS["p2026_02"][0] @@ -476,30 +630,21 @@ def test_full_scan_lists_every_partition(self, partition_backend): dialect = partition_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = _json_explain( - partition_backend, - "EXPLAIN (FORMAT JSON) SELECT * FROM %s" % _PART_TABLE, - ) + plan = _json_plan(partition_backend, _partition_full_scan_query(dialect)) names = _relation_names(plan) - for partition_name, _, _ in _PARTITIONS.values(): - assert partition_name in names, ( - "partition %s missing from full-scan plan" % partition_name - ) + for name, _, _ in _PARTITIONS.values(): + assert name in names, "partition %s missing from full-scan plan" % name class TestAsyncPostgresPartitionPruningEvidence: - """Asynchronous partition-pruning counterpart.""" - @pytest.mark.asyncio async def test_range_predicate_prunes_unrelated_partitions(self, async_partition_backend): dialect = async_partition_backend.dialect if not dialect.supports_explain_format("JSON"): pytest.skip("dialect does not support EXPLAIN FORMAT JSON") - plan = await _async_json_explain( + plan = await _async_json_plan( async_partition_backend, - "EXPLAIN (FORMAT JSON) SELECT * FROM %s " - "WHERE created_at >= TIMESTAMP '2026-02-01' " - "AND created_at < TIMESTAMP '2026-03-01'" % _PART_TABLE, + _partition_range_query(dialect, datetime(2026, 2, 1), datetime(2026, 3, 1)), ) names = _relation_names(plan) target = _PARTITIONS["p2026_02"][0] From 50cf4563ef510903b51f95365c2da684ac322830 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Thu, 19 Nov 2026 23:18:29 +0800 Subject: [PATCH 63/81] test(benchmark): wire shared testsuite benchmark contracts for postgres Register CRUD/query/transaction/mixin benchmark implementations with the shared testsuite registry via tests/benchmark/providers.py and conftest.py. Scenarios derive from support.postgres with a fresh database per run; DDL is derived from the model via create_table_statement (no hand-built SQL). Enable -p tests.benchmark.providers in the benchmark job's testsuite pytest command so the generic contracts register before collection. --- .github/workflows/test.yml | 2 +- tests/benchmark/conftest.py | 9 ++ tests/benchmark/providers.py | 230 +++++++++++++++++++++++++++++++++++ 3 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 tests/benchmark/conftest.py create mode 100644 tests/benchmark/providers.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f7407b9c..1ff7105d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -119,7 +119,7 @@ jobs: print(pathlib.Path(testsuite.__file__).parent) PY ) - python -m pytest \ + python -m pytest -p tests.benchmark.providers \ --rootdir=. \ --confcutdir=. \ "$TESTSUITE_DIR/benchmark/crud/core/test_delete_async.py" \ diff --git a/tests/benchmark/conftest.py b/tests/benchmark/conftest.py new file mode 100644 index 00000000..0421d11a --- /dev/null +++ b/tests/benchmark/conftest.py @@ -0,0 +1,9 @@ +# tests/benchmark/conftest.py +"""Register PostgreSQL implementations for the shared benchmark contracts. + +Importing ``providers`` populates the testsuite's global ``benchmarks`` +registry before pytest collects the shared ``benchmark/*`` contract files. +Without this import those contracts skip with "no implementation registered". +""" + +from tests.benchmark import providers # noqa: F401 diff --git a/tests/benchmark/providers.py b/tests/benchmark/providers.py new file mode 100644 index 00000000..c6602013 --- /dev/null +++ b/tests/benchmark/providers.py @@ -0,0 +1,230 @@ +# tests/benchmark/providers.py +"""PostgreSQL benchmark implementations registered with the shared testsuite. + +The testsuite's ``benchmark/*`` contracts obtain a backend implementation from +the global ``benchmarks`` registry. Registering here (at conftest import time) +is what turns those contracts from "skip: no implementation" into real +measurements. Direct ``StorageBackend.execute`` benchmarks stay backend-owned +under ``tests/benchmark/backend/`` and do not use this registry. +""" + +import uuid +from typing import ClassVar, Optional + +from pydantic import EmailStr, Field + +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.base.field_proxy import FieldProxy +from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin +from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord +from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.data import ( + make_user_payloads, + payload_count_for_size, +) +from rhosocial.activerecord.testsuite.benchmark.crud.interfaces import CrudBenchmarkContext +from rhosocial.activerecord.testsuite.benchmark.mixin.interfaces import MixinBenchmarkContext +from rhosocial.activerecord.testsuite.benchmark.query.interfaces import QueryBenchmarkContext +from rhosocial.activerecord.testsuite.benchmark.registry import ( + BenchmarkImplementation, + benchmarks, +) +from rhosocial.activerecord.testsuite.benchmark.transaction.interfaces import ( + TransactionBenchmarkContext, +) + +from support.postgres import SCENARIOS, scenario + +BACKEND_NAMESPACE = "rhosocial.activerecord.backend.impl.postgres" +BACKEND_NAME = "postgres" + + +# --------------------------------------------------------------------------- # +# Minimal benchmark-only models. Each run uses a fresh database, so these are +# declared locally instead of reusing feature fixtures. DDL is derived from +# the model via the expression system (no hand-built SQL). +# --------------------------------------------------------------------------- # +class _BenchUserBase: + @classmethod + def table_name(cls): + return "benchmark_users" + + c: ClassVar[FieldProxy] = FieldProxy() + id: Optional[int] = None + username: str + email: EmailStr + age: Optional[int] = Field(..., ge=0, le=120) + balance: float = 0.0 + notes: Optional[str] = None + is_active: bool = True + + +class BenchUser(IntegerPKMixin, DefaultTimestampMixin, _BenchUserBase, ActiveRecord): + pass + + +class AsyncBenchUser(IntegerPKMixin, DefaultTimestampMixin, _BenchUserBase, AsyncActiveRecord): + pass + + +def _config_for_scenario(scenario_name: str, tag: str): + """A fresh, scenario-derived config; each feature run gets its own database.""" + sc = scenario(scenario_name) + # PostgreSQL is a server backend: each run needs its own logical database. + # Keep the name short enough to stay under the 63-byte identifier limit. + unique = f"bench_{tag}_{uuid.uuid4().hex}" + sc.reset_database(unique) + cfg = sc.make_config(unique) + return sc, cfg + + +async def _seed_async(model, payloads): + ids = [] + for payload in payloads: + obj = model(**payload) + await obj.save() + ids.append(obj.id) + return ids + + +class CrudBenchmarkImpl(BenchmarkImplementation): + def __init__(self, tag="crud"): + self.tag = tag + self._backends = [] + + def scenarios(self): + return list(SCENARIOS) + + def sync_setup(self, scenario_name, size): + sc, cfg = _config_for_scenario(scenario_name, self.tag) + BenchUser.configure(cfg, sc.backend_class) + backend = BenchUser.backend() + backend.execute(*BenchUser.create_table_statement(backend=backend).to_sql(), options=DDL) + self._backends.append(backend) + payloads = make_user_payloads(payload_count_for_size(size)) + ids = [] + for payload in payloads: + obj = BenchUser(**payload) + obj.save() + ids.append(obj.id) + return CrudBenchmarkContext( + scenario_name, size, BenchUser, payloads, ids, BACKEND_NAMESPACE, BACKEND_NAME + ) + + def sync_teardown(self, scenario_name, context): + for backend in self._backends: + backend.disconnect() + self._backends.clear() + + async def async_setup(self, scenario_name, size, strategy="context"): + sc, cfg = _config_for_scenario(scenario_name, self.tag) + await AsyncBenchUser.configure(cfg, sc.async_backend_class) + backend = AsyncBenchUser.backend() + await backend.execute( + *AsyncBenchUser.create_table_statement(backend=backend).to_sql(), options=DDL + ) + self._backends.append(backend) + payloads = make_user_payloads(payload_count_for_size(size)) + ids = await _seed_async(AsyncBenchUser, payloads) + return CrudBenchmarkContext( + scenario_name, size, AsyncBenchUser, payloads, ids, BACKEND_NAMESPACE, BACKEND_NAME + ) + + async def async_teardown(self, scenario_name, context): + for backend in self._backends: + await backend.disconnect() + self._backends.clear() + + +class QueryBenchmarkImpl(CrudBenchmarkImpl): + """Query benchmark shares the CRUD context shape.""" + + def sync_setup(self, scenario_name, size): + ctx = super().sync_setup(scenario_name, size) + return QueryBenchmarkContext( + ctx.scenario, + ctx.size, + ctx.model_class, + ctx.payloads, + ctx.record_ids, + ctx.backend_namespace, + ctx.backend_name, + ) + + async def async_setup(self, scenario_name, size, strategy="context"): + ctx = await super().async_setup(scenario_name, size, strategy) + return QueryBenchmarkContext( + ctx.scenario, + ctx.size, + ctx.model_class, + ctx.payloads, + ctx.record_ids, + ctx.backend_namespace, + ctx.backend_name, + ) + + +class TransactionBenchmarkImpl(CrudBenchmarkImpl): + def sync_setup(self, scenario_name, size): + ctx = super().sync_setup(scenario_name, size) + return TransactionBenchmarkContext( + ctx.scenario, + ctx.size, + ctx.model_class, + ctx.payloads, + ctx.record_ids, + ctx.backend_namespace, + ctx.backend_name, + ) + + async def async_setup(self, scenario_name, size, strategy="context"): + ctx = await super().async_setup(scenario_name, size, strategy) + return TransactionBenchmarkContext( + ctx.scenario, + ctx.size, + ctx.model_class, + ctx.payloads, + ctx.record_ids, + ctx.backend_namespace, + ctx.backend_name, + ) + + +class MixinBenchmarkImpl(CrudBenchmarkImpl): + def sync_setup(self, scenario_name, size): + ctx = super().sync_setup(scenario_name, size) + return MixinBenchmarkContext( + ctx.scenario, + ctx.size, + ctx.model_class, + ctx.payloads, + ctx.record_ids, + ctx.backend_namespace, + ctx.backend_name, + ) + + async def async_setup(self, scenario_name, size, strategy="context"): + ctx = await super().async_setup(scenario_name, size, strategy) + return MixinBenchmarkContext( + ctx.scenario, + ctx.size, + ctx.model_class, + ctx.payloads, + ctx.record_ids, + ctx.backend_namespace, + ctx.backend_name, + ) + + +# DDL options used by the derived statements. +DDL = ExecutionOptions(stmt_type=StatementType.DDL) + + +# --------------------------------------------------------------------------- # +# Register. Imported as a pytest plugin (``-p tests.benchmark.providers``) so +# registration happens before the shared contracts are collected. +# --------------------------------------------------------------------------- # +benchmarks.register("crud", CrudBenchmarkImpl("crud")) +benchmarks.register("query", QueryBenchmarkImpl("query")) +benchmarks.register("transaction", TransactionBenchmarkImpl("transaction")) +benchmarks.register("mixin", MixinBenchmarkImpl("mixin")) From fbb4dfde0329936287d9aa55a135723230746cc1 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 00:58:57 +0800 Subject: [PATCH 64/81] test(cli): bridge shared migrate CLI contracts --- .../feature/cli_contracts/test_cli_migrate.py | 3 +++ .../feature/cli_contracts/test_cli_migrate_async.py | 3 +++ 2 files changed, 6 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py new file mode 100644 index 00000000..c3cb89de --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py +"""Bridge to the shared ``feature/cli`` migrate contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_migrate import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py new file mode 100644 index 00000000..e966c21b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py +"""Bridge to the shared ``feature/cli`` migrate contract.""" +from rhosocial.activerecord.testsuite.feature.cli.test_cli_migrate_async import * # noqa: F401,F403 From d59cd7ec8bcf86bf76aeaef6d2a283b000a1a9c9 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 01:46:32 +0800 Subject: [PATCH 65/81] test(query): bridge shared testsuite contract dirs --- .../activerecord_postgres_test/feature/adapters/conftest.py | 3 +++ .../feature/adapters/test_json_codec.py | 3 +++ .../feature/adapters/test_neutral_types.py | 3 +++ .../feature/adapters/test_neutral_types_async.py | 3 +++ .../feature/query/aggregate/conftest.py | 3 +++ .../feature/query/aggregate/test_active_query_aggregate.py | 3 +++ .../query/aggregate/test_active_query_aggregate_async.py | 3 +++ .../feature/query/aggregate/test_aggregate_queries.py | 3 +++ .../feature/query/aggregate/test_aggregate_queries_async.py | 3 +++ .../feature/query/connection/conftest.py | 3 +++ .../feature/query/connection/test_active_query_context.py | 3 +++ .../query/connection/test_active_query_context_async.py | 3 +++ .../feature/query/connection/test_cte_query_context.py | 3 +++ .../feature/query/connection/test_cte_query_context_async.py | 3 +++ .../feature/query/connection/test_set_operation_context.py | 3 +++ .../query/connection/test_set_operation_context_async.py | 3 +++ .../feature/query/cross_schema/conftest.py | 3 +++ .../feature/query/cross_schema/test_cross_schema_join.py | 3 +++ .../feature/query/cross_schema/test_cross_schema_join_async.py | 3 +++ .../feature/query/cross_schema/test_mixed_schema.py | 3 +++ .../feature/query/cross_schema/test_mixed_schema_async.py | 3 +++ .../feature/query/cross_schema/test_mixed_schema_qualifiers.py | 3 +++ .../feature/query/eager_loading/conftest.py | 3 +++ .../feature/query/eager_loading/test_eager_loading_caching.py | 3 +++ .../query/eager_loading/test_eager_loading_caching_async.py | 3 +++ .../feature/query/eager_loading/test_eager_loading_nested.py | 3 +++ .../query/eager_loading/test_eager_loading_nested_async.py | 3 +++ .../query/eager_loading/test_eager_loading_scenarios.py | 3 +++ .../query/eager_loading/test_eager_loading_scenarios_async.py | 3 +++ .../feature/query/eager_loading/test_eager_loading_with_all.py | 3 +++ .../query/eager_loading/test_eager_loading_with_all_async.py | 3 +++ .../query/eager_loading/test_eager_loading_with_modifier.py | 3 +++ .../eager_loading/test_eager_loading_with_modifier_async.py | 3 +++ .../feature/query/eager_loading/test_eager_loading_with_one.py | 3 +++ .../query/eager_loading/test_eager_loading_with_one_async.py | 3 +++ .../feature/query/error_handling/conftest.py | 3 +++ .../feature/query/error_handling/test_error_handling.py | 3 +++ .../feature/query/error_handling/test_error_handling_async.py | 3 +++ .../activerecord_postgres_test/feature/query/json/conftest.py | 3 +++ .../feature/query/json/test_json_probe_honesty.py | 3 +++ .../feature/query/logging/conftest.py | 3 +++ .../feature/query/logging/test_logging_data_summarization.py | 3 +++ .../query/logging/test_logging_data_summarization_async.py | 3 +++ .../feature/query/optimization/conftest.py | 3 +++ .../feature/query/optimization/test_query_optimization.py | 3 +++ .../query/optimization/test_query_optimization_async.py | 3 +++ .../feature/query/range_queries/conftest.py | 3 +++ .../feature/query/range_queries/test_active_query_range.py | 3 +++ .../query/range_queries/test_active_query_range_async.py | 3 +++ .../feature/query/range_queries/test_range_queries.py | 3 +++ .../feature/query/range_queries/test_range_queries_async.py | 3 +++ .../feature/query/range_queries/test_range_query_detailed.py | 3 +++ .../query/range_queries/test_range_query_detailed_async.py | 3 +++ .../feature/query/special/conftest.py | 3 +++ .../feature/query/special/test_example_query_fixtures.py | 3 +++ .../feature/query/special/test_example_query_fixtures_async.py | 3 +++ .../feature/query/special/test_special_queries.py | 3 +++ .../feature/query/special/test_special_queries_async.py | 3 +++ .../feature/query/window_functions/conftest.py | 3 +++ .../feature/query/window_functions/test_window_functions.py | 3 +++ .../query/window_functions/test_window_functions_async.py | 3 +++ .../feature/query/worker/conftest.py | 3 +++ .../feature/query/worker/test_parallel_queries.py | 3 +++ .../feature/query/worker/test_parallel_queries_async.py | 3 +++ .../feature/query/worker/test_transaction_isolation.py | 3 +++ .../feature/query/worker/test_transaction_isolation_async.py | 3 +++ 66 files changed, 198 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py new file mode 100644 index 00000000..8b0f95c4 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py +"""Bridge to the shared ``adapters`` contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py new file mode 100644 index 00000000..881817ab --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py +"""Bridge to the shared ``adapters`` contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.test_json_codec import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py new file mode 100644 index 00000000..e294ba71 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py +"""Bridge to the shared ``adapters`` contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py new file mode 100644 index 00000000..f0f2a7b9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py +"""Bridge to the shared ``adapters`` contract.""" +from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py new file mode 100644 index 00000000..cc950f64 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py +"""Bridge to the shared ``query/aggregate`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.aggregate.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py new file mode 100644 index 00000000..afc1f88c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py +"""Bridge to the shared ``query/aggregate`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py new file mode 100644 index 00000000..5b2406b6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py +"""Bridge to the shared ``query/aggregate`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py new file mode 100644 index 00000000..2dea45b3 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py +"""Bridge to the shared ``query/aggregate`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py new file mode 100644 index 00000000..c839fa53 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py +"""Bridge to the shared ``query/aggregate`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py new file mode 100644 index 00000000..54004cff --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py new file mode 100644 index 00000000..48580637 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py new file mode 100644 index 00000000..85450915 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py new file mode 100644 index 00000000..acc4c346 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py new file mode 100644 index 00000000..29fc0273 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py new file mode 100644 index 00000000..b916ccfa --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py new file mode 100644 index 00000000..1dc25e75 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py +"""Bridge to the shared ``query/connection`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py new file mode 100644 index 00000000..5f738de9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py +"""Bridge to the shared ``query/cross_schema`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.cross_schema.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py new file mode 100644 index 00000000..7a81840f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py +"""Bridge to the shared ``query/cross_schema`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_cross_schema_join import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py new file mode 100644 index 00000000..0c35215d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py +"""Bridge to the shared ``query/cross_schema`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_cross_schema_join_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py new file mode 100644 index 00000000..76107087 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py +"""Bridge to the shared ``query/cross_schema`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_mixed_schema import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py new file mode 100644 index 00000000..9326cf8e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py +"""Bridge to the shared ``query/cross_schema`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_mixed_schema_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py new file mode 100644 index 00000000..70dd696d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py +"""Bridge to the shared ``query/cross_schema`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_mixed_schema_qualifiers import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py new file mode 100644 index 00000000..1a31ac71 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py new file mode 100644 index 00000000..47a2ab61 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py new file mode 100644 index 00000000..6887dd0d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py new file mode 100644 index 00000000..85acb036 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py new file mode 100644 index 00000000..39b6672b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py new file mode 100644 index 00000000..deae767c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py new file mode 100644 index 00000000..0687f716 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py new file mode 100644 index 00000000..6eeff6a6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py new file mode 100644 index 00000000..83f4c9f8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py new file mode 100644 index 00000000..2576b488 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py new file mode 100644 index 00000000..be23ceea --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py new file mode 100644 index 00000000..fcb72fe7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py new file mode 100644 index 00000000..a964468d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py +"""Bridge to the shared ``query/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py new file mode 100644 index 00000000..7fb5d45e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py +"""Bridge to the shared ``query/error_handling`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.error_handling.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py new file mode 100644 index 00000000..6cb01aff --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py +"""Bridge to the shared ``query/error_handling`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py new file mode 100644 index 00000000..0e35d381 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py +"""Bridge to the shared ``query/error_handling`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py new file mode 100644 index 00000000..8b173d48 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py +"""Bridge to the shared ``query/json`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.json.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py b/tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py new file mode 100644 index 00000000..843c2e99 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py +"""Bridge to the shared ``query/json`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.json.test_json_probe_honesty import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py new file mode 100644 index 00000000..e45e0ff2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py +"""Bridge to the shared ``query/logging`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.logging.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py new file mode 100644 index 00000000..ba17b876 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py +"""Bridge to the shared ``query/logging`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py new file mode 100644 index 00000000..6d1211b9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py +"""Bridge to the shared ``query/logging`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py new file mode 100644 index 00000000..b1830f22 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py +"""Bridge to the shared ``query/optimization`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.optimization.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py new file mode 100644 index 00000000..5e9726e0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py +"""Bridge to the shared ``query/optimization`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py new file mode 100644 index 00000000..a7ce0389 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py +"""Bridge to the shared ``query/optimization`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py new file mode 100644 index 00000000..3190e2f0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py new file mode 100644 index 00000000..9b900a81 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py new file mode 100644 index 00000000..9068d462 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py new file mode 100644 index 00000000..7923c145 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py new file mode 100644 index 00000000..2a20daee --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py new file mode 100644 index 00000000..f5ba66d9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py new file mode 100644 index 00000000..4e3c8a53 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py +"""Bridge to the shared ``query/range_queries`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py new file mode 100644 index 00000000..64242303 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py +"""Bridge to the shared ``query/special`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.special.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py new file mode 100644 index 00000000..c4517c6a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py +"""Bridge to the shared ``query/special`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py new file mode 100644 index 00000000..ed6f09fd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py +"""Bridge to the shared ``query/special`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py new file mode 100644 index 00000000..dce47161 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py +"""Bridge to the shared ``query/special`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py new file mode 100644 index 00000000..ff00a9f9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py +"""Bridge to the shared ``query/special`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py new file mode 100644 index 00000000..1997d42d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py +"""Bridge to the shared ``query/window_functions`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.window_functions.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py new file mode 100644 index 00000000..145b1b45 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py +"""Bridge to the shared ``query/window_functions`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py new file mode 100644 index 00000000..e58c9295 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py +"""Bridge to the shared ``query/window_functions`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py new file mode 100644 index 00000000..3077deb7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py +"""Bridge to the shared ``query/worker`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py new file mode 100644 index 00000000..05ff3f56 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py +"""Bridge to the shared ``query/worker`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py new file mode 100644 index 00000000..ac9b92b1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py +"""Bridge to the shared ``query/worker`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py new file mode 100644 index 00000000..eb12b56f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py +"""Bridge to the shared ``query/worker`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py new file mode 100644 index 00000000..af30118e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py +"""Bridge to the shared ``query/worker`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation_async import * # noqa: F401,F403 From 07972fc32e7d67d1cd38321de2e40682ac4bff75 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 03:20:30 +0800 Subject: [PATCH 66/81] test(query): rename worker bridge to avoid pytest basename collision --- ...action_isolation.py => test_worker_transaction_isolation.py} | 2 +- ...tion_async.py => test_worker_transaction_isolation_async.py} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/rhosocial/activerecord_postgres_test/feature/query/worker/{test_transaction_isolation.py => test_worker_transaction_isolation.py} (84%) rename tests/rhosocial/activerecord_postgres_test/feature/query/worker/{test_transaction_isolation_async.py => test_worker_transaction_isolation_async.py} (81%) diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py similarity index 84% rename from tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py rename to tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py index eb12b56f..ab42dc10 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py @@ -1,3 +1,3 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation.py +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py.py """Bridge to the shared ``query/worker`` contract.""" from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py similarity index 81% rename from tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py rename to tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py index af30118e..b99d28b9 100644 --- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py @@ -1,3 +1,3 @@ -# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py +# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py_async.py """Bridge to the shared ``query/worker`` contract.""" from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation_async import * # noqa: F401,F403 From e3d53731ccf09aedace99ebda74bc96ffc36a935 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 10:41:30 +0800 Subject: [PATCH 67/81] test: bridge query/relation + typed_column contracts --- .../feature/query/relation/base/test_base.py | 3 +++ .../feature/query/relation/base/test_base_async.py | 3 +++ .../feature/query/relation/base/test_interfaces.py | 3 +++ .../feature/query/relation/base/test_interfaces_async.py | 3 +++ .../feature/query/relation/boundary/conftest.py | 3 +++ .../feature/query/relation/boundary/test_boundary.py | 3 +++ .../feature/query/relation/boundary/test_boundary_async.py | 3 +++ .../feature/query/relation/cache/test_cache.py | 3 +++ .../feature/query/relation/cache/test_cache_async.py | 3 +++ .../feature/query/relation/cache/test_cache_clearing.py | 3 +++ .../feature/query/relation/cache/test_cache_clearing_async.py | 3 +++ .../feature/query/relation/derived/conftest.py | 3 +++ .../query/relation/derived/test_relation_derived_field.py | 3 +++ .../relation/derived/test_relation_derived_field_async.py | 3 +++ .../query/relation/derived/test_relation_derived_field_json.py | 3 +++ .../relation/derived/test_relation_derived_field_json_async.py | 3 +++ .../query/relation/descriptors/test_descriptor_compat.py | 3 +++ .../query/relation/descriptors/test_descriptor_compat_async.py | 3 +++ .../feature/query/relation/descriptors/test_descriptors.py | 3 +++ .../query/relation/descriptors/test_descriptors_async.py | 3 +++ .../feature/query/relation/eager_loading/conftest.py | 3 +++ .../relation/eager_loading/test_nested_relationship_access.py | 3 +++ .../eager_loading/test_nested_relationship_access_async.py | 3 +++ .../feature/query/relation/eager_loading/test_with_method.py | 3 +++ .../query/relation/eager_loading/test_with_method_async.py | 3 +++ .../feature/query/relation/integration/conftest.py | 3 +++ .../feature/query/relation/integration/test_integration.py | 3 +++ .../query/relation/integration/test_integration_async.py | 3 +++ .../query/relation/legacy/test_relational_validation.py | 3 +++ .../query/relation/legacy/test_relational_validation_async.py | 3 +++ .../feature/query/relation/modifiers/conftest.py | 3 +++ .../feature/query/relation/modifiers/test_modifier_behavior.py | 3 +++ .../query/relation/modifiers/test_modifier_behavior_async.py | 3 +++ .../feature/query/relation/modifiers/test_modifier_warning.py | 3 +++ .../query/relation/modifiers/test_modifier_warning_async.py | 3 +++ .../feature/query/relation/ordering/test_has_many_order_by.py | 3 +++ .../query/relation/ordering/test_has_many_order_by_async.py | 3 +++ .../feature/query/relation/validation/conftest.py | 3 +++ .../feature/query/relation/validation/test_path_validation.py | 3 +++ .../query/relation/validation/test_path_validation_async.py | 3 +++ .../feature/query/relation/validation/test_validator.py | 3 +++ .../feature/query/relation/validation/test_validator_async.py | 3 +++ .../feature/query/typed_column/conftest.py | 3 +++ .../feature/query/typed_column/test_column_operations_core.py | 3 +++ .../query/typed_column/test_enum_capability_contracts.py | 3 +++ .../feature/query/typed_column/test_protocol_guarantees.py | 3 +++ .../query/typed_column/test_seconds_between_contract.py | 3 +++ .../feature/query/typed_column/test_typed_column_contracts.py | 3 +++ .../query/typed_column/test_uuid_capability_contracts.py | 3 +++ 49 files changed, 147 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py new file mode 100644 index 00000000..8c53d9b7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py +"""Bridge to the shared ``query/relation/base`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.base.test_base import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py new file mode 100644 index 00000000..98f20887 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py +"""Bridge to the shared ``query/relation/base`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.base.test_base_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py new file mode 100644 index 00000000..9523448a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py +"""Bridge to the shared ``query/relation/base`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.base.test_interfaces import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py new file mode 100644 index 00000000..edd832d2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py +"""Bridge to the shared ``query/relation/base`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.base.test_interfaces_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py new file mode 100644 index 00000000..bd9707ac --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py +"""Bridge fixture configuration for ``query/relation/boundary``.""" +from rhosocial.activerecord.testsuite.feature.query.relation.boundary.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py new file mode 100644 index 00000000..2a17cd04 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py +"""Bridge to the shared ``query/relation/boundary`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.boundary.test_boundary import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py new file mode 100644 index 00000000..2d7194bf --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py +"""Bridge to the shared ``query/relation/boundary`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.boundary.test_boundary_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py new file mode 100644 index 00000000..026b8ecf --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py +"""Bridge to the shared ``query/relation/cache`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py new file mode 100644 index 00000000..d1e84e64 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py +"""Bridge to the shared ``query/relation/cache`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py new file mode 100644 index 00000000..9f8a1024 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py +"""Bridge to the shared ``query/relation/cache`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_clearing import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py new file mode 100644 index 00000000..5659ca9d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py +"""Bridge to the shared ``query/relation/cache`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_clearing_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py new file mode 100644 index 00000000..d5509296 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py +"""Bridge fixture configuration for ``query/relation/derived``.""" +from rhosocial.activerecord.testsuite.feature.query.relation.derived.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py new file mode 100644 index 00000000..c9d699fc --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py +"""Bridge to the shared ``query/relation/derived`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py new file mode 100644 index 00000000..ffa45448 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py +"""Bridge to the shared ``query/relation/derived`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py new file mode 100644 index 00000000..669b35f7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py +"""Bridge to the shared ``query/relation/derived`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_json import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py new file mode 100644 index 00000000..01d4e3fd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py +"""Bridge to the shared ``query/relation/derived`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_json_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py new file mode 100644 index 00000000..5492e7d9 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py +"""Bridge to the shared ``query/relation/descriptors`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptor_compat import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py new file mode 100644 index 00000000..7046b9c1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py +"""Bridge to the shared ``query/relation/descriptors`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptor_compat_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py new file mode 100644 index 00000000..4680b79e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py +"""Bridge to the shared ``query/relation/descriptors`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptors import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py new file mode 100644 index 00000000..8453205d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py +"""Bridge to the shared ``query/relation/descriptors`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptors_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py new file mode 100644 index 00000000..0fb01806 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py +"""Bridge fixture configuration for ``query/relation/eager_loading``.""" +from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py new file mode 100644 index 00000000..e917abc6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py +"""Bridge to the shared ``query/relation/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_nested_relationship_access import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py new file mode 100644 index 00000000..0ddbee16 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py +"""Bridge to the shared ``query/relation/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_nested_relationship_access_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py new file mode 100644 index 00000000..bba49cda --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py +"""Bridge to the shared ``query/relation/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_with_method import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py new file mode 100644 index 00000000..de9291c2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py +"""Bridge to the shared ``query/relation/eager_loading`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_with_method_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py new file mode 100644 index 00000000..4c527dd7 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py +"""Bridge fixture configuration for ``query/relation/integration``.""" +from rhosocial.activerecord.testsuite.feature.query.relation.integration.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py new file mode 100644 index 00000000..172739d1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py +"""Bridge to the shared ``query/relation/integration`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.integration.test_integration import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py new file mode 100644 index 00000000..7444cb98 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py +"""Bridge to the shared ``query/relation/integration`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.integration.test_integration_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py new file mode 100644 index 00000000..3b6dbd70 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py +"""Bridge to the shared ``query/relation/legacy`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.legacy.test_relational_validation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py new file mode 100644 index 00000000..ef7690c2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py +"""Bridge to the shared ``query/relation/legacy`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.legacy.test_relational_validation_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py new file mode 100644 index 00000000..ace3ff66 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py +"""Bridge fixture configuration for ``query/relation/modifiers``.""" +from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py new file mode 100644 index 00000000..c47df05d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py +"""Bridge to the shared ``query/relation/modifiers`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_behavior import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py new file mode 100644 index 00000000..c06be888 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py +"""Bridge to the shared ``query/relation/modifiers`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_behavior_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py new file mode 100644 index 00000000..42ba6f55 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py +"""Bridge to the shared ``query/relation/modifiers`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_warning import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py new file mode 100644 index 00000000..483c0640 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py +"""Bridge to the shared ``query/relation/modifiers`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_warning_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py new file mode 100644 index 00000000..3e437b46 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py +"""Bridge to the shared ``query/relation/ordering`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.ordering.test_has_many_order_by import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py new file mode 100644 index 00000000..93b05c4d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py +"""Bridge to the shared ``query/relation/ordering`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.ordering.test_has_many_order_by_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py new file mode 100644 index 00000000..bc562cbd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py +"""Bridge fixture configuration for ``query/relation/validation``.""" +from rhosocial.activerecord.testsuite.feature.query.relation.validation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py new file mode 100644 index 00000000..4d02bfcd --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py +"""Bridge to the shared ``query/relation/validation`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_path_validation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py new file mode 100644 index 00000000..2bef540c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py +"""Bridge to the shared ``query/relation/validation`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_path_validation_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py new file mode 100644 index 00000000..f45cf228 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py +"""Bridge to the shared ``query/relation/validation`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_validator import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py new file mode 100644 index 00000000..dca12bab --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py +"""Bridge to the shared ``query/relation/validation`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_validator_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py new file mode 100644 index 00000000..a529658e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py +"""Bridge fixture configuration for ``query/typed_column``.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py new file mode 100644 index 00000000..6575f54d --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py +"""Bridge to the shared ``query/typed_column`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_column_operations_core import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py new file mode 100644 index 00000000..98d9ef0b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py +"""Bridge to the shared ``query/typed_column`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_enum_capability_contracts import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py new file mode 100644 index 00000000..b7980f2a --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py +"""Bridge to the shared ``query/typed_column`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_protocol_guarantees import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py new file mode 100644 index 00000000..312864ea --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py +"""Bridge to the shared ``query/typed_column`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_seconds_between_contract import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py new file mode 100644 index 00000000..4fcfb115 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py +"""Bridge to the shared ``query/typed_column`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_typed_column_contracts import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py new file mode 100644 index 00000000..b40310a0 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py +"""Bridge to the shared ``query/typed_column`` contract.""" +from rhosocial.activerecord.testsuite.feature.query.typed_column.test_uuid_capability_contracts import * # noqa: F401,F403 From 2bb5eb43b30025c3c41b4872eeb8aa7a2542d247 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 11:10:58 +0800 Subject: [PATCH 68/81] test(postgres): self-owned tests for cli/status --- .../backend/construct/cli/test_status_cli.py | 220 ++++++++++++++++++ 1 file changed, 220 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py new file mode 100644 index 00000000..ea90f810 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py @@ -0,0 +1,220 @@ +# tests/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py +"""Backend-owned tests for ``postgres.cli.status``. + +The shared testsuite covers data-operation compatibility, not this backend's +CLI surface. These portable tests pin the parts of the status subcommand that +are common to every backend: parser shape, pure serialization/size helpers, +rich rendering of the overview header, and the dispatch guard. No live server +is needed. +""" +from dataclasses import dataclass +from enum import Enum +from unittest.mock import MagicMock, patch + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.cli import status as mod +from rhosocial.activerecord.backend.introspection.status import ServerOverview + + +# --------------------------------------------------------------------------- +# create_parser +# --------------------------------------------------------------------------- + + +class TestCreateParser: + def test_parser_defaults_and_choices(self): + import argparse + + subs = argparse.ArgumentParser(prog="x").add_subparsers(dest="command") + parser = mod.create_parser(subs) + args = parser.parse_args([]) + assert args.type == "all" + assert args.output == "table" + assert args.verbose == 0 + assert args.rich_ascii is False + + @pytest.mark.parametrize("t", mod.STATUS_TYPES) + def test_all_status_types_accepted(self, t): + import argparse + + subs = argparse.ArgumentParser(prog="x").add_subparsers(dest="command") + parser = mod.create_parser(subs) + assert parser.parse_args([t]).type == t + + def test_verbose_is_counted(self): + import argparse + + subs = argparse.ArgumentParser(prog="x").add_subparsers(dest="command") + parser = mod.create_parser(subs) + assert parser.parse_args(["-vvv"]).verbose == 3 + + +# --------------------------------------------------------------------------- +# _serialize_for_output +# --------------------------------------------------------------------------- + + +class _Colour(Enum): + RED = "red" + + +@dataclass +class _Point: + x: int + y: int + + +class _WithModelDump: + def model_dump(self, mode="python"): + return {"a": 1, "mode": mode} + + +class _Fallback: + def __str__(self): + return "fallback" + + +class TestSerializeForOutput: + def test_none_and_scalars(self): + assert mod._serialize_for_output(None) is None + assert mod._serialize_for_output("x") == "x" + assert mod._serialize_for_output(3) == 3 + assert mod._serialize_for_output(1.5) == 1.5 + assert mod._serialize_for_output(True) is True + + def test_enum(self): + assert mod._serialize_for_output(_Colour.RED) == "red" + + def test_dataclass(self): + assert mod._serialize_for_output(_Point(1, 2)) == {"x": 1, "y": 2} + + def test_dict_and_list_recursive(self): + obj = {"p": _Point(1, 2), "c": _Colour.RED, "items": [_Colour.RED, 2]} + assert mod._serialize_for_output(obj) == { + "p": {"x": 1, "y": 2}, "c": "red", "items": ["red", 2], + } + + def test_tuple_becomes_list(self): + assert mod._serialize_for_output((1, 2)) == [1, 2] + + def test_model_dump(self): + assert mod._serialize_for_output(_WithModelDump()) == {"a": 1, "mode": "json"} + + def test_model_dump_typeerror_falls_back(self): + class BadNoMode: + def model_dump(self): + return {"ok": True} + + assert mod._serialize_for_output(BadNoMode()) == {"ok": True} + + def test_unknown_falls_back_to_str(self): + assert mod._serialize_for_output(_Fallback()) == "fallback" + + +# --------------------------------------------------------------------------- +# _format_size +# --------------------------------------------------------------------------- + + +class TestFormatSize: + @pytest.mark.parametrize( + "size,expected", + [ + (0, "0.0 B"), + (512, "512.0 B"), + (1024, "1.0 KB"), + (1024 * 1024, "1.0 MB"), + (1024**3, "1.0 GB"), + (1024**4, "1.0 TB"), + (1024**5, "1.0 PB"), + ], + ) + def test_units(self, size, expected): + assert mod._format_size(size) == expected + + +# --------------------------------------------------------------------------- +# _display_status_rich (fake rich so it runs without the optional dependency) +# --------------------------------------------------------------------------- + + +class _FakeTable: + def __init__(self, *a, **k): + self.columns = [] + self.rows = [] + + def add_column(self, *a, **k): + self.columns.append((a, k)) + + def add_row(self, *a, **k): + self.rows.append((a, k)) + + +class _FakeConsole: + printed = [] + + def __init__(self, *a, **k): + pass + + def print(self, *a, **k): + for item in a: + if isinstance(item, _FakeTable): + for args, kwargs in item.columns: + _FakeConsole.printed.extend(str(x) for x in args) + for args, kwargs in item.rows: + _FakeConsole.printed.extend(str(x) for x in args) + else: + _FakeConsole.printed.append(str(item)) + + +@pytest.fixture +def fake_rich(): + import sys + import types + + console_mod = types.ModuleType("rich.console") + console_mod.Console = _FakeConsole + table_mod = types.ModuleType("rich.table") + table_mod.Table = _FakeTable + rich_mod = types.ModuleType("rich") + rich_mod.console = console_mod + rich_mod.table = table_mod + with patch.dict( + sys.modules, + {"rich": rich_mod, "rich.console": console_mod, "rich.table": table_mod}, + ): + _FakeConsole.printed = [] + yield + + +class TestDisplayStatusRich: + def test_header_always_rendered(self, fake_rich): + ov = ServerOverview(server_version="8.0", server_vendor="Vendor") + mod._display_status_rich(ov) + out = " ".join(_FakeConsole.printed) + assert "Server Status" in out + assert "8.0" in out + assert "Vendor" in out + + def test_verbose_adds_columns(self, fake_rich): + ov = ServerOverview(server_version="8.0", server_vendor="Vendor") + mod._display_status_rich(ov, verbose=1) + # At minimum the console was driven with more than the bare header. + assert len(_FakeConsole.printed) >= 3 + + +# --------------------------------------------------------------------------- +# handle: shared dispatch guard +# --------------------------------------------------------------------------- + + +class TestHandleDispatch: + def test_requires_database(self, capsys): + args = MagicMock() + args.database = None + args.named_connection = None + with pytest.raises(SystemExit) as e: + mod.handle(args) + assert e.value.code == 1 + assert "database is required" in capsys.readouterr().err From 9c8b59b0afa8f12182e0650a8faf2c9d9f321841 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 13:57:24 +0800 Subject: [PATCH 69/81] ci(postgres): use stable postgres:19 image (19 GA) --- .github/workflows/test.yml | 4 ++-- README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1ff7105d..e90e450f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -459,12 +459,12 @@ jobs: fail_ci_if_error: false test-postgres-19: - name: Python 3.14 / postgres 19rc1 + name: Python 3.14 / postgres 19 runs-on: ubuntu-latest services: postgres: - image: postgres:19rc1 + image: postgres:19 env: POSTGRES_DB: test_db POSTGRES_USER: root diff --git a/README.md b/README.md index 0fba9c78..ed316399 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ _979088a_ - **Python**: `>=3.8` - **Core**: `rhosocial-activerecord>=1.0.0.dev0,<2.0.0` - **Driver**: `psycopg[binary]>=3.2.13` -- **CI-tested server versions**: 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19rc1 +- **CI-tested server versions**: 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 - **Published**: PyPI `1.0.0.dev16` ## Installation From 952d9a9165b3e765880edec62ce7ad1b106563c1 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 15:15:07 +0800 Subject: [PATCH 70/81] test(postgres): cover async status introspector (native async) --- .../test_status_introspector_async_offline.py | 970 ++++++++++++++++++ 1 file changed, 970 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py new file mode 100644 index 00000000..ce34b8d8 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py @@ -0,0 +1,970 @@ +# tests/.../feature/backend/execute/introspection/test_status_introspector_async_offline.py +"""Offline unit tests for ``AsyncPostgreSQLStatusIntrospector``. + +PostgreSQL has a native async driver, so the async introspector must be covered +without a live server. Every I/O seam is an ``AsyncMock``: the fake backend's +``execute`` coroutine dispatches on a stable SQL token and returns a controlled +``result.data`` payload. A real (pure-Python, version-adapted) ``PostgresDialect`` +is used only so the query expression nodes render real SQL -- no connection, +socket or network is involved. + +Only ``AsyncPostgreSQLStatusIntrospector`` is exercised here; the synchronous +introspector is covered by ``test_status_introspector.py``. +""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect +from rhosocial.activerecord.backend.impl.postgres.introspection.status_introspector import ( + AsyncPostgreSQLStatusIntrospector, + POSTGRES_CONFIG_VARIABLES, +) +from rhosocial.activerecord.backend.impl.postgres.introspection.status_types import ( + ArchiveInfo, + PostgreSQLServerOverview, + ReplicationInfo, + SecurityInfo, + WALInfo, +) +from rhosocial.activerecord.backend.introspection.status import ( + ConnectionInfo, + DatabaseBriefInfo, + ExtensionInfo, + SessionInfo, + StatusCategory, + StatusItem, + StorageInfo, + UserInfo, +) + + +# --------------------------------------------------------------------------- +# SQL dispatch tokens. Each is a stable substring of the SQL rendered by the +# (version-adapted) PostgresDialect. SHOW statements are matched exactly because +# "SHOW ssl" is a prefix of "SHOW ssl_cert_file" / "SHOW ssl_key_file" / ... . +# --------------------------------------------------------------------------- +class SQL: + SETTINGS_ALL = "pg_settings ORDER BY name" + SETTINGS_NAMED = "pg_settings WHERE name IN" + ACTIVITY = "total_connections" + SHOW_MAX_CONN = "SHOW max_connections" + DB_SIZE = "PG_DATABASE_SIZE(%s)" + DB_LIST = "FROM pg_database" + CURRENT_DB = "SELECT CURRENT_DATABASE()" + SCHEMA_STATS = "FROM pg_namespace" + ROLE_LIST = "FROM pg_roles" + CURRENT_USER = "SELECT CURRENT_USER" + CURRENT_SCHEMA = "SELECT CURRENT_SCHEMA()" + CLIENT_ADDR = "INET_CLIENT_ADDR()" + SSL_SESSION = "FROM pg_stat_ssl" + SHOW_WAL_LEVEL = "SHOW wal_level" + WAL_POSITION = 'AS "wal_bytes"' + WAL_FILES = "pg_ls_waldir" + CHECKPOINT_COUNT = "checkpoint_count" + CHECKPOINT_LSN = "checkpoint_info" + SHOW_WAL_KEEP_SIZE = "SHOW wal_keep_size" + SHOW_WAL_KEEP_SEGMENTS = "SHOW wal_keep_segments" + RECOVERY = "PG_IS_IN_RECOVERY()" + REPL_SLOTS = "pg_replication_slots" + ACTIVE_REPL = "pg_stat_replication" + REPL_LAG = 'AS "lag_bytes"' + SHOW_ARCHIVE_MODE = "SHOW archive_mode" + SHOW_ARCHIVE_COMMAND = "SHOW archive_command" + SHOW_ARCHIVE_TIMEOUT = "SHOW archive_timeout" + ARCHIVE_STATS = "FROM pg_stat_archiver" + SHOW_SSL = "SHOW ssl" + SHOW_SSL_CERT = "SHOW ssl_cert_file" + SHOW_SSL_KEY = "SHOW ssl_key_file" + SHOW_SSL_CA = "SHOW ssl_ca_file" + SHOW_PASSWORD_ENCRYPTION = "SHOW password_encryption" + SHOW_ROW_SECURITY = "SHOW row_security" + EXT_LIST = "FROM pg_extension" + + +class FakeBackend: + """Minimal backend double: a real dialect plus an async execute seam.""" + + def __init__(self, responses=None, version=(16, 0, 0), database="testdb", password=None): + self.dialect = PostgresDialect() + self.dialect.version = tuple(version) + self.config = SimpleNamespace(database=database, password=password) + self._server_version_cache = tuple(version) + self.get_server_version = Mock(return_value=tuple(version)) + self.raise_all = False + self.null_result = False + self.execute = AsyncMock(side_effect=self._dispatch) + self._responses = dict(responses or {}) + + def _dispatch(self, sql, params=None): + if self.null_result: + return None + if self.raise_all: + raise RuntimeError("simulated backend failure") + for token, payload in self._responses.items(): + matched = (sql == token) if token.startswith("SHOW ") else (token in sql) + if matched: + if isinstance(payload, BaseException): + raise payload + return SimpleNamespace(data=payload) + return SimpleNamespace(data=[]) + + +def make_introspector(responses=None, **backend_kwargs): + """Build an async introspector wired to a fully mocked backend.""" + backend = FakeBackend(responses, **backend_kwargs) + return AsyncPostgreSQLStatusIntrospector(backend), backend + + +def setting(name, value, unit=None): + return {"name": name, "setting": value, "unit": unit} + + +def show(value): + """A SHOW statement returns one row with a single (anonymously named) column.""" + return [{"value": value}] + + +# --------------------------------------------------------------------------- +# get_overview +# --------------------------------------------------------------------------- +class TestAsyncOverview: + async def test_get_overview_happy_path_populates_all_families(self): + responses = { + SQL.SETTINGS_ALL: [setting("port", "5432")], + SQL.SETTINGS_NAMED: [setting("checkpoint_timeout", "300", "s")], + SQL.ACTIVITY: [{"total_connections": 12}], + SQL.SHOW_MAX_CONN: show("100"), + SQL.DB_SIZE: [{"size_bytes": 4096}], + SQL.DB_LIST: [{"name": "testdb", "size_bytes": 4096}], + SQL.CURRENT_DB: [{"current_database": "testdb"}], + SQL.SCHEMA_STATS: [{"schema_name": "public", "table_count": 3, "view_count": 1}], + SQL.ROLE_LIST: [{"name": "alice", "is_superuser": True, "owner": "postgres"}], + SQL.CURRENT_USER: [{"current_user": "alice"}], + SQL.CURRENT_SCHEMA: [{"current_schema": "public"}], + SQL.CLIENT_ADDR: [{"inet_client_addr": "10.0.0.5"}], + SQL.SSL_SESSION: [{"ssl": "t", "version": "TLSv1.3", "cipher": "AES"}], + SQL.SHOW_WAL_LEVEL: show("replica"), + SQL.WAL_POSITION: [{"wal_bytes": 1024}], + SQL.WAL_FILES: [{"wal_files": 7}], + SQL.CHECKPOINT_COUNT: [{"checkpoint_count": 9}], + SQL.CHECKPOINT_LSN: [{"checkpoint_info": "0/16B7F20"}], + SQL.SHOW_WAL_KEEP_SIZE: show("128MB"), + SQL.RECOVERY: show("f"), + SQL.REPL_SLOTS: [{"slot_count": 2}], + SQL.ACTIVE_REPL: [{"active_count": 1}], + SQL.REPL_LAG: [{"lag_bytes": 512}], + SQL.SHOW_ARCHIVE_MODE: show("on"), + SQL.SHOW_ARCHIVE_COMMAND: show("wal-archive"), + SQL.SHOW_ARCHIVE_TIMEOUT: show("300"), + SQL.ARCHIVE_STATS: [{"archived_count": 5, "failed_count": 0}], + SQL.SHOW_SSL: show("on"), + SQL.SHOW_SSL_CERT: show("server.crt"), + SQL.SHOW_SSL_KEY: show("server.key"), + SQL.SHOW_SSL_CA: show("ca.crt"), + SQL.SHOW_PASSWORD_ENCRYPTION: show("scram-sha-256"), + SQL.SHOW_ROW_SECURITY: show("on"), + SQL.EXT_LIST: [{"name": "uuid-ossp", "version": "1.1", "schema": "public"}], + } + introspector, _ = make_introspector(responses, password="secret") + + overview = await introspector.get_overview() + + assert isinstance(overview, PostgreSQLServerOverview) + assert overview.server_vendor == "PostgreSQL" + assert overview.server_version == "16.0.0" + assert [item.name for item in overview.configuration] == ["port"] + assert [item.name for item in overview.performance] == ["checkpoint_timeout"] + assert isinstance(overview.connections, ConnectionInfo) + assert overview.connections.active_count == 12 + assert overview.connections.max_connections == 100 + assert isinstance(overview.storage, StorageInfo) + assert overview.storage.total_size_bytes == 4096 + assert isinstance(overview.databases[0], DatabaseBriefInfo) + assert "schemas" in overview.databases[0].extra + assert isinstance(overview.users[0], UserInfo) + assert isinstance(overview.session, SessionInfo) + assert overview.session.user == "alice" + assert overview.session.password_used is True + assert isinstance(overview.wal, WALInfo) + assert overview.wal.wal_level == "replica" + assert isinstance(overview.replication, ReplicationInfo) + assert overview.replication.is_primary is True + assert isinstance(overview.archive, ArchiveInfo) + assert overview.archive.archive_mode == "on" + assert isinstance(overview.security, SecurityInfo) + assert overview.security.ssl_enabled is True + assert isinstance(overview.extensions[0], ExtensionInfo) + + async def test_get_overview_with_no_rows_returns_empty_collections(self): + introspector, _ = make_introspector() + + overview = await introspector.get_overview() + + assert overview.configuration == [] + assert overview.performance == [] + assert overview.databases == [] + assert overview.users == [] + assert overview.extensions == [] + assert overview.session.user is None + assert overview.wal == WALInfo() + assert overview.replication == ReplicationInfo() + assert overview.archive == ArchiveInfo() + assert overview.security == SecurityInfo() + + async def test_get_overview_to_dict_serializes_engine_families(self): + introspector, _ = make_introspector() + overview = await introspector.get_overview() + + payload = overview.to_dict() + + assert {"wal", "replication", "archive", "security"} <= payload.keys() + assert payload["server_vendor"] == "PostgreSQL" + + +# --------------------------------------------------------------------------- +# list_configuration +# --------------------------------------------------------------------------- +class TestAsyncListConfiguration: + SETTINGS = [ + setting("port", "5432"), + setting("shared_buffers", "134217728", "MB"), + setting("ssl", "on"), + setting("max_wal_senders", "10"), + setting("checkpoint_timeout", "300", "s"), + setting("bogus.unknown", "ignored"), + ] + + async def test_lists_known_settings_with_parsed_values(self): + introspector, _ = make_introspector({SQL.SETTINGS_ALL: self.SETTINGS}) + + items = await introspector.list_configuration() + + assert all(isinstance(item, StatusItem) for item in items) + names = [item.name for item in items] + assert "port" in names + assert "ssl" in names + assert "bogus.unknown" not in names + by_name = {item.name: item for item in items} + assert by_name["port"].value == "5432" + assert by_name["ssl"].value is True + assert by_name["port"].is_readonly is True + + async def test_empty_rows_return_no_items(self): + introspector, _ = make_introspector() + + assert await introspector.list_configuration() == [] + + async def test_row_unit_overrides_declared_unit(self): + introspector, _ = make_introspector( + {SQL.SETTINGS_ALL: [setting("work_mem", "65536", "kB")]} + ) + + items = await introspector.list_configuration() + + work_mem = next(item for item in items if item.name == "work_mem") + assert work_mem.unit == "kB" + + async def test_missing_row_unit_falls_back_to_declared_unit(self): + introspector, _ = make_introspector({SQL.SETTINGS_ALL: [setting("work_mem", "65536")]}) + + items = await introspector.list_configuration() + + work_mem = next(item for item in items if item.name == "work_mem") + assert work_mem.unit == "bytes" + + @pytest.mark.parametrize( + ("category", "expected_name"), + [ + (StatusCategory.CONFIGURATION, "port"), + (StatusCategory.SECURITY, "ssl"), + (StatusCategory.REPLICATION, "max_wal_senders"), + (StatusCategory.PERFORMANCE, "checkpoint_timeout"), + ], + ) + async def test_category_filter_keeps_only_matching_items(self, category, expected_name): + introspector, _ = make_introspector({SQL.SETTINGS_ALL: self.SETTINGS}) + + items = await introspector.list_configuration(category=category) + + assert items + assert all(item.category == category for item in items) + assert expected_name in {item.name for item in items} + + async def test_category_with_no_config_variables_returns_empty(self): + introspector, _ = make_introspector({SQL.SETTINGS_ALL: self.SETTINGS}) + + items = await introspector.list_configuration(category=StatusCategory.CONNECTION) + + assert items == [] + + async def test_all_declared_categories_are_reachable(self): + expected = {cat for _, cat, _, _, _ in POSTGRES_CONFIG_VARIABLES} + assert expected == { + StatusCategory.CONFIGURATION, + StatusCategory.PERFORMANCE, + StatusCategory.SECURITY, + StatusCategory.REPLICATION, + } + + +# --------------------------------------------------------------------------- +# list_performance_metrics +# --------------------------------------------------------------------------- +class TestAsyncPerformanceMetrics: + async def test_maps_named_settings_to_performance_items(self): + rows = [ + setting("checkpoint_timeout", "300", "s"), + setting("archive_command", "wal-archive"), + setting("bogus.unknown", "x"), + ] + introspector, _ = make_introspector({SQL.SETTINGS_NAMED: rows}) + + items = await introspector.list_performance_metrics() + + assert {item.name for item in items} == {"checkpoint_timeout", "archive_command"} + assert all(item.category == StatusCategory.PERFORMANCE for item in items) + assert all(isinstance(item, StatusItem) for item in items) + + async def test_empty_rows_return_no_items(self): + introspector, _ = make_introspector() + + assert await introspector.list_performance_metrics() == [] + + async def test_category_argument_does_not_alter_mapping(self): + rows = [setting("archive_timeout", "60", "s")] + introspector, _ = make_introspector({SQL.SETTINGS_NAMED: rows}) + + items = await introspector.list_performance_metrics(category=StatusCategory.SECURITY) + + assert len(items) == 1 + assert items[0].category == StatusCategory.PERFORMANCE + + +# --------------------------------------------------------------------------- +# get_connection_info +# --------------------------------------------------------------------------- +class TestAsyncConnectionInfo: + async def test_returns_activity_total_and_max_connections(self): + responses = { + SQL.ACTIVITY: [{"total_connections": 42}], + SQL.SHOW_MAX_CONN: show("200"), + } + introspector, _ = make_introspector(responses) + + info = await introspector.get_connection_info() + + assert isinstance(info, ConnectionInfo) + assert info.active_count == 42 + assert info.max_connections == 200 + + async def test_activity_row_without_key_defaults_to_one(self): + introspector, _ = make_introspector({SQL.ACTIVITY: [{}]}) + + info = await introspector.get_connection_info() + + assert info.active_count == 1 + + async def test_no_rows_returns_zero_and_none(self): + introspector, _ = make_introspector() + + info = await introspector.get_connection_info() + + assert info.active_count == 0 + assert info.max_connections is None + + async def test_show_failure_is_swallowed(self): + responses = { + SQL.ACTIVITY: [{"total_connections": 5}], + SQL.SHOW_MAX_CONN: RuntimeError("SHOW unsupported"), + } + introspector, _ = make_introspector(responses) + + info = await introspector.get_connection_info() + + assert info.active_count == 5 + assert info.max_connections is None + + +# --------------------------------------------------------------------------- +# get_storage_info +# --------------------------------------------------------------------------- +class TestAsyncStorageInfo: + async def test_returns_database_size(self): + introspector, _ = make_introspector({SQL.DB_SIZE: [{"size_bytes": 987654}]}) + + info = await introspector.get_storage_info() + + assert isinstance(info, StorageInfo) + assert info.total_size_bytes == 987654 + + async def test_empty_rows_leave_size_none(self): + introspector, _ = make_introspector() + + info = await introspector.get_storage_info() + + assert info.total_size_bytes is None + + async def test_uses_configured_database_name(self): + introspector, backend = make_introspector(database="analytics") + + await introspector.get_storage_info() + + sql = backend.execute.await_args.args[0] + assert "PG_DATABASE_SIZE(%s)" in sql + + +# --------------------------------------------------------------------------- +# list_databases +# --------------------------------------------------------------------------- +class TestAsyncListDatabases: + async def test_attaches_schema_info_to_current_database(self): + responses = { + SQL.DB_LIST: [ + {"name": "postgres", "size_bytes": 100}, + {"name": "testdb", "size_bytes": 200}, + ], + SQL.CURRENT_DB: [{"current_database": "testdb"}], + SQL.SCHEMA_STATS: [ + {"schema_name": "public", "table_count": 4, "view_count": 2}, + {"schema_name": "audit", "table_count": 1, "view_count": 0}, + ], + } + introspector, _ = make_introspector(responses) + + databases = await introspector.list_databases() + + assert [db.name for db in databases] == ["postgres", "testdb"] + assert all(isinstance(db, DatabaseBriefInfo) for db in databases) + current = databases[1] + assert current.extra["schemas"]["public"] == {"tables": 4, "views": 2} + assert current.table_count == 5 + assert current.view_count == 2 + assert databases[0].extra == {} + + async def test_schema_rows_without_name_are_skipped(self): + responses = { + SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}], + SQL.CURRENT_DB: [{"current_database": "testdb"}], + SQL.SCHEMA_STATS: [ + {"schema_name": None, "table_count": 9, "view_count": 9}, + {"schema_name": "public", "table_count": 2, "view_count": 1}, + ], + } + introspector, _ = make_introspector(responses) + + databases = await introspector.list_databases() + + assert databases[0].extra["schemas"] == {"public": {"tables": 2, "views": 1}} + + async def test_no_current_database_leaves_all_databases_without_schema_info(self): + responses = { + SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}], + SQL.CURRENT_DB: [], + SQL.SCHEMA_STATS: [{"schema_name": "public", "table_count": 4, "view_count": 2}], + } + introspector, _ = make_introspector(responses) + + databases = await introspector.list_databases() + + assert databases[0].extra == {} + assert databases[0].table_count is None + + async def test_schema_query_failure_is_swallowed(self): + responses = { + SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}], + SQL.CURRENT_DB: [{"current_database": "testdb"}], + SQL.SCHEMA_STATS: RuntimeError("permission denied"), + } + introspector, _ = make_introspector(responses) + + databases = await introspector.list_databases() + + assert len(databases) == 1 + assert databases[0].extra == {} + + async def test_current_database_query_failure_is_swallowed(self): + responses = { + SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}], + SQL.CURRENT_DB: RuntimeError("query failed"), + } + introspector, _ = make_introspector(responses) + + databases = await introspector.list_databases() + + assert len(databases) == 1 + + async def test_empty_database_list(self): + introspector, _ = make_introspector() + + assert await introspector.list_databases() == [] + + +# --------------------------------------------------------------------------- +# list_users +# --------------------------------------------------------------------------- +class TestAsyncListUsers: + async def test_maps_roles_with_owner_into_extra(self): + rows = [ + {"name": "alice", "is_superuser": True, "owner": "postgres"}, + {"name": "bob", "is_superuser": False, "owner": None}, + ] + introspector, _ = make_introspector({SQL.ROLE_LIST: rows}) + + users = await introspector.list_users() + + assert all(isinstance(user, UserInfo) for user in users) + assert users[0].name == "alice" + assert users[0].is_superuser is True + assert users[0].extra == {"owner": "postgres"} + assert users[1].extra == {} + + async def test_empty_roles(self): + introspector, _ = make_introspector() + + assert await introspector.list_users() == [] + + +# --------------------------------------------------------------------------- +# get_session_info +# --------------------------------------------------------------------------- +class TestAsyncSessionInfo: + async def test_full_session_with_ssl_and_password(self): + responses = { + SQL.CURRENT_USER: [{"current_user": "alice"}], + SQL.CURRENT_DB: [{"current_database": "testdb"}], + SQL.CURRENT_SCHEMA: [{"current_schema": "public"}], + SQL.CLIENT_ADDR: [{"inet_client_addr": "10.0.0.5"}], + SQL.SSL_SESSION: [{"ssl": "t", "version": "TLSv1.3", "cipher": "AES-256"}], + } + introspector, _ = make_introspector(responses, password="pw") + + session = await introspector.get_session_info() + + assert isinstance(session, SessionInfo) + assert session.user == "alice" + assert session.database == "testdb" + assert session.schema == "public" + assert session.host == "10.0.0.5" + assert session.ssl_enabled is True + assert session.ssl_version == "TLSv1.3" + assert session.ssl_cipher == "AES-256" + assert session.password_used is True + + @pytest.mark.parametrize( + ("ssl_value", "expected"), + [("t", True), ("true", True), (True, True), ("f", False), (False, False), (None, False)], + ) + async def test_ssl_flag_parsing(self, ssl_value, expected): + introspector, _ = make_introspector( + {SQL.SSL_SESSION: [{"ssl": ssl_value, "version": None, "cipher": None}]} + ) + + session = await introspector.get_session_info() + + assert session.ssl_enabled is expected + + async def test_null_client_host_is_ignored(self): + introspector, _ = make_introspector({SQL.CLIENT_ADDR: [{"inet_client_addr": None}]}) + + session = await introspector.get_session_info() + + assert session.host is None + + async def test_no_rows_leave_session_fields_unset(self): + introspector, _ = make_introspector() + + session = await introspector.get_session_info() + + assert session.user is None + assert session.database is None + assert session.schema is None + assert session.host is None + assert session.ssl_enabled is None + assert session.password_used is False + + async def test_all_queries_failing_still_returns_session_info(self): + introspector, backend = make_introspector() + backend.raise_all = True + + session = await introspector.get_session_info() + + assert isinstance(session, SessionInfo) + assert session.user is None + assert session.password_used is False + + +# --------------------------------------------------------------------------- +# get_wal_info +# --------------------------------------------------------------------------- +class TestAsyncWalInfo: + def _full_responses(self): + return { + SQL.SHOW_WAL_LEVEL: show("replica"), + SQL.WAL_POSITION: [{"wal_bytes": 2048}], + SQL.WAL_FILES: [{"wal_files": 12}], + SQL.CHECKPOINT_COUNT: [{"checkpoint_count": 30}], + SQL.CHECKPOINT_LSN: [{"checkpoint_info": "0/2000000"}], + SQL.SHOW_WAL_KEEP_SIZE: show("64MB"), + } + + async def test_full_wal_info(self): + introspector, _ = make_introspector(self._full_responses()) + + wal = await introspector.get_wal_info() + + assert isinstance(wal, WALInfo) + assert wal.wal_level == "replica" + assert wal.wal_size_bytes == 2048 + assert wal.wal_files == 12 + assert wal.checkpoint_count == 30 + assert wal.checkpoint_time == "0/2000000" + assert wal.wal_segments == "64MB" + + async def test_old_version_skips_pg10_queries_and_uses_keep_segments(self): + responses = self._full_responses() + responses[SQL.SHOW_WAL_KEEP_SEGMENTS] = show("32") + introspector, backend = make_introspector(responses, version=(9, 6, 24)) + + wal = await introspector.get_wal_info() + + assert wal.wal_segments == "32" + executed = [call.args[0] for call in backend.execute.await_args_list] + assert not any("pg_ls_waldir" in sql for sql in executed) + assert not any("pg_control_checkpoint" in sql for sql in executed) + + async def test_empty_rows_leave_fields_none(self): + introspector, _ = make_introspector() + + wal = await introspector.get_wal_info() + + assert wal == WALInfo() + + async def test_all_queries_failing_still_returns_wal_info(self): + introspector, backend = make_introspector() + backend.raise_all = True + + assert await introspector.get_wal_info() == WALInfo() + + +# --------------------------------------------------------------------------- +# get_replication_info +# --------------------------------------------------------------------------- +class TestAsyncReplicationInfo: + async def test_primary_with_active_streaming(self): + responses = { + SQL.RECOVERY: show("f"), + SQL.REPL_SLOTS: [{"slot_count": 3}], + SQL.ACTIVE_REPL: [{"active_count": 2}], + } + introspector, _ = make_introspector(responses) + + repl = await introspector.get_replication_info() + + assert isinstance(repl, ReplicationInfo) + assert repl.is_primary is True + assert repl.is_standby is False + assert repl.replication_slots == 3 + assert repl.active_replications == 2 + assert repl.streaming is True + assert repl.lag_bytes is None + + async def test_standby_reports_lag(self): + responses = { + SQL.RECOVERY: show("t"), + SQL.REPL_SLOTS: [{"slot_count": 1}], + SQL.ACTIVE_REPL: [{"active_count": 0}], + SQL.REPL_LAG: [{"lag_bytes": 4096}], + } + introspector, _ = make_introspector(responses) + + repl = await introspector.get_replication_info() + + assert repl.is_standby is True + assert repl.is_primary is False + assert repl.streaming is False + assert repl.lag_bytes == 4096 + + @pytest.mark.parametrize("recovery_value", [True, "t", "true"]) + async def test_truthy_recovery_values_mean_standby(self, recovery_value): + introspector, _ = make_introspector({SQL.RECOVERY: show(recovery_value)}) + + repl = await introspector.get_replication_info() + + assert repl.is_standby is True + + async def test_standby_lag_query_failure_is_swallowed(self): + responses = { + SQL.RECOVERY: show("t"), + SQL.REPL_LAG: RuntimeError("lag query unsupported"), + } + introspector, _ = make_introspector(responses) + + repl = await introspector.get_replication_info() + + assert repl.is_standby is True + assert repl.lag_bytes is None + + async def test_empty_rows_leave_flags_unset(self): + introspector, _ = make_introspector() + + repl = await introspector.get_replication_info() + + assert repl == ReplicationInfo() + + async def test_all_queries_failing_still_returns_replication_info(self): + introspector, backend = make_introspector() + backend.raise_all = True + + assert await introspector.get_replication_info() == ReplicationInfo() + + +# --------------------------------------------------------------------------- +# get_archive_info +# --------------------------------------------------------------------------- +class TestAsyncArchiveInfo: + async def test_full_archive_info_with_integer_timeout(self): + responses = { + SQL.SHOW_ARCHIVE_MODE: show("on"), + SQL.SHOW_ARCHIVE_COMMAND: show("wal-archive %p"), + SQL.SHOW_ARCHIVE_TIMEOUT: show("300"), + SQL.ARCHIVE_STATS: [ + { + "archived_count": 10, + "failed_count": 2, + "last_archived": "2026-11-20", + "last_failed": "2026-11-19", + } + ], + } + introspector, _ = make_introspector(responses) + + archive = await introspector.get_archive_info() + + assert isinstance(archive, ArchiveInfo) + assert archive.archive_mode == "on" + assert archive.archive_command == "wal-archive %p" + assert archive.archive_timeout == 300 + assert archive.archived_count == 10 + assert archive.failed_count == 2 + assert archive.last_archived == "2026-11-20" + assert archive.last_failed == "2026-11-19" + + @pytest.mark.parametrize("timeout_value", ["5min", "0", None, ""]) + async def test_non_integer_or_zero_timeout_is_ignored(self, timeout_value): + introspector, _ = make_introspector({SQL.SHOW_ARCHIVE_TIMEOUT: show(timeout_value)}) + + archive = await introspector.get_archive_info() + + assert archive.archive_timeout is None + + async def test_archive_stats_with_null_counts_default_to_zero(self): + introspector, _ = make_introspector( + {SQL.ARCHIVE_STATS: [{"archived_count": None, "failed_count": None}]} + ) + + archive = await introspector.get_archive_info() + + assert archive.archived_count == 0 + assert archive.failed_count == 0 + + async def test_empty_rows_leave_fields_none(self): + introspector, _ = make_introspector() + + assert await introspector.get_archive_info() == ArchiveInfo() + + async def test_all_queries_failing_still_returns_archive_info(self): + introspector, backend = make_introspector() + backend.raise_all = True + + assert await introspector.get_archive_info() == ArchiveInfo() + + +# --------------------------------------------------------------------------- +# get_security_info +# --------------------------------------------------------------------------- +class TestAsyncSecurityInfo: + async def test_full_security_info_from_show_values(self): + responses = { + SQL.SHOW_SSL: show("on"), + SQL.SHOW_SSL_CERT: show("server.crt"), + SQL.SHOW_SSL_KEY: show("server.key"), + SQL.SHOW_SSL_CA: show("ca.crt"), + SQL.SHOW_PASSWORD_ENCRYPTION: show("scram-sha-256"), + SQL.SHOW_ROW_SECURITY: show("on"), + } + introspector, _ = make_introspector(responses) + + security = await introspector.get_security_info() + + assert isinstance(security, SecurityInfo) + assert security.ssl_enabled is True + assert security.ssl_cert_file == "server.crt" + assert security.ssl_key_file == "server.key" + assert security.ssl_ca_file == "ca.crt" + assert security.password_encryption == "scram-sha-256" + assert security.row_security is True + + @pytest.mark.parametrize( + ("ssl_value", "rls_value", "expected_ssl", "expected_rls"), + [ + (True, True, True, True), + ("off", "off", False, False), + (False, False, False, False), + ], + ) + async def test_boolean_flags(self, ssl_value, rls_value, expected_ssl, expected_rls): + responses = {SQL.SHOW_SSL: show(ssl_value), SQL.SHOW_ROW_SECURITY: show(rls_value)} + introspector, _ = make_introspector(responses) + + security = await introspector.get_security_info() + + assert security.ssl_enabled is expected_ssl + assert security.row_security is expected_rls + + async def test_empty_rows_leave_fields_none(self): + introspector, _ = make_introspector() + + assert await introspector.get_security_info() == SecurityInfo() + + async def test_all_queries_failing_still_returns_security_info(self): + introspector, backend = make_introspector() + backend.raise_all = True + + assert await introspector.get_security_info() == SecurityInfo() + + +# --------------------------------------------------------------------------- +# list_extensions +# --------------------------------------------------------------------------- +class TestAsyncExtensions: + async def test_maps_extension_rows(self): + rows = [ + {"name": "uuid-ossp", "version": "1.1", "schema": "public", "description": "UUIDs"}, + {"name": "pgcrypto", "version": "1.3", "schema": None, "description": None}, + ] + introspector, _ = make_introspector({SQL.EXT_LIST: rows}) + + extensions = await introspector.list_extensions() + + assert len(extensions) == 2 + assert all(isinstance(ext, ExtensionInfo) for ext in extensions) + assert extensions[0].name == "uuid-ossp" + assert extensions[0].version == "1.1" + assert extensions[0].description == "UUIDs" + assert extensions[1].schema is None + + async def test_empty_rows_return_empty_list(self): + introspector, _ = make_introspector() + + assert await introspector.list_extensions() == [] + + async def test_query_failure_returns_empty_list(self): + introspector, backend = make_introspector() + backend.raise_all = True + + assert await introspector.list_extensions() == [] + + +# --------------------------------------------------------------------------- +# I/O seam and inherited helpers (through the async class) +# --------------------------------------------------------------------------- +class TestAsyncExecutionSeamAndHelpers: + async def test_exec_query_async_returns_empty_when_execute_returns_none(self): + introspector, backend = make_introspector() + backend.null_result = True + + result = await introspector._exec_query_async("SELECT 1") + + assert result == [] + backend.execute.assert_awaited_once_with("SELECT 1", None) + + async def test_exec_query_async_returns_result_data(self): + introspector, backend = make_introspector({SQL.CURRENT_DB: [{"current_database": "x"}]}) + + result = await introspector._exec_query_async(*[SQL.CURRENT_DB, ()]) + + assert result == [{"current_database": "x"}] + + async def test_get_vendor_name(self): + introspector, _ = make_introspector() + + assert introspector._get_vendor_name() == "PostgreSQL" + + @pytest.mark.parametrize( + ("raw", "expected"), + [ + (b"utf8", "utf8"), + (True, True), + ("on", True), + ("yes", True), + ("off", False), + ("no", False), + (42, 42), + ("5432", "5432"), + (1.5, "1.5"), + ], + ) + async def test_parse_setting_value(self, raw, expected): + introspector, _ = make_introspector() + + assert introspector.parse_setting_value(raw) == expected + + async def test_create_status_item_parses_value(self): + introspector, _ = make_introspector() + + item = introspector._create_status_item( + name="ssl", + value="on", + category=StatusCategory.SECURITY, + description="SSL enabled", + unit=None, + is_readonly=True, + ) + + assert item.value is True + assert item.category is StatusCategory.SECURITY + assert item.description == "SSL enabled" + assert item.is_readonly is True + + +class TestAsyncVersionResolution: + async def test_version_string_from_server_version_cache(self): + introspector, _ = make_introspector(version=(18, 3, 1)) + + assert introspector._get_version_string() == "18.3.1" + + async def test_version_tuple_from_server_version_cache(self): + introspector, _ = make_introspector(version=(18, 3, 1)) + + assert introspector._get_version_tuple() == (18, 3, 1) + + async def test_version_string_falls_back_to_private_version(self): + introspector, backend = make_introspector() + del backend._server_version_cache + backend._version = (15, 2, 0) + + assert introspector._get_version_string() == "15.2.0" + + async def test_version_string_falls_back_to_get_server_version(self): + introspector, backend = make_introspector(version=(14, 1, 0)) + del backend._server_version_cache + backend.get_server_version.return_value = (14, 1, 0) + + assert introspector._get_version_string() == "14.1.0" + + async def test_version_string_unknown_when_all_sources_fail(self): + introspector, backend = make_introspector() + del backend._server_version_cache + backend.get_server_version.side_effect = RuntimeError("no server") + + assert introspector._get_version_string() == "Unknown" + + async def test_version_tuple_unknown_when_all_sources_fail(self): + introspector, backend = make_introspector() + del backend._server_version_cache + backend.get_server_version.side_effect = RuntimeError("no server") + + assert introspector._get_version_tuple() == (0, 0, 0) From 87c9c841ba013f4cb6e23e6cc4f7a379ba435609 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 15:59:38 +0800 Subject: [PATCH 71/81] test(postgres): offline tests for partition maintenance/plan --- .../partition/test_partition_offline.py | 1445 +++++++++++++++++ 1 file changed, 1445 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py new file mode 100644 index 00000000..0e08962b --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py @@ -0,0 +1,1445 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py +"""Offline unit tests for PostgreSQL partition maintenance and plan helpers. + +Every check here is synchronous and connectionless: pure parsing/comparison +helpers are called directly, plan derivation is exercised in memory, and the +catalog/DDL I/O seams are replaced with ``MagicMock``. No PostgreSQL server, +network or driver connection is involved. +""" + +from dataclasses import FrozenInstanceError +from datetime import date, datetime, timedelta, timezone +from unittest.mock import MagicMock + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect +from rhosocial.activerecord.backend.impl.postgres.partition import ( + HashBranch, + HashPolicy, + ListBranch, + ListPolicy, + PairedDifference, + PartitionBatchReport, + PartitionInfo, + PartitionReport, + PartitionSpec, + PostgresPartitionMaintenance, + PostgresPartitionPlan, + RangeBranch, + RangePolicy, +) +from rhosocial.activerecord.backend.impl.postgres.partition import maintenance as mnt +from rhosocial.activerecord.backend.impl.postgres.partition import plan as plan_mod + +UTC = timezone.utc +PLUS8 = timezone(timedelta(hours=8)) +PLUS830 = timezone(timedelta(hours=8, minutes=30)) +MINUS5 = timezone(-timedelta(hours=5)) + + +def _info(name, **overrides): + values = {"name": name, "parent": "events", "level": 1} + values.update(overrides) + return PartitionInfo(**values) + + +def _spec(name, method="RANGE", **overrides): + values = { + "name": name, + "parent": "events", + "method": method, + "columns": ("created_at",), + "bounds": {}, + "level": 1, + "is_leaf": True, + } + values.update(overrides) + return PartitionSpec(**values) + + +def _range_plan(parent="events", bounds=None): + if bounds is None: + bounds = ((date(2026, 1, 1), date(2026, 2, 1)),) + return PostgresPartitionPlan( + parent=parent, + method="RANGE", + columns="created_at", + policy=RangePolicy(bounds=bounds), + ) + + +def _base(): + backend = MagicMock() + backend.dialect = PostgresDialect(version=(17, 0, 0)) + return mnt._PartitionMaintenanceBase(backend), backend + + +# --------------------------------------------------------------------------- # +# Pure bound-text helpers +# --------------------------------------------------------------------------- # +class TestUnquoteBoundValue: + @pytest.mark.parametrize( + "text, expected", + [ + ("'abc'", "abc"), + (" 'abc' ", "abc"), + ("'a''b'", "a'b"), + ("''", ""), + ("abc", "abc"), + ("", ""), + ("'unterminated", "'unterminated"), + ("' x '", " x "), + ], + ) + def test_unquote(self, text, expected): + assert mnt._unquote_bound_value(text) == expected + + +class TestSplitBoundValues: + @pytest.mark.parametrize( + "text, expected", + [ + ("a, b, c", ("a", "b", "c")), + (" a , b ", ("a", "b")), + ("'a,b', c", ("'a,b'", "c")), + ("'a''b', c", ("'a''b'", "c")), + ("'x,y','z'", ("'x,y'", "'z'")), + ("", ()), + ("a", ("a",)), + ("a,,b", ("a", "", "b")), + ("a,", ("a",)), + ], + ) + def test_split(self, text, expected): + assert mnt._split_bound_values(text) == expected + + +class TestParseListValue: + @pytest.mark.parametrize( + "token, expected", + [ + ("'abc'", "abc"), + ("'a''b'", "a'b"), + ("'NULL'", "NULL"), + ("NULL", None), + ("null", None), + ("42", 42), + ("-7", -7), + ("+3", 3), + (" 42 ", 42), + ("1.5", 1.5), + ("-0.25", -0.25), + ("abc", "abc"), + ("", ""), + ], + ) + def test_parse(self, token, expected): + assert mnt._parse_list_value(token) == expected + + +class TestParseTemporal: + @pytest.mark.parametrize( + "text, expected", + [ + ("2026-01-02", date(2026, 1, 2)), + ("'2026-01-02'", date(2026, 1, 2)), + ("2026-01-02 03:04", datetime(2026, 1, 2, 3, 4)), + ("2026-01-02T03:04:05", datetime(2026, 1, 2, 3, 4, 5)), + ("2026-01-02 03:04:05.12", datetime(2026, 1, 2, 3, 4, 5, 120000)), + ("2026-01-02 03:04:05Z", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)), + ("2026-01-02 03:04:05+08", datetime(2026, 1, 2, 3, 4, 5, tzinfo=PLUS8)), + ("2026-01-02 03:04:05+08:30", datetime(2026, 1, 2, 3, 4, 5, tzinfo=PLUS830)), + ("2026-01-02 03:04:05-05:00", datetime(2026, 1, 2, 3, 4, 5, tzinfo=MINUS5)), + ("MINVALUE", None), + ("MAXVALUE", None), + ("'MAXVALUE'", None), + ("NULL", None), + ("nonsense", None), + ("2026-13-01", None), + ("2026-02-30", None), + ("2026-01-02 03:04:05.1234567", None), + ("", None), + ], + ) + def test_parse(self, text, expected): + assert mnt._parse_temporal(text) == expected + + +class TestParsePartitionBound: + @pytest.mark.parametrize("text", [None, "", " ", 123, "nonsense"]) + def test_unparseable_returns_none(self, text): + assert mnt._parse_partition_bound(text) is None + + def test_range_date_bounds(self): + result = mnt._parse_partition_bound("FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')") + assert result == { + "kind": "RANGE", + "range_start": date(2026, 1, 1), + "range_end": date(2026, 2, 1), + } + + def test_range_with_maxvalue_omits_unparsed_end(self): + result = mnt._parse_partition_bound("for values from ('2026-01-01') to (maxvalue)") + assert result == {"kind": "RANGE", "range_start": date(2026, 1, 1)} + + def test_list_values(self): + result = mnt._parse_partition_bound("FOR VALUES IN ('a', 'b', 3, NULL)") + assert result == {"kind": "LIST", "list_values": ("a", "b", 3, None)} + + @pytest.mark.parametrize( + "text, modulus, remainder", + [ + ("FOR VALUES WITH (MODULUS 4, REMAINDER 2)", 4, 2), + ("for values with (modulus 8, remainder 0)", 8, 0), + ("FOR VALUES WITH ( modulus 3 , remainder 1 )", 3, 1), + ], + ) + def test_hash_bounds(self, text, modulus, remainder): + assert mnt._parse_partition_bound(text) == { + "kind": "HASH", + "modulus": modulus, + "remainder": remainder, + } + + +class TestSameBound: + @pytest.mark.parametrize( + "actual, expected, same", + [ + (date(2026, 1, 1), date(2026, 1, 1), True), + (date(2026, 1, 1), date(2026, 1, 2), False), + (datetime(2026, 1, 1), datetime(2026, 1, 1), True), + (datetime(2026, 1, 1, 12), datetime(2026, 1, 1), False), + (date(2026, 1, 1), datetime(2026, 1, 1), True), + (datetime(2026, 1, 1), date(2026, 1, 1), True), + (date(2026, 1, 1), datetime(2026, 1, 1, 12), False), + (datetime(2026, 1, 1, 8, tzinfo=PLUS8), datetime(2026, 1, 1, tzinfo=UTC), True), + (datetime(2026, 1, 1, 9, tzinfo=PLUS8), datetime(2026, 1, 1, tzinfo=UTC), False), + (datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 1, 1), True), + ("a", "a", True), + (1, 1, True), + (1, 2, False), + (None, None, True), + (None, "x", False), + ], + ) + def test_same_bound(self, actual, expected, same): + assert mnt._same_bound(actual, expected) is same + + +class TestFormatAndNormalise: + @pytest.mark.parametrize( + "value, expected", + [ + (datetime(2026, 1, 2, 3, 4, 5), "2026-01-02 03:04:05"), + (date(2026, 1, 2), "2026-01-02"), + (42, "42"), + (None, "None"), + ], + ) + def test_format_bound_value(self, value, expected): + assert mnt._format_bound_value(value) == expected + + @pytest.mark.parametrize( + "text, expected", + [ + (" a b ", "a b"), + ("\n a\t b \n", "a b"), + ("", None), + (" ", None), + (None, None), + (123, None), + ], + ) + def test_normalise_bound_text(self, text, expected): + assert mnt._normalise_bound_text(text) == expected + + +class TestKeyValueAndSorting: + @pytest.mark.parametrize( + "value, expected", + [ + (datetime(2026, 1, 1), "2026-01-01"), + (datetime(2026, 1, 1, tzinfo=UTC), "2026-01-01"), + (datetime(2026, 1, 1, 12, 30), "2026-01-01 12:30:00"), + (date(2026, 1, 1), "2026-01-01"), + ("abc", "'abc'"), + (4, "4"), + (None, "None"), + ], + ) + def test_key_value(self, value, expected): + assert mnt._key_value(value) == expected + + @pytest.mark.parametrize( + "values, expected", + [ + ((3, 1, 2), (1, 2, 3)), + (("b", "a"), ("a", "b")), + (("a", 1), (1, "a")), + ((), ()), + ], + ) + def test_sorted_values(self, values, expected): + assert mnt._sorted_values(values) == expected + + +class TestExtrasBucket: + def test_range_bucket(self): + info = _info( + "p", + method="range", + extras={"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)}, + ) + assert mnt._extras_bucket(info) == "RANGE|2026-01-01|2026-02-01" + + def test_range_bucket_normalises_midnight_datetime(self): + info = _info( + "p", + method="RANGE", + extras={ + "range_start": datetime(2026, 1, 1), + "range_end": datetime(2026, 2, 1), + }, + ) + assert mnt._extras_bucket(info) == "RANGE|2026-01-01|2026-02-01" + + def test_hash_bucket(self): + info = _info("p", method="HASH", extras={"modulus": 4, "remainder": 2}) + assert mnt._extras_bucket(info) == "HASH|4|2" + + def test_list_bucket_sorts_values(self): + info = _info("p", method="LIST", extras={"list_values": ("b", "a")}) + assert mnt._extras_bucket(info) == "LIST|'a','b'" + + def test_list_bucket_with_integers(self): + info = _info("p", method="LIST", extras={"list_values": (2, 1)}) + assert mnt._extras_bucket(info) == "LIST|1,2" + + def test_incomplete_or_missing_extras_return_none(self): + assert mnt._extras_bucket(_info("p", method="RANGE", extras={"range_start": 1})) is None + assert mnt._extras_bucket(_info("p", method="LIST", extras={})) is None + assert ( + mnt._extras_bucket(_info("p", method=None, extras={"modulus": 4, "remainder": 1})) + is None + ) + + +class TestDifferenceKeyAndSignature: + def test_extras_take_precedence_over_bound(self): + info = _info( + "events_2026_01", + method="RANGE", + bound="some unparsed text", + extras={"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)}, + ) + assert mnt._difference_key(info) == "RANGE|2026-01-01|2026-02-01" + assert mnt._boundary_signature(info) == "RANGE|2026-01-01|2026-02-01" + + def test_bound_is_fallback(self): + info = _info("events_x", bound=" FOR VALUES IN ('a') ") + assert mnt._difference_key(info) == "FOR VALUES IN ('a')" + assert mnt._boundary_signature(info) == "FOR VALUES IN ('a')" + + def test_name_suffix_is_last_resort(self): + info = _info("events_2026_01", parent="events") + assert mnt._difference_key(info) == "2026_01" + + def test_unprefixed_name_used_as_is(self): + assert mnt._difference_key(_info("orphan", parent="events")) == "orphan" + assert mnt._difference_key(_info("solo", parent=None)) == "solo" + + def test_signature_none_without_extras_or_bound(self): + assert mnt._boundary_signature(_info("p")) is None + + def test_boundaries_disagree_on_verbatim_text(self): + left = _info("p", bound="for values in ('a')") + right = _info("p", bound="FOR VALUES IN ('a')") + assert mnt._boundaries_disagree(left, right) is True + + def test_boundaries_agree_on_same_text(self): + left = _info("p", bound="FOR VALUES IN ('a')") + right = _info("p", bound=" FOR VALUES IN ('a') ") + assert mnt._boundaries_disagree(left, right) is False + + def test_boundaries_disagree_falls_back_to_extras(self): + extras = {"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)} + left = _info("p", method="RANGE", extras=extras) + right = _info( + "p", + method="RANGE", + extras={"range_start": date(2026, 1, 1), "range_end": date(2026, 3, 1)}, + ) + assert mnt._boundaries_disagree(left, right) is True + assert mnt._boundaries_disagree(left, _info("p", method="RANGE", extras=extras)) is False + + def test_boundaries_agree_when_both_have_no_signature(self): + assert mnt._boundaries_disagree(_info("a"), _info("b")) is False + + +# --------------------------------------------------------------------------- # +# Shape derivation helpers +# --------------------------------------------------------------------------- # +class TestShapeHelpers: + def test_policy_shape_none(self): + assert mnt._policy_shape(None) is None + + def test_policy_shape_explicit_range(self): + policy = RangePolicy(columns="d", bounds=((date(2026, 1, 1), date(2026, 2, 1)),)) + assert mnt._policy_shape(policy) == ("RANGE", ("d",), None, True) + + @pytest.mark.parametrize( + "interval, normalised", + [ + ("quarter", (1, "quarter")), + ((3, "month"), (3, "month")), + ("15 day", (15, "day")), + ], + ) + def test_policy_shape_generated_range(self, interval, normalised): + policy = RangePolicy(columns="d", start=date(2026, 1, 1), interval=interval) + assert mnt._policy_shape(policy) == ("RANGE", ("d",), normalised, False) + + def test_policy_shape_list(self): + policy = ListPolicy(columns="status", groups=(("a",),)) + assert mnt._policy_shape(policy) == ("LIST", ("status",)) + + def test_policy_shape_hash(self): + assert mnt._policy_shape(HashPolicy(columns="tenant", modulus=4)) == ( + "HASH", + ("tenant",), + 4, + ) + + def test_branch_shape(self): + assert mnt._branch_shape(HashBranch(remainder=0)) == ("HashBranch", None) + branch = HashBranch(remainder=1, child=HashPolicy(modulus=2)) + assert mnt._branch_shape(branch) == ("HashBranch", ("HASH", ("bucket",), 2)) + branch = RangeBranch(date(2026, 1, 1), date(2026, 2, 1)) + assert mnt._branch_shape(branch) == ("RangeBranch", None) + + def test_plan_shape_equal_for_identical_plans(self): + left = _range_plan() + right = _range_plan() + assert mnt._plan_shape(left) == mnt._plan_shape(right) + + @pytest.mark.parametrize( + "mutate", + [ + lambda p: PostgresPartitionPlan( + parent=p.parent, + method="LIST", + columns=p.columns, + policy=ListPolicy(groups=(("a",),)), + ), + lambda p: PostgresPartitionPlan( + parent=p.parent, method="RANGE", columns="other", policy=p.policy + ), + lambda p: PostgresPartitionPlan( + parent=p.parent, + method="RANGE", + columns=p.columns, + policy=RangePolicy(start=date(2027, 1, 1), interval="year"), + ), + ], + ) + def test_plan_shape_detects_structure_changes(self, mutate): + plan = _range_plan() + assert mnt._plan_shape(mutate(plan)) != mnt._plan_shape(plan) + + def test_plan_shape_includes_branches(self): + plan = PostgresPartitionPlan( + parent="events", + method="HASH", + columns="tenant", + modulus=2, + branches=( + HashBranch(0), + HashBranch(1, child=RangePolicy(bounds=((date(2026, 1, 1), date(2026, 2, 1)),))), + ), + ) + shape = mnt._plan_shape(plan) + assert shape[0] == "HASH" + assert shape[2] == 2 + assert shape[4] == ( + ("HashBranch", None), + ("HashBranch", ("RANGE", ("created_at",), None, True)), + ) + + +# --------------------------------------------------------------------------- # +# _PartitionMaintenanceBase helpers +# --------------------------------------------------------------------------- # +class TestParseRows: + def test_empty_rows(self): + assert mnt._PartitionMaintenanceBase._parse_rows([]) == () + + def test_derives_method_bound_extras_and_stats(self): + rows = [ + { + "name": "events_2026_01", + "parent": "events", + "level": 1, + "schema_name": "public", + "partition_key": "RANGE (created_at)", + "bound": "FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')", + "row_count": "12", + "total_bytes": "4096", + "is_partitioned": 0, + } + ] + info = mnt._PartitionMaintenanceBase._parse_rows(rows)[0] + assert info.name == "events_2026_01" + assert info.parent == "events" + assert info.level == 1 + assert info.schema == "public" + assert info.method == "RANGE" + assert info.bound == rows[0]["bound"] + assert info.row_count == 12 + assert info.size_bytes == 4096 + assert info.is_partitioned is False + assert info.extras == { + "range_start": date(2026, 1, 1), + "range_end": date(2026, 2, 1), + } + + @pytest.mark.parametrize( + "partition_key, method", + [ + ("HASH (tenant)", "HASH"), + ("LIST (status)", "LIST"), + ("RANGE (created_at)", "RANGE"), + ("KEY (x)", None), + (None, None), + ("", None), + ], + ) + def test_method_detection(self, partition_key, method): + info = mnt._PartitionMaintenanceBase._parse_rows( + [ + {"name": "p", "partition_key": partition_key}, + ] + )[0] + assert info.method == method + + def test_missing_stats_become_none_and_defaults(self): + info = mnt._PartitionMaintenanceBase._parse_rows([{"name": "p"}])[0] + assert info.row_count is None + assert info.size_bytes is None + assert info.level == 0 + assert info.parent is None + assert info.is_partitioned is False + assert info.extras == {} + + def test_list_extras_parsed(self): + info = mnt._PartitionMaintenanceBase._parse_rows( + [ + {"name": "p", "partition_key": "LIST (status)", "bound": "FOR VALUES IN ('a', 2)"}, + ] + )[0] + assert info.extras == {"list_values": ("a", 2)} + + +class TestExpectedHelpers: + def test_expected_returns_specs(self): + base, _ = _base() + specs = base._expected(_range_plan(), None) + assert [spec.name for spec in specs] == ["events_2026_01_01"] + + def test_expected_rejects_plan_without_partitions(self): + base, _ = _base() + plan = PostgresPartitionPlan(parent="events", method="RANGE", columns="d") + with pytest.raises(ValueError, match="no partitions"): + base._expected(plan, None) + + def test_safe_expected_returns_empty_for_unbounded_plan(self): + base, _ = _base() + plan = PostgresPartitionPlan( + parent="events", + method="RANGE", + columns="d", + policy=RangePolicy(start=date(2026, 1, 1)), + ) + assert base._safe_expected(plan) == () + assert len(base._safe_expected(plan, through=date(2026, 3, 1))) == 2 + + def test_safe_expected_reraises_for_bounded_empty_plan(self): + base, _ = _base() + plan = PostgresPartitionPlan(parent="events", method="RANGE", columns="d") + with pytest.raises(ValueError): + base._safe_expected(plan) + + def test_actual_names_excludes_root(self): + infos = [ + _info("events", level=0, parent=None), + _info("p1", level=1), + _info("p1_a", level=2, parent="p1"), + ] + actual = mnt._PartitionMaintenanceBase._actual_names(infos) + assert set(actual) == {"p1", "p1_a"} + assert actual["p1"].level == 1 + + +class TestBoundaryComparison: + def _range_spec(self): + return _spec( + "events_2026_01_01", + method="RANGE", + bounds={"from": date(2026, 1, 1), "to": date(2026, 2, 1)}, + range_start=date(2026, 1, 1), + range_end=date(2026, 2, 1), + ) + + def test_range_matching_bound_has_no_issue(self): + base, _ = _base() + info = _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')") + assert base._boundary_issue(self._range_spec(), info) is None + assert base._boundary_mismatch(self._range_spec(), info) is False + + def test_range_mismatch_issue_and_flag(self): + base, _ = _base() + info = _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') TO ('2026-03-01')") + assert base._boundary_issue(self._range_spec(), info) == ( + "boundary mismatch for events_2026_01_01: catalog " + "2026-01-01..2026-03-01, plan 2026-01-01..2026-02-01" + ) + assert base._boundary_mismatch(self._range_spec(), info) is True + + def test_unparsed_bound_issue_but_no_mismatch(self): + base, _ = _base() + info = _info("events_2026_01_01", bound=None) + assert base._boundary_issue(self._range_spec(), info) == ( + "unparsed bound for events_2026_01_01: " + ) + assert base._boundary_mismatch(self._range_spec(), info) is False + + def test_maxvalue_bound_is_unparsed_issue(self): + base, _ = _base() + info = _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') TO (MAXVALUE)") + assert base._boundary_issue(self._range_spec(), info).startswith("unparsed bound") + + def test_kind_mismatch(self): + base, _ = _base() + info = _info("events_2026_01_01", bound="FOR VALUES IN ('a')") + assert base._boundary_issue(self._range_spec(), info) == ( + "boundary mismatch for events_2026_01_01: catalog LIST bound, plan RANGE bound" + ) + assert base._boundary_mismatch(self._range_spec(), info) is True + + def test_list_boundary_comparison(self): + base, _ = _base() + spec = _spec("events_a", method="LIST", bounds={"values": ("a", "b")}) + matching = _info("events_a", bound="FOR VALUES IN ('b', 'a')") + assert base._boundary_issue(spec, matching) is None + assert base._boundary_mismatch(spec, matching) is False + wrong = _info("events_a", bound="FOR VALUES IN ('x')") + assert base._boundary_issue(spec, wrong) == ( + "boundary mismatch for events_a: catalog values ('x',), plan values ('a', 'b')" + ) + assert base._boundary_mismatch(spec, wrong) is True + + def test_hash_boundary_comparison(self): + base, _ = _base() + spec = _spec("events_p2", method="HASH", bounds={"modulus": 4, "remainder": 2}) + matching = _info("events_p2", bound="FOR VALUES WITH (MODULUS 4, REMAINDER 2)") + assert base._boundary_issue(spec, matching) is None + wrong = _info("events_p2", bound="FOR VALUES WITH (MODULUS 4, REMAINDER 1)") + assert base._boundary_issue(spec, wrong) == ( + "boundary mismatch for events_p2: catalog modulus 4 remainder 1, " + "plan modulus 4 remainder 2" + ) + assert base._boundary_mismatch(spec, wrong) is True + + def test_needs_partition_missing_or_mismatched(self): + base, _ = _base() + spec = self._range_spec() + assert base._needs_partition(spec, {}) is True + matching = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')") + assert base._needs_partition(spec, {spec.name: matching}) is False + wrong = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-03-01')") + assert base._needs_partition(spec, {spec.name: wrong}) is True + + def test_missing_pairs(self): + base, _ = _base() + spec = self._range_spec() + assert base._missing([spec], {}) == (("events", spec.name),) + matching = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')") + assert base._missing([spec], {spec.name: matching}) == () + + +class TestOtherBaseHelpers: + def test_orphans_bounded(self): + base, _ = _base() + plan = _range_plan() + spec = _spec("events_2026_01_01") + actual = {"events_2026_01_01": _info("events_2026_01_01"), "events_z": _info("events_z")} + assert base._orphans(plan, [spec], actual, None) == ("events_z",) + + def test_orphans_unbounded(self): + base, _ = _base() + plan = PostgresPartitionPlan( + parent="events", + method="RANGE", + columns="d", + policy=RangePolicy(start=date(2026, 1, 1)), + ) + assert base._orphans(plan, [], {"x": _info("x")}, None) == () + + def test_units_flat_plan(self): + specs = [_spec("a"), _spec("b")] + assert mnt._PartitionMaintenanceBase._units(_range_plan(), specs) == (tuple(specs),) + assert mnt._PartitionMaintenanceBase._units(_range_plan(), []) == () + + def test_units_multilevel_plan(self): + plan = PostgresPartitionPlan( + parent="events", + method="HASH", + columns="tenant", + modulus=2, + branches=(HashBranch(0), HashBranch(1)), + ) + branch0 = _spec("events_p0", level=1) + leaf0 = _spec("events_p0_0", level=2, parent="events_p0") + branch1 = _spec("events_p1", level=1) + assert mnt._PartitionMaintenanceBase._units(plan, [branch0, leaf0, branch1]) == ( + (branch0, leaf0), + (branch1,), + ) + + def test_continuity_gap_and_overlap(self): + base, _ = _base() + specs = [ + _spec("a", range_start=date(2026, 1, 1), range_end=date(2026, 2, 1)), + _spec("b", range_start=date(2026, 2, 2), range_end=date(2026, 3, 1)), + _spec("c", range_start=date(2026, 2, 15), range_end=date(2026, 3, 15), parent="other"), + ] + issues = base._continuity_issues(specs) + assert "gap in events between a and b" in issues + assert "overlap in other between b and c" not in issues # b is in a different parent + + def test_continuity_overlap(self): + base, _ = _base() + specs = [ + _spec("a", range_start=date(2026, 1, 1), range_end=date(2026, 2, 1)), + _spec("b", range_start=date(2026, 1, 15), range_end=date(2026, 2, 15)), + ] + assert base._continuity_issues(specs) == ("overlap in events between a and b",) + + def test_continuity_ignores_unranged_specs(self): + base, _ = _base() + assert base._continuity_issues([_spec("a"), _spec("b")]) == () + + def test_structure_issues_clean(self): + base, _ = _base() + plan = _range_plan() + root = _info("events", level=0, parent=None, method="RANGE") + spec = _spec( + "events_2026_01_01", + method="RANGE", + bounds={"from": date(2026, 1, 1), "to": date(2026, 2, 1)}, + range_start=date(2026, 1, 1), + range_end=date(2026, 2, 1), + ) + info = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')") + assert base._structure_issues(plan, [root, info], [spec]) == () + + def test_structure_issues_no_root(self): + base, _ = _base() + assert base._structure_issues(_range_plan(), [], []) == ( + "partitioned parent events does not exist", + ) + + def test_structure_issues_root_method_mismatch(self): + base, _ = _base() + root = _info("events", level=0, parent=None, method="LIST") + assert base._structure_issues(_range_plan(), [root], []) == ( + "parent events is partitioned by LIST, plan says RANGE", + ) + + def test_structure_issues_parent_and_leaf_flags(self): + base, _ = _base() + root = _info("events", level=0, parent=None, method="RANGE") + spec = _spec( + "p", + bounds={"from": date(2026, 1, 1), "to": date(2026, 2, 1)}, + range_start=date(2026, 1, 1), + range_end=date(2026, 2, 1), + ) + info = _info( + "p", + parent="other", + is_partitioned=True, + bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')", + ) + issues = base._structure_issues(_range_plan(), [root, info], [spec]) + assert "p belongs to other, plan expects events" in issues + assert "leaf p is partitioned; plan expects it to be a leaf" in issues + + def test_structure_issues_branch_flags(self): + base, _ = _base() + root = _info("events", level=0, parent=None, method="RANGE") + spec = _spec("p", child_method="RANGE") + plain = _info("p", is_partitioned=False) + issues = base._structure_issues(_range_plan(), [root, plain], [spec]) + assert "branch p is not further partitioned; RANGE leaves are missing" in issues + wrong = _info("p", is_partitioned=True, method="HASH") + issues = base._structure_issues(_range_plan(), [root, wrong], [spec]) + assert "branch p is partitioned by HASH, plan says RANGE" in issues + + def test_report_composition(self): + base, _ = _base() + plan = _range_plan() + infos = (_info("events", level=0, parent=None, method="RANGE"),) + specs = (_spec("events_2026_01_01"),) + report = base._report(plan, infos, specs, None, dry_run=True) + assert report.target == "events" + assert report.partitions == infos + assert report.missing == (("events", "events_2026_01_01"),) + assert report.issues == () + assert report.dry_run is True + + def test_without(self): + specs = [_spec("a"), _spec("b"), _spec("c")] + assert mnt._PartitionMaintenanceBase._without(specs, ["b"]) == (specs[0], specs[2]) + + def test_drop_candidates_rejects_non_date_cutoff(self): + base, _ = _base() + with pytest.raises(TypeError, match="cutoff must be a date or datetime"): + base._drop_candidates(_range_plan(), "2026-02-15", [], None) + + def test_drop_candidates_selects_early_existing_leaves(self): + base, _ = _base() + plan = _range_plan( + bounds=( + (date(2026, 1, 1), date(2026, 2, 1)), + (date(2026, 2, 1), date(2026, 3, 1)), + ) + ) + infos = [ + _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') " "TO ('2026-02-01')"), + _info("events_2026_02_01", bound="FOR VALUES FROM ('2026-02-01') " "TO ('2026-03-01')"), + ] + candidates = base._drop_candidates(plan, date(2026, 2, 15), infos, None) + assert [spec.name for spec in candidates] == ["events_2026_01_01"] + + def test_resolve_batch_dedup_and_pairs(self): + plan_a = _range_plan("a") + plan_b = _range_plan("b") + entries, unique = mnt._PartitionMaintenanceBase._resolve_batch( + [plan_a, plan_a, plan_b], None + ) + assert entries == () + assert unique == (plan_a, plan_b) + entries, unique = mnt._PartitionMaintenanceBase._resolve_batch( + None, [("pair", plan_a, plan_b)] + ) + assert entries == (("pair", plan_a, plan_b),) + assert unique == (plan_a, plan_b) + + @pytest.mark.parametrize( + "plans, pairs, message", + [ + ([], None, "at least one plan"), + (["x"], None, "must be PostgresPartitionPlan"), + (None, [("bad",)], "must be \\(name, left_plan, right_plan\\)"), + ], + ) + def test_resolve_batch_errors(self, plans, pairs, message): + with pytest.raises((TypeError, ValueError), match=message): + mnt._PartitionMaintenanceBase._resolve_batch(plans, pairs) + + def test_bucket_map_flags_duplicates(self): + infos = [ + _info("a", level=1, bound="FOR VALUES IN ('x')"), + _info("b", level=1, bound="FOR VALUES IN ('x')"), + _info("skip", level=2, bound="FOR VALUES IN ('y')"), + ] + issues = [] + buckets = mnt._PartitionMaintenanceBase._bucket_map("p", "left", infos, issues) + assert set(buckets) == {"FOR VALUES IN ('x')"} + assert "duplicate bucket" in issues[0] + + def test_paired_report_differences_and_issues(self): + base, _ = _base() + left_plan = _range_plan("left_t") + right_plan = _range_plan("right_t") + left_report = PartitionReport( + target="left_t", + partitions=(_info("l_only", level=1, bound="FOR VALUES IN ('left')"),), + ) + right_report = PartitionReport( + target="right_t", + partitions=(_info("r_only", level=1, bound="FOR VALUES IN ('right')"),), + ) + differences, issues = base._paired_report( + (("p", left_plan, right_plan),), + {"left_t": left_report, "right_t": right_report}, + ) + assert issues == () + assert differences == ( + PairedDifference("p", "FOR VALUES IN ('left')", "left", "l_only", None), + PairedDifference("p", "FOR VALUES IN ('right')", "right", None, "r_only"), + ) + + def test_paired_report_incompatible_plan(self): + base, _ = _base() + left_plan = _range_plan("left_t") + right_plan = PostgresPartitionPlan( + parent="right_t", + method="LIST", + columns="d", + policy=ListPolicy(groups=(("a",),)), + ) + differences, issues = base._paired_report((("p", left_plan, right_plan),), {}) + assert differences == () + assert issues == ("pair p plans are not comparable",) + + def test_paired_report_boundary_drift_with_same_semantic_key(self): + base, _ = _base() + left_plan = _range_plan("t_left") + right_plan = _range_plan("t_right") + extras = {"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)} + left = _info( + "l", + level=1, + method="RANGE", + extras=extras, + bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')", + ) + right = _info( + "r", + level=1, + method="RANGE", + extras=extras, + bound="for values from ('2026-01-01') to ('2026-02-01')", + ) + reports = { + "t_left": PartitionReport(target="t_left", partitions=(left,)), + "t_right": PartitionReport(target="t_right", partitions=(right,)), + } + differences, issues = base._paired_report((("p", left_plan, right_plan),), reports) + assert differences == () + assert issues == ("boundary mismatch for p/RANGE|2026-01-01|2026-02-01",) + + def test_batch_report_assembly(self): + reports = {"t": PartitionReport(target="t")} + batch = mnt._PartitionMaintenanceBase._batch_report( + (("p", _range_plan("a"), _range_plan("b")),), + reports, + (PairedDifference("p", "k", "left", "l", None),), + ("issue",), + ) + assert isinstance(batch, PartitionBatchReport) + assert batch.reports == reports + assert batch.pairs == ("p",) + assert batch.issues == ("issue",) + assert len(batch.differences) == 1 + + +# --------------------------------------------------------------------------- # +# I/O seams (mocked) +# --------------------------------------------------------------------------- # +class TestIoSeams: + def test_base_seams_raise_not_implemented(self): + base, _ = _base() + with pytest.raises(NotImplementedError): + base._fetch_rows("SELECT 1", ()) + with pytest.raises(NotImplementedError): + base._execute("DDL", ()) + with pytest.raises(NotImplementedError): + base._run_units(_range_plan(), (), lambda spec: None) + + def test_sync_fetch_and_execute_delegate_to_backend(self): + backend = MagicMock() + backend.dialect = PostgresDialect(version=(17, 0, 0)) + backend.fetch_all.return_value = [{"name": "p"}] + maintenance = PostgresPartitionMaintenance(backend) + assert maintenance._fetch_rows("SELECT", ("p",)) == [{"name": "p"}] + backend.fetch_all.assert_called_once_with("SELECT", ("p",)) + maintenance._execute("DDL", ("p",)) + backend.execute.assert_called_once_with("DDL", ("p",)) + + def test_infos_uses_fetch_seam_and_parses_rows(self): + base, _ = _base() + rows = [ + { + "name": "events_2026_01_01", + "parent": "events", + "level": 1, + "partition_key": "RANGE (created_at)", + "bound": "FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')", + } + ] + base._fetch_rows = MagicMock(return_value=rows) + infos = base._infos(_range_plan()) + assert base._fetch_rows.call_count == 1 + sql, params = base._fetch_rows.call_args.args + assert "partition_tree" in sql + assert params == ("events",) + assert infos[0].name == "events_2026_01_01" + assert "range_start" in infos[0].extras + + +# --------------------------------------------------------------------------- # +# plan.py pure helpers and policy objects +# --------------------------------------------------------------------------- # +class TestPlanModuleHelpers: + @pytest.mark.parametrize( + "value, expected", + [ + ("a", ("a",)), + (("a", "b"), ("a", "b")), + (["a", "b"], ("a", "b")), + ], + ) + def test_as_columns_valid(self, value, expected): + assert plan_mod._as_columns(value) == expected + + @pytest.mark.parametrize("value", [None, 1, {}]) + def test_as_columns_wrong_type(self, value): + with pytest.raises(TypeError, match="columns must be a string"): + plan_mod._as_columns(value) + + @pytest.mark.parametrize("value", [(), [], ("",), ("a", " ")]) + def test_as_columns_empty(self, value): + with pytest.raises(ValueError): + plan_mod._as_columns(value) + + @pytest.mark.parametrize( + "method, expected", + [ + ("range", "RANGE"), + ("List", "LIST"), + ("HASH", "HASH"), + ], + ) + def test_normalise_method(self, method, expected): + assert plan_mod._normalise_method(method) == expected + + @pytest.mark.parametrize("method", ["KEY", "", None, 1]) + def test_normalise_method_rejects_unknown(self, method): + with pytest.raises(ValueError, match="method must be one of"): + plan_mod._normalise_method(method) + + @pytest.mark.parametrize( + "values, expected", + [ + (("a", "b"), "a_b"), + ((1, 2), "1_2"), + (("a-b",), "a_b"), + (("",), "value"), + ], + ) + def test_label_from_values(self, values, expected): + assert plan_mod._label_from_values(values) == expected + + def test_render_label(self): + assert ( + plan_mod._render_label("{year}-{month:02d}", date(2026, 3, 1), date(2026, 4, 1)) + == "2026-03" + ) + assert plan_mod._render_label("q{quarter}", date(2026, 4, 1), date(2026, 7, 1)) == "q2" + + +class TestRangePolicy: + def test_method_and_explicit_bounds(self): + policy = RangePolicy(columns="d", bounds=((date(2026, 1, 1), date(2026, 2, 1)),)) + assert policy.method == "RANGE" + assert list(policy.iter_bounds()) == [(date(2026, 1, 1), date(2026, 2, 1))] + assert policy.label_for(date(2026, 1, 1), date(2026, 2, 1)) == "2026_01_01" + + def test_generated_bounds_by_count(self): + policy = RangePolicy(start=date(2026, 1, 1), count=3) + assert list(policy.iter_bounds()) == [ + (date(2026, 1, 1), date(2026, 2, 1)), + (date(2026, 2, 1), date(2026, 3, 1)), + (date(2026, 3, 1), date(2026, 4, 1)), + ] + assert policy.label_for(date(2026, 1, 1), date(2026, 2, 1)) == "2026_01" + + def test_generated_bounds_by_through(self): + policy = RangePolicy(start=date(2026, 1, 1), interval=(15, "day")) + assert list(policy.iter_bounds(through=date(2026, 1, 20))) == [ + (date(2026, 1, 1), date(2026, 1, 16)), + (date(2026, 1, 16), date(2026, 1, 31)), + ] + + def test_generated_policy_without_horizon_raises(self): + policy = RangePolicy(start=date(2026, 1, 1)) + with pytest.raises(ValueError, match="count or through"): + list(policy.iter_bounds()) + + def test_custom_label_pattern(self): + policy = RangePolicy( + start=date(2026, 1, 1), + count=1, + label_pattern="y{year}q{quarter}", + ) + assert policy.label_for(date(2026, 1, 1), date(2026, 4, 1)) == "y2026q1" + + @pytest.mark.parametrize( + "kwargs", + [ + {}, + {"start": date(2026, 1, 1), "bounds": ((date(2026, 1, 1), date(2026, 2, 1)),)}, + {"start": "2026-01-01"}, + {"start": date(2026, 1, 1), "count": 0}, + {"start": date(2026, 1, 1), "count": True}, + {"start": date(2026, 1, 1), "interval": "fortnight"}, + {"bounds": ()}, + {"bounds": ((date(2026, 1, 1),),)}, + {"bounds": ((date(2026, 2, 1), date(2026, 1, 1)),)}, + ], + ) + def test_invalid_construction(self, kwargs): + with pytest.raises((TypeError, ValueError)): + RangePolicy(**kwargs) + + +class TestListPolicy: + def test_iter_groups_derived_labels(self): + policy = ListPolicy(columns="status", groups=(("a", "b"), ("c",))) + assert policy.method == "LIST" + assert list(policy.iter_groups()) == [(("a", "b"), "a_b"), (("c",), "c")] + + def test_iter_groups_explicit_labels(self): + policy = ListPolicy(groups=(("a",), ("b",)), labels=("first", "second")) + assert list(policy.iter_groups()) == [(("a",), "first"), (("b",), "second")] + + @pytest.mark.parametrize( + "kwargs", + [ + {}, + {"groups": ((),)}, + {"groups": (("a",),), "labels": ("one", "two")}, + {"groups": (("a",),), "labels": ("",)}, + ], + ) + def test_invalid_construction(self, kwargs): + with pytest.raises(ValueError): + ListPolicy(**kwargs) + + +class TestHashPolicy: + def test_all_remainders(self): + policy = HashPolicy(modulus=3) + assert policy.method == "HASH" + assert list(policy.iter_remainders()) == [0, 1, 2] + + def test_selected_remainders(self): + policy = HashPolicy(modulus=4, remainders=(2, 0)) + assert list(policy.iter_remainders()) == [2, 0] + + @pytest.mark.parametrize( + "kwargs", + [ + {"modulus": 0}, + {"modulus": -1}, + {"modulus": True}, + {"modulus": "4"}, + {"modulus": 4, "remainders": ()}, + {"modulus": 4, "remainders": (4,)}, + {"modulus": 4, "remainders": (1, 1)}, + {"modulus": 4, "remainders": (True,)}, + ], + ) + def test_invalid_construction(self, kwargs): + with pytest.raises((TypeError, ValueError)): + HashPolicy(**kwargs) + + +class TestBranches: + def test_hash_branch_defaults(self): + branch = HashBranch(remainder=3) + assert branch.remainder == 3 + assert branch.child is None + assert branch.name is None + + @pytest.mark.parametrize( + "kwargs", + [ + {"remainder": "0"}, + {"remainder": True}, + {"remainder": -1}, + {"remainder": 0, "name": " "}, + ], + ) + def test_hash_branch_invalid(self, kwargs): + with pytest.raises((TypeError, ValueError)): + HashBranch(**kwargs) + + def test_range_branch(self): + branch = RangeBranch(date(2026, 1, 1), date(2026, 2, 1), label="jan") + assert branch.label == "jan" + + @pytest.mark.parametrize( + "kwargs", + [ + {"start": "2026-01-01", "end": date(2026, 2, 1)}, + {"start": date(2026, 2, 1), "end": date(2026, 1, 1)}, + {"start": date(2026, 1, 1), "end": date(2026, 1, 1), "name": " "}, + {"start": date(2026, 1, 1), "end": date(2026, 2, 1), "label": ""}, + ], + ) + def test_range_branch_invalid(self, kwargs): + with pytest.raises((TypeError, ValueError)): + RangeBranch(**kwargs) + + def test_list_branch_normalises_values(self): + assert ListBranch(values=["a", "b"]).values == ("a", "b") + + @pytest.mark.parametrize( + "kwargs", + [ + {"values": ()}, + {"values": ("a",), "name": ""}, + {"values": ("a",), "label": " "}, + ], + ) + def test_list_branch_invalid(self, kwargs): + with pytest.raises(ValueError): + ListBranch(**kwargs) + + +class TestPostgresPartitionPlan: + def test_method_and_columns_normalised(self): + plan = PostgresPartitionPlan( + parent="events", + method="range", + columns="d", + policy=RangePolicy(count=1, start=date(2026, 1, 1)), + ) + assert plan.method == "RANGE" + assert plan.columns == ("d",) + + @pytest.mark.parametrize( + "kwargs", + [ + {"parent": ""}, + {"parent": "e", "method": "KEY"}, + {"parent": "e", "method": "RANGE", "columns": ()}, + {"parent": "e", "method": "RANGE", "name_pattern": "x"}, + {"parent": "e", "method": "RANGE", "name_pattern": ""}, + {"parent": "e", "method": "RANGE", "schema": " "}, + ], + ) + def test_invalid_plan_fields(self, kwargs): + with pytest.raises((TypeError, ValueError)): + PostgresPartitionPlan(**kwargs) + + def test_policy_and_branches_mutually_exclusive(self): + with pytest.raises(ValueError, match="mutually exclusive"): + PostgresPartitionPlan( + parent="e", + method="HASH", + columns="tenant", + modulus=2, + branches=(HashBranch(0),), + policy=HashPolicy(modulus=2), + ) + + @pytest.mark.parametrize( + "kwargs, message", + [ + ( + { + "parent": "e", + "method": "HASH", + "columns": "tenant", + "policy": RangePolicy(bounds=((date(2026, 1, 1), date(2026, 2, 1)),)), + }, + "must be a HashPolicy", + ), + ( + { + "parent": "e", + "method": "HASH", + "columns": "tenant", + "branches": (HashBranch(0),), + }, + "requires modulus", + ), + ( + {"parent": "e", "method": "RANGE", "columns": "d", "modulus": 2}, + "only meaningful for a HASH parent", + ), + ( + { + "parent": "e", + "method": "HASH", + "columns": "tenant", + "modulus": 0, + "branches": (HashBranch(0),), + }, + "positive integer", + ), + ( + { + "parent": "e", + "method": "HASH", + "columns": "tenant", + "modulus": 1, + "branches": (HashBranch(1),), + }, + "less than modulus", + ), + ], + ) + def test_hash_specific_validation(self, kwargs, message): + with pytest.raises((TypeError, ValueError), match=message): + PostgresPartitionPlan(**kwargs) + + @pytest.mark.parametrize( + "method, branch", + [ + ("HASH", RangeBranch(date(2026, 1, 1), date(2026, 2, 1))), + ("RANGE", HashBranch(0)), + ("LIST", HashBranch(0)), + ], + ) + def test_branch_type_must_match_method(self, method, branch): + with pytest.raises(ValueError, match="branches must be"): + PostgresPartitionPlan(parent="e", method=method, columns="d", branches=(branch,)) + + def test_branch_suffix_variants(self): + plan = PostgresPartitionPlan( + parent="events", + method="HASH", + columns="tenant", + modulus=2, + branches=(HashBranch(0), HashBranch(1, name="custom")), + ) + assert plan.branch_suffix(0, plan.branches[0]) == "p0" + assert plan.branch_suffix(1, plan.branches[1]) == "custom" + assert plan.branch_name(0, plan.branches[0]) == "events_p0" + assert plan.branch_name(1, plan.branches[1]) == "events_custom" + + def test_branch_suffix_range_and_list(self): + range_branch = RangeBranch(date(2026, 3, 1), date(2026, 4, 1), label="march") + list_branch = ListBranch(values=("a", "b")) + assert ( + plan_mod.PostgresPartitionPlan( + parent="e", method="RANGE", columns="d", branches=(range_branch,) + ).branch_suffix(0, range_branch) + == "march" + ) + assert ( + plan_mod.PostgresPartitionPlan( + parent="e", method="LIST", columns="d", branches=(list_branch,) + ).branch_suffix(0, list_branch) + == "a_b" + ) + + def test_custom_name_pattern(self): + plan = PostgresPartitionPlan( + parent="events", + method="HASH", + columns="tenant", + modulus=2, + branches=(HashBranch(0),), + name_pattern="{parent}~{suffix}", + ) + assert plan.branch_name(0, plan.branches[0]) == "events~p0" + + def test_iter_specs_flat(self): + plan = _range_plan( + bounds=( + (date(2026, 1, 1), date(2026, 2, 1)), + (date(2026, 2, 1), date(2026, 3, 1)), + ) + ) + specs = list(plan.iter_specs()) + assert [spec.name for spec in specs] == [ + "events_2026_01_01", + "events_2026_02_01", + ] + assert all(spec.level == 1 and spec.is_leaf for spec in specs) + + def test_iter_specs_multilevel_order(self): + plan = PostgresPartitionPlan( + parent="events", + method="HASH", + columns="tenant", + modulus=2, + branches=( + HashBranch(0, child=RangePolicy(bounds=((date(2026, 1, 1), date(2026, 2, 1)),))), + HashBranch(1), + ), + ) + specs = list(plan.iter_specs()) + assert [spec.level for spec in specs] == [1, 2, 1] + assert specs[0].name == "events_p0" + assert specs[0].child_method == "RANGE" + assert specs[1].name == "events_p0_2026_01_01" + assert specs[1].parent == "events_p0" + assert specs[2].is_leaf is True + + def test_iter_specs_duplicate_name_raises(self): + plan = PostgresPartitionPlan( + parent="events", + method="HASH", + columns="tenant", + modulus=2, + branches=(HashBranch(0, name="same"), HashBranch(1, name="same")), + ) + with pytest.raises(ValueError, match="duplicate partition name"): + list(plan.iter_specs()) + + @pytest.mark.parametrize( + "plan, through, bounded", + [ + (_range_plan(), None, True), + ( + PostgresPartitionPlan( + parent="e", + method="RANGE", + columns="d", + policy=RangePolicy(start=date(2026, 1, 1)), + ), + None, + False, + ), + ( + PostgresPartitionPlan( + parent="e", + method="RANGE", + columns="d", + policy=RangePolicy(start=date(2026, 1, 1)), + ), + date(2026, 3, 1), + True, + ), + (PostgresPartitionPlan(parent="e", method="RANGE", columns="d"), None, True), + ], + ) + def test_is_fully_bounded(self, plan, through, bounded): + assert plan.is_fully_bounded(through=through) is bounded + + +class TestPartitionSpec: + def test_fields_and_equality(self): + spec = _spec( + "p", + range_start=date(2026, 1, 1), + range_end=date(2026, 2, 1), + child_method="HASH", + child_columns=("tenant",), + label="jan", + ) + assert spec.name == "p" + assert spec.parent == "events" + assert spec.child_columns == ("tenant",) + assert spec == _spec( + "p", + range_start=date(2026, 1, 1), + range_end=date(2026, 2, 1), + child_method="HASH", + child_columns=("tenant",), + label="jan", + ) + + def test_frozen(self): + spec = _spec("p") + with pytest.raises(FrozenInstanceError): + spec.name = "other" From 6e4a2f31332154d290b783f61ca7c435fee93d25 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 16:33:32 +0800 Subject: [PATCH 72/81] test(postgres): offline tests for cli and ddl/type --- .../backend/construct/cli/test_cli_offline.py | 1503 +++++++++++++++++ .../construct/ddl/test_ddl_type_offline.py | 623 +++++++ 2 files changed, 2126 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py new file mode 100644 index 00000000..98a11069 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py @@ -0,0 +1,1503 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py +"""Offline unit tests for the PostgreSQL CLI subcommands. + +Every test here is pure: parser construction, serialization/formatting helpers, +validation maps and handler dispatch are exercised with MagicMock / AsyncMock +backends and providers. No PostgreSQL server, socket or driver is contacted. +""" + +import argparse +import json +import sys +import types +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from rhosocial.activerecord.backend.errors import ConnectionError, QueryError +from rhosocial.activerecord.backend.impl.postgres.cli import info as info_mod +from rhosocial.activerecord.backend.impl.postgres.cli import introspect as introspect_mod +from rhosocial.activerecord.backend.impl.postgres.cli import query as query_mod +from rhosocial.activerecord.backend.impl.postgres.cli import status as status_mod +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect +from rhosocial.activerecord.backend.introspection.status import ( + ConnectionInfo, + DatabaseBriefInfo, + ExtensionInfo, + ServerOverview, + SessionInfo, + StatusCategory, + StatusItem, + StorageInfo, + UserInfo, +) + + +def _args(**overrides): + """A namespace carrying every flag the four handlers may read.""" + base = dict( + output="json", + rich_ascii=False, + verbose=0, + type="all", + database="db", + named_connection=None, + is_async=False, + version=None, + sql=None, + file=None, + log_level="INFO", + name=None, + column=None, + right_table=None, + right_column=None, + include_system=False, + connection_params=[], + ) + base.update(overrides) + return argparse.Namespace(**base) + + +def _subparser(factory): + return factory(argparse.ArgumentParser(prog="pgx").add_subparsers(dest="command")) + + +# =========================================================================== +# status +# =========================================================================== + + +class TestStatusParser: + def test_defaults(self): + args = _subparser(status_mod.create_parser).parse_args([]) + assert args.type == "all" + assert args.output == "table" + assert args.verbose == 0 + assert args.rich_ascii is False + + @pytest.mark.parametrize("status_type", status_mod.STATUS_TYPES) + def test_every_status_type_accepted(self, status_type): + parser = _subparser(status_mod.create_parser) + assert parser.parse_args([status_type]).type == status_type + + def test_invalid_type_rejected(self): + with pytest.raises(SystemExit): + _subparser(status_mod.create_parser).parse_args(["bogus"]) + + @pytest.mark.parametrize("output", ["table", "json", "csv", "tsv"]) + def test_output_choices(self, output): + assert _subparser(status_mod.create_parser).parse_args(["-o", output]).output == output + + def test_invalid_output_rejected(self): + with pytest.raises(SystemExit): + _subparser(status_mod.create_parser).parse_args(["-o", "xml"]) + + @pytest.mark.parametrize( + "flags,attr,value", + [ + (["-vvv"], "verbose", 3), + (["--rich-ascii"], "rich_ascii", True), + (["--async"], "is_async", True), + (["--named-connection", "app.db"], "named_connection", "app.db"), + ], + ) + def test_flags(self, flags, attr, value): + assert getattr(_subparser(status_mod.create_parser).parse_args(flags), attr) == value + + +class TestStatusHandleDispatch: + def test_missing_database_exits(self, capsys): + with pytest.raises(SystemExit) as exc: + status_mod.handle(_args(database=None)) + assert exc.value.code == 1 + assert "database is required" in capsys.readouterr().err + + def test_sync_dispatch(self): + args = _args(rich_ascii=True) + with patch.object(status_mod, "create_provider") as provider_factory, patch.object( + status_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object(status_mod, "PostgresBackend") as backend_cls, patch.object( + status_mod, "_handle_status_sync" + ) as handler: + status_mod.handle(args) + provider_factory.assert_called_once_with("json", ascii_borders=True) + backend_cls.assert_called_once_with(connection_config="cfg") + handler.assert_called_once_with( + args, backend_cls.return_value, provider_factory.return_value + ) + + def test_async_dispatch(self): + args = _args(is_async=True) + coroutine = object() + with patch.object(status_mod, "create_provider"), patch.object( + status_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object(status_mod, "AsyncPostgresBackend") as backend_cls, patch.object( + status_mod, "_handle_status_async", new=MagicMock(return_value=coroutine) + ) as handler, patch.object( + status_mod, "run_coroutine" + ) as runner: + status_mod.handle(args) + backend_cls.assert_called_once_with(connection_config="cfg") + handler.assert_called_once() + runner.assert_called_once_with(coroutine) + + +class TestStatusSyncHandler: + @pytest.mark.parametrize( + "status_type,method,title,wrapped", + [ + ("config", "list_configuration", "Configuration", False), + ("performance", "list_configuration", "Performance", False), + ("connections", "get_connection_info", "Connections", True), + ("storage", "get_storage_info", "Storage", True), + ("databases", "list_databases", "Databases", False), + ("users", "list_users", "Users", False), + ], + ) + def test_section_dispatch(self, status_type, method, title, wrapped): + backend = MagicMock() + backend._connection = False + sample = [{"name": "x", "value": 1}] + getattr(backend.introspector.status, method).return_value = sample + provider = MagicMock() + args = _args(type=status_type) + status_mod._handle_status_sync(args, backend, provider) + backend.connect.assert_called_once_with() + backend.introspect_and_adapt.assert_called_once_with() + expected = [sample] if wrapped else sample + provider.display_results.assert_called_once_with(expected, title=title) + + def test_all_prints_json(self, capsys): + backend = MagicMock() + backend._connection = False + backend.introspector.status.get_overview.return_value = {"server_version": "16"} + status_mod._handle_status_sync(_args(type="all"), backend, MagicMock()) + assert json.loads(capsys.readouterr().out) == {"server_version": "16"} + + @pytest.mark.parametrize("output", ["csv", "tsv"]) + def test_all_falls_back_to_json_for_tabular_formats(self, output, capsys): + backend = MagicMock() + backend._connection = False + backend.introspector.status.get_overview.return_value = {"k": "v"} + status_mod._handle_status_sync(_args(type="all", output=output), backend, MagicMock()) + assert json.loads(capsys.readouterr().out) == {"k": "v"} + + def test_all_uses_rich_when_available(self): + backend = MagicMock() + backend._connection = False + backend.introspector.status.get_overview.return_value = {"k": "v"} + with patch.object(status_mod, "RICH_AVAILABLE", True), patch.object( + status_mod, "_display_status_rich" + ) as rich: + status_mod._handle_status_sync(_args(type="all", output="table"), backend, MagicMock()) + rich.assert_called_once_with({"k": "v"}, 0) + + def test_all_uses_json_without_rich(self, capsys): + backend = MagicMock() + backend._connection = False + backend.introspector.status.get_overview.return_value = {"k": "v"} + with patch.object(status_mod, "RICH_AVAILABLE", False): + status_mod._handle_status_sync(_args(type="all", output="table"), backend, MagicMock()) + assert json.loads(capsys.readouterr().out) == {"k": "v"} + + def test_disconnect_when_connected(self): + backend = MagicMock() + backend._connection = object() + backend.introspector.status.get_overview.return_value = {} + status_mod._handle_status_sync(_args(type="all"), backend, MagicMock()) + backend.disconnect.assert_called_once_with() + + def test_connection_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.connect.side_effect = ConnectionError("no db") + provider = MagicMock() + with pytest.raises(SystemExit) as exc: + status_mod._handle_status_sync(_args(), backend, provider) + assert exc.value.code == 1 + provider.display_connection_error.assert_called_once() + + def test_query_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.introspect_and_adapt.side_effect = QueryError("bad sql") + provider = MagicMock() + with pytest.raises(SystemExit): + status_mod._handle_status_sync(_args(), backend, provider) + provider.display_query_error.assert_called_once() + + def test_unexpected_error_exits(self, capsys): + backend = MagicMock() + backend._connection = False + backend.connect.side_effect = RuntimeError("boom") + with pytest.raises(SystemExit): + status_mod._handle_status_sync(_args(), backend, MagicMock()) + assert "Error during status introspection" in capsys.readouterr().err + + +class TestStatusAsyncHandler: + @pytest.mark.parametrize( + "status_type,method,title", + [ + ("config", "list_configuration", "Configuration"), + ("connections", "get_connection_info", "Connections"), + ("users", "list_users", "Users"), + ], + ) + async def test_async_section_dispatch(self, status_type, method, title): + backend = AsyncMock() + backend._connection = False + introspector = MagicMock() + setattr(introspector, method, AsyncMock(return_value=[{"a": 1}])) + backend.introspector = MagicMock(status=introspector) + provider = MagicMock() + await status_mod._handle_status_async(_args(type=status_type), backend, provider) + backend.connect.assert_awaited_once_with() + backend.introspect_and_adapt.assert_awaited_once_with() + expected = [[{"a": 1}]] if method == "get_connection_info" else [{"a": 1}] + provider.display_results.assert_called_once_with(expected, title=title) + + async def test_async_all_prints_json(self, capsys): + backend = AsyncMock() + backend._connection = False + backend.introspector = MagicMock( + status=MagicMock(get_overview=AsyncMock(return_value={"v": 16})) + ) + await status_mod._handle_status_async(_args(type="all"), backend, MagicMock()) + assert json.loads(capsys.readouterr().out) == {"v": 16} + + async def test_async_connection_error_exits(self): + backend = AsyncMock() + backend._connection = False + backend.connect.side_effect = ConnectionError("no db") + provider = MagicMock() + with pytest.raises(SystemExit): + await status_mod._handle_status_async(_args(), backend, provider) + provider.display_connection_error.assert_called_once() + + async def test_async_disconnect_when_connected(self): + backend = AsyncMock() + backend._connection = object() + backend.introspector = MagicMock(status=MagicMock(get_overview=AsyncMock(return_value={}))) + await status_mod._handle_status_async(_args(type="all"), backend, MagicMock()) + backend.disconnect.assert_awaited_once_with() + + +# =========================================================================== +# info +# =========================================================================== + + +class TestInfoParser: + def test_defaults(self): + args = _subparser(info_mod.create_parser).parse_args([]) + assert args.output == "table" + assert args.verbose == 0 + assert args.version is None + assert args.rich_ascii is False + + @pytest.mark.parametrize("output", info_mod.INFO_OUTPUT_CHOICES) + def test_output_choices(self, output): + assert _subparser(info_mod.create_parser).parse_args(["-o", output]).output == output + + def test_output_rejects_csv(self): + with pytest.raises(SystemExit): + _subparser(info_mod.create_parser).parse_args(["-o", "csv"]) + + def test_version_and_verbosity(self): + args = _subparser(info_mod.create_parser).parse_args(["--version", "15.4.1", "-vv"]) + assert args.version == "15.4.1" + assert args.verbose == 2 + + +class _Proto: + def supports_alpha(self): + return True + + def supports_beta(self): + return False + + def is_gamma_available(self): + return True + + def supports_explain_format(self, fmt): + return fmt in ("TEXT", "JSON") + + def supports_needs_arg(self, required): + return True + + def helper_not_a_check(self): + return True + + +class _ProtoDialect: + def supports_alpha(self): + return True + + def supports_beta(self): + return 0 + + def is_gamma_available(self): + return 1 + + def supports_explain_format(self, fmt): + return fmt in ("TEXT", "JSON") + + def supports_needs_arg(self, required): + return True + + +class TestInfoHelpers: + @pytest.mark.parametrize( + "text,expected", + [ + ("15.4.1", (15, 4, 1)), + ("13", (13, 0, 0)), + ("15.2", (15, 2, 0)), + ("9.6.1", (9, 6, 1)), + ("16.0.0", (16, 0, 0)), + ], + ) + def test_parse_version(self, text, expected): + assert info_mod.parse_version(text) == expected + + def test_get_protocol_support_methods(self): + assert info_mod.get_protocol_support_methods(_Proto) == [ + "is_gamma_available", + "supports_alpha", + "supports_beta", + "supports_explain_format", + "supports_needs_arg", + ] + + def test_check_protocol_support(self): + result = info_mod.check_protocol_support(_ProtoDialect(), _Proto) + assert result["supports_alpha"] is True + assert result["supports_beta"] is False + assert result["is_gamma_available"] is True + assert result["supports_needs_arg"] is False + explain = result["supports_explain_format"] + assert explain["supported"] == 2 + assert explain["total"] == 6 + assert explain["args"]["TEXT"] is True + assert explain["args"]["DOT"] is False + + def test_check_protocol_support_missing_method(self): + class _Empty: + pass + + result = info_mod.check_protocol_support(object(), _Proto) + assert set(result) == set(info_mod.get_protocol_support_methods(_Proto)) + assert all(value is False for value in result.values()) + + @pytest.mark.parametrize( + "methods,expected", + [ + ({"a": True, "b": False}, (1, 2)), + ({"a": {"supported": 2, "total": 6}}, (2, 6)), + ({"a": True, "b": {"supported": 3, "total": 3}}, (4, 4)), + ], + ) + def test_calculate_protocol_stats(self, methods, expected): + assert info_mod._calculate_protocol_stats(methods) == expected + + def test_build_protocol_info(self): + info = info_mod._build_protocol_info(_ProtoDialect(), "G", [_Proto], 0) + stats = info["_Proto"] + assert set(stats) == {"supported", "total", "percentage"} + assert stats["total"] == 10 + assert stats["percentage"] == 40.0 + + def test_build_protocol_info_verbose_includes_methods(self): + info = info_mod._build_protocol_info(_ProtoDialect(), "G", [_Proto], 2) + assert "methods" in info["_Proto"] + + @pytest.mark.parametrize( + "pct,expected", + [ + (100, ("green", "[OK]")), + (75, ("yellow", "[~]")), + (25, ("red", "[~]")), + (0, ("red", "[X]")), + ], + ) + def test_get_status_style(self, pct, expected): + assert info_mod._get_status_style(pct) == expected + + @pytest.mark.parametrize( + "method,expected", + [("supports_explain_format", "explain format"), ("supports_x", "x")], + ) + def test_format_method_display(self, method, expected): + assert info_mod._format_method_display(method) == expected + + def test_constants(self): + assert info_mod.DIALECT_SPECIFIC_GROUPS == {"PostgreSQL Native", "PostgreSQL Extensions"} + assert info_mod.SUPPORT_METHOD_ALL_ARGS["supports_explain_format"] == [ + "TEXT", + "JSON", + "XML", + "YAML", + "TREE", + "DOT", + ] + + +class TestInfoHandle: + def test_default_version_without_connection(self, capsys): + args = _args(output="json", version=None) + with patch.object(info_mod, "create_provider") as factory, patch.object( + info_mod, "_build_protocol_info", return_value={} + ): + info_mod.handle(args) + factory.assert_called_once_with("json", ascii_borders=False) + payload = json.loads(capsys.readouterr().out) + assert payload["database"] == { + "type": "postgresql", + "version": "13.0.0", + "version_tuple": [13, 0, 0], + "connected": False, + } + assert payload["features"]["extensions"] == {} + + def test_version_override(self, capsys): + args = _args(output="json", version="15.2.3") + with patch.object(info_mod, "create_provider"), patch.object( + info_mod, "_build_protocol_info", return_value={} + ): + info_mod.handle(args) + payload = json.loads(capsys.readouterr().out) + assert payload["database"]["version"] == "15.2.3" + assert payload["database"]["version_tuple"] == [15, 2, 3] + + def test_connected_path_reports_extensions(self, capsys): + dialect = PostgresDialect(version=(15, 2, 3)) + ext = SimpleNamespace(installed=True, available=True, version="1.3", schema="public") + dialect._extensions = {"pgcrypto": ext} + backend = MagicMock() + backend.dialect = dialect + backend.get_server_version.return_value = (15, 2, 3) + args = _args(output="json", database="mydb") + with patch.object(info_mod, "create_provider"), patch.object( + info_mod, "_build_protocol_info", return_value={} + ), patch.object(info_mod, "resolve_connection_config_from_args", return_value="cfg"), patch( + "rhosocial.activerecord.backend.impl.postgres.backend.PostgresBackend", + return_value=backend, + ) as backend_cls: + info_mod.handle(args) + backend_cls.assert_called_once_with(connection_config="cfg") + payload = json.loads(capsys.readouterr().out) + assert payload["database"]["connected"] is True + assert payload["database"]["version"] == "15.2.3" + assert payload["features"]["extensions"]["pgcrypto"] == { + "installed": True, + "available": True, + "version": "1.3", + "schema": "public", + } + backend.disconnect.assert_called_once_with() + + def test_connection_failure_falls_back_to_defaults(self, capsys): + args = _args(output="json", database="mydb", version="14.1.0") + with patch.object(info_mod, "create_provider"), patch.object( + info_mod, "_build_protocol_info", return_value={} + ), patch.object( + info_mod, "resolve_connection_config_from_args", side_effect=RuntimeError("no db") + ): + info_mod.handle(args) + payload = json.loads(capsys.readouterr().out) + assert payload["database"]["connected"] is False + assert payload["database"]["version"] == "14.1.0" + + +# =========================================================================== +# introspect +# =========================================================================== + + +class TestIntrospectParser: + def test_defaults(self): + args = _subparser(introspect_mod.create_parser).parse_args(["tables"]) + assert args.type == "tables" + assert args.output == "table" + assert args.name is None + assert args.include_system is False + + @pytest.mark.parametrize("kind", introspect_mod.INTROSPECT_TYPES) + def test_all_types_accepted(self, kind): + assert _subparser(introspect_mod.create_parser).parse_args([kind]).type == kind + + def test_invalid_type_rejected(self): + with pytest.raises(SystemExit): + _subparser(introspect_mod.create_parser).parse_args(["bogus"]) + + def test_name_and_flags(self): + args = _subparser(introspect_mod.create_parser).parse_args( + ["value-samples", "orders", "--column", "email", "--include-system", "--async"] + ) + assert args.name == "orders" + assert args.column == "email" + assert args.include_system is True + assert args.is_async is True + + def test_join_coverage_flags(self): + args = _subparser(introspect_mod.create_parser).parse_args( + ["join-coverage", "a", "--column", "x", "--right-table", "b", "--right-column", "y"] + ) + assert (args.right_table, args.right_column) == ("b", "y") + + +class TestValidateName: + @pytest.mark.parametrize( + "kind", [k for k, v in introspect_mod._NAME_RULE.items() if v == "required"] + ) + def test_required_missing_exits(self, kind): + with pytest.raises(SystemExit) as exc: + introspect_mod._validate_name(_args(type=kind, name=None)) + assert exc.value.code == 1 + + @pytest.mark.parametrize( + "kind", [k for k, v in introspect_mod._NAME_RULE.items() if v == "forbidden"] + ) + def test_forbidden_with_name_exits(self, kind): + with pytest.raises(SystemExit) as exc: + introspect_mod._validate_name(_args(type=kind, name="obj")) + assert exc.value.code == 2 + + @pytest.mark.parametrize("kind,rule", sorted(introspect_mod._NAME_RULE.items())) + def test_valid_invocation_accepted(self, kind, rule): + name = None if rule == "forbidden" else "obj" + introspect_mod._validate_name(_args(type=kind, name=name)) + + +class TestRequireCapability: + @pytest.mark.parametrize("kind,switch", sorted(introspect_mod._TYPE_CAPABILITIES.items())) + def test_unsupported_switch_exits(self, kind, switch): + backend = MagicMock() + dialect = MagicMock() + setattr(dialect, switch, MagicMock(return_value=False)) + backend.dialect = dialect + with pytest.raises(SystemExit) as exc: + introspect_mod._require_capability(backend, _args(type=kind)) + assert exc.value.code == 2 + + @pytest.mark.parametrize("kind,switch", sorted(introspect_mod._TYPE_CAPABILITIES.items())) + def test_supported_switch_passes(self, kind, switch): + backend = MagicMock() + dialect = MagicMock() + setattr(dialect, switch, MagicMock(return_value=True)) + backend.dialect = dialect + introspect_mod._require_capability(backend, _args(type=kind)) + + def test_missing_switch_passes(self): + backend = MagicMock() + backend.dialect = object() + introspect_mod._require_capability(backend, _args(type="tables")) + + def test_missing_dialect_passes(self): + backend = MagicMock() + backend.dialect = None + introspect_mod._require_capability(backend, _args(type="tables")) + + +class TestRefuseUnusedArguments: + @pytest.mark.parametrize("kind", ["tables", "columns", "database", "table-stats"]) + def test_column_on_wrong_type_exits(self, kind): + with pytest.raises(SystemExit) as exc: + introspect_mod._refuse_unused_arguments(_args(type=kind, column="c")) + assert exc.value.code == 2 + + @pytest.mark.parametrize("kind", ["value-samples", "join-coverage"]) + def test_column_on_probe_type_accepted(self, kind): + introspect_mod._refuse_unused_arguments(_args(type=kind, column="c")) + + @pytest.mark.parametrize("kind", ["tables", "columns", "value-samples"]) + def test_right_flags_on_wrong_type_exits(self, kind): + with pytest.raises(SystemExit) as exc: + introspect_mod._refuse_unused_arguments(_args(type=kind, right_table="b")) + assert exc.value.code == 2 + + def test_right_flags_on_join_coverage_accepted(self): + introspect_mod._refuse_unused_arguments( + _args(type="join-coverage", right_table="b", right_column="y") + ) + + +class TestExtensionRows: + def test_extension_rows(self): + rows = introspect_mod._extension_rows( + [ + ExtensionInfo( + name="pgcrypto", version="1.3", schema="public", description="crypto" + ), + ExtensionInfo(name="hstore"), + ] + ) + assert rows == [ + {"name": "pgcrypto", "version": "1.3", "schema": "public", "description": "crypto"}, + {"name": "hstore", "version": None, "schema": None, "description": None}, + ] + + +class TestIntrospectHandleDispatch: + def test_missing_database_exits(self, capsys): + with pytest.raises(SystemExit) as exc: + introspect_mod.handle(_args(type="tables", database=None)) + assert exc.value.code == 1 + assert "database is required" in capsys.readouterr().err + + def test_sync_dispatch(self): + args = _args(type="tables") + with patch.object(introspect_mod, "create_provider") as factory, patch.object( + introspect_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object(introspect_mod, "PostgresBackend") as backend_cls, patch.object( + introspect_mod, "_handle_introspect_sync" + ) as handler: + introspect_mod.handle(args) + factory.assert_called_once_with("json", ascii_borders=False) + backend_cls.assert_called_once_with(connection_config="cfg") + handler.assert_called_once_with(args, backend_cls.return_value, factory.return_value) + + def test_async_dispatch(self): + args = _args(type="tables", is_async=True) + coroutine = object() + with patch.object(introspect_mod, "create_provider"), patch.object( + introspect_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object(introspect_mod, "AsyncPostgresBackend") as backend_cls, patch.object( + introspect_mod, "_handle_introspect_async", new=MagicMock(return_value=coroutine) + ) as handler, patch.object( + introspect_mod, "run_coroutine" + ) as runner: + introspect_mod.handle(args) + backend_cls.assert_called_once_with(connection_config="cfg") + handler.assert_called_once() + runner.assert_called_once_with(coroutine) + + +_SYNC_CASES = [ + ("tables", None, "list_tables", dict(schema=None, include_system=False), "Tables", False), + ("views", None, "list_views", dict(schema=None), "Views", False), + ("columns", "users", "list_columns", dict(schema=None), "Columns of users", False), + ("indexes", "users", "list_indexes", dict(schema=None), "Indexes of users", False), + ( + "foreign-keys", + "users", + "list_foreign_keys", + dict(schema=None), + "Foreign Keys of users", + False, + ), + ("triggers", None, "list_triggers", dict(table_name=None, schema=None), "Triggers", False), + ("database", None, "get_database_info", {}, "Database Info", True), + ( + "materialized-views", + None, + "list_materialized_views", + dict(schema=None, include_system=False), + "Materialized Views", + False, + ), + ("sequences", None, "list_sequences", dict(schema=None), "Sequences", False), + ("partitions", "orders", "list_partitions", dict(schema=None), "Partitions of orders", False), + ("routines", None, "list_routines", dict(schema=None, routine_name=None), "Routines", False), + ("types", None, "list_types", dict(schema=None, type_name=None), "Types", False), + ( + "operators", + None, + "list_operators", + dict(schema=None, operator_name=None), + "Operators", + False, + ), + ( + "operator-classes", + None, + "list_operator_classes", + dict(schema=None, operator_class_name=None), + "Operator Classes", + False, + ), + ( + "operator-families", + None, + "list_operator_families", + dict(schema=None, operator_family_name=None), + "Operator Families", + False, + ), + ("unused-indexes", None, "list_unused_indexes", dict(schema=None), "Unused Indexes", False), + ("table-stats", None, "list_table_usage_stats", dict(schema=None), "Table Usage Stats", False), + ("runtime", None, "list_runtime_metrics", dict(schema=None), "Runtime Metrics", False), + ("index-stats", None, "list_index_usage_stats", dict(schema=None), "Index Usage Stats", False), + ( + "dependencies", + None, + "list_object_dependencies", + dict(object_name=None, schema=None), + "Object Dependencies", + False, + ), + ( + "column-profiles", + "orders", + "list_column_data_profiles", + dict(schema=None), + "Column profiles of orders", + False, + ), +] + + +class TestIntrospectSyncHandler: + @pytest.mark.parametrize("kind,name,method,kwargs,title,wrapped", _SYNC_CASES) + def test_family_dispatch(self, kind, name, method, kwargs, title, wrapped): + backend = MagicMock() + backend._connection = False + sample = [{"k": "v"}] + getattr(backend.introspector, method).return_value = sample + provider = MagicMock() + introspect_mod._handle_introspect_sync(_args(type=kind, name=name), backend, provider) + backend.connect.assert_called_once_with() + backend.introspect_and_adapt.assert_called_once_with() + if name and method in ( + "list_columns", + "list_indexes", + "list_foreign_keys", + "list_partitions", + "list_column_data_profiles", + ): + getattr(backend.introspector, method).assert_called_once_with(name, **kwargs) + else: + getattr(backend.introspector, method).assert_called_once_with(**kwargs) + expected = [sample] if wrapped else sample + provider.display_results.assert_called_once_with(expected, title=title) + + def test_extensions_family(self): + backend = MagicMock() + backend._connection = False + backend.introspector.list_extensions.return_value = [ + ExtensionInfo(name="pgcrypto", version="1.3", schema="public", description=None) + ] + provider = MagicMock() + introspect_mod._handle_introspect_sync(_args(type="extensions"), backend, provider) + provider.display_results.assert_called_once_with( + [{"name": "pgcrypto", "version": "1.3", "schema": "public", "description": None}], + title="Extensions", + ) + + def test_value_samples(self): + backend = MagicMock() + backend._connection = False + backend.introspector.sample_column_values.return_value = [{"value": 1}] + provider = MagicMock() + introspect_mod._handle_introspect_sync( + _args(type="value-samples", name="orders", column="email"), backend, provider + ) + backend.introspector.sample_column_values.assert_called_once_with( + "orders", "email", schema=None + ) + provider.display_results.assert_called_once_with( + [{"value": 1}], title="Values of orders.email" + ) + + def test_join_coverage(self): + backend = MagicMock() + backend._connection = False + backend.introspector.estimate_join_coverage.return_value = {"overlap": 0.5} + provider = MagicMock() + introspect_mod._handle_introspect_sync( + _args( + type="join-coverage", + name="orders", + column="buyer", + right_table="users", + right_column="id", + ), + backend, + provider, + ) + backend.introspector.estimate_join_coverage.assert_called_once_with( + "orders", "buyer", "users", "id", schema=None + ) + provider.display_results.assert_called_once_with([{"overlap": 0.5}], title="Join Coverage") + + @pytest.mark.parametrize( + "kind,name,method", + [ + ("views", "missing", "get_view_info"), + ("extensions", "missing", "get_extension_info"), + ("materialized-views", "missing", "get_materialized_view_info"), + ("sequences", "missing", "get_sequence_info"), + ], + ) + def test_named_object_not_found_exits(self, kind, name, method): + backend = MagicMock() + backend._connection = False + getattr(backend.introspector, method).return_value = None + with pytest.raises(SystemExit) as exc: + introspect_mod._handle_introspect_sync( + _args(type=kind, name=name), backend, MagicMock() + ) + assert exc.value.code == 1 + + def test_value_samples_requires_column(self): + backend = MagicMock() + backend._connection = False + with pytest.raises(SystemExit) as exc: + introspect_mod._handle_introspect_sync( + _args(type="value-samples", name="orders", column=None), backend, MagicMock() + ) + assert exc.value.code == 1 + + def test_join_coverage_requires_right_flags(self): + backend = MagicMock() + backend._connection = False + with pytest.raises(SystemExit): + introspect_mod._handle_introspect_sync( + _args(type="join-coverage", name="orders", column="buyer"), backend, MagicMock() + ) + + def test_connection_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.connect.side_effect = ConnectionError("down") + provider = MagicMock() + with pytest.raises(SystemExit): + introspect_mod._handle_introspect_sync(_args(type="tables"), backend, provider) + provider.display_connection_error.assert_called_once() + + +class TestIntrospectAsyncHandler: + @pytest.mark.parametrize("kind,name,method,kwargs,title,wrapped", _SYNC_CASES[:6]) + async def test_async_family_dispatch(self, kind, name, method, kwargs, title, wrapped): + backend = AsyncMock() + backend._connection = False + introspector = MagicMock() + setattr(introspector, method, AsyncMock(return_value=[{"k": "v"}])) + backend.introspector = introspector + backend.dialect = None + provider = MagicMock() + await introspect_mod._handle_introspect_async( + _args(type=kind, name=name), backend, provider + ) + backend.connect.assert_awaited_once_with() + backend.introspect_and_adapt.assert_awaited_once_with() + expected = [[{"k": "v"}]] if wrapped else [{"k": "v"}] + provider.display_results.assert_called_once_with(expected, title=title) + + async def test_async_value_samples(self): + backend = AsyncMock() + backend._connection = False + backend.introspector = MagicMock( + sample_column_values=AsyncMock(return_value=[{"value": 2}]) + ) + backend.dialect = None + provider = MagicMock() + await introspect_mod._handle_introspect_async( + _args(type="value-samples", name="t", column="c"), backend, provider + ) + provider.display_results.assert_called_once_with([{"value": 2}], title="Values of t.c") + + async def test_async_unsupported_capability_exits(self): + backend = AsyncMock() + backend._connection = False + dialect = MagicMock() + dialect.supports_table_introspection = MagicMock(return_value=False) + backend.dialect = dialect + with pytest.raises(SystemExit) as exc: + await introspect_mod._handle_introspect_async( + _args(type="tables"), backend, MagicMock() + ) + assert exc.value.code == 2 + + +# =========================================================================== +# query +# =========================================================================== + + +class TestQueryParser: + def test_defaults(self): + args = _subparser(query_mod.create_parser).parse_args([]) + assert args.output == "table" + assert args.sql is None + assert args.file is None + assert args.log_level == "INFO" + assert args.rich_ascii is False + + @pytest.mark.parametrize("output", ["table", "json", "csv", "tsv"]) + def test_output_choices(self, output): + assert _subparser(query_mod.create_parser).parse_args(["-o", output]).output == output + + def test_sql_and_file(self): + parser = _subparser(query_mod.create_parser) + assert parser.parse_args(["SELECT 1"]).sql == "SELECT 1" + assert parser.parse_args(["-f", "q.sql"]).file == "q.sql" + + +class TestQueryHandleValidation: + def test_invalid_log_level_raises(self): + with pytest.raises(ValueError, match="Invalid log level"): + query_mod.handle(_args(sql="SELECT 1", log_level="NOPE")) + + def test_missing_sql_exits(self, capsys): + fake_stdin = MagicMock() + fake_stdin.isatty.return_value = True + with patch.object(query_mod.sys, "stdin", fake_stdin): + with pytest.raises(SystemExit) as exc: + query_mod.handle(_args(sql=None, file=None)) + assert exc.value.code == 1 + assert "No SQL query provided" in capsys.readouterr().err + + def test_multiple_statements_exit(self): + with pytest.raises(SystemExit) as exc: + query_mod.handle(_args(sql="SELECT 1; SELECT 2;")) + assert exc.value.code == 1 + + def test_single_trailing_semicolon_allowed(self): + with patch.object(query_mod, "create_provider"), patch.object( + query_mod.logging, "basicConfig" + ), patch.object( + query_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object( + query_mod, "PostgresBackend" + ), patch.object( + query_mod, "_execute_query_sync" + ) as executor: + query_mod.handle(_args(sql="SELECT 1;")) + executor.assert_called_once() + + def test_file_not_found_exits(self): + with pytest.raises(SystemExit) as exc: + query_mod.handle(_args(sql=None, file="no/such/query.sql")) + assert exc.value.code == 1 + + def test_file_source(self, tmp_path): + path = tmp_path / "q.sql" + path.write_text("SELECT 42", encoding="utf-8") + with patch.object(query_mod, "create_provider"), patch.object( + query_mod.logging, "basicConfig" + ), patch.object( + query_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object( + query_mod, "PostgresBackend" + ), patch.object( + query_mod, "_execute_query_sync" + ) as executor: + query_mod.handle(_args(sql=None, file=str(path))) + assert executor.call_args.args[0] == "SELECT 42" + + def test_stdin_source(self): + fake_stdin = MagicMock() + fake_stdin.isatty.return_value = False + fake_stdin.read.return_value = "SELECT 7" + with patch.object(query_mod.sys, "stdin", fake_stdin), patch.object( + query_mod, "create_provider" + ), patch.object(query_mod.logging, "basicConfig"), patch.object( + query_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object( + query_mod, "PostgresBackend" + ), patch.object( + query_mod, "_execute_query_sync" + ) as executor: + query_mod.handle(_args(sql=None, file=None)) + assert executor.call_args.args[0] == "SELECT 7" + + +class TestQueryHandleDispatch: + def test_sync_dispatch(self): + args = _args(sql="SELECT 1", log_level="DEBUG", rich_ascii=True) + with patch.object(query_mod, "create_provider") as factory, patch.object( + query_mod.logging, "basicConfig" + ) as logging_mod, patch.object( + query_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object( + query_mod, "PostgresBackend" + ) as backend_cls, patch.object( + query_mod, "_execute_query_sync" + ) as executor: + query_mod.handle(args) + factory.assert_called_once_with("json", ascii_borders=True) + logging_mod.assert_called_once() + factory.return_value.display_greeting.assert_called_once_with() + backend_cls.assert_called_once_with(connection_config="cfg") + executor.assert_called_once_with( + "SELECT 1", backend_cls.return_value, factory.return_value, use_ascii=True + ) + + def test_async_dispatch(self): + args = _args(sql="SELECT 1", is_async=True) + coroutine = object() + with patch.object(query_mod, "create_provider"), patch.object( + query_mod.logging, "basicConfig" + ), patch.object( + query_mod, "resolve_connection_config_from_args", return_value="cfg" + ), patch.object( + query_mod, "AsyncPostgresBackend" + ) as backend_cls, patch.object( + query_mod, "_execute_query_async", new=MagicMock(return_value=coroutine) + ) as executor, patch.object( + query_mod, "run_coroutine" + ) as runner: + query_mod.handle(args) + backend_cls.assert_called_once_with(connection_config="cfg") + executor.assert_called_once() + runner.assert_called_once_with(coroutine) + + +class TestQueryExecuteSync: + def test_result_with_data(self): + backend = MagicMock() + backend._connection = True + backend.execute.return_value = SimpleNamespace( + affected_rows=2, duration=0.5, data=[{"a": 1}] + ) + provider = MagicMock() + query_mod._execute_query_sync("SELECT 1", backend, provider, use_ascii=False) + provider.display_query.assert_called_once_with("SELECT 1", is_async=False) + provider.display_success.assert_called_once_with(2, 0.5) + provider.display_results.assert_called_once_with([{"a": 1}], use_ascii=False) + backend.disconnect.assert_called_once_with() + provider.display_disconnect.assert_called_once_with(is_async=False) + + def test_result_without_data(self): + backend = MagicMock() + backend._connection = False + backend.execute.return_value = SimpleNamespace(affected_rows=0, duration=0.1, data=[]) + provider = MagicMock() + query_mod._execute_query_sync("UPDATE t", backend, provider) + provider.display_no_data.assert_called_once_with() + provider.display_results.assert_not_called() + + def test_no_result_object(self): + backend = MagicMock() + backend._connection = False + backend.execute.return_value = None + provider = MagicMock() + query_mod._execute_query_sync("SET x", backend, provider) + provider.display_no_result_object.assert_called_once_with() + + def test_connection_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.connect.side_effect = ConnectionError("down") + provider = MagicMock() + with pytest.raises(SystemExit): + query_mod._execute_query_sync("SELECT 1", backend, provider) + provider.display_connection_error.assert_called_once() + + def test_query_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.execute.side_effect = QueryError("bad") + provider = MagicMock() + with pytest.raises(SystemExit): + query_mod._execute_query_sync("SELECT 1", backend, provider) + provider.display_query_error.assert_called_once() + + def test_unexpected_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.execute.side_effect = RuntimeError("boom") + provider = MagicMock() + with pytest.raises(SystemExit): + query_mod._execute_query_sync("SELECT 1", backend, provider) + provider.display_unexpected_error.assert_called_once() + + +class TestQueryExecuteAsync: + async def test_result_with_data(self): + backend = AsyncMock() + backend._connection = True + backend.execute.return_value = SimpleNamespace( + affected_rows=1, duration=0.2, data=[{"b": 2}] + ) + provider = MagicMock() + await query_mod._execute_query_async("SELECT 1", backend, provider, use_ascii=True) + backend.connect.assert_awaited_once_with() + provider.display_query.assert_called_once_with("SELECT 1", is_async=True) + provider.display_results.assert_called_once_with([{"b": 2}], use_ascii=True) + backend.disconnect.assert_awaited_once_with() + provider.display_disconnect.assert_called_once_with(is_async=True) + + async def test_no_result_object(self): + backend = AsyncMock() + backend._connection = False + backend.execute.return_value = None + provider = MagicMock() + await query_mod._execute_query_async("SELECT 1", backend, provider) + provider.display_no_result_object.assert_called_once_with() + + async def test_connection_error_exits(self): + backend = AsyncMock() + backend._connection = False + backend.connect.side_effect = ConnectionError("down") + provider = MagicMock() + with pytest.raises(SystemExit): + await query_mod._execute_query_async("SELECT 1", backend, provider) + provider.display_connection_error.assert_called_once() + + async def test_unexpected_error_exits(self): + backend = AsyncMock() + backend._connection = False + backend.execute.side_effect = RuntimeError("boom") + provider = MagicMock() + with pytest.raises(SystemExit): + await query_mod._execute_query_async("SELECT 1", backend, provider) + provider.display_unexpected_error.assert_called_once_with( + backend.execute.side_effect, is_async=True + ) + + +# =========================================================================== +# rich rendering (fake rich modules -- no optional dependency required) +# =========================================================================== + + +class _FakeTable: + def __init__(self, *args, **kwargs): + self.columns = [] + self.rows = [] + + def add_column(self, *args, **kwargs): + self.columns.append(args) + + def add_row(self, *args, **kwargs): + self.rows.append(args) + + +class _FakeConsole: + printed = [] + + def __init__(self, *args, **kwargs): + pass + + def print(self, *args, **kwargs): + for item in args: + if isinstance(item, _FakeTable): + for names in item.columns: + _FakeConsole.printed.extend(str(name) for name in names) + for row in item.rows: + _FakeConsole.printed.extend(str(value) for value in row) + else: + _FakeConsole.printed.append(str(item)) + + +@pytest.fixture +def fake_rich(): + console_mod = types.ModuleType("rich.console") + console_mod.Console = _FakeConsole + table_mod = types.ModuleType("rich.table") + table_mod.Table = _FakeTable + rich_mod = types.ModuleType("rich") + rich_mod.console = console_mod + rich_mod.table = table_mod + with patch.dict( + sys.modules, {"rich": rich_mod, "rich.console": console_mod, "rich.table": table_mod} + ): + _FakeConsole.printed = [] + yield _FakeConsole + + +def _full_overview(): + overview = ServerOverview(server_version="16.2", server_vendor="PostgreSQL") + overview.session = SessionInfo( + user="bob", + database="db", + schema="public", + host="h", + ssl_enabled=True, + ssl_version="TLS1.3", + ssl_cipher="AES", + password_used=True, + ) + overview.connections = ConnectionInfo(active_count=5, max_connections=100) + overview.storage = StorageInfo(total_size_bytes=1024**3) + overview.configuration = [ + StatusItem( + "shared_buffers", + "128MB", + StatusCategory.CONFIGURATION, + description="buffer cache", + is_readonly=True, + ), + StatusItem("work_mem", "4MB", StatusCategory.PERFORMANCE, unit="MB"), + ] + overview.databases = [ + DatabaseBriefInfo( + name="db", + size_bytes=2048, + table_count=3, + view_count=1, + extra={"schemas": {"public": {"tables": 2, "views": 1}}}, + ) + ] + overview.users = [UserInfo(name="bob", is_superuser=True)] + overview.wal = SimpleNamespace( + wal_level="replica", + wal_files=2, + wal_size_bytes=4096, + checkpoint_count=7, + checkpoint_time="now", + wal_segments=3, + ) + overview.replication = SimpleNamespace( + is_primary=True, + replication_slots=1, + active_replications=2, + streaming=True, + lag_bytes=512, + ) + overview.archive = SimpleNamespace( + archive_mode="on", + archive_command="x" * 60, + archive_timeout=30, + archived_count=4, + failed_count=0, + ) + overview.security = SimpleNamespace( + ssl_enabled=True, + ssl_cert_file="c", + ssl_key_file="k", + ssl_ca_file="ca", + password_encryption="scram", + row_security=False, + ) + overview.extensions = [SimpleNamespace(name="pgcrypto", version="1.3", schema="public")] + return overview + + +class TestStatusRichDisplay: + def test_all_sections_render(self, fake_rich): + status_mod._display_status_rich(_full_overview(), verbose=1) + out = " ".join(fake_rich.printed) + for label in ( + "Server Status", + "Session", + "Configuration", + "Performance", + "Storage", + "Databases", + "Schemas in db", + "Users", + "WAL", + "Replication", + "Archive", + "Security", + "Extensions", + ): + assert label in out + assert "1.0 GB" in out + assert "..." in out # the long archive command is truncated + + def test_non_verbose_paths(self, fake_rich): + status_mod._display_status_rich(_full_overview(), verbose=0) + out = " ".join(fake_rich.printed) + assert "buffer cache" not in out + assert "16.2" in out + + def test_optional_sections_absent(self, fake_rich): + overview = ServerOverview(server_version="16", server_vendor="PostgreSQL") + status_mod._display_status_rich(overview, verbose=2) + out = " ".join(fake_rich.printed) + assert "Server Status" in out + assert "Session" not in out + assert "WAL" not in out + + +class TestInfoRichDisplay: + def _legacy_info(self): + return { + "postgresql": {"version": "16.0"}, + "extensions": { + "pgcrypto": SimpleNamespace( + installed=True, available=True, version="1.3", schema="public" + ), + "hstore": SimpleNamespace( + installed=False, available=True, version="1.4", schema=None + ), + }, + "protocols": { + "Query Features": { + "ProtoA": { + "percentage": 100.0, + "supported": 1, + "total": 1, + "methods": { + "supports_x": True, + "supports_explain_format": {"args": {"TEXT": True, "YAML": False}}, + }, + } + }, + "PostgreSQL Native": {"ProtoB": {"percentage": 0.0, "supported": 0, "total": 2}}, + }, + } + + def test_connected_detailed_render(self, fake_rich): + extensions = self._legacy_info()["extensions"] + info_mod._display_info_rich(self._legacy_info(), 2, "16.0", extensions, is_connected=True) + out = " ".join(fake_rich.printed) + for label in ( + "Environment Information", + "actual connection", + "Extension Support", + "Installed", + "Available (not installed)", + "Protocol Support", + "Detailed", + "dialect-specific", + "ProtoA", + "ProtoB", + "explain format", + ): + assert label in out + + def test_disconnected_family_overview(self, fake_rich): + info_mod._display_info_rich(self._legacy_info(), 0, "13.0.0", None, is_connected=False) + out = " ".join(fake_rich.printed) + assert "default value" in out + assert "Family Overview" in out + + +# =========================================================================== +# introspect: remaining per-object and error branches +# =========================================================================== + + +class TestIntrospectExtraBranches: + @pytest.mark.parametrize( + "kind,name,method,title", + [ + ("views", "v", "get_view_info", "View v"), + ("materialized-views", "mv", "get_materialized_view_info", "Materialized View mv"), + ("sequences", "s", "get_sequence_info", "Sequence s"), + ], + ) + def test_named_object_found(self, kind, name, method, title): + backend = MagicMock() + backend._connection = False + getattr(backend.introspector, method).return_value = {"name": name} + provider = MagicMock() + introspect_mod._handle_introspect_sync(_args(type=kind, name=name), backend, provider) + provider.display_results.assert_called_once_with([{"name": name}], title=title) + + def test_named_extension_found(self): + backend = MagicMock() + backend._connection = False + backend.introspector.get_extension_info.return_value = ExtensionInfo( + name="pgcrypto", version="1.3", schema="public", description="crypto" + ) + provider = MagicMock() + introspect_mod._handle_introspect_sync( + _args(type="extensions", name="pgcrypto"), backend, provider + ) + provider.display_results.assert_called_once_with( + [{"name": "pgcrypto", "version": "1.3", "schema": "public", "description": "crypto"}], + title="Extension pgcrypto", + ) + + def test_table_storage_found(self): + backend = MagicMock() + backend._connection = False + backend.introspector.list_tables.return_value = [ + DatabaseBriefInfo(name="other"), + DatabaseBriefInfo(name="orders", size_bytes=128), + ] + provider = MagicMock() + introspect_mod._handle_introspect_sync( + _args(type="table-storage", name="orders"), backend, provider + ) + provider.display_results.assert_called_once() + assert provider.display_results.call_args.kwargs["title"] == "Table storage orders" + + def test_table_storage_not_found_exits(self): + backend = MagicMock() + backend._connection = False + backend.introspector.list_tables.return_value = [DatabaseBriefInfo(name="other")] + with pytest.raises(SystemExit) as exc: + introspect_mod._handle_introspect_sync( + _args(type="table-storage", name="orders"), backend, MagicMock() + ) + assert exc.value.code == 1 + + def test_dependencies_with_name(self): + backend = MagicMock() + backend._connection = False + backend.introspector.list_object_dependencies.return_value = [{"edge": 1}] + provider = MagicMock() + introspect_mod._handle_introspect_sync( + _args(type="dependencies", name="orders"), backend, provider + ) + provider.display_results.assert_called_once_with( + [{"edge": 1}], title="Dependencies of orders" + ) + + def test_join_coverage_without_measurement_exits(self): + backend = MagicMock() + backend._connection = False + backend.introspector.estimate_join_coverage.return_value = None + args = _args(type="join-coverage", name="a", column="x", right_table="b", right_column="y") + with pytest.raises(SystemExit) as exc: + introspect_mod._handle_introspect_sync(args, backend, MagicMock()) + assert exc.value.code == 1 + + def test_query_error_exits(self): + backend = MagicMock() + backend._connection = False + backend.introspector.list_tables.side_effect = QueryError("bad") + provider = MagicMock() + with pytest.raises(SystemExit): + introspect_mod._handle_introspect_sync(_args(type="tables"), backend, provider) + provider.display_query_error.assert_called_once() + + def test_unexpected_error_exits(self, capsys): + backend = MagicMock() + backend._connection = False + backend.introspector.list_tables.side_effect = RuntimeError("boom") + with pytest.raises(SystemExit): + introspect_mod._handle_introspect_sync(_args(type="tables"), backend, MagicMock()) + assert "Error during introspection" in capsys.readouterr().err + + async def test_named_object_found_async(self): + backend = AsyncMock() + backend._connection = False + backend.dialect = None + backend.introspector = MagicMock(get_view_info=AsyncMock(return_value={"name": "v"})) + provider = MagicMock() + await introspect_mod._handle_introspect_async( + _args(type="views", name="v"), backend, provider + ) + provider.display_results.assert_called_once_with([{"name": "v"}], title="View v") + + async def test_table_storage_async(self): + backend = AsyncMock() + backend._connection = False + backend.dialect = None + backend.introspector = MagicMock( + list_tables=AsyncMock(return_value=[DatabaseBriefInfo(name="orders", size_bytes=8)]) + ) + provider = MagicMock() + await introspect_mod._handle_introspect_async( + _args(type="table-storage", name="orders"), backend, provider + ) + assert provider.display_results.call_args.kwargs["title"] == "Table storage orders" + + async def test_join_coverage_without_measurement_async(self): + backend = AsyncMock() + backend._connection = False + backend.dialect = None + backend.introspector = MagicMock(estimate_join_coverage=AsyncMock(return_value=None)) + args = _args(type="join-coverage", name="a", column="x", right_table="b", right_column="y") + with pytest.raises(SystemExit): + await introspect_mod._handle_introspect_async(args, backend, MagicMock()) + + async def test_query_error_async(self): + backend = AsyncMock() + backend._connection = False + backend.dialect = None + backend.introspector = MagicMock(list_tables=AsyncMock(side_effect=QueryError("bad"))) + provider = MagicMock() + with pytest.raises(SystemExit): + await introspect_mod._handle_introspect_async(_args(type="tables"), backend, provider) + provider.display_query_error.assert_called_once() diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py new file mode 100644 index 00000000..96d25d8f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py @@ -0,0 +1,623 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py +"""Offline unit tests for the PostgreSQL user-defined TYPE DDL mixin. + +A connectionless :class:`PostgresDialect` is constructed directly and its +``format_*`` / ``supports_*`` methods are exercised against representative +definitions and alter actions. No connection, driver or server is involved. +""" + +from unittest.mock import MagicMock, patch + +import pytest + +from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError +from rhosocial.activerecord.backend.expression.objects import Type +from rhosocial.activerecord.backend.expression.statements.ddl_type import ( + AlterTypeStatement, + CreateTypeStatement, +) +from rhosocial.activerecord.backend.expression.types import DataType +from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect +from rhosocial.activerecord.backend.impl.postgres.expression.ddl.type import ( + PostgresAddEnumValueAction, + PostgresAddTypeAttributeAction, + PostgresAlterTypeAttributeAction, + PostgresBaseTypeDefinition, + PostgresChangeTypeOwnerAction, + PostgresCompositeTypeAttribute, + PostgresCompositeTypeDefinition, + PostgresDropTypeAttributeAction, + PostgresDropTypeExpression, + PostgresEnumTypeDefinition, + PostgresRangeTypeDefinition, + PostgresRenameEnumValueAction, + PostgresRenameTypeAction, + PostgresRenameTypeAttributeAction, + PostgresSetTypePropertiesAction, + PostgresSetTypeSchemaAction, + PostgresShellTypeDefinition, +) + +PG96 = (9, 6, 0) +PG10 = (10, 0, 0) +PG13 = (13, 0, 0) +PG14 = (14, 0, 0) +PG16 = (16, 0, 0) + + +def _dialect(version=PG16): + return PostgresDialect(version=version) + + +def _type(name, schema=None): + return Type(_dialect(), name, schema_name=schema) + + +def _data_type(text, dialect=None): + return DataType.as_type(dialect or _dialect(), text) + + +# =========================================================================== +# capability switches +# =========================================================================== + + +class TestCapabilities: + @pytest.mark.parametrize("version,supported", [((9, 5, 0), False), (PG96, True), (PG16, True)]) + def test_type_objects_versions(self, version, supported): + assert _dialect(version).supports_type_objects() is supported + + @pytest.mark.parametrize( + "method", + [ + "supports_type_objects", + "supports_create_type", + "supports_alter_type", + "supports_drop_type", + "supports_drop_type_if_exists", + "supports_multiple_type_alter_actions", + "supports_drop_type_cascade", + "supports_drop_type_restrict", + "supports_type_if_exists", + "supports_type_cascade", + ], + ) + def test_supported_on_modern_server(self, method): + assert getattr(_dialect(PG16), method)() is True + + @pytest.mark.parametrize( + "method", + [ + "supports_create_type_if_not_exists", + "supports_create_type_or_replace", + "supports_alter_type_if_exists", + "supports_type_if_not_exists", + ], + ) + def test_never_supported(self, method): + assert getattr(_dialect(PG16), method)() is False + + @pytest.mark.parametrize( + "method", + [ + "supports_type_objects", + "supports_create_type", + "supports_alter_type", + "supports_drop_type", + "supports_drop_type_if_exists", + "supports_multiple_type_alter_actions", + "supports_drop_type_cascade", + "supports_drop_type_restrict", + ], + ) + def test_not_supported_before_96(self, method): + assert getattr(_dialect((9, 5, 0)), method)() is False + + def test_supported_type_definitions(self): + assert _dialect(PG16).supported_type_definitions() == ( + PostgresCompositeTypeDefinition, + PostgresEnumTypeDefinition, + PostgresRangeTypeDefinition, + PostgresBaseTypeDefinition, + PostgresShellTypeDefinition, + ) + assert _dialect((9, 5, 0)).supported_type_definitions() == () + + @pytest.mark.parametrize( + "definition", + [ + PostgresCompositeTypeDefinition, + PostgresEnumTypeDefinition, + PostgresRangeTypeDefinition, + PostgresBaseTypeDefinition, + PostgresShellTypeDefinition, + ], + ) + def test_supports_type_definition(self, definition): + assert _dialect(PG16).supports_type_definition(definition) is True + assert _dialect((9, 5, 0)).supports_type_definition(definition) is False + + @pytest.mark.parametrize("bogus", [str, int, object]) + def test_rejects_unknown_definition(self, bogus): + assert _dialect(PG16).supports_type_definition(bogus) is False + + @pytest.mark.parametrize( + "action", + [ + PostgresRenameTypeAction, + PostgresSetTypeSchemaAction, + PostgresChangeTypeOwnerAction, + PostgresRenameTypeAttributeAction, + PostgresAddTypeAttributeAction, + PostgresDropTypeAttributeAction, + PostgresAlterTypeAttributeAction, + PostgresAddEnumValueAction, + PostgresRenameEnumValueAction, + PostgresSetTypePropertiesAction, + ], + ) + def test_supports_all_actions_on_modern_server(self, action): + assert _dialect(PG16).supports_type_alter_action(action) is True + + @pytest.mark.parametrize( + "action,version,expected", + [ + (PostgresRenameEnumValueAction, PG96, False), + (PostgresRenameEnumValueAction, PG10, True), + (PostgresSetTypePropertiesAction, PG10, False), + (PostgresSetTypePropertiesAction, PG13, True), + (PostgresAddEnumValueAction, PG96, True), + ], + ) + def test_version_gated_actions(self, action, version, expected): + assert _dialect(version).supports_type_alter_action(action) is expected + + @pytest.mark.parametrize("bogus", [str, object]) + def test_rejects_unknown_action(self, bogus): + assert _dialect(PG16).supports_type_alter_action(bogus) is False + + +# =========================================================================== +# pure formatting helpers +# =========================================================================== + + +class TestFormattingHelpers: + @pytest.mark.parametrize( + "name,schema,expected", + [ + ("name", None, '"name"'), + ("name", "public", '"public"."name"'), + ("MiXeD", "MySchema", '"MySchema"."MiXeD"'), + ], + ) + def test_qualified_identifier(self, name, schema, expected): + assert _dialect()._format_qualified_identifier(name, schema) == expected + + @pytest.mark.parametrize("value", ["", "a..b", ".b", "a."]) + def test_qualified_identifier_rejects_empty_segments(self, value): + with pytest.raises(ValueError, match="non-empty segments"): + _dialect()._format_qualified_identifier(value) + + @pytest.mark.parametrize( + "text", + ["INTEGER", "TEXT", "UUID", "NUMERIC", "TIMESTAMP", "JSONB", "DECIMAL(10,2)", "TEXT[]"], + ) + def test_data_type_rendering(self, text): + assert _dialect()._format_type_data_type(_data_type(text)) == text + + def test_data_type_requires_data_type(self): + with pytest.raises(TypeError, match="must be a DataType"): + _dialect()._format_type_data_type("TEXT") + + def test_data_type_rejects_bind_parameters(self): + fake = MagicMock(spec=DataType) + fake.to_sql.return_value = ("?", ("param",)) + with pytest.raises(ValueError, match="without bind parameters"): + _dialect()._format_type_data_type(fake) + + @pytest.mark.parametrize( + "cascade,restrict,expected", + [(False, False, ""), (True, False, "CASCADE"), (False, True, "RESTRICT")], + ) + def test_behavior(self, cascade, restrict, expected): + assert _dialect()._format_type_behavior(cascade, restrict) == expected + + def test_behavior_rejects_both(self): + with pytest.raises(ValueError, match="mutually exclusive"): + _dialect()._format_type_behavior(True, True) + + def test_enum_value(self): + assert _dialect()._format_postgres_enum_value("a'b") == "'a''b'" + + def test_enum_value_requires_string(self): + with pytest.raises(TypeError, match="must be strings"): + _dialect()._format_postgres_enum_value(1) + + def test_composite_attribute(self): + attr = PostgresCompositeTypeAttribute( + "label", _data_type("TEXT"), collation="public.mycoll" + ) + assert _dialect()._format_postgres_composite_attribute(attr) == ( + '"label" TEXT COLLATE "public"."mycoll"' + ) + + def test_composite_attribute_without_collation(self): + attr = PostgresCompositeTypeAttribute("n", _data_type("INTEGER")) + assert _dialect()._format_postgres_composite_attribute(attr) == '"n" INTEGER' + + +# =========================================================================== +# CREATE TYPE / type definitions +# =========================================================================== + + +class TestCreateType: + def test_enum_helper(self): + sql, params = _dialect().format_create_type_enum_statement("mood", ["happy", "sad"]) + assert sql == "CREATE TYPE \"mood\" AS ENUM ('happy', 'sad')" + assert params == () + + def test_enum_helper_with_schema(self): + sql, _ = _dialect().format_create_type_enum_statement("mood", ["ok"], schema="public") + assert sql == 'CREATE TYPE "public"."mood" AS ENUM (\'ok\')' + + def test_composite_statement(self): + definition = PostgresCompositeTypeDefinition( + _dialect(), + [ + PostgresCompositeTypeAttribute("x", _data_type("INTEGER")), + PostgresCompositeTypeAttribute( + "label", _data_type("TEXT"), collation="public.mycoll" + ), + ], + ) + sql, params = _dialect().format_create_type_statement( + CreateTypeStatement(_dialect(), _type("addr"), definition) + ) + assert sql == 'CREATE TYPE "addr" AS ("x" INTEGER, "label" TEXT COLLATE "public"."mycoll")' + assert params == () + + def test_statement_type_must_be_type_object(self): + definition = PostgresEnumTypeDefinition(_dialect(), ["a"]) + bad = MagicMock() + bad.definition_kind = "enum" + with pytest.raises(TypeError, match="must be a Type"): + _dialect().format_create_type_statement( + CreateTypeStatement(_dialect(), bad, definition) + ) + + @pytest.mark.parametrize( + "kwargs,match", + [ + (dict(if_not_exists=True), "IF NOT EXISTS"), + (dict(or_replace=True), "OR REPLACE"), + ], + ) + def test_unsupported_create_modifiers(self, kwargs, match): + definition = PostgresEnumTypeDefinition(_dialect(), ["a"]) + with pytest.raises(UnsupportedFeatureError, match=match): + _dialect().format_create_type_statement( + CreateTypeStatement(_dialect(), _type("mood"), definition, **kwargs) + ) + + def test_create_type_requires_96(self): + with pytest.raises(UnsupportedFeatureError, match="CREATE TYPE"): + _dialect((9, 5, 0)).format_create_type_enum_statement("mood", ["a"]) + + def test_definition_must_be_supported(self): + with pytest.raises(UnsupportedFeatureError, match="TYPE definition"): + _dialect().format_create_type_statement( + CreateTypeStatement(_dialect(), _type("mood"), MagicMock()) + ) + + +class TestTypeDefinitions: + def test_enum_definition(self): + definition = PostgresEnumTypeDefinition(_dialect(), ["a", "b'c"]) + assert definition.definition_kind == "enum" + assert _dialect().format_type_definition(definition) == ("AS ENUM ('a', 'b''c')", ()) + + @pytest.mark.parametrize("labels", [["a", "a"], [1]]) + def test_enum_definition_rejects_bad_labels(self, labels): + with pytest.raises((ValueError, TypeError)): + PostgresEnumTypeDefinition(_dialect(), labels) + + def test_range_definition_minimal(self): + definition = PostgresRangeTypeDefinition(_dialect(), _data_type("INTEGER")) + assert _dialect().format_type_definition(definition) == ("AS RANGE (SUBTYPE = INTEGER)", ()) + + def test_range_definition_full(self): + definition = PostgresRangeTypeDefinition( + _dialect(), + _data_type("NUMERIC"), + subtype_operator_class="public.opc", + collation="public.coll", + canonical_function="public.canon", + subtype_diff_function="public.diff", + multirange_type_name="public.mr", + ) + sql, params = _dialect().format_type_definition(definition) + assert sql == ( + 'AS RANGE (SUBTYPE = NUMERIC, SUBTYPE_OPCLASS = "public"."opc", ' + 'COLLATION = "public"."coll", CANONICAL = "public"."canon", ' + 'SUBTYPE_DIFF = "public"."diff", MULTIRANGE_TYPE_NAME = "public"."mr")' + ) + assert params == () + + def test_multirange_requires_14(self): + definition = PostgresRangeTypeDefinition( + _dialect(PG13), _data_type("INT4RANGE"), multirange_type_name="public.mr" + ) + with pytest.raises(UnsupportedFeatureError, match="MULTIRANGE_TYPE_NAME"): + _dialect(PG13).format_type_definition(definition) + + def test_base_definition_full(self): + definition = PostgresBaseTypeDefinition( + _dialect(), + input_function="public.in_fn", + output_function="public.out_fn", + internallength=4, + passedbyvalue=True, + alignment="int4", + storage="plain", + like_type=_data_type("INTEGER"), + category="U", + preferred=True, + default="x", + element=_data_type("TEXT"), + delimiter=",", + collatable=True, + ) + sql, params = _dialect().format_type_definition(definition) + assert sql == ( + '(INPUT = "public"."in_fn", OUTPUT = "public"."out_fn", INTERNALLENGTH = 4, ' + 'PASSEDBYVALUE, ALIGNMENT = "int4", STORAGE = "plain", LIKE = INTEGER, ' + "CATEGORY = \"U\", PREFERRED = TRUE, DEFAULT = 'x', ELEMENT = TEXT, " + "DELIMITER = ',', COLLATABLE = TRUE)" + ) + assert params == () + + def test_base_definition_variable_length(self): + definition = PostgresBaseTypeDefinition( + _dialect(), + input_function="in", + output_function="out", + internallength="VARIABLE", + ) + assert "INTERNALLENGTH = VARIABLE" in _dialect().format_type_definition(definition)[0] + + def test_base_subscript_requires_14(self): + definition = PostgresBaseTypeDefinition( + _dialect(PG13), + input_function="public.i", + output_function="public.o", + subscript_function="public.s", + ) + with pytest.raises(UnsupportedFeatureError, match="SUBSCRIPT"): + _dialect(PG13).format_type_definition(definition) + + def test_base_requires_io_functions(self): + with pytest.raises(ValueError, match="required"): + PostgresBaseTypeDefinition(_dialect(), input_function="only_in") + + def test_shell_definition_is_empty(self): + assert _dialect().format_type_definition(PostgresShellTypeDefinition(_dialect())) == ( + "", + (), + ) + + def test_unknown_definition_rejected(self): + with pytest.raises(UnsupportedFeatureError, match="TYPE definition"): + _dialect().format_type_definition(MagicMock(definition_kind="bogus")) + + +# =========================================================================== +# ALTER TYPE actions and statements +# =========================================================================== + + +class TestAlterActions: + @pytest.mark.parametrize( + "action,expected", + [ + (PostgresRenameTypeAction(_dialect(), "newname"), 'RENAME TO "newname"'), + (PostgresSetTypeSchemaAction(_dialect(), "other"), 'SET SCHEMA "other"'), + (PostgresChangeTypeOwnerAction(_dialect(), "bob"), 'OWNER TO "bob"'), + ( + PostgresRenameTypeAttributeAction(_dialect(), "old", "new", cascade=True), + 'RENAME ATTRIBUTE "old" TO "new" CASCADE', + ), + ( + PostgresAddTypeAttributeAction( + _dialect(), "extra", _data_type("TEXT"), collation="public.c" + ), + 'ADD ATTRIBUTE "extra" TEXT COLLATE "public"."c"', + ), + ( + PostgresDropTypeAttributeAction(_dialect(), "gone", if_exists=True, restrict=True), + 'DROP ATTRIBUTE IF EXISTS "gone" RESTRICT', + ), + ( + PostgresAlterTypeAttributeAction( + _dialect(), "col", _data_type("INTEGER"), set_data=True + ), + 'ALTER ATTRIBUTE "col" SET DATA TYPE INTEGER', + ), + ( + PostgresAlterTypeAttributeAction(_dialect(), "col", _data_type("TEXT")), + 'ALTER ATTRIBUTE "col" TYPE TEXT', + ), + ( + PostgresAddEnumValueAction(_dialect(), "new", before="z"), + "ADD VALUE 'new' BEFORE 'z'", + ), + ( + PostgresAddEnumValueAction(_dialect(), "new", after="a", if_not_exists=True), + "ADD VALUE IF NOT EXISTS 'new' AFTER 'a'", + ), + ( + PostgresRenameEnumValueAction(_dialect(), "old", "new"), + "RENAME VALUE 'old' TO 'new'", + ), + ( + PostgresSetTypePropertiesAction( + _dialect(), {"STORAGE": "plain", "RECEIVE": "public.recv"} + ), + 'SET (STORAGE = "plain", RECEIVE = "public"."recv")', + ), + ], + ) + def test_action_sql(self, action, expected): + assert _dialect().format_type_alter_action(action) == (expected, ()) + + def test_set_properties_none_becomes_none(self): + action = PostgresSetTypePropertiesAction(_dialect(), {"RECEIVE": None}) + assert _dialect().format_type_alter_action(action) == ("SET (RECEIVE = NONE)", ()) + + def test_rename_enum_value_requires_10(self): + action = PostgresRenameEnumValueAction(_dialect(PG96), "a", "b") + with pytest.raises(UnsupportedFeatureError, match="RENAME VALUE"): + _dialect(PG96).format_type_alter_action(action) + + def test_add_enum_if_not_exists_requires_93(self): + dialect = _dialect((9, 2, 0)) + action = PostgresAddEnumValueAction(dialect, "x", if_not_exists=True) + with patch.object(dialect, "supports_type_objects", return_value=True): + with pytest.raises(UnsupportedFeatureError, match="IF NOT EXISTS"): + dialect.format_type_alter_action(action) + + def test_set_properties_requires_13(self): + action = PostgresSetTypePropertiesAction(_dialect(PG10), {"RECEIVE": "public.r"}) + with pytest.raises(UnsupportedFeatureError, match="SET properties"): + _dialect(PG10).format_type_alter_action(action) + + def test_set_subscript_requires_14(self): + action = PostgresSetTypePropertiesAction(_dialect(PG13), {"SUBSCRIPT": "public.s"}) + with pytest.raises(UnsupportedFeatureError, match="SUBSCRIPT"): + _dialect(PG13).format_type_alter_action(action) + + def test_set_storage_none_rejected(self): + with pytest.raises(ValueError, match="STORAGE"): + PostgresSetTypePropertiesAction(_dialect(), {"STORAGE": None}) + + def test_unknown_action_rejected(self): + with pytest.raises(UnsupportedFeatureError, match="ALTER TYPE action"): + _dialect().format_type_alter_action(MagicMock(action_kind="bogus")) + + def test_add_enum_rejects_before_and_after(self): + with pytest.raises(ValueError, match="mutually exclusive"): + PostgresAddEnumValueAction(_dialect(), "x", before="a", after="b") + + +class TestAlterStatement: + def test_single_action(self): + statement = AlterTypeStatement( + _dialect(), _type("mood"), [PostgresAddEnumValueAction(_dialect(), "x")] + ) + assert _dialect().format_alter_type_statement(statement) == ( + "ALTER TYPE \"mood\" ADD VALUE 'x'", + (), + ) + + def test_multiple_combinable_actions(self): + statement = AlterTypeStatement( + _dialect(), + _type("addr"), + [ + PostgresAddTypeAttributeAction(_dialect(), "a", _data_type("TEXT")), + PostgresDropTypeAttributeAction(_dialect(), "b"), + ], + ) + assert _dialect().format_alter_type_statement(statement) == ( + 'ALTER TYPE "addr" ADD ATTRIBUTE "a" TEXT, DROP ATTRIBUTE "b"', + (), + ) + + def test_multiple_non_combinable_actions_rejected(self): + statement = AlterTypeStatement( + _dialect(), + _type("mood"), + [ + PostgresAddEnumValueAction(_dialect(), "a"), + PostgresRenameTypeAction(_dialect(), "b"), + ], + ) + with pytest.raises(UnsupportedFeatureError, match="multiple ALTER TYPE actions"): + _dialect().format_alter_type_statement(statement) + + def test_if_exists_unsupported(self): + statement = AlterTypeStatement( + _dialect(), + _type("mood"), + [PostgresAddEnumValueAction(_dialect(), "x")], + if_exists=True, + ) + with pytest.raises(UnsupportedFeatureError, match="IF EXISTS"): + _dialect().format_alter_type_statement(statement) + + def test_statement_type_must_be_type_object(self): + statement = AlterTypeStatement( + _dialect(), MagicMock(), [PostgresAddEnumValueAction(_dialect(), "x")] + ) + with pytest.raises(TypeError, match="must be a Type"): + _dialect().format_alter_type_statement(statement) + + +# =========================================================================== +# DROP TYPE +# =========================================================================== + + +class TestDropType: + def test_by_name(self): + assert _dialect().format_drop_type_statement(name="mood") == ('DROP TYPE "mood"', ()) + + def test_with_schema_and_if_exists(self): + assert _dialect().format_drop_type_statement( + name="mood", schema="public", if_exists=True + ) == ('DROP TYPE IF EXISTS "public"."mood"', ()) + + def test_legacy_schema_name(self): + assert _dialect().format_drop_type_statement(name="mood", schema_name="public") == ( + 'DROP TYPE "public"."mood"', + (), + ) + + def test_cascade(self): + assert _dialect().format_drop_type_statement(name="mood", cascade=True) == ( + 'DROP TYPE "mood" CASCADE', + (), + ) + + def test_restrict_via_expression(self): + expression = PostgresDropTypeExpression( + _dialect(), Type(_dialect(), "mood"), if_exists=True, restrict=True + ) + assert _dialect().format_drop_type_statement(expr=expression) == ( + 'DROP TYPE IF EXISTS "mood" RESTRICT', + (), + ) + + def test_expr_and_name_are_mutually_exclusive(self): + expression = PostgresDropTypeExpression(_dialect(), _type("mood")) + with pytest.raises(ValueError, match="mutually exclusive"): + _dialect().format_drop_type_statement(expr=expression, name="mood") + + def test_expr_or_name_required(self): + with pytest.raises(TypeError, match="required"): + _dialect().format_drop_type_statement() + + def test_conflicting_schema_arguments(self): + with pytest.raises(ValueError, match="must match"): + _dialect().format_drop_type_statement(name="mood", schema="a", schema_name="b") + + def test_drop_type_requires_96(self): + with pytest.raises(UnsupportedFeatureError, match="DROP TYPE"): + _dialect((9, 5, 0)).format_drop_type_statement(name="mood") + + def test_if_exists_guard(self): + dialect = _dialect() + with patch.object(dialect, "supports_drop_type_if_exists", return_value=False): + with pytest.raises(UnsupportedFeatureError, match="IF EXISTS"): + dialect.format_drop_type_statement(name="mood", if_exists=True) From 37d6f178b22b4ef236f57f2185f2d207d007a2d7 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 16:51:57 +0800 Subject: [PATCH 73/81] test(postgres): live CLI integration tests (info/query/introspect/status) --- .../backend/execute/cli/test_cli_live.py | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py new file mode 100644 index 00000000..4fb551c6 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py @@ -0,0 +1,143 @@ +# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py +"""End-to-end PostgreSQL CLI tests against a real server. + +The offline suites under ``feature/backend/construct/cli`` and the sibling files +in this directory prove argument wiring and dispatch with fakes. These drive +``main()`` with the connection parameters of the live ``postgres_backend_single`` +fixture, so a passing test means the command connected, ran, and rendered a +machine-readable answer -- not merely that the parser accepted the argv. + +When no PostgreSQL scenario is configured the fixture skips, so these cases are +inert on a machine without a server and run for real in CI. +""" + +import json + +import pytest + +from rhosocial.activerecord.backend.impl.postgres.__main__ import main + +#: ``PostgresConnectionConfig.sslmode`` (libpq spelling) -> the CLI's --ssl choice. +_SSL_TO_CLI = { + "disable": "disabled", + "allow": "auto", + "prefer": "auto", + "require": "require", + "verify-ca": "verify-ca", + "verify-full": "verify-full", +} + + +def _connection_argv(config): + """Build connection flags for the scenario the fixture connected with.""" + argv = [ + "--host", + config.host, + "--port", + str(config.port), + "--database", + config.database, + "--user", + config.username, + "--password", + config.password or "", + ] + sslmode = getattr(config, "sslmode", None) + if sslmode: + argv += ["--ssl", _SSL_TO_CLI.get(sslmode, "auto")] + return argv + + +@pytest.fixture +def probed_backend(postgres_backend_single): + """Give the catalogue listings one known table to find.""" + backend = postgres_backend_single + backend.execute('DROP TABLE IF EXISTS "cli_live_probe"') + backend.execute('CREATE TABLE "cli_live_probe" (id INTEGER PRIMARY KEY)') + yield backend + backend.execute('DROP TABLE IF EXISTS "cli_live_probe"') + + +class TestLiveCli: + """Each subcommand returns non-empty, expected JSON from the live server.""" + + def test_info(self, postgres_backend_single, capsys): + main(["info", "-o", "json", *_connection_argv(postgres_backend_single.config)]) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, dict) and payload + assert {"database", "features", "protocols"} <= payload.keys() + assert payload["database"]["type"] == "postgresql" + assert payload["database"]["connected"] is True + assert payload["database"]["version"] + + def test_query(self, postgres_backend_single, capsys): + main( + [ + "query", + "-o", + "json", + *_connection_argv(postgres_backend_single.config), + "SELECT 1 AS n", + ] + ) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, list) and len(payload) == 1 + assert int(payload[0]["n"]) == 1 + + def test_introspect_tables(self, probed_backend, capsys): + main( + [ + "introspect", + "tables", + "-o", + "json", + *_connection_argv(probed_backend.config), + ] + ) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, list) and payload + assert "cli_live_probe" in [row["name"] for row in payload] + + def test_introspect_database(self, probed_backend, capsys): + main( + [ + "introspect", + "database", + "-o", + "json", + *_connection_argv(probed_backend.config), + ] + ) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, list) and payload + assert {"name", "version", "vendor"} <= payload[0].keys() + assert payload[0]["name"] + + def test_status_all(self, postgres_backend_single, capsys): + main( + [ + "status", + "all", + "-o", + "json", + *_connection_argv(postgres_backend_single.config), + ] + ) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, dict) and payload + assert {"server_version", "server_vendor", "configuration"} <= payload.keys() + assert payload["server_version"] + + def test_status_config(self, postgres_backend_single, capsys): + main( + [ + "status", + "config", + "-o", + "json", + *_connection_argv(postgres_backend_single.config), + ] + ) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, list) and payload + assert all(row.get("name") for row in payload) From c692bdeba14361b15235a3e8b0750fab6d18e59e Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 19:52:06 +0800 Subject: [PATCH 74/81] test: bridge DDLSource contracts (ddl/core) --- .../activerecord_postgres_test/feature/ddl/conftest.py | 3 +++ .../activerecord_postgres_test/feature/ddl/core/conftest.py | 3 +++ .../feature/ddl/core/test_ddl_source_contract.py | 3 +++ .../feature/ddl/core/test_derivation.py | 3 +++ .../feature/ddl/core/test_derivation_async.py | 3 +++ .../feature/ddl/core/test_migration_function_contract.py | 3 +++ .../feature/ddl/core/test_statement_derivation.py | 3 +++ 7 files changed, 21 insertions(+) create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py create mode 100644 tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py new file mode 100644 index 00000000..8def55d1 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py +"""Bridge fixture configuration for the shared DDL contract group.""" +from rhosocial.activerecord.testsuite.feature.ddl.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py new file mode 100644 index 00000000..fe34b5ec --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py +"""Bridge fixture configuration for the shared DDL core contracts.""" +from rhosocial.activerecord.testsuite.feature.ddl.core.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py new file mode 100644 index 00000000..1762533e --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py +"""Bridge to the shared DDL contract.""" +from rhosocial.activerecord.testsuite.feature.ddl.core.test_ddl_source_contract import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py new file mode 100644 index 00000000..2daa54e2 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py +"""Bridge to the shared DDL contract.""" +from rhosocial.activerecord.testsuite.feature.ddl.core.test_derivation import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py new file mode 100644 index 00000000..62b929e5 --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py +"""Bridge to the shared DDL contract.""" +from rhosocial.activerecord.testsuite.feature.ddl.core.test_derivation_async import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py new file mode 100644 index 00000000..2342440f --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py +"""Bridge to the shared DDL contract.""" +from rhosocial.activerecord.testsuite.feature.ddl.core.test_migration_function_contract import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py new file mode 100644 index 00000000..f9e30c4c --- /dev/null +++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py +"""Bridge to the shared DDL contract.""" +from rhosocial.activerecord.testsuite.feature.ddl.core.test_statement_derivation import * # noqa: F401,F403 From 278c04d5400806d7948d330c1df179586d395b4f Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 21:57:56 +0800 Subject: [PATCH 75/81] docs: restructure README to 6-section template + version badge --- README.md | 212 +++++++++++++++++------------------------------------- 1 file changed, 65 insertions(+), 147 deletions(-) diff --git a/README.md b/README.md index ed316399..fd5ea651 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ + # rhosocial-activerecord-postgres ($\rho_{\mathbf{AR}\text{-postgres}}$) [![PyPI version](https://badge.fury.io/py/rhosocial-activerecord-postgres.svg)](https://badge.fury.io/py/rhosocial-activerecord-postgres) [![Python](https://img.shields.io/pypi/pyversions/rhosocial-activerecord-postgres.svg)](https://pypi.org/project/rhosocial-activerecord-postgres/) [![Tests](https://github.com/rhosocial/python-activerecord-postgres/actions/workflows/test.yml/badge.svg)](https://github.com/rhosocial/python-activerecord-postgres/actions) [![Coverage Status](https://codecov.io/gh/rhosocial/python-activerecord-postgres/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rhosocial/python-activerecord-postgres/tree/main) +[![Supported PostgreSQL versions](https://img.shields.io/badge/PostgreSQL-9.6%7C10%7C11%7C12%7C13%7C14%7C15%7C16%7C17%7C18%7C19-blue?logo=postgresql)](docs/en_US/introduction/supported_versions.md) [![Apache 2.0 License](https://img.shields.io/github/license/rhosocial/python-activerecord-postgres.svg)](https://github.com/rhosocial/python-activerecord-postgres/blob/main/LICENSE)
@@ -12,64 +14,56 @@

Native arrays & JSONB · Range types · DDL expressions · Sync & async

-This is a backend implementation for [rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). -It cannot be used standalone. +This is a PostgreSQL backend implementation for [rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). It cannot be used standalone. -## Requirements +**Keywords:** orm, activerecord, postgresql, psycopg, pydantic, python, async, type-safe - +## Why This Project? -_979088a_ +PostgreSQL is a mature, standards-compliant database with a rich type system — native arrays, JSONB, range types, UUID, full-text search, and more. This backend brings the familiar, intuitive ActiveRecord experience to PostgreSQL without trading any of that away. -- **Python**: `>=3.8` -- **Core**: `rhosocial-activerecord>=1.0.0.dev0,<2.0.0` -- **Driver**: `psycopg[binary]>=3.2.13` -- **CI-tested server versions**: 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 -- **Published**: PyPI `1.0.0.dev16` +- **One consistent model API.** A class represents a table; an instance represents a row. No Session object to manage — the same typed models, field mixins, and query expressions used throughout rhosocial-activerecord, now backed by PostgreSQL. +- **PostgreSQL-native SQL, not a lowest common denominator.** The dialect renders expressions as real PostgreSQL SQL with version-aware capability gating, so native features such as array operators, JSONB containment, ranges, advanced indexes, and `RETURNING` are available when your server supports them. +- **Sync and async parity.** `PostgresBackend` and `AsyncPostgresBackend` expose the same method names and patterns; the async variant just adds `await`. -## Installation +## Quick Start + +### Installation ```bash pip install rhosocial-activerecord-postgres ``` -## Quick Start +Requires Python 3.8+ and a reachable PostgreSQL server (9.6+); the example below uses the synchronous `PostgresBackend` with `psycopg`. + +### End-to-End Example ```python -from typing import ClassVar, Optional -from uuid import UUID, uuid4 +"""Save as demo.py and run with: python demo.py""" +from typing import Annotated, ClassVar -from rhosocial.activerecord.base import FieldProxy +from rhosocial.activerecord.base import FieldProxy, UseSqlType +from rhosocial.activerecord.backend.expression.types import VarCharType from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig -from rhosocial.activerecord.backend.expression import CreateTableStatement -from rhosocial.activerecord.backend.expression.statements import ( - ColumnConstraint, - ColumnDefinition, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.types import ( - ArrayType, - JsonBType, - TextType, - UUIDType, - VarCharType, -) +from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin from rhosocial.activerecord.model import ActiveRecord -class Article(ActiveRecord): - __table_name__ = "articles" +class User(IntegerPKMixin, DefaultTimestampMixin, ActiveRecord): + name: Annotated[str, UseSqlType(VarCharType(length=100))] + email: Annotated[str, UseSqlType(VarCharType(length=255))] + age: int = 0 - id: Optional[UUID] = None - title: str - tags: list[str] # maps to text[] / TEXT[] - metadata: dict # maps to JSONB + c: ClassVar[FieldProxy] = FieldProxy() # enables User.c. expressions - c: ClassVar[FieldProxy] = FieldProxy() + @classmethod + def table_name(cls) -> str: + return "users" -Article.configure( +# Configure the PostgreSQL backend and create the table from the model declaration +User.configure( PostgresConnectionConfig( host="localhost", port=5432, @@ -79,139 +73,63 @@ Article.configure( ), PostgresBackend, ) +User.create_table() -dialect = Article.__backend__.dialect -Article.__backend__.execute(*CreateTableStatement( - dialect, - "articles", - columns=[ - ColumnDefinition( - dialect, "id", UUIDType(dialect), - constraints=[ColumnConstraint( - dialect, branch=ColumnPrimaryKeyConstraint(dialect), - )], - ), - ColumnDefinition(dialect, "title", VarCharType(dialect, 200)), - ColumnDefinition(dialect, "tags", ArrayType(dialect, TextType(dialect))), - ColumnDefinition(dialect, "metadata", JsonBType(dialect)), - ], -).to_sql()) -# CREATE TABLE "articles" ("id" UUID PRIMARY KEY, "title" VARCHAR(200), -# "tags" TEXT[], "metadata" JSONB) -``` +# Create +alice = User(name="Alice", email="alice@example.com", age=30) +alice.save() +print(alice.id) # database-assigned integer primary key -> Type mapping is not automatic for every field. `list[str]` and `dict` need -> either an explicit `DataType` in the DDL above or a type adapter; check -> [type adapters](docs/en_US/type_adapters/) before assuming the column -> matches your annotation. +# Query with type-safe expressions +adults = User.query().where(User.c.age >= 18).all() +print([user.name for user in adults]) -### Async - -`AsyncPostgresBackend` exposes the same API. Method names are identical; add -`await`. - -```python -from rhosocial.activerecord.backend.impl.postgres.backend import AsyncPostgresBackend -from rhosocial.activerecord.model import AsyncActiveRecord +# Inspect the generated SQL without executing it +sql, params = User.query().where(User.c.age >= 18).to_sql() +print(sql, params) # SELECT ... FROM "users" WHERE "users"."age" >= %s (18,) +``` +> **Async parity:** use `AsyncActiveRecord` with `AsyncPostgresBackend` for the async model — same method names, same patterns, just add `await`. -class Article(AsyncActiveRecord): - ... +## Project Architecture +This package plugs into the rhosocial-activerecord stack as a single layer: models and query expressions come from the core library, the PostgreSQL dialect binds them to PostgreSQL SQL, and psycopg 3 carries the statements to the server. Both the synchronous (`PostgresBackend`) and asynchronous (`AsyncPostgresBackend`) implementations share the same API. -Article.configure(config, AsyncPostgresBackend) -rows = await Article.query().where(Article.c.title == "hello").all() -``` +For the full picture, start with the [Documentation](docs/en_US/README.md). -## PostgreSQL-Specific Features +**PostgreSQL highlights.** Native arrays, JSONB, UUID, range and geometric types, full-text search, advanced indexing (GIN / GiST / BRIN), and version-gated `RETURNING`. Connection settings live in `PostgresConnectionConfig`; connection management follows a connect-on-use pattern. -### Native arrays +## Backend Support & Progress -No serialization adapter is needed for `text[]`; operators map straight -through. +PostgreSQL 9.6 is the minimum tested server version; releases through 19 are supported. See [Supported Versions](docs/en_US/introduction/supported_versions.md) for the full matrix and for which features are version-gated. Requires Python 3.8+ and `psycopg[binary]` 3.2.13+. -```python -Article.query().where("tags @> ARRAY[?]", ("python",)).all() -Article.query().where("? = ANY(tags)", ("python",)).all() -Article.query().where("tags && ARRAY[?]", ("python",)).all() -``` +This backend ships as a separate package on top of `rhosocial-activerecord`; the core library provides the framework and this package provides the PostgreSQL implementation. -### JSONB +> **⚠️ Development Stage:** This project is under active development. APIs may change, and some features are not yet production-ready. -```python -Product.query().where("metadata->>'brand' = ?", ("Dell",)).all() -Product.query().where("metadata @> ?", ('{"brand": "Dell"}',)).all() -``` +## Contributing, License, Links -## Version Gates - -Gates below are the versions at which this backend's own `supports_*` -switch returns `True`, probed at 8.2, 8.4, 9, 9.2, 9.4, 9.5, 10, 12, 13, 14, 15, 16, 17, 18. -A version is the first probe at or above the real gate, so each is an -upper bound within one ladder step. Switches already `True` at the -oldest release carry no gate and are omitted. - -| Min version | Capabilities that turn on | -|---|---| -| 8.4 | `array_fill`, `full_text_search`, `truncate_restart_identity`, `xmlagg`, `xmlattributes`, `xmlcomment`, `xmlconcat`, `xmlelement`, `xmlexists`, `xmlforest`, `xmlparse`, `xmlpi`, `xmlroot`, `xmlserialize` | -| 9 | `for_no_key_update`, `for_share`, `ts_rank_cd` | -| 9.2 | `json_type`, `range_constructors`, `range_functions`, `range_operators`, `range_type` | -| 9.4 | `alter_materialized_view`, `filter_clause`, `for_key_share`, `jsonb`, `lateral_join`, `materialized_view`, `materialized_view_concurrent_refresh`, `materialized_view_if_not_exists`, `materialized_view_storage_options`, `materialized_view_tablespace`, `ordered_set_aggregation`, `refresh_materialized_view` | -| 9.5 | `alter_policy_rename`, `alter_policy_replace`, `array_position`, `create_policy`, `cube`, `drop_policy_if_exists`, `for_update_skip_locked`, `grouping_sets`, `if_not_exists_table`, `index_if_not_exists`, `rls_enable_always`, `rls_enable_disable`, `rls_force`, `rollup`, `trigger_if_not_exists`, `unlogged_table`, `upsert` | -| 10 | `add_partition`, `aggregate_ddl`, `alter_domain`, `alter_type`, `attach_partition`, `cluster`, `collation_ddl`, `commit_timestamp`, `copy_from`, `copy_to`, `create_domain`, `create_statistics`, `create_type`, `detach_partition`, `foreign_table_ddl`, `function_ddl`, `parallel_append`, `parallel_gather_merge`, `parallel_index_scan`, `parallel_query`, `partitioned_table_creation`, `partition_metadata_introspection`, `phrase_search`, `publication`, `safe_hash_index`, `statistics_dependencies`, `statistics_ndistinct`, `subscription`, `table_logging_switch`, `table_partitioning`, `trigger_referencing`, `type_objects`, `xmltable` | -| 12 | `call_statement`, `composite_domains`, `concurrent_index`, `default_partition`, `domain_arrays`, `generated_columns`, `gist_include`, `hash_partitioning`, `index_include`, `jit`, `json_path`, `json_table`, `jsonb_subscript`, `materialized_cte`, `nondeterministic_collation`, `parallel_create_index`, `parallel_hash_join`, `parallel_index_only_scan`, `partition_key_update`, `partitionwise_aggregate`, `partitionwise_join`, `reindex_concurrently`, `statistics_mcv`, `stored_generated_columns`, `websearch_tsquery` | -| 13 | `btree_deduplication`, `database_if_exists`, `database_if_not_exists`, `incremental_sort`, `parallel_vacuum`, `xid8_type` | -| 14 | `async_foreign_scan`, `binary_replication`, `brin_bloom`, `brin_multivalue`, `concurrent_detach`, `cte_search_cycle`, `multirange`, `multirange_agg`, `multirange_constructor`, `multirange_type`, `numeric_infinity`, `spgist_include`, `streaming_transactions`, `two_phase_decoding`, `vacuum_process_toast` | -| 15 | `copy_header_match`, `copy_text_header`, `current_role_keyword`, `merge_statement`, `nulls_not_distinct_unique`, `table_set_access_method` | -| 16 | `concurrent_unique_nulls_not_distinct`, `random_normal`, `regexp_like` | -| 17 | `copy_force_all`, `copy_log_verbosity`, `copy_on_error`, `json_table_nested_path`, `merge_with_cte`, `returning_old_new`, `update_returning_old` | -| 18 | `constraint_enforced`, `copy_reject_limit`, `copy_silent_log`, `streaming_btree_index_build` | - -PostgreSQL 12 or newer is the practical baseline; anything older misses -JSON_TABLE, materialized CTEs, generated columns and concurrent index -operations. - -## Known Limitations - -- **No connection pooling by default.** This backend connects on use and - keeps a single connection. Optional pooling is a separate extra: - `pip install rhosocial-activerecord-postgres[pooling]`, configured with - `pool_min_size` / `pool_max_size` / `pool_timeout`. See - [connection management](docs/en_US/installation_and_configuration/pool.md). -- **`RETURNING` is version-gated.** The basic clause works broadly, but - `returning_old_new` and `update_returning_old` need PostgreSQL 18. -- Field annotations do not drive DDL. `list[str]`, `dict` and `UUID` columns - are described explicitly in the `CreateTableStatement` above. - -## Testing - -Tests require a reachable PostgreSQL server and must run serially. +### Contributing -```bash -export PYTHONPATH=src:tests -.venv3.14-ubuntu26.04/bin/pytest tests/ -``` +We welcome contributions! Please see [CONTRIBUTING.md](https://github.com/rhosocial/python-activerecord/blob/main/CONTRIBUTING.md) for guidelines. -The shared contract suite lives in -[python-activerecord-testsuite](https://github.com/rhosocial/python-activerecord-testsuite): +### License -```bash -PYTHONPATH=tests .venv3.14-ubuntu26.04/bin/pytest \ - ../python-activerecord-testsuite/src/rhosocial/activerecord/testsuite/feature/ -``` +[Apache License 2.0](LICENSE) — Copyright © 2026 [vistart](https://github.com/vistart) -## Documentation +### Documentation +- **[Documentation Home](docs/en_US/README.md)** — the full documentation table of contents +- **[Supported Versions](docs/en_US/introduction/supported_versions.md)** — PostgreSQL and Python version matrix - **[Getting started](docs/en_US/installation_and_configuration/)** — installation, connection configuration, SSL, encoding - **[PostgreSQL features](docs/en_US/postgres_specific_features/)** — PostgreSQL-specific capabilities -- **[Type adapters](docs/en_US/type_adapters/)** — type conversion rules, array comparison across databases +- **[Type adapters](docs/en_US/type_adapters/)** — type conversion rules and array comparison - **[Transactions](docs/en_US/transaction_support/)** — isolation levels and savepoints - **[Troubleshooting](docs/en_US/troubleshooting/)** — connection, performance and encoding issues -## Contributing - -See [CONTRIBUTING.md](https://github.com/rhosocial/python-activerecord/blob/main/CONTRIBUTING.md). - -## License +--- -[Apache License 2.0](LICENSE) — Copyright © 2026 [vistart](https://github.com/vistart) +
From 2ef4d6d481abb0d85c6bf631dabe04be6e5d48c3 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 22:03:56 +0800 Subject: [PATCH 76/81] docs: refine README section title and model mixin annotations --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fd5ea651..6b008def 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,11 @@ from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin from rhosocial.activerecord.model import ActiveRecord -class User(IntegerPKMixin, DefaultTimestampMixin, ActiveRecord): +class User( + IntegerPKMixin, # auto-increment integer primary key (`id`) + DefaultTimestampMixin, # injects `created_at` / `updated_at` timestamps + ActiveRecord, # persistence, query builder, relations +): name: Annotated[str, UseSqlType(VarCharType(length=100))] email: Annotated[str, UseSqlType(VarCharType(length=255))] age: int = 0 @@ -107,7 +111,7 @@ This backend ships as a separate package on top of `rhosocial-activerecord`; the > **⚠️ Development Stage:** This project is under active development. APIs may change, and some features are not yet production-ready. -## Contributing, License, Links +## Documentation ### Contributing From 875be29fa330145829694a8575e2bc5f9a224556 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 22:45:01 +0800 Subject: [PATCH 77/81] docs: build out backend docs chapters and examples --- docs/LANGS.md | 4 ++ docs/en_US/README.md | 9 ++--- docs/en_US/SUMMARY.md | 85 +++++++++++++++++++++++++++++++++++++++++++ docs/zh_CN/README.md | 6 +-- 4 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 docs/LANGS.md create mode 100644 docs/en_US/SUMMARY.md diff --git a/docs/LANGS.md b/docs/LANGS.md new file mode 100644 index 00000000..e38ff32b --- /dev/null +++ b/docs/LANGS.md @@ -0,0 +1,4 @@ +# Languages + +* [English](en_US/) +* [中文 (Chinese)](zh_CN/) diff --git a/docs/en_US/README.md b/docs/en_US/README.md index 55e644f7..462b3206 100644 --- a/docs/en_US/README.md +++ b/docs/en_US/README.md @@ -4,7 +4,7 @@ > **Example:** "How does the PostgreSQL backend handle JSONB data types? What are the advantages over regular JSON?" -> 📖 **For detailed usage, please refer to**: [AI-Assisted Development Guide](introduction/ai_assistance.md) +> 📖 **For detailed usage, please refer to**: [AI-Assisted Development Guide](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/introduction/ai_assistance.md) ## Table of Contents @@ -44,18 +44,17 @@ 7. **[Testing](testing/README.md)** * **[Test Configuration](testing/configuration.md)**: test environment setup - * **[Using testsuite for Testing](testing/testsuite.md)**: test suite usage + * **[Using testsuite for Testing](https://github.com/rhosocial/python-activerecord-testsuite/blob/main/docs/en_US/README.md)**: test suite usage * **[Local PostgreSQL Testing](testing/local.md)**: local database testing 8. **[Troubleshooting](troubleshooting/README.md)** * **[Common Connection Errors](troubleshooting/connection.md)**: connection issue diagnosis * **[Performance Issues](troubleshooting/performance.md)**: performance bottleneck analysis - * **[SQL Standard Compliance](troubleshooting/sql_standard.md)**: strict SQL compliance handling 9. **[Scenarios](scenarios/README.md)** * **[Parallel Worker Processing](scenarios/parallel_workers.md)**: correct usage in multi-process/async concurrent scenarios -10. **[Worker Isolation Experiment](examples/chapter_05_worker_isolation/README.md)** - * **[Worker Connection Isolation](examples/chapter_05_worker_isolation/README.md)**: worker process isolation experiment +10. **[Worker Isolation Experiment](../examples/chapter_05_worker_isolation/README.md)** + * **[Worker Connection Isolation](../examples/chapter_05_worker_isolation/README.md)**: worker process isolation experiment > 📖 **Core Library Documentation**: To learn about the complete functionality of the ActiveRecord framework, please refer to [rhosocial-activerecord documentation](https://github.com/rhosocial/python-activerecord/tree/main/docs/en_US). diff --git a/docs/en_US/SUMMARY.md b/docs/en_US/SUMMARY.md new file mode 100644 index 00000000..586e8cba --- /dev/null +++ b/docs/en_US/SUMMARY.md @@ -0,0 +1,85 @@ +# Table of Contents + +* [rhosocial-activerecord PostgreSQL Backend Documentation](README.md) + +## Introduction + +* [Overview](introduction/README.md) +* [Relationship with the core library](introduction/relationship.md) +* [Supported versions](introduction/supported_versions.md) + +## Installation & Configuration + +* [Installation & Configuration overview](installation_and_configuration/README.md) +* [Installation guide](installation_and_configuration/installation.md) +* [Connection configuration](installation_and_configuration/configuration.md) +* [SSL/TLS configuration](installation_and_configuration/ssl.md) +* [Connection management](installation_and_configuration/pool.md) +* [Client encoding](installation_and_configuration/encoding.md) +* [Backend groups](installation_and_configuration/backend_group.md) + +## Plugins + +* [Plugins overview](plugins/README.md) +* [hstore](plugins/hstore.md) +* [pg_trgm](plugins/pg_trgm.md) +* [pgvector](plugins/pgvector.md) +* [PostGIS](plugins/postgis.md) + +## PostgreSQL Specific Features + +* [PostgreSQL Specific Features overview](postgres_specific_features/README.md) +* [PostgreSQL-specific field types](postgres_specific_features/field_types.md) +* [PostgreSQL dialect expressions](postgres_specific_features/dialect.md) +* [Advanced indexing](postgres_specific_features/indexing.md) +* [RETURNING clause](postgres_specific_features/returning.md) +* [EXPLAIN support](postgres_specific_features/explain.md) +* [Introspection](postgres_specific_features/introspection.md) +* [Partitioning](postgres_specific_features/partition.md) +* [Property graph queries](postgres_specific_features/property_graph_query.md) +* [Protocol support](postgres_specific_features/protocol_support.md) + +## DDL Operations + +* [DDL overview](ddl/README.md) +* [Materialized views](ddl/materialized_view.md) +* [DDL example](../examples/chapter_04_ddl/ddl.py) + +## Transaction Support + +* [Transaction Support overview](transaction_support/README.md) +* [Transaction isolation levels](transaction_support/isolation_level.md) +* [Savepoint support](transaction_support/savepoint.md) +* [DEFERRABLE mode](transaction_support/deferrable.md) +* [Deadlock handling](transaction_support/deadlock.md) + +## Type Adapters + +* [Type Adapters overview](type_adapters/README.md) +* [PostgreSQL to Python type mapping](type_adapters/mapping.md) +* [Custom type adapters](type_adapters/custom.md) +* [Timezone handling](type_adapters/timezone.md) +* [Array type handling](type_adapters/arrays.md) +* [Array comparison](type_adapters/array_comparison.md) + +## Testing + +* [Testing overview](testing/README.md) +* [Test configuration](testing/configuration.md) +* [Using testsuite for testing](https://github.com/rhosocial/python-activerecord-testsuite/blob/main/docs/en_US/README.md) +* [Local PostgreSQL testing](testing/local.md) + +## Troubleshooting + +* [Troubleshooting overview](troubleshooting/README.md) +* [Common connection errors](troubleshooting/connection.md) +* [Performance issues](troubleshooting/performance.md) + +## Scenarios + +* [Scenarios overview](scenarios/README.md) +* [Parallel worker processing](scenarios/parallel_workers.md) + +## Worker Isolation Experiment + +* [Worker connection isolation](../examples/chapter_05_worker_isolation/README.md) diff --git a/docs/zh_CN/README.md b/docs/zh_CN/README.md index ab1a61a3..fffa6d38 100644 --- a/docs/zh_CN/README.md +++ b/docs/zh_CN/README.md @@ -4,7 +4,7 @@ > **示例:** "PostgreSQL 后端如何处理 JSONB 数据类型?与普通 JSON 有什么优势?" -> 📖 **详细用法请参考**:[AI 辅助开发指南](introduction/ai_assistance.md) +> 📖 **详细用法请参考**:[AI 辅助开发指南](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/introduction/ai_assistance.md) ## 目录 (Table of Contents) @@ -53,7 +53,7 @@ 9. **[场景实战 (Scenarios)](scenarios/README.md)** * **[并行 Worker 处理](scenarios/parallel_workers.md)**: 多进程/异步并发场景的正确用法 -10. **[Worker 隔离实验](examples/chapter_05_worker_isolation/README.md)** - * **[Worker 连接隔离实验](examples/chapter_05_worker_isolation/README.md)**: Worker 进程隔离实验 +10. **[Worker 隔离实验](../examples/chapter_05_worker_isolation/README.md)** + * **[Worker 连接隔离实验](../examples/chapter_05_worker_isolation/README.md)**: Worker 进程隔离实验 > 📖 **核心库文档**:要了解 ActiveRecord 框架的完整功能,请参考 [rhosocial-activerecord 文档](https://github.com/Rhosocial/python-activerecord/tree/main/docs/zh_CN)。 From 59b11cbda19b7239556a2ecd947873a24cd17808 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Fri, 20 Nov 2026 23:24:32 +0800 Subject: [PATCH 78/81] docs(migration): add backend-specific migration guide and examples --- docs/en_US/README.md | 4 + docs/en_US/SUMMARY.md | 5 + docs/en_US/migration/README.md | 182 ++++++++++++++++++ .../migration/01_transactional_ddl.py | 144 ++++++++++++++ docs/examples/migration/02_named_migration.py | 80 ++++++++ docs/examples/migration/README.md | 25 +++ docs/zh_CN/README.md | 4 + docs/zh_CN/migration/README.md | 169 ++++++++++++++++ 8 files changed, 613 insertions(+) create mode 100644 docs/en_US/migration/README.md create mode 100644 docs/examples/migration/01_transactional_ddl.py create mode 100644 docs/examples/migration/02_named_migration.py create mode 100644 docs/examples/migration/README.md create mode 100644 docs/zh_CN/migration/README.md diff --git a/docs/en_US/README.md b/docs/en_US/README.md index 462b3206..24667497 100644 --- a/docs/en_US/README.md +++ b/docs/en_US/README.md @@ -57,4 +57,8 @@ 10. **[Worker Isolation Experiment](../examples/chapter_05_worker_isolation/README.md)** * **[Worker Connection Isolation](../examples/chapter_05_worker_isolation/README.md)**: worker process isolation experiment +11. **[Migrations](migration/README.md)** + * **[PostgreSQL Migration Guide](migration/README.md)**: configuration, transactional DDL, version-gated features, function-style and class-style usage + * **[Migration Examples](../examples/migration/README.md)**: runnable PostgreSQL migration scripts + > 📖 **Core Library Documentation**: To learn about the complete functionality of the ActiveRecord framework, please refer to [rhosocial-activerecord documentation](https://github.com/rhosocial/python-activerecord/tree/main/docs/en_US). diff --git a/docs/en_US/SUMMARY.md b/docs/en_US/SUMMARY.md index 586e8cba..2c3dad4e 100644 --- a/docs/en_US/SUMMARY.md +++ b/docs/en_US/SUMMARY.md @@ -45,6 +45,11 @@ * [Materialized views](ddl/materialized_view.md) * [DDL example](../examples/chapter_04_ddl/ddl.py) +## Migrations + +* [Migrations overview](migration/README.md) +* [Migration examples](../examples/migration/README.md) + ## Transaction Support * [Transaction Support overview](transaction_support/README.md) diff --git a/docs/en_US/migration/README.md b/docs/en_US/migration/README.md new file mode 100644 index 00000000..f30d1859 --- /dev/null +++ b/docs/en_US/migration/README.md @@ -0,0 +1,182 @@ +# Migrations — PostgreSQL Backend + +> **Scope:** This chapter covers only the PostgreSQL backend's migration-specific concerns: +> configuring a PostgreSQL backend for migrations, transactional DDL, version-gated features/types, +> and how the two migration APIs are wired to this backend. It does **not** re-explain the migration +> system itself — the two authoring APIs, ordering and dependency rules, version records, dry-run +> internals, the `migrate` CLI, and the exception hierarchy are all documented in the +> [core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md). +> Read that chapter first if you are new to migrations; come back here for PostgreSQL details. + +> 💡 **AI Prompt:** "Show me a PostgreSQL migration that renders its DDL in a dry run, then applies it +> inside a transaction and rolls back cleanly if a later statement fails." + +## 1. Configuring a PostgreSQL backend for migrations + +Migrations run on a backend instance you supply. Build this backend's `PostgresConnectionConfig` and +`PostgresBackend`, then — importantly — call `introspect_and_adapt()` before running migrations. That +call detects the live server version and installed extensions so the dialect renders version-gated +DDL correctly (see §3). + +```python +import os + +from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend +from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig + +config = PostgresConnectionConfig( + host=os.getenv("POSTGRES_HOST", "localhost"), + port=int(os.getenv("POSTGRES_PORT", "5432")), + database=os.getenv("POSTGRES_DATABASE", "test"), + username=os.getenv("POSTGRES_USER", "postgres"), + password=os.getenv("POSTGRES_PASSWORD", ""), +) +backend = PostgresBackend(connection_config=config) +backend.connect() +backend.introspect_and_adapt() # detect server version + installed extensions +``` + +Notes specific to this backend: + +- `PostgresConnectionConfig` accepts PostgreSQL/libpq-style options (`sslmode`, `search_path`, + `default_schema`, `application_name`, `target_session_attrs`, `connect_timeout`, `service`, …). + `search_path` / `default_schema` are worth setting when migrations target a non-`public` schema. + See [Connection configuration](../installation_and_configuration/configuration.md). +- The connection runs with driver-level autocommit; transaction boundaries are managed explicitly by + the framework. You do **not** need to open a transaction yourself around a migration group — + `run_migration_group` does it (§2). +- `introspect_and_adapt()` falls back to a default version when the server cannot be queried. If a + migration needs a specific server version, check it explicitly rather than assuming (§3). + +## 2. Transactional DDL — PostgreSQL's key advantage + +**PostgreSQL DDL is transactional.** Schema statements such as `CREATE TABLE`, `ALTER TABLE`, and +`DROP TABLE` participate in a transaction and can be **rolled back cleanly**. This is a genuine +advantage over backends whose DDL is *non-transactional*: on those, a failure part-way through a +migration leaves a partially applied schema that must be repaired by hand. On PostgreSQL the same +failure leaves the schema exactly as it was. + +How the system uses this: + +- This backend's dialect declares `supports_transactional_ddl() -> True`. The + `run_migration_group` path probes `backend.dialect.supports_transactional_ddl()` and records the + answer on `MigrationFunctionExecutionError.transactional_ddl` when a function fails. +- With the default `TransactionMode.AUTO`, a group begins one transaction, runs every function in + the group, and commits only if all succeed. Any exception rolls the whole group back — DDL + included. A dry run never begins a transaction or writes anything. +- Consequently a multi-statement migration on PostgreSQL is effectively **all-or-nothing**: you can + write `up()`/`down()` functions as a sequence of DDL steps without hand-rolled compensation for a + failed step. + +```python +from rhosocial.activerecord.backend.migration import ( + MigrationFunctionExecutionError, + run_migration_group, +) + +assert backend.dialect.supports_transactional_ddl() is True + +run_migration_group(backend, [user_fqn], dry_run=True) # renders SQL, writes nothing +run_migration_group(backend, [user_fqn], record_store=store) # one transaction, then commit + +try: + run_migration_group(backend, [failing_fqn], record_store=store) +except MigrationFunctionExecutionError as exc: + assert exc.transactional_ddl is True # the failed DDL was rolled back +``` + +PostgreSQL-specific caveats that still apply: + +- A few PostgreSQL statements cannot run inside a transaction block at all — notably + `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REFRESH MATERIALIZED VIEW CONCURRENTLY`, + and `CREATE DATABASE`/`DROP DATABASE`. Keep them out of a transactional migration group (run them + with `transaction_mode=TransactionMode.NONE` from + `rhosocial.activerecord.backend.named_expression`) and handle compensation yourself. +- DDL takes locks; concurrent migrations against the same relations can block or deadlock. Use the + backend's [deadlock handling](../transaction_support/deadlock.md) guidance where appropriate. +- See [Transaction support](../transaction_support/README.md) for isolation levels, savepoints, and + DEFERRABLE constraints. + +## 3. Version-gated features and types + +PostgreSQL features arrive at different server versions, and this backend renders only what the +target server supports. `introspect_and_adapt()` caches the live server version on the dialect; +migrations should gate version-specific DDL on it. + +- `backend.dialect.version_at_least((major, minor, patch))` — safe predicates; returns `False` when + the version is unknown (never raises). `backend.dialect.version_or_none` returns the tuple or + `None`. `backend.get_server_version()` queries the server directly. +- Examples of gated capabilities: `JSONB` (9.4+), stored generated columns (12+), `multirange` types + such as `PostgresInt4MultirangeType` (14+), `UNIQUE NULLS NOT DISTINCT` and `MERGE` (15+). + The full table is in [Supported versions](../introduction/supported_versions.md), and this + backend's version-specific types live under `rhosocial.activerecord.backend.impl.postgres.expression.types`. + +```python +from rhosocial.activerecord.backend.impl.postgres.expression.types import ( + PostgresInt4MultirangeType, +) + +def create_archive(ctx): # decorated with @migration in a real module + # Archive has a PostgresInt4MultirangeType column (PG 14+); skip on older servers. + if not ctx.backend.dialect.version_at_least((14, 0, 0)): + return + ctx.apply(Archive.create_table_statement(backend=ctx.backend)) +``` + +Always emit DDL through `ctx.apply(...)` so dry runs and version records behave correctly. + +## 4. Function-style migrations (`run_migration_group`) + +For new work, use `@migration` functions and `run_migration_group`, exactly as the core chapter +describes — only the backend differs. A complete, PostgreSQL-specific script is +[`docs/examples/migration/01_transactional_ddl.py`](../../examples/migration/01_transactional_ddl.py): +it creates a `PostgresBackend`, renders a migration with `dry_run=True`, applies it with a +`JSONFileMigrationRecordStore`, demonstrates a version-gated type, and shows the +`transactional_ddl` flag on a failure. + +```bash +# from the repository root +PYTHONPATH=src python docs/examples/migration/01_transactional_ddl.py +``` + +A successful setup requires a reachable PostgreSQL server; configure it with the `POSTGRES_*` +environment variables. Ordering, dependency validation, and record-store semantics are the system's +business — see the core chapter, not this page. + +## 5. Class-style `named-migration` CLI wiring + +The class-style (`NamedMigration`) API is fully supported for existing migrations. This backend's +CLI exposes a `named-migration` subcommand whose handler lives in +[`cli/named_migration.py`](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/named_migration.py) +and delegates to the shared core helper. It builds a `PostgresBackend` (or `AsyncPostgresBackend` +with `--async`) from the connection arguments and calls `introspect_and_adapt()` before running. + +```bash +python -m rhosocial.activerecord.backend.impl.postgres named-migration \ + myapp.migrations.v001.CreateUsersTable --host localhost --database mydb --direction up \ + --record-store ./migrations.json +python -m rhosocial.activerecord.backend.impl.postgres named-migration \ + myapp.migrations.v001.CreateUsersTable --database mydb --direction up --dry-run +python -m rhosocial.activerecord.backend.impl.postgres named-migration \ + myapp.migrations --all --record-store ./migrations.json --single-transaction +``` + +`--direction up|down`, `--record-store`, `--dry-run`, `--describe`, `--list`, `--param KEY=VALUE`, +`--all`, `--single-transaction`, and `--async` are all supported. `--single-transaction` wraps a +whole batch in one transaction — which, because PostgreSQL DDL is transactional, genuinely rolls the +entire batch back on failure. The full end-to-end demos (single migration, dependency chain, batch, +async, parameters) are in +[`src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/`](../../../src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/) +and the CLI's own options are in the [CLI README](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/README.md). + +A programmatic class-style run is also available through `MigrationRunner`; see the second example, +[`docs/examples/migration/02_named_migration.py`](../../examples/migration/02_named_migration.py). + +## 6. Where to go next + +- Migration **system** (the authoritative guide): + [core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md) +- Runnable examples: [local migration examples](../../examples/migration/README.md) +- PostgreSQL DDL statements: [DDL overview](../ddl/README.md) +- Server capabilities by version: [Supported versions](../introduction/supported_versions.md) +- Transaction behaviour: [Transaction support](../transaction_support/README.md) diff --git a/docs/examples/migration/01_transactional_ddl.py b/docs/examples/migration/01_transactional_ddl.py new file mode 100644 index 00000000..0a18fe13 --- /dev/null +++ b/docs/examples/migration/01_transactional_ddl.py @@ -0,0 +1,144 @@ +# docs/examples/migration/01_transactional_ddl.py +"""Function-style PostgreSQL migrations: dry run, transactional DDL, version gating. + +Requires a reachable PostgreSQL server; configure it with the POSTGRES_* environment +variables. Run from the repository root with PYTHONPATH=src. + +Demonstrates (see docs/en_US/migration/README.md for the system itself): + - configuring this repo's PostgresConnectionConfig / PostgresBackend + - the dialect's transactional DDL support and the all-or-nothing failure path + - @migration functions emitted through ctx.apply() and run via run_migration_group + - gating a PostgreSQL 14+ type on the adapted server version +No raw SQL strings are built here: every DDL statement comes from a model helper. +""" +import os +import tempfile +from typing import Annotated, Optional + +from rhosocial.activerecord.base import UseSqlType +from rhosocial.activerecord.backend.expression.types import IntegerType, VarCharType +from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend +from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig +from rhosocial.activerecord.backend.impl.postgres.expression.types import ( + PostgresInt4MultirangeType, +) +from rhosocial.activerecord.backend.migration import ( + JSONFileMigrationRecordStore, + MigrationDirection, + MigrationFunctionExecutionError, + migration, + run_migration_group, +) +from rhosocial.activerecord.model import ActiveRecord + + +class User(ActiveRecord): + @classmethod + def table_name(cls) -> str: + return "users" + + id: Annotated[Optional[int], UseSqlType(IntegerType())] = None + name: Annotated[str, UseSqlType(VarCharType(length=64))] + + +class Archive(ActiveRecord): + """Uses INT4MULTIRANGE, which exists only on PostgreSQL 14+.""" + + @classmethod + def table_name(cls) -> str: + return "archives" + + id: Annotated[Optional[int], UseSqlType(IntegerType())] = None + spans: Annotated[Optional[tuple], UseSqlType(PostgresInt4MultirangeType())] = None + + +@migration("v001_create_users", description="create the initial users table") +def create_users(ctx): + if ctx.direction == MigrationDirection.UP: + ctx.apply(User.create_table_statement(backend=ctx.backend)) + else: + ctx.apply(User.drop_table_statement(if_exists=True, backend=ctx.backend)) + + +@migration("v002_create_archive", description="create a PostgreSQL 14+ multirange table") +def create_archive(ctx): + # The dialect carries the version detected by introspect_and_adapt(). + if not ctx.backend.dialect.version_at_least((14, 0, 0)): + print(" [gate] server < 14: skipping INT4MULTIRANGE archive table") + return + if ctx.direction == MigrationDirection.UP: + ctx.apply(Archive.create_table_statement(backend=ctx.backend)) + else: + ctx.apply(Archive.drop_table_statement(if_exists=True, backend=ctx.backend)) + + +@migration("v003_failing_step", description="intentional failure to show DDL rollback") +def failing_step(ctx): + raise RuntimeError("intentional failure for the transactional DDL demo") + + +def build_backend(): + config = PostgresConnectionConfig( + host=os.getenv("POSTGRES_HOST", "localhost"), + port=int(os.getenv("POSTGRES_PORT", "5432")), + database=os.getenv("POSTGRES_DATABASE", "test"), + username=os.getenv("POSTGRES_USER", "postgres"), + password=os.getenv("POSTGRES_PASSWORD", ""), + ) + backend = PostgresBackend(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + return backend + + +def main(): + backend = build_backend() + rec_path = tempfile.mktemp(suffix=".json") + store = JSONFileMigrationRecordStore(rec_path) + users = f"{__name__}:create_users" + archive = f"{__name__}:create_archive" + failing = f"{__name__}:failing_step" + + try: + print("dialect supports transactional DDL:", + backend.dialect.supports_transactional_ddl()) + + # 1) dry run — renders SQL through the backend, writes nothing. + preview = run_migration_group(backend, [users, archive], dry_run=True) + print("\n== dry run ==") + print(" statements:", preview.dry_run_total) + for label, sql, _params in preview.dry_run_sql: + print(f" [{label}] {sql}") + print(" records written:", preview.records_written) + + # 2) real UP — one transaction, DDL committed only if every step succeeds. + up = run_migration_group(backend, [users, archive], record_store=store) + print("\n== UP ==") + print(" applied:", up.applied) + print(" records written:", up.records_written) + + # 3) a failing step — on PostgreSQL the group's DDL is rolled back cleanly. + print("\n== failing step (expect rollback) ==") + try: + run_migration_group(backend, [failing], record_store=store) + except MigrationFunctionExecutionError as exc: + print(" version:", exc.version) + print(" transactional_ddl:", exc.transactional_ddl) + print(" cause:", exc.cause) + + # 4) DOWN — reverse order; a clean rollback removes the applied versions. + down = run_migration_group( + backend, [users, archive], direction=MigrationDirection.DOWN, record_store=store + ) + print("\n== DOWN ==") + print(" rolled back:", down.rolled_back) + print(" applied versions after rollback:", + [r.version for r in store.get_applied()]) + finally: + backend.disconnect() + if os.path.exists(rec_path): + os.remove(rec_path) + + +if __name__ == "__main__": + main() diff --git a/docs/examples/migration/02_named_migration.py b/docs/examples/migration/02_named_migration.py new file mode 100644 index 00000000..a8a6baa6 --- /dev/null +++ b/docs/examples/migration/02_named_migration.py @@ -0,0 +1,80 @@ +# docs/examples/migration/02_named_migration.py +"""Class-style ``NamedMigration`` on PostgreSQL, plus the CLI wiring. + +Runs the repo's own example migration (V001CreateUsers) through MigrationRunner with +this backend's PostgresConnectionConfig / PostgresBackend, and prints the equivalent +``named-migration`` CLI commands. Requires a reachable PostgreSQL server; configure it +with POSTGRES_*. Run from the repository root with PYTHONPATH=src. + +For the migration system itself see the core migration chapter; for the full set of +class-style demos see src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/. +""" +import os +import tempfile + +from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend +from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig +from rhosocial.activerecord.backend.migration import ( + JSONFileMigrationRecordStore, + MigrationDirection, + MigrationRunner, +) + +MIGRATION_FQN = ( + "rhosocial.activerecord.backend.impl.postgres.examples" + ".named_migrations.migrations.V001CreateUsers" +) + + +def build_backend(): + config = PostgresConnectionConfig( + host=os.getenv("POSTGRES_HOST", "localhost"), + port=int(os.getenv("POSTGRES_PORT", "5432")), + database=os.getenv("POSTGRES_DATABASE", "test"), + username=os.getenv("POSTGRES_USER", "postgres"), + password=os.getenv("POSTGRES_PASSWORD", ""), + ) + backend = PostgresBackend(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + return backend + + +def main(): + backend = build_backend() + rec_path = tempfile.mktemp(suffix=".json") + store = JSONFileMigrationRecordStore(rec_path) + runner = MigrationRunner(MIGRATION_FQN) + + try: + # The class-style dry run captures ctx.execute(...) named-expression SQL. + preview = runner.run(backend, MigrationDirection.UP, dry_run=True) + print("\n== dry run ==") + print(" version:", preview.version) + for fqn, sql, _params in preview.dry_run_sql or []: + print(f" [{fqn}] {sql}") + + up = runner.run(backend, MigrationDirection.UP, record_store=store) + print("\n== UP ==") + print(" version:", up.version, "success:", up.success) + print(" applied:", [r.version for r in store.get_applied()]) + + down = runner.run(backend, MigrationDirection.DOWN, record_store=store) + print("\n== DOWN ==") + print(" version:", down.version, "success:", down.success) + print(" applied after rollback:", [r.version for r in store.get_applied()]) + finally: + backend.disconnect() + if os.path.exists(rec_path): + os.remove(rec_path) + + print("\n== equivalent CLI (python -m ... named-migration) ==") + print(" ", f"python -m rhosocial.activerecord.backend.impl.postgres named-migration " + f"{MIGRATION_FQN} --host localhost --database mydb --direction up " + f"--record-store ./migrations.json") + print(" ", f"python -m rhosocial.activerecord.backend.impl.postgres named-migration " + f"{MIGRATION_FQN} --database mydb --direction up --dry-run") + + +if __name__ == "__main__": + main() diff --git a/docs/examples/migration/README.md b/docs/examples/migration/README.md new file mode 100644 index 00000000..30ddce38 --- /dev/null +++ b/docs/examples/migration/README.md @@ -0,0 +1,25 @@ +# PostgreSQL Migration Examples + +Runnable examples for migrations **on this PostgreSQL backend**. They cover only this backend's +concerns (configuration, transactional DDL, version-gated types, and CLI wiring); the migration +system itself is documented in the +[core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md) +and summarised in the [backend migration guide](../../en_US/migration/README.md). + +All scripts need a reachable PostgreSQL server. Configure it with the `POSTGRES_*` environment +variables (`POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_DATABASE`, `POSTGRES_USER`, +`POSTGRES_PASSWORD`) and run from the repository root with `PYTHONPATH=src`: + +```bash +PYTHONPATH=src python docs/examples/migration/01_transactional_ddl.py +PYTHONPATH=src python docs/examples/migration/02_named_migration.py +``` + +| Script | Demonstrates | +|---|---| +| `01_transactional_ddl.py` | `PostgresConnectionConfig` + `PostgresBackend`; `introspect_and_adapt()`; `@migration` + `ctx.apply()`; `run_migration_group` dry run → UP → DOWN; dialect's `supports_transactional_ddl()` and `MigrationFunctionExecutionError.transactional_ddl`; a PostgreSQL 14+ `INT4MULTIRANGE` type gated by `version_at_least()` | +| `02_named_migration.py` | class-style `NamedMigration` via `MigrationRunner` with the PostgreSQL backend; class-style dry-run SQL capture; equivalent `named-migration` CLI commands | + +> The longer-running class-style demos (single migration, dependency chain, batch, async, parameters) +> live in +> `src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/`. diff --git a/docs/zh_CN/README.md b/docs/zh_CN/README.md index fffa6d38..1c9423ab 100644 --- a/docs/zh_CN/README.md +++ b/docs/zh_CN/README.md @@ -56,4 +56,8 @@ 10. **[Worker 隔离实验](../examples/chapter_05_worker_isolation/README.md)** * **[Worker 连接隔离实验](../examples/chapter_05_worker_isolation/README.md)**: Worker 进程隔离实验 +11. **[迁移 (Migrations)](migration/README.md)** + * **[PostgreSQL 迁移指南](migration/README.md)**: 配置、事务性 DDL、受版本门禁的特性、函数式与类式用法 + * **[迁移示例](../examples/migration/README.md)**: 可运行的 PostgreSQL 迁移脚本 + > 📖 **核心库文档**:要了解 ActiveRecord 框架的完整功能,请参考 [rhosocial-activerecord 文档](https://github.com/Rhosocial/python-activerecord/tree/main/docs/zh_CN)。 diff --git a/docs/zh_CN/migration/README.md b/docs/zh_CN/migration/README.md new file mode 100644 index 00000000..76fd5a5f --- /dev/null +++ b/docs/zh_CN/migration/README.md @@ -0,0 +1,169 @@ +# 迁移(Migrations)— PostgreSQL 后端 + +> **范围说明:** 本章只讲 PostgreSQL 后端与迁移相关的特有事项:如何为迁移配置 PostgreSQL 后端、 +> 事务性 DDL、受版本门禁的特性/类型,以及两套迁移 API 如何接到本后端上。本章**不**重复讲解迁移 +> 系统本身——两套编写 API、顺序与依赖规则、版本记录、dry run 内部机制、`migrate` CLI 以及异常 +> 层级,全部记录在[核心库迁移章节](https://github.com/rhosocial/python-activerecord/blob/main/docs/zh_CN/migration/README.md)中。 +> 如果你是初次接触迁移,请先阅读那一章;需要 PostgreSQL 细节时再回到这里。 + +> 💡 **AI 提示词:** "给我展示一个 PostgreSQL 迁移:先在 dry run 中渲染 DDL,然后在事务中应用它, +> 并在后续语句失败时干净地回滚。" + +## 1. 为迁移配置 PostgreSQL 后端 + +迁移运行在由你提供的后端实例上。构造本后端的 `PostgresConnectionConfig` 与 `PostgresBackend`, +然后——很重要——在运行迁移前调用 `introspect_and_adapt()`。该调用会探测实际服务器版本与已安装 +的扩展,使方言能正确渲染受版本门禁的 DDL(见 §3)。 + +```python +import os + +from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend +from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig + +config = PostgresConnectionConfig( + host=os.getenv("POSTGRES_HOST", "localhost"), + port=int(os.getenv("POSTGRES_PORT", "5432")), + database=os.getenv("POSTGRES_DATABASE", "test"), + username=os.getenv("POSTGRES_USER", "postgres"), + password=os.getenv("POSTGRES_PASSWORD", ""), +) +backend = PostgresBackend(connection_config=config) +backend.connect() +backend.introspect_and_adapt() # detect server version + installed extensions +``` + +本后端特有的注意点: + +- `PostgresConnectionConfig` 接受 PostgreSQL/libpq 风格的选项(`sslmode`、`search_path`、 + `default_schema`、`application_name`、`target_session_attrs`、`connect_timeout`、`service` 等)。 + 当迁移面向非 `public` schema 时,设置 `search_path` / `default_schema` 很有价值。参见 + [连接配置](../installation_and_configuration/configuration.md)。 +- 连接以驱动层 autocommit 运行;事务边界由框架显式管理。你**不需要**自己在迁移组外层开启事务—— + `run_migration_group` 会处理(§2)。 +- 当无法查询服务器时,`introspect_and_adapt()` 会回退到默认版本。如果某个迁移依赖特定服务器版本, + 请显式检查,而不要假设(§3)。 + +## 2. 事务性 DDL — PostgreSQL 的关键优势 + +**PostgreSQL 的 DDL 是事务性的。** `CREATE TABLE`、`ALTER TABLE`、`DROP TABLE` 等模式语句会参与事务, +并且可以**干净地回滚**。这是相对于 DDL *非事务性* 的后端而言真正的优势:在那些后端上,迁移中途 +失败会留下部分应用的 schema,必须手工修复。而在 PostgreSQL 上,同样的失败会让 schema 保持原样。 + +系统如何利用这一点: + +- 本后端的方言声明 `supports_transactional_ddl() -> True`。`run_migration_group` 路径会探测 + `backend.dialect.supports_transactional_ddl()`,并在函数失败时把结果记录到 + `MigrationFunctionExecutionError.transactional_ddl` 上。 +- 在默认的 `TransactionMode.AUTO` 下,一个组会开启一个事务,运行组内所有函数,只有全部成功才提交。 + 任何异常都会回滚整个组——包括 DDL。dry run 从不开启事务,也不写入任何内容。 +- 因此,PostgreSQL 上的多语句迁移实际上是**全有或全无(all-or-nothing)**:你可以把 + `up()`/`down()` 函数写成一串 DDL 步骤,而无需为某个失败步骤手写补偿逻辑。 + +```python +from rhosocial.activerecord.backend.migration import ( + MigrationFunctionExecutionError, + run_migration_group, +) + +assert backend.dialect.supports_transactional_ddl() is True + +run_migration_group(backend, [user_fqn], dry_run=True) # renders SQL, writes nothing +run_migration_group(backend, [user_fqn], record_store=store) # one transaction, then commit + +try: + run_migration_group(backend, [failing_fqn], record_store=store) +except MigrationFunctionExecutionError as exc: + assert exc.transactional_ddl is True # the failed DDL was rolled back +``` + +仍然适用的 PostgreSQL 特有注意事项: + +- 少数 PostgreSQL 语句根本不能在事务块中执行——尤其是 `CREATE INDEX CONCURRENTLY`、 + `DROP INDEX CONCURRENTLY`、`REFRESH MATERIALIZED VIEW CONCURRENTLY` 以及 + `CREATE DATABASE`/`DROP DATABASE`。请把它们排除在事务性迁移组之外(用 + `rhosocial.activerecord.backend.named_expression` 中的 `transaction_mode=TransactionMode.NONE` + 单独运行),并自行处理补偿。 +- DDL 会加锁;针对同一关系的并发迁移可能阻塞或死锁。必要时参见本后端的 + [死锁处理](../transaction_support/deadlock.md)指南。 +- 隔离级别、savepoint 与 DEFERRABLE 约束参见 [事务支持](../transaction_support/README.md)。 + +## 3. 受版本门禁的特性与类型 + +PostgreSQL 的特性在不同服务器版本中陆续引入,本后端只渲染目标服务器支持的内容。 +`introspect_and_adapt()` 会把实际服务器版本缓存到方言上;迁移应据此对版本相关 DDL 做门禁。 + +- `backend.dialect.version_at_least((major, minor, patch))` —— 安全的判定方法;版本未知时返回 + `False`(从不抛异常)。`backend.dialect.version_or_none` 返回版本元组或 `None`。 + `backend.get_server_version()` 直接查询服务器。 +- 受门禁能力的例子:`JSONB`(9.4+)、存储生成列(12+)、`multirange` 类型(如 + `PostgresInt4MultirangeType`,14+)、`UNIQUE NULLS NOT DISTINCT` 与 `MERGE`(15+)。 + 完整表格见[支持版本](../introduction/supported_versions.md),本后端的版本相关类型位于 + `rhosocial.activerecord.backend.impl.postgres.expression.types`。 + +```python +from rhosocial.activerecord.backend.impl.postgres.expression.types import ( + PostgresInt4MultirangeType, +) + +def create_archive(ctx): # decorated with @migration in a real module + # Archive has a PostgresInt4MultirangeType column (PG 14+); skip on older servers. + if not ctx.backend.dialect.version_at_least((14, 0, 0)): + return + ctx.apply(Archive.create_table_statement(backend=ctx.backend)) +``` + +请始终通过 `ctx.apply(...)` 发出 DDL,这样 dry run 与版本记录才能正确工作。 + +## 4. 函数式迁移(`run_migration_group`) + +对于新工作,使用 `@migration` 函数与 `run_migration_group`,与核心章节所述完全一致——只有后端不同。 +一个完整的 PostgreSQL 专用脚本见 +[`docs/examples/migration/01_transactional_ddl.py`](../../examples/migration/01_transactional_ddl.py): +它创建 `PostgresBackend`,用 `dry_run=True` 渲染迁移,用 `JSONFileMigrationRecordStore` 实际应用, +演示一个受版本门禁的类型,并展示失败时的 `transactional_ddl` 标记。 + +```bash +# from the repository root +PYTHONPATH=src python docs/examples/migration/01_transactional_ddl.py +``` + +成功运行需要可连接的 PostgreSQL 服务器;请用 `POSTGRES_*` 环境变量配置。顺序、依赖校验与 +record-store 语义属于系统层面的内容——请看核心章节,而不是本页。 + +## 5. 类式 `named-migration` CLI 接线 + +类式(`NamedMigration`)API 对既有迁移提供完整支持。本后端的 CLI 暴露 `named-migration` 子命令, +其处理器位于 +[`cli/named_migration.py`](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/named_migration.py), +并委托给共享的核心辅助函数。它根据连接参数构造 `PostgresBackend`(使用 `--async` 时为 +`AsyncPostgresBackend`),并在运行前调用 `introspect_and_adapt()`。 + +```bash +python -m rhosocial.activerecord.backend.impl.postgres named-migration \ + myapp.migrations.v001.CreateUsersTable --host localhost --database mydb --direction up \ + --record-store ./migrations.json +python -m rhosocial.activerecord.backend.impl.postgres named-migration \ + myapp.migrations.v001.CreateUsersTable --database mydb --direction up --dry-run +python -m rhosocial.activerecord.backend.impl.postgres named-migration \ + myapp.migrations --all --record-store ./migrations.json --single-transaction +``` + +`--direction up|down`、`--record-store`、`--dry-run`、`--describe`、`--list`、`--param KEY=VALUE`、 +`--all`、`--single-transaction` 与 `--async` 均受支持。`--single-transaction` 会把整批包装进一个事务—— +由于 PostgreSQL 的 DDL 是事务性的,这能真正做到整批失败即全部回滚。完整的端到端演示(单个迁移、 +依赖链、批量、异步、参数)位于 +[`src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/`](../../../src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/), +CLI 自身的选项见 [CLI README](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/README.md)。 + +类式迁移也可以通过 `MigrationRunner` 以编程方式运行;见第二个示例 +[`docs/examples/migration/02_named_migration.py`](../../examples/migration/02_named_migration.py)。 + +## 6. 下一步 + +- 迁移**系统**(权威指南): + [核心库迁移章节](https://github.com/rhosocial/python-activerecord/blob/main/docs/zh_CN/migration/README.md) +- 可运行示例:[本地迁移示例](../../examples/migration/README.md) +- PostgreSQL DDL 语句:[DDL 概览](../ddl/README.md) +- 各版本的服务器能力:[支持版本](../introduction/supported_versions.md) +- 事务行为:[事务支持](../transaction_support/README.md) From 65090b9f9b0890f8a94ff0adb15b4c8c332ea529 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sat, 21 Nov 2026 02:07:12 +0800 Subject: [PATCH 79/81] ci: pin testsuite dependency to release/v1.0.0.dev17 --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e90e450f..154d6584 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -64,7 +64,7 @@ jobs: - name: Install activerecord and testsuite run: | pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies run: | @@ -279,7 +279,7 @@ jobs: - name: Install activerecord and testsuite run: | pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies run: | @@ -386,7 +386,7 @@ jobs: - name: Install activerecord and testsuite run: | pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies run: | @@ -489,7 +489,7 @@ jobs: - name: Install activerecord and testsuite run: | pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR - pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies run: | From ab949f90c4a85e1627c55c64d9b7d49991340469 Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sat, 21 Nov 2026 02:22:56 +0800 Subject: [PATCH 80/81] ci: pin core dependency to release/v1.0.0.dev30 --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 154d6584..f91b1285 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -63,7 +63,7 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies @@ -278,7 +278,7 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies @@ -385,7 +385,7 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies @@ -488,7 +488,7 @@ jobs: - name: Install activerecord and testsuite run: | - pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@feature/activerecord-ddl" # NOSONAR + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR - name: Install dependencies From e132c2bfb7597a62ff6d710d559bf2a58418ccad Mon Sep 17 00:00:00 2001 From: zhao vistart Date: Sat, 21 Nov 2026 02:27:33 +0800 Subject: [PATCH 81/81] chore: add changelog fragment for PR #72 --- changelog.d/72.added.md | 1 + changelog.d/72.changed.md | 1 + 2 files changed, 2 insertions(+) create mode 100644 changelog.d/72.added.md create mode 100644 changelog.d/72.changed.md diff --git a/changelog.d/72.added.md b/changelog.d/72.added.md new file mode 100644 index 00000000..b6cc35a9 --- /dev/null +++ b/changelog.d/72.added.md @@ -0,0 +1 @@ +Add PostgreSQL-side DDL and migration support: auto-increment suggestions with `SERIAL` on every server version, expression-built DDL, the full 24-entry column-class table including PostGIS `ST_*` plus hstore, vector, text-search, range, multirange, bit-string and geometric operators, the suggested data-type table with the `substitute_data_types` hook, neutral and network-address adapters, a backend migration guide with examples, live and offline CLI tests, RawSQL-free deep EXPLAIN tests, and bridges for the rebuilt testsuite's DDLSource, query/relation/typed_column, restructured query topics, feature CLI and shared benchmarks on directory-owned databases. diff --git a/changelog.d/72.changed.md b/changelog.d/72.changed.md new file mode 100644 index 00000000..1357c37c --- /dev/null +++ b/changelog.d/72.changed.md @@ -0,0 +1 @@ +Change the PostgreSQL backend's internal test layout to directory-owned databases built from dialect-only definition classes (no raw SQL in `basic/core`, `query/collation` or `connection`), moving connection-pool tables into `pool_definitions.py`, and decide every capability skip from dialect probes rather than server-version tuples. These are internal changes with no public API impact.