strata-python 0.2.5__py3-none-any.whl → 0.2.7__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/cli.py CHANGED
@@ -5,6 +5,7 @@
5
5
  checks=[Check("ffmpeg", program("ffmpeg"))])
6
6
  add_set(sub, SETTINGS)
7
7
  add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
8
+ add_openapi(sub, create_app) # myapp openapi [-o web/openapi.json | -] [--check]
8
9
  args = parser.parse_args(argv); return args.fn(args)
9
10
 
10
11
  Each command sets `fn` on its parser; the handler returns the exit code."""
@@ -15,10 +16,14 @@ import shutil
15
16
  import sys
16
17
  from collections.abc import Callable, Iterable
17
18
  from dataclasses import dataclass
18
- from typing import Any, Literal
19
+ from pathlib import Path
20
+ from typing import TYPE_CHECKING, Any, Literal
19
21
 
20
22
  from strata_python.settings import Settings
21
23
 
24
+ if TYPE_CHECKING:
25
+ from fastapi import FastAPI
26
+
22
27
  Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
23
28
 
24
29
  Status = Literal["ok", "missing", "slow", "broken"]
@@ -128,7 +133,8 @@ def add_set(sub: Sub, settings: Settings) -> None:
128
133
  settings.save({args.key: None if args.value == "default" else args.value})
129
134
  except ValueError as e:
130
135
  sys.exit(str(e))
131
- print(f"{args.key} = {settings.get(args.key)}")
136
+ allowed = settings.allowed(args.key)
137
+ print(f"{args.key} = {settings.get(args.key)}" + (f" (one of: {', '.join(allowed)})" if allowed else ""))
132
138
  return 0
133
139
 
134
140
  p = sub.add_parser("set", help=f'show or change a setting ({", ".join(settings.keys)}); value "default" resets it')
@@ -148,3 +154,40 @@ def add_serve(sub: Sub, run: Callable[[str, int], None], *, default_port: int) -
148
154
  p.add_argument("--host", default="127.0.0.1")
149
155
  p.add_argument("--port", type=int, default=default_port)
150
156
  p.set_defaults(fn=cmd_serve)
157
+
158
+
159
+ def add_openapi(sub: Sub, create_app: "Callable[[], FastAPI]", *, default: Path = Path("web/openapi.json")) -> None:
160
+ """`openapi [-o PATH|-] [--check]`: write the app's schema (`web.openapi_text`) to `default`, another path or
161
+ stdout, for strata-react's `strata-api-types`, which reads the file so CI needs no server. `--check` writes
162
+ nothing and exits 1 when the file differs, so a Python-only CI job can gate it too. The app is built only when
163
+ the command runs, so `create_app` may be slow."""
164
+
165
+ def cmd_openapi(args: argparse.Namespace) -> int:
166
+ from strata_python import web # here, so the app's other commands do not import FastAPI
167
+
168
+ text = web.openapi_text(create_app())
169
+ out: str = args.output
170
+ if out == "-":
171
+ if args.check:
172
+ sys.exit("--check compares a file; give -o PATH")
173
+ sys.stdout.write(text)
174
+ return 0
175
+ path = Path(out)
176
+ if args.check:
177
+ current = path.read_text(encoding="utf-8") if path.is_file() else None
178
+ if current == text:
179
+ return 0
180
+ print(
181
+ f"{path} is {'missing' if current is None else 'out of date'}: run the openapi command", file=sys.stderr
182
+ )
183
+ return 1
184
+ path.parent.mkdir(parents=True, exist_ok=True)
185
+ with open(path, "w", encoding="utf-8", newline="\n") as f: # LF on Windows too, or the check never agrees
186
+ f.write(text)
187
+ print(f"wrote {path}")
188
+ return 0
189
+
190
+ p = sub.add_parser("openapi", help=f"write the API schema for the web app's types (default {default.as_posix()})")
191
+ p.add_argument("-o", "--output", default=str(default), help='file to write, or "-" for stdout')
192
+ p.add_argument("--check", action="store_true", help="write nothing; exit 1 if the file differs")
193
+ p.set_defaults(fn=cmd_openapi)
@@ -13,6 +13,7 @@ generated from it instead of copied.
13
13
  Page[T] one page of a list: items, the cursor for the next page (None at the end), the total when it is known
14
14
  FileRef a file by content and place: sha256, size, mtime, root, rel (the path under that root)
15
15
  Judgment one pairwise choice by a person or a model: a, b, the winner (a, b or tie), who, when, undone when
16
+ ApiModel a base for an app's own response shapes: a field with a default is still required in the schema
16
17
 
17
18
  Times are timezone-aware datetimes, sent as ISO 8601 with their offset: the apps had both ISO text and float epochs,
18
19
  and only one of those reads correctly in a browser. Use `utc(epoch)` to turn a stored float into one."""
