예제 #1
0
def tmpdb():
    """Get a handle to an empty temporary database that is wiped on
    teardown."""

    from brainscopypaste.conf import settings
    engine = create_engine(
        'postgresql+psycopg2://{user}:{pw}@localhost:5432/{db}'
        .format(user=settings.DB_USER, pw=settings.DB_PASSWORD,
                db=settings.DB_NAME_TEST),
        client_encoding='utf8')
    Session.configure(bind=engine)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    yield
    Base.metadata.drop_all(engine)
예제 #2
0
def session_scope():
    """Provide an SQLAlchemy transactional scope around a series of
    operations.

    Wrap your SQLAlchemy operations (queries, insertions, modifications, etc.)
    in a ``with session_scope() as session`` block to deal with sessions
    easily.  Changes are committed when the block finishes. If an exception
    occurrs in the block, the session is rolled back and the exception
    propagated.

    """

    from brainscopypaste.db import Session
    session = Session()
    logger.debug('Opened session %s', session)
    try:
        yield session
        logger.debug('Committing session %s', session)
        session.commit()
    except:
        logger.debug('Rolling back session %s', session)
        session.rollback()
        raise
    finally:
        logger.debug('Closing session %s', session)
        session.close()
예제 #3
0
def init_db(echo_sql=False):
    """Connect to the database and bind :mod:`.db`'s `Session` object to it.

    Uses the :data:`~.settings.DB_USER` and :data:`~.settings.DB_PASSWORD`
    credentials to connect to PostgreSQL database :data:`~.settings.DB_NAME`.
    It binds the `Session` object in :mod:`.db` to this engine, and returns the
    engine object. Note that once this is done, you can directly use
    :func:`session_scope` since it uses the right `Session` object.

    Parameters
    ----------
    echo_sql : bool, optional
        If `True`, print to stdout all SQL commands sent to the engine;
        defaults to `False`.

    Returns
    -------
    :class:`sqlalchemy.engine.Engine`
        The engine connected to the database.

    """

    from brainscopypaste.db import Base, Session
    from brainscopypaste.conf import settings
    logger.info('Initializing database connection')

    engine = create_engine(
        'postgresql+psycopg2://{user}:{pw}@localhost:5432/{db}'
        .format(user=settings.DB_USER, pw=settings.DB_PASSWORD,
                db=settings.DB_NAME),
        client_encoding='utf8', echo=echo_sql)
    Session.configure(bind=engine)

    logger.info('Database connected')
    logger.debug('Checking tables to create')

    Base.metadata.create_all(engine)
    return engine