Skip to content

Database Handlers

Database Handlers are Singleton or NamedSingleton classes to handle database connections, engines and sessions using SQLModel.

SingleDatabaseHandler

SingleDatabaseHandler is a singleton to create a db instance. Once you create an instance of the db, it will be the only db that you can create. Even if you call the class again with different arguments - or no arguments, it will return you the first db instance. The parameter echo is the one from SQLModel, and if create_tables is True, all the tables will be created by SQLModel automatically during the initialization of the db instance.

from backend_dev_utils import SingleDatabaseHandler

db = SingleDatabaseHandler(
    database_uri="sqlite:///:memory:", echo=True, create_tables=True
)

session = db.get_session()


db2 = SingleDatabaseHandler()

MultipleDatabaseHandler

MultipleDatabaseHandler is almost the same with SingleDatabaseHandler, but it can handle multiple db instance with different names. It is a NamedSingleton (please see the NamedSingleton in DesignPatterns module).

1
2
3
4
5
6
7
from backend_dev_utils import MultipleDatabaseHandler

first_db = MultipleDatabaseHandler(
    name="first_db", database_uri="sqlite:///:memory:", echo=True, create_tables=True
)

session = first_db.get_session()