Create the engine and the session on first use
All checks were successful
CI / Checks (Python 3.13) (push) Successful in 2m47s

The global `db.session` is now a `scoped_session`,
like, for example, in Flask-SQLAlchemy.

Importing the package no longer creates an engine;
so, the placeholder for the tests is obsolete.

The `db_session` fixture replaces `db.session` with `monkeypatch`
such that it is reset after each test.

Tests without the fixture get a placeholder that fails loudly
instead of opening a real session,
which would block the `DROP SCHEMA` at the end of the test run.
This commit is contained in:
Alexander Hess 2026-12-02 00:19:19 +01:00
commit fc185fa3c0
Signed by: alexander
GPG key ID: B46EDB4DFC26805D

View file

@ -1,13 +1,12 @@
"""Provide connection utils for the ORM layer.
This module defines a fully configured `session` object
to be used as a global within the `velofy` package.
If a database is not guaranteed to be available, it is set to `None`.
That is the case on the CI server.
The `session` object is used as a global within the `velofy` package,
like `db.session` in Flask-SQLAlchemy: It is a proxy to one session per thread.
The engine and the session are only created on first use;
so, importing the package does not require a database.
"""
import os
import functools
import typing as t
import sqlalchemy as sa
@ -16,10 +15,18 @@ from sqlalchemy import orm
import velofy
if os.getenv("TESTING"):
# Placeholder that the test fixtures replace
session: orm.Session = None # type: ignore[assignment]
@functools.cache
def get_engine() -> sa.Engine:
"""The engine for the configured `DATABASE_URI`, created on first use."""
return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI))
else: # pragma: no cover
engine = sa.create_engine(t.cast(str, velofy.config.DATABASE_URI))
session = orm.Session(bind=engine)
# `scoped_session()` accepts any callable creating sessions
# while its type stubs expect a `sessionmaker`
# => The lambda defers creating the engine to first use.
session: orm.scoped_session[orm.Session] = orm.scoped_session(
t.cast(
"orm.sessionmaker[orm.Session]",
lambda: orm.Session(bind=get_engine()),
),
)