-
Notifications
You must be signed in to change notification settings - Fork 0
/
sts_db_ops.py
376 lines (311 loc) · 10.2 KB
/
sts_db_ops.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""Module defines STS functions that interface with the sqlite3 database
File: sts_db_ops.py
Disclaimer: The following source code is the sole work of the author unless otherwise stated.
Copyright (C) Ashley Taylor. All Rights Reserved.
"""
import sqlite3
import datetime
import logging
from tabulate import tabulate
from sts_logging import log_function
logger = logging.getLogger(__name__)
# TEST DB
@log_function
def db_test(database):
"""Inits db, logs connection and sqlite3 version. If table doesn't exist, new one is created.
Returns True if no errors, otherwise returns False and logs errors"""
table_query = f"""
CREATE TABLE IF NOT EXISTS {database["table_name"]}(
id INTEGER PRIMARY KEY,
severity INTEGER,
title TEXT,
status TEXT,
info TEXT,
updated_by TEXT,
created_by TEXT,
date_updated TEXT,
date_created TEXT)
"""
try:
# opens or creates a sqlite3 db and inits a cursor
db_connection = sqlite3.connect(database["db_name"])
cursor = db_connection.cursor()
logger.info("connected to db: %s", database["db_name"])
# Gets version no. of sqlite3 for logger
cursor.execute("SELECT sqlite_version();")
db_version = cursor.fetchall()
logger.info("SQLite Database version: %s", db_version[0][0])
# Checks for valid table in db
if not db_table_test(database, cursor):
print(
"""IMPORTANT:
Database doesn't contain a valid table, see logs for more info.
New table has now been created.
System is ready to use.
"""
)
cursor.execute(table_query)
db_connection.commit()
cursor.close()
return True
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")
# TEST TABLE
@log_function
def db_table_test(database, cursor):
"""Tests the db file to assert whether a table exists, if not a new table is created"""
try:
cursor.execute(
"""SELECT name
FROM sqlite_master
WHERE type='table'
AND name = ?""",
(database["table_name"],),
)
test_result = cursor.fetchone()
if not test_result:
logger.error("no valid table found in database")
return False
logger.info("valid table (%s) found in database", database["table_name"])
return True
except sqlite3.Error as error:
logger.exception(error)
return False
# COUNT
@log_function
def count_tickets(database):
"""Function counts tickets in db and returns an int"""
try:
db_connection = sqlite3.connect(database["db_name"])
logger.info("connected to db")
cursor = db_connection.cursor()
db_init_query = "SELECT COUNT(*) FROM tickets;"
cursor.execute(db_init_query)
tickets_amount = cursor.fetchone()[0]
cursor.close()
logger.info("There are %s tickets in the db", tickets_amount)
print(
f"*** There are currently {tickets_amount} tickets stored in the STS database ***\n"
)
return tickets_amount
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")
# CREATE
@log_function
def insert_ticket_to_db(database, ticket):
"""Function inserts a new ticket into the database"""
query = """INSERT INTO tickets (severity,title,status,info,updated_by,created_by,
date_updated,date_created) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"""
try:
db_connection = sqlite3.connect(database["db_name"])
logger.info("connected to db")
cursor = db_connection.cursor()
datetime_created = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
cursor.execute(
query,
(
ticket.sev,
ticket.title,
ticket.status,
ticket.info,
ticket.username,
ticket.username,
datetime_created,
datetime_created,
),
)
db_connection.commit()
logger.info("ticket successfully inserted into db")
cursor.close()
print("Ticket successfully saved into database\n")
return True
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")
# READ
@log_function
def search_database(database, category, search, order="id"):
"""Function dynamically searches database based on user input,
prints to screen and returns result"""
if category == "username":
query = f"SELECT * FROM tickets WHERE created_by OR updated_by LIKE ? ORDER BY {order}"
else:
query = f"SELECT * FROM tickets WHERE {category} LIKE ? ORDER BY {order}"
try:
table = False
db_connection = sqlite3.connect(database["db_name"])
logger.info("connected to db")
cursor = db_connection.cursor()
cursor.execute(query, (str(search),))
table = cursor.fetchall()
logger.info("db successfully searched")
cursor.close()
if table:
print(
tabulate(
table,
headers=[
"ID",
"Severity",
"Title",
"Status",
"Info",
"Updated by",
"Created by",
"Date Updated",
"Date Created",
],
tablefmt="fancy_grid",
maxcolwidths=25,
)
)
print()
logger.info("ticket/s found & displayed to user")
return table
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")
# UPDATE
@log_function
def update_ticket_to_db(database, ticket):
"""Updates a ticket in the database"""
query = """
UPDATE tickets
SET severity = ?,
title = ?,
status = ?,
info = ?,
updated_by = ?,
date_updated = ?
WHERE
id = ?
"""
try:
db_connection = sqlite3.connect(database["db_name"])
logger.info("connected to db")
cursor = db_connection.cursor()
datetime_updated = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
cursor.execute(
query,
(
ticket.sev,
ticket.title,
ticket.status,
ticket.info,
ticket.username,
datetime_updated,
str(ticket.i_d),
),
)
db_connection.commit()
logger.info("ticket id:%s successfully updated in db", str(ticket.i_d))
cursor.close()
print("Ticket updated successfully\n")
return True
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")
# DELETE
@log_function
def delete_ticket_by_id(database, ticket_id):
"""deletes a ticket from the database, by id"""
query = "DELETE FROM tickets WHERE id = ?"
try:
db_connection = sqlite3.connect(database["db_name"])
logger.info("connected to db")
cursor = db_connection.cursor()
cursor.execute(query, (ticket_id,))
db_connection.commit()
logger.info("ticket id:%s deleted from db", ticket_id)
print(f"Ticket id: {ticket_id} permanently deleted from database\n")
cursor.close()
return True
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
@log_function
def find_id_range(database):
"""Queries database for min and max ids, returns a list of two ints"""
query = "SELECT MIN(id), MAX(id) FROM tickets"
try:
db_connection = sqlite3.connect(database["db_name"])
logger.info("connected to db")
cursor = db_connection.cursor()
cursor.execute(query)
min_max_ids = cursor.fetchall()
logger.info("db id range found")
cursor.close()
return min_max_ids
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")
@log_function
def view_all_tickets(database):
"""Function displays all tickets in database"""
query = "SELECT * FROM tickets;"
try:
db_connection = sqlite3.connect(database["db_name"])
cursor = db_connection.cursor()
logger.info("connected to db")
cursor.execute(query)
table = cursor.fetchall()
logger.info("db successfully searched")
cursor.close()
if table:
print(
tabulate(
table,
headers=[
"ID",
"Sev",
"Title",
"Status",
"Info",
"Updated by",
"Created by",
"Date Updated",
"Date Created",
],
tablefmt="fancy_grid",
maxcolwidths=25,
)
)
print()
logger.info("all tickets found & displayed to user")
return True
except sqlite3.Error as error:
logger.exception(error)
return False
finally:
if db_connection:
db_connection.close()
logger.info("db connection closed")