|
| 1 | +import datetime |
| 2 | + |
| 3 | +from sqlalchemy import create_engine, String, ForeignKey |
| 4 | +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship |
| 5 | +from typing_extensions import Annotated |
| 6 | +from typing import List |
| 7 | + |
| 8 | + |
| 9 | +class Base(DeclarativeBase): |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +class Base2(DeclarativeBase): |
| 14 | + pass |
| 15 | + |
| 16 | + |
| 17 | +engine = create_engine('mysql://root:test@localhost/testdb', echo=True) |
| 18 | +engine2 = create_engine('mysql://root:test@localhost/myblog_db', echo=True) |
| 19 | + |
| 20 | + |
| 21 | +int_pk = Annotated[int, mapped_column(primary_key=True)] |
| 22 | +required_unique_string = Annotated[str, mapped_column(String(128), unique=True, nullable=False)] |
| 23 | +required_string = Annotated[str, mapped_column(String(128), nullable=False)] |
| 24 | +timestamp_not_null = Annotated[datetime.datetime, mapped_column(nullable=False)] |
| 25 | + |
| 26 | + |
| 27 | +class User(Base2): |
| 28 | + __tablename__ = "users" |
| 29 | + |
| 30 | + id: Mapped[int_pk] |
| 31 | + name: Mapped[required_unique_string] |
| 32 | + |
| 33 | + def __repr__(self): |
| 34 | + return f'id: {self.id}, name: {self.name}' |
| 35 | + |
| 36 | + |
| 37 | +class Department(Base): |
| 38 | + __tablename__ = "department" |
| 39 | + |
| 40 | + id: Mapped[int_pk] |
| 41 | + name: Mapped[required_unique_string] |
| 42 | + |
| 43 | + employees: Mapped[List["Employee"]] = relationship(back_populates="department") |
| 44 | + |
| 45 | + def __repr__(self): |
| 46 | + return f'id: {self.id}, name: {self.name}' |
| 47 | + |
| 48 | + |
| 49 | +class Employee(Base): |
| 50 | + __tablename__ = "employee" |
| 51 | + |
| 52 | + id: Mapped[int_pk] |
| 53 | + dep_id: Mapped[int] = mapped_column(ForeignKey("department.id")) |
| 54 | + name: Mapped[required_unique_string] |
| 55 | + birthday: Mapped[timestamp_not_null] |
| 56 | + |
| 57 | + department: Mapped[Department] = relationship(back_populates="employees") |
| 58 | + |
| 59 | + def __repr__(self): |
| 60 | + return f'id: {self.id}, dep_id: {self.dep_id}, name: {self.name}, birthday: {self.birthday}' |
| 61 | + |
| 62 | + |
| 63 | +Base.metadata.create_all(engine) |
| 64 | +Base2.metadata.create_all(engine2) |
0 commit comments