1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-08-02 12:05:21 +02:00
mealie/mealie/db/db_setup.py
Hayden 9e77a9f367
prs-fleshgolem-2070: feat: sqlalchemy 2.0 (#2096)
* upgrade sqlalchemy to 2.0

* rewrite all db models to sqla 2.0 mapping api

* fix some importing and typing weirdness

* fix types of a lot of nullable columns

* remove get_ref methods

* fix issues found by tests

* rewrite all queries in repository_recipe to 2.0 style

* rewrite all repository queries to 2.0 api

* rewrite all remaining queries to 2.0 api

* remove now-unneeded __allow_unmapped__ flag

* remove and fix some unneeded cases of "# type: ignore"

* fix formatting

* bump black version

* run black

* can this please be the last one. okay. just. okay.

* fix repository errors

* remove return

* drop open API validator

---------

Co-authored-by: Sören Busch <fleshgolem@gmx.net>
2023-02-06 18:43:12 -09:00

59 lines
1.6 KiB
Python

from collections.abc import Generator
from contextlib import contextmanager
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session
from mealie.core.config import get_app_settings
settings = get_app_settings()
def sql_global_init(db_url: str):
connect_args = {}
if "sqlite" in db_url:
connect_args["check_same_thread"] = False
engine = sa.create_engine(db_url, echo=False, connect_args=connect_args, pool_pre_ping=True, future=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, future=True)
return SessionLocal, engine
SessionLocal, engine = sql_global_init(settings.DB_URL) # type: ignore
@contextmanager
def session_context() -> Session:
"""
session_context() provides a managed session to the database that is automatically
closed when the context is exited. This is the preferred method of accessing the
database.
Note: use `generate_session` when using the `Depends` function from FastAPI
"""
global SessionLocal
sess = SessionLocal()
try:
yield sess
finally:
sess.close()
def generate_session() -> Generator[Session, None, None]:
"""
WARNING: This function should _only_ be called when used with
using the `Depends` function from FastAPI. This function will leak
sessions if used outside of the context of a request.
Use `with_session` instead. That function will allow you to use the
session within a context manager
"""
global SessionLocal
db = SessionLocal()
try:
yield db
finally:
db.close()