simple-module-db 0.0.42__tar.gz → 0.0.43__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.
Files changed (127) hide show
  1. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/.gitignore +3 -0
  2. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/PKG-INFO +3 -3
  3. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/pyproject.toml +3 -3
  4. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/_bulk_audit_records.py +0 -11
  5. simple_module_db-0.0.43/simple_module_db/_bulk_pk_update.py +70 -0
  6. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/_core_joins.py +5 -0
  7. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/_core_walk.py +79 -13
  8. simple_module_db-0.0.43/simple_module_db/_engine_policies.py +80 -0
  9. simple_module_db-0.0.43/simple_module_db/_entity_selectables.py +218 -0
  10. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/_migration_render.py +18 -9
  11. simple_module_db-0.0.43/simple_module_db/_persisted_owner.py +86 -0
  12. simple_module_db-0.0.43/simple_module_db/_secondary_scope.py +145 -0
  13. simple_module_db-0.0.43/simple_module_db/admission.py +32 -0
  14. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/audit.py +8 -14
  15. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/bulk_audit.py +31 -3
  16. simple_module_db-0.0.43/simple_module_db/bulk_guard.py +89 -0
  17. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/callbacks.py +11 -3
  18. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/core_scope.py +44 -12
  19. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/data_compatibility.py +13 -3
  20. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/deps.py +2 -1
  21. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/flush_guard.py +35 -8
  22. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/insert_guard.py +81 -20
  23. simple_module_db-0.0.43/simple_module_db/insert_scope.py +117 -0
  24. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/listeners.py +10 -1
  25. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/migrations.py +44 -6
  26. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/model_registry.py +7 -6
  27. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/query_filter.py +48 -75
  28. simple_module_db-0.0.43/simple_module_db/scope_predicates.py +102 -0
  29. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/transaction.py +39 -20
  30. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/writes.py +82 -4
  31. simple_module_db-0.0.43/tests/_db_dml_scope_models.py +99 -0
  32. simple_module_db-0.0.43/tests/_db_read_scope_models.py +118 -0
  33. simple_module_db-0.0.43/tests/test_db_aliased_join_text_scope.py +115 -0
  34. simple_module_db-0.0.43/tests/test_db_aliased_selectable_scope.py +121 -0
  35. simple_module_db-0.0.43/tests/test_db_audit_regressions.py +104 -0
  36. simple_module_db-0.0.43/tests/test_db_dml_target_scope.py +136 -0
  37. simple_module_db-0.0.43/tests/test_db_doctor_session_filters.py +91 -0
  38. simple_module_db-0.0.43/tests/test_db_engine_policy_resolution.py +204 -0
  39. simple_module_db-0.0.43/tests/test_db_flush_persisted_owner.py +179 -0
  40. simple_module_db-0.0.43/tests/test_db_insert_value_subqueries.py +133 -0
  41. simple_module_db-0.0.43/tests/test_db_migration_review_regressions.py +186 -0
  42. simple_module_db-0.0.43/tests/test_db_nested_dml_and_bulk_api.py +176 -0
  43. simple_module_db-0.0.43/tests/test_db_relationship_loader_scope.py +106 -0
  44. simple_module_db-0.0.43/tests/test_db_response_finalization.py +243 -0
  45. simple_module_db-0.0.43/tests/test_db_secondary_scope_execution.py +95 -0
  46. simple_module_db-0.0.43/tests/test_db_sqlite_admission_lock.py +67 -0
  47. simple_module_db-0.0.43/tests/test_db_strict_insert_context.py +105 -0
  48. simple_module_db-0.0.43/tests/test_db_tenant_upsert_guard.py +169 -0
  49. simple_module_db-0.0.43/tests/test_db_write_marks.py +101 -0
  50. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/LICENSE +0 -0
  51. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/README.md +0 -0
  52. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/__init__.py +0 -0
  53. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/_outer_joins.py +0 -0
  54. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/audit_sinks.py +0 -0
  55. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/base.py +0 -0
  56. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/bulk_audit_targets.py +0 -0
  57. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/engine_options.py +0 -0
  58. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/extensions.py +0 -0
  59. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/independent.py +0 -0
  60. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/leases.py +0 -0
  61. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/migration_portability.py +0 -0
  62. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/mixins.py +0 -0
  63. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/pagination.py +0 -0
  64. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/provider.py +0 -0
  65. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/py.typed +0 -0
  66. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/resource_policy.py +0 -0
  67. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/search.py +0 -0
  68. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/session.py +0 -0
  69. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/stored_settings.py +0 -0
  70. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/tenancy.py +0 -0
  71. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/tenant_cleanup.py +0 -0
  72. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/types.py +0 -0
  73. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/simple_module_db/user_directory_sql.py +0 -0
  74. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/_audit_models.py +0 -0
  75. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/_bulk_audit_support.py +0 -0
  76. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/_core_scope_models.py +0 -0
  77. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/_db_shape_matrix.py +0 -0
  78. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/_models.py +0 -0
  79. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/conftest.py +0 -0
  80. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_audit.py +0 -0
  81. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_audit_per_engine.py +0 -0
  82. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_aware_datetime.py +0 -0
  83. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_base.py +0 -0
  84. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_bulk_audit.py +0 -0
  85. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_bulk_audit_targets.py +0 -0
  86. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_connection_policy.py +0 -0
  87. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_core_full_setup_join.py +0 -0
  88. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_core_in_orm_select.py +0 -0
  89. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_core_join_scope.py +0 -0
  90. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_core_nested_scope.py +0 -0
  91. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_data_compatibility_doctor.py +0 -0
  92. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_engine_options.py +0 -0
  93. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_extensions.py +0 -0
  94. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_extensions_pg.py +0 -0
  95. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_independent_checkpoint.py +0 -0
  96. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_insert_select_tenant.py +0 -0
  97. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_lease_lock_wait.py +0 -0
  98. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_listeners_attach.py +0 -0
  99. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_logging.py +0 -0
  100. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_pagination.py +0 -0
  101. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_pagination_options.py +0 -0
  102. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_savepoint_callbacks.py +0 -0
  103. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_shape_matrix_dml.py +0 -0
  104. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_shape_matrix_joins.py +0 -0
  105. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_shape_matrix_selects.py +0 -0
  106. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_sqlite_savepoint.py +0 -0
  107. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_sqlite_wal_switch.py +0 -0
  108. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_stored_settings.py +0 -0
  109. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_tenant_cleanup.py +0 -0
  110. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_db_user_directory_sql.py +0 -0
  111. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_default_tenant.py +0 -0
  112. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_independent_session.py +0 -0
  113. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_migration_portability.py +0 -0
  114. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_migrations.py +0 -0
  115. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_mixins.py +0 -0
  116. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_multi_tenancy.py +0 -0
  117. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_query_filter_outer_joins.py +0 -0
  118. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_query_filter_rel_outer_joins.py +0 -0
  119. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_query_filters.py +0 -0
  120. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_rollback_logging.py +0 -0
  121. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_session.py +0 -0
  122. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_soft_delete_shapes.py +0 -0
  123. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_tenant_dml.py +0 -0
  124. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_tenant_shapes.py +0 -0
  125. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_tenant_strict.py +0 -0
  126. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_transaction.py +0 -0
  127. {simple_module_db-0.0.42 → simple_module_db-0.0.43}/tests/test_writes.py +0 -0
