55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
|
#!/usr/bin/env python3
|
||
|
|
||
|
# Imports
|
||
|
import psycopg2
|
||
|
from configparser import ConfigParser
|
||
|
|
||
|
|
||
|
class Database:
|
||
|
def __init__(self):
|
||
|
filename = "postgres.ini"
|
||
|
section = "postgresql"
|
||
|
parser = ConfigParser()
|
||
|
parser.read(filename)
|
||
|
|
||
|
config = {}
|
||
|
if parser.has_section(section):
|
||
|
params = parser.items(section)
|
||
|
for param in params:
|
||
|
config[param[0]] = param[1]
|
||
|
else:
|
||
|
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
|
||
|
|
||
|
self.host = config["host"]
|
||
|
self.user = config["user"]
|
||
|
self.password = config["password"]
|
||
|
self.port = 5432
|
||
|
self.dbname = config["database"]
|
||
|
self.conn = None
|
||
|
|
||
|
|
||
|
def connect(self):
|
||
|
if self.conn is None:
|
||
|
try:
|
||
|
self.conn = psycopg2.connect(host=self.host, user=self.user, password=self.password, port=self.port, dbname=self.dbname)
|
||
|
except psycopg2.DatabaseError as e:
|
||
|
print(e)
|
||
|
raise e
|
||
|
finally:
|
||
|
print("Connection opened successfully.")
|
||
|
|
||
|
|
||
|
def runcmd_unsafe(self, cmd):
|
||
|
self.connect()
|
||
|
with self.conn.cursor() as cur:
|
||
|
cur.execute(cmd)
|
||
|
return cur.fetchall()
|
||
|
|
||
|
|
||
|
def list_types(self):
|
||
|
self.connect()
|
||
|
with self.conn.cursor() as cur:
|
||
|
cur.execute("SELECT name FROM types")
|
||
|
types = [row for row in cur.fetchall()]
|
||
|
return types
|