Debian Codegraph @

docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py

raw
1 from __future__ import annotations
2
3 import uuid
4 from datetime import date
5 from typing import List
6 from uuid import UUID
7
8 from sqlalchemy import ForeignKey, func, select
9 from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
10 from sqlalchemy.orm import Mapped, mapped_column, relationship
11
12 from litestar import Litestar, get
13 from litestar.di import NamedDependency
14 from litestar.plugins.sqlalchemy import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyPlugin, base
15
16
17 # The SQLAlchemy base includes a declarative model for you to use in your models.
18 # The `UUIDBase` class includes a `UUID` based primary key (`id`)
19 class Author(base.UUIDBase):
20 __tablename__ = "author"
21 name: Mapped[str]
22 dob: Mapped[date]
23 books: Mapped[List[Book]] = relationship(back_populates="author", lazy="selectin")
24
25
26 # The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
27 # additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
28 # record created, and `updated_at` is the last time the record was modified.
29 class Book(base.UUIDAuditBase):
30 __tablename__ = "book"
31 title: Mapped[str]
32 author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
33 author: Mapped[Author] = relationship(lazy="joined", innerjoin=True, viewonly=True)
34
35
36 session_config = AsyncSessionConfig(expire_on_commit=False)
37 sqlalchemy_config = SQLAlchemyAsyncConfig(
38 connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config, create_all=True
39 ) # Create 'async_session' dependency.
40
41
42 async def on_startup(app: Litestar) -> None:
43 """Adds some dummy data if no data is present."""
44 async with sqlalchemy_config.get_session() as session:
45 statement = select(func.count()).select_from(Author)
46 count = await session.execute(statement)
47 if not count.scalar():
48 author_id = uuid.uuid4()
49 session.add(Author(name="Stephen King", dob=date(1954, 9, 21), id=author_id))
50 session.add(Book(title="It", author_id=author_id))
51 await session.commit()
52
53
54 @get(path="/authors")
55 async def get_authors(
56 db_session: NamedDependency[AsyncSession], db_engine: NamedDependency[AsyncEngine]
57 ) -> List[Author]:
58 """Interact with SQLAlchemy engine and session."""
59 return list(await db_session.scalars(select(Author)))
60
61
62 app = Litestar(
63 route_handlers=[get_authors],
64 on_startup=[on_startup],
65 debug=True,
66 plugins=[SQLAlchemyPlugin(config=sqlalchemy_config)],
67 )