forked from Hanabi/hanabi-league
31 lines
924 B
Python
31 lines
924 B
Python
|
import psycopg2
|
||
|
|
||
|
from config import read_db_config
|
||
|
from log_setup import logger
|
||
|
|
||
|
|
||
|
class DBConnectionManager:
|
||
|
def __init__(self):
|
||
|
self._conn = None
|
||
|
|
||
|
def connect(self):
|
||
|
config = read_db_config()
|
||
|
logger.debug("Establishing database connection.")
|
||
|
self._conn = psycopg2.connect("dbname='{}' user='{}' password='{}' host='localhost'".format(
|
||
|
config.db_name, config.db_user, config.db_pass
|
||
|
))
|
||
|
logger.debug("Established database connection.")
|
||
|
|
||
|
def get_connection(self):
|
||
|
"""
|
||
|
Get the database connection.
|
||
|
If not already connected, this reads the database config file and connects to the DB.
|
||
|
Otherwise, the already active connection is returned.
|
||
|
"""
|
||
|
if self._conn is None:
|
||
|
self.connect()
|
||
|
return self._conn
|
||
|
|
||
|
|
||
|
# Global instance that will hold our DB connection
|
||
|
conn_manager = DBConnectionManager()
|