@@ -22,6 +22,9 @@ node_modules/
22
22
 
23
23
  # Database
24
24
  *.db
25
+ *.db-wal
26
+ *.db-shm
27
+ *.db-journal
25
28
  *.sqlite3
26
29
 
27
30
  # Module-managed runtime state (e.g. uploaded dataset files,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_db
3
- Version: 0.0.42
3
+ Version: 0.0.43
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,8 +25,8 @@ Requires-Dist: aiosqlite<0.23,>=0.20
25
25
  Requires-Dist: alembic<2,>=1.14
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.42
29
- Requires-Dist: sqlalchemy[asyncio]<3,>=2.0
28
+ Requires-Dist: simple-module-core==0.0.43
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
32
32
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_db"
3
- version = "0.0.42"
3
+ version = "0.0.43"
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,8 +28,8 @@ 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.42",
32
- "sqlalchemy[asyncio]>=2.0,<3",
31
+ "simple_module_core==0.0.43",
32
+ "sqlalchemy[asyncio]>=2.0.2,<3",
33
33
  "sqlmodel>=0.0.22,<0.1",
34
34
  ]
35
35
 
@@ -9,8 +9,6 @@ from typing import Any, Final
9
9
  from simple_module_core.correlation import correlation_id
10
10
  from sqlalchemy import inspect as sa_inspect
11
11
  from sqlalchemy.orm import ORMExecuteState, Session
12
- from sqlalchemy.sql.elements import BindParameter
13
- from sqlalchemy.sql.visitors import iterate
14
12
 
15
13
  from simple_module_db.audit import AuditRecord, _serialize, format_pk
16
14
  from simple_module_db.query_filter import engine_policy
@@ -61,15 +59,6 @@ def _current_user() -> str | None:
61
59
  return current_user_id.get()
62
60
 
63
61
 