@@ -30,7 +31,17 @@ def utc(epoch: float | None) -> datetime.datetime | None:
30
31
  return None if epoch is None else datetime.datetime.fromtimestamp(epoch, datetime.UTC)
31
32
 
32
33
 
33
- class Health(BaseModel):
34
+ class ApiModel(BaseModel):
35
+ """The base of the response shapes here, and for an app's own. pydantic marks a field with a default as optional in
36
+ the schema, so the generated TypeScript gets a `?` though the server always sends it; this config makes the
37
+ response schema say what is sent (`Page.next` is `string | null`, not `next?`). Use it for responses: a request
38
+ body built on it has an `-Input` and an `-Output` schema. `FileRef` and `Judgment` stay on `BaseModel`, since an
39
+ app may take them as a request body."""
40
+
41
+ model_config = ConfigDict(json_schema_serialization_defaults_required=True)
42
+
43
+
44
+ class Health(ApiModel):
34
45
  """What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
35
46
 
36
47
  model_config = ConfigDict(extra="allow")
@@ -39,7 +50,7 @@ class Health(BaseModel):
39
50
  commit: str | None = None # the source commit the server runs, so a probe can tell a stale deploy
40
51
 
41
52
 
42
- class Folder(BaseModel):
53
+ class Folder(ApiModel):
43
54
  """A folder the app uses, and the disk it is on (None when the folder does not exist yet)."""
44
55
 
45
56
  name: str
@@ -49,7 +60,7 @@ class Folder(BaseModel):
49
60
  total_bytes: int | None = None
50
61
 
51
62
 
52
- class ServiceStatus(BaseModel):
63
+ class ServiceStatus(ApiModel):
53
64
  """Another strata service this app calls, as its health endpoint answered just now."""
54
65
 
55
66
  name: str
@@ -59,7 +70,7 @@ class ServiceStatus(BaseModel):
59
70
  detail: str | None = None # why it is not ok: not reachable, or what it answered
60
71
 
61
72
 
62
- class SystemInfo(BaseModel):
73
+ class SystemInfo(ApiModel):
63
74
  """What `GET /api/system` answers: what is running, where its data is, and whether its services answer."""
64
75
 
65
76
  model_config = ConfigDict(extra="allow")
@@ -72,7 +83,7 @@ class SystemInfo(BaseModel):
72
83
  services: list[ServiceStatus] = Field(default_factory=lambda: [])
73
84
 
74
85
 
75
- class ErrorBody(BaseModel):
86
+ class ErrorBody(ApiModel):
76
87
  """The body of every error the app answers. `detail` is what FastAPI already uses, so clients that read it keep
77
88
  working; `payload` carries what the error wants the client to have (the job row of a refused job)."""
78
89
 
@@ -84,7 +95,7 @@ TaskState = Literal["queued", "running", "done", "failed", "cancelled"]
84
95
  FINISHED: frozenset[str] = frozenset({"done", "failed", "cancelled"})
85
96
 
86
97
 
87
- class Progress(BaseModel):
98
+ class Progress(ApiModel):
88
99
  """How far a task has got. `total` None means not known yet; `text` is the line a person reads ("Page 3 of 40")."""
89
100
 
90
101
  done: float = 0
@@ -98,7 +109,7 @@ class Progress(BaseModel):
98
109
  return None if not self.total else min(max(self.done / self.total, 0.0), 1.0)
99
110
 
100
111
 
101
- class Task(BaseModel):
112
+ class Task(ApiModel):
102
113
  """A job or task row as an API answers it."""
103
114
 
104
115
  id: int | str
@@ -117,7 +128,7 @@ class Task(BaseModel):
117
128
  T = TypeVar("T")
118
129
 
119
130
 
120
- class Page(BaseModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
131
+ class Page(ApiModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
121
132
  """One page of a list. `next` is an opaque cursor (pass it back as `after`), None on the last page; a cursor, not an
