python-mylib/mylib/pgsql.py

173 lines
5 KiB
Python
Raw Normal View History

""" PostgreSQL client """
import datetime
import logging
import sys
import psycopg2
from mylib.db import DB, DBFailToConnect
2021-10-06 21:33:25 +02:00
log = logging.getLogger(__name__)
class PgDB(DB):
"""PostgreSQL client"""
_host = None
_user = None
_pwd = None
_db = None
date_format = "%Y-%m-%d"
datetime_format = "%Y-%m-%d %H:%M:%S"
def __init__(self, host, user, pwd, db, **kwargs):
2021-11-07 21:37:18 +01:00
self._host = host
self._user = user
self._pwd = pwd
self._db = db
super().__init__(**kwargs)
def connect(self, exit_on_error=True):
"""Connect to PostgreSQL server"""
2021-11-07 21:37:18 +01:00
if self._conn is None:
try:
log.info(
"Connect on PostgreSQL server %s as %s on database %s",
self._host,
self._user,
self._db,
)
2021-11-07 21:37:18 +01:00
self._conn = psycopg2.connect(
dbname=self._db, user=self._user, host=self._host, password=self._pwd
2021-05-19 19:19:57 +02:00
)
2023-01-06 19:36:14 +01:00
except psycopg2.Error as err:
2021-11-07 21:37:18 +01:00
log.fatal(
"An error occured during Postgresql database connection (%s@%s, database=%s).",
self._user,
self._host,
self._db,
exc_info=1,
)
if exit_on_error:
sys.exit(1)
else:
raise DBFailToConnect(f"{self._user}@{self._host}:{self._db}") from err
return True
def close(self):
"""Close connection with PostgreSQL server (if opened)"""
2021-11-07 21:37:18 +01:00
if self._conn:
self._conn.close()
self._conn = None
def setEncoding(self, enc):
"""Set connection encoding"""
2021-11-07 21:37:18 +01:00
if self._conn:
try:
2021-11-07 21:37:18 +01:00
self._conn.set_client_encoding(enc)
return True
2023-01-06 19:36:14 +01:00
except psycopg2.Error:
2021-10-06 21:33:25 +02:00
log.error(
'An error occured setting Postgresql database connection encoding to "%s"',
enc,
exc_info=1,
2021-10-06 21:33:25 +02:00
)
return False
def doSQL(self, sql, params=None):
2021-10-06 21:33:25 +02:00
"""
Run SQL query and commit changes (rollback on error)
:param sql: The SQL query
:param params: The SQL query's parameters as dict (optional)
:return: True on success, False otherwise
:rtype: bool
"""
if self.just_try:
2021-10-06 21:33:25 +02:00
log.debug("Just-try mode : do not really execute SQL query '%s'", sql)
return True
2021-11-07 21:37:18 +01:00
cursor = self._conn.cursor()
try:
2023-01-06 19:36:14 +01:00
self._log_query(sql, params)
if params is None:
cursor.execute(sql)
else:
cursor.execute(sql, params)
2021-11-07 21:37:18 +01:00
self._conn.commit()
return True
2023-01-06 19:36:14 +01:00
except psycopg2.Error:
self._log_query_exception(sql, params)
2021-11-07 21:37:18 +01:00
self._conn.rollback()
return False
2021-10-06 21:33:25 +02:00
def doSelect(self, sql, params=None):
"""
Run SELECT SQL query and return list of selected rows as dict
:param sql: The SQL query
:param params: The SQL query's parameters as dict (optional)
:return: List of selected rows as dict on success, False otherwise
:rtype: list, bool
"""
2021-11-07 21:37:18 +01:00
cursor = self._conn.cursor()
try:
2023-01-06 19:36:14 +01:00
self._log_query(sql, params)
cursor.execute(sql, params)
results = cursor.fetchall()
return results
2023-01-06 19:36:14 +01:00
except psycopg2.Error:
self._log_query_exception(sql, params)
2021-10-06 21:33:25 +02:00
return False
2023-01-06 19:36:14 +01:00
@staticmethod
def _map_row_fields_by_index(fields, row):
return {field: row[idx] for idx, field in enumerate(fields)}
2023-01-06 19:36:14 +01:00
2021-10-06 21:33:25 +02:00
#
# Depreated helpers
#
@classmethod
def _quote_value(cls, value):
"""Quote a value for SQL query"""
2021-10-06 21:33:25 +02:00
if value is None:
return "NULL"
2021-10-06 21:33:25 +02:00
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, datetime.datetime):
value = cls._format_datetime(value)
elif isinstance(value, datetime.date):
value = cls._format_date(value)
2023-01-06 19:36:14 +01:00
# pylint: disable=consider-using-f-string
return "'{}'".format(value.replace("'", "''"))
2021-10-06 21:33:25 +02:00
@classmethod
def _format_datetime(cls, value):
"""Format datetime object as string"""
2021-10-06 21:33:25 +02:00
assert isinstance(value, datetime.datetime)
return value.strftime(cls.datetime_format)
@classmethod
def _format_date(cls, value):
"""Format date object as string"""
2021-10-06 21:33:25 +02:00
assert isinstance(value, (datetime.date, datetime.datetime))
return value.strftime(cls.date_format)
@classmethod
def time2datetime(cls, time):
"""Convert timestamp to datetime string"""
2021-10-06 21:33:25 +02:00
return cls._format_datetime(datetime.datetime.fromtimestamp(int(time)))
@classmethod
def time2date(cls, time):
"""Convert timestamp to date string"""
2021-10-06 21:33:25 +02:00
return cls._format_date(datetime.date.fromtimestamp(int(time)))