64
- def _where_params(stmt: Any, params: Any) -> dict[str, Any] | None:
65
- """The execute params the ``WHERE`` clause binds, so the prefetch can run it."""
66
- where = getattr(stmt, "whereclause", None)
67
- if where is None or not isinstance(params, dict):
68
- return None
69
- keys = {e.key for e in iterate(where) if isinstance(e, BindParameter)}
70
- return {k: v for k, v in params.items() if k in keys} or None
71
-
72
-
73
62
  def _bulk_by_pk_ids(execute_state: ORMExecuteState, cls: type) -> list[str] | None:
74
63
  """``session.execute(update(Model), [{pk..., col...}, ...])``: ids from the rows."""
75
64
  params = execute_state.parameters
@@ -0,0 +1,70 @@
1
+ """ORM bulk UPDATE by primary key: ``session.execute(update(Model), [{"id": …}, …])``.
2
+
3
+ SQLAlchemy runs that shape as an executemany keyed on the primary key and
4
+ does not apply loader criteria to it, so the tenant predicate is added to
5
+ the statement's ``WHERE`` instead: a row of another tenant matches nothing
6
+ and is left unchanged.
7
+
8
+ SQLAlchemy refuses its own identity-map synchronization (``evaluate``) for a
9
+ bulk UPDATE with extra ``WHERE`` criteria, so it is switched off for the
10
+ statement and done here: objects of the bound tenant already in the session
11
+ get the new values, as ``evaluate`` would have given them.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any
17
+
18
+ from sqlalchemy.orm import ORMExecuteState
19
+
20
+ from simple_module_db.insert_guard import TENANT_COLUMN, _param_rows
21
+
22
+ _NO_SYNC = (False, None)
23
+
24
+
25
+ def is_bulk_pk_update(execute_state: ORMExecuteState) -> bool:
26
+ return (
27
+ execute_state.is_update
28
+ and getattr(execute_state.update_delete_options, "_dml_strategy", None) == "bulk"
29
+ )
30
+
31
+
32
+ def scoped_bulk_pk_update(
33
+ execute_state: ORMExecuteState, classes: list[type], tenant_id: str
34
+ ) -> Any:
35
+ stmt = execute_state.statement
36
+ for cls in classes:
37
+ stmt = stmt.where(cls.tenant_id == tenant_id)
38
+ execute_state.statement = stmt
39
+ if execute_state.execution_options.get("synchronize_session", "auto") in _NO_SYNC:
40
+ return None
41
+ result = execute_state.invoke_statement(execution_options={"synchronize_session": False})
42
+ _synchronize(execute_state, tenant_id)
43
+ return result
44
+
45
+
46
+ def _synchronize(execute_state: ORMExecuteState, tenant_id: str) -> None:
47
+ """``synchronize_session="evaluate"``, limited to the bound tenant's objects."""
48
+ rows = _param_rows(execute_state)
49
+ mapper = execute_state.update_delete_options._subject_mapper
50
+ if mapper is None or not rows:
51
+ return
52
+ pk_keys = [prop.key for prop in mapper._identity_key_props]
53
+ identity_map = execute_state.session.identity_map
54
+ for row in rows:
55
+ if any(key not in row for key in pk_keys):
56
+ continue
57
+ state = identity_map.fast_get_state(
58
+ mapper.identity_key_from_primary_key(tuple(row[key] for key in pk_keys))
59
+ )
60
+ if state is None or state.dict.get(TENANT_COLUMN) != tenant_id:
61
+ continue
62
+ evaluated = state.unmodified.intersection(set(row).difference(pk_keys))
63
+ for key in evaluated:
64
+ if key in state.dict:
65
+ state.dict[key] = row[key]
66
+ state.manager.dispatch.refresh(state, None, evaluated)
67
+ state._commit(state.dict, list(evaluated))
68
+
69
+
70
+ __all__ = ["is_bulk_pk_update", "scoped_bulk_pk_update"]
@@ -58,6 +58,11 @@ def is_plain_leaf(node: Any) -> bool:
58
58
  return isinstance(base, TableClause)
59
59
 
60
60
 
61
+ def is_scoped_leaf(node: Any, names: set[str]) -> bool:
62
+ """A plain Core table (or alias of one) whose base table is one of ``names``."""
63
+ return is_plain_leaf(node) and _base_name(node) in names
64
+
65
+
61
66
  def _padded(leaf: Any) -> Any | None:
62
67
  """``leaf``'s row is the NULL padding of an outer join: its primary key is NULL."""
63
68
  pk = list(leaf.primary_key)
@@ -21,10 +21,18 @@ from __future__ import annotations
21
21
  from typing import Any
22
22
 
23
23
  from sqlalchemy.sql.elements import ClauseElement, ColumnClause, ColumnElement
