From 9c1f3cc0c9ff3a56d4c58a05cbee4ad1e04aa657 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Simon=20K=C3=BCnzel?= <simonk@fsmpi.rwth-aachen.de>
Date: Mon, 13 May 2024 23:55:26 +0200
Subject: [PATCH] Add postgres adapter

---
 config.py.example |  7 +++++++
 db.py             | 33 ++++++++++++++++++++++++++++++++-
 requirements.txt  |  1 +
 3 files changed, 40 insertions(+), 1 deletion(-)

diff --git a/config.py.example b/config.py.example
index 767ec61..cf5134a 100644
--- a/config.py.example
+++ b/config.py.example
@@ -16,6 +16,13 @@ DB_DATA = 'db_example.sql'
 #MYSQL_PASSWD = 'somuchsecret'
 #MYSQL_DB = 'videos'
 
+#DB_ENGINE = 'postgres'
+POSTGRES_HOST = '10.0.0.101'
+POSTGRES_PORT = 5432
+POSTGRES_USER = 'videoag'
+POSTGRES_PASSWORD = ''
+POSTGRES_DATABASE = 'videoag'
+
 DB_ENGINE = 'sqlite'
 SQLITE_DB = 'db.sqlite'
 SQLITE_INIT_SCHEMA = True
diff --git a/db.py b/db.py
index 2095b67..b8f274c 100644
--- a/db.py
+++ b/db.py
@@ -90,6 +90,30 @@ elif config['DB_ENGINE'] == 'mysql':
 		cur.close()
 		db.close()
 		return res
+elif config['DB_ENGINE'] == 'postgres':
+	import psycopg
+	
+	def get_dbcursor():
+		if 'db' not in g or g.db.broken:
+			g.db = psycopg.Connection.connect(
+				host=config["POSTGRES_HOST"],
+				port=config["POSTGRES_PORT"],
+				user=config["POSTGRES_USER"],
+				password=config["POSTGRES_PASSWORD"],
+				dbname=config["POSTGRES_DATABASE"]
+				# TODO autocommit?
+			)
+		if not hasattr(request, 'db'):
+			request.db = g.db.cursor()
+		return request.db
+
+	def fix_query(operation, params):
+		operation = operation.replace('?', '%s')
+		params = [(p.replace(microsecond=0) if isinstance(p, datetime) else p) for p in params]
+		return operation, params
+
+	def show(operation, host=None): #pylint: disable=unused-argument
+		return {}
 
 def query(operation, *params, delim="sep", nlfix=True):
 	operation, params = fix_query(operation, params)
@@ -131,11 +155,18 @@ def query(operation, *params, delim="sep", nlfix=True):
 
 def modify(operation, *params, get_id=False):
 	operation, params = fix_query(operation, params)
+	if get_id and config["DB_ENGINE"] == "postgres":
+		operation += " RETURNING id"  # Not nice, but works for now
 	cur = get_dbcursor()
 	cur.execute(operation, params)
 	if not get_id:
 		return None
-	return cur.lastrowid
+	if config["DB_ENGINE"] != "postgres":
+		return cur.lastrowid
+	all_res = cur.fetchall()
+	if len(all_res) <= 0:
+		raise ValueError("Got no id")
+	return int(all_res[0][0])
 
 @app.teardown_request
 def commit_db(*args): #pylint: disable=unused-argument
diff --git a/requirements.txt b/requirements.txt
index d0976ac..77ef8bf 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -9,3 +9,4 @@ ldap3
 icalendar
 mysql-connector-python
 coverage
+psycopg[c]
\ No newline at end of file
-- 
GitLab