import os import psycopg from psycopg.rows import dict_row TABLE_ACCOUNTS = "x_accounts" TABLE_X = "x_posts" class DatabaseController: def __init__(self): if not os.path.exists("database_config.txt"): raise Exception(f"Create 'database_config.txt' in {os.path.abspath(os.curdir)} with database connection string, example: 'dbname=japariarchive user=postgres password=password123'") with open("database_config.txt", "rt") as file: connection_string = file.read() self.conn = psycopg.connect(connection_string, row_factory=dict_row) self.cursor = self.conn.cursor() def run_query(self, query): try: self.cursor.execute(query) results = self.cursor.fetchall() self.conn.rollback() return True, results except Exception as e: print(query, e) self.conn.rollback() return False, str(e) def run_command(self, command): try: self.cursor.execute(command) result = self.cursor.rowcount self.conn.commit() return result > 0 except Exception as e: self.conn.rollback() print(command, e) return False def run_commands(self, commands): last_command = "" try: for command in commands: last_command = command self.cursor.execute(command) result = self.cursor.rowcount self.conn.commit() return result > 0 except Exception as e: self.conn.rollback() print(last_command, e) return False def close(self): self.conn.close()