122
133
  offset, so rows added while a person pages through do not repeat or vanish."""
123
134
 
@@ -19,7 +19,8 @@ extra: `strata-python[db]`.
19
19
  s.add(Note(text="hi")); s.commit()
20
20
 
21
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`
22
+ `Project.load(__file__).upgrade(engine)` (or `.open()`, connect and migrate) at service start; a FastAPI server
23
+ uses `strata_python.db.web.add_database` and its `DbSession` dependency. Tests: the plugin's `db_session` / `db_engine` / `db_url`
23
24
  / `db_env` fixtures and `strata_python.db.testing`. See the README.
24
25
 
25
26
  The names load on first use: the pytest plugin imports `strata_python.db.guard` in every app with strata-python
@@ -35,6 +36,9 @@ if TYPE_CHECKING:
35
36
  from .config import (
36
37
  DatabaseNotConfigured as DatabaseNotConfigured,
37
38
  )
39
+ from .config import (
40
+ local_url as local_url,
41
+ )
38
42
  from .config import (
39
43
  normalise_url as normalise_url,
40
44
  )
@@ -74,6 +78,7 @@ _WHERE = {
74
78
  "DatabaseNotConfigured": "config",
75
79
  "normalise_url": "config",
76
80
  "resolve_url": "config",
81
+ "local_url": "config",
77
82
  "url_for": "config",
78
83
  "connect": "engine",
79
84
  "session": "engine",
@@ -93,6 +98,7 @@ __all__ = [ # noqa: RUF022 (grouped as _WHERE is)
93
98
  "DatabaseNotConfigured",
94
99
  "normalise_url",
95
100
  "resolve_url",
101
+ "local_url",
96
102
  "url_for",
97
103
  "connect",
98
104
  "session",
strata_python/db/cli.py CHANGED
@@ -1,6 +1,6 @@
1
1
  """strata-db: the app-facing command line (run from anywhere inside the app's repo; also `python -m strata_python.db`).
2
2
 
3
- strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres]
3
+ strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres] [--package src/pkg]
4
4
  add [tool.strata-db] to pyproject.toml and create migrations/
5
5
  strata-db new-app [NAME] on the shared server: owner role NAME (NOLOGIN, you are a member) and schema NAME in
6
6
  the shared database, owned by it, no USAGE for PUBLIC (other app roles cannot see it).
@@ -33,7 +33,7 @@ from . import migrations as m
33
33
  from .config import normalise_url, resolve_url, shared_database
34
34
  from .engine import connect
35
35
  from .guard import LIVE, LiveDatabaseRefused, allow_live
36
- from .project import TABLE, Project
36
+ from .project import FILE, TABLE, Project
37
37
  from .scratch import live_admin_url, pg_available, scratch_database
38
38
  from .testing import scratch_engine
39
39
 
@@ -41,18 +41,29 @@ NAME = re.compile(r"[a-z][a-z0-9_]*") # role and schema names: nothing that nee
41
41
 
42
42
 
43
43
  def cmd_init(a: argparse.Namespace) -> None:
44
+ """Write the declaration: into pyproject.toml, or with --package into the package's strata-db.toml (migrations
45
+ beside it, so an installed wheel carries both) with a pointer to it in pyproject.toml."""
44
46
  pp = Path.cwd() / "pyproject.toml"
45
47
  body = pp.read_text(encoding="utf-8") if pp.exists() else f'[project]\nname = "{a.app}"\nversion = "0.1.0"\n'
46
48
  if f"[tool.{TABLE}]" in body:
47
49
  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
- )
50
+ keys = f'app = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
51
51
  if a.engine != "portable":
