"""Utils related to databases.""" import sqlite3 import sys from sqlalchemy import event from masters_registry import config from masters_registry.connectors import mysql from masters_registry.models import bulk_tasks @event.listens_for(mysql._bulk_statuses_engine, 'connect') def sqlite_engine_connect(dbapi_connection, connection_record): """Listener for the event of establishing connection to a SQLite database. Creates `isnull` function within SQLite engine. """ if not isinstance(dbapi_connection, sqlite3.Connection): return dbapi_connection.create_function(config.ISNULL_FUNC, 1, _is_null) def _is_null(val): """A substitute for missing Sqlite isnull function.""" return 0 if val is None else 1 def create_tables(): """Create tables for testing purposes.""" with mysql.bulk_statuses_session_scope() as session: exit_if_not_test_environment(session) bulk_tasks.BaseModel.metadata.create_all(mysql._bulk_statuses_engine) def drop_tables(): """Drop track and related tables.""" with mysql.bulk_statuses_session_scope() as session: exit_if_not_test_environment(session) bulk_tasks.BaseModel.metadata.drop_all(mysql._bulk_statuses_engine) def exit_if_not_test_environment(session): """For safety, only run tests in test environment pointed to sqlite. Exit if not in test environment or not pointed to sqlite. """ if config.ENVIRONMENT != config.TEST_ENVIRONMENT: sys.exit('Environment must be set to {}.'.format( config.TEST_ENVIRONMENT)) if 'sqlite' not in session.bind.url.drivername: sys.exit('Tests must point to sqlite database.')