|
| 1 | +import datetime |
| 2 | + |
| 3 | +from sqlalchemy import create_engine, String, ForeignKey, Table, Column |
| 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, Set |
| 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 | +required_string = Annotated[str, mapped_column(String(128), nullable=False)] |
| 17 | + |
| 18 | + |
| 19 | +association_table = Table( |
| 20 | + "user_role", |
| 21 | + Base.metadata, |
| 22 | + Column("user_id", ForeignKey("users.id"), primary_key=True), |
| 23 | + Column("role_id", ForeignKey("roles.id"), primary_key=True) |
| 24 | +) |
| 25 | + |
| 26 | + |
| 27 | +class User(Base): |
| 28 | + __tablename__ = "users" |
| 29 | + |
| 30 | + id: Mapped[int_pk] |
| 31 | + name: Mapped[required_unique_name] |
| 32 | + password: Mapped[required_string] |
| 33 | + |
| 34 | + roles: Mapped[List["Role"]] = relationship(secondary=association_table, lazy=False, back_populates="users") |
| 35 | + |
| 36 | + def __repr__(self): |
| 37 | + return f'id: {self.id}, name: {self.name}' |
| 38 | + |
| 39 | + |
| 40 | +class Role(Base): |
| 41 | + __tablename__ = "roles" |
| 42 | + |
| 43 | + id: Mapped[int_pk] |
| 44 | + name: Mapped[required_unique_name] |
| 45 | + |
| 46 | + users: Mapped[List["User"]] = relationship(secondary=association_table, lazy=True, back_populates="roles") |
| 47 | + |
| 48 | + def __repr__(self): |
| 49 | + return f'id: {self.id}, name: {self.name}' |
| 50 | + |
| 51 | + |
| 52 | +Base.metadata.create_all(engine) |
| 53 | +Session = sessionmaker(bind=engine) |
0 commit comments