52
- body += f'engine = "{a.engine}"\n'
52
+ keys += f'engine = "{a.engine}"\n'
53
+ if a.package:
54
+ pkg = Path(a.package)
55
+ if not (Path.cwd() / pkg / "__init__.py").is_file():
56
+ sys.exit(f"{pkg} is not a package folder (no __init__.py)")
57
+ (Path.cwd() / pkg / FILE).write_text(keys, encoding="utf-8")
58
+ (Path.cwd() / pkg / "migrations").mkdir(exist_ok=True)
59
+ body = body.rstrip("\n") + f'\n\n[tool.{TABLE}]\nfile = "{(pkg / FILE).as_posix()}"\n'
60
+ where = f"{(pkg / FILE).as_posix()} (pointed to from {pp.name}); {(pkg / 'migrations').as_posix()}/ ready"
61
+ else:
62
+ body = body.rstrip("\n") + f"\n\n[tool.{TABLE}]\n{keys}"
63
+ (Path.cwd() / "migrations").mkdir(exist_ok=True)
64
+ where = f"[tool.{TABLE}] to {pp}; migrations/ ready"
53
65
  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'")
66
+ print(f"wrote {where}. Next: strata-db revision -m 'initial'")
56
67
 
57
68
 
58
69
  def cmd_new_app(a: argparse.Namespace) -> None:
@@ -103,7 +114,9 @@ def cmd_revision(a: argparse.Namespace) -> None:
103
114
  path = m.revision(eng, p.migrations_dir, p.metadata, a.message, autogenerate=not a.empty)
104
115
  eng.dispose()
105
116
  if path:
106
- print(f"wrote {Path(path).relative_to(p.root).as_posix()}: review it, then commit it")
117
+ shown = Path(path).resolve()
118
+ shown = shown.relative_to(Path.cwd().resolve()) if shown.is_relative_to(Path.cwd().resolve()) else shown
119
+ print(f"wrote {shown.as_posix()}: review it, then commit it")
107
120
  else:
108
121
  print("no changes: the models match the migrations")
109
122
 
@@ -162,6 +175,7 @@ def main(argv: list[str] | None = None) -> None:
162
175
  s.add_argument("--app", required=True)
163
176
  s.add_argument("--models", required=True)
164
177
  s.add_argument("--engine", choices=["portable", "postgres"], default="portable")
178
+ s.add_argument("--package", metavar="DIR", help="declare in DIR/strata-db.toml, so an installed wheel has it")
165
179
  s.set_defaults(f=cmd_init)
166
180
  s = sub.add_parser("new-app", help="role and schema on the shared server")
167
181
  s.add_argument("name", nargs="?")
@@ -12,6 +12,9 @@ has no schemas.
12
12
 
13
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
14
 
15
+ An app that should still work before it is given a database (a checkout, a new deployment) passes a `default`, usually
16
+ `local_url(SETTINGS)`: a SQLite file in its settings folder. It is used only when nothing above is set.
17
+
15
18
  A real Postgres database is opt-in (see `strata_python.db.guard`): url_for() and connect() refuse one unless the
16
19
  process has `STRATA_DB_LIVE=1`, and refuse it always during tests.
17
20
  """
@@ -20,6 +23,10 @@ from __future__ import annotations
20
23
 
21
24
  import os
22
25
  import re
26
+ from typing import TYPE_CHECKING
27
+
28
+ if TYPE_CHECKING:
29
+ from strata_python.settings import Settings
23
30
 
24
31
  URL = "STRATA_DB_URL"
25
32
  DATABASE = "STRATA_DB_DATABASE"
@@ -67,19 +74,36 @@ def with_search_path(url: str, schema: str) -> str:
67
74
  return url + ("&" if "?" in url else "?") + f"options=-csearch_path%3D{schema}"
68
75
 
69
76
 
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."""
77
+ def local_url(home: Settings | str | os.PathLike[str], name: str | None = None) -> str:
78
+ """A SQLite file for an app with no database configured: `<home>/<name>.db`, where home is a folder or the app's
79
+ `Settings` (its folder, `<APP>_HOME` or `~/.<app>`, and its name). `connect` makes the folder."""
80
+ from strata_python.settings import Settings
81
+
82
+ if isinstance(home, Settings):
83
+ folder, name = home.home(), name or home.app
84
+ else:
85
+ folder = os.fspath(home)
86
+ if not name:
87
+ raise ValueError("local_url(folder) needs the app name")
88
+ return normalise_url(os.path.join(folder, f"{name}.db"))
89
+
90
+
91
+ def resolve_url(app: str, schema: str | None = None, *, default: str | None = None) -> str:
92
+ """Where `app`'s data is (see the module docstring), without the live-database check. `default` (a URL or a
93
+ path) is used when nothing is configured, instead of raising DatabaseNotConfigured."""
72
94
  for var in (URL, env_name(app)):
