From 7301ced7162ffcd47c7a61bf70b62ca9fd66d2d6 Mon Sep 17 00:00:00 2001 From: Russ Allbery Date: Thu, 12 Sep 2024 10:21:36 -0700 Subject: [PATCH] Remove remaining declarative_base references Update the documentation for defining a database schema and one test case to use the new `DeclarativeBase` inheritance syntax. Add a documentation link to the current way of defining ORM models with SQLAlchemy. --- docs/user-guide/database/initialize.rst | 10 ++++++---- safir/tests/dependencies/db_session_test.py | 10 ++++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/user-guide/database/initialize.rst b/docs/user-guide/database/initialize.rst index 70d6ae5..4d7fa18 100644 --- a/docs/user-guide/database/initialize.rst +++ b/docs/user-guide/database/initialize.rst @@ -19,14 +19,16 @@ In the file :file:`schema/base.py`, define the SQLAlchemy declarative base: .. code-block:: python - from sqlalchemy.orm import declarative_base + from sqlalchemy.orm import DeclarativeBase + - Base = declarative_base() + class Base(DeclarativeBase): + """Declarative base for SQLAlchemy ORM model of database schema.""" -In other files in that directory, define the database tables using the normal SQLAlchemy ORM syntax, one table per file. +In other files in that directory, define the database tables using the `normal SQLAlchemy ORM syntax `__, one table per file. Each database table definition must inherit from ``Base``, imported from ``.base``. -In :file:`schema/__init__.py`, import the table definitions from all of the files in the directory, as well as the ``Base`` variable, and export them using ``__all__``. +In :file:`schema/__init__.py`, import the table definitions from all of the files in the directory, as well as the ``Base`` class, and export them using ``__all__``. Using non-default PostgreSQL schemas ------------------------------------ diff --git a/safir/tests/dependencies/db_session_test.py b/safir/tests/dependencies/db_session_test.py index d824ed7..a3aee3e 100644 --- a/safir/tests/dependencies/db_session_test.py +++ b/safir/tests/dependencies/db_session_test.py @@ -8,10 +8,10 @@ import structlog from fastapi import Depends, FastAPI from httpx import ASGITransport, AsyncClient -from sqlalchemy import Column, String +from sqlalchemy import String from sqlalchemy.ext.asyncio import async_scoped_session from sqlalchemy.future import select -from sqlalchemy.orm import declarative_base +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from safir.database import ( create_async_session, @@ -20,7 +20,9 @@ ) from safir.dependencies.db_session import db_session_dependency -Base = declarative_base() + +class Base(DeclarativeBase): + """Declarative base for testing.""" class User(Base): @@ -28,7 +30,7 @@ class User(Base): __tablename__ = "user" - username: str = Column(String(64), primary_key=True) + username: Mapped[str] = mapped_column(String(64), primary_key=True) @pytest.mark.asyncio