simple-module-db 0.0.43__tar.gz → 0.0.45__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 (138) hide show
  1. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/PKG-INFO +3 -3
  2. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/pyproject.toml +3 -3
  3. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_bulk_audit_records.py +22 -4
  4. simple_module_db-0.0.45/simple_module_db/_sqlite_index_compare.py +97 -0
  5. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/audit.py +7 -4
  6. simple_module_db-0.0.45/simple_module_db/audit_redaction.py +71 -0
  7. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/audit_sinks.py +1 -1
  8. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/bulk_audit.py +3 -2
  9. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/data_compatibility.py +2 -13
  10. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/leases.py +3 -1
  11. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/listeners.py +8 -1
  12. simple_module_db-0.0.45/simple_module_db/migration_state.py +78 -0
  13. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/migrations.py +4 -0
  14. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/query_filter.py +1 -1
  15. simple_module_db-0.0.45/simple_module_db/query_stats.py +85 -0
  16. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/stored_settings.py +12 -0
  17. simple_module_db-0.0.45/tests/_alembic_project.py +46 -0
  18. simple_module_db-0.0.45/tests/test_db_credential_audit.py +168 -0
  19. simple_module_db-0.0.45/tests/test_db_credential_log_masking.py +16 -0
  20. simple_module_db-0.0.45/tests/test_db_migration_doctor.py +123 -0
  21. simple_module_db-0.0.45/tests/test_db_migration_state.py +74 -0
  22. simple_module_db-0.0.45/tests/test_db_query_stats.py +95 -0
  23. simple_module_db-0.0.45/tests/test_migrations_sqlite_index_compare.py +188 -0
  24. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/.gitignore +0 -0
  25. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/LICENSE +0 -0
  26. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/README.md +0 -0
  27. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/__init__.py +0 -0
  28. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_bulk_pk_update.py +0 -0
  29. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_core_joins.py +0 -0
  30. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_core_walk.py +0 -0
  31. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_engine_policies.py +0 -0
  32. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_entity_selectables.py +0 -0
  33. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_migration_render.py +0 -0
  34. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_outer_joins.py +0 -0
  35. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_persisted_owner.py +0 -0
  36. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/_secondary_scope.py +0 -0
  37. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/admission.py +0 -0
  38. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/base.py +0 -0
  39. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/bulk_audit_targets.py +0 -0
  40. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/bulk_guard.py +0 -0
  41. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/callbacks.py +0 -0
  42. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/core_scope.py +0 -0
  43. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/deps.py +0 -0
  44. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/engine_options.py +0 -0
  45. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/extensions.py +0 -0
  46. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/flush_guard.py +0 -0
  47. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/independent.py +0 -0
  48. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/insert_guard.py +0 -0
  49. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/insert_scope.py +0 -0
  50. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/migration_portability.py +0 -0
  51. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/mixins.py +0 -0
  52. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/model_registry.py +0 -0
  53. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/pagination.py +0 -0
  54. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/provider.py +0 -0
  55. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/py.typed +0 -0
  56. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/resource_policy.py +0 -0
  57. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/scope_predicates.py +0 -0
  58. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/search.py +0 -0
  59. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/session.py +0 -0
  60. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/tenancy.py +0 -0
  61. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/tenant_cleanup.py +0 -0
  62. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/transaction.py +0 -0
  63. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/types.py +0 -0
  64. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/user_directory_sql.py +0 -0
  65. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/simple_module_db/writes.py +0 -0
  66. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_audit_models.py +0 -0
  67. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_bulk_audit_support.py +0 -0
  68. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_core_scope_models.py +0 -0
  69. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_db_dml_scope_models.py +0 -0
  70. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_db_read_scope_models.py +0 -0
  71. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_db_shape_matrix.py +0 -0
  72. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/_models.py +0 -0
  73. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/conftest.py +0 -0
  74. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_audit.py +0 -0
  75. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_audit_per_engine.py +0 -0
  76. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_aware_datetime.py +0 -0
  77. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_base.py +0 -0
  78. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_aliased_join_text_scope.py +0 -0
  79. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_aliased_selectable_scope.py +0 -0
  80. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_audit_regressions.py +0 -0
  81. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_bulk_audit.py +0 -0
  82. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_bulk_audit_targets.py +0 -0
  83. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_connection_policy.py +0 -0
  84. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_core_full_setup_join.py +0 -0
  85. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_core_in_orm_select.py +0 -0
  86. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_core_join_scope.py +0 -0
  87. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_core_nested_scope.py +0 -0
  88. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_data_compatibility_doctor.py +0 -0
  89. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_dml_target_scope.py +0 -0
  90. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_doctor_session_filters.py +0 -0
  91. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_engine_options.py +0 -0
  92. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_engine_policy_resolution.py +0 -0
  93. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_extensions.py +0 -0
  94. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_extensions_pg.py +0 -0
  95. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_flush_persisted_owner.py +0 -0
  96. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_independent_checkpoint.py +0 -0
  97. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_insert_select_tenant.py +0 -0
  98. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_insert_value_subqueries.py +0 -0
  99. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_lease_lock_wait.py +0 -0
  100. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_listeners_attach.py +0 -0
  101. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_logging.py +0 -0
  102. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_migration_review_regressions.py +0 -0
  103. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_nested_dml_and_bulk_api.py +0 -0
  104. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_pagination.py +0 -0
  105. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_pagination_options.py +0 -0
  106. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_relationship_loader_scope.py +0 -0
  107. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_response_finalization.py +0 -0
  108. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_savepoint_callbacks.py +0 -0
  109. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_secondary_scope_execution.py +0 -0
  110. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_shape_matrix_dml.py +0 -0
  111. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_shape_matrix_joins.py +0 -0
  112. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_shape_matrix_selects.py +0 -0
  113. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_sqlite_admission_lock.py +0 -0
  114. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_sqlite_savepoint.py +0 -0
  115. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_sqlite_wal_switch.py +0 -0
  116. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_stored_settings.py +0 -0
  117. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_strict_insert_context.py +0 -0
  118. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_tenant_cleanup.py +0 -0
  119. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_tenant_upsert_guard.py +0 -0
  120. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_user_directory_sql.py +0 -0
  121. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_db_write_marks.py +0 -0
  122. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_default_tenant.py +0 -0
  123. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_independent_session.py +0 -0
  124. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_migration_portability.py +0 -0
  125. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_migrations.py +0 -0
  126. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_mixins.py +0 -0
  127. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_multi_tenancy.py +0 -0
  128. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_query_filter_outer_joins.py +0 -0
  129. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_query_filter_rel_outer_joins.py +0 -0
  130. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_query_filters.py +0 -0
  131. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_rollback_logging.py +0 -0
  132. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_session.py +0 -0
  133. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_soft_delete_shapes.py +0 -0
  134. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_tenant_dml.py +0 -0
  135. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_tenant_shapes.py +0 -0
  136. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_tenant_strict.py +0 -0
  137. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/tests/test_transaction.py +0 -0
  138. {simple_module_db-0.0.43 → simple_module_db-0.0.45}/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.43
