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,116 @@
1
+ """The apps' database: one shared PostgreSQL with a schema per app (SQLite for a file path and in tests), typed
2
+ SQLAlchemy models, Alembic migrations generated from them, the `strata-db` command and pytest fixtures. Install the
3
+ extra: `strata-python[db]`.
4
+
5
+ from sqlalchemy import MetaData
6
+ from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
7
+ from strata_python.db import NAMING_CONVENTION, connect, session
8
+
9
+ class Base(MappedAsDataclass, DeclarativeBase): # the app's own base: written out, so ty and pyright accept it
10
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
11
+
12
+ class Note(Base): # a typed record; Alembic generates the table from it
13
+ __tablename__ = "notes"
14
+ id: Mapped[int] = mapped_column(primary_key=True, init=False)
15
+ text: Mapped[str]
16
+
17
+ engine = connect("notes") # schema notes of the shared database (socket, peer auth)
18
+ with session(engine) as s:
19
+ s.add(Note(text="hi")); s.commit()
20
+
21
+ Migrations: `strata-db revision -m "..."` (autogenerate), `strata-db migrate`, `strata-db check`; or in code
22
+ `Project.load(__file__).upgrade(engine)` at service start. Tests: the plugin's `db_session` / `db_engine` / `db_url`
23
+ / `db_env` fixtures and `strata_python.db.testing`. See the README.
24
+
25
+ The names load on first use: the pytest plugin imports `strata_python.db.guard` in every app with strata-python
26
+ installed, and that must not need SQLAlchemy.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import importlib
32
+ from typing import TYPE_CHECKING, Any
33
+
34
+ if TYPE_CHECKING:
35
+ from .config import (
36
+ DatabaseNotConfigured as DatabaseNotConfigured,
37
+ )
38
+ from .config import (
39
+ normalise_url as normalise_url,
40
+ )
41
+ from .config import (
42
+ resolve_url as resolve_url,
43
+ )
44
+ from .config import (
45
+ url_for as url_for,
46
+ )
47
+ from .engine import connect as connect
48
+ from .engine import session as session
49
+ from .guard import LiveDatabaseRefused as LiveDatabaseRefused
50
+ from .migrations import (
51
+ check_migrations as check_migrations,
52
+ )
53
+ from .migrations import (
54
+ downgrade as downgrade,
55
+ )
56
+ from .migrations import (
57
+ drift as drift,
58
+ )
59
+ from .migrations import (
60
+ lint_revisions as lint_revisions,
61
+ )
62
+ from .migrations import (
63
+ stairway as stairway,
64
+ )
65
+ from .migrations import (
66
+ upgrade as upgrade,
67
+ )
68
+ from .models import NAMING_CONVENTION as NAMING_CONVENTION
69
+ from .models import Base as Base
70
+ from .models import make_base as make_base
71
+ from .project import Project as Project
72
+
73
+ _WHERE = {
74
+ "DatabaseNotConfigured": "config",
75
+ "normalise_url": "config",
76
+ "resolve_url": "config",
77
+ "url_for": "config",
78
+ "connect": "engine",
79
+ "session": "engine",
80
+ "LiveDatabaseRefused": "guard",
81
+ "check_migrations": "migrations",
82
+ "downgrade": "migrations",
83
+ "drift": "migrations",
84
+ "lint_revisions": "migrations",
85
+ "stairway": "migrations",
86
+ "upgrade": "migrations",
87
+ "NAMING_CONVENTION": "models",
88
+ "Base": "models",
89
+ "make_base": "models",
90
+ "Project": "project",
91
+ }
92
+ __all__ = [ # noqa: RUF022 (grouped as _WHERE is)
93
+ "DatabaseNotConfigured",
94
+ "normalise_url",
95
+ "resolve_url",
96
+ "url_for",
97
+ "connect",
98
+ "session",
99
+ "LiveDatabaseRefused",
100
+ "check_migrations",
101
+ "downgrade",
102
+ "drift",
103
+ "lint_revisions",
104
+ "stairway",
105
+ "upgrade",
106
+ "NAMING_CONVENTION",
107
+ "Base",
108
+ "make_base",
109
+ "Project",
110
+ ]
111
+
112
+
113
+ def __getattr__(name: str) -> Any:
114
+ if name not in _WHERE:
115
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
116
+ return getattr(importlib.import_module(f"{__name__}.{_WHERE[name]}"), name)
@@ -0,0 +1,5 @@
1
+ """`python -m strata_python.db`: the strata-db command."""
2
+
3
+ from strata_python.db.cli import main
4
+
5
+ main()
@@ -0,0 +1,24 @@
1
+ # Shared Alembic environment for every app: apps have no env.py or alembic.ini of their own.
2
+ # strata_python.db.migrations passes the connection and the app's MetaData in config.attributes.
3
+ from alembic import context
4
+
5
+ from strata_python.db.migrations import include_name
6
+
7
+ cfg = context.config
8
+ connection = cfg.attributes["connection"]
9
+
10
+ context.configure(
11
+ connection=connection,
12
+ target_metadata=cfg.attributes["metadata"],
13
+ # Always render batch ops: on SQLite (limited ALTER) they recreate-and-copy, on Postgres they run plain ALTERs,
14
+ # so a revision generated against either engine runs on both.
15
+ render_as_batch=True,
16
+ compare_type=True,
17
+ # SQLite reflects defaults as raw text ('false' vs the model's false() compiled as 0), so comparing them there
18
+ # reports drift that is not real; Postgres compares them properly, and strata-db check runs on both.
19
+ compare_server_default=connection.dialect.name != "sqlite",
20
+ include_name=include_name,
21
+ process_revision_directives=cfg.attributes.get("process_revision_directives"),
22
+ )
23
+ with context.begin_transaction():
24
+ context.run_migrations()
@@ -0,0 +1,28 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ ${imports if imports else ""}
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = ${repr(up_revision)}
16
+ down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
17
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19
+
20
+
21
+ def upgrade() -> None:
22
+ """Upgrade schema."""
23
+ ${upgrades if upgrades else "pass"}
24
+
25
+
26
+ def downgrade() -> None:
27
+ """Downgrade schema."""
28
+ ${downgrades if downgrades else "pass"}
@@ -0,0 +1,199 @@
1
+ """strata-db: the app-facing command line (run from anywhere inside the app's repo; also `python -m strata_python.db`).
2
+
3
+ strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres]
4
+ add [tool.strata-db] to pyproject.toml and create migrations/
5
+ strata-db new-app [NAME] on the shared server: owner role NAME (NOLOGIN, you are a member) and schema NAME in
6
+ the shared database, owned by it, no USAGE for PUBLIC (other app roles cannot see it).
7
+ No sudo (your role has CREATEDB CREATEROLE). --database for another database (tests)
8
+ strata-db revision -m MSG autogenerate a migration: a scratch database is migrated to head and compared with
9
+ the models; nothing is written if there is no change. --empty for a hand-written one
10
+ strata-db migrate --live [--url URL]
11
+ upgrade the app's schema (default URL: config.url_for(app)) to head (or --to REV).
12
+ --live (or STRATA_DB_LIVE=1) says you mean a real database; refused under tests
13
+ strata-db check on a scratch database: migrate from empty, compare with the models, downgrade to
14
+ base, migrate again. Exit 1 on any problem (models changed without a revision, ...)
15
+ strata-db current --live [--url URL] revision the database is at
16
+ Scratch databases go on a throwaway Postgres (STRATA_DB_TEST_ADMIN_URL, else a private server,
17
+ strata_python.db.testserver), never the real one. `revision` uses Postgres when one can be had, because Alembic
18
+ renders defaults in the scratch database's dialect and Postgres's form (e.g. `false`) also works on SQLite, while
19
+ SQLite's (`0`) breaks Postgres; --sqlite forces SQLite. `check` runs on SQLite and, when reachable, Postgres
20
+ (engine = "postgres" projects: Postgres only).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ from sqlalchemy import create_engine, text
31
+
32
+ from . import migrations as m
33
+ from .config import normalise_url, resolve_url, shared_database
34
+ from .engine import connect
35
+ from .guard import LIVE, LiveDatabaseRefused, allow_live
36
+ from .project import TABLE, Project
37
+ from .scratch import live_admin_url, pg_available, scratch_database
38
+ from .testing import scratch_engine
39
+
40
+ NAME = re.compile(r"[a-z][a-z0-9_]*") # role and schema names: nothing that needs quoting to read
41
+
42
+
43
+ def cmd_init(a: argparse.Namespace) -> None:
44
+ pp = Path.cwd() / "pyproject.toml"
45
+ body = pp.read_text(encoding="utf-8") if pp.exists() else f'[project]\nname = "{a.app}"\nversion = "0.1.0"\n'
46
+ if f"[tool.{TABLE}]" in body:
47
+ sys.exit(f"{pp} already has [tool.{TABLE}]")
48
+ body = (
49
+ body.rstrip("\n") + f'\n\n[tool.{TABLE}]\napp = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
50
+ )
51
+ if a.engine != "portable":
52
+ body += f'engine = "{a.engine}"\n'
53
+ pp.write_text(body, encoding="utf-8")
54
+ (Path.cwd() / "migrations").mkdir(exist_ok=True)
55
+ print(f"wrote [tool.{TABLE}] to {pp}; migrations/ ready. Next: strata-db revision -m 'initial'")
56
+
57
+
58
+ def cmd_new_app(a: argparse.Namespace) -> None:
59
+ try:
60
+ p: Project | None = Project.load()
61
+ except FileNotFoundError:
62
+ p = None
63
+ name: str | None = a.name or (p.app if p else None)
64
+ schema: str | None = a.schema or (p.schema if p and not a.name else name)
65
+ database: str | None = a.database or shared_database()
66
+ if not name or not schema or not NAME.fullmatch(name) or not NAME.fullmatch(schema):
67
+ sys.exit("app and schema names: lower case letters, digits and _ (they are role and schema names)")
68
+ if not database:
69
+ sys.exit("which database? Pass --database or set STRATA_DB_DATABASE")
70
+ adm = create_engine(live_admin_url(), isolation_level="AUTOCOMMIT")
71
+ with adm.connect() as c:
72
+ q = c.dialect.identifier_preparer.quote_identifier
73
+ if not c.execute(text("SELECT 1 FROM pg_roles WHERE rolname = :n"), {"n": name}).scalar():
74
+ c.execute(text(f"CREATE ROLE {q(name)} NOLOGIN"))
75
+ print(f"created role {name}")
76
+ # The schema below is created AUTHORIZATION the role, which needs the caller to be able to SET ROLE to it. A
77
+ # CREATEROLE login gets only ADMIN on a role it creates unless the server sets createrole_self_grant, so
78
+ # grant it explicitly (a no-op notice when the caller is a member already, a superuser included).
79
+ c.execute(text(f"GRANT {q(name)} TO CURRENT_USER"))
80
+ if not c.execute(text("SELECT 1 FROM pg_database WHERE datname = :n"), {"n": database}).scalar():
81
+ c.execute(text(f"CREATE DATABASE {q(database)}"))
82
+ print(f"created database {database}")
83
+ adm.dispose()
84
+ eng = create_engine(adm.url.set(database=database), isolation_level="AUTOCOMMIT")
85
+ with eng.connect() as c:
86
+ q = c.dialect.identifier_preparer.quote_identifier
87
+ if not c.execute(text("SELECT 1 FROM pg_namespace WHERE nspname = :s"), {"s": schema}).scalar():
88
+ c.execute(text(f"CREATE SCHEMA {q(schema)} AUTHORIZATION {q(name)}"))
89
+ c.execute(text(f"REVOKE ALL ON SCHEMA {q(schema)} FROM PUBLIC"))
90
+ print(f"created schema {database}.{schema} (owner {name}, no PUBLIC access)")
91
+ eng.dispose()
92
+ where = resolve_url(name, schema) if database == shared_database() else "(--database given)"
93
+ print(f"{name}: schema {schema} in {database}; URL {where} (strata-db migrate creates the tables)")
94
+
95
+
96
+ def cmd_revision(a: argparse.Namespace) -> None:
97
+ p = Project.load()
98
+ pg = p.postgres_only or a.pg or (not a.sqlite and pg_available())
99
+ print(f"autogenerating against a scratch {'Postgres' if pg else 'SQLite'} database")
100
+ with scratch_database(pg) as url:
101
+ eng = scratch_engine(url)
102
+ m.upgrade(eng, p.migrations_dir, p.metadata)
103
+ path = m.revision(eng, p.migrations_dir, p.metadata, a.message, autogenerate=not a.empty)
104
+ eng.dispose()
105
+ if path:
106
+ print(f"wrote {Path(path).relative_to(p.root).as_posix()}: review it, then commit it")
107
+ else:
108
+ print("no changes: the models match the migrations")
109
+
110
+
111
+ def cmd_migrate(a: argparse.Namespace) -> None:
112
+ if a.live:
113
+ allow_live()
114
+ p = Project.load()
115
+ eng = connect(normalise_url(a.url) if a.url else p.url())
116
+ schema = p.schema if eng.dialect.name == "postgresql" else None
117
+ before = m.current(eng, schema)
118
+ p.upgrade(eng, a.to)
119
+ print(f"{p.app}: {before or 'empty'} -> {m.current(eng, schema)}")
120
+ eng.dispose()
121
+
122
+
123
+ def cmd_check(a: argparse.Namespace) -> None:
124
+ p = Project.load()
125
+ if p.postgres_only or a.pg:
126
+ engines = ["postgres"]
127
+ else:
128
+ engines = ["sqlite"] + (["postgres"] if not a.sqlite and pg_available() else [])
129
+ failed = False
130
+ for e in engines:
131
+ with scratch_database(e == "postgres") as url:
132
+ eng = scratch_engine(url)
133
+ try:
134
+ problems = m.check_migrations(eng, p.migrations_dir, p.metadata)
135
+ except Exception as ex: # a migration that crashes is a failed check, reported like the others
136
+ problems = [f"{type(ex).__name__}: {ex}".split("\n")[0]]
137
+ eng.dispose()
138
+ for x in problems:
139
+ print(f"FAIL [{e}] {x}")
140
+ failed |= bool(problems)
141
+ if not problems:
142
+ print(f"ok [{e}]: {p.app} migrations run from empty, match the models, and downgrade cleanly")
143
+ if "postgres" not in engines and not a.sqlite:
144
+ print("note: Postgres not reachable, checked SQLite only")
145
+ if failed:
146
+ sys.exit(1)
147
+
148
+
149
+ def cmd_current(a: argparse.Namespace) -> None:
150
+ if a.live:
151
+ allow_live()
152
+ p = Project.load()
153
+ eng = connect(normalise_url(a.url) if a.url else p.url())
154
+ print(m.current(eng, p.schema) or "empty")
155
+ eng.dispose()
156
+
157
+
158
+ def main(argv: list[str] | None = None) -> None:
159
+ ap = argparse.ArgumentParser(prog="strata-db", description=(__doc__ or "").split("\n")[0])
160
+ sub = ap.add_subparsers(dest="cmd", required=True)
161
+ s = sub.add_parser("init", help="add [tool.strata-db] to pyproject.toml")
162
+ s.add_argument("--app", required=True)
163
+ s.add_argument("--models", required=True)
164
+ s.add_argument("--engine", choices=["portable", "postgres"], default="portable")
165
+ s.set_defaults(f=cmd_init)
166
+ s = sub.add_parser("new-app", help="role and schema on the shared server")
167
+ s.add_argument("name", nargs="?")
168
+ s.add_argument("--schema")
169
+ s.add_argument("--database", help="default: STRATA_DB_DATABASE")
170
+ s.set_defaults(f=cmd_new_app)
171
+ s = sub.add_parser("revision", help="autogenerate a migration")
172
+ s.add_argument("-m", "--message", required=True)
173
+ s.add_argument("--empty", action="store_true")
174
+ s.add_argument("--pg", action="store_true")
175
+ s.add_argument("--sqlite", action="store_true")
176
+ s.set_defaults(f=cmd_revision)
177
+ live = f"you mean a real database (as {LIVE}=1); refused under tests"
178
+ s = sub.add_parser("migrate", help="upgrade a database to head")
179
+ s.add_argument("--url")
180
+ s.add_argument("--live", action="store_true", help=live)
181
+ s.add_argument("--to", default="head")
182
+ s.set_defaults(f=cmd_migrate)
183
+ s = sub.add_parser("check", help="the migration checks on scratch databases")
184
+ s.add_argument("--pg", action="store_true", help="Postgres only")
185
+ s.add_argument("--sqlite", action="store_true", help="SQLite only")
186
+ s.set_defaults(f=cmd_check)
187
+ s = sub.add_parser("current", help="the revision a database is at")
188
+ s.add_argument("--url")
189
+ s.add_argument("--live", action="store_true", help=live)
190
+ s.set_defaults(f=cmd_current)
191
+ a = ap.parse_args(argv)
192
+ try:
193
+ a.f(a)
194
+ except LiveDatabaseRefused as e:
195
+ sys.exit(f"strata-db: {e}")
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()
@@ -0,0 +1,85 @@
1
+ """Where an app's data is.
2
+
3
+ Layout on the shared server: ONE database (its name in `STRATA_DB_DATABASE`, set where the apps run) with a schema
4
+ per app, owned by the app's role, so apps can query each other's tables (`select ... from notes.notes join
5
+ photos.albums ...`). Postgres cannot join across databases, so never one database per app.
6
+
7
+ Order: `STRATA_DB_URL` (any app; handy in tests and one-off runs), then `<APP>_DATABASE_URL` (e.g.
8
+ `NOTES_DATABASE_URL`), then the default: `postgresql+psycopg:///<database>?options=-csearch_path%3D<schema>` over the
9
+ Unix socket with peer auth (you connect as your OS user, a member of the app's owner role). The search_path makes the
10
+ app's unqualified table names resolve to its schema. A plain path ("data/app.db", "~/x.sqlite") means SQLite, which
11
+ has no schemas.
12
+
13
+ The shared database has no built-in name: the name is the owner's, and this package is public (AGENTS.md rule 4).
14
+
15
+ A real Postgres database is opt-in (see `strata_python.db.guard`): url_for() and connect() refuse one unless the
16
+ process has `STRATA_DB_LIVE=1`, and refuse it always during tests.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+
24
+ URL = "STRATA_DB_URL"
25
+ DATABASE = "STRATA_DB_DATABASE"
26
+
27
+
28
+ class DatabaseNotConfigured(RuntimeError):
29
+ """No URL for the app and no shared database named, so there is nowhere to connect."""
30
+
31
+
32
+ def normalise_url(url: str) -> str:
33
+ """postgresql:///x -> postgresql+psycopg:///x (psycopg 3); a bare path -> sqlite:///abs/path."""
34
+ if url.startswith(("postgresql://", "postgres://")):
35
+ return "postgresql+psycopg://" + url.split("://", 1)[1]
36
+ if "://" not in url and not url.startswith("sqlite:"):
37
+ return "sqlite:///" + os.path.abspath(os.path.expanduser(url))
38
+ return url
39
+
40
+
41
+ def env_name(app: str) -> str:
42
+ """The app's own URL variable: "my-app" -> MY_APP_DATABASE_URL."""
43
+ return re.sub(r"[^A-Z0-9]", "_", app.upper()) + "_DATABASE_URL"
44
+
45
+
46
+ def shared_database() -> str | None:
47
+ """The shared database's name (`STRATA_DB_DATABASE`), read each time so a test or launcher can set it late."""
48
+ return os.environ.get(DATABASE) or None
49
+
50
+
51
+ def schema_url(schema: str, database: str | None = None) -> str:
52
+ database = database or shared_database()
53
+ if not database:
54
+ raise DatabaseNotConfigured(
55
+ f"no database URL for {schema!r}: set {URL} or {env_name(schema)}, or name the shared database in "
56
+ f"{DATABASE} (in the service environment, next to STRATA_DB_LIVE=1)"
57
+ )
58
+ return f"postgresql+psycopg:///{database}?options=-csearch_path%3D{schema}"
59
+
60
+
61
+ def with_search_path(url: str, schema: str) -> str:
62
+ """A Postgres URL that resolves unqualified names in `schema`, unless it already sets search_path itself.
63
+ Without this, a URL from the environment would read and write a different schema (public) from the one
64
+ Project.upgrade() migrates (the app's)."""
65
+ if not url.startswith("postgresql") or "search_path" in url:
66
+ return url
67
+ return url + ("&" if "?" in url else "?") + f"options=-csearch_path%3D{schema}"
68
+
69
+
70
+ def resolve_url(app: str, schema: str | None = None) -> str:
71
+ """Where `app`'s data is (see the module docstring), without the live-database check."""
72
+ for var in (URL, env_name(app)):
73
+ if value := os.environ.get(var):
74
+ return with_search_path(normalise_url(value), schema or app)
75
+ return schema_url(schema or app)
76
+
77
+
78
+ def url_for(app: str, schema: str | None = None) -> str:
79
+ """resolve_url(), refused (guard.LiveDatabaseRefused) when it is a real Postgres database and the process has
80
+ not opted in with `STRATA_DB_LIVE=1`, or is running tests."""
81
+ from .guard import check_url
82
+
83
+ url = resolve_url(app, schema)
84
+ check_url(url, f"url_for({app!r})")
85
+ return url
@@ -0,0 +1,53 @@
1
+ """Engines and sessions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sqlite3
7
+ from collections.abc import Generator
8
+ from contextlib import contextmanager
9
+ from typing import Any
10
+
11
+ from sqlalchemy import create_engine, event
12
+ from sqlalchemy.engine import Engine
13
+ from sqlalchemy.orm import Session
14
+
15
+ from .config import normalise_url, url_for
16
+ from .guard import check_url
17
+
18
+ APP_NAME = re.compile(r"[a-z][a-z0-9_-]*")
19
+
20
+
21
+ def connect(app_or_url: str, **kw: Any) -> Engine:
22
+ """Engine for an app name ("notes": see config.url_for) or a URL / SQLite path.
23
+ SQLite gets foreign keys on, WAL and a busy timeout, so it behaves like the server in tests.
24
+ A real Postgres database needs `STRATA_DB_LIVE=1` and is never allowed during tests (strata_python.db.guard)."""
25
+ url = url_for(app_or_url) if APP_NAME.fullmatch(app_or_url) else normalise_url(app_or_url)
26
+ check_url(url, f"connect({app_or_url!r})" if "://" not in app_or_url else "connect(url)")
27
+ engine = create_engine(url, **kw)
28
+ if engine.dialect.name == "sqlite":
29
+ sqlite_pragmas(engine)
30
+ return engine
31
+
32
+
33
+ def sqlite_pragmas(engine: Engine, wal: bool = True) -> None:
34
+ """Foreign keys on, a 30 s busy timeout and (for a file) WAL on every new SQLite connection of `engine`."""
35
+
36
+ def on_connect(dbapi_conn: Any, _record: Any) -> None:
37
+ if not isinstance(dbapi_conn, sqlite3.Connection):
38
+ return
39
+ c = dbapi_conn.cursor()
40
+ c.execute("PRAGMA foreign_keys = ON")
41
+ c.execute("PRAGMA busy_timeout = 30000")
42
+ if wal and engine.url.database not in (None, "", ":memory:"):
43
+ c.execute("PRAGMA journal_mode = WAL")
44
+ c.close()
45
+
46
+ event.listen(engine, "connect", on_connect)
47
+
48
+
49
+ @contextmanager
50
+ def session(engine: Engine, **kw: Any) -> Generator[Session]:
51
+ """A Session that is closed afterwards (commit yourself: s.commit())."""
52
+ with Session(engine, **kw) as s:
53
+ yield s
@@ -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)