db_insert()   B
last analyzed

Complexity

Conditions 5

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 5
c 4
b 0
f 0
dl 0
loc 25
rs 8.8133
1
#    Copyright 2017 Starbot Discord Project
2
#
3
#    Licensed under the Apache License, Version 2.0 (the "License");
4
#    you may not use this file except in compliance with the License.
5
#    You may obtain a copy of the License at
6
#
7
#        http://www.apache.org/licenses/LICENSE-2.0
8
#
9
#    Unless required by applicable law or agreed to in writing, software
10
#    distributed under the License is distributed on an "AS IS" BASIS,
11
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
#    See the License for the specific language governing permissions and
13
#    limitations under the License.
14
"""SQLite Abstraction layer for Starbot's database API."""
15
16
import sqlite3
17
from api.database.entry import Entry
18
19
20
def db_open(db_in):
21
    """Open the Database."""
22
    db_in.type = "SQLite"
23
    db_in.connection = sqlite3.connect("bot.db3")
24
25
26
def db_close(db_in):
27
    """Close the Database."""
28
    # Close the database.
29
    db_in.connection.close()
30
31
32
def db_create_table(db_in, tablename):
33
    """Create a new table in the database unless it already exists."""
34
    connection = db_in.connection.cursor()
35
    connection.execute('CREATE TABLE IF NOT EXISTS %s(id INTEGER PRIMARY KEY);' % tablename)
36
37
38
def db_insert(db_in, table, dict_in):
39
    """Insert new entry in database."""
40
    connection = db_in.connection.cursor()
41
    keys = []
42
    values = []
43
    for key, value in dict_in.items():
44
        keys.append(key)
45
        # Escape quotes
46
        if isinstance(value, str):
47
            values.append("'" + value.replace("'", "''") + "'")
48
        else:
49
            values.append("'" + str(value) + "'")
50
51
    # Update entries for each key and value.
52
    for key in keys:
53
        # Attempt to add column, fail silently if it exists.
54
        try:
55
            connection.execute('ALTER TABLE %s ADD COLUMN %s' % (table.name, key))
56
        except sqlite3.OperationalError:
57
            pass
58
59
    connection.execute('INSERT INTO %s(%s) VALUES (%s);' % (table.name, ",".join(keys), ",".join(values)))
60
    return_entry = Entry(connection.lastrowid, db_in, table, dict_in)
61
    db_in.connection.commit()
62
    return return_entry
63
64
65
def db_entry_edit(db_in, table, entry_id, dict_in):
66
    """Edit existing database entry."""
67
    connection = db_in.connection.cursor()
68
69
    # Update entries for each key and value.
70
    for key, value in dict_in.items():
71
        # Attempt to add column, fail silently if it exists.
72
        try:
73
            connection.execute('ALTER TABLE %s ADD COLUMN %s' % (table.name, key.replace("'", "''")))
74
        except sqlite3.OperationalError:
75
            pass
76
        # Update the entry in the database.
77
        connection.execute("UPDATE '%s' SET %s='%s' WHERE id=%s;" % (table.name, key, value, str(entry_id)))
78
79
    db_in.connection.commit()
80
81
82
def db_entry_delete(db_in, table, entry_id):
83
    """Delete database entry."""
84
    connection = db_in.connection.cursor()
85
    connection.execute('DELETE FROM %s WHERE id=%s' % (table.name, str(entry_id)))
86
87
88
def db_search(db_in, table, search_key, search_query):
89
    """Select first entry that matches and return type entry."""
90
    connection = db_in.connection.cursor()
91
    search_query = search_query.replace("'", "''")  # Escape quotes
92
    cursor = connection.execute("SELECT * FROM %s WHERE %s='%s';" %
93
                                (table.name, search_key, search_query))
94
    for row in cursor:
95
        return Entry(row[0], db_in, table, row)
96
97
def db_get_contents_of_table(db_in, table, rows):
98
    connection = db_in.connection.cursor()
99
    cursor = connection.execute("SELECT %s FROM %s" % (", ".join(rows), table.name))
100
    results = []
101
    for row in cursor:
102
        results.append(row)
103
    return results
104
105
def db_get_latest_id(db_in, table):
106
    connection = db_in.connection.cursor()
107
    cursor = connection.execute("SELECT * FROM \"%s\" ORDER BY id DESC LIMIT 1" % (table.name))
108
    for row in cursor:
109
        return row[0]
110