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 CHANGED
@@ -6,7 +6,8 @@ web reverse-proxy-safe page serving, health and settings routes, static
6
6
  cli argparse commands every app has: doctor, set, serve
7
7
  http_server a real scripted HTTP server on loopback for tests of outbound requests
8
8
  live run a FastAPI app on a real loopback port for tests
9
- pytest plugin (automatic once installed): hermetic environment, no-network guard, `http_server` and `live_app` fixtures
9
+ testing the fakes for HTTP, subprocesses and sleep, and CLI runners, shared by every app's tests
10
+ pytest plugin (automatic once installed): hermetic environment, no-network guard, `http_server`, `live_app` and the fake_* fixtures
10
11
  check `strata-check`, the one gate: lockfile, ruff, ruff format, pyright, ty, unit tests with coverage
11
12
  public_check `strata-public-check`: no email addresses, private addresses, home paths or owner-listed names in what is published
12
13
  """
@@ -0,0 +1,113 @@
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 strata_python.db import connect, make_base, session
6
+ from sqlalchemy.orm import Mapped, mapped_column
7
+
8
+ Base = make_base()
9
+ class Note(Base): # a typed record; Alembic generates the table from it
10
+ __tablename__ = "notes"
11
+ id: Mapped[int] = mapped_column(primary_key=True, init=False)
12
+ text: Mapped[str]
13
+
14
+ engine = connect("notes") # schema notes of the shared database (socket, peer auth)
15
+ with session(engine) as s:
16
+ s.add(Note(text="hi")); s.commit()
17
+
18
+ Migrations: `strata-db revision -m "..."` (autogenerate), `strata-db migrate`, `strata-db check`; or in code
19
+ `Project.load(__file__).upgrade(engine)` at service start. Tests: the plugin's `db_session` / `db_engine` / `db_url`
20
+ / `db_env` fixtures and `strata_python.db.testing`. See the README.
21
+
22
+ The names load on first use: the pytest plugin imports `strata_python.db.guard` in every app with strata-python
23
+ installed, and that must not need SQLAlchemy.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import importlib
29
+ from typing import TYPE_CHECKING, Any
30
+
31
+ if TYPE_CHECKING:
32
+ from .config import (
33
+ DatabaseNotConfigured as DatabaseNotConfigured,
34
+ )
35
+ from .config import (
36
+ normalise_url as normalise_url,
37
+ )
38
+ from .config import (
39
+ resolve_url as resolve_url,
40
+ )
41
+ from .config import (
42
+ url_for as url_for,
43
+ )
44
+ from .engine import connect as connect
45
+ from .engine import session as session
46
+ from .guard import LiveDatabaseRefused as LiveDatabaseRefused
47
+ from .migrations import (
48
+ check_migrations as check_migrations,
49
+ )
50
+ from .migrations import (
51
+ downgrade as downgrade,
52
+ )
53
+ from .migrations import (
54
+ drift as drift,
55
+ )
56
+ from .migrations import (
57
+ lint_revisions as lint_revisions,
58
+ )
59
+ from .migrations import (
60
+ stairway as stairway,
61
+ )
62
+ from .migrations import (
63
+ upgrade as upgrade,
64
+ )
65
+ from .models import NAMING_CONVENTION as NAMING_CONVENTION
66
+ from .models import Base as Base
67
+ from .models import make_base as make_base
68
+ from .project import Project as Project
69
+
70
+ _WHERE = {
71
+ "DatabaseNotConfigured": "config",
72
+ "normalise_url": "config",
73
+ "resolve_url": "config",
74
+ "url_for": "config",
75
+ "connect": "engine",
76
+ "session": "engine",
77
+ "LiveDatabaseRefused": "guard",
78
+ "check_migrations": "migrations",
79
+ "downgrade": "migrations",
80
+ "drift": "migrations",
81
+ "lint_revisions": "migrations",
82
+ "stairway": "migrations",
83
+ "upgrade": "migrations",
84
+ "NAMING_CONVENTION": "models",
85
+ "Base": "models",
86
+ "make_base": "models",
87
+ "Project": "project",
88
+ }
89
+ __all__ = [ # noqa: RUF022 (grouped as _WHERE is)
90
+ "DatabaseNotConfigured",
91
+ "normalise_url",
92
+ "resolve_url",
93
+ "url_for",
94
+ "connect",
95
+ "session",
96
+ "LiveDatabaseRefused",
97
+ "check_migrations",
98
+ "downgrade",
99
+ "drift",
100
+ "lint_revisions",
101
+ "stairway",
102
+ "upgrade",
103
+ "NAMING_CONVENTION",
104
+ "Base",
105
+ "make_base",
106
+ "Project",
107
+ ]
108
+
109
+
110
+ def __getattr__(name: str) -> Any:
111
+ if name not in _WHERE:
112
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
113
+ 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