db.py 1.76 KB
Newer Older
1
import mysql.connector
2
import sqlite3
3

4
import aurweb.config
5
6
7
8


class Connection:
    _conn = None
9
    _paramstyle = None
10
11

    def __init__(self):
12
        aur_db_backend = aurweb.config.get('database', 'backend')
13
14

        if aur_db_backend == 'mysql':
15
16
17
18
19
            aur_db_host = aurweb.config.get('database', 'host')
            aur_db_name = aurweb.config.get('database', 'name')
            aur_db_user = aurweb.config.get('database', 'user')
            aur_db_pass = aurweb.config.get('database', 'password')
            aur_db_socket = aurweb.config.get('database', 'socket')
20
21
22
23
24
25
26
27
            self._conn = mysql.connector.connect(host=aur_db_host,
                                                 user=aur_db_user,
                                                 passwd=aur_db_pass,
                                                 db=aur_db_name,
                                                 unix_socket=aur_db_socket,
                                                 buffered=True)
            self._paramstyle = mysql.connector.paramstyle
        elif aur_db_backend == 'sqlite':
28
            aur_db_name = aurweb.config.get('database', 'name')
29
30
31
32
            self._conn = sqlite3.connect(aur_db_name)
            self._paramstyle = sqlite3.paramstyle
        else:
            raise ValueError('unsupported database backend')
33
34

    def execute(self, query, params=()):
35
        if self._paramstyle in ('format', 'pyformat'):
36
37
38
39
40
            query = query.replace('%', '%%').replace('?', '%s')
        elif self._paramstyle == 'qmark':
            pass
        else:
            raise ValueError('unsupported paramstyle')
41
42
43
44
45
46
47
48
49
50
51

        cur = self._conn.cursor()
        cur.execute(query, params)

        return cur

    def commit(self):
        self._conn.commit()

    def close(self):
        self._conn.close()