aboutsummaryrefslogtreecommitdiff
path: root/prometheus_pgbouncer_exporter/utils.py
blob: 12e9dddd681ac7f0dedd4d0bd063bfac46b3801f (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
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import psycopg2


def get_connection(user, port):
    connection = psycopg2.connect(
        database='pgbouncer',
        user=user,
        port=port,
    )

    # pgbouncer does not support transactions (as it does not make sense to),
    # so don't start a transaction when connecting
    connection.set_session(autocommit=True)

    return connection


def get_data_by_named_column(connection, key):
    with connection.cursor() as cursor:
        cursor.execute('SHOW %s;' % key)

        rows = cursor.fetchall()
        column_names = list(column.name for column in cursor.description)

    return [
        dict(zip(column_names, row))
        for row in rows
    ]


def get_data_by_named_row(connection, key):
    with connection.cursor() as cursor:
        cursor.execute('SHOW %s;' % key)

        return dict(cursor.fetchall())