-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbms.py
207 lines (158 loc) · 5.85 KB
/
dbms.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
#!/usr/bin/python3
#-----------------------------------------------------------------------------
# project: chinook
# authors: 1966bc
# mailto: [giuseppecostanzi@gmail.com]
# modify: hiems MMXXI
#-----------------------------------------------------------------------------
import sys
import inspect
import datetime
import sqlite3 as lite
class DBMS:
def __init__(self,):
self.set_connection()
def __str__(self):
return "class: {0}\nMRO: {1}".format(self.__class__.__name__,
[x.__name__ for x in DBMS.__mro__],)
def set_connection(self):
self.con = lite.connect("chinook.db",
detect_types=lite.PARSE_DECLTYPES|lite.PARSE_COLNAMES,
isolation_level='IMMEDIATE')
self.con.text_factory = lite.OptimizedUnicode
def read(self, fetch, sql, args=()):
"""Remember that fetchall() return a list.\
An empty list is returned when no rows are available.
Testing if the list is empty with 'if rs' or 'if not rs'
Otherwise fetchone() return a single sequence, or None
when no more data is available.
Testing as 'if rs is not None'.
"""
try:
cur = self.con.cursor()
cur.execute(sql, args)
if fetch == True:
rs = cur.fetchall()
else:
rs = cur.fetchone()
cur.close()
return rs
except:
self.on_log(self,
inspect.stack()[0][3],
sys.exc_info()[1],
sys.exc_info()[0],
sys.modules[__name__])
def write(self, sql, args=()):
try:
cur = self.con.cursor()
cur.execute(sql, args)
self.con.commit()
return cur.lastrowid
except:
self.con.rollback()
self.on_log(self,
inspect.stack()[0][3],
sys.exc_info()[1],
sys.exc_info()[0],
sys.modules[__name__])
finally:
try:
cur.close()
except:
self.on_log(self,
inspect.stack()[0][3],
sys.exc_info()[1],
sys.exc_info()[0],
sys.modules[__name__])
def dump(self,):
dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
s = dt + ".sql"
with open(s, 'w') as f:
for line in self.con.iterdump():
f.write('%s\n' % line)
def get_fields(self, table):
"""return fields name of the args table ordered by field number
@param name: table,
@return: fields
@rtype: tuple
"""
try:
columns = []
fields = []
sql = "SELECT * FROM {0}".format(table)
cur = self.con.cursor()
cur.execute(sql)
for field in cur.description:
columns.append(field[0])
cur.close()
for k, v in enumerate(columns):
if k > 0:
fields.append(v)
return tuple(fields)
except:
self.on_log(self,
inspect.stack()[0][3],
sys.exc_info()[1],
sys.exc_info()[0],
sys.modules[__name__])
finally:
try:
cur.close()
except:
self.on_log(self,
inspect.stack()[0][3],
sys.exc_info()[1],
sys.exc_info()[0],
sys.modules[__name__])
def get_update_sql(self, table, pk):
"""recive a table name and his pk to format an update sql statement
@param name: table, pk
@return: sql formatted stringstring
@rtype: string
"""
return "UPDATE {0} SET {1} =? WHERE {2} =?".format(table, " =?, ".join(self.get_fields(table)), pk)
def get_insert_sql(self, table, n):
"""recive a table name and len of args, len(args),
to format an insert sql statement
@param name: table, n = len(args)
@return: sql formatted stringstring
@rtype: string
"""
return "INSERT INTO {0}({1})VALUES({2})".format(table, ",".join(self.get_fields(table)), ",".join("?"*n))
def get_selected(self, table, field, *args):
"""recive table name, pk and return a dictionary
@param name: table,field,*args
@return: dictionary
@rtype: dictionary
"""
d = {}
sql = "SELECT * FROM {0} WHERE {1} = ?".format(table, field)
for k, v in enumerate(self.read(False, sql, args)):
d[k] = v
return d
def set_total(self, invoice):
sql = "SELECT unit_price, quantity\
FROM invoice_items\
WHERE invoice_id = ?\
AND status =1;"
args = (invoice[0],)
count = 0
rs = self.read(True, sql, args)
if rs:
for i in rs:
count += (i[0]*i[1])
sql = "UPDATE invoices SET total=? WHERE invoice_id=?"
args = (count, invoice[0], )
self.write(sql, args)
def main():
foo = DBMS()
print(foo)
sql = "SELECT name FROM sqlite_master WHERE type = 'table'"
rs = foo.read(True, sql)
if rs:
for i in enumerate(rs):
print(i)
input('end')
if __name__ == "__main__":
main()