simple-module-db 0.0.44__tar.gz → 0.0.46__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 (139) hide show
  1. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/PKG-INFO +3 -3
  2. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/pyproject.toml +3 -3
  3. simple_module_db-0.0.46/simple_module_db/_sqlite_index_compare.py +98 -0
  4. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/data_compatibility.py +2 -13
  5. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/migration_portability.py +42 -15
  6. simple_module_db-0.0.46/simple_module_db/migration_state.py +78 -0
  7. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/migrations.py +19 -5
  8. simple_module_db-0.0.46/tests/_alembic_project.py +46 -0
  9. simple_module_db-0.0.46/tests/test_db_expression_index_warning_scope.py +95 -0
  10. simple_module_db-0.0.46/tests/test_db_migration_doctor.py +123 -0
  11. simple_module_db-0.0.46/tests/test_db_migration_state.py +74 -0
  12. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_migration_portability.py +6 -3
  13. simple_module_db-0.0.46/tests/test_migrations_sqlite_index_compare.py +188 -0
  14. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/.gitignore +0 -0
  15. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/LICENSE +0 -0
  16. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/README.md +0 -0
  17. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/__init__.py +0 -0
  18. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_bulk_audit_records.py +0 -0
  19. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_bulk_pk_update.py +0 -0
  20. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_core_joins.py +0 -0
  21. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_core_walk.py +0 -0
  22. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_engine_policies.py +0 -0
  23. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_entity_selectables.py +0 -0
  24. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_migration_render.py +0 -0
  25. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_outer_joins.py +0 -0
  26. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_persisted_owner.py +0 -0
  27. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/_secondary_scope.py +0 -0
  28. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/admission.py +0 -0
  29. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/audit.py +0 -0
  30. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/audit_redaction.py +0 -0
  31. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/audit_sinks.py +0 -0
  32. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/base.py +0 -0
  33. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/bulk_audit.py +0 -0
  34. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/bulk_audit_targets.py +0 -0
  35. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/bulk_guard.py +0 -0
  36. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/callbacks.py +0 -0
  37. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/core_scope.py +0 -0
  38. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/deps.py +0 -0
  39. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/engine_options.py +0 -0
  40. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/extensions.py +0 -0
  41. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/flush_guard.py +0 -0
  42. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/independent.py +0 -0
  43. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/insert_guard.py +0 -0
  44. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/insert_scope.py +0 -0
  45. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/leases.py +0 -0
  46. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/listeners.py +0 -0
  47. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/mixins.py +0 -0
  48. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/model_registry.py +0 -0
  49. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/pagination.py +0 -0
  50. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/provider.py +0 -0
  51. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/py.typed +0 -0
  52. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/query_filter.py +0 -0
  53. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/query_stats.py +0 -0
  54. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/resource_policy.py +0 -0
  55. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/scope_predicates.py +0 -0
  56. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/search.py +0 -0
  57. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/session.py +0 -0
  58. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/stored_settings.py +0 -0
  59. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/tenancy.py +0 -0
  60. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/tenant_cleanup.py +0 -0
  61. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/transaction.py +0 -0
  62. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/types.py +0 -0
  63. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/user_directory_sql.py +0 -0
  64. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/simple_module_db/writes.py +0 -0
  65. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_audit_models.py +0 -0
  66. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_bulk_audit_support.py +0 -0
  67. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_core_scope_models.py +0 -0
  68. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_db_dml_scope_models.py +0 -0
  69. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_db_read_scope_models.py +0 -0
  70. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_db_shape_matrix.py +0 -0
  71. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/_models.py +0 -0
  72. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/conftest.py +0 -0
  73. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_audit.py +0 -0
  74. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_audit_per_engine.py +0 -0
  75. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_aware_datetime.py +0 -0
  76. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_base.py +0 -0
  77. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_aliased_join_text_scope.py +0 -0
  78. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_aliased_selectable_scope.py +0 -0
  79. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_audit_regressions.py +0 -0
  80. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_bulk_audit.py +0 -0
  81. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_bulk_audit_targets.py +0 -0
  82. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_connection_policy.py +0 -0
  83. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_core_full_setup_join.py +0 -0
  84. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_core_in_orm_select.py +0 -0
  85. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_core_join_scope.py +0 -0
  86. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_core_nested_scope.py +0 -0
  87. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_credential_audit.py +0 -0
  88. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_credential_log_masking.py +0 -0
  89. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_data_compatibility_doctor.py +0 -0
  90. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_dml_target_scope.py +0 -0
  91. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_doctor_session_filters.py +0 -0
  92. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_engine_options.py +0 -0
  93. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_engine_policy_resolution.py +0 -0
  94. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_extensions.py +0 -0
  95. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_extensions_pg.py +0 -0
  96. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_flush_persisted_owner.py +0 -0
  97. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_independent_checkpoint.py +0 -0
  98. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_insert_select_tenant.py +0 -0
  99. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_insert_value_subqueries.py +0 -0
  100. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_lease_lock_wait.py +0 -0
  101. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_listeners_attach.py +0 -0
  102. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_logging.py +0 -0
  103. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_migration_review_regressions.py +0 -0
  104. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_nested_dml_and_bulk_api.py +0 -0
  105. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_pagination.py +0 -0
  106. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_pagination_options.py +0 -0
  107. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_query_stats.py +0 -0
  108. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_relationship_loader_scope.py +0 -0
  109. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_response_finalization.py +0 -0
  110. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_savepoint_callbacks.py +0 -0
  111. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_secondary_scope_execution.py +0 -0
  112. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_shape_matrix_dml.py +0 -0
  113. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_shape_matrix_joins.py +0 -0
  114. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_shape_matrix_selects.py +0 -0
  115. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_sqlite_admission_lock.py +0 -0
  116. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_sqlite_savepoint.py +0 -0
  117. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_sqlite_wal_switch.py +0 -0
  118. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_stored_settings.py +0 -0
  119. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_strict_insert_context.py +0 -0
  120. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_tenant_cleanup.py +0 -0
  121. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_tenant_upsert_guard.py +0 -0
  122. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_user_directory_sql.py +0 -0
  123. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_db_write_marks.py +0 -0
  124. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_default_tenant.py +0 -0
  125. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_independent_session.py +0 -0
  126. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_migrations.py +0 -0
  127. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_mixins.py +0 -0
  128. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_multi_tenancy.py +0 -0
  129. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_query_filter_outer_joins.py +0 -0
  130. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_query_filter_rel_outer_joins.py +0 -0
  131. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_query_filters.py +0 -0
  132. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_rollback_logging.py +0 -0
  133. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_session.py +0 -0
  134. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_soft_delete_shapes.py +0 -0
  135. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_tenant_dml.py +0 -0
  136. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_tenant_shapes.py +0 -0
  137. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_tenant_strict.py +0 -0
  138. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/tests/test_transaction.py +0 -0
  139. {simple_module_db-0.0.44 → simple_module_db-0.0.46}/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.46
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.46
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.46"
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.46",
32
32
  "sqlalchemy[asyncio]>=2.0.2,<3",
