-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.py
86 lines (65 loc) · 2.9 KB
/
sql.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
import sqlite3
import dateutil.parser
class Database:
def __init__(self, path):
self._db_connection = sqlite3.connect(path)
def retrieve_single_row(self, query, arguments = None):
"""Executes the query and retrieves the single line returned by it
If not exactly one line is retrieved, None is returned.
TODO: Raise exception in case of none or multiple lines"""
cursor = self._db_connection.cursor()
self._execute_query(cursor, query, arguments)
results = cursor.fetchall()
if len(results) <> 1:
return None
else:
return results[0]
def retrieve_rows(self, query, arguments = None):
"""Executes the given query and returns its results.
The resulting list may be empty or contain multiple rows"""
cursor = self._db_connection.cursor()
self._execute_query(cursor, query, arguments)
return cursor.fetchall()
def create_single_row(self, query, arguments = None):
"""Executes the given query and returns the last inserted row_id"""
cursor = self._db_connection.cursor()
self._execute_query(cursor, query, arguments)
last_row_id = cursor.lastrowid
self._db_connection.commit()
return last_row_id
def update_rows(self, query, arguments = None):
"""Executes the given query and commits the results
Until now the difference between this and delete_rows
is purely syntactical.
TODO: Handle errors differently in both functions"""
cursor = self._db_connection.cursor()
self._execute_query(cursor, query, arguments)
self._db_connection.commit()
def delete_rows(self, query, arguments = None):
"""Executes the given query and commits the results
Until now the difference between this and update_rows
is purely syntactical.
TODO: Handle errors differently in both functions"""
cursor = self._db_connection.cursor()
self._execute_query(cursor, query, arguments)
self._db_connection.commit()
def create_table(self, query):
"""Executes the given query and commits the results"""
cursor = self._db_connection.cursor()
self._execute_query(cursor, query, None)
self._db_connection.commit()
def _execute_query(self, cursor, query, arguments):
if arguments <> None:
cursor.execute(query, arguments)
else:
cursor.execute(query)
def sql_datetime_to_python(self, value):
if value <> None:
return dateutil.parser.parse(value)
else:
return None
def python_datetime_to_sql(self, value):
if value <> None:
return str(value)
else:
return None