2022-11-03 12:49:39 -04:00
|
|
|
"""
|
|
|
|
Persistence (Postgresql) configuration
|
|
|
|
SPDX - License - Identifier: LGPL - 3.0 - or -later
|
|
|
|
Copyright © 2022 Concordia CERC group
|
|
|
|
Project Coder Peter Yefi peteryefi@gmail.com
|
|
|
|
"""
|
|
|
|
|
|
|
|
import os
|
2023-05-10 17:06:51 -04:00
|
|
|
from pathlib import Path
|
2022-11-03 12:49:39 -04:00
|
|
|
from dotenv import load_dotenv
|
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
2023-01-24 10:51:50 -05:00
|
|
|
from hub.hub_logger import logger
|
2022-11-03 12:49:39 -04:00
|
|
|
|
2023-02-02 06:12:24 -05:00
|
|
|
Models = declarative_base()
|
2022-11-03 12:49:39 -04:00
|
|
|
|
2023-02-01 06:05:12 -05:00
|
|
|
class Configuration:
|
|
|
|
"""
|
|
|
|
Configuration class to hold common persistence configuration
|
2022-12-07 19:06:17 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, db_name: str, dotenv_path: str, app_env='TEST'):
|
|
|
|
"""
|
2023-02-20 07:24:27 -05:00
|
|
|
:param db_name: database name
|
|
|
|
:param app_env: application environment, test or production
|
|
|
|
:param dotenv_path: the absolute path to dotenv file
|
|
|
|
"""
|
2022-12-07 19:06:17 -05:00
|
|
|
try:
|
|
|
|
# load environmental variables
|
2023-05-10 17:06:51 -04:00
|
|
|
if not Path(dotenv_path).exists():
|
|
|
|
logger.error(f'File not exist: {dotenv_path}')
|
|
|
|
raise FileNotFoundError(f'dotenv file doesn\'t exists at {dotenv_path}')
|
2022-12-07 19:06:17 -05:00
|
|
|
load_dotenv(dotenv_path=dotenv_path)
|
2023-05-10 17:06:51 -04:00
|
|
|
|
2022-11-11 16:16:31 -05:00
|
|
|
self._db_name = db_name
|
2022-11-15 20:48:42 -05:00
|
|
|
self._db_host = os.getenv(f'{app_env}_DB_HOST')
|
|
|
|
self._db_user = os.getenv(f'{app_env}_DB_USER')
|
|
|
|
self._db_pass = os.getenv(f'{app_env}_DB_PASSWORD')
|
|
|
|
self._db_port = os.getenv(f'{app_env}_DB_PORT')
|
2022-11-15 21:48:09 -05:00
|
|
|
self.hub_token = os.getenv('HUB_TOKEN')
|
2022-12-07 19:06:17 -05:00
|
|
|
except KeyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error with credentials: {err}')
|
2022-11-03 12:49:39 -04:00
|
|
|
|
2023-05-10 17:06:51 -04:00
|
|
|
@property
|
|
|
|
def connection_string(self):
|
|
|
|
"""
|
|
|
|
Returns a connection string postgresql
|
|
|
|
:return: connection string
|
2022-12-07 19:06:17 -05:00
|
|
|
"""
|
|
|
|
if self._db_pass:
|
|
|
|
return f'postgresql://{self._db_user}:{self._db_pass}@{self._db_host}:{self._db_port}/{self._db_name}'
|
|
|
|
return f'postgresql://{self._db_user}@{self._db_host}:{self._db_port}/{self._db_name}'
|
2022-11-25 18:21:09 -05:00
|
|
|
|
2023-05-10 17:06:51 -04:00
|
|
|
@property
|
|
|
|
def db_user(self):
|
|
|
|
"""
|
|
|
|
retrieve the configured user name
|
|
|
|
"""
|
2022-12-07 19:06:17 -05:00
|
|
|
return self._db_user
|
2023-05-10 17:06:51 -04:00
|
|
|
|
|
|
|
@property
|
|
|
|
def db_name(self):
|
|
|
|
"""
|
|
|
|
retrieve the configured database name
|
|
|
|
"""
|
|
|
|
return self._db_name
|