Skip to content
Snippets Groups Projects
Engine.py 1.9 KiB
Newer Older
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging, sqlalchemy, sqlalchemy_utils
from common.Settings import get_setting

LOGGER = logging.getLogger(__name__)

APP_NAME = 'tfs'
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
ECHO = False # true: dump SQL commands and transactions executed
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed

class Engine:
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
    @staticmethod
    def get_engine() -> sqlalchemy.engine.Engine:
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        crdb_uri = get_setting('CRDB_URI')
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed

        try:
            engine = sqlalchemy.create_engine(
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
                crdb_uri, connect_args={'application_name': APP_NAME}, echo=ECHO, future=True)
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        except: # pylint: disable=bare-except # pragma: no cover
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            LOGGER.exception('Failed to connect to database: {:s}'.format(crdb_uri))
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            return None

        try:
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            Engine.create_database(engine)
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        except: # pylint: disable=bare-except # pragma: no cover
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            LOGGER.exception('Failed to check/create to database: {:s}'.format(engine.url))
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            return None

        return engine
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed

    @staticmethod
    def create_database(engine : sqlalchemy.engine.Engine) -> None:
        if not sqlalchemy_utils.database_exists(engine.url):
            sqlalchemy_utils.create_database(engine.url)

    @staticmethod
    def drop_database(engine : sqlalchemy.engine.Engine) -> None:
        if sqlalchemy_utils.database_exists(engine.url):
            sqlalchemy_utils.drop_database(engine.url)