Commit cb5d56e8 authored by Broughton, Mitchell's avatar Broughton, Mitchell
Browse files

added dict option to query function

parent faea14fa
Loading
Loading
Loading
Loading
+7 −4
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@
"""Allow opening with a psycopg2 connection."""
try:
    import psycopg2
    import psycopg2.extras
except ImportError:
    import sys

@@ -77,6 +78,7 @@ class PostgresMixin:
            self.connection.set_client_encoding("UTF8")
            self.logger.debug("Successfully opened connection to database")
            self.cursor = self.connection.cursor()
            self.dict_cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
            self.logger.debug("Successfully created a cursor")
            if isinstance(search_path, list):
                self.search_path = (",").join(search_path)
@@ -94,7 +96,7 @@ class PostgresMixin:
            return False
        return True

    def query(self, query):
    def query(self, query, as_dict=False):
        """Query the database.

        :param query: A Valid SQL statement to send to the database.
@@ -107,9 +109,10 @@ class PostgresMixin:
            self.open()  # assume that it is already open - check if it is
        self.logger.debug("Submitting user specified query to database.")
        try:
            self.cursor.execute(query)
            if self.cursor.description is not None:
                return self.cursor.fetchall()
            this_cursor = self.cursor if not as_dict else self.dict_cursor
            this_cursor.execute(query)
            if this_cursor.description is not None:
                return this_cursor.fetchall()
            return None
        except psycopg2.InterfaceError as error:
            self.logger.error(f"An unexpected InterfaceError occurred: {error}")