This commit is contained in:
Waylon Walker 2023-05-19 20:37:42 -05:00
parent c238b9d757
commit fcc0698aeb
No known key found for this signature in database
GPG key ID: 66E2BF2B4190EFE4
12 changed files with 95 additions and 97 deletions

View file

@ -1,18 +1,40 @@
from typing import TYPE_CHECKING
from pydantic import BaseSettings
from sqlmodel import SQLModel, Session, create_engine
from sqlalchemy import create_engine
from sqlmodel import SQLModel, Session
from learn_sql_model.models.hero import Hero
from learn_sql_model.models.pet import Pet
from learn_sql_model.standard_config import load
models = [Hero, Pet]
if TYPE_CHECKING:
from sqlalchemy import Engine
class Database:
def __init__(self, config: "Config" = None) -> None:
if config is None:
self.config = get_config()
else:
self.config = config
self.create_db_and_tables()
@property
def engine(self) -> "Engine":
return create_engine(self.config.database_url)
def session(self) -> "Session":
return Session(self.engine)
def create_db_and_tables(self) -> None:
from learn_sql_model.models.hero import Hero
from learn_sql_model.models.pet import Pet
__all__ = [Hero, Pet]
SQLModel.metadata.create_all(self.engine)
class Config(BaseSettings):
database_url: str = "sqlite:///database.db"
port: int = 5000
@ -21,27 +43,19 @@ class Config(BaseSettings):
env_prefix = "LEARN_SQL_MODEL_"
@property
def engine(self) -> "Engine":
return create_engine(self.database_url)
def database(self) -> Database:
return get_database(config=self)
@property
def session(self) -> "Session":
return Session(self.engine)
def create_db_and_tables(self) -> None:
SQLModel.metadata.create_all(self.engine)
def get_database(config: Config = None) -> Database:
# def create_endpoints(self) -> None:
# for model in models:
# app.post("/heroes/")(Hero.post_local)
# app.get("/heroes/")(Hero.read_heroes)
if config is None:
config = get_config()
return Database(config)
def get_config(overrides: dict = {}) -> Config:
raw_config = load("learn_sql_model")
config = Config(**raw_config, **overrides)
config.create_db_and_tables()
return config
config = get_config()