|
| 1 | +import datetime |
| 2 | + |
| 3 | +from sqlalchemy import create_engine, String, ForeignKey |
| 4 | +from sqlalchemy.ext.declarative import declarative_base |
| 5 | +from sqlalchemy.orm import sessionmaker, Mapped, mapped_column, relationship |
| 6 | +from typing_extensions import Annotated |
| 7 | +from typing import List |
| 8 | + |
| 9 | + |
| 10 | +engine = create_engine('mysql://root:test@localhost/testdb', echo=True) |
| 11 | +Base = declarative_base() |
| 12 | + |
| 13 | + |
| 14 | +int_pk = Annotated[int, mapped_column(primary_key=True)] |
| 15 | +required_unique_name = Annotated[str, mapped_column(String(128), unique=True, nullable=False)] |
| 16 | +timestamp_not_null = Annotated[datetime.datetime, mapped_column(nullable=False)] |
| 17 | + |
| 18 | + |
| 19 | +class Department(Base): |
| 20 | + __tablename__ = "department" |
| 21 | + |
| 22 | + id: Mapped[int_pk] |
| 23 | + name: Mapped[required_unique_name] |
| 24 | + |
| 25 | + employees: Mapped[List["Employee"]] = relationship(back_populates="department") |
| 26 | + |
| 27 | + def __repr__(self): |
| 28 | + return f'id: {self.id}, name: {self.name}' |
| 29 | + |
| 30 | + |
| 31 | +class Employee(Base): |
| 32 | + __tablename__ = "employee" |
| 33 | + |
| 34 | + id: Mapped[int_pk] |
| 35 | + dep_id: Mapped[int] = mapped_column(ForeignKey("department.id")) |
| 36 | + name: Mapped[required_unique_name] |
| 37 | + birthday: Mapped[timestamp_not_null] |
| 38 | + |
| 39 | + department: Mapped[Department] = relationship(lazy=False, back_populates="employees") |
| 40 | + |
| 41 | + def __repr__(self): |
| 42 | + return f'id: {self.id}, dep_id: {self.dep_id}, name: {self.name}, birthday: {self.birthday}' |
| 43 | + |
| 44 | + |
| 45 | +Base.metadata.create_all(engine) |
| 46 | +Session = sessionmaker(bind=engine) |
0 commit comments