Commit c82a5667 authored by Huihui, Jonathan's avatar Huihui, Jonathan
Browse files

Merge branch 'feature/search_path' into 'develop'

Feature/search path

See merge request nset-utilities/common-package!5
parents eb255b41 aa34c73a
Loading
Loading
Loading
Loading
+23 −14
Original line number Diff line number Diff line
@@ -2,12 +2,19 @@
# -*- coding: utf-8 -*-
"""Allow opening with a psycopg2 connection."""
import psycopg2
from common.env import check_environment as ce


class PostgresMixin():
    """Serve common connection method for postgres."""
    """Serve common connection method for postgres.

    def open(self, search_path='public'):
       The default `search_path` variable can be set with the following
       operating system variable:
           - DATABASE_SEARCH_PATH
    """
    DEFAULT_SEARCH_PATH = ce('DATABASE_SEARCH_PATH', 'public')

    def open(self, search_path=DEFAULT_SEARCH_PATH):
        """ Explicitly open the database connection

        :param search_path: the search path to default to
@@ -16,8 +23,6 @@ class PostgresMixin():
        """
        self.logger.debug('Opening Database Connection and creating Cursor')
        try:
            """ print(self.dbName + ',' + self.user + ',' + self.host + "," +
            str(self.port) + "," + str(self.timeout)) """
            self.connection = psycopg2.connect(
                database=self.connection_info['dbName'],
                user=self.connection_info['dbUser'],
@@ -29,15 +34,19 @@ class PostgresMixin():
            self.logger.debug('Successfully opened connection to database')
            self.cursor = self.connection.cursor()
            self.logger.debug('Successfully created a cursor')
            # TODO @Jonathan v--- not the default search paths - env var?
            """ ^---- need this re-explained """
            # @TODO @Jonathan add searth_paths as a possible variable to pass
            if isinstance(search_path, list):
                self.search_path = (',').join(search_path)
                # if passed as a list, split and concat into commas
            self.cursor.execute("""SET search_path TO public, outage_data,
                                 utility, system_monitoring;""")
            elif isinstance(search_path, str):
                self.search_path = search_path
            else:
                self.logger.error(f'Unknown type: {search_path}.')
                self.search_path = 'public'
            self.cursor.execute(f"""SET search_path TO {self.search_path};""")
            self.cursor.commit()
            self.logger.debug('Successfully set search_path')
        except psycopg2.OperationalError as e:  # TODO @Jonathan other errors?
            self.logger.error(f'Database Error: {e}')
        except psycopg2.OperationalError as error:
            self.logger.error(f'Database Error: {error}')
            return False
        return True

@@ -50,9 +59,9 @@ class PostgresMixin():

        """
        if not self.is_open():
            self.logger.info(f'Database not open, opening now.')
            self.logger.info('Database not open, opening now.')
            self.open()  # assume that it is already open - check if it is
        self.logger.debug(f'Submitting user specified query to database.')
        self.logger.debug('Submitting user specified query to database.')
        try:
            self.cursor.execute(query)
            if self.cursor.description is not None:
+11 −11

File changed.

Contains only whitespace changes.