73
95
  if value := os.environ.get(var):
74
96
  return with_search_path(normalise_url(value), schema or app)
97
+ if default is not None and not shared_database():
98
+ return with_search_path(normalise_url(default), schema or app) # as an environment URL (review finding)
75
99
  return schema_url(schema or app)
76
100
 
77
101
 
78
- def url_for(app: str, schema: str | None = None) -> str:
102
+ def url_for(app: str, schema: str | None = None, *, default: str | None = None) -> str:
79
103
  """resolve_url(), refused (guard.LiveDatabaseRefused) when it is a real Postgres database and the process has
80
104
  not opted in with `STRATA_DB_LIVE=1`, or is running tests."""
81
105
  from .guard import check_url
82
106
 
83
- url = resolve_url(app, schema)
107
+ url = resolve_url(app, schema, default=default)
84
108
  check_url(url, f"url_for({app!r})")
85
109
  return url
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import os
5
6
  import re
6
7
  import sqlite3
7
8
  from collections.abc import Generator
@@ -27,6 +28,9 @@ def connect(app_or_url: str, **kw: Any) -> Engine:
27
28
  engine = create_engine(url, **kw)
28
29
  if engine.dialect.name == "sqlite":
29
30
  sqlite_pragmas(engine)
31
+ file = engine.url.database
32
+ if file and file != ":memory:" and not file.startswith("file:"):
33
+ os.makedirs(os.path.dirname(os.path.abspath(file)), exist_ok=True) # a fallback in a folder not made yet
30
34
  return engine
31
35
 
32
36
 
@@ -7,6 +7,16 @@ models = "notes.models:Base" # module:attribute with .metadata (a Base or
7
7
  migrations = "migrations" # folder of Alembic revisions, relative to pyproject.toml
8
8
  engine = "portable" # or "postgres": uses Postgres-only features; tests and autogenerate then
9
9
  # need Postgres (strata-db and the pytest plugin follow this)
10
+
11
+ An app installed as a wheel (a service run from `uv tool install`) has no pyproject.toml beside its code, so the same
12
+ keys can live in the package instead, in a `strata-db.toml` (top level, no table header) next to the migrations:
13
+
14
+ [tool.strata-db] # pyproject.toml: only where the declaration is
15
+ file = "src/notes/strata-db.toml"
16
+
17
+ `migrations` is then relative to that file, so the folder ships inside the package, and `Project.load(__file__)` at
18
+ service start finds the file by walking up from the module, in a checkout and in site-packages alike. strata-db and
19
+ the pytest plugin follow the pointer, so all three read one declaration.
10
20
  """
11
21
 
12
22
  from __future__ import annotations
@@ -24,22 +34,46 @@ if TYPE_CHECKING:
24
34
  from sqlalchemy.engine import Engine
25
35
 
26
36
  TABLE = "strata-db"
37
+ FILE = "strata-db.toml"
38
+
39
+
40
+ def _read(f: Path) -> dict[str, Any]:
41
+ return tomllib.loads(f.read_text(encoding="utf-8"))
27
42
 
28
43
 
29
44
  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."""
45
+ """The nearest declaration, from start (default: cwd) upwards: a `strata-db.toml`, or a pyproject.toml with
46
+ [tool.strata-db] (followed to the file its `file` key names). Returns the folder paths are relative to and the
47
+ keys. Standard library only, so the pytest plugin can ask without loading SQLAlchemy."""
32
48
  p = Path(start or os.getcwd()).resolve()