33
33
  "sqlmodel>=0.0.22,<0.1",
34
34
  ]
@@ -0,0 +1,98 @@
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; a PostgreSQL
15
+ round trip (``make migrations-roundtrip-pg`` in the framework repository) is what
16
+ catches it.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ import re
23
+
24
+ from alembic import context
25
+ from simple_module_core.diagnostics._expression_index import unwrap_ordering
26
+ from sqlalchemy import Index
27
+ from sqlalchemy.schema import SchemaItem
28
+ from sqlalchemy.sql.elements import ColumnClause, TextClause
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ # One identifier, optionally double-quoted, then an optional ordering.
33
+ _ORDERED_COLUMN = re.compile(
34
+ r'\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))'
35
+ r"(?:\s+(?:ASC|DESC))?(?:\s+NULLS\s+(?:FIRST|LAST))?\s*",
36
+ re.IGNORECASE,
37
+ )
38
+
39
+
40
+ def _on_sqlite() -> bool:
41
+ """Whether the active Alembic migration context targets SQLite.
42
+
43
+ Outside a migration (no context configured) the answer is no, so the
44
+ caller never suppresses a comparison it cannot place.
45
+ """
46
+ try:
47
+ return context.get_context().dialect.name == "sqlite"
48
+ except Exception as exc:
49
+ logger.debug("No Alembic migration context, SQLite index guard off: %s", exc)
50
+ return False
51
+
52
+
53
+ def _element_name(element: object) -> tuple[str | None, bool]:
54
+ """``(column name, written as an expression)`` for one index element.
55
+
56
+ The name is ``None`` for a real expression, which never matches.
57
+ """
58
+ element = unwrap_ordering(element)
59
+ if isinstance(element, TextClause):
60
+ match = _ORDERED_COLUMN.fullmatch(element.text)
61
+ return (match[1] or match[2], True) if match else (None, True)
62
+ if isinstance(element, ColumnClause) and not element.is_literal:
63
+ return element.name, False
64
+ # ``sa.desc("col")`` wraps a textual label reference holding the bare name.
65
+ label = getattr(element, "element", None)
66
+ if type(element).__name__ == "_textual_label_reference" and isinstance(label, str):
67
+ return label, True
68
+ return None, False
69
+
70
+
71
+ def _is_partial(index: Index) -> bool:
72
+ """A partial index (``WHERE`` predicate), modelled or reflected."""
73
+ return any(
74
+ index.dialect_options[dialect].get("where") is not None
75
+ for dialect in ("sqlite", "postgresql")
76
+ )
77
+
78
+
79
+ def differs_only_in_sqlite_ordering(left: SchemaItem, right: SchemaItem | None) -> bool:
80
+ """True when two indexes are the same index as far as SQLite can tell.
81
+
82
+ Requires an active SQLite migration context, equal uniqueness, no partial
83
+ index (``WHERE`` predicate) on either side, the same
84
+ column names in the same order (compared case-insensitively, as SQLite
85
+ compares identifiers), and at least one element written as an expression
86
+ (otherwise Alembic's own comparison is already right).
87
+ """
88
+ if not isinstance(left, Index) or not isinstance(right, Index) or left.unique != right.unique:
89
+ return False
90
+ if _is_partial(left) or _is_partial(right):
91
+ # Only columns are compared here, so a changed predicate would be hidden.
92
+ return False
93
+ if not _on_sqlite():
94
+ return False
95
+ sides = [[_element_name(e) for e in index.expressions] for index in (left, right)]
96
+ names = [[name.casefold() if name else None for name, _ in side] for side in sides]
97
+ written_as_expression = any(is_expr for side in sides for _, is_expr in side)
98
+ 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()
@@ -7,7 +7,8 @@ or never sees, and neither ``alembic check`` nor the boot check notices:
7
7
  integer default on a boolean column. :func:`rewrite_boolean_defaults` and
8
8
  :func:`render_boolean_default` emit ``sa.false()`` / ``sa.true()`` instead.
9
9
  * Expression indexes (``lower(email)``) are skipped on SQLite because it cannot
10
- reflect them. :func:`warn_unverifiable_expression_indexes` says so loudly.
10
+ reflect them. :func:`warn_unverifiable_expression_indexes` names the ones a
11
+ revision misses.
11
12
  * ``op.drop_table`` leaves ``CREATE TYPE`` behind on Postgres, so a downgrade
12
13
  followed by an upgrade fails with ``DuplicateObject``. Use
13
14
  :func:`drop_enums_if_postgres` in the revision's ``downgrade``.
@@ -23,8 +24,11 @@ from collections.abc import Iterator
23
24
  from typing import Any
24
25
 
25
26
  import sqlalchemy as sa
26
- from alembic.operations.ops import AddColumnOp, AlterColumnOp, CreateTableOp
27
- from simple_module_core.diagnostics._expression_index import find_expression_indexes
27
+ from alembic.operations.ops import AddColumnOp, AlterColumnOp, CreateIndexOp, CreateTableOp
28
+ from simple_module_core.diagnostics._expression_index import (
29
+ expression_index_advice,
30
+ find_expression_indexes,
31
+ )
28
32
  from sqlalchemy.dialects import postgresql
29
33
  from sqlalchemy.schema import DefaultClause
30
34
  from sqlalchemy.sql.elements import ColumnElement, False_, TextClause, True_
@@ -116,38 +120,61 @@ def rewrite_boolean_defaults(upgrade_ops: Any) -> None:
116
120
  column.server_default = DefaultClause(replacement)
117
121
 
118
122
 
119
- def warn_unverifiable_expression_indexes(dialect_name: str | None, metadata: sa.MetaData) -> list:
120
- """Warn when autogenerating on SQLite while models declare expression indexes.
121
-
122
- A warning rather than an error: autogenerate also runs for ordinary,
123
- unrelated revisions, and failing every one of them for an index that is
124
- already in history would block normal work. The warning is emitted on every
125
- run, names each index, and ``alembic check`` on Postgres
126
- (``make migrations-roundtrip-pg``) is the real gate. Returns the
123
+ def warn_unverifiable_expression_indexes(
124
+ dialect_name: str | None,
125
+ metadata: sa.MetaData,
126
+ upgrade_ops: Any = None,
127
+ existing_index_names: set[str] | None = None,
128
+ ) -> list:
129
+ """Warn when a revision autogenerated on SQLite misses expression indexes.
130
+
131
+ SQLite cannot reflect an expression index's definition, so autogenerate
132
+ skips them, but it does record their names. The revision hook passes
133
+ ``upgrade_ops`` (after re-emitting the indexes of new tables) and the index
134
+ names the database already has; then only indexes that are in neither are
135
+ named: one added to an existing table, typically. A fresh initial schema
136
+ creates them, and a revision on another table leaves them alone, so both
137
+ stay silent (GH #917). Without those arguments every expression index in
138
+ ``metadata`` is named.
139
+
140
+ A warning rather than an error: a PostgreSQL run is the real gate, and an
141
+ index whose name exists may still differ in definition. Returns the
127
142
  ``(table, index)`` pairs it warned about.
128
143
  """
129
144
  if dialect_name != "sqlite":
130
145
  return []
131
146
  found = find_expression_indexes(metadata.tables.values())
147
+ if upgrade_ops is not None:
148
+ emitted = {
149
+ op.index_name for op in iter_ops_recursive(upgrade_ops) if isinstance(op, CreateIndexOp)
150
+ }
151
+ existing = existing_index_names or set()
152
+ found = [(t, i) for t, i in found if i not in emitted and i not in existing]
132
153
  if not found:
133
154
  return []
134
155
  listing = "\n".join(f" - {index} on {table}" for table, index in found)
135
156
  logger.warning(
136
157
  "\n%s\n"
137
158
  "WARNING: autogenerating on SQLite. SQLite cannot reflect expression indexes,\n"
138
- "so this revision does NOT account for the following (they are neither\n"
139
- "created nor verified here) and `alembic check` will not notice drift:\n"
159
+ "so this revision does NOT create the following, which the models declare\n"
160
+ "and the database does not have:\n"
140
161
  "%s\n"
141
- "Add them to the revision by hand and verify on PostgreSQL before merging\n"
142
- "(`make migrations-roundtrip-pg`). See docs/module-authoring.md, Migrations.\n"
162
+ "Add them to the revision by hand and %s.\n"
143
163
  "%s",
144
164
  "=" * 78,
145
165
  listing,
166
+ expression_index_advice(),
146
167
  "=" * 78,
147
168
  )
148
169
  return found
149
170
 
150
171
 
172
+ def sqlite_index_names(connection: Any) -> set[str]:
173
+ """Every index name in a SQLite database, expression indexes included."""
174
+ rows = connection.execute(sa.text("SELECT name FROM sqlite_master WHERE type = 'index'"))
175
+ return {row[0] for row in rows}
176
+
177
+
151
178
  def drop_enums_if_postgres(op: Any, *names: str) -> None:
152
179
  """Drop the named enum types on PostgreSQL; a no-op elsewhere.
153
180
 
@@ -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,
@@ -35,6 +36,7 @@ from simple_module_db.extensions import ( # noqa: F401 (ensure_db_extensions r
35
36
  from simple_module_db.migration_portability import (
36
37
  iter_ops_recursive,
37
38
  rewrite_boolean_defaults,
39
+ sqlite_index_names,
38
40
  warn_unverifiable_expression_indexes,
39
41
  )
40
42
 
@@ -147,6 +149,9 @@ def make_include_object(
147
149
  ) -> bool:
148
150
  if type_ == "table":
149
151
  return name in allowlist
152
+ if type_ == "index" and differs_only_in_sqlite_ordering(object, compare_to):
153
+ # SQLite reflects ``created_at DESC`` as a plain column (GH #869).
154
+ return False
150
155
  if (
151
156
  ignore_unmodeled_fks
152
157
  and type_ == "foreign_key_constraint"
@@ -191,8 +196,8 @@ def make_process_revision_directives(
191
196
  alone, which keeps this dialect-agnostic rather than special-casing SQLite.
192
197
 
193
198
  It also rewrites ``0``/``1``/``false``/``true`` server defaults on Boolean
194
- columns to ``sa.false()``/``sa.true()`` and, when running on SQLite, warns
195
- that expression indexes cannot be verified (see
199
+ columns to ``sa.false()``/``sa.true()`` and, when running on SQLite, names
200
+ the expression indexes the revision misses (see
196
201
  :mod:`simple_module_db.migration_portability`).
197
202
 
198
203
  Call as::
@@ -209,15 +214,17 @@ def make_process_revision_directives(
209
214
  expression_indexes.setdefault(table.name, []).append(index)
210
215
 
211
216
  def process_revision_directives(context, revision, directives):
212
- warn_unverifiable_expression_indexes(
213
- getattr(getattr(context, "dialect", None), "name", None), metadata
214
- )
217
+ dialect_name = getattr(getattr(context, "dialect", None), "name", None)
215
218
  for script in directives:
216
219
  upgrade_ops = getattr(script, "upgrade_ops", None)
217
220
  if upgrade_ops is not None:
218
221
  rewrite_boolean_defaults(upgrade_ops)
219
222
  if expression_indexes:
220
223
  _inject_create_index_after_create_table(upgrade_ops, expression_indexes)
224
+ # After the re-emission, so an index this revision creates is not reported.
225
+ warn_unverifiable_expression_indexes(
226
+ dialect_name, metadata, upgrade_ops, _existing_sqlite_indexes(context)
227
+ )
221
228
  downgrade_ops = getattr(script, "downgrade_ops", None)
222
229
  if downgrade_ops is not None:
223
230
  # A downgrade re-creates dropped tables/columns from reflected
@@ -229,6 +236,13 @@ def make_process_revision_directives(
229
236
  return process_revision_directives
230
237
 
231
238
 
239
+ def _existing_sqlite_indexes(context) -> set[str]:
240
+ connection = getattr(context, "connection", None)
241
+ if connection is None or connection.dialect.name != "sqlite":
242
+ return set()
243
+ return sqlite_index_names(connection)
244
+
245
+
232
246
  def _existing_index_names(container, op_type) -> set[str | None]:
233
247
  """Names of every ``op_type`` index op already present anywhere under ``container``."""
234
248
  return {
@@ -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,95 @@
1
+ """The SQLite expression-index warning names only what the revision missed (GH #917).
2
+
3
+ The hook used to warn about every expression index in the metadata, before it
4
+ had re-emitted them, so a fresh app's initial schema (which does create the
5
+ index) and every unrelated module migration told users to hand-edit it in.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+
12
+ import sqlalchemy as sa
13
+ from alembic.autogenerate import produce_migrations
14
+ from alembic.runtime.migration import MigrationContext
15
+ from simple_module_core.diagnostics._expression_index import expression_index_advice
16
+ from simple_module_db.migrations import make_process_revision_directives, render_item
17
+
18
+
19
+ def _metadata(*, extra_column: bool = False) -> sa.MetaData:
20
+ md = sa.MetaData()
21
+ sa.Table(
22
+ "people",
23
+ md,
24
+ sa.Column("id", sa.Integer, primary_key=True),
25
+ sa.Column("email", sa.String),
26
+ *([sa.Column("nickname", sa.String)] if extra_column else []),
27
+ sa.Index("ix_people_email_lower", sa.text("lower(email)"), unique=True),
28
+ )
29
+ sa.Table("orders", md, sa.Column("id", sa.Integer, primary_key=True))
30
+ return md
31
+
32
+
33
+ def _run_hook(existing: sa.MetaData | None, target: sa.MetaData, caplog) -> str:
34
+ engine = sa.create_engine("sqlite://")
35
+ with engine.connect() as conn:
36
+ if existing is not None:
37
+ existing.create_all(conn)
38
+ ctx = MigrationContext.configure(conn, opts={"render_item": render_item})
39
+ script = produce_migrations(ctx, target)
40
+ with caplog.at_level(logging.WARNING, logger="alembic.env"):
41
+ make_process_revision_directives(target)(ctx, None, [script])
42
+ return caplog.text
43
+
44
+
45
+ def test_initial_schema_that_creates_the_index_is_silent(caplog) -> None:
46
+ assert "ix_people_email_lower" not in _run_hook(None, _metadata(), caplog)
47
+
48
+
49
+ def test_revision_on_another_table_is_silent(caplog) -> None:
50
+ existing = _metadata()
51
+ existing.remove(existing.tables["orders"])
52
+ assert "ix_people_email_lower" not in _run_hook(existing, _metadata(), caplog)
53
+
54
+
55
+ def test_revision_altering_a_table_whose_index_exists_is_silent(caplog) -> None:
56
+ """SQLite records the index's name even though it cannot reflect it."""
57
+ text = _run_hook(_metadata(), _metadata(extra_column=True), caplog)
58
+ assert "ix_people_email_lower" not in text
59
+
60
+
61
+ def test_an_expression_index_added_to_an_existing_table_warns(caplog) -> None:
62
+ """Autogenerate emits nothing for it on SQLite, so the revision misses it."""
63
+ existing = _metadata()
64
+ existing.tables["people"].indexes.clear()
65
+ text = _run_hook(existing, _metadata(), caplog)
66
+ assert "ix_people_email_lower on people" in text
67
+
68
+
69
+ def test_advice_outside_this_repo_points_at_what_exists(tmp_path, monkeypatch) -> None:
70
+ monkeypatch.chdir(tmp_path)
71
+ advice = expression_index_advice()
72
+ assert "migrations-roundtrip-pg" not in advice
73
+ assert "alembic -c host/alembic.ini check" in advice
74
+ assert "PostgreSQL" in advice
75
+
76
+
77
+ def test_advice_in_a_checkout_with_the_roundtrip_target(tmp_path, monkeypatch) -> None:
78
+ (tmp_path / "Makefile").write_text("migrations-roundtrip-pg:\n\techo\n", encoding="utf-8")
79
+ monkeypatch.chdir(tmp_path)
80
+ assert "make migrations-roundtrip-pg" in expression_index_advice()
81
+
82
+
83
+ def test_a_ci_prefixed_target_is_not_the_roundtrip_target(tmp_path, monkeypatch) -> None:
84
+ (tmp_path / "Makefile").write_text("ci-migrations-roundtrip-pg:\n\techo\n", encoding="utf-8")
85
+ monkeypatch.chdir(tmp_path)
86
+ assert "make migrations-roundtrip-pg" not in expression_index_advice()
87
+
88
+
89
+ def test_dropping_the_index_does_not_count_as_creating_it() -> None:
90
+ from alembic.operations.ops import DropIndexOp, UpgradeOps
91
+ from simple_module_db.migration_portability import warn_unverifiable_expression_indexes
92
+
93
+ ops = UpgradeOps(ops=[DropIndexOp("ix_people_email_lower", table_name="people")])
94
+ found = warn_unverifiable_expression_indexes("sqlite", _metadata(), ops, set())
95
+ assert found == [("people", "ix_people_email_lower")]