aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/common/postgres.py
blob: 5692535543d621579a24c0307f8babfcdc21770a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python3
""" common functions and stuff """

import sys

import psycopg

from . import env

pg_db = env("el_pg_db")
pg_host = env("el_pg_host")
pg_user = env("el_pg_user", "")
pg_pass = env("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 in db")
    return True