Exemplo n.º 1
0
    def create_session_factory(self, **kwargs) -> "DBManager":
        """
        Args:
            kwargs  => passed to SQLAlchemy sessionmaker constructor
        Description:
            Create SQLAlchemy scoped_session if self._scoped_sessions is True,
            otherwise sessionmaker. All kwargs are passed to sessionmaker constructor.
            This method should only be called _once_ by the DBManager. SQLAlchemy doesn't
            recommend manually closing all sessions, and the mechanics for doing so have changed
            across versions.
            See: https://docs.sqlalchemy.org/en/13/orm/session_api.html#session-and-sessionmaker
            and  https://docs.sqlalchemy.org/en/13/orm/contextual.html#sqlalchemy.orm.scoping.scoped_session
            and  https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.sessionmaker.close_all
        Preconditions:
            N/A
        Raises:
            RuntimeError: if self._session_factory is already defined, or
                          if self._engine isn't defined
        """
        # Ensure self._session_factory isn't already defined
        if self._session_factory:
            raise RuntimeError("Session factory already created")
        # Ensure self._engine is defined
        if not self._engine:
            raise RuntimeError("Cannot create session factory without an Engine")

        # Generate sessionmaker session factory
        self._session_factory = SessionMaker(bind=self._engine, **kwargs)
        # If scoped sessions, wrap in scoped_sessions factory
        if self._scoped_sessions:
            self._session_factory = ScopedSession(self._session_factory)
        return self
Exemplo n.º 2
0
def _init_session_maker():
    global _session_maker
    _session_maker = SessionMaker(bind=get_engine())
Exemplo n.º 3
0
import os

import psycopg2
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker as SessionMaker

#from config import DatabaseConfig

engine = create_engine(os.environ['DATABASE_URL'], echo=True)
session_maker = SessionMaker(bind=engine)

def connect_db():
    db_conf = DatabaseConfig()
    return psycopg2.connect(host=db_conf.db_host,
                            database=db_conf.db_name,
                            user=db_conf.db_user,
                            password=db_conf.db_password)


def made_sql(db_con, sql) -> bool:
    try:
        with db_con:
            with db_con.cursor() as curs:
                curs.execute(sql)
                return True
    except psycopg2.Error:
        return False


def create_schema(db_con, sch_name):
    return made_sql(db_con, 'CREATE SCHEMA {};'.format(sch_name))
Exemplo n.º 4
0
def setup_sessionmaker() -> SessionMaker:
    engine = create_engine(MYSQL_URL, pool_recycle=300, pool_size=10)
    sessionmaker = SessionMaker(bind=engine)
    return sessionmaker