aboutsummaryrefslogtreecommitdiffstats
path: root/common/postgres.py
diff options
context:
space:
mode:
authorDennis Eriksen <d@ennis.no>2023-02-01 12:24:22 +0100
committerDennis Eriksen <d@ennis.no>2023-02-01 12:24:22 +0100
commitd86413ad81135454df7ef1c7d7faeb52eb51efa8 (patch)
treefaf9e7cc5bc728065f4d87f86db7c8b190ba42ed /common/postgres.py
parentuse new db thingy (diff)
downloadenergyscripts-d86413ad81135454df7ef1c7d7faeb52eb51efa8.tar.gz
adding some common stuff, less code replica
Diffstat (limited to 'common/postgres.py')
-rw-r--r--common/postgres.py28
1 files changed, 28 insertions, 0 deletions
diff --git a/common/postgres.py b/common/postgres.py
new file mode 100644
index 0000000..bff0720
--- /dev/null
+++ b/common/postgres.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python3
+''' common functions and stuff '''
+
+import os
+import sys
+import psycopg
+
+pg_db = os.environ['el_pg_db']
+pg_host = os.environ['el_pg_host']
+pg_user = os.environ.get('el_pg_user','')
+pg_pass = os.environ.get('el_pg_pass','')
+
+def dbi(sql, values, **kwargs):
+ ''' insert into db '''
+ verbose = bool(kwargs['verbose']) if 'verbose' in kwargs else False
+ # pylint: disable=E1129
+ with psycopg.connect(dbname=pg_db, host=pg_host, user=pg_user, password=pg_pass) as conn:
+ cur = conn.cursor()
+ if isinstance(values, list):
+ cur.executemany(sql, values)
+ elif isinstance(values, tuple):
+ cur.execute(sql, values)
+ else:
+ print('`values` is a', type(values), 'but it needs to be tuple or list')
+ sys.exit(1)
+ if verbose is True:
+ print("Inserted and/or changed", cur.rowcount, "rows into db")
+ return True