33
49
  for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
50
+ if (d / FILE).is_file():
51
+ return d, _read(d / FILE)
34
52
  f = d / "pyproject.toml"
35
53
  if not f.is_file():
36
54
  continue
37
- cfg = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {})).get(TABLE)
55
+ cfg = cast("dict[str, Any] | None", cast("dict[str, Any]", _read(f).get("tool", {})).get(TABLE))
56
+ if cfg and "file" in cfg:
57
+ target = (d / str(cfg["file"])).resolve()
58
+ if not target.is_file():
59
+ raise FileNotFoundError(f"{f}: [tool.{TABLE}] file = {cfg['file']!r} does not exist")
60
+ return target.parent, _read(target)
38
61
  if cfg:
39
- return d, cast("dict[str, Any]", cfg)
62
+ return d, cfg
40
63
  return None
41
64
 
42
65
 
66
+ def _import_roots(root: Path) -> list[Path]:
67
+ """Folders to put on sys.path so the models import when the app is not installed (a test run from its checkout):
68
+ `src` and the project folder, or for a declaration inside a package, the folder above its top package."""
69
+ if (root / "__init__.py").is_file():
70
+ top = root
71
+ while (top.parent / "__init__.py").is_file():
72
+ top = top.parent
73
+ return [top.parent]
74
+ return [root / "src", root]
75
+
76
+
43
77
  @dataclass
44
78
  class Project:
45
79
  root: Path
@@ -54,12 +88,13 @@ class Project:
54
88
 
55
89
  @classmethod