24
- from sqlalchemy.sql.selectable import Alias, Join, Select, TableClause
24
+ from sqlalchemy.sql.selectable import (
25
+ Alias,
26
+ CompoundSelect,
27
+ Join,
28
+ Select,
29
+ TableClause,
30
+ TextualSelect,
31
+ )
25
32
  from sqlalchemy.sql.traversals import _get_children
26
33
 
27
- from simple_module_db._core_joins import _base_name, _is_orm, is_plain_leaf
34
+ from simple_module_db._core_joins import _base_name, _is_orm, is_scoped_leaf
35
+ from simple_module_db.insert_guard import raw_values
28
36
 
29
37
 
30
38
  def orm_less(stmt: Any) -> bool:
@@ -46,11 +54,21 @@ def froms_read(stmt: Any) -> list[Any]:
46
54
  """The FROMs a SELECT reads besides its joins, and the extra FROMs of a DML."""
47
55
  if not isinstance(stmt, Select):
48
56
  target = stmt.table._deannotate()
49
- return [f for f in where_froms(stmt) if f is not target]
57
+ return [f for f in (*where_froms(stmt), *set_froms(stmt)) if f is not target]
50
58
  froms = [*stmt.columns_clause_froms, *(f for f in stmt._from_obj if not isinstance(f, Join))]
51
59
  return [*froms, *(where_froms(stmt) if orm_less(stmt) else core_where_froms(stmt))]
52
60
 
53
61
 
62
+ def set_froms(stmt: Any) -> list[Any]:
63
+ """The FROMs an UPDATE's ``SET`` values pull in: ``values(name=other.c.name)``.
64
+
65
+ Such a table is joined in as ``UPDATE ... FROM``, exactly like one named
66
+ in the ``WHERE``. A scalar subquery adds no FROM; its own SELECT is
67
+ scoped where it is visited.
68
+ """
69
+ return [f for value in raw_values(stmt).values() for f in getattr(value, "_from_objects", ())]
70
+
71
+
54
72
  def core_where_froms(stmt: Select) -> list[Any]:
55
73
  """The FROMs a SELECT's ``WHERE`` pulls in through plain (non-ORM) columns.
56
74
 
@@ -75,34 +93,82 @@ def core_where_froms(stmt: Select) -> list[Any]:
75
93
  return found
76
94
 
77
95
 
78
- def references_plain(stmt: Any, names: set[str]) -> bool:
96
+ def references_plain(stmt: Any, names: set[str], opaque: frozenset[int] = frozenset()) -> bool:
79
97
  """Whether ``stmt`` reads a scoped table outside the ORM's annotations.
80
98
 
81
99
  ORM-annotated elements are not descended into: their tables are the
82
- loader criteria's business, and every ORM column leads to a plain table.
100
+ loader criteria's business, and every ORM column leads to a plain table —
101
+ except the selectable of an ``aliased(Model, <subquery or join>)`` entity,
102
+ which is whatever the caller built and is walked like any FROM, unless its
103
+ id is in ``opaque`` (SQL text under a scoped entity counts as a read).
83
104
  The answer depends only on *which* elements are reachable, so an element
