TheShooter89/tgc-data-inspector

application datalayer

Opened this issue · 0 comments

Short Summary

add application datalayer

Impact/Urgency

medium/high urgency

Full Description & Acceptance Criteria

add datalayer package for database interaction leveraging sqlalchemy library
core functionality is provided by ConnectionManager class that init and handles app Sessions and provides useful decorators and functions to use it

Related Items & Feedback

📣 ConnectionManager instance holds current Session for shared use among different parts of the application and provides scoped_session factory method along with useSession decorator to easily use the session for query functions

📣 Model interaction is organized followig a "repo" pattern, where modelRepo module holds model metadata class and query functions, along with utility functions
es: from datalayer.userRepo import User

  • #4
  • datalayer.init() initialization method
  • useSession decorator injecting session object and properly closing session
  • #5
  • #6
  • #7
  • #8

Follow-up & Follows-from

ConncectionManager class pattern took inspiration from this StackOverflow question

class ConnectionManager:
    def __init__(self):
        self.base = declarative_base()

    def get_db_session(self):
        self.engine = create_engine(get_db_path())
        self.base.metadata.bind = self.engine
        self.session_maker = sessionmaker(bind = self.engine)
        self.session = self.session_maker()
        return self.session

    def persist_in_db(self,record):
        session = self.get_db_session()
        session.add(record)
        session.commit()
        session.close()

    def close_session(self):
        self.session.close()
        self.session_maker.close_all()
        del self.session
        del self.session_maker
        del self.engine
       #self.engine.dispose()

scoped_session factory

from my_web_framework import get_current_request, on_request_end
from sqlalchemy.orm import scoped_session, sessionmaker

Session = scoped_session(sessionmaker(bind=some_engine), scopefunc=get_current_request)

ConnectionManager class should be future-proofed for refactoring toward multiple engine use, some inspirations:
multiple engines and multiple Bases
sqlalchemy Uniefied Tutorial - multiple backends

Session API official docs

Session = sessionmaker(engine)

with Session.begin() as session:
    session.add(some_object)
    session.add(some_other_object)
# commits transaction, closes session

Session and sessionmaker usage

Test Cases

none

Technical Notes

none


Guidelines Reference

use emoji-labeled quote blocks for important sections

⚠️ use this for dangerous/critical info sections

use this for sections about critical errors to avoid

📣 use this to mark important (but not dangerous/critical) points or reminders

spec status emoji

✔️ this is a completed/accepted spec
🔲 this is a under-develop spec