some docstring things

This commit is contained in:
2024-01-14 15:24:24 -06:00
parent 4a4e969e0f
commit cfa45fc970

View File

@ -1,6 +1,8 @@
"""This module contains functionality for interacting with a PostgreSQL database. It will automatically handle error """This module contains functionality for interacting with a PostgreSQL database. It will automatically handle error
conditions (i.e. missing columns) without terminating the entire program. Use the :py:class:`DBConnector` class to conditions (i.e. missing columns) without terminating the entire program. Use the :py:class:`DBConnector` class to
handle database interactions, either as a standalone object or in a context manager.""" handle database interactions, either as a standalone object or in a context manager."""
from __future__ import annotations
import os import os
import psycopg2 import psycopg2
from psycopg2 import DatabaseError, OperationalError from psycopg2 import DatabaseError, OperationalError
@ -22,7 +24,9 @@ class DBConnector:
with DBConnector() as db: with DBConnector() as db:
db.read() db.read()
""" """
def _db_start(self): def _db_start(self):
"""Setup the database connection and cursor."""
try: try:
self.conn = psycopg2.connect( self.conn = psycopg2.connect(
f"host={DB_ADDRESS} port={DB_PORT} dbname={DB_NAME} user={DB_USER} password={DB_PASSWORD}") f"host={DB_ADDRESS} port={DB_PORT} dbname={DB_NAME} user={DB_USER} password={DB_PASSWORD}")
@ -31,6 +35,7 @@ class DBConnector:
raise e raise e
def _db_stop(self): def _db_stop(self):
"""Close the cursor and connection."""
self.cur.close() self.cur.close()
self.conn.close() self.conn.close()
@ -47,12 +52,18 @@ class DBConnector:
self._db_stop() self._db_stop()
def _query(self, sql) -> list[dict]: def _query(self, sql) -> list[dict]:
"""Basic function for running queries.
:param sql: SQL query as plaintext.
:return: Results of the query, or an empty list if none."""
result = []
try: try:
self.cur.execute(sql) self.cur.execute(sql)
result = self.cur.fetchall() result = self._read_dict()
except DatabaseError as e: except DatabaseError as e:
print(f"DB ERROR [{e.pgcode}]: {e.pgerror}") print(f"ERROR {e.pgcode}: {e.pgerror}\n"
result = [] f"Caused by query: {sql}")
finally:
return result return result
def read(self, **kwargs) -> list[dict]: def read(self, **kwargs) -> list[dict]: