You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.3 KiB

6 years ago
# coding: utf-8
This module contains functions related to the database.
from __future__ import absolute_import, print_function, unicode_literals
import sqlite3
from contextlib import contextmanager
from sqlalchemy import event, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
6 years ago
import flatisfy.models.flat # noqa: F401
from flatisfy.database.base import BASE
from flatisfy.database.whooshalchemy import IndexService
6 years ago
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, _):
Auto enable foreign keys for SQLite.
# Play well with other DB backends
if isinstance(dbapi_connection, sqlite3.Connection):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
def init_db(database_uri=None, search_db_uri=None):
6 years ago
Initialize the database, ensuring tables exist etc.
:param database_uri: An URI describing an engine to use. Defaults to
in-memory SQLite database.
:param search_db_uri: Path to the Whoosh index file to use.
6 years ago
:return: A tuple of an SQLAlchemy session maker and the created engine.
if database_uri is None:
database_uri = "sqlite:///:memory:"
engine = create_engine(database_uri)
BASE.metadata.create_all(engine, checkfirst=True)
Session = sessionmaker(bind=engine) # pylint: disable=locally-disabled,invalid-name
6 years ago
if search_db_uri:
index_service = IndexService(
6 years ago
def get_session():
# pylint: disable=locally-disabled,line-too-long
6 years ago
Provide a transactional scope around a series of operations.
From [1].
# pylint: enable=line-too-long,locally-disabled
6 years ago
session = Session()
yield session
except SQLAlchemyError:
6 years ago
return get_session