summaryrefslogtreecommitdiffstats
path: root/tests/features/db_utils.py
blob: 595c6c2c375130d7604ef5ab8bec0b6bf774aea8 (plain)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from psycopg import connect


def create_db(
    hostname="localhost", username=None, password=None, dbname=None, port=None
):
    """Create test database.

    :param hostname: string
    :param username: string
    :param password: string
    :param dbname: string
    :param port: int
    :return:

    """
    cn = create_cn(hostname, password, username, "postgres", port)

    cn.autocommit = True
    with cn.cursor() as cr:
        cr.execute(f"drop database if exists {dbname}")
        cr.execute(f"create database {dbname}")

    cn.close()

    cn = create_cn(hostname, password, username, dbname, port)
    return cn


def create_cn(hostname, password, username, dbname, port):
    """
    Open connection to database.
    :param hostname:
    :param password:
    :param username:
    :param dbname: string
    :return: psycopg2.connection
    """
    cn = connect(
        host=hostname, user=username, dbname=dbname, password=password, port=port
    )

    print(f"Created connection: {cn.info.get_parameters()}.")
    return cn


def pgbouncer_available(hostname="localhost", password=None, username="postgres"):
    cn = None
    try:
        cn = create_cn(hostname, password, username, "pgbouncer", 6432)
        return True
    except:
        print("Pgbouncer is not available.")
    finally:
        if cn:
            cn.close()
    return False


def drop_db(hostname="localhost", username=None, password=None, dbname=None, port=None):
    """
    Drop database.
    :param hostname: string
    :param username: string
    :param password: string
    :param dbname: string
    """
    cn = create_cn(hostname, password, username, "postgres", port)

    # Needed for DB drop.
    cn.autocommit = True

    with cn.cursor() as cr:
        cr.execute(f"drop database if exists {dbname}")

    close_cn(cn)


def close_cn(cn=None):
    """
    Close connection.
    :param connection: psycopg2.connection
    """
    if cn:
        cn_params = cn.info.get_parameters()
        cn.close()
        print(f"Closed connection: {cn_params}.")