Use globals for the database connection

- remove the factory functions for creating engines and sessions
- define global engine, connection, and session objects to be used
  everywhere in the urban_meal_delivery package
This commit is contained in:
Alexander Hess 2021-01-04 18:50:26 +01:00
commit 2e3ccd14d5
Signed by: alexander
GPG key ID: 344EA5AB10D868E0
8 changed files with 74 additions and 24 deletions

View file

@ -85,7 +85,10 @@ def make_config(env: str = 'production') -> Config:
raise ValueError("Must be either 'production' or 'testing'")
# Without a PostgreSQL database the package cannot work.
if config.DATABASE_URI is None:
# As pytest sets the "TESTING" environment variable explicitly,
# the warning is only emitted if the code is not run by pytest.
# We see the bad configuration immediately as all "db" tests fail.
if config.DATABASE_URI is None and not os.getenv('TESTING'):
warnings.warn('Bad configurartion: no DATABASE_URI set in the environment')
return config

View file

@ -3,8 +3,9 @@
from urban_meal_delivery.db.addresses import Address
from urban_meal_delivery.db.addresses_pixels import AddressPixelAssociation
from urban_meal_delivery.db.cities import City
from urban_meal_delivery.db.connection import make_engine
from urban_meal_delivery.db.connection import make_session_factory
from urban_meal_delivery.db.connection import connection
from urban_meal_delivery.db.connection import engine
from urban_meal_delivery.db.connection import session
from urban_meal_delivery.db.couriers import Courier
from urban_meal_delivery.db.customers import Customer
from urban_meal_delivery.db.grids import Grid

View file

@ -1,17 +1,26 @@
"""Provide connection utils for the ORM layer."""
"""Provide connection utils for the ORM layer.
This module defines fully configured `engine`, `connection`, and `session`
objects to be used as globals within the `urban_meal_delivery` package.
If a database is not guaranteed to be available, they are set to `None`.
That is the case on the CI server.
"""
import os
import sqlalchemy as sa
from sqlalchemy import engine
from sqlalchemy import orm
import urban_meal_delivery
def make_engine() -> engine.Engine: # pragma: no cover
"""Provide a configured Engine object."""
return sa.create_engine(urban_meal_delivery.config.DATABASE_URI)
if os.getenv('TESTING'):
engine = None
connection = None
session = None
def make_session_factory() -> orm.Session: # pragma: no cover
"""Provide a configured Session factory."""
return orm.sessionmaker(bind=make_engine())
else: # pragma: no cover
engine = sa.create_engine(urban_meal_delivery.config.DATABASE_URI)
connection = engine.connect()
session = orm.sessionmaker(bind=connection)()