Skip to content
This repository has been archived by the owner on Sep 6, 2024. It is now read-only.

Commit

Permalink
Add example orm database classes
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsDrike committed Jul 21, 2024
1 parent 0dec86c commit ddddcb3
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions src/db_tables/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,76 @@ All of these tables must inherit from the `Base` class, that can be imported fro

There is no need to register newly created classes / files anywhere, as all files in this directory (except those
starting with `_`) will be automatically imported and picked up by SQLAlchemy.

## Example database class

Imagine an application that schedules appointmnets for users:

`user.py`:

```python
import enum
from typing import TYPE_CHECKING
from sqlalchemy import Mapped, mapped_column, relationship

from src.utils.database import Base


# Prevent circular imports for relationships
if TYPE_CHECKING:
from src.db_tables.appointment import Appointment


class Role(enum.IntEnum):
"""Enumeration of all possible user roles."""

USER = 0
ADMIN = 1


class User(Base):
"""User database table."""

__tablename__ = "user"

id: Mapped[int] = mapped_column(primary_key=True, index=True, nullable=False)
email: Mapped[str] = mapped_column(unique=True, nullable=False)
name: Mapped[str] = mapped_column(nullable=False)
surname: Mapped[str] = mapped_column(nullable=False)
user_role: Mapped[Role] = mapped_column(nullable=False, default=Role.USER)

appointments: Mapped[list["Appointment"]] = relationship(
lazy="selectin",
back_populates="user",
cascade="all, delete-orphan",
)
```

`appointment.py`:

```python
from datetime import date, time
from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.utils.database import Base

# Prevent circular imports for relationships
if TYPE_CHECKING:
from src.db_tables.user import User


class Appointment(Base):
"""Appointment database table."""

__tablename__ = "appointment"

id: Mapped[int] = mapped_column(primary_key=True, index=True, nullable=False)
booked_date: Mapped[date] = mapped_column(nullable=False)
booked_time: Mapped[time] = mapped_column(nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), nullable=False)

user: Mapped["User"] = relationship(lazy="selectin", back_populates="appointments")
```

0 comments on commit ddddcb3

Please sign in to comment.