3
+ Version: 0.0.45
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
@@ -22,10 +22,10 @@ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
22
22
  Classifier: Typing :: Typed
23
23
  Requires-Python: >=3.12
24
24
  Requires-Dist: aiosqlite<0.23,>=0.20
25
- Requires-Dist: alembic<2,>=1.14
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.43
28
+ Requires-Dist: simple-module-core==0.0.45
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.43"
3
+ version = "0.0.45"
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"
@@ -22,13 +22,13 @@ classifiers = [
22
22
  ]
23
23
  dependencies = [
24
24
  "aiosqlite>=0.20,<0.23",
25
- "alembic>=1.14,<2",
25
+ "alembic>=1.16.3,<2",
26
26
  "asyncpg>=0.30,<0.33",
27
27
  # psycopg2 is the *sync* Postgres driver Alembic uses for migrations.
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.43",
31
+ "simple_module_core==0.0.45",
32
32
  "sqlalchemy[asyncio]>=2.0.2,<3",
33
33
  "sqlmodel>=0.0.22,<0.1",
34
34
  ]
@@ -10,7 +10,8 @@ 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
12
 
13
- from simple_module_db.audit import AuditRecord, _serialize, format_pk
13
+ from simple_module_db.audit import AuditRecord, _excluded_fields, _serialize, format_pk
14
+ from simple_module_db.audit_redaction import model_for_audit, redact_changes, redact_entity_id
14
15
  from simple_module_db.query_filter import engine_policy
15
16
 
16
17
  logger = logging.getLogger("simple_module_db.bulk_audit")
@@ -29,8 +30,16 @@ _ACTIVE_KEY: Final = "_sm_bulk_audit_active"
29
30
  class _Ctx:
30
31
  """What one audited statement records, built before it runs."""
31
32
 