84
- met twice is expanded once. ``seen`` keeps the objects, not just their
85
- ids, so a temporary child list cannot free one and recycle its id.
105
+ met twice — ORM-annotated and opaque ones included — is looked at once.
106
+ ``seen`` keeps the objects, not just their ids, so a temporary child list
107
+ cannot free one and recycle its id.
86
108
  """
87
109
  stack = [stmt]
88
110
  seen: dict[int, Any] = {}
89
111
  while stack:
90
112
  el = stack.pop()
91
- if id(el) in seen or _is_orm(el):
113
+ if id(el) in seen:
92
114
  continue
115
+ if el is not stmt and _nested_dml_on(el, names):
116
+ return True # its target is checked even when ORM-annotated
93
117
  seen[id(el)] = el
118
+ if _is_orm(el):
119
+ selectable = aliased_selectable(el)
120
+ if selectable is not None and id(selectable) not in opaque:
121
+ if reads_text_as_scoped(el._annotations["parententity"], selectable, names):
122
+ return True # SQL text: nothing in it can be seen, let alone scoped
123
+ stack.append(selectable)
124
+ continue
125
+ if id(el) in opaque:
126
+ continue
94
127
  target = el if isinstance(el, (TableClause, Alias)) else _table_of(el)
95
- if (
96
- isinstance(target, (TableClause, Alias))
97
- and is_plain_leaf(target)
98
- and _base_name(target) in names
99
- ):
128
+ if isinstance(target, (TableClause, Alias)) and is_scoped_leaf(target, names):
100
129
  return True
101
130
  if el.__visit_name__ != "bindparam": # a bound value: no clause children
102
131
  stack.extend(_children(el))
103
132
  return False
104
133
 
105
134
 
135
+ def aliased_selectable(el: Any) -> Any | None:
136
+ """The selectable an ``aliased(Model, selectable)`` entity of ``el`` reads, if any.
137
+
138
+ A subquery / CTE of a SELECT (or of SQL text), a bare ``text().columns()``
139
+ or a ``Join`` of tables: whatever the caller built. ``aliased(Model)`` (an
140
+ alias of the mapped table) and other entities give ``None``: their tables
141
+ are covered by the loader criteria.
142
+ """
143
+ insp = el._annotations.get("parententity")
144
+ if insp is None or not insp.is_aliased_class:
145
+ return None
146
+ selectable = insp.selectable
147
+ if isinstance(selectable, (Join, TextualSelect)):
148
+ return selectable
149
+ inner = getattr(selectable, "element", None)
150
+ return selectable if isinstance(inner, (Select, CompoundSelect, TextualSelect)) else None
151
+
152
+
153
+ def is_textual(selectable: Any) -> bool:
154
+ """``text(...).columns(...)``, bare or as a subquery / CTE."""
155
+ return isinstance(selectable, TextualSelect) or isinstance(
156
+ getattr(selectable, "element", None), TextualSelect
157
+ )
158
+
159
+
160
+ def reads_text_as_scoped(insp: Any, selectable: Any, names: set[str]) -> bool:
161
+ """An entity of a scoped table whose rows come from SQL text, which no filter can read."""
162
+ return is_textual(selectable) and _base_name(insp.mapper.local_table) in names
163
+
164
+
165
+ _DML = ("insert", "update", "delete")
166
+
167
+
168
+ def _nested_dml_on(el: Any, names: set[str]) -> bool:
169
+ return el.__visit_name__ in _DML and _base_name(el.table) in names
170
+
171
+
106
172
  _SELECT_OMIT = ("_correlate", "_correlate_except")
107
173
  _EMPTYABLE = (tuple, list)
108
174
 
@@ -0,0 +1,80 @@
1
+ """Per-engine tenancy policy, resolved through derived engines and session binds.
2
+
3
+ Keyed by engine rather than held in a module global so two ``DatabaseState``s
4
+ in one process (tests, a CLI next to an app) cannot switch each other's
5
+ strict mode off. ``engine.execution_options(...)`` returns an ``OptionEngine``
6
+ that proxies the engine it came from, and a session may be bound per model or
7
+ table (``binds={...}``) instead of to one engine: both resolve to the policy
8
+ of the base engine.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+ from weakref import WeakKeyDictionary
15
+
16
+ from sqlalchemy.engine import Connection, Engine
17
+ from sqlalchemy.exc import UnboundExecutionError
18
+ from sqlalchemy.orm import Session
19
+ from sqlalchemy.orm.exc import UnmappedClassError
20
+
21
+ from simple_module_db import model_registry as registry
22
+
23
+ _POLICY_KEY = "sm_engine_policy"
24
+ _engine_policy: WeakKeyDictionary[Engine, Any] = WeakKeyDictionary()
25
+ _NO_POLICY = object() # cached for a session none of whose binds has a policy
26
+ _bound = 0 # bumped by ``set_policy``: a memoized answer older than it is stale
27
+
28
+
29
+ def set_policy(engine: Engine, policy: Any) -> None:
30
+ """Attach ``policy`` to ``engine`` and invalidate every session's memoized answer."""
31
+ global _bound
32
+ _engine_policy[engine] = policy
33
+ _bound += 1
34
+
35
+
36
+ def policy_of(bind: Any) -> Any:
37
+ """The policy of ``bind`` (an engine, a derived engine or a connection), or ``None``."""
38
+ if isinstance(bind, Connection):
39
+ bind = bind.engine
40
+ while isinstance(bind, Engine):
41
+ found = _engine_policy.get(bind)
42
+ if found is not None:
43
+ return found
44
+ bind = getattr(bind, "_proxied", None) # ``OptionEngine`` -> its base engine
45
+ return None
46
+
47
+
48
+ def session_policy(session: Session) -> Any:
49
+ """The policy for ``session``: the strictest of the binds ``get_bind`` resolves.
50
+
51
+ Asked through the public ``Session.get_bind`` — once without a mapper and
52
+ once per tenant-scoped model — so per-model binds and a subclass that
53
+ overrides ``get_bind`` keep the strict policy of the engine they route to.
54
+ A class that is no longer mapped (or has no bind) is skipped, never raised.
55
+ The answer (a policy, or none) is memoized on ``session.info`` for the
56
+ session's ``bind``, the number of tenant models and the policy bindings
57
+ made; a bind added with ``bind_mapper()`` after the first statement is not
58
+ seen.
59
+ """
60
+ count = (len(registry.tenant_classes), _bound)
61
+ cached = session.info.get(_POLICY_KEY)
62
+ if cached is not None and cached[0] is session.bind and cached[1] == count:
63
+ return None if cached[2] is _NO_POLICY else cached[2]
64
+ found: dict[int, Any] = {}
65
+ for mapper in (None, *registry.tenant_classes):
66
+ try:
67
+ bind = session.get_bind(mapper=mapper)
68
+ except (UnboundExecutionError, UnmappedClassError):
69
+ continue
70
+ policy = policy_of(bind)
71
+ if policy is not None:
72
+ found.setdefault(id(policy), policy)
73
+ policies = list(found.values())
74
+ strict = [p for p in policies if getattr(p, "tenant_strict", False)]
75
+ policy = (strict or policies or [None])[0]
76
+ session.info[_POLICY_KEY] = (session.bind, count, _NO_POLICY if policy is None else policy)
77
+ return policy
78
+
79
+
80
+ __all__ = ["policy_of", "session_policy", "set_policy"]
@@ -0,0 +1,218 @@
1
+ """``aliased(Model, <subquery, CTE, join or text>)`` entities in a statement (#816).
2
+
3
+ The ORM renders such an entity from the selectable it was built over, found
4
+ through its annotations — not from the statement's FROM list. So
5
+ ``core_scope`` must not clone one: the clone would be rendered *next to* the
6
+ original, under the same name (``subqueryload()`` is built this way).
7
+
8
+ What the selectable reads is therefore never rewritten. It is either trusted
9
+ or refused:
10
+
11
+ * a relationship loader's statement (``subqueryload``) wraps the parent
12
+ statement, which was scoped when it ran — trusted;
13
+ * a selectable that reads only the entity's own table, in its own ``FROM``,
14
+ is covered by the entity's loader criteria (``include_aliases``) on the
15
+ rows it returns — allowed; so is a ``Join`` of the entity's own table with
16
+ tables that are not scoped;
17
+ * any other selectable that reads a tenant-scoped or soft-deletable table
18
+ through Core (``select(Model.__table__)``, a nested ``select(t.c.x)``, a
19
+ join) is refused with ``TenantIsolationError``. Built from ORM entities
20
+ (``select(Model)``) it is scoped by the loader criteria and runs;
21
+ * SQL text (``text().columns()``, bare or as a subquery / CTE) under an
22
+ entity of a scoped table is refused: no filter can read what it selects.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from collections.abc import Callable
28
+ from typing import Any
29
+
30
+ from sqlalchemy.sql import visitors
31
+ from sqlalchemy.sql.elements import FunctionFilter, Over, WithinGroup
32
+ from sqlalchemy.sql.functions import FunctionElement
33
+ from sqlalchemy.sql.selectable import (
34
+ Alias,
35
+ CompoundSelect,
36
+ FromClause,
37
+ FromGrouping,
38
+ Join,
39
+ Select,
40
+ )
41
+
42
+ from simple_module_db._core_joins import _base_name, _is_orm, is_plain_leaf, is_scoped_leaf
43
+ from simple_module_db._core_walk import (
44
+ aliased_selectable,
45
+ froms_read,
46
+ is_textual,
47
+ reads_text_as_scoped,
48
+ references_plain,
49
+ )
50
+ from simple_module_db.tenancy import TenantIsolationError
51
+
52
+ AliasedGuard = Callable[[Any, Any, set[str]], None]
53
+
54
+ # Functions that read one row at a time; any other (an aggregate such as ``max``,
55
+ # ``any_value`` or a custom ``GenericFunction``) may combine every tenant's rows
56
+ # even without a GROUP BY, so it makes the own-rows shortcut decline. Names, since
57
+ # ``func.<name>`` builds a plain ``Function`` for any name SQLAlchemy has no class for.
58
+ _ROW_WISE = frozenset(
59
+ {
60
+ "abs", "ceil", "ceiling", "char_length", "coalesce", "concat", "current_date",
61
+ "current_time", "current_timestamp", "floor", "ifnull", "instr", "length",
62
+ "localtime", "localtimestamp", "lower", "ltrim", "now", "nullif", "replace",
63
+ "round", "rtrim", "substr", "substring", "trim", "upper",
64
+ }
65
+ ) # fmt: skip
66
+
67
+
68
+ class StatementParts:
69
+ """One pass over a statement: its ORM options and its aliased-entity selectables."""
70
+
71
+ def __init__(self, stmt: Any) -> None:
72
+ self.options: list[Any] = []
73
+ self.entities: dict[int, tuple[Any, Any]] = {} # id(selectable) -> (insp, selectable)
74
+ annotated: list[Any] = []
75
+ for el in visitors.iterate(stmt):
76
+ self.options.extend(getattr(el, "_with_options", ()))
77
+ if _is_orm(el):
78
+ selectable = aliased_selectable(el)
79
+ if selectable is not None:
80
+ self.entities.setdefault(
81
+ id(selectable), (el._annotations["parententity"], selectable)
82
+ )
83
+ if isinstance(el, FromClause):
84
+ annotated.append(el)
85
+ # The annotated copies of an entity's selectable (``select_from(P)``)
86
+ # are as much the entity's as the selectable itself.
87
+ self.keep = [sel for _insp, sel in self.entities.values()]
88
+ if self.entities:
89
+ self.keep += [el for el in annotated if id(el._deannotate()) in self.entities]
90
+ self.opaque = frozenset(self.entities)
91
+
92
+
93
+ def check_entities(parts: StatementParts, names: set[str], guard: AliasedGuard | None) -> None:
94
+ if guard is None:
95
+ return
96
+ for insp, selectable in parts.entities.values():
97
+ if references_plain(selectable, names) or reads_text_as_scoped(insp, selectable, names):
98
+ guard(insp, selectable, names)
99
+
100
+
101
+ def refuse_aliased_core(insp: Any, selectable: Any, names: set[str]) -> None:
102
+ """The guard for statements a caller wrote (not relationship loads)."""
103
+ entity = insp.mapper.class_.__name__
104
+ if is_textual(selectable):
105
+ raise TenantIsolationError(
106
+ f"aliased({entity}) over SQL text is not tenant-scoped: the filter cannot read "
107
+ "what the text selects; build the selectable from ORM entities (select(Model)) "
108
+ "or run it under all_tenants() (with include_deleted=True for trashed rows)"
109
+ )
110
+ if _own_rows_only(insp, selectable, names):
111
+ return
112
+ leaves = (el for el in visitors.iterate(selectable) if is_scoped_leaf(el, names))
113
+ tables = sorted({str(_base_name(el)) for el in leaves})
114
+ raise TenantIsolationError(
115
+ f"aliased({entity}) over a selectable that reads "
116
+ f"{', '.join(repr(t) for t in tables) or 'a scoped table'} through Core is not "
117
+ "tenant-scoped; build the selectable from ORM entities (select(Model)) or run "
118
+ "it under all_tenants() (with include_deleted=True for trashed rows)"
119
+ )
120
+
121
+
122
+ def _own_rows_only(insp: Any, selectable: Any, names: set[str]) -> bool:
123
+ """``aliased(Doc, select(doc).where(doc.c.x == ...).subquery())``: one SELECT, own table.
124
+
125
+ No join, no grouping, window function or function outside a small set of
126
+ row-wise ones, no scoped table other than the entity's own (those of its
127
+ mapper, so a joined-inheritance entity's base table counts), and no nested
128
+ SELECT reading one — so every row it returns is a row of the entity's
129
+ tables, and the entity's loader criteria, applied to the alias, filter
130
+ exactly those rows.
131
+ """
132
+ if isinstance(selectable, Join):
133
+ return _own_join_only(insp, selectable, names)
134
+ inner = selectable.element
135
+ if not isinstance(inner, Select) or inner._setup_joins:
136
+ return False
137
+ if any(isinstance(f, Join) for f in inner._from_obj):
138
+ return False
139
+ # Grouping, aggregates and window functions combine rows *before* the entity's
140
+ # criteria filter the result, so a row of this tenant could carry other tenants' data.
141
+ if inner._group_by_clauses or inner._having_criteria or _combines_rows(inner):
142
+ return False
143
+ own = _own_tables(insp)
144
+ if any(is_scoped_leaf(f, names) and f not in own for f in froms_read(inner)):
145
+ return False
146
+ return not any(
147
+ el is not inner and isinstance(el, (Select, CompoundSelect)) and references_plain(el, names)
148
+ for el in visitors.iterate(inner)
149
+ )
150
+
151
+
152
+ def _own_join_only(insp: Any, join: Join, names: set[str]) -> bool:
153
+ """``aliased(Doc, doc.join(tag))``: the entity's own table(s) joined to unscoped tables.
154
+
155
+ Every row carries one row of the entity's tables, which its loader
156
+ criteria filter. The entity's tables are those of its mapper (and of a
157
+ ``with_polymorphic`` entity's mappers), so the flat alias the ORM builds
158
+ for joined inheritance counts too. Each may appear once: a second copy of
159
+ one, any other scoped table, a subquery or text on a side, or an ``ON``
160
+ clause with a nested SELECT reading a scoped table through Core is not
161
+ covered.
162
+ """
163
+ own = _own_tables(insp)
164
+ met: set[Any] = set()
165
+ stack: list[Any] = [join]
166
+ while stack:
167
+ node = stack.pop()
168
+ if isinstance(node, FromGrouping):
169
+ stack.append(node.element)
170
+ elif isinstance(node, Join):
171
+ stack.extend((node.left, node.right))
172
+ nested = (
173
+ el
174
+ for el in visitors.iterate(node.onclause)
175
+ if isinstance(el, (Select, CompoundSelect))
176
+ )
177
+ if any(references_plain(el, names) for el in nested):
178
+ return False
179
+ elif not is_plain_leaf(node):
180
+ return False
181
+ elif is_scoped_leaf(node, names):
182
+ base = _table_of_leaf(node)
183
+ if base not in own or base in met:
184
+ return False
185
+ met.add(base)
186
+ return True
187
+
188
+
189
+ def _own_tables(insp: Any) -> set[Any]:
190
+ """The tables of the entity's mapper and of a ``with_polymorphic`` entity's mappers."""
191
+ return {t for m in (insp.mapper, *insp.with_polymorphic_mappers) for t in m.tables}
192
+
193
+
194
+ def _table_of_leaf(node: Any) -> Any:
195
+ while isinstance(node, Alias):
196
+ node = node.element
197
+ return node
198
+
199
+
200
+ def _combines_rows(inner: Select) -> bool:
201
+ """A function in ``inner`` itself that is not row-wise (a nested SELECT is its own)."""
202
+ stack = list(inner.get_children())
203
+ while stack:
204
+ el = stack.pop()
205
+ if isinstance(el, (Select, CompoundSelect)):
206
+ continue
207
+ if isinstance(el, (Over, WithinGroup, FunctionFilter)):
208
+ return True
209
+ if (
210
+ isinstance(el, FunctionElement)
211
+ and str(getattr(el, "name", "")).lower() not in _ROW_WISE
212
+ ):
213
+ return True
214
+ stack.extend(el.get_children())
215
+ return False
216
+
217
+
218
+ __all__ = ["AliasedGuard", "StatementParts", "check_entities", "refuse_aliased_core"]
@@ -18,10 +18,10 @@ def render_item(type_, obj, autogen_context):
18
18
  to ``sa.DateTime(timezone=True)`` so migrations don't need to
19
19
  ``import sqlmodel`` (GH #440). Any other ``sqlmodel`` type still gets
20
20
  the import added, so the migration stays importable.
21
- * Renders Python ``StrEnum`` columns with ``values_callable`` so the
22
- Postgres enum labels match the lowercase ``StrEnum`` values rather than
23
- SQLAlchemy's default of using uppercase attribute names. This means raw
24
- SQL like ``WHERE status = 'ready'`` actually works against the live DB.
21
+ * Renders Python ``StrEnum`` columns using their configured labels and
22
+ storage options, without importing application enums into revisions.
23
+ Value-based labels require ``values_callable`` on the runtime type too;
24
+ plain enum columns keep SQLAlchemy's member-name labels.
25
25
  * Renders ``true()``/``false()`` server defaults as ``sa.true()``/``sa.false()``
26
26
  instead of the dialect-specific ``sa.text('1')``/``sa.text('0')`` (GH #342).
27
27
  * Renders ``LTree``/``TSVector`` through ``simple_module_db.types`` (with
@@ -63,10 +63,19 @@ def render_item(type_, obj, autogen_context):
63
63
  if isinstance(obj, sa.Enum):
64
64
  python_type = getattr(obj, "enum_class", None)
65
65
  if isinstance(python_type, type) and issubclass(python_type, StrEnum):
66
- name = getattr(obj, "name", None) or python_type.__name__.lower()
67
- members = ", ".join(repr(m.value) for m in python_type)
68
- return (
69
- f"sa.Enum({members}, name={name!r}, values_callable=lambda e: [m.value for m in e])"
70
- )
66
+ members = ", ".join(repr(label) for label in obj.enums)
67
+ options = [f"name={obj.name!r}"]
68
+ if not obj.native_enum:
69
+ options.append("native_enum=False")
70
+ if obj.create_constraint:
71
+ options.append("create_constraint=True")
72
+ if obj.length != max((len(label) for label in obj.enums), default=0):
73
+ options.append(f"length={obj.length!r}")
74
+ if obj.values_callable is not None:
75
+ # Freeze custom labels; revisions must not import application callables.
76
+ values = [member.value for member in python_type]
77
+ callable_body = "[m.value for m in e]" if obj.enums == values else repr(obj.enums)
78
+ options.append(f"values_callable=lambda e: {callable_body}")
79
+ return f"sa.Enum({members}, {', '.join(options)})"
71
80
 
72
81
  return False # let alembic use its default rendering