simple-module-db 0.0.44__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.44 → simple_module_db-0.0.45}/PKG-INFO +3 -3
  2. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/pyproject.toml +3 -3
  3. simple_module_db-0.0.45/simple_module_db/_sqlite_index_compare.py +97 -0
  4. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/data_compatibility.py +2 -13
  5. simple_module_db-0.0.45/simple_module_db/migration_state.py +78 -0
  6. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/migrations.py +4 -0
  7. simple_module_db-0.0.45/tests/_alembic_project.py +46 -0
  8. simple_module_db-0.0.45/tests/test_db_migration_doctor.py +123 -0
  9. simple_module_db-0.0.45/tests/test_db_migration_state.py +74 -0
  10. simple_module_db-0.0.45/tests/test_migrations_sqlite_index_compare.py +188 -0
  11. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/.gitignore +0 -0
  12. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/LICENSE +0 -0
  13. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/README.md +0 -0
  14. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/__init__.py +0 -0
  15. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_bulk_audit_records.py +0 -0
  16. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_bulk_pk_update.py +0 -0
  17. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_core_joins.py +0 -0
  18. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_core_walk.py +0 -0
  19. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_engine_policies.py +0 -0
  20. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_entity_selectables.py +0 -0
  21. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_migration_render.py +0 -0
  22. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_outer_joins.py +0 -0
  23. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_persisted_owner.py +0 -0
  24. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/_secondary_scope.py +0 -0
  25. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/admission.py +0 -0
  26. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/audit.py +0 -0
  27. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/audit_redaction.py +0 -0
  28. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/audit_sinks.py +0 -0
  29. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/base.py +0 -0
  30. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/bulk_audit.py +0 -0
  31. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/bulk_audit_targets.py +0 -0
  32. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/bulk_guard.py +0 -0
  33. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/callbacks.py +0 -0
  34. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/core_scope.py +0 -0
  35. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/deps.py +0 -0
  36. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/engine_options.py +0 -0
  37. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/extensions.py +0 -0
  38. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/flush_guard.py +0 -0
  39. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/independent.py +0 -0
  40. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/insert_guard.py +0 -0
  41. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/insert_scope.py +0 -0
  42. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/leases.py +0 -0
  43. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/listeners.py +0 -0
  44. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/migration_portability.py +0 -0
  45. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/mixins.py +0 -0
  46. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/model_registry.py +0 -0
  47. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/pagination.py +0 -0
  48. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/provider.py +0 -0
  49. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/py.typed +0 -0
  50. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/query_filter.py +0 -0
  51. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/query_stats.py +0 -0
  52. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/resource_policy.py +0 -0
  53. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/scope_predicates.py +0 -0
  54. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/search.py +0 -0
  55. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/session.py +0 -0
  56. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/stored_settings.py +0 -0
  57. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/tenancy.py +0 -0
  58. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/tenant_cleanup.py +0 -0
  59. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/transaction.py +0 -0
  60. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/types.py +0 -0
  61. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/user_directory_sql.py +0 -0
  62. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/simple_module_db/writes.py +0 -0
  63. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_audit_models.py +0 -0
  64. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_bulk_audit_support.py +0 -0
  65. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_core_scope_models.py +0 -0
  66. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_db_dml_scope_models.py +0 -0
  67. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_db_read_scope_models.py +0 -0
  68. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_db_shape_matrix.py +0 -0
  69. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/_models.py +0 -0
  70. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/conftest.py +0 -0
  71. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_audit.py +0 -0
  72. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_audit_per_engine.py +0 -0
  73. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_aware_datetime.py +0 -0
  74. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_base.py +0 -0
  75. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_aliased_join_text_scope.py +0 -0
  76. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_aliased_selectable_scope.py +0 -0
  77. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_audit_regressions.py +0 -0
  78. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_bulk_audit.py +0 -0
  79. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_bulk_audit_targets.py +0 -0
  80. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_connection_policy.py +0 -0
  81. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_core_full_setup_join.py +0 -0
  82. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_core_in_orm_select.py +0 -0
  83. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_core_join_scope.py +0 -0
  84. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_core_nested_scope.py +0 -0
  85. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_credential_audit.py +0 -0
  86. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_credential_log_masking.py +0 -0
  87. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_data_compatibility_doctor.py +0 -0
  88. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_dml_target_scope.py +0 -0
  89. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_doctor_session_filters.py +0 -0
  90. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_engine_options.py +0 -0
  91. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_engine_policy_resolution.py +0 -0
  92. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_extensions.py +0 -0
  93. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_extensions_pg.py +0 -0
  94. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_flush_persisted_owner.py +0 -0
  95. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_independent_checkpoint.py +0 -0
  96. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_insert_select_tenant.py +0 -0
  97. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_insert_value_subqueries.py +0 -0
  98. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_lease_lock_wait.py +0 -0
  99. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_listeners_attach.py +0 -0
  100. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_logging.py +0 -0
  101. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_migration_review_regressions.py +0 -0
  102. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_nested_dml_and_bulk_api.py +0 -0
  103. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_pagination.py +0 -0
  104. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_pagination_options.py +0 -0
  105. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_query_stats.py +0 -0
  106. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_relationship_loader_scope.py +0 -0
  107. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_response_finalization.py +0 -0
  108. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_savepoint_callbacks.py +0 -0
  109. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_secondary_scope_execution.py +0 -0
  110. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_shape_matrix_dml.py +0 -0
  111. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_shape_matrix_joins.py +0 -0
  112. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_shape_matrix_selects.py +0 -0
  113. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_sqlite_admission_lock.py +0 -0
  114. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_sqlite_savepoint.py +0 -0
  115. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_sqlite_wal_switch.py +0 -0
  116. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_stored_settings.py +0 -0
  117. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_strict_insert_context.py +0 -0
  118. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_tenant_cleanup.py +0 -0
  119. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_tenant_upsert_guard.py +0 -0
  120. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_user_directory_sql.py +0 -0
  121. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_db_write_marks.py +0 -0
  122. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_default_tenant.py +0 -0
  123. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_independent_session.py +0 -0
  124. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_migration_portability.py +0 -0
  125. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_migrations.py +0 -0
  126. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_mixins.py +0 -0
  127. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_multi_tenancy.py +0 -0
  128. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_query_filter_outer_joins.py +0 -0
  129. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_query_filter_rel_outer_joins.py +0 -0
  130. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_query_filters.py +0 -0
  131. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_rollback_logging.py +0 -0
  132. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_session.py +0 -0
  133. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_soft_delete_shapes.py +0 -0
  134. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_tenant_dml.py +0 -0
  135. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_tenant_shapes.py +0 -0
  136. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_tenant_strict.py +0 -0
  137. {simple_module_db-0.0.44 → simple_module_db-0.0.45}/tests/test_transaction.py +0 -0
  138. {simple_module_db-0.0.44 → 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.44
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.44
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.44"
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.44",
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
  ]
