
| Current Path : /var/www/web-klick.de/dsh/order_model/scripts/scratches/ |
Linux ift1.ift-informatik.de 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64 |
| Current File : /var/www/web-klick.de/dsh/order_model/scripts/scratches/db_connect.py |
__author__ = 'Patrick Thomanek'
__maintainer__ = 'Patrick Thomanek'
__status__ = 'Development'
import logging
import platform
from pathlib import PurePath
from typing import List, Dict, Optional, Any
import cx_Oracle
from ordermodel.config import Config
LIB_ORACLE_LOCAL_PATH = PurePath(__file__).parents[1] / 'lib-oracle/instantclient_19_10_win_x64'
print(LIB_ORACLE_LOCAL_PATH.as_posix())
class DBConnect:
"""Class to connect to db-timmy.
Requires Oracle client libraries in $PATH or $LD_LIBRARY_PATH.
Installation path might be /sw/common-os/oracle/client/12.2.0.1/bin or similar.
Alternatively load directly via cx_Oracle.init_oracle_client(lib_dir=<install_path>).
Attributes:
self._connection: cx_Oracle client connection object.
"""
def __init__(self):
self.log = logging.getLogger(__name__)
self.config = Config()
self._init_oracle_client()
self._connection = None
self.success = None # Todo: Review this implementation.
def connect(self):
try:
connection = cx_Oracle.connect(
self.config.get('db_timmy_maintenance', 'username'),
self.config.get('db_timmy_maintenance', 'password'),
self.config.get('db_timmy_maintenance', 'dsn'),
encoding=self.config.get('db_timmy_maintenance', 'encoding'))
connection.autocommit = True
self._connection = connection
print(f'{connection.version=} '
f'{connection.dsn=} '
f'{connection.username=}')
except cx_Oracle.Error as e:
print(e)
self.log.error(f'{e}')
self.success = False
def disconnect(self):
if self._connection:
self._connection.close()
def execute_plain(self, sql_statement):
self.success = True
try:
with self._connection.cursor() as cursor:
cursor.execute(sql_statement)
row = cursor.fetchone()
print(row[0])
except Exception as e:
print(f'{e} {sql_statement}')
self.success = False
def execute(self, sql_statement, values: List[str]):
self.success = True
try:
with self._connection.cursor() as cursor:
cursor.execute(sql_statement, values)
except Exception as e:
self.log.error(f'{e} {sql_statement}')
self.success = False
def executemany(self, sql_statement, values: List[Dict[str, Optional[Any]]]):
self.success = True
try:
with self._connection.cursor() as cursor:
cursor.executemany(sql_statement, values)
except Exception as e:
self.log.error(f'{e} {sql_statement}')
self.success = False
@staticmethod
def _init_oracle_client():
if platform.system() == 'Linux':
cx_Oracle.init_oracle_client()
else:
cx_Oracle.init_oracle_client(lib_dir=LIB_ORACLE_LOCAL_PATH.as_posix())