strata-python 0.2.0__py3-none-any.whl → 0.2.2__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.
Files changed (36) hide show
  1. strata_python/__init__.py +2 -1
  2. strata_python/cli.py +99 -20
  3. strata_python/clients/__init__.py +2 -0
  4. strata_python/clients/models.py +780 -0
  5. strata_python/db/__init__.py +116 -0
  6. strata_python/db/__main__.py +5 -0
  7. strata_python/db/_alembic/env.py +24 -0
  8. strata_python/db/_alembic/script.py.mako +28 -0
  9. strata_python/db/cli.py +199 -0
  10. strata_python/db/config.py +85 -0
  11. strata_python/db/engine.py +53 -0
  12. strata_python/db/guard.py +159 -0
  13. strata_python/db/migrations.py +243 -0
  14. strata_python/db/models.py +62 -0
  15. strata_python/db/project.py +98 -0
  16. strata_python/db/pytest_plugin.py +205 -0
  17. strata_python/db/scratch.py +143 -0
  18. strata_python/db/settings.py +63 -0
  19. strata_python/db/testing.py +43 -0
  20. strata_python/db/testserver.py +205 -0
  21. strata_python/oslib.py +44 -5
  22. strata_python/pages/__init__.py +21 -0
  23. strata_python/pages/model.py +241 -0
  24. strata_python/pages/render.py +273 -0
  25. strata_python/public_check.py +54 -8
  26. strata_python/pytest_plugin.py +70 -1
  27. strata_python/settings.py +243 -42
  28. strata_python/testing.py +257 -0
  29. strata_python/web.py +15 -6
  30. strata_python-0.2.2.dist-info/METADATA +334 -0
  31. strata_python-0.2.2.dist-info/RECORD +38 -0
  32. {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +2 -0
  33. strata_python-0.2.0.dist-info/METADATA +0 -82
  34. strata_python-0.2.0.dist-info/RECORD +0 -16
  35. {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
  36. {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
@@ -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,62 @@
1
+ """Declarative bases for apps' models.
2
+
3
+ from sqlalchemy import MetaData
4
+ from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
5
+ from strata_python.db import NAMING_CONVENTION
6
+
7
+ class Base(MappedAsDataclass, DeclarativeBase): # one per app, in its models module
8
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
9
+
10
+ class Note(Base):
11
+ __tablename__ = "notes"
12
+ id: Mapped[int] = mapped_column(primary_key=True, init=False)
13
+ text: Mapped[str]
14
+
15
+ MappedAsDataclass makes each model a typed record (constructor, repr, eq from the annotations). The naming
16
+ convention gives every index and constraint a stable name, which Alembic needs to alter or drop them later,
17
+ especially on SQLite (batch mode recreates tables and must name what it recreates). It must stay exactly as it is:
18
+ the apps' existing revisions and databases carry these names, and a change would make every one of them drift.
19
+ `Base` is a ready-made shared one for scripts that only ever load one app's models.
20
+
21
+ An app writes its base class out, as above, rather than `Base = make_base()` (issue #20): ty cannot take a value of
22
+ type `type[...]` as a base class, since it cannot know that value's MRO, and the gate fails on its warning. pyright
23
+ accepts either. A class statement cannot be shared from here instead: SQLAlchemy makes only a *direct* subclass of
24
+ DeclarativeBase a base with its own registry and MetaData, so a subclass of a base defined here would put every app's
25
+ tables in one MetaData. `make_base()` stays for code that needs a fresh base at run time (tests, scripts).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typing import TYPE_CHECKING, cast
31
+
32
+ from sqlalchemy import MetaData
33
+ from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
34
+
35
+ NAMING_CONVENTION = {
36
+ "ix": "ix_%(table_name)s_%(column_0_N_name)s",
37
+ "uq": "uq_%(table_name)s_%(column_0_N_name)s",
38
+ "ck": "ck_%(table_name)s_%(constraint_name)s",
39
+ "fk": "fk_%(table_name)s_%(column_0_N_name)s_%(referred_table_name)s",
40
+ "pk": "pk_%(table_name)s",
41
+ }
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ # What every make_base() returns, for the type checker only: subclassing it gives a model the dataclass
46
+ # constructor (`Note(text="hi")` checked against the annotations). A real class here would be a declarative base
47
+ # of its own, with a registry every app's models would share.
48
+ class DataclassBase(MappedAsDataclass, DeclarativeBase): ...
49
+
50
+
51
+ def make_base() -> type[DataclassBase]:
52
+ """A new declarative base with its own MetaData (so two apps' models never mix in one process), for code that needs
53
+ one at run time. An app's models module writes its class out instead (see the module docstring): ty cannot
54
+ subclass the result."""
55
+
56
+ class AppBase(MappedAsDataclass, DeclarativeBase):
57
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
58
+
59
+ return cast("type[DataclassBase]", AppBase) # the same shape as DataclassBase, a different class
60
+
61
+
62
+ Base = make_base()
@@ -0,0 +1,98 @@
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
+ def find_table(start: str | os.PathLike[str] | None = None) -> tuple[Path, dict[str, Any]] | None:
30
+ """The nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards: its folder and the table.
31
+ Standard library only, so the pytest plugin can ask without loading SQLAlchemy."""
32
+ p = Path(start or os.getcwd()).resolve()
33
+ for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
34
+ f = d / "pyproject.toml"
35
+ if not f.is_file():
36
+ continue
37
+ cfg = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {})).get(TABLE)
38
+ if cfg:
39
+ return d, cast("dict[str, Any]", cfg)
40
+ return None
41
+
42
+
43
+ @dataclass
44
+ class Project:
45
+ root: Path
46
+ app: str
47
+ models: str
48
+ migrations_dir: Path
49
+ engine: str = "portable"
50
+ schema: str = ""
51
+
52
+ def __post_init__(self) -> None:
53
+ self.schema = self.schema or self.app
54
+
55
+ @classmethod
56
+ def load(cls, start: str | os.PathLike[str] | None = None) -> Project:
57
+ """Find the nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards."""
58
+ found = find_table(start)
59
+ if found is None:
60
+ p = Path(start or os.getcwd()).resolve()
61
+ raise FileNotFoundError(
62
+ f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
63
+ )
64
+ d, cfg = found
65
+ return cls(
66
+ root=d,
67
+ app=cfg["app"],
68
+ models=cfg["models"],
69
+ migrations_dir=(d / cfg.get("migrations", "migrations")).resolve(),
70
+ engine=cfg.get("engine", "portable"),
71
+ schema=cfg.get("schema", cfg["app"]),
72
+ )
73
+
74
+ @property
75
+ def metadata(self) -> MetaData:
76
+ from sqlalchemy import MetaData
77
+
78
+ for extra in (self.root / "src", self.root): # the app need not be installed (a test run from its checkout)
79
+ if extra.is_dir() and str(extra) not in sys.path:
80
+ sys.path.insert(0, str(extra))
81
+ mod, _, attr = self.models.partition(":")
82
+ obj: Any = getattr(importlib.import_module(mod), attr or "Base")
83
+ return obj if isinstance(obj, MetaData) else cast("MetaData", obj.metadata)
84
+
85
+ @property
86
+ def postgres_only(self) -> bool:
87
+ return self.engine == "postgres"
88
+
89
+ def url(self) -> str:
90
+ from .config import url_for
91
+
92
+ return url_for(self.app, self.schema)
93
+
94
+ def upgrade(self, engine: Engine, revision: str = "head") -> None:
95
+ """Migrate to head (safe at every start). On Postgres: in the app's schema, as the app's role."""
96
+ from .migrations import upgrade
97
+
98
+ upgrade(engine, self.migrations_dir, self.metadata, revision, owner_role=self.app, schema=self.schema)
@@ -0,0 +1,205 @@
1
+ """pytest fixtures for apps with a database (strata_python.db). Registered with every strata-python install, inert
2
+ unless the db extra is installed: nothing here imports SQLAlchemy until a fixture runs.
3
+
4
+ db_engine an Engine on a fresh database with the app's migrations applied, per test
5
+ db_session a Session on it (closed afterwards)
6
+ db_url a URL to a fresh migrated database, per test, for code that makes its own engine (connect(url))
7
+ db_env for app code that connects by itself (connect("myapp")): points STRATA_DB_URL and <APP>_DATABASE_URL
8
+ at db_url for the test. Make it autouse in the app's conftest.py to cover every test
9
+ db_backend "sqlite" or "postgres"
10
+ db_project the app's Project ([tool.strata-db] in pyproject.toml)
11
+
12
+ Default backend: SQLite. The migrations run ONCE per session into a template; each test gets a copy (in memory for
13
+ db_engine, a file for db_url), so a test costs a copy, not a migration.
14
+ `pytest --pg` (also `--strata-pg`; or STRATA_DB_TEST=postgres, or engine = "postgres" in the project) uses a real Postgres instead:
15
+ a template database is migrated once and each test gets `CREATE DATABASE ... TEMPLATE` (a file copy on the server,
16
+ milliseconds), dropped afterwards. That server is a throwaway one, never the real server: STRATA_DB_TEST_ADMIN_URL
17
+ if set (CI), otherwise a private server started for the run (strata_python.db.testserver).
18
+
19
+ When is it on? Only for an app that uses strata_python.db: SQLAlchemy and Alembic are installed (the db extra) AND
20
+ the project says so, by a [tool.strata-db] table in its pyproject.toml (found from pytest's rootdir upwards) or by
21
+ `strata_db = true` in its pytest ini options (`strata_db = false` turns it off whatever else is there). Having
22
+ SQLAlchemy and Alembic installed by some other package is not enough (issue #19): such an app, or one still on the old
23
+ database package, must be able to run pytest with this plugin registered and inert.
24
+
25
+ When it is on, the plugin switches on the test guard (strata_python.db.guard) in pytest_load_initial_conftests, before
26
+ conftest.py or any app module is imported (or, when it is loaded from a conftest.py itself, as in this repo's own
27
+ tests, in pytest_configure, before any test runs): for the whole run, every Postgres connection in the process (connect(),
28
+ create_engine(), psycopg.connect()) and in its subprocesses (STRATA_DB_TESTING=1) is refused unless it is a
29
+ throwaway strata_db_* database. A test that would reach the shared database fails with LiveDatabaseRefused instead.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import contextlib
35
+ import os
36
+ import shutil
37
+ import tempfile
38
+ from collections.abc import Iterator
39
+ from importlib.util import find_spec
40
+ from pathlib import Path
41
+ from typing import TYPE_CHECKING, cast
42
+
43
+ import pytest
44
+
45
+ from . import guard
46
+
47
+ if TYPE_CHECKING:
48
+ from sqlalchemy.engine import Engine
49
+ from sqlalchemy.orm import Session
50
+
51
+ from .project import Project
52
+
53
+ TEST_BACKEND = "STRATA_DB_TEST"
54
+ INSTALLED = find_spec("sqlalchemy") is not None and find_spec("alembic") is not None
55
+ INI = "strata_db"
56
+ PG_DEST = "strata_db_pg"
57
+ PG_HELP = "run strata_python.db fixtures on a throwaway PostgreSQL"
58
+ _ACTIVE = pytest.StashKey[bool]() # per Config, not a module global: pytester runs nested sessions in one process
59
+
60
+
61
+ def pytest_addoption(parser: pytest.Parser) -> None:
62
+ # Only names of our own here: another plugin (the old database package) may also add --pg, and two addoption
63
+ # calls for one name raise. --pg itself is added once we know the plugin is on (_activate).
64
+ parser.addoption("--strata-pg", action="store_true", dest=PG_DEST, help=PG_HELP)
65
+ parser.addini(INI, type="bool", default=None, help="turn the strata_python.db fixtures and test guard on or off")
66
+
67
+
68
+ def active(config: pytest.Config) -> bool:
69
+ """Whether this run uses strata_python.db (see the module docstring)."""
70
+ if not INSTALLED:
71
+ return False
72
+ wanted = cast("bool | None", config.getini(INI))
73
+ if wanted is not None:
74
+ return bool(wanted)
75
+ from .project import find_table
76
+
77
+ return find_table(config.rootpath) is not None
78
+
79
+
80
+ def _activate(config: pytest.Config, parser: pytest.Parser | None) -> None:
81
+ if _ACTIVE in config.stash:
82
+ return
83
+ config.stash[_ACTIVE] = on = active(config)
84
+ if not on:
85
+ return
86
+ guard.enter_test_mode()
87
+ if parser is not None: # still before the full command line is parsed, so --pg given there is recognised
88
+ # ValueError: another plugin (the old database package) has --pg; it means the same, and db_backend reads it
89
+ with contextlib.suppress(ValueError):
90
+ parser.addoption("--pg", action="store_true", dest=PG_DEST, help=PG_HELP)
91
+
92
+
93
+ @pytest.hookimpl(tryfirst=True)
94
+ def pytest_load_initial_conftests(early_config: pytest.Config, parser: pytest.Parser) -> None:
95
+ _activate(early_config, parser) # entry point or -p: before conftest.py and the app's modules are imported
96
+
97
+
98
+ def pytest_configure(config: pytest.Config) -> None:
99
+ _activate(config, None) # loaded from a conftest.py (pytest_plugins): the hook above has already run
100
+
101
+
102
+ @pytest.fixture(scope="session")
103
+ def db_project(request: pytest.FixtureRequest) -> Project:
104
+ from .project import Project
105
+
106
+ if not request.config.stash.get(_ACTIVE, False):
107
+ pytest.fail(
108
+ "the strata_python.db fixtures are off: they need the db extra (strata-python[db]) and a [tool.strata-db]"
109
+ f" table in pyproject.toml, or {INI} = true in the pytest ini options",
110
+ pytrace=False,
111
+ )
112
+ return Project.load(request.config.rootpath)
113
+
114
+
115
+ @pytest.fixture(scope="session")
116
+ def db_backend(request: pytest.FixtureRequest, db_project: Project) -> str:
117
+ cfg = request.config
118
+ pg = cfg.getoption(PG_DEST) or cfg.getoption("--pg", default=False) # ours, or another plugin's --pg
119
+ pg = pg or os.environ.get(TEST_BACKEND) == "postgres" or db_project.postgres_only
120
+ return "postgres" if pg else "sqlite"
121
+
122
+
123
+ @pytest.fixture(scope="session")
124
+ def _db_template(db_project: Project, db_backend: str) -> Iterator[str]:
125
+ from sqlalchemy import create_engine
126
+
127
+ from . import migrations as m
128
+ from .engine import sqlite_pragmas
129
+ from .scratch import create_pg, drop_pg, unique
130
+
131
+ if db_backend == "postgres":
132
+ name = unique(f"tmpl_{db_project.app}")
133
+ eng = create_engine(create_pg(name))
134
+ m.upgrade(eng, db_project.migrations_dir, db_project.metadata)
135
+ eng.dispose() # a template must have no open connections when it is copied
136
+ yield name
137
+ drop_pg(name)
138
+ else:
139
+ d = tempfile.mkdtemp(prefix="strata_db_")
140
+ path = os.path.join(d, "template.db")
141
+ eng = create_engine("sqlite:///" + path) # no WAL: the template must be one self-contained file
142
+ sqlite_pragmas(eng, wal=False)
143
+ m.upgrade(eng, db_project.migrations_dir, db_project.metadata)
144
+ eng.dispose()
145
+ yield path
146
+ shutil.rmtree(d, ignore_errors=True)
147
+
148
+
149
+ @pytest.fixture
150
+ def db_engine(_db_template: str, db_backend: str, db_project: Project) -> Iterator[Engine]:
151
+ from sqlalchemy import create_engine
152
+ from sqlalchemy.pool import StaticPool
153
+
154
+ from .engine import sqlite_pragmas
155
+ from .scratch import create_pg, drop_pg, sqlite_copy_to_memory, unique
156
+
157
+ if db_backend == "postgres":
158
+ name = unique(f"test_{db_project.app}")
159
+ eng = create_engine(create_pg(name, template=_db_template))
160
+ yield eng
161
+ eng.dispose()
162
+ drop_pg(name)
163
+ else:
164
+ mem = sqlite_copy_to_memory(_db_template)
165
+ eng = create_engine("sqlite://", creator=lambda: mem, poolclass=StaticPool)
166
+ sqlite_pragmas(eng, wal=False)
167
+ yield eng
168
+ eng.dispose()
169
+ mem.close()
170
+
171
+
172
+ @pytest.fixture
173
+ def db_session(db_engine: Engine) -> Iterator[Session]:
174
+ from sqlalchemy.orm import Session
175
+
176
+ with Session(db_engine) as s:
177
+ yield s
178
+
179
+
180
+ @pytest.fixture
181
+ def db_url(_db_template: str, db_backend: str, db_project: Project, tmp_path: Path) -> Iterator[str]:
182
+ from .scratch import create_pg, drop_pg, unique
183
+
184
+ if db_backend == "postgres":
185
+ name = unique(f"test_{db_project.app}")
186
+ yield create_pg(name, template=_db_template)
187
+ drop_pg(name)
188
+ else:
189
+ path = tmp_path / "test.db"
190
+ shutil.copyfile(_db_template, path)
191
+ yield f"sqlite:///{path}"
192
+
193
+
194
+ @pytest.fixture
195
+ def db_env(db_url: str, db_backend: str, db_project: Project, monkeypatch: pytest.MonkeyPatch) -> str:
196
+ """Points the app's own connect("<app>") at a fresh migrated test database for this test (STRATA_DB_URL and
197
+ <APP>_DATABASE_URL). On Postgres the fixtures' tables are in public, so the URL says search_path=public."""
198
+ from .config import URL, env_name
199
+
200
+ url = db_url
201
+ if db_backend == "postgres":
202
+ url += ("&" if "?" in url else "?") + "options=-csearch_path%3Dpublic"
203
+ monkeypatch.setenv(URL, url)
204
+ monkeypatch.setenv(env_name(db_project.app), url)
205
+ return url