32
- def __init__(self, entity_type: str, action: str, changes: list[dict[str, Any]]) -> None:
33
+ def __init__(
34
+ self,
35
+ entity_type: str,
36
+ action: str,
37
+ changes: list[dict[str, Any]],
38
+ model: type | None = None,
39
+ ) -> None:
33
40
  self.entity_type = entity_type
41
+ # The statement's own class when known: a name lookup scans the registry.
42
+ self._model = model or model_for_audit(entity_type)
34
43
  self.action = action
35
44
  self.row_actions = [action]
36
45
  self.changes = changes
@@ -45,7 +54,11 @@ class _Ctx:
45
54
  ) -> AuditRecord:
46
55
  return AuditRecord(
47
56
  entity_type=self.entity_type,
48
- entity_id=entity_id,
57
+ entity_id=(
58
+ entity_id
59
+ if entity_id == SUMMARY_ENTITY_ID
60
+ else redact_entity_id(self._model, entity_id)
61
+ ),
49
62
  action=action or self.action,
50
63
  changes=self.changes if changes is None else changes,
51
64
  user_id=self.user_id,
@@ -113,6 +126,11 @@ def record_bulk_audit(
113
126
  return
114
127
  name = entity_type if isinstance(entity_type, str) else entity_type.__name__
115
128
  diff = [{"field": k, "new": _serialize(v)} for k, v in (changes or {}).items()]
116
- ctx = _Ctx(name, action, diff)
129
+ ctx = _Ctx(name, action, diff, entity_type if isinstance(entity_type, type) else None)
130
+ model = ctx._model
131
+ if model is not None:
132
+ ctx.changes = redact_changes(
133
+ model, [c for c in diff if c["field"] not in _excluded_fields(model)]
134
+ )
117
135
  keys = [SUMMARY_ENTITY_ID] if ids is None else [str(i) for i in ids]
118
136
  _deliver(sync, callback, [ctx.record(k) for k in keys])
@@ -0,0 +1,97 @@
1
+ """Index comparisons SQLite cannot make faithfully (GH #869).
2
+
3
+ SQLite reflects ``CREATE INDEX ... (tenant_id, created_at DESC, id)`` as three
4
+ plain columns. A model that wrote the ordered column as ``sa.text("created_at
5
+ DESC")`` or ``sa.desc("created_at")`` holds an expression there, and Alembic
6
+ compares the two element by element: every autogenerate on SQLite then writes a
7
+ drop and re-create of a correct index, and ``alembic check`` fails on a correct
8
+ schema. Postgres reflects the ordering, so it compares these faithfully.
9
+
10
+ :func:`differs_only_in_sqlite_ordering` recognises exactly that pair, so
11
+ ``make_include_object`` can skip it on SQLite. Anything else still reaches
12
+ Alembic: a different column list, a uniqueness change, or a real expression
13
+ such as ``lower(email)``. A change of ordering alone (``DESC`` to ``ASC``) is not
14
+ reported on SQLite, which cannot reflect ordering at all; the Postgres round
15
+ trip (``make migrations-roundtrip-pg``) is what catches it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import re
22
+
23
+ from alembic import context
24
+ from simple_module_core.diagnostics._expression_index import unwrap_ordering
25
+ from sqlalchemy import Index
26
+ from sqlalchemy.schema import SchemaItem
27
+ from sqlalchemy.sql.elements import ColumnClause, TextClause
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # One identifier, optionally double-quoted, then an optional ordering.
32
+ _ORDERED_COLUMN = re.compile(
33
+ r'\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))'
34
+ r"(?:\s+(?:ASC|DESC))?(?:\s+NULLS\s+(?:FIRST|LAST))?\s*",
35
+ re.IGNORECASE,
36
+ )
37
+
38
+
39
+ def _on_sqlite() -> bool:
40
+ """Whether the active Alembic migration context targets SQLite.
41
+
42
+ Outside a migration (no context configured) the answer is no, so the
43
+ caller never suppresses a comparison it cannot place.
44
+ """
45
+ try:
46
+ return context.get_context().dialect.name == "sqlite"
47
+ except Exception as exc:
48
+ logger.debug("No Alembic migration context, SQLite index guard off: %s", exc)
49
+ return False
50
+
51
+
52
+ def _element_name(element: object) -> tuple[str | None, bool]:
53
+ """``(column name, written as an expression)`` for one index element.
54
+
55
+ The name is ``None`` for a real expression, which never matches.
56
+ """
57
+ element = unwrap_ordering(element)
58
+ if isinstance(element, TextClause):
59
+ match = _ORDERED_COLUMN.fullmatch(element.text)
60
+ return (match[1] or match[2], True) if match else (None, True)
61
+ if isinstance(element, ColumnClause) and not element.is_literal:
62
+ return element.name, False
63
+ # ``sa.desc("col")`` wraps a textual label reference holding the bare name.
64
+ label = getattr(element, "element", None)
65
+ if type(element).__name__ == "_textual_label_reference" and isinstance(label, str):
66
+ return label, True
67
+ return None, False
68
+
69
+
70
+ def _is_partial(index: Index) -> bool:
71
+ """A partial index (``WHERE`` predicate), modelled or reflected."""
72
+ return any(
73
+ index.dialect_options[dialect].get("where") is not None
74
+ for dialect in ("sqlite", "postgresql")
75
+ )
76
+
77
+
78
+ def differs_only_in_sqlite_ordering(left: SchemaItem, right: SchemaItem | None) -> bool:
79
+ """True when two indexes are the same index as far as SQLite can tell.
80
+
81
+ Requires an active SQLite migration context, equal uniqueness, no partial
82
+ index (``WHERE`` predicate) on either side, the same
83
+ column names in the same order (compared case-insensitively, as SQLite
84
+ compares identifiers), and at least one element written as an expression
85
+ (otherwise Alembic's own comparison is already right).
86
+ """
87
+ if not isinstance(left, Index) or not isinstance(right, Index) or left.unique != right.unique:
88
+ return False
89
+ if _is_partial(left) or _is_partial(right):
90
+ # Only columns are compared here, so a changed predicate would be hidden.
91
+ return False
92
+ if not _on_sqlite():
93
+ return False
94
+ sides = [[_element_name(e) for e in index.expressions] for index in (left, right)]
95
+ names = [[name.casefold() if name else None for name, _ in side] for side in sides]
96
+ written_as_expression = any(is_expr for side in sides for _, is_expr in side)
97
+ return written_as_expression and None not in names[0] and names[0] == names[1]
@@ -23,6 +23,7 @@ from typing import Any
23
23
  from sqlalchemy import inspect as sa_inspect
24
24
  from sqlalchemy.orm import Session
25
25
 
26
+ from simple_module_db.audit_redaction import redact_changes, redact_entity_id
26
27
  from simple_module_db.mixins import SoftDeleteMixin
27
28
 
28
29
  # Fields injected by AuditMixin — always excluded from change diffs
@@ -97,8 +98,10 @@ def _entity_pk_str(obj: object) -> str:
97
98
  if identity is None:
98
99
  # Pre-flush: fall back to the mapper-level key attrs
99
100
  mapper = inspector.mapper
100
- return format_pk([getattr(obj, col.key) for col in mapper.primary_key])
101
- return format_pk(identity)
101
+ pk = format_pk([getattr(obj, col.key) for col in mapper.primary_key])
102
+ else:
103
+ pk = format_pk(identity)
104
+ return redact_entity_id(type(obj), pk)
102
105
 
103
106
 
104
107
  def _column_names(obj: object) -> list[str]:
@@ -128,7 +131,7 @@ def _column_diffs(obj: object, inspector: Any, excl: frozenset[str]) -> list[dic
128
131
  old_val = hist.deleted[0] if hist.deleted else None
129
132
  new_val = hist.added[0] if hist.added else None
130
133
  changes.append({"field": col_name, "old": _serialize(old_val), "new": _serialize(new_val)})
131
- return changes
134
+ return redact_changes(type(obj), changes, obj)
132
135
 
133
136
 
134
137
  # ---------------------------------------------------------------------------
@@ -182,7 +185,7 @@ def snapshot_changes(
182
185
  obj_ref=obj,
183
186
  entity_type=type(obj).__name__,
184
187
  action="created",
185
- changes=changes,
188
+ changes=redact_changes(type(obj), changes, obj),
186
189
  user_id=user_id,
187
190
  correlation_id=correlation_id,
188
191
  )
@@ -0,0 +1,71 @@
1
+ """Shared credential redaction for flush, statement and manual audit capture."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final
6
+
7
+ from sqlalchemy import inspect
8
+
9
+ AUDIT_REDACTED: Final = "[redacted]"
10
+
11
+
12
+ def model_for_audit(model: type | str) -> type | None:
13
+ """Accept a mapped class or its registered class name; None for unknown names."""
14
+ if isinstance(model, type):
15
+ return model
16
+ from simple_module_db.model_registry import classes_by_table
17
+
18
+ return next((cls for cls in classes_by_table.values() if cls.__name__ == model), None)
19
+
20
+
21
+ def redact_changes(
22
+ model: type, changes: list[dict[str, Any]], obj: object | None = None
23
+ ) -> list[dict[str, Any]]:
24
+ """Keep fields and diff shape, replacing credential values before delivery.
25
+
26
+ A row predicate receives both the current and pre-edit column values. With
27
+ no row (statement/manual capture) it receives None and must fail closed.
28
+ """
29
+ if not changes:
30
+ return changes
31
+ fields = set(getattr(model, "__audit_redact_fields__", ()))
32
+ predicate = getattr(model, "__audit_redact_row__", None)
33
+ if predicate is not None:
34
+ if obj is None:
35
+ fields.update(predicate(None))
36
+ else:
37
+ state = inspect(obj)
38
+ current: dict[str, Any] = {}
39
+ previous: dict[str, Any] = {}
40
+ for attr in state.mapper.column_attrs:
41
+ key = attr.key
42
+ value = current[key] = state.dict.get(key)
43
+ history = state.attrs[key].history
44
+ if history.has_changes():
45
+ previous[key] = history.deleted[0] if history.deleted else None
46
+ else:
47
+ previous[key] = value
48
+ fields.update(predicate(current))
49
+ if state.persistent:
50
+ fields.update(predicate(previous))
51
+ if not fields:
52
+ return changes
53
+ return [
54
+ {
55
+ k: AUDIT_REDACTED if c["field"] in fields and k in {"old", "new"} else v
56
+ for k, v in c.items()
57
+ }
58
+ for c in changes
59
+ ]
60
+
61
+
62
+ def pk_is_redacted(model: type | None) -> bool:
63
+ """True when a primary-key column of ``model`` is itself a redacted credential."""
64
+ fields = getattr(model, "__audit_redact_fields__", None)
65
+ if model is None or not fields:
66
+ return False
67
+ return any(col.key in fields for col in inspect(model).primary_key)
68
+
69
+
70
+ def redact_entity_id(model: type | None, entity_id: str) -> str:
71
+ return AUDIT_REDACTED if pk_is_redacted(model) else entity_id
@@ -7,7 +7,7 @@ the installed distributions instead: a module that stores audit records
7
7
  declares::
8
8
 
9
9
  [project.entry-points."simple_module.audit_sinks"]
10
- audit_log = "audit_log.capture:audit_callback"
10
+ audit_log = "audit_log.core.capture:audit_callback"
11
11
 
12
12
  and the worker binds the result to its engine with
13
13
  ``EngineTenancy(audit_callback=...)``. Neither side imports the other (#498).
@@ -52,6 +52,7 @@ from simple_module_db._bulk_audit_records import ( # noqa: F401 (re-exported)
52
52
  record_bulk_audit,
53
53
  )
54
54
  from simple_module_db.audit import _excluded_fields, format_pk
55
+ from simple_module_db.audit_redaction import redact_changes
55
56
  from simple_module_db.bulk_audit_targets import _is_set, _shown, _targets
56
57
  from simple_module_db.query_filter import engine_policy
57
58
  from simple_module_db.tenancy import ALL_TENANTS_OPTION
@@ -85,7 +86,7 @@ def _plan(execute_state: ORMExecuteState, cls: type) -> _Ctx | None:
85
86
  """The record shape for this statement, or ``None`` when nothing is audited."""
86
87
  name = cls.__name__
87
88
  if execute_state.is_delete:
88
- return _Ctx(name, ACTION_BULK_DELETED, [])
89
+ return _Ctx(name, ACTION_BULK_DELETED, [], cls)
89
90
  rows, many = _targets(execute_state, cls)
90
91
  default = ACTION_BULK_INSERTED if execute_state.is_insert else ACTION_BULK_UPDATED
91
92
  # The soft-delete flag picks a row's action; it is never a change, and
@@ -112,7 +113,7 @@ def _plan(execute_state: ORMExecuteState, cls: type) -> _Ctx | None:
112
113
  changes = [{"field": k} for k in kept]
113
114
  else:
114
115
  changes = [{"field": k, "new": _shown(rows[0][k])} for k in kept]
115
- ctx = _Ctx(name, actions[0] if actions else default, changes)
116
+ ctx = _Ctx(name, actions[0] if actions else default, redact_changes(cls, changes), cls)
116
117
  ctx.row_actions = actions or [default]
117
118
  return ctx
118
119
 
@@ -1,7 +1,6 @@
1
1
  """Database-backed Doctor diagnostics, separate from core's static checks."""
2
2
 
3
3
  from collections.abc import Sequence
4
- from pathlib import Path
5
4
 
6
5
  from alembic.runtime.migration import MigrationContext
7
6
  from simple_module_core.data_compatibility import collect_data_compatibility
@@ -9,6 +8,7 @@ from simple_module_core.diagnostics import Diagnostic, DiagnosticLevel
9
8
  from simple_module_core.module import ModuleBase
10
9
 
11
10
  from simple_module_db.listeners import register_listeners
11
+ from simple_module_db.migration_state import database_exists
12
12
  from simple_module_db.session import init_db
13
13
 
14
14
  DATA_COMPATIBILITY_CODE = "SM033"
@@ -19,7 +19,7 @@ async def database_compatibility_diagnostics(
19
19
  ) -> list[Diagnostic]:
20
20
  state = None
21
21
  try:
22
- if not _database_exists(database_url):
22
+ if not database_exists(database_url):
23
23
  return [] # Nothing migrated yet; opening it would create an empty SQLite file.
24
24
  # Read-only diagnostics: never switch a legacy SQLite file to WAL.
25
25
  state = init_db(database_url, sqlite_wal=False)
@@ -80,14 +80,3 @@ def _problem(level: DiagnosticLevel, message: str) -> Diagnostic:
80
80
  suggestion="Check database connectivity and apply pending host schema migrations, "
81
81
  "then rerun doctor.",
82
82
  )
83
-
84
-
85
- def _database_exists(database_url: str) -> bool:
86
- """False for a SQLite file that isn't there yet; every other URL is tried."""
87
- from sqlalchemy.engine import make_url
88
-
89
- url = make_url(database_url)
90
- if not url.get_backend_name().startswith("sqlite"):
91
- return True
92
- database = url.database or ""
93
- return database in ("", ":memory:") or Path(database).exists()
@@ -19,7 +19,7 @@ import asyncio
19
19
  import contextlib
20
20
  from collections.abc import AsyncGenerator
21
21
  from datetime import UTC, datetime, timedelta
22
- from typing import Any, Final
22
+ from typing import Any, ClassVar, Final
23
23
 
24
24
  from sqlalchemy import and_, func, select, text, update
25
25
  from sqlalchemy.dialects import postgresql, sqlite
@@ -48,6 +48,8 @@ Base = create_module_base(LEASE_METADATA_NAME)
48
48
  class LeaseRow(Base, table=True): # ty: ignore[unsupported-base]
49
49
  """One lease slot. ``holder`` is the owner's token, ``""`` when never held."""
50
50
 
51
+ __audit_redact_fields__: ClassVar[set[str]] = {"holder"}
52
+
51
53
  __tablename__ = TABLE_LEASE
52
54
 
53
55
  name: str = Field(primary_key=True, max_length=NAME_MAX_LENGTH)
@@ -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.audit_redaction import AUDIT_REDACTED, pk_is_redacted
16
17
  from simple_module_db.bulk_audit import audit_statement
17
18
  from simple_module_db.bulk_guard import install_bulk_guard
18
19
  from simple_module_db.flush_guard import guard_flush
@@ -76,8 +77,14 @@ def _entity_label(obj: object) -> str:
76
77
 
77
78
 
78
79
  def _entity_pk(obj: object) -> object:
79
- """Return the primary key value(s) if available, else None."""
80
+ """Return the primary key value(s) if available, else None.
81
+
82
+ A primary key that is itself a credential (a session or refresh token) is
83
+ masked: this value goes to the application log.
84
+ """
80
85
  try:
86
+ if pk_is_redacted(type(obj)):
87
+ return AUDIT_REDACTED
81
88
  inspector = sa_inspect(obj)
82
89
  if inspector is None:
83
90
  return None
@@ -0,0 +1,78 @@
1
+ """Read a database's Alembic state without a host app (Doctor's SM010/SM011, #895)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from alembic.config import Config
9
+ from alembic.runtime.migration import MigrationContext
10
+ from alembic.script import ScriptDirectory
11
+ from sqlalchemy import inspect
12
+ from sqlalchemy.engine import make_url
13
+ from sqlalchemy.ext.asyncio import create_async_engine
14
+ from sqlalchemy.pool import NullPool
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class MigrationState:
19
+ """What the migrations define (``heads``) and what the database holds."""
20
+
21
+ heads: frozenset[str]
22
+ #: ``alembic_version`` rows; empty for a database that was never migrated.
23
+ current: frozenset[str]
24
+ tables: frozenset[str]
25
+
26
+
27
+ def database_exists(database_url: str) -> bool:
28
+ """False for a SQLite file that isn't there yet; every other URL is tried.
29
+
30
+ A URI-mode path (``file:...?uri=true``) is checked by the file it names,
31
+ since opening a missing one in the default ``rwc`` mode would create it.
32
+ """
33
+ url = make_url(database_url)
34
+ if not url.get_backend_name().startswith("sqlite"):
35
+ return True
36
+ database = url.database or ""
37
+ if database.startswith("file:"):
38
+ if url.query.get("mode") == "memory":
39
+ return True
40
+ database = database.removeprefix("file:").split("?", 1)[0]
41
+ return database in ("", ":memory:") or Path(database).exists()
42
+
43
+
44
+ def _heads(alembic_ini: Path) -> frozenset[str]:
45
+ # An ini that exists but cannot be loaded (bad script_location, a broken
46
+ # revision) raises: the caller reports it rather than skipping silently.
47
+ if not alembic_ini.is_file():
48
+ return frozenset()
49
+ return frozenset(ScriptDirectory.from_config(Config(str(alembic_ini))).get_heads())
50
+
51
+
52
+ async def read_migration_state(database_url: str, alembic_ini: str | Path) -> MigrationState | None:
53
+ """The heads in *alembic_ini* beside the current revisions and tables of the database.
54
+
55
+ ``None`` when there is no ``alembic.ini`` or it defines no revisions: there
56
+ is nothing to compare against. An ini Alembic cannot load raises. A SQLite
57
+ file that does not exist reads as empty rather than being opened, which
58
+ would create it. Connection errors propagate; their text can carry
59
+ credentials, so callers must not echo it.
60
+ """
61
+ heads = _heads(Path(alembic_ini))
62
+ if not heads:
63
+ return None
64
+ if not database_exists(database_url):
65
+ return MigrationState(heads=heads, current=frozenset(), tables=frozenset())
66
+
67
+ def _read(sync_conn) -> tuple[frozenset[str], frozenset[str]]:
68
+ # Plural, like the boot check: a branching history keeps one row per branch.
69
+ current = MigrationContext.configure(sync_conn).get_current_heads()
70
+ return frozenset(current), frozenset(inspect(sync_conn).get_table_names())
71
+
72
+ engine = create_async_engine(database_url, poolclass=NullPool)
73
+ try:
74
+ async with engine.connect() as conn:
75
+ current, tables = await conn.run_sync(_read)
76
+ finally:
77
+ await engine.dispose()
78
+ return MigrationState(heads=heads, current=current, tables=tables)
@@ -28,6 +28,7 @@ from sqlalchemy.exc import NoReferenceError
28
28
  from sqlalchemy.schema import SchemaItem
29
29
 
30
30
  from simple_module_db._migration_render import render_item # noqa: F401 (re-exported)
31
+ from simple_module_db._sqlite_index_compare import differs_only_in_sqlite_ordering
31
32
  from simple_module_db.base import all_module_bases
32
33
  from simple_module_db.extensions import ( # noqa: F401 (ensure_db_extensions re-exported)
33
34
  ensure_db_extensions,
@@ -147,6 +148,9 @@ def make_include_object(
147
148
  ) -> bool:
148
149
  if type_ == "table":
149
150
  return name in allowlist
151
+ if type_ == "index" and differs_only_in_sqlite_ordering(object, compare_to):
152
+ # SQLite reflects ``created_at DESC`` as a plain column (GH #869).
153
+ return False
150
154
  if (
151
155
  ignore_unmodeled_fks
152
156
  and type_ == "foreign_key_constraint"
@@ -46,7 +46,7 @@ from simple_module_db.tenancy import (
46
46
  )
47
47
 
48
48
  # ``_engine_policy`` (imported above) is re-exported: the per-engine policy map lives in
49
- # ``_engine_policies``; modules/background_tasks/tests/test_worker_tenancy.py reads it here.
49
+ # ``_engine_policies``; the background_tasks worker tenancy test reads it here.
50
50
 
51
51
 
52
52
  class EngineTenancy:
@@ -0,0 +1,85 @@
1
+ """Per-request SQL statement counting.
2
+
3
+ Development hosts install this on their engine and expose the totals in a
4
+ ``Server-Timing`` header (see ``simple_module_hosting._server_timing``), so a
5
+ page that issues one query per row shows up in the browser's network panel and
6
+ in the page-perf audit instead of only under load.
7
+
8
+ Counting is opt-in twice over: :func:`install_query_stats` adds the engine
9
+ listeners, and only code inside :func:`track_queries` is counted. Statements
10
+ run outside a tracked block (startup, background work) cost one ContextVar
11
+ read each.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from collections.abc import Generator
18
+ from contextlib import contextmanager
19
+ from contextvars import ContextVar
20
+ from dataclasses import dataclass
21
+
22
+ from sqlalchemy import event
23
+ from sqlalchemy.ext.asyncio import AsyncEngine
24
+
25
+ __all__ = ["QueryStats", "install_query_stats", "track_queries"]
26
+
27
+ _START_KEY = "_sm_query_started"
28
+ _INSTALLED_FLAG = "_sm_query_stats_installed"
29
+
30
+
31
+ @dataclass(slots=True)
32
+ class QueryStats:
33
+ """Statements executed inside one :func:`track_queries` block."""
34
+
35
+ count: int = 0
36
+ seconds: float = 0.0
37
+ active: bool = True
38
+
39
+
40
+ _current: ContextVar[QueryStats | None] = ContextVar("sm_query_stats", default=None)
41
+
42
+
43
+ def _before(conn, cursor, statement, parameters, context, executemany) -> None:
44
+ stats = _current.get()
45
+ if stats is not None and stats.active and context is not None:
46
+ setattr(context, _START_KEY, time.perf_counter())
47
+
48
+
49
+ def _after(conn, cursor, statement, parameters, context, executemany) -> None:
50
+ stats = _current.get()
51
+ if stats is None or not stats.active:
52
+ return
53
+ stats.count += 1
54
+ started = getattr(context, _START_KEY, None) if context is not None else None
55
+ if started is not None:
56
+ stats.seconds += time.perf_counter() - started
57
+
58
+
59
+ def install_query_stats(engine: AsyncEngine) -> None:
60
+ """Count statements on *engine* for any :func:`track_queries` block.
61
+
62
+ Idempotent per engine.
63
+ """
64
+ sync_engine = engine.sync_engine
65
+ if getattr(sync_engine, _INSTALLED_FLAG, False):
66
+ return
67
+ event.listen(sync_engine, "before_cursor_execute", _before)
68
+ event.listen(sync_engine, "after_cursor_execute", _after)
69
+ setattr(sync_engine, _INSTALLED_FLAG, True)
70
+
71
+
72
+ @contextmanager
73
+ def track_queries() -> Generator[QueryStats]:
74
+ """Count the statements run by this task (and tasks it spawns) until exit.
75
+
76
+ The stats object is shared by reference, so work SQLAlchemy runs in a
77
+ greenlet or a child task still lands in the same totals.
78
+ """
79
+ stats = QueryStats()
80
+ token = _current.set(stats)
81
+ try:
82
+ yield stats
83
+ finally:
84
+ stats.active = False
85
+ _current.reset(token)
@@ -16,6 +16,7 @@ from collections.abc import Iterable
16
16
  from typing import Final
17
17
 
18
18
  from pydantic_settings import BaseSettings
19
+ from simple_module_core.secret_fields import conceals_secret
19
20
  from simple_module_core.settings_hydrate import build_settings
20
21
  from sqlalchemy import Select, UniqueConstraint, inspect, select
21
22
  from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession
@@ -84,6 +85,17 @@ class Setting(Base, AuditMixin, table=True): # ty: ignore[unsupported-base]
84
85
  inputs that don't parse.
85
86
  """
86
87
 
88
+ @staticmethod
89
+ def __audit_redact_row__(row: dict | None) -> set[str]:
90
+ # Fail closed: no row (bulk/manual capture) or a partly loaded one hides the value.
91
+ if (
92
+ row is None
93
+ or any(row.get(k) is None for k in (COL_KEY, COL_VALUE, COL_VALUE_TYPE))
94
+ or conceals_secret(row[COL_KEY], row[COL_VALUE], row[COL_VALUE_TYPE])
95
+ ):
96
+ return {COL_VALUE}
97
+ return set()
98
+
87
99
  __tablename__ = TABLE_SETTING
88
100
  __table_args__ = (UniqueConstraint(COL_SCOPE, COL_SCOPE_ID, COL_KEY, name=UQ_SCOPE_KEY),)
89
101