Reworked SQLAlchemy code