-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.py
executable file
·317 lines (293 loc) · 11.8 KB
/
database.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
#!/usr/bin/python3
import os, sqlite3, json, time
# Got some great tips from:
# http://www.pythoncentral.io/introduction-to-sqlite-in-python/
# Class to manage all database operations
class Database:
# Create a new database connection _
def __init__(self, dbfile, dbstruct, ignore='locals'):
self.msg = '\n=======__init--() ==='
try:
self.dbfile = dbfile
self.dbstruct = dbstruct
self.db = sqlite3.connect(self.dbfile)
self.ignore = ignore
self.msg += '\nStarted DB'
self.keys = {}
for table in self.dbstruct:
if table != ignore:
self.keys[table] = {}
for key, datatype in self.dbstruct[table]:
self.keys[table][key] = datatype
except Exception as e:
self.msg += '\n'+str(e)
def printmsg(self):
rmsg = self.msg
self.msg= ''
return rmsg
# Build the db and create the structure if it doesn't exist
def build(self):
self.msg = '\n====--database build()====='
try:
cursor = self.db.cursor()
# lets loop through our structure
for tablename in self.dbstruct:
# Check we should be building this table
if self.ignore != tablename:
# Check if our table exists
qry = "SELECT * FROM sqlite_master WHERE type='table' AND name='{}';".format(tablename)
self.msg += '\n'+qry
cursor.execute(qry)
table = str(cursor.fetchone())
# It doesn't seem to exist so lets create it
if table == 'None':
fieldlist = s = ''
for i, v in self.dbstruct[tablename]:
if fieldlist != '': s = ','
fieldlist += '{}{} {}'.format(s, i, v)
qry = 'CREATE TABLE {0} ({1})'.format(tablename, fieldlist)
self.msg += '\n'+qry
cursor.execute(qry)
self.msg += '\n'+qry
self.msg += '\nBuilt a new database\n'
else:
self.msg += '\nFound a table/database so didn\'t recreate it\n'
self.db.commit()
return True
except Exception as e:
self.msg += '\n'+str(e)
return False
# Close the dbconnection
def close(self):
self.db.close()
# Create a new set of records when presented with a list of tablenames, fieldnames and values
def create(self, tablename, data):
self.msg ="\n====database create() (creates new records)===="
try:
# Create a cursor
cursor = self.db.cursor()
# And a list of fieldname
fieldnames = ','.join(data['fieldnames'])
q = ','.join(['?']*len(data['fieldnames']))
# Prep the vars for inserting many nodes at a time
if len(data['values']) > 1:
qry = 'INSERT INTO {0}({1}) VALUES({2}) '.format(tablename, fieldnames, q)
self.msg +="\nMultiplenodes:\n"+qry
cursor.executemany(qry, data['values'])
myid = None
# Prep the vars for inserting a single record
else:
qry = 'INSERT INTO {}({}) VALUES({})'.format(tablename, fieldnames,q)
self.msg +="\nSinglnode:\n"+qry
cursor.execute(qry, (data['values'][0]))
myid = cursor.lastrowid
self.db.commit()
return myid
except Exception as e:
# TODO: Return the error message, not just false..
self.msg += '\n'+str(e)
return False
# Return a json formated list of a select query
def readasjson(self, table, fields, nodelist=[], qry=''):
self.msg = '\n=========database readasjson()======'
#try:
cursor = self.db.cursor()
fieldstr = ','.join(fields)
where = ''
# If we have nodes, then attempt to convert the string to an int
# This has the effect of failing if the there is a code insertion event
if len(nodelist) != 0:
where = 'WHERE nid IN ('+','.join(map(str, map(int, nodelist)))+')'
qry = 'SELECT {0} FROM {1} {2} {3}'.format(fieldstr, table, where, qry)
self.msg += '\n'+qry
cursor.execute(qry)
arr = []
for row in cursor:
arr.append({})
n = len(arr)-1
i = 0
for val in row:
key = fields[i]
if self.keys[table][key] == 'JSON':
try:
val = json.loads(val)
except Exception as e:
val = json.loads('{}')
arr[n][key] = val
i += 1
return json.dumps(arr)
#except Exception as e:
self.msg += '\n'+str(e)
return False
#
def dbselectquery(self, qry):
self.msg ="\n====database query() ===="
try:
cursor = self.db.cursor()
cursor.execute(qry)
self.msg += '\n{}'.format(qry)
return cursor
except Exception as e:
self.msg += '\n'+str(e)
return False
# Update
def update(self, table, idname, idval, fieldnvalues):
self.msg ="\n====database update() ===="
try:
# Create a cursor
cursor = self.db.cursor()
# Prep the vars
fieldnames = []
values = []
for key in fieldnvalues:
fieldnames.append(key+'=?')
values.append(fieldnvalues[key])
values.append(idval)
setqry = ','.join(fieldnames)
qry = 'UPDATE {0} SET {2} WHERE {1}=?'.format(table, idname, setqry)
self.msg +="\n"+qry
cursor.execute(qry, values)
self.db.commit()
self.msg +="\n"+str(fieldnvalues)
self.msg +="\n"+str(values)
self.msg +="\nSuccess!"
return True
except Exception as e:
self.msg += '\n'+str(e)
return False
def dbquery(self, qry):
self.msg ="\n====database query() ===="
try:
cursor = self.db.cursor()
cursor.execute(qry)
self.db.commit()
except Exception as e:
self.msg += '\n'+str(e)
return False
# Search for a value and return the spec
# TODO: Clean up this to return one or many
def searchfor(self, intable, returnfields, searchfor, sql='', returnrows='one'):
self.msg = '\n=========database searchfor()======'
self.msg += '\n'+str(searchfor)
try:
cursor = self.db.cursor()
fields = ','.join(returnfields)
search = ''
sp = ''
values = []
for key in searchfor:
search += sp+key+'=?'
values.append(searchfor[key])
sp = ' AND '
qry = 'SELECT {0} FROM {1} WHERE {2}'.format(fields, intable, search)
qry += ' '+sql
# Make thu query human readable for debugging
self.msg += '\n'+qry
cursor.execute(qry, (values) )
if returnrows == 'one':
row = cursor.fetchone()
return row
else:
rows = []
for row in cursor:
rows.append(row)
return rows
except Exception as e:
self.msg += '\n'+str(e)
return False
# Example showing how to to use this class
# Used for unit tests
if __name__ == "__main__":
# Setup elements for example
import random, time
from collections import OrderedDict
# Our database structure as an ordered list
dbstruct = OrderedDict([
('nodes', [
('nid', 'INTEGER PRIMARY KEY'),
('apikey', 'TEXT unique'),
('created', 'INTEGER'),
('createdhuman', 'DATETIME DEFAULT CURRENT_TIMESTAMP'),
('updated', 'INTEGER'),
('title', 'TEXT'),
('csvfile','TEXT'),
('description', 'TEXT'),
('datatype','TEXT'),
('lat','REAL'),
('lon','REAL'),
('fuzzylatlon', 'TEXT'),
('tags','TEXT'),
('createdby','INTEGER'),
('submissiondata','JSON'),
('latest','JSON'),
('visible','INTEGER'),
]),
# This isn't created in the database, its just used for internal var storage so order doen't matter
('locals',{
'path':[],
'postedbody':'',
'filestosave':[],
'submitted':{},
'errors':{},
'success':{},
'altresponse':''
})
])
# Initialise the database
db = Database("data/db.sqlite3", dbstruct, ignore='locals')
# BUILD A NEW DATABASE
db.build()
# CREATE LIST OF NODES TO INSERT
newnodes = OrderedDict([
('fieldnames',[]),
('values',[])
])
# Generate the fieldnames
for fieldname,v in dbstruct['nodes']:
if fieldname != 'nid' and fieldname != 'createdhuman':
newnodes['fieldnames'].append(fieldname)
# And the node values
nodes = 1
nodecnt = nodes
while nodes >= 1:
newVals = []
for i,v in dbstruct['nodes']:
if i != 'nid' and i != 'createdhuman':
if v == 'TEXT unique': val = i+str(random.randint(1,5000000000))
if v == 'TEXT': val = i+str(random.randint(1,50000))
if v == 'INTEGER': val = random.randint(1,50000)
# 51.47501,-0.03608
if v == 'REAL': val = float("{0:.5f}".format(random.uniform(51.47000, 51.48000)))
if i == 'created': val = int(time.time())
if i == 'datatype': val = "speck"
if i == 'latest': val = json.dumps({"raw":random.randint(1,500), "concentration":random.randint(1,50000), "humidity":random.randint(1,50000) })
if i == 'lat': val = float("{0:.5f}".format(random.uniform(51.44000, 51.49000)))
if i == 'lon': val = float("{0:.5f}".format(random.uniform(-0.03000, -0.09999)))
newVals.append(val)
newnodes['values'].append(newVals)
nodes += -1
# Now create a nice new bunch of nodes
nids = db.create('nodes', newnodes)
# VIEW ALL NODES IN THE DATBASE
fields = ['nid', 'created', 'createdhuman', 'updated', 'title', 'datatype', 'lat', 'lon', 'fuzzylatlon', 'latest']
jsonstr = db.readasjson('nodes', fields)
if jsonstr: print('ALL NODES: json response:\n'+jsonstr)
# VIEW A SINGLE NODE
jsonstr = db.readasjson('nodes', fields, [1])
if jsonstr: print('SINGLE NODES: json response:\n'+jsonstr)
# SEARCH FOR A VALUE AND SEE IF IT EXISTS. Return a row of fields if its exists
searchfor = {'nid':2, 'datatype':'speck'}
intable = 'nodes'
returnfields = ['nid', 'createdby']
row = db.searchfor(intable, returnfields, searchfor)
# SEARCH FOR ANOTHER VALUE AND SEE IF IT EXISTS. Return a row of fields if its exists
searchfor = {'nid':2, 'datatype':'bob'}
intable = 'nodes'
returnfields = ['nid', 'createdby']
row = db.searchfor(intable, returnfields, searchfor)
# UPDATE NODE WHERE
table = 'nodes'
idname = 'nid'
idval= 1
fieldnvalues = {'title':'Changed!!', 'apikey':'changed'}
db.update(table, idname, idval, fieldnvalues)