@@ -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]
@@ -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()
@@ -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"
@@ -0,0 +1,46 @@
1
+ """A throwaway Alembic project and SQLite database for the migration-state tests."""
2
+
3
+ from pathlib import Path
4
+
5
+ import sqlalchemy as sa
6
+
7
+ _REVISION = """revision = "{rev}"
8
+ down_revision = {down}
9
+ branch_labels = None
10
+ depends_on = None
11
+
12
+
13
+ def upgrade():
14
+ pass
15
+
16
+
17
+ def downgrade():
18
+ pass
19
+ """
20
+
21
+
22
+ def write_alembic_project(root: Path, chain: list[str]) -> Path:
23
+ """An ``alembic.ini`` over the ``"rev:down_revision"`` entries in *chain*.
24
+
25
+ ``down_revision`` is empty for a root, so a test can build several heads
26
+ without a real ``env.py``.
27
+ """
28
+ versions = root / "migrations" / "versions"
29
+ versions.mkdir(parents=True)
30
+ for entry in chain:
31
+ rev, _, down = entry.partition(":")
32
+ (versions / f"{rev}.py").write_text(
33
+ _REVISION.format(rev=rev, down=repr(down) if down else "None")
34
+ )
35
+ ini = root / "alembic.ini"
36
+ ini.write_text("[alembic]\nscript_location = %(here)s/migrations\n")
37
+ return ini
38
+
39
+
40
+ def sqlite_database(path: Path, *statements: str) -> str:
41
+ engine = sa.create_engine(f"sqlite:///{path}")
42
+ with engine.begin() as conn:
43
+ for statement in statements:
44
+ conn.execute(sa.text(statement))
45
+ engine.dispose()
46
+ return f"sqlite+aiosqlite:///{path}"
@@ -0,0 +1,123 @@
1
+ """``make doctor`` reports SM010 and SM011 from the database it points at (#895)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from _alembic_project import sqlite_database, write_alembic_project
7
+ from simple_module_core import ModuleBase, ModuleMeta, _migration_doctor
8
+ from simple_module_core import __main__ as doctor
9
+
10
+ _STAMP = "CREATE TABLE alembic_version (version_num VARCHAR(32))"
11
+
12
+
13
+ class _Module(ModuleBase):
14
+ meta = ModuleMeta(name="Orders")
15
+
16
+
17
+ @pytest.fixture
18
+ def run_doctor(tmp_path, monkeypatch, capsys):
19
+ """Run ``main()`` over one module declaring ``orders_order`` and ``orders_line``."""
20
+ monkeypatch.setattr(doctor, "discover_modules", lambda strict: [_Module()])
21
+ monkeypatch.setattr(doctor, "find_env_file", lambda: tmp_path / ".env")
22
+ monkeypatch.setattr(doctor, "parse_dotenv", dict)
23
+ monkeypatch.setattr(doctor, "run_diagnostics", lambda *a, **kw: [])
24
+ monkeypatch.setattr(
25
+ _migration_doctor, "module_table_names", lambda modules: {"orders_order", "orders_line"}
26
+ )
27
+
28
+ def run(url: str) -> tuple[int, str]:
29
+ monkeypatch.setenv("SM_DATABASE_URL", url)
30
+ code = doctor.main()
31
+ return code, capsys.readouterr().err
32
+
33
+ return run
34
+
35
+
36
+ def test_db_doctor_reports_a_table_no_migration_creates(tmp_path, run_doctor):
37
+ write_alembic_project(tmp_path, ["a:", "b:"])
38
+ url = sqlite_database(
39
+ tmp_path / "app.db",
40
+ _STAMP,
41
+ "INSERT INTO alembic_version VALUES ('a'), ('b')",
42
+ "CREATE TABLE orders_order (id INTEGER)",
43
+ )
44
+
45
+ code, err = run_doctor(url)
46
+
47
+ assert code == 0
48
+ assert "SM011" in err
49
+ assert "orders_line" in err
50
+ assert "orders_order" not in err
51
+ assert "SM010" not in err
52
+
53
+
54
+ def test_db_doctor_fails_on_a_database_behind_head(tmp_path, run_doctor):
55
+ # The CLI's fallback location: host/alembic.ini under the project root.
56
+ write_alembic_project(tmp_path / "host", ["a:", "a2:a", "b:"])
57
+ url = sqlite_database(
58
+ tmp_path / "app.db", _STAMP, "INSERT INTO alembic_version VALUES ('a'), ('b')"
59
+ )
60
+
61
+ code, err = run_doctor(url)
62
+
63
+ assert code == 1
64
+ assert "SM010" in err
65
+ assert "missing heads 'a2'" in err
66
+ # Behind head the table may only be in a pending revision.
67
+ assert "SM011" not in err
68
+
69
+
70
+ def test_db_doctor_warns_on_a_missing_database(tmp_path, run_doctor):
71
+ write_alembic_project(tmp_path, ["a:"])
72
+ path = tmp_path / "app.db"
73
+
74
+ code, err = run_doctor(f"sqlite+aiosqlite:///{path}")
75
+
76
+ assert code == 0
77
+ assert "SM010" in err
78
+ assert "never been migrated" in err
79
+ assert not path.exists()
80
+
81
+
82
+ def test_db_doctor_warns_on_an_unreadable_database(tmp_path, run_doctor):
83
+ write_alembic_project(tmp_path, ["a:"])
84
+
85
+ # A directory exists but cannot be opened as a SQLite database.
86
+ code, err = run_doctor(f"sqlite+aiosqlite:///{tmp_path}")
87
+
88
+ assert code == 0
89
+ assert "SM010" in err
90
+ assert "could not read the migration state" in err.lower()
91
+
92
+
93
+ def test_db_doctor_skips_without_an_alembic_project(tmp_path, run_doctor):
94
+ code, err = run_doctor(f"sqlite+aiosqlite:///{tmp_path / 'app.db'}")
95
+
96
+ assert code == 0
97
+ assert "SM010" not in err
98
+ assert "SM011" not in err
99
+
100
+
101
+ def test_db_doctor_anchors_a_relative_sqlite_url_at_the_project_root(
102
+ tmp_path, monkeypatch, run_doctor
103
+ ):
104
+ # The app resolves ./app.db against the project root, not the cwd; doctor must too.
105
+ write_alembic_project(tmp_path, ["a:"])
106
+ sqlite_database(tmp_path / "app.db", _STAMP, "INSERT INTO alembic_version VALUES ('a')")
107
+ (tmp_path / "host").mkdir()
108
+ monkeypatch.chdir(tmp_path / "host")
109
+
110
+ code, err = run_doctor("sqlite+aiosqlite:///./app.db")
111
+
112
+ assert code == 0
113
+ assert "never been migrated" not in err
114
+ assert not (tmp_path / "host" / "app.db").exists()
115
+
116
+
117
+ def test_db_doctor_warns_on_a_broken_alembic_ini(tmp_path, run_doctor):
118
+ (tmp_path / "alembic.ini").write_text("[alembic]\nscript_location = %(here)s/missing\n")
119
+
120
+ code, err = run_doctor(f"sqlite+aiosqlite:///{tmp_path / 'app.db'}")
121
+
122
+ assert code == 0
123
+ assert "could not read the migration state" in err.lower()
@@ -0,0 +1,74 @@
1
+ """Doctor reads the migration state from the database it points at (#895)."""
2
+
3
+ from _alembic_project import sqlite_database, write_alembic_project
4
+ from simple_module_db.migration_state import read_migration_state
5
+
6
+
7
+ async def test_db_migration_state_none_without_an_ini(tmp_path):
8
+ assert await read_migration_state("sqlite+aiosqlite://", tmp_path / "alembic.ini") is None
9
+
10
+
11
+ async def test_db_migration_state_missing_file_is_not_created(tmp_path):
12
+ ini = write_alembic_project(tmp_path, ["a:", "b:"])
13
+ path = tmp_path / "app.db"
14
+
15
+ state = await read_migration_state(f"sqlite+aiosqlite:///{path}", ini)
16
+
17
+ assert state is not None
18
+ assert state.heads == {"a", "b"}
19
+ assert state.current == set()
20
+ assert state.tables == set()
21
+ assert not path.exists()
22
+
23
+
24
+ async def test_db_migration_state_reads_an_unstamped_database(tmp_path):
25
+ ini = write_alembic_project(tmp_path, ["a:"])
26
+ url = sqlite_database(tmp_path / "app.db", "CREATE TABLE orders_order (id INTEGER)")
27
+
28
+ state = await read_migration_state(url, ini)
29
+
30
+ assert state is not None
31
+ assert state.current == set()
32
+ assert state.tables == {"orders_order"}
33
+
34
+
35
+ async def test_db_migration_state_reads_current_heads(tmp_path):
36
+ ini = write_alembic_project(tmp_path, ["a:", "a2:a", "b:"])
37
+ url = sqlite_database(
38
+ tmp_path / "app.db",
39
+ "CREATE TABLE alembic_version (version_num VARCHAR(32))",
40
+ "INSERT INTO alembic_version VALUES ('a'), ('b')",
41
+ )
42
+
43
+ state = await read_migration_state(url, ini)
44
+
45
+ assert state is not None
46
+ assert state.heads == {"a2", "b"}
47
+ assert state.current == {"a", "b"}
48
+ assert "alembic_version" in state.tables
49
+
50
+
51
+ async def test_db_migration_state_reads_a_uri_mode_database(tmp_path):
52
+ ini = write_alembic_project(tmp_path, ["a:"])
53
+ path = tmp_path / "app.db"
54
+ sqlite_database(
55
+ path,
56
+ "CREATE TABLE alembic_version (version_num VARCHAR(32))",
57
+ "INSERT INTO alembic_version VALUES ('a')",
58
+ )
59
+
60
+ state = await read_migration_state(f"sqlite+aiosqlite:///file:{path}?mode=ro&uri=true", ini)
61
+
62
+ assert state is not None
63
+ assert state.current == {"a"}
64
+
65
+
66
+ async def test_db_migration_state_missing_uri_mode_file_is_not_created(tmp_path):
67
+ ini = write_alembic_project(tmp_path, ["a:"])
68
+ path = tmp_path / "app.db"
69
+
70
+ state = await read_migration_state(f"sqlite+aiosqlite:///file:{path}?uri=true", ini)
71
+
72
+ assert state is not None
73
+ assert state.current == set()
74
+ assert not path.exists()
@@ -0,0 +1,188 @@
1
+ """SQLite loses text index ordering on reflection, but real changes must survive (GH #869)."""
2
+
3
+ from types import SimpleNamespace
4
+
5
+ import pytest
6
+ import sqlalchemy as sa
7
+ from alembic import context
8
+ from alembic.autogenerate import compare_metadata
9
+ from alembic.config import Config
10
+ from alembic.runtime.environment import EnvironmentContext
11
+ from simple_module_db.migrations import make_include_object
12
+ from sqlalchemy.dialects import postgresql
13
+
14
+ pytestmark = [
15
+ pytest.mark.filterwarnings("ignore:Skipped unsupported reflection.*:sqlalchemy.exc.SAWarning"),
16
+ pytest.mark.filterwarnings("ignore:autogenerate skipping metadata-specified.*:UserWarning"),
17
+ ]
18
+
19
+
20
+ def _metadata(element="created_at DESC", *, first="tenant_id", unique=False):
21
+ """``element`` is text for ``sa.text()``, or an already-built SQL element."""
22
+ meta = sa.MetaData()
23
+ sa.Table(
24
+ "record",
25
+ meta,
26
+ sa.Column("id", sa.Integer, primary_key=True),
27
+ sa.Column("tenant_id", sa.Integer),
28
+ sa.Column("created_at", sa.Integer),
29
+ sa.Column("email", sa.String),
30
+ sa.Index(
31
+ "ix",
32
+ first,
33
+ sa.text(element) if isinstance(element, str) else element,
34
+ "id",
35
+ unique=unique,
36
+ ),
37
+ )
38
+ return meta
39
+
40
+
41
+ def _index(meta):
42
+ return next(iter(meta.tables["record"].indexes))
43
+
44
+
45
+ @pytest.fixture
46
+ def connection():
47
+ engine = sa.create_engine("sqlite://")
48
+ try:
49
+ with engine.connect() as conn:
50
+ yield conn
51
+ finally:
52
+ engine.dispose()
53
+
54
+
55
+ def _environment(connection, meta, *, filtered=True):
56
+ config = Config()
57
+ config.set_main_option("script_location", "host/migrations")
58
+ env = EnvironmentContext(config, None)
59
+ options = {"include_object": make_include_object(meta)} if filtered else {}
60
+ env.configure(connection=connection, target_metadata=meta, **options)
61
+ return env
62
+
63
+
64
+ @pytest.mark.parametrize(
65
+ "element", ["created_at DESC", '"created_at" ASC', "created_at", "Created_At DESC"]
66
+ )
67
+ def test_sqlite_text_index_compares_clean(connection, element):
68
+ meta = _metadata(element)
69
+ meta.create_all(connection)
70
+ with _environment(connection, meta) as env:
71
+ assert compare_metadata(env.get_context(), meta) == []
72
+
73
+
74
+ @pytest.mark.parametrize(
75
+ "build",
76
+ [lambda: sa.desc("created_at"), lambda: sa.desc(sa.column("created_at"))],
77
+ ids=["label", "column"],
78
+ )
79
+ def test_sqlite_desc_index_compares_clean(connection, build):
80
+ """``sa.desc("col")`` is a label expression; ``sa.desc(sa.column("col"))`` a column."""
81
+ meta = _metadata(build())
82
+ meta.create_all(connection)
83
+ with _environment(connection, meta) as env:
84
+ assert compare_metadata(env.get_context(), meta) == []
85
+
86
+
87
+ def test_sqlite_text_index_without_filter_reproduces_remove_add(connection):
88
+ meta = _metadata()
89
+ meta.create_all(connection)
90
+ with _environment(connection, meta, filtered=False) as env:
91
+ diffs = compare_metadata(env.get_context(), meta)
92
+ assert [diff[0] for diff in diffs] == ["remove_index", "add_index"]
93
+
94
+
95
+ @pytest.mark.parametrize(
96
+ "changes",
97
+ [{"first": "email"}, {"unique": True}, {"element": "tenant_id DESC", "first": "created_at"}],
98
+ ids=["different-column", "unique", "column-order"],
99
+ )
100
+ def test_sqlite_text_index_real_changes_are_reported(connection, changes):
101
+ _metadata().create_all(connection)
102
+ target = _metadata(**changes)
103
+ with _environment(connection, target) as env:
104
+ diffs = compare_metadata(env.get_context(), target)
105
+ assert [diff[0] for diff in diffs] == ["remove_index", "add_index"]
106
+
107
+
108
+ @pytest.mark.parametrize("reflected", [False, True])
109
+ @pytest.mark.parametrize(
110
+ "element",
111
+ [
112
+ "created_at",
113
+ '"created_at"',
114
+ "created_at asc",
115
+ '"created_at" DESC NULLS LAST',
116
+ "created_at NULLS FIRST",
117
+ ],
118
+ )
119
+ def test_sqlite_text_index_filter_handles_both_comparison_directions(
120
+ connection, reflected, element
121
+ ):
122
+ meta = _metadata(element)
123
+ modeled = _index(meta)
124
+ other = sa.MetaData()
125
+ table = meta.tables["record"].to_metadata(other)
126
+ table.indexes.clear()
127
+ database = sa.Index("ix", table.c.tenant_id, table.c.created_at, table.c.id)
128
+ obj, compare_to = (database, modeled) if reflected else (modeled, database)
129
+ with _environment(connection, meta):
130
+ assert make_include_object(meta)(obj, "ix", "index", reflected, compare_to) is False
131
+
132
+
133
+ @pytest.mark.parametrize("reflected", [False, True])
134
+ def test_sqlite_real_expression_is_not_hidden(connection, reflected):
135
+ meta = _metadata("lower(email)")
136
+ meta.create_all(connection)
137
+ # SQLite cannot reflect this index, so exercise the callback pair directly.
138
+ modeled = _index(meta)
139
+ database = _index(_metadata("email"))
140
+ obj, compare_to = (database, modeled) if reflected else (modeled, database)
141
+ with _environment(connection, meta):
142
+ assert make_include_object(meta)(obj, "ix", "index", reflected, compare_to) is True
143
+
144
+
145
+ def test_sqlite_text_index_without_active_context_is_not_hidden():
146
+ meta = _metadata()
147
+ assert (
148
+ make_include_object(meta)(
149
+ _index(meta), "ix", "index", False, _index(_metadata("created_at"))
150
+ )
151
+ is True
152
+ )
153
+
154
+
155
+ def test_postgres_text_index_is_not_hidden(monkeypatch):
156
+ """Postgres reflects the ordering, so its comparison is left to Alembic."""
157
+ meta = _metadata()
158
+ monkeypatch.setattr(
159
+ context, "get_context", lambda: SimpleNamespace(dialect=postgresql.dialect())
160
+ )
161
+ assert (
162
+ make_include_object(meta)(
163
+ _index(meta), "ix", "index", False, _index(_metadata("created_at"))
164
+ )
165
+ is True
166
+ )
167
+
168
+
169
+ def _partial(where: str) -> sa.MetaData:
170
+ meta = sa.MetaData()
171
+ sa.Table(
172
+ "record",
173
+ meta,
174
+ sa.Column("id", sa.Integer, primary_key=True),
175
+ sa.Column("active", sa.Integer),
176
+ sa.Column("email", sa.String),
177
+ sa.Index("ix", sa.text("email DESC"), sqlite_where=sa.text(where)),
178
+ )
179
+ return meta
180
+
181
+
182
+ def test_a_changed_partial_index_predicate_is_still_reported(connection):
183
+ """The guard compares columns only, so it must leave partial indexes alone."""
184
+ _partial("active = 1").create_all(connection)
185
+ target = _partial("active = 0")
186
+ with _environment(connection, target) as env:
187
+ diffs = compare_metadata(env.get_context(), target)
188
+ assert [diff[0] for diff in diffs] == ["remove_index", "add_index"]