56
90
  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."""
91
+ """The nearest declaration from start (default: cwd) upwards: a `strata-db.toml`, or a pyproject.toml with
92
+ [tool.strata-db] (see the module notes). Pass `__file__` in the service, so an installed wheel finds it too."""
58
93
  found = find_table(start)
59
94
  if found is None:
60
95
  p = Path(start or os.getcwd()).resolve()
61
96
  raise FileNotFoundError(
62
- f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
97
+ f"no {FILE} or pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
63
98
  )
64
99
  d, cfg = found
65
100
  return cls(
@@ -75,7 +110,7 @@ class Project:
75
110
  def metadata(self) -> MetaData:
76
111
  from sqlalchemy import MetaData
77
112
 
78
- for extra in (self.root / "src", self.root): # the app need not be installed (a test run from its checkout)
113
+ for extra in _import_roots(self.root): # the app need not be installed (a test run from its checkout)
79
114
  if extra.is_dir() and str(extra) not in sys.path:
80
115
  sys.path.insert(0, str(extra))
81
116
  mod, _, attr = self.models.partition(":")
@@ -91,6 +126,22 @@ class Project:
91
126
 
92
127
  return url_for(self.app, self.schema)
93
128
 
129
+ def open(self, url: str | None = None, *, default: str | None = None) -> Engine:
130
+ """An engine on the app's database, migrated to head: `url`, else `url()` with `default` (a URL or path,
131
+ such as `config.local_url(SETTINGS)`) when nothing is configured. Call once and keep the engine."""
132
+ from .config import normalise_url, url_for, with_search_path
133
+ from .engine import connect
134
+
135
+ # a Postgres URL without a search_path would query public while upgrade() migrated the app's schema
136
+ given = with_search_path(normalise_url(url), self.schema) if url else None
137
+ engine = connect(given or url_for(self.app, self.schema, default=default))
138
+ try:
139
+ self.upgrade(engine)
140
+ except BaseException:
141
+ engine.dispose()
142
+ raise
143
+ return engine
144
+
94
145
  def upgrade(self, engine: Engine, revision: str = "head") -> None:
95
146
  """Migrate to head (safe at every start). On Postgres: in the app's schema, as the app's role."""
96
147
  from .migrations import upgrade
@@ -0,0 +1,103 @@
1
+ """A FastAPI server's records: one engine per app, opened and migrated on the first request that needs it, a session
2
+ per request, and the engine disposed when the server stops.
3
+
4
+ from strata_python.db.web import DbSession, add_database
5
+
6
+ app = web.base_app("notes", __version__, SETTINGS)
7
+ add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
8
+
9
+ @app.get("/api/notes")
10
+ def notes(db: DbSession) -> list[NoteOut]:
11
+ return [NoteOut.of(n) for n in db.scalars(select(Note))]
12
+
13
+ Every app with records behind its server wrote this glue (flashtap's `learners/db.py` and `_records`, issue #39). The
14
+ engine is lazy so a server nobody records on never creates a database and its other routes never wait for a
15
+ migration; `default` (a URL, a path, or a function giving one, read when the engine opens) keeps a checkout or a
16
+ deployment with no database configured working on a local SQLite file. Needs the `[db]` extra."""
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import threading
22
+ from collections.abc import AsyncGenerator, Callable, Iterator
23
+ from typing import TYPE_CHECKING, Annotated, Any
24
+
25
+ from fastapi import Depends, FastAPI, Request
26
+ from sqlalchemy.orm import Session
27
+
28
+ if TYPE_CHECKING:
29
+ from sqlalchemy.engine import Engine
30
+
31
+ from .project import Project
32
+
33
+ STATE = "strata_db" # the attribute on app.state
34
+
35
+
36
+ class Database:
37
+ """The app's engine, opened once on first use (thread-safe: sync routes run in a pool) and disposed by `close`."""
38
+
39
+ def __init__(self, project: Project, url: str | None = None, default: str | Callable[[], str] | None = None):
40
+ self.project, self.url, self.default = project, url, default
41
+ self._engine: Engine | None = None
42
+ self._lock = threading.Lock()
43
+
44
+ @property
45
+ def opened(self) -> bool:
46
+ return self._engine is not None
47
+
48
+ def engine(self) -> Engine:
49
+ """The migrated engine, opened on the first call. A failure (a bad URL, a migration that fails) is raised to
50
+ that request and tried again on the next one, so a fixed configuration needs no restart."""
51
+ if self._engine is None:
52
+ with self._lock:
53
+ if self._engine is None:
54
+ d = self.default
55
+ default = d if d is None or isinstance(d, str) else d()
56
+ self._engine = self.project.open(self.url, default=default)
57
+ return self._engine
58
+
59
+ def close(self) -> None:
60
+ with self._lock:
61
+ if self._engine is not None:
62
+ self._engine.dispose()
63
+ self._engine = None
64
+
65
+
66
+ def add_database(
67
+ app: FastAPI, project: Project, *, url: str | None = None, default: str | Callable[[], str] | None = None
68
+ ) -> Database:
69
+ """Hold the app's database on `app.state` for `DbSession`, and dispose it when the server stops (wrapping the
70
+ app's own lifespan, which still runs). `url` overrides the configured one (a test); `default` is used when
71
+ nothing is configured (see `config.local_url`). Returns the `Database`, also reachable as `database(app)`."""
72
+ holder = Database(project, url, default)
73
+ setattr(app.state, STATE, holder)
74
+ inner = app.router.lifespan_context
75
+
76
+ @contextlib.asynccontextmanager
77
+ async def lifespan(a: Any) -> AsyncGenerator[Any]:
78
+ try:
79
+ async with inner(a) as state:
80
+ yield state
81
+ finally:
82
+ holder.close()
83
+
84
+ app.router.lifespan_context = lifespan
85
+ return holder
86
+
87
+
88
+ def database(app: FastAPI) -> Database:
89
+ """The `Database` `add_database` put on the app (RuntimeError, naming the call, when there is none)."""
90
+ holder = getattr(app.state, STATE, None)
91
+ if not isinstance(holder, Database):
92
+ raise RuntimeError("no database on this app: call strata_python.db.web.add_database(app, project) first")
93
+ return holder
94
+
95
+
96
+ def db_session(request: Request) -> Iterator[Session]:
97
+ """A Session on the app's database for one request, closed afterwards (commit yourself: `db.commit()`)."""
98
+ with Session(database(request.app).engine()) as s:
99
+ yield s
100
+
101
+
102
+ DbSession = Annotated[Session, Depends(db_session)]
103
+ """A route parameter typed `DbSession` gets a session for that request."""