Venture_Of_Heros/sql.py
2025-02-24 13:35:58 -05:00

50 lines
1.2 KiB
Python

# Imports
from typing import Annotated
from fastapi import Depends
from sqlmodel import Field, Session, SQLModel, create_engine
# The base hero class
class HeroBase(SQLModel):
name: str = Field(index=True)
gold: int | None = 0
health: int | None = 100
email: str = Field(index=True)
# The player
class Hero(HeroBase, table=True):
id: int = Field(default=None, primary_key=True, index=True)
# This class will be returned to the public
class HeroPublic(HeroBase):
id: int
# The class used to create a hero
class HeroCreate(HeroBase):
secret_name: str
# The class used to update a hero
class HeroUpdate(Hero):
name: str | None = None
gold: int | None = 0
health: int | None = 0
email: str | None = None
# SQLModel initialization
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, connect_args=connect_args)
# Create DB
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
# Get the session
def get_session():
with Session(engine) as session:
yield session
# Return the sessiondep
SessionDep = Annotated[Session, Depends(get_session)]