summaryrefslogtreecommitdiffstats
path: root/test/features/db_utils.py
blob: be550e9f32ebf12bcc8458a50608167032d76225 (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
88
89
90
91
92
93
import pymysql


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

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

    """
    cn = pymysql.connect(
        host=hostname,
        port=port,
        user=username,
        password=password,
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )

    with cn.cursor() as cr:
        cr.execute('drop database if exists ' + dbname)
        cr.execute('create database ' + dbname)

    cn.close()

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


def create_cn(hostname, port, password, username, dbname):
    """Open connection to database.

    :param hostname:
    :param port:
    :param password:
    :param username:
    :param dbname: string
    :return: psycopg2.connection

    """
    cn = pymysql.connect(
        host=hostname,
        port=port,
        user=username,
        password=password,
        db=dbname,
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )

    return cn


def drop_db(hostname='localhost', port=3306, username=None,
            password=None, dbname=None):
    """Drop database.

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

    """
    cn = pymysql.connect(
        host=hostname,
        port=port,
        user=username,
        password=password,
        db=dbname,
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )

    with cn.cursor() as cr:
        cr.execute('drop database if exists ' + dbname)

    close_cn(cn)


def close_cn(cn=None):
    """Close connection.

    :param connection: pymysql.connection

    """
    if cn:
        cn.close()