summaryrefslogtreecommitdiff
path: root/server/database.py
blob: 792fc275f9db7f360768648f9cdf7ca721134791 (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
'''
    A class with the specific intent of making
    database actions easy & decluttered.

    Verified: 2021 February 7
    * Follows PEP8
    * Tested Platforms
        * Windows 10
'''

from server.state import ServerStatic

import sqlite3
import os


class Database:

    __DATABASE_FN = 'database.db'

    def __init__(self):
        if not os.path.isdir(ServerStatic.ARCHIVE_DIR):
            os.makedirs(ServerStatic.ARCHIVE_DIR, exist_ok=True)

        self.__conn = sqlite3.connect(os.path.join(
                                      ServerStatic.ARCHIVE_DIR,
                                      Database.__DATABASE_FN))
        self.__cursor = self.__conn.cursor()

    def commit(self):
        self.__conn.commit()

    def close(self):
        self.__conn.close()

    def execute(self, sql, values=()):
        self.__cursor.execute(sql, values)

    def create_table(self, table, **kwargs):
        self.__cursor.execute(
            'CREATE TABLE IF NOT EXISTS '
            '{} ({}, UNIQUE ({}) ON CONFLICT IGNORE)'.format(
                table, Database.parse(kwargs), ','.join(kwargs)))

    def read(self, table, fields=('*',), fetch=0, condition=()):
        self.__cursor.execute('SELECT {} FROM {}{}'.format(
            ','.join(fields), table, (' WHERE {}{}?'.format(
                *condition[:2]) if condition else '')
            ), (condition[2],) if condition else condition)

        if fetch > 0:
            return self.__cursor.fetchmany(fetch)
        else:
            return self.__cursor.fetchall()

    def write(self, table, values):
        self.__cursor.execute('INSERT INTO {} VALUES ({})'.format(
            table, ','.join(tuple('?' * len(values)))), values)

    def update(self, table, condition, **kwargs):
        self.__cursor.execute('UPDATE {} SET {} WHERE {}{}?'.format(
            table, Database.parse({
                key: '?' for key in kwargs
            }, '='), *condition[:2]
        ), list(kwargs.values()) + [condition[2]])

    def delete(self, table, condition):
        self.__cursor.execute('DELETE FROM {} WHERE {}{}?'.format(
            table, *condition[:2]), (condition[2],))

    @staticmethod
    def parse(dictionary, seperator=' '):
        return ','.join((key + seperator + value
                        for key, value in dictionary.items()))