simple-module-db 0.0.46__tar.gz → 0.0.48__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/.gitignore +6 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/PKG-INFO +2 -2
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/pyproject.toml +2 -2
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/__init__.py +6 -0
- simple_module_db-0.0.48/simple_module_db/_builtin_scopes.py +45 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_bulk_pk_update.py +25 -15
- simple_module_db-0.0.48/simple_module_db/_scope_writes.py +215 -0
- simple_module_db-0.0.48/simple_module_db/_secondary_scope.py +116 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/bulk_guard.py +13 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/listeners.py +2 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/migration_portability.py +29 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/migrations.py +2 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/model_registry.py +17 -11
- simple_module_db-0.0.48/simple_module_db/principals.py +84 -0
- simple_module_db-0.0.48/simple_module_db/provider.py +26 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/query_filter.py +79 -97
- simple_module_db-0.0.48/simple_module_db/scope_predicates.py +78 -0
- simple_module_db-0.0.48/simple_module_db/scopes.py +142 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/stored_settings.py +4 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/tenancy.py +1 -1
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/user_directory_sql.py +21 -1
- simple_module_db-0.0.48/tests/_scope_inheritance_models.py +20 -0
- simple_module_db-0.0.48/tests/_workspace_scope_models.py +121 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_base.py +49 -11
- simple_module_db-0.0.48/tests/test_custom_scope_registration.py +132 -0
- simple_module_db-0.0.48/tests/test_custom_scope_relationships.py +86 -0
- simple_module_db-0.0.48/tests/test_custom_scope_writes.py +117 -0
- simple_module_db-0.0.48/tests/test_custom_scopes.py +124 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_data_compatibility_doctor.py +1 -1
- simple_module_db-0.0.48/tests/test_db_expression_index_library_warnings.py +51 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_migration_doctor.py +11 -5
- simple_module_db-0.0.48/tests/test_db_user_directory_sql.py +64 -0
- simple_module_db-0.0.48/tests/test_principals.py +181 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_session.py +6 -0
- simple_module_db-0.0.46/simple_module_db/_secondary_scope.py +0 -145
- simple_module_db-0.0.46/simple_module_db/provider.py +0 -16
- simple_module_db-0.0.46/simple_module_db/scope_predicates.py +0 -102
- simple_module_db-0.0.46/tests/test_db_user_directory_sql.py +0 -29
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/LICENSE +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/README.md +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_bulk_audit_records.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_core_joins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_core_walk.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_engine_policies.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_entity_selectables.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_migration_render.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_outer_joins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_persisted_owner.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/_sqlite_index_compare.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/admission.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/audit.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/audit_redaction.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/audit_sinks.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/base.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/bulk_audit.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/bulk_audit_targets.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/callbacks.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/core_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/data_compatibility.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/deps.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/engine_options.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/extensions.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/flush_guard.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/independent.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/insert_guard.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/insert_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/leases.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/migration_state.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/mixins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/pagination.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/py.typed +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/query_stats.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/resource_policy.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/search.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/session.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/tenant_cleanup.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/transaction.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/types.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/writes.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_alembic_project.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_audit_models.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_bulk_audit_support.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_core_scope_models.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_db_dml_scope_models.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_db_read_scope_models.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_db_shape_matrix.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/_models.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/conftest.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_audit.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_audit_per_engine.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_aware_datetime.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_aliased_join_text_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_aliased_selectable_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_audit_regressions.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_bulk_audit.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_bulk_audit_targets.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_connection_policy.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_core_full_setup_join.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_core_in_orm_select.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_core_join_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_core_nested_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_credential_audit.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_credential_log_masking.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_dml_target_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_doctor_session_filters.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_engine_options.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_engine_policy_resolution.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_expression_index_warning_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_extensions.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_extensions_pg.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_flush_persisted_owner.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_independent_checkpoint.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_insert_select_tenant.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_insert_value_subqueries.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_lease_lock_wait.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_listeners_attach.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_logging.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_migration_review_regressions.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_migration_state.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_nested_dml_and_bulk_api.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_pagination.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_pagination_options.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_query_stats.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_relationship_loader_scope.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_response_finalization.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_savepoint_callbacks.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_secondary_scope_execution.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_shape_matrix_dml.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_shape_matrix_joins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_shape_matrix_selects.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_sqlite_admission_lock.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_sqlite_savepoint.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_sqlite_wal_switch.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_stored_settings.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_strict_insert_context.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_tenant_cleanup.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_tenant_upsert_guard.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_db_write_marks.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_default_tenant.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_independent_session.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_migration_portability.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_migrations.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_migrations_sqlite_index_compare.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_mixins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_multi_tenancy.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_query_filter_outer_joins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_query_filter_rel_outer_joins.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_query_filters.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_rollback_logging.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_soft_delete_shapes.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_tenant_dml.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_tenant_shapes.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_tenant_strict.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_transaction.py +0 -0
- {simple_module_db-0.0.46 → simple_module_db-0.0.48}/tests/test_writes.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: simple_module_db
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.48
|
|
4
4
|
Summary: Per-module SQLModel Base, async session, standard mixins (Audit, SoftDelete, MultiTenant, Versioned) for simple_module
|
|
5
5
|
Project-URL: Homepage, https://github.com/antosubash/simple_module_python
|
|
6
6
|
Project-URL: Repository, https://github.com/antosubash/simple_module_python
|
|
@@ -25,7 +25,7 @@ Requires-Dist: aiosqlite<0.23,>=0.20
|
|
|
25
25
|
Requires-Dist: alembic<2,>=1.16.3
|
|
26
26
|
Requires-Dist: asyncpg<0.33,>=0.30
|
|
27
27
|
Requires-Dist: psycopg2-binary<3,>=2.9
|
|
28
|
-
Requires-Dist: simple-module-core==0.0.
|
|
28
|
+
Requires-Dist: simple-module-core==0.0.48
|
|
29
29
|
Requires-Dist: sqlalchemy[asyncio]<3,>=2.0.2
|
|
30
30
|
Requires-Dist: sqlmodel<0.1,>=0.0.22
|
|
31
31
|
Description-Content-Type: text/markdown
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "simple_module_db"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.48"
|
|
4
4
|
description = "Per-module SQLModel Base, async session, standard mixins (Audit, SoftDelete, MultiTenant, Versioned) for simple_module"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -28,7 +28,7 @@ dependencies = [
|
|
|
28
28
|
# The async app code goes through asyncpg; migration env.py rewrites the
|
|
29
29
|
# URL to +psycopg2 because Alembic's online migrations are sync-only.
|
|
30
30
|
"psycopg2-binary>=2.9,<3",
|
|
31
|
-
"simple_module_core==0.0.
|
|
31
|
+
"simple_module_core==0.0.48",
|
|
32
32
|
"sqlalchemy[asyncio]>=2.0.2,<3",
|
|
33
33
|
"sqlmodel>=0.0.22,<0.1",
|
|
34
34
|
]
|
|
@@ -22,7 +22,9 @@ from simple_module_db.pagination import (
|
|
|
22
22
|
paginate,
|
|
23
23
|
total_pages,
|
|
24
24
|
)
|
|
25
|
+
from simple_module_db.principals import principal_for
|
|
25
26
|
from simple_module_db.provider import DatabaseProvider, detect_provider
|
|
27
|
+
from simple_module_db.scopes import ScopeFilter, ScopeIsolationError, register_scope
|
|
26
28
|
from simple_module_db.search import LIKE_ESCAPE_CHAR, like_contains_pattern, like_prefix_pattern
|
|
27
29
|
from simple_module_db.session import DatabaseState, RequestSession, init_db
|
|
28
30
|
from simple_module_db.tenancy import (
|
|
@@ -62,6 +64,8 @@ __all__ = [
|
|
|
62
64
|
"Page",
|
|
63
65
|
"PageParams",
|
|
64
66
|
"RequestSession",
|
|
67
|
+
"ScopeFilter",
|
|
68
|
+
"ScopeIsolationError",
|
|
65
69
|
"SoftDeleteMixin",
|
|
66
70
|
"TSVector",
|
|
67
71
|
"TenantIsolationError",
|
|
@@ -90,7 +94,9 @@ __all__ = [
|
|
|
90
94
|
"mark_written",
|
|
91
95
|
"no_tenant",
|
|
92
96
|
"paginate",
|
|
97
|
+
"principal_for",
|
|
93
98
|
"record_bulk_audit",
|
|
99
|
+
"register_scope",
|
|
94
100
|
"render_item",
|
|
95
101
|
"tenant_context",
|
|
96
102
|
"total_pages",
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Built-in scope definitions; tenancy retains its engine policy and bypass context."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from simple_module_db.mixins import MultiTenantMixin, SoftDeleteMixin
|
|
6
|
+
from simple_module_db.scopes import ScopeFilter
|
|
7
|
+
from simple_module_db.tenancy import current_tenant_id, is_all_tenants, missing_tenant_error
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class _TenantScope(ScopeFilter):
|
|
11
|
+
def bypassed(self, options: Any) -> bool:
|
|
12
|
+
return super().bypassed(options) or is_all_tenants()
|
|
13
|
+
|
|
14
|
+
def requires_context(self, owner: Any) -> bool:
|
|
15
|
+
from sqlalchemy.orm import Session
|
|
16
|
+
|
|
17
|
+
from simple_module_db._engine_policies import policy_of, session_policy
|
|
18
|
+
|
|
19
|
+
policy = session_policy(owner) if isinstance(owner, Session) else policy_of(owner)
|
|
20
|
+
return bool(policy is not None and policy.tenant_strict)
|
|
21
|
+
|
|
22
|
+
def missing_error(self, entity: str, operation: str) -> Exception:
|
|
23
|
+
return missing_tenant_error(entity, operation)
|
|
24
|
+
|
|
25
|
+
def missing_criteria(self, target: Any) -> Any:
|
|
26
|
+
return target.tenant_id.is_(None)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
soft_delete_scope = ScopeFilter(
|
|
30
|
+
name="soft_delete",
|
|
31
|
+
applies_to=SoftDeleteMixin,
|
|
32
|
+
criteria=lambda cls, ctx: cls.is_deleted.is_(False),
|
|
33
|
+
context=lambda: True,
|
|
34
|
+
bypass_option="include_deleted",
|
|
35
|
+
column="is_deleted",
|
|
36
|
+
reads_only=True,
|
|
37
|
+
)
|
|
38
|
+
tenant_scope = _TenantScope(
|
|
39
|
+
name="tenant",
|
|
40
|
+
applies_to=MultiTenantMixin,
|
|
41
|
+
criteria=lambda cls, ctx: cls.tenant_id == ctx,
|
|
42
|
+
context=current_tenant_id,
|
|
43
|
+
bypass_option="all_tenants",
|
|
44
|
+
column="tenant_id",
|
|
45
|
+
)
|
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
"""ORM bulk UPDATE by primary key: ``session.execute(update(Model), [{"id": …}, …])``.
|
|
2
2
|
|
|
3
3
|
SQLAlchemy runs that shape as an executemany keyed on the primary key and
|
|
4
|
-
does not apply loader criteria to it, so
|
|
5
|
-
the statement's ``WHERE`` instead:
|
|
6
|
-
and is left unchanged.
|
|
4
|
+
does not apply loader criteria to it, so registered scope predicates are added
|
|
5
|
+
to the statement's ``WHERE`` instead: rows outside any scope stay unchanged.
|
|
7
6
|
|
|
8
7
|
SQLAlchemy refuses its own identity-map synchronization (``evaluate``) for a
|
|
9
8
|
bulk UPDATE with extra ``WHERE`` criteria, so it is switched off for the
|
|
10
|
-
statement and done here: objects
|
|
11
|
-
|
|
9
|
+
statement and done here: matching objects already in the session get the new
|
|
10
|
+
values, as ``evaluate`` would have given them. Unevaluable predicates expire
|
|
11
|
+
objects instead of guessing which rows changed.
|
|
12
12
|
"""
|
|
13
13
|
|
|
14
14
|
from __future__ import annotations
|
|
15
15
|
|
|
16
16
|
from typing import Any
|
|
17
17
|
|
|
18
|
+
from sqlalchemy import and_
|
|
18
19
|
from sqlalchemy.orm import ORMExecuteState
|
|
20
|
+
from sqlalchemy.orm.evaluator import UnevaluatableError, _EvaluatorCompiler
|
|
19
21
|
|
|
20
|
-
from simple_module_db.insert_guard import
|
|
22
|
+
from simple_module_db.insert_guard import _param_rows
|
|
21
23
|
|
|
22
24
|
_NO_SYNC = (False, None)
|
|
23
25
|
|
|
@@ -29,26 +31,29 @@ def is_bulk_pk_update(execute_state: ORMExecuteState) -> bool:
|
|
|
29
31
|
)
|
|
30
32
|
|
|
31
33
|
|
|
32
|
-
def scoped_bulk_pk_update(
|
|
33
|
-
execute_state: ORMExecuteState, classes: list[type], tenant_id: str
|
|
34
|
-
) -> Any:
|
|
34
|
+
def scoped_bulk_pk_update(execute_state: ORMExecuteState, predicates: list[Any]) -> Any:
|
|
35
35
|
stmt = execute_state.statement
|
|
36
|
-
|
|
37
|
-
stmt = stmt.where(cls.tenant_id == tenant_id)
|
|
36
|
+
stmt = stmt.where(*predicates)
|
|
38
37
|
execute_state.statement = stmt
|
|
39
38
|
if execute_state.execution_options.get("synchronize_session", "auto") in _NO_SYNC:
|
|
40
39
|
return None
|
|
41
40
|
result = execute_state.invoke_statement(execution_options={"synchronize_session": False})
|
|
42
|
-
_synchronize(execute_state
|
|
41
|
+
_synchronize(execute_state)
|
|
43
42
|
return result
|
|
44
43
|
|
|
45
44
|
|
|
46
|
-
def _synchronize(execute_state: ORMExecuteState
|
|
47
|
-
"""``synchronize_session="evaluate"``, limited to
|
|
45
|
+
def _synchronize(execute_state: ORMExecuteState) -> None:
|
|
46
|
+
"""``synchronize_session="evaluate"``, limited to objects matching every scope."""
|
|
48
47
|
rows = _param_rows(execute_state)
|
|
49
48
|
mapper = execute_state.update_delete_options._subject_mapper
|
|
50
49
|
if mapper is None or not rows:
|
|
51
50
|
return
|
|
51
|
+
try:
|
|
52
|
+
matches = _EvaluatorCompiler(mapper.class_).process(
|
|
53
|
+
and_(*execute_state.statement._where_criteria)
|
|
54
|
+
)
|
|
55
|
+
except UnevaluatableError:
|
|
56
|
+
matches = None
|
|
52
57
|
pk_keys = [prop.key for prop in mapper._identity_key_props]
|
|
53
58
|
identity_map = execute_state.session.identity_map
|
|
54
59
|
for row in rows:
|
|
@@ -57,7 +62,12 @@ def _synchronize(execute_state: ORMExecuteState, tenant_id: str) -> None:
|
|
|
57
62
|
state = identity_map.fast_get_state(
|
|
58
63
|
mapper.identity_key_from_primary_key(tuple(row[key] for key in pk_keys))
|
|
59
64
|
)
|
|
60
|
-
if state is None
|
|
65
|
+
if state is None:
|
|
66
|
+
continue
|
|
67
|
+
if matches is None:
|
|
68
|
+
execute_state.session.expire(state.obj())
|
|
69
|
+
continue
|
|
70
|
+
if matches(state.obj()) is not True:
|
|
61
71
|
continue
|
|
62
72
|
evaluated = state.unmodified.intersection(set(row).difference(pk_keys))
|
|
63
73
|
for key in evaluated:
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Insert hooks and ownership guards for module-defined scopes.
|
|
2
|
+
|
|
3
|
+
Tenant writes retain their established guards. Custom scalar scopes stamp direct
|
|
4
|
+
INSERTs too; arbitrary SQL expressions cannot be checked and are refused.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from copy import copy
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import and_, inspect, literal, select
|
|
13
|
+
from sqlalchemy.orm import Session
|
|
14
|
+
from sqlalchemy.orm.evaluator import UnevaluatableError, _EvaluatorCompiler
|
|
15
|
+
from sqlalchemy.sql.elements import BindParameter, Label
|
|
16
|
+
|
|
17
|
+
from simple_module_db._builtin_scopes import tenant_scope
|
|
18
|
+
from simple_module_db._core_joins import _base_name
|
|
19
|
+
from simple_module_db.insert_guard import (
|
|
20
|
+
_column_name,
|
|
21
|
+
_param_rows,
|
|
22
|
+
conflict_arm,
|
|
23
|
+
raw_values,
|
|
24
|
+
statement_values,
|
|
25
|
+
)
|
|
26
|
+
from simple_module_db.scopes import ResolvedScope, ScopeFilter, ScopeIsolationError, resolve_scopes
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def refuse_scope_move(state: Any, scope: ScopeFilter) -> None:
|
|
30
|
+
column = scope.column
|
|
31
|
+
if column and (
|
|
32
|
+
column in statement_values(state.statement)
|
|
33
|
+
or any(column in row for row in _param_rows(state))
|
|
34
|
+
):
|
|
35
|
+
raise ScopeIsolationError(f"Cannot change {column} of existing rows ({scope.name})")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def guard_scope_flush(session: Session) -> None:
|
|
39
|
+
for resolved in resolve_scopes(session, {}, is_write=True):
|
|
40
|
+
scope = resolved.scope
|
|
41
|
+
if scope is tenant_scope:
|
|
42
|
+
continue
|
|
43
|
+
for obj in list(session.new) + list(session.dirty) + list(session.deleted):
|
|
44
|
+
if type(obj) not in scope._classes:
|
|
45
|
+
continue
|
|
46
|
+
if resolved.required:
|
|
47
|
+
raise scope.missing_error(type(obj).__name__, "FLUSH")
|
|
48
|
+
if not resolved.active:
|
|
49
|
+
continue
|
|
50
|
+
state = inspect(obj)
|
|
51
|
+
if obj in session.new:
|
|
52
|
+
if scope.stamp:
|
|
53
|
+
scope.stamp(obj, resolved.value)
|
|
54
|
+
try:
|
|
55
|
+
matches = _EvaluatorCompiler(type(obj)).process(resolved.predicate(type(obj)))(
|
|
56
|
+
obj
|
|
57
|
+
)
|
|
58
|
+
except UnevaluatableError as exc:
|
|
59
|
+
raise ScopeIsolationError(
|
|
60
|
+
f"Cannot validate new object for scope '{scope.name}'"
|
|
61
|
+
) from exc
|
|
62
|
+
if not matches:
|
|
63
|
+
raise ScopeIsolationError(f"New object violates scope '{scope.name}'")
|
|
64
|
+
continue
|
|
65
|
+
if obj not in session.deleted and not session.is_modified(obj):
|
|
66
|
+
continue
|
|
67
|
+
if scope.column and state.attrs[scope.column].history.has_changes():
|
|
68
|
+
raise ScopeIsolationError(f"Cannot change {scope.column} of an existing object")
|
|
69
|
+
# Read persisted ownership even for detached/forged objects: the unit of
|
|
70
|
+
# work itself writes by PK and cannot carry our predicate.
|
|
71
|
+
mapper = state.mapper
|
|
72
|
+
predicates = [
|
|
73
|
+
col == value for col, value in zip(mapper.primary_key, state.identity, strict=True)
|
|
74
|
+
]
|
|
75
|
+
probe = (
|
|
76
|
+
select(literal(1))
|
|
77
|
+
.select_from(mapper.local_table)
|
|
78
|
+
.where(*predicates, resolved.predicate(mapper.local_table.c))
|
|
79
|
+
)
|
|
80
|
+
conn = session.connection(bind_arguments={"mapper": mapper})
|
|
81
|
+
if conn.execute(probe).first() is None:
|
|
82
|
+
raise ScopeIsolationError(f"Object is outside scope '{scope.name}'")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _check_value(value: Any, resolved: ResolvedScope, params: list[dict], binds: dict) -> None:
|
|
86
|
+
while isinstance(value, Label):
|
|
87
|
+
value = value.element
|
|
88
|
+
if isinstance(value, BindParameter):
|
|
89
|
+
if value.callable is not None:
|
|
90
|
+
raise ScopeIsolationError(f"Unverifiable INSERT for scope '{resolved.scope.name}'")
|
|
91
|
+
values = [
|
|
92
|
+
row.get(value.key, row.get(binds.get(value), value.value)) for row in params or [{}]
|
|
93
|
+
]
|
|
94
|
+
elif hasattr(value, "__visit_name__"):
|
|
95
|
+
raise ScopeIsolationError(f"Unverifiable INSERT for scope '{resolved.scope.name}'")
|
|
96
|
+
else:
|
|
97
|
+
values = [value]
|
|
98
|
+
if any(value != resolved.value for value in values):
|
|
99
|
+
raise ScopeIsolationError(f"INSERT violates scope '{resolved.scope.name}'")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def guard_scope_insert(state: Any, scopes: list[ResolvedScope]) -> None:
|
|
103
|
+
for resolved in scopes:
|
|
104
|
+
scope = resolved.scope
|
|
105
|
+
stmt = state.statement
|
|
106
|
+
if (
|
|
107
|
+
scope is tenant_scope
|
|
108
|
+
or scope.reads_only
|
|
109
|
+
or _base_name(stmt.table) not in scope._table_names
|
|
110
|
+
):
|
|
111
|
+
continue
|
|
112
|
+
if resolved.required:
|
|
113
|
+
raise scope.missing_error(stmt.table.name, "INSERT")
|
|
114
|
+
if not resolved.active:
|
|
115
|
+
continue
|
|
116
|
+
if scope.column is None:
|
|
117
|
+
raise ScopeIsolationError(f"INSERT needs a scalar column for scope '{scope.name}'")
|
|
118
|
+
for prefix, _dialect in getattr(stmt, "_prefixes", ()):
|
|
119
|
+
if "REPLACE" in str(prefix).upper():
|
|
120
|
+
raise ScopeIsolationError(f"INSERT OR REPLACE is not scoped ({scope.name})")
|
|
121
|
+
_guard_upsert(state, resolved)
|
|
122
|
+
_stamp_insert(state, resolved)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _stamp_insert(state: Any, resolved: ResolvedScope) -> None:
|
|
126
|
+
scope, stmt = resolved.scope, state.statement
|
|
127
|
+
column = scope.column
|
|
128
|
+
assert column is not None
|
|
129
|
+
rows = _param_rows(state)
|
|
130
|
+
binds = {
|
|
131
|
+
v: _column_name(k) for k, v in raw_values(stmt).items() if isinstance(v, BindParameter)
|
|
132
|
+
}
|
|
133
|
+
source = getattr(stmt, "select", None)
|
|
134
|
+
if source is not None:
|
|
135
|
+
names = list(stmt._select_names)
|
|
136
|
+
if column in names:
|
|
137
|
+
binds = stmt.compile().bind_names if rows else {}
|
|
138
|
+
sources = [source]
|
|
139
|
+
while sources:
|
|
140
|
+
part = sources.pop()
|
|
141
|
+
if hasattr(part, "selects"):
|
|
142
|
+
sources.extend(part.selects)
|
|
143
|
+
else:
|
|
144
|
+
_check_value(
|
|
145
|
+
list(part.selected_columns)[names.index(column)], resolved, rows, binds
|
|
146
|
+
)
|
|
147
|
+
elif scope.stamp:
|
|
148
|
+
source = source.subquery()
|
|
149
|
+
state.statement = stmt.from_select(
|
|
150
|
+
[*names, column],
|
|
151
|
+
select(*source.c, literal(resolved.value)),
|
|
152
|
+
include_defaults=stmt.include_insert_from_select_defaults,
|
|
153
|
+
)
|
|
154
|
+
else:
|
|
155
|
+
raise ScopeIsolationError(f"INSERT missing '{column}'")
|
|
156
|
+
return
|
|
157
|
+
if stmt._multi_values:
|
|
158
|
+
groups = []
|
|
159
|
+
for group in stmt._multi_values:
|
|
160
|
+
stamped = []
|
|
161
|
+
for row in group:
|
|
162
|
+
mapping = (
|
|
163
|
+
dict(row)
|
|
164
|
+
if isinstance(row, dict)
|
|
165
|
+
else dict(zip(stmt.table.c, row, strict=False))
|
|
166
|
+
)
|
|
167
|
+
keys = {_column_name(k): k for k in mapping}
|
|
168
|
+
if column in keys:
|
|
169
|
+
_check_value(mapping[keys[column]], resolved, rows, binds)
|
|
170
|
+
elif scope.stamp:
|
|
171
|
+
mapping[stmt.table.c[column]] = resolved.value
|
|
172
|
+
else:
|
|
173
|
+
raise ScopeIsolationError(f"INSERT missing '{column}'")
|
|
174
|
+
stamped.append(mapping)
|
|
175
|
+
groups.append(stamped)
|
|
176
|
+
stmt = stmt._generate()
|
|
177
|
+
stmt._multi_values = tuple(groups)
|
|
178
|
+
state.statement = stmt
|
|
179
|
+
return
|
|
180
|
+
values = {_column_name(k): v for k, v in raw_values(stmt).items()}
|
|
181
|
+
if column in values:
|
|
182
|
+
_check_value(values[column], resolved, rows, binds)
|
|
183
|
+
for row in rows:
|
|
184
|
+
if column in row:
|
|
185
|
+
_check_value(row[column], resolved, [], {})
|
|
186
|
+
if rows:
|
|
187
|
+
stamped = []
|
|
188
|
+
for row in rows:
|
|
189
|
+
if column not in row and column not in values:
|
|
190
|
+
if not scope.stamp:
|
|
191
|
+
raise ScopeIsolationError(f"INSERT missing '{column}'")
|
|
192
|
+
row = {**row, column: resolved.value}
|
|
193
|
+
stamped.append(row)
|
|
194
|
+
# Keep later tenant stamping/audit in the same execution pipeline.
|
|
195
|
+
state.parameters = stamped if isinstance(state.parameters, list) else stamped[0]
|
|
196
|
+
elif column not in values:
|
|
197
|
+
if not scope.stamp:
|
|
198
|
+
raise ScopeIsolationError(f"INSERT missing '{column}'")
|
|
199
|
+
state.statement = stmt.values(**{column: resolved.value})
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _guard_upsert(state: Any, resolved: ResolvedScope) -> None:
|
|
203
|
+
stmt = state.statement
|
|
204
|
+
arm = conflict_arm(stmt)
|
|
205
|
+
if arm is None:
|
|
206
|
+
return
|
|
207
|
+
if any(_column_name(k) == resolved.scope.column for k, _ in arm.update_values_to_set):
|
|
208
|
+
raise ScopeIsolationError(f"Cannot change {resolved.scope.column} in conflict update")
|
|
209
|
+
out, arm = stmt._generate(), copy(arm)
|
|
210
|
+
pred = resolved.predicate(stmt.table.c)
|
|
211
|
+
arm.update_whereclause = (
|
|
212
|
+
pred if arm.update_whereclause is None else and_(arm.update_whereclause, pred)
|
|
213
|
+
)
|
|
214
|
+
out._post_values_clause = arm
|
|
215
|
+
state.statement = out
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Registered scopes for mapped relationship secondary tables.
|
|
2
|
+
|
|
3
|
+
Loader criteria cannot see a plain secondary Table built at compile time. Add
|
|
4
|
+
parameterized join predicates once, then bind each scope and bypass per execution.
|
|
5
|
+
Unmapped association tables remain unscoped, regardless of their column names.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from contextvars import ContextVar
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from sqlalchemy import Boolean, and_, bindparam, event, or_
|
|
14
|
+
from sqlalchemy.engine import Engine
|
|
15
|
+
from sqlalchemy.orm import Mapper
|
|
16
|
+
|
|
17
|
+
from simple_module_db import scopes
|
|
18
|
+
from simple_module_db._core_joins import _base_name
|
|
19
|
+
from simple_module_db.scopes import ScopeFilter
|
|
20
|
+
|
|
21
|
+
_SCOPED_MARK = "_sm_secondary_scoped"
|
|
22
|
+
_scope: ContextVar[dict[str, tuple[bool, Any]] | None] = ContextVar(
|
|
23
|
+
"sm_secondary_scope", default=None
|
|
24
|
+
)
|
|
25
|
+
_any_scoped = False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _current(scope: ScopeFilter) -> tuple[bool, Any]:
|
|
29
|
+
found = _scope.get()
|
|
30
|
+
if found is not None:
|
|
31
|
+
return found.get(scope.name, (True, None))
|
|
32
|
+
value = scope.value()
|
|
33
|
+
return scope.bypassed({}) or value is None, value
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def secondary_criteria(table: Any, added: set[str]) -> list[Any]:
|
|
37
|
+
name = _base_name(table)
|
|
38
|
+
criteria = []
|
|
39
|
+
for scope in scopes._scopes.values():
|
|
40
|
+
if name not in scope._table_names or scope.name in added:
|
|
41
|
+
continue
|
|
42
|
+
skip = bindparam(
|
|
43
|
+
f"sm_secondary_skip_{scope.name}",
|
|
44
|
+
type_=Boolean(),
|
|
45
|
+
callable_=lambda s=scope: _current(s)[0],
|
|
46
|
+
)
|
|
47
|
+
value = bindparam(
|
|
48
|
+
f"sm_secondary_value_{scope.name}",
|
|
49
|
+
type_=table.c[scope.column].type if scope.column else None,
|
|
50
|
+
callable_=lambda s=scope: _current(s)[1],
|
|
51
|
+
)
|
|
52
|
+
present = bindparam(
|
|
53
|
+
f"sm_secondary_present_{scope.name}",
|
|
54
|
+
type_=Boolean(),
|
|
55
|
+
callable_=lambda s=scope: _current(s)[1] is not None,
|
|
56
|
+
)
|
|
57
|
+
criteria.append(or_(skip, and_(present, scope.criteria(table.c, value))))
|
|
58
|
+
added.add(scope.name)
|
|
59
|
+
return criteria
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def scope_relationship(prop: Any) -> None:
|
|
63
|
+
"""Extend a relationship with any not-yet-installed registered scopes."""
|
|
64
|
+
if prop.secondary is None:
|
|
65
|
+
return
|
|
66
|
+
added = getattr(prop, _SCOPED_MARK, set())
|
|
67
|
+
criteria = secondary_criteria(prop.secondary, added)
|
|
68
|
+
if not criteria:
|
|
69
|
+
return
|
|
70
|
+
join_condition = prop._join_condition
|
|
71
|
+
join_condition.secondaryjoin = and_(join_condition.secondaryjoin, *criteria)
|
|
72
|
+
prop.secondaryjoin = join_condition.secondaryjoin
|
|
73
|
+
setattr(prop, _SCOPED_MARK, added)
|
|
74
|
+
global _any_scoped
|
|
75
|
+
_any_scoped = True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@event.listens_for(Mapper, "mapper_configured")
|
|
79
|
+
def _on_mapper_configured(mapper: Mapper, cls: type) -> None:
|
|
80
|
+
for prop in mapper.relationships:
|
|
81
|
+
if prop.parent is mapper:
|
|
82
|
+
scope_relationship(prop)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def record_execution_scope(
|
|
86
|
+
conn: Any, clause: Any, multiparams: Any, params: Any, options: Any
|
|
87
|
+
) -> None:
|
|
88
|
+
if not _any_scoped:
|
|
89
|
+
return
|
|
90
|
+
is_write = bool(getattr(clause, "is_update", False) or getattr(clause, "is_delete", False))
|
|
91
|
+
values = {}
|
|
92
|
+
for scope in scopes._scopes.values():
|
|
93
|
+
value = scope.value()
|
|
94
|
+
skip = (
|
|
95
|
+
(is_write and scope.reads_only)
|
|
96
|
+
or scope.bypassed(options)
|
|
97
|
+
or (value is None and not scope.requires_context(conn))
|
|
98
|
+
)
|
|
99
|
+
# Keep the bound value even during a bypass: cached relationship SQL
|
|
100
|
+
# still binds it, as the built-in tenant policy has always done.
|
|
101
|
+
values[scope.name] = (skip, value)
|
|
102
|
+
_scope.set(values)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def clear_execution_scope(*_args: Any) -> None:
|
|
106
|
+
if _scope.get() is not None:
|
|
107
|
+
_scope.set(None)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# Every engine records options, including unbound engines. Clear after failure too,
|
|
111
|
+
# so a subsequent execution (or child task) cannot inherit a previous bypass.
|
|
112
|
+
event.listen(Engine, "before_execute", record_execution_scope)
|
|
113
|
+
event.listen(Engine, "after_execute", clear_execution_scope)
|
|
114
|
+
event.listen(Engine, "handle_error", clear_execution_scope)
|
|
115
|
+
|
|
116
|
+
__all__: list[str] = []
|
|
@@ -22,8 +22,10 @@ from typing import Any
|
|
|
22
22
|
from sqlalchemy import inspect as sa_inspect
|
|
23
23
|
from sqlalchemy.orm import Session
|
|
24
24
|
|
|
25
|
+
from simple_module_db._builtin_scopes import tenant_scope
|
|
25
26
|
from simple_module_db.mixins import MultiTenantMixin
|
|
26
27
|
from simple_module_db.query_filter import strict_configured
|
|
28
|
+
from simple_module_db.scopes import ScopeIsolationError, resolve_scopes
|
|
27
29
|
from simple_module_db.tenancy import TenantIsolationError, current_tenant_id, is_all_tenants
|
|
28
30
|
|
|
29
31
|
_GUARDED_ATTR = "_sm_bulk_guarded"
|
|
@@ -34,6 +36,17 @@ def _mapped_class(mapper: Any) -> type:
|
|
|
34
36
|
|
|
35
37
|
|
|
36
38
|
def _check(session: Session, method: str, classes: Iterable[type]) -> None:
|
|
39
|
+
classes = tuple(classes)
|
|
40
|
+
for resolved in resolve_scopes(session, {}, is_write=True):
|
|
41
|
+
if (
|
|
42
|
+
resolved.scope is not tenant_scope
|
|
43
|
+
and resolved.active
|
|
44
|
+
and any(cls in resolved.scope._classes for cls in classes)
|
|
45
|
+
):
|
|
46
|
+
raise ScopeIsolationError(
|
|
47
|
+
f"Session.{method}() bypasses scope '{resolved.scope.name}'; "
|
|
48
|
+
"use session.execute() instead"
|
|
49
|
+
)
|
|
37
50
|
if is_all_tenants():
|
|
38
51
|
return
|
|
39
52
|
if current_tenant_id.get() is None and not strict_configured(session):
|
|
@@ -13,6 +13,7 @@ from sqlalchemy import inspect as sa_inspect
|
|
|
13
13
|
from sqlalchemy.orm import Session
|
|
14
14
|
|
|
15
15
|
from simple_module_db._persisted_owner import mark_unverified, owner_mark, restore_owner_mark
|
|
16
|
+
from simple_module_db._scope_writes import guard_scope_flush
|
|
16
17
|
from simple_module_db.audit_redaction import AUDIT_REDACTED, pk_is_redacted
|
|
17
18
|
from simple_module_db.bulk_audit import audit_statement
|
|
18
19
|
from simple_module_db.bulk_guard import install_bulk_guard
|
|
@@ -168,6 +169,7 @@ def _before_flush_listener(
|
|
|
168
169
|
instances: object,
|
|
169
170
|
) -> None:
|
|
170
171
|
guard_flush(session)
|
|
172
|
+
guard_scope_flush(session)
|
|
171
173
|
user_id = current_user_id.get()
|
|
172
174
|
now = datetime.now(UTC)
|
|
173
175
|
|
{simple_module_db-0.0.46 → simple_module_db-0.0.48}/simple_module_db/migration_portability.py
RENAMED
|
@@ -20,6 +20,8 @@ or never sees, and neither ``alembic check`` nor the boot check notices:
|
|
|
20
20
|
from __future__ import annotations
|
|
21
21
|
|
|
22
22
|
import logging
|
|
23
|
+
import re
|
|
24
|
+
import warnings
|
|
23
25
|
from collections.abc import Iterator
|
|
24
26
|
from typing import Any
|
|
25
27
|
|
|
@@ -30,6 +32,7 @@ from simple_module_core.diagnostics._expression_index import (
|
|
|
30
32
|
find_expression_indexes,
|
|
31
33
|
)
|
|
32
34
|
from sqlalchemy.dialects import postgresql
|
|
35
|
+
from sqlalchemy.exc import SAWarning
|
|
33
36
|
from sqlalchemy.schema import DefaultClause
|
|
34
37
|
from sqlalchemy.sql.elements import ColumnElement, False_, TextClause, True_
|
|
35
38
|
|
|
@@ -120,6 +123,32 @@ def rewrite_boolean_defaults(upgrade_ops: Any) -> None:
|
|
|
120
123
|
column.server_default = DefaultClause(replacement)
|
|
121
124
|
|
|
122
125
|
|
|
126
|
+
def silence_expression_index_reflection_warnings(metadata: sa.MetaData) -> None:
|
|
127
|
+
"""Ignore the library warnings about expression indexes the models declare (GH #933).
|
|
128
|
+
|
|
129
|
+
On SQLite, SQLAlchemy warns that it skipped reflecting each expression index
|
|
130
|
+
and Alembic that it skipped comparing it, on every autogenerate. For an
|
|
131
|
+
index in ``metadata`` the revision hook already covers both cases: it
|
|
132
|
+
re-emits the index for a new table and :func:`warn_unverifiable_expression_indexes`
|
|
133
|
+
names one the database lacks. Indexes the models do not declare still warn.
|
|
134
|
+
"""
|
|
135
|
+
names = [index for _, index in find_expression_indexes(metadata.tables.values())]
|
|
136
|
+
if not names:
|
|
137
|
+
return
|
|
138
|
+
alternatives = "|".join(re.escape(name) for name in names)
|
|
139
|
+
warnings.filterwarnings(
|
|
140
|
+
"ignore",
|
|
141
|
+
message=rf"Skipped unsupported reflection of expression-based index ({alternatives})$",
|
|
142
|
+
category=SAWarning,
|
|
143
|
+
)
|
|
144
|
+
warnings.filterwarnings(
|
|
145
|
+
"ignore",
|
|
146
|
+
message=rf"autogenerate skipping metadata-specified expression-based index "
|
|
147
|
+
rf"'({alternatives})';",
|
|
148
|
+
category=UserWarning,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
123
152
|
def warn_unverifiable_expression_indexes(
|
|
124
153
|
dialect_name: str | None,
|
|
125
154
|
metadata: sa.MetaData,
|
|
@@ -36,6 +36,7 @@ from simple_module_db.extensions import ( # noqa: F401 (ensure_db_extensions r
|
|
|
36
36
|
from simple_module_db.migration_portability import (
|
|
37
37
|
iter_ops_recursive,
|
|
38
38
|
rewrite_boolean_defaults,
|
|
39
|
+
silence_expression_index_reflection_warnings,
|
|
39
40
|
sqlite_index_names,
|
|
40
41
|
warn_unverifiable_expression_indexes,
|
|
41
42
|
)
|
|
@@ -207,6 +208,7 @@ def make_process_revision_directives(
|
|
|
207
208
|
process_revision_directives=make_process_revision_directives(target_metadata),
|
|
208
209
|
)
|
|
209
210
|
"""
|
|
211
|
+
silence_expression_index_reflection_warnings(metadata)
|
|
210
212
|
expression_indexes: dict[str, list[Index]] = {}
|
|
211
213
|
for table in metadata.tables.values():
|
|
212
214
|
for index in table.indexes:
|