diff --git a/app/database.py b/app/database.py index 3bbecde..fe90ba7 100644 --- a/app/database.py +++ b/app/database.py @@ -1,11 +1,78 @@ -from sqlmodel import SQLModel, create_engine +from sqlmodel import SQLModel, create_engine, Session, select +from app.models import example_model, project from app.config import settings engine = create_engine( - settings.database_url, + settings.database_url, echo=True, connect_args={"check_same_thread": False}, ) def create_database(): - SQLModel.metadata.create_all(engine) \ No newline at end of file + SQLModel.metadata.create_all(engine) + +def add_to_database(input: any): + with Session(engine) as session: + session.add(input) + session.commit() + +def get_from_database(query: any) -> list: + with Session(engine) as session: + results = session.exec(select(query)).all() + return results + +def get_from_database_where(query: any, variable: any, value: any, first_only: bool = False, offset: int | None = None, limit: int | None = None) -> list: + with Session(engine) as session: + statement = select(query).where(variable == value) + if offset: + statement = statement.offset(offset) + if limit: + statement = statement.limit(limit) + results = session.exec(statement) + if first_only: + results = results.first() + else: + results = results.all() + return results + +def get_from_database_where_id(query: any, value: int): + with Session(engine) as session: + result = session.get(query, value) + return result + +def get_from_database_where_join_filter(query: any, joined: any, variable: any, value: any): + with Session(engine) as session: + results = session.exec(select(query).join(joined).where(variable == value)) + return results + +def get_and_join_from_database(query: any, joined: any, isouter: bool = False): + with Session(engine) as session: + results = session.exec(select(query, joined).join(joined, isouter)).all() + return results + +def update_database_where(query: any, variable: any, value: any, attribute: any, new_value: any): + with Session(engine) as session: + results = session.exec(select(query).where(variable == value)) + + for instance in results: + instance.setAttribute(attribute, new_value) + session.add(instance) + session.commit() + session.refresh(instance) + return results + +def delete_from_database_where(query: any, variable: any, value: any): + with Session(engine) as session: + results = session.exec(select(query).where(variable == value)) + + for instance in results: + session.delete(instance) + session.commit() + + remainder = session.exec(select(query).where(variable == value)) + if remainder is None: + return {"message": "Successfully deleted matching query(ies)", "deleted": results.all()} + else: + return {"message": "Failed to delete all matching queries", "remaining": remainder.all()} + + \ No newline at end of file