Skip to content

Commit

Permalink
misc: Use single SQLAlchemy engine and session maker
Browse files Browse the repository at this point in the history
As recommended by SQLAlchemy [1], this change makes a single
instantiation of the database engine and session maker, instead of one
entity per handler.

It also uses the provided `URL` constructor to better define the
database URL structure.

[1] https://docs.sqlalchemy.org/en/20/core/connections.html#basic-usage
  • Loading branch information
adamantike committed Aug 21, 2024
1 parent 419f3ba commit a85c84a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
14 changes: 9 additions & 5 deletions backend/config/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import sys
from pathlib import Path
from typing import Final
from urllib.parse import quote_plus

import pydash
import yaml
Expand All @@ -21,6 +20,7 @@
ConfigNotWritableException,
)
from logger.logger import log
from sqlalchemy import URL
from yaml.loader import SafeLoader

ROMM_USER_CONFIG_PATH: Final = f"{ROMM_BASE_PATH}/config"
Expand Down Expand Up @@ -76,7 +76,7 @@ def __init__(self, config_file: str = ROMM_USER_CONFIG_FILE):
sys.exit(5)

@staticmethod
def get_db_engine() -> str:
def get_db_engine() -> URL:
"""Builds the database connection string depending on the defined database in the config.yml file
Returns:
Expand All @@ -90,9 +90,13 @@ def get_db_engine() -> str:
)
sys.exit(3)

return (
f"mariadb+mariadbconnector://{DB_USER}:%s@{DB_HOST}:{DB_PORT}/{DB_NAME}"
% quote_plus(DB_PASSWD)
return URL.create(
drivername="mariadb+mariadbconnector",
username=DB_USER,
password=DB_PASSWD,
host=DB_HOST,
port=DB_PORT,
database=DB_NAME,
)

# DEPRECATED
Expand Down
3 changes: 2 additions & 1 deletion backend/decorators/database.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import functools

from fastapi import HTTPException, status
from handler.database.base_handler import sync_session
from logger.logger import log
from sqlalchemy.exc import ProgrammingError

Expand All @@ -12,7 +13,7 @@ def wrapper(*args, **kwargs):
return func(*args, **kwargs)

try:
with args[0].session.begin() as s:
with sync_session.begin() as s:
kwargs["session"] = s
return func(*args, **kwargs)
except ProgrammingError as exc:
Expand Down
8 changes: 4 additions & 4 deletions backend/handler/database/base_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

sync_engine = create_engine(ConfigManager.get_db_engine(), pool_pre_ping=True)
sync_session = sessionmaker(bind=sync_engine, expire_on_commit=False)

class DBBaseHandler:
def __init__(self) -> None:
self.engine = create_engine(ConfigManager.get_db_engine(), pool_pre_ping=True)
self.session = sessionmaker(bind=self.engine, expire_on_commit=False)

class DBBaseHandler: ...

0 comments on commit a85c84a

Please sign in to comment.