strata-python 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl
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.
- strata_python/__init__.py +2 -1
- strata_python/db/__init__.py +113 -0
- strata_python/db/__main__.py +5 -0
- strata_python/db/_alembic/env.py +24 -0
- strata_python/db/_alembic/script.py.mako +28 -0
- strata_python/db/cli.py +199 -0
- strata_python/db/config.py +85 -0
- strata_python/db/engine.py +53 -0
- strata_python/db/guard.py +159 -0
- strata_python/db/migrations.py +243 -0
- strata_python/db/models.py +50 -0
- strata_python/db/project.py +85 -0
- strata_python/db/pytest_plugin.py +151 -0
- strata_python/db/scratch.py +143 -0
- strata_python/db/testing.py +43 -0
- strata_python/db/testserver.py +205 -0
- strata_python/pytest_plugin.py +70 -1
- strata_python/testing.py +257 -0
- strata_python-0.2.1.dist-info/METADATA +274 -0
- strata_python-0.2.1.dist-info/RECORD +32 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.1.dist-info}/entry_points.txt +2 -0
- strata_python-0.2.0.dist-info/METADATA +0 -82
- strata_python-0.2.0.dist-info/RECORD +0 -16
- {strata_python-0.2.0.dist-info → strata_python-0.2.1.dist-info}/WHEEL +0 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Keeping tests and stray processes off real data.
|
|
2
|
+
|
|
3
|
+
Two rules:
|
|
4
|
+
|
|
5
|
+
1. **Tests never open a real database.** During a test run (pytest with the db extra installed, which loads the
|
|
6
|
+
plugin; or `STRATA_DB_TESTING=1`, which the plugin sets so that subprocesses inherit it; or `PYTEST_CURRENT_TEST`)
|
|
7
|
+
the only Postgres databases that can be opened are throwaway ones: names starting `strata_db_` (what the fixtures,
|
|
8
|
+
`scratch_database()` and `strata-db`'s scratch runs create) and the admin database they are created through
|
|
9
|
+
(`STRATA_DB_TEST_ADMIN_URL`). Anything else raises `LiveDatabaseRefused`, whatever the environment says, including
|
|
10
|
+
`STRATA_DB_LIVE`. Under pytest this is enforced on every psycopg (and psycopg2) connection in the process, so it
|
|
11
|
+
also covers code that calls `create_engine()` or `psycopg.connect()` itself, not only `connect()`. It is the guard
|
|
12
|
+
that matters: the plugin's `no_network` does not cover the local Unix socket the shared server listens on.
|
|
13
|
+
2. **A real database is opt-in.** Outside tests, `connect()` and `url_for()` open a Postgres database that is not a
|
|
14
|
+
throwaway one only when the process says so: `STRATA_DB_LIVE=1` in its environment (set it in the app's service
|
|
15
|
+
unit or launcher, not in a shell profile, so scripts, REPLs and agents started from a shell never get it), or
|
|
16
|
+
`strata-db --live`.
|
|
17
|
+
|
|
18
|
+
SQLite is never restricted: a file path is always deliberate, and tests use in-memory or temporary copies.
|
|
19
|
+
|
|
20
|
+
No SQLAlchemy at import: the pytest plugin imports this module in every app that has strata-python installed.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import importlib
|
|
26
|
+
import os
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
from typing import Any, cast
|
|
29
|
+
|
|
30
|
+
THROWAWAY_PREFIX = "strata_db_"
|
|
31
|
+
LIVE = "STRATA_DB_LIVE"
|
|
32
|
+
TESTING = "STRATA_DB_TESTING"
|
|
33
|
+
TEST_ADMIN_URL = "STRATA_DB_TEST_ADMIN_URL"
|
|
34
|
+
_GUARDED = "_strata_db_guarded"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LiveDatabaseRefused(RuntimeError):
|
|
38
|
+
"""A connection to a real (non-throwaway) database was refused: under tests always, otherwise without
|
|
39
|
+
`STRATA_DB_LIVE=1`."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_testing = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def testing() -> bool:
|
|
46
|
+
return _testing or os.environ.get(TESTING) == "1" or "PYTEST_CURRENT_TEST" in os.environ
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def live_allowed() -> bool:
|
|
50
|
+
return os.environ.get(LIVE) == "1" and not testing()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def allow_live() -> None:
|
|
54
|
+
"""Opt this process in to real databases (`strata-db --live`). Has no effect under tests."""
|
|
55
|
+
os.environ[LIVE] = "1"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_throwaway(dbname: str | None) -> bool:
|
|
59
|
+
return bool(dbname) and str(dbname).startswith(THROWAWAY_PREFIX)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _admin_database() -> str | None:
|
|
63
|
+
"""The database the test admin URL connects to: allowed under tests, since throwaway databases are created
|
|
64
|
+
through it. Never the shared database, whatever the URL says."""
|
|
65
|
+
url = os.environ.get(TEST_ADMIN_URL) # set by CI, or by testserver once it has started
|
|
66
|
+
if not url:
|
|
67
|
+
return None
|
|
68
|
+
from sqlalchemy.engine import make_url
|
|
69
|
+
|
|
70
|
+
from .config import normalise_url, shared_database
|
|
71
|
+
|
|
72
|
+
name = make_url(normalise_url(url)).database or None
|
|
73
|
+
return None if name == shared_database() else name
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def check_database(dbname: str | None, where: str = "connect") -> None:
|
|
77
|
+
"""Raise LiveDatabaseRefused unless the Postgres database `dbname` may be opened by this process now."""
|
|
78
|
+
if is_throwaway(dbname):
|
|
79
|
+
return
|
|
80
|
+
if testing():
|
|
81
|
+
if dbname and dbname == _admin_database():
|
|
82
|
+
return
|
|
83
|
+
raise LiveDatabaseRefused(
|
|
84
|
+
f"{where}: refused Postgres database {dbname!r} during tests. Tests may only use throwaway "
|
|
85
|
+
f"{THROWAWAY_PREFIX}* databases: use the db_env / db_url / db_engine / db_session fixtures "
|
|
86
|
+
"(db_env points the app's own connect(app) at a fresh test database)."
|
|
87
|
+
)
|
|
88
|
+
if not live_allowed():
|
|
89
|
+
raise LiveDatabaseRefused(
|
|
90
|
+
f"{where}: {dbname!r} is a real database and this process has not opted in. Set {LIVE}=1 in the app's "
|
|
91
|
+
"service environment (systemd unit, launcher), or pass --live to strata-db."
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_url(url: str, where: str = "connect") -> None:
|
|
96
|
+
"""check_database() for a SQLAlchemy URL; SQLite and other non-Postgres URLs pass."""
|
|
97
|
+
from sqlalchemy.engine import make_url
|
|
98
|
+
|
|
99
|
+
u = make_url(url)
|
|
100
|
+
if u.get_backend_name() != "postgresql":
|
|
101
|
+
return
|
|
102
|
+
q: str | tuple[str, ...] | None = u.query.get("dbname") # psycopg's dialect lets ?dbname= override the path
|
|
103
|
+
dbname = (q[-1] if isinstance(q, tuple) else q) or u.database
|
|
104
|
+
check_database(dbname or os.environ.get("PGDATABASE") or u.username or os.environ.get("USER"), where)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def enter_test_mode() -> None:
|
|
108
|
+
"""Called by the pytest plugin as it loads (before conftest.py and the app's modules are imported)."""
|
|
109
|
+
global _testing
|
|
110
|
+
_testing = True
|
|
111
|
+
os.environ[TESTING] = "1"
|
|
112
|
+
_guard_drivers()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _guarded_sync(where: str, orig: Callable[..., Any]) -> Callable[..., Any]:
|
|
116
|
+
def connect(*a: Any, **k: Any) -> Any:
|
|
117
|
+
conn = orig(*a, **k)
|
|
118
|
+
try:
|
|
119
|
+
check_database(conn.info.dbname, where)
|
|
120
|
+
except LiveDatabaseRefused:
|
|
121
|
+
conn.close()
|
|
122
|
+
raise
|
|
123
|
+
return conn
|
|
124
|
+
|
|
125
|
+
return connect
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _guard_drivers() -> None:
|
|
129
|
+
"""Check the database of every new psycopg / psycopg2 connection (so raw create_engine and driver calls are
|
|
130
|
+
covered too). The check runs right after connecting, before any statement; a refused connection is closed."""
|
|
131
|
+
try:
|
|
132
|
+
import psycopg
|
|
133
|
+
except ImportError:
|
|
134
|
+
psycopg = None
|
|
135
|
+
if psycopg is not None and not getattr(psycopg, _GUARDED, False):
|
|
136
|
+
sync_connect = cast("Any", psycopg.Connection).connect.__func__
|
|
137
|
+
async_connect = cast("Any", psycopg.AsyncConnection).connect.__func__
|
|
138
|
+
guarded = _guarded_sync("psycopg.connect", sync_connect)
|
|
139
|
+
|
|
140
|
+
async def aconnect(cls: Any, *a: Any, **k: Any) -> Any:
|
|
141
|
+
conn = await async_connect(cls, *a, **k)
|
|
142
|
+
try:
|
|
143
|
+
check_database(conn.info.dbname, "psycopg.AsyncConnection.connect")
|
|
144
|
+
except LiveDatabaseRefused:
|
|
145
|
+
await conn.close()
|
|
146
|
+
raise
|
|
147
|
+
return conn
|
|
148
|
+
|
|
149
|
+
cast("Any", psycopg.Connection).connect = classmethod(guarded)
|
|
150
|
+
cast("Any", psycopg.AsyncConnection).connect = classmethod(aconnect)
|
|
151
|
+
cast("Any", psycopg).connect = psycopg.Connection.connect # the module-level alias SQLAlchemy calls
|
|
152
|
+
setattr(psycopg, _GUARDED, True)
|
|
153
|
+
try:
|
|
154
|
+
p2: Any = importlib.import_module("psycopg2") # by name: it is never a dependency, only guarded if there
|
|
155
|
+
except ImportError:
|
|
156
|
+
return
|
|
157
|
+
if not getattr(p2, _GUARDED, False):
|
|
158
|
+
p2.connect = _guarded_sync("psycopg2.connect", p2.connect)
|
|
159
|
+
setattr(p2, _GUARDED, True)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Alembic without per-app boilerplate: one shared env.py (strata_python/db/_alembic), the app's revisions in its
|
|
2
|
+
own migrations/ folder, the connection and MetaData passed in from here.
|
|
3
|
+
|
|
4
|
+
upgrade() is safe to call at every app start: on Postgres it takes an advisory lock so two processes starting at
|
|
5
|
+
once do not both migrate, sets search_path to the app's schema (creating the schema if needed), so the tables and
|
|
6
|
+
Alembic's version table land there whatever the connection's search_path, and runs as the app's owner role (if it
|
|
7
|
+
exists and you are a member) so the app role owns what it creates.
|
|
8
|
+
|
|
9
|
+
Identifiers (schema and role names) cannot be bound parameters, so they go through the dialect's own quoting
|
|
10
|
+
(`quote()`), never into SQL as they are.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import zlib
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, cast
|
|
20
|
+
|
|
21
|
+
from alembic import command
|
|
22
|
+
from alembic.autogenerate import compare_metadata
|
|
23
|
+
from alembic.config import Config
|
|
24
|
+
from alembic.migration import MigrationContext
|
|
25
|
+
from alembic.operations import Operations
|
|
26
|
+
from alembic.script import ScriptDirectory
|
|
27
|
+
from sqlalchemy import MetaData, inspect, text
|
|
28
|
+
from sqlalchemy.engine import Connection, Engine
|
|
29
|
+
|
|
30
|
+
ENV_DIR = Path(__file__).parent / "_alembic"
|
|
31
|
+
LOCK_NAMESPACE = "strata_db"
|
|
32
|
+
PathLike = str | os.PathLike[str]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def quote(conn: Connection, name: str) -> str:
|
|
36
|
+
"""`name` as a quoted SQL identifier in this dialect ("a""b" for a"b)."""
|
|
37
|
+
return conn.dialect.identifier_preparer.quote_identifier(name)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def make_config(
|
|
41
|
+
migrations_dir: PathLike, metadata: MetaData, connection: Connection | None, **attributes: Any
|
|
42
|
+
) -> Config:
|
|
43
|
+
migrations_dir = Path(migrations_dir)
|
|
44
|
+
migrations_dir.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
cfg = Config()
|
|
46
|
+
cfg.set_main_option("script_location", str(ENV_DIR))
|
|
47
|
+
cfg.set_main_option("version_locations", str(migrations_dir))
|
|
48
|
+
cfg.set_main_option("path_separator", "os")
|
|
49
|
+
cfg.set_main_option("file_template", "%%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s")
|
|
50
|
+
cfg.set_main_option("truncate_slug_length", "40")
|
|
51
|
+
cfg.attributes.update(connection=connection, metadata=metadata, **attributes)
|
|
52
|
+
return cfg
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _prepare(conn: Connection, owner_role: str | None, schema: str | None = None) -> None:
|
|
56
|
+
if conn.dialect.name != "postgresql":
|
|
57
|
+
return
|
|
58
|
+
key = zlib.crc32(f"{LOCK_NAMESPACE}:{conn.engine.url.database}:{schema}".encode())
|
|
59
|
+
conn.execute(text("SELECT pg_advisory_xact_lock(:k)"), {"k": key})
|
|
60
|
+
member = (
|
|
61
|
+
owner_role
|
|
62
|
+
and conn.execute(
|
|
63
|
+
text("SELECT pg_has_role(current_user, :r, 'SET') FROM pg_roles WHERE rolname = :r"), {"r": owner_role}
|
|
64
|
+
).scalar()
|
|
65
|
+
)
|
|
66
|
+
role = owner_role if member else None
|
|
67
|
+
if schema:
|
|
68
|
+
if not conn.execute(text("SELECT 1 FROM pg_namespace WHERE nspname = :s"), {"s": schema}).scalar():
|
|
69
|
+
owner = f" AUTHORIZATION {quote(conn, role)}" if role else ""
|
|
70
|
+
conn.execute(text(f"CREATE SCHEMA {quote(conn, schema)}{owner}"))
|
|
71
|
+
conn.execute(text(f"REVOKE ALL ON SCHEMA {quote(conn, schema)} FROM PUBLIC"))
|
|
72
|
+
conn.execute(text(f"SET LOCAL search_path TO {quote(conn, schema)}"))
|
|
73
|
+
if role:
|
|
74
|
+
conn.execute(text(f"SET LOCAL ROLE {quote(conn, role)}"))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _run(engine: Engine, owner_role: str | None, fn: Callable[[Connection], object], schema: str | None = None) -> None:
|
|
78
|
+
"""Run fn(conn) in one transaction. On SQLite, foreign-key enforcement is switched off around it (the pragma
|
|
79
|
+
only takes effect outside a transaction): batch mode recreates a table by copy, drop and rename, and dropping a
|
|
80
|
+
table that other rows reference would fail or cascade. Before committing, PRAGMA foreign_key_check must come
|
|
81
|
+
back empty, otherwise everything is rolled back; enforcement is switched back on either way. The SQLite transaction
|
|
82
|
+
is begun explicitly: the driver would otherwise run the DDL outside one, and a failed revision would leave half its
|
|
83
|
+
tables behind."""
|
|
84
|
+
with engine.connect() as conn:
|
|
85
|
+
sqlite = conn.dialect.name == "sqlite"
|
|
86
|
+
if sqlite:
|
|
87
|
+
conn.exec_driver_sql("PRAGMA foreign_keys = OFF")
|
|
88
|
+
conn.commit()
|
|
89
|
+
try:
|
|
90
|
+
with conn.begin():
|
|
91
|
+
if sqlite: # pysqlite begins only before DML, so DDL would commit as it ran (review finding)
|
|
92
|
+
conn.exec_driver_sql("BEGIN")
|
|
93
|
+
_prepare(conn, owner_role, schema)
|
|
94
|
+
fn(conn)
|
|
95
|
+
if sqlite and (bad := conn.exec_driver_sql("PRAGMA foreign_key_check").fetchall()):
|
|
96
|
+
raise RuntimeError(
|
|
97
|
+
f"migration left foreign key violations (table, rowid, parent, fk): {bad[:10]}; rolled back"
|
|
98
|
+
)
|
|
99
|
+
finally:
|
|
100
|
+
if sqlite:
|
|
101
|
+
conn.exec_driver_sql("PRAGMA foreign_keys = ON")
|
|
102
|
+
conn.commit()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def upgrade(
|
|
106
|
+
engine: Engine,
|
|
107
|
+
migrations_dir: PathLike,
|
|
108
|
+
metadata: MetaData,
|
|
109
|
+
revision: str = "head",
|
|
110
|
+
owner_role: str | None = None,
|
|
111
|
+
schema: str | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
_run(engine, owner_role, lambda c: command.upgrade(make_config(migrations_dir, metadata, c), revision), schema)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def downgrade(
|
|
117
|
+
engine: Engine,
|
|
118
|
+
migrations_dir: PathLike,
|
|
119
|
+
metadata: MetaData,
|
|
120
|
+
revision: str = "base",
|
|
121
|
+
owner_role: str | None = None,
|
|
122
|
+
schema: str | None = None,
|
|
123
|
+
) -> None:
|
|
124
|
+
_run(engine, owner_role, lambda c: command.downgrade(make_config(migrations_dir, metadata, c), revision), schema)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def current(engine: Engine, schema: str | None = None) -> str | None:
|
|
128
|
+
with engine.connect() as conn:
|
|
129
|
+
if schema and conn.dialect.name == "postgresql":
|
|
130
|
+
conn.execute(text(f"SET search_path TO {quote(conn, schema)}"))
|
|
131
|
+
return MigrationContext.configure(conn).get_current_revision()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def include_name(name: str | None, type_: str, _parents: object) -> bool:
|
|
135
|
+
# Only the app's own tables count; ignore Alembic's bookkeeping table.
|
|
136
|
+
return not (type_ == "table" and name == "alembic_version")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def drift(engine: Engine, metadata: MetaData) -> list[Any]:
|
|
140
|
+
"""Differences between the database's schema and the models (empty = in sync). Alembic's own comparison."""
|
|
141
|
+
with engine.connect() as conn:
|
|
142
|
+
opts: dict[str, Any] = {
|
|
143
|
+
"compare_type": True,
|
|
144
|
+
"compare_server_default": conn.dialect.name != "sqlite", # see _alembic/env.py
|
|
145
|
+
"include_name": include_name,
|
|
146
|
+
}
|
|
147
|
+
return list(cast("list[Any]", compare_metadata(MigrationContext.configure(conn, opts=opts), metadata)))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _revisions(migrations_dir: PathLike) -> ScriptDirectory:
|
|
151
|
+
"""The app's revisions, loaded. Inside a (database-less) Operations context, because a revision may call `op.f()`
|
|
152
|
+
or other `op` helpers at module level, which outside a migration raises "proxy object has not yet been established"."""
|
|
153
|
+
script = ScriptDirectory.from_config(make_config(migrations_dir, MetaData(), None))
|
|
154
|
+
with Operations.context(MigrationContext.configure(dialect_name="sqlite")):
|
|
155
|
+
script.get_revisions("heads") # loads every revision file now
|
|
156
|
+
return script
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def lint_revisions(migrations_dir: PathLike) -> list[str]:
|
|
160
|
+
"""Checks on the revision files alone, no database: exactly one base and one head. Two branches that each added
|
|
161
|
+
a revision on the same parent (two PRs written in parallel) leave two heads, and `upgrade head` then fails at app
|
|
162
|
+
start; this catches it in the tests instead."""
|
|
163
|
+
try:
|
|
164
|
+
script = _revisions(migrations_dir)
|
|
165
|
+
heads, bases = script.get_heads(), script.get_bases()
|
|
166
|
+
except Exception as e: # any load error is the finding: report it like the others, do not crash the check
|
|
167
|
+
return [f"revision files do not form a chain: {type(e).__name__}: {str(e).splitlines()[0]}"]
|
|
168
|
+
problems: list[str] = []
|
|
169
|
+
if len(heads) > 1:
|
|
170
|
+
problems.append(
|
|
171
|
+
f"{len(heads)} heads ({', '.join(sorted(heads))}): revisions written in parallel on the same "
|
|
172
|
+
"parent; set the newer one's down_revision to the other (or write a merge revision)"
|
|
173
|
+
)
|
|
174
|
+
if len(bases) > 1:
|
|
175
|
+
problems.append(
|
|
176
|
+
f"{len(bases)} base revisions ({', '.join(sorted(bases))}): only the first may have down_revision = None"
|
|
177
|
+
)
|
|
178
|
+
return problems
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def stairway(engine: Engine, migrations_dir: PathLike, metadata: MetaData) -> list[str]:
|
|
182
|
+
"""From base, one revision at a time (in dependency order): upgrade to it, downgrade one step, upgrade again.
|
|
183
|
+
Catches a downgrade that only works from head, or a revision that cannot be re-applied after its own downgrade (a
|
|
184
|
+
leftover index, type or sequence). Ends at head. Returns problems (empty = all good); stops at the first broken
|
|
185
|
+
step. Branches and merges: "one step down" from a revision with one parent is that parent (which also undoes a
|
|
186
|
+
sibling branch applied meanwhile; it is re-applied when the merge needs it), and from a merge revision, its
|
|
187
|
+
first parent (which removes just the merge: the other parents stay applied as heads)."""
|
|
188
|
+
script = _revisions(migrations_dir)
|
|
189
|
+
for rev in reversed(list(script.walk_revisions())):
|
|
190
|
+
name = f"{rev.revision} ({rev.doc.splitlines()[0] if rev.doc else 'no message'})"
|
|
191
|
+
parents = rev.down_revision
|
|
192
|
+
down = "base" if not parents else parents if isinstance(parents, str) else parents[0]
|
|
193
|
+
steps: tuple[tuple[str, Callable[[Engine, PathLike, MetaData, str], None], str], ...] = (
|
|
194
|
+
("upgrade", upgrade, rev.revision),
|
|
195
|
+
("downgrade one step from", downgrade, down),
|
|
196
|
+
("upgrade again to", upgrade, rev.revision),
|
|
197
|
+
)
|
|
198
|
+
for step, fn, target in steps:
|
|
199
|
+
try:
|
|
200
|
+
fn(engine, migrations_dir, metadata, target)
|
|
201
|
+
except Exception as e: # the failing step is the finding
|
|
202
|
+
return [f"stairway: {step} {name} failed: {type(e).__name__}: {str(e).splitlines()[0]}"]
|
|
203
|
+
upgrade(engine, migrations_dir, metadata) # every head (a sibling undone above may not be re-applied yet)
|
|
204
|
+
return []
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _tables(engine: Engine) -> list[str]:
|
|
208
|
+
return [t for t in inspect(engine).get_table_names() if t != "alembic_version"]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def check_migrations(engine: Engine, migrations_dir: PathLike, metadata: MetaData) -> list[str]:
|
|
212
|
+
"""On an EMPTY database: one head and one base; upgrade from nothing to head and compare with the models;
|
|
213
|
+
downgrade to base (every downgrade must run and leave no tables); then the stairway (each revision up, down one
|
|
214
|
+
step, up again), which ends at head. Returns a list of problems (empty = all good)."""
|
|
215
|
+
if problems := lint_revisions(migrations_dir):
|
|
216
|
+
return problems
|
|
217
|
+
if _tables(engine):
|
|
218
|
+
return ["check_migrations needs an empty database"]
|
|
219
|
+
upgrade(engine, migrations_dir, metadata)
|
|
220
|
+
if d := drift(engine, metadata):
|
|
221
|
+
problems.append(f"after upgrade head the schema differs from the models (run strata-db revision): {d}")
|
|
222
|
+
downgrade(engine, migrations_dir, metadata, "base")
|
|
223
|
+
if left := _tables(engine):
|
|
224
|
+
problems.append(f"downgrade to base left tables: {left}")
|
|
225
|
+
return problems # upgrading again would only fail on the leftovers
|
|
226
|
+
return problems + stairway(engine, migrations_dir, metadata)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def revision(
|
|
230
|
+
engine: Engine, migrations_dir: PathLike, metadata: MetaData, message: str, autogenerate: bool = True
|
|
231
|
+
) -> str | None:
|
|
232
|
+
"""Write a new revision file. With autogenerate, `engine` must be a database at head (strata-db uses a scratch
|
|
233
|
+
one) and nothing is written when there is no change. Returns the path written, or None."""
|
|
234
|
+
|
|
235
|
+
def directives(_context: object, _rev: object, dirs: list[Any]) -> None:
|
|
236
|
+
if autogenerate and dirs[0].upgrade_ops.is_empty():
|
|
237
|
+
dirs[:] = []
|
|
238
|
+
|
|
239
|
+
with engine.begin() as conn:
|
|
240
|
+
cfg = make_config(migrations_dir, metadata, conn, process_revision_directives=directives)
|
|
241
|
+
scripts = command.revision(cfg, message=message, autogenerate=autogenerate)
|
|
242
|
+
written = [s.path for s in (scripts if isinstance(scripts, list) else [scripts]) if s is not None]
|
|
243
|
+
return written[0] if written else None
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Declarative bases for apps' models.
|
|
2
|
+
|
|
3
|
+
from strata_python.db import make_base
|
|
4
|
+
Base = make_base() # one per app, in its models module
|
|
5
|
+
|
|
6
|
+
class Note(Base):
|
|
7
|
+
__tablename__ = "notes"
|
|
8
|
+
id: Mapped[int] = mapped_column(primary_key=True, init=False)
|
|
9
|
+
text: Mapped[str]
|
|
10
|
+
|
|
11
|
+
MappedAsDataclass makes each model a typed record (constructor, repr, eq from the annotations). The naming
|
|
12
|
+
convention gives every index and constraint a stable name, which Alembic needs to alter or drop them later,
|
|
13
|
+
especially on SQLite (batch mode recreates tables and must name what it recreates). It must stay exactly as it is:
|
|
14
|
+
the apps' existing revisions and databases carry these names, and a change would make every one of them drift.
|
|
15
|
+
`Base` is a ready-made shared one for scripts that only ever load one app's models.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from typing import TYPE_CHECKING, cast
|
|
21
|
+
|
|
22
|
+
from sqlalchemy import MetaData
|
|
23
|
+
from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
|
|
24
|
+
|
|
25
|
+
NAMING_CONVENTION = {
|
|
26
|
+
"ix": "ix_%(table_name)s_%(column_0_N_name)s",
|
|
27
|
+
"uq": "uq_%(table_name)s_%(column_0_N_name)s",
|
|
28
|
+
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
|
29
|
+
"fk": "fk_%(table_name)s_%(column_0_N_name)s_%(referred_table_name)s",
|
|
30
|
+
"pk": "pk_%(table_name)s",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
# What every make_base() returns, for the type checker only: subclassing it gives a model the dataclass
|
|
36
|
+
# constructor (`Note(text="hi")` checked against the annotations). A real class here would be a declarative base
|
|
37
|
+
# of its own, with a registry every app's models would share.
|
|
38
|
+
class DataclassBase(MappedAsDataclass, DeclarativeBase): ...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def make_base() -> type[DataclassBase]:
|
|
42
|
+
"""A new declarative base with its own MetaData (so two apps' models never mix in one process)."""
|
|
43
|
+
|
|
44
|
+
class AppBase(MappedAsDataclass, DeclarativeBase):
|
|
45
|
+
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
46
|
+
|
|
47
|
+
return cast("type[DataclassBase]", AppBase) # the same shape as DataclassBase, a different class
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
Base = make_base()
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""An app's database settings, from its pyproject.toml:
|
|
2
|
+
|
|
3
|
+
[tool.strata-db]
|
|
4
|
+
app = "notes" # owner role name; also picks the URL (config.url_for)
|
|
5
|
+
schema = "notes" # its schema in the shared database (default: the app name)
|
|
6
|
+
models = "notes.models:Base" # module:attribute with .metadata (a Base or a MetaData)
|
|
7
|
+
migrations = "migrations" # folder of Alembic revisions, relative to pyproject.toml
|
|
8
|
+
engine = "portable" # or "postgres": uses Postgres-only features; tests and autogenerate then
|
|
9
|
+
# need Postgres (strata-db and the pytest plugin follow this)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import importlib
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
import tomllib
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from sqlalchemy import MetaData
|
|
24
|
+
from sqlalchemy.engine import Engine
|
|
25
|
+
|
|
26
|
+
TABLE = "strata-db"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Project:
|
|
31
|
+
root: Path
|
|
32
|
+
app: str
|
|
33
|
+
models: str
|
|
34
|
+
migrations_dir: Path
|
|
35
|
+
engine: str = "portable"
|
|
36
|
+
schema: str = ""
|
|
37
|
+
|
|
38
|
+
def __post_init__(self) -> None:
|
|
39
|
+
self.schema = self.schema or self.app
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def load(cls, start: str | os.PathLike[str] | None = None) -> Project:
|
|
43
|
+
"""Find the nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards."""
|
|
44
|
+
p = Path(start or os.getcwd()).resolve()
|
|
45
|
+
for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
|
|
46
|
+
f = d / "pyproject.toml"
|
|
47
|
+
if not f.is_file():
|
|
48
|
+
continue
|
|
49
|
+
cfg = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {})).get(TABLE)
|
|
50
|
+
if cfg:
|
|
51
|
+
return cls(
|
|
52
|
+
root=d,
|
|
53
|
+
app=cfg["app"],
|
|
54
|
+
models=cfg["models"],
|
|
55
|
+
migrations_dir=(d / cfg.get("migrations", "migrations")).resolve(),
|
|
56
|
+
engine=cfg.get("engine", "portable"),
|
|
57
|
+
schema=cfg.get("schema", cfg["app"]),
|
|
58
|
+
)
|
|
59
|
+
raise FileNotFoundError(f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)")
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def metadata(self) -> MetaData:
|
|
63
|
+
from sqlalchemy import MetaData
|
|
64
|
+
|
|
65
|
+
for extra in (self.root / "src", self.root): # the app need not be installed (a test run from its checkout)
|
|
66
|
+
if extra.is_dir() and str(extra) not in sys.path:
|
|
67
|
+
sys.path.insert(0, str(extra))
|
|
68
|
+
mod, _, attr = self.models.partition(":")
|
|
69
|
+
obj: Any = getattr(importlib.import_module(mod), attr or "Base")
|
|
70
|
+
return obj if isinstance(obj, MetaData) else cast("MetaData", obj.metadata)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def postgres_only(self) -> bool:
|
|
74
|
+
return self.engine == "postgres"
|
|
75
|
+
|
|
76
|
+
def url(self) -> str:
|
|
77
|
+
from .config import url_for
|
|
78
|
+
|
|
79
|
+
return url_for(self.app, self.schema)
|
|
80
|
+
|
|
81
|
+
def upgrade(self, engine: Engine, revision: str = "head") -> None:
|
|
82
|
+
"""Migrate to head (safe at every start). On Postgres: in the app's schema, as the app's role."""
|
|
83
|
+
from .migrations import upgrade
|
|
84
|
+
|
|
85
|
+
upgrade(engine, self.migrations_dir, self.metadata, revision, owner_role=self.app, schema=self.schema)
|