db.Session: Add

Add database session API to db. This is a breaking change, because
from this commit on, a session object has to be passed to every
query.

This commit also removes any reference to Cmds / App objects. An
instantiated database object can be worked with outside of an App.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2025-03-10 18:44:39 +01:00
commit 495cebd769
5 changed files with 56 additions and 31 deletions

View file

@ -3,21 +3,27 @@
from typing import Any
import abc
from contextlib import contextmanager
from jwutils.Config import Config
from jwutils.db.schema.Schema import Schema
from jwutils import Cmds
from .Session import Session
from ..log import *
class DataBase(abc.ABC):
def __init__(self, schema: Schema, conf: Config, app: Any) -> None:
def __init__(self, schema: Schema, conf: Config) -> None:
self.__conf = conf
self.__app = app
self.__schema = schema
conf.dump(NOTICE, "Initializing database with configuration")
@property
def app(self) -> Cmds:
return self.__app
@abc.abstractmethod
def _create_session(self):
pass
def _delete_session(self, session: Session):
del session
@property
def schema(self):
@ -26,3 +32,11 @@ class DataBase(abc.ABC):
@property
def conf(self):
return self.__conf
@contextmanager
def session(self):
ret = self._create_session()
try:
yield ret
finally:
self._delete_session(ret)