39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
from os import environ
|
|
from typing import Iterator, Optional
|
|
|
|
from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select
|
|
|
|
DB_URL = environ.get("DB_URL", "sqlite:///pilotwings.sqlite")
|
|
engine = create_engine(DB_URL)
|
|
|
|
|
|
class User(SQLModel, table=True):
|
|
id: Optional[int] = Field(default=None, primary_key=True)
|
|
username: str = Field(unique=True)
|
|
password: str
|
|
containers: list["Container"] = Relationship(back_populates="user")
|
|
|
|
|
|
class Container(SQLModel, table=True):
|
|
id: Optional[int] = Field(default=None, primary_key=True)
|
|
name: str = Field(unique=True)
|
|
user_id: int = Field(foreign_key="user.id")
|
|
user: User = Relationship(back_populates="containers")
|
|
envs: str
|
|
|
|
|
|
def get_session() -> Iterator[Session]:
|
|
with Session(engine) as session:
|
|
yield session
|
|
|
|
|
|
def create_db_and_tables() -> None:
|
|
SQLModel.metadata.create_all(engine)
|
|
with Session(engine) as session:
|
|
statement = select(User).where(User.username == "admin")
|
|
user = session.exec(statement).first()
|
|
if not user:
|
|
user = User(username="admin", password="admin")
|
|
session.add(user)
|
|
session.commit()
|