-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimple_db_client.py
More file actions
350 lines (326 loc) · 13.1 KB
/
Copy pathsimple_db_client.py
File metadata and controls
350 lines (326 loc) · 13.1 KB
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
#
################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2025 Curt Timmerman
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
################################################################################
#
## SimpleDBClient
#
# Notes:
# o get_date_time,get_date,get_time functions return local time, not the
# server local time.
#
################################################################################
import time
import requests
import json
## This function determines how the json RPC request is sent
# The RPC reply is returned as a dict or None on error
# This code should be in a module
REQUEST_URL = None
def send_request (rpc_dict) :
response = None
try :
response = requests.post (REQUEST_URL ,
json = rpc_dict ,
headers = {'Content-Type': 'application/json'})
#print ("send_rpc: reply:",response.json())
return response.json ()
except Exception as e :
print ("requests.post:", e)
finally :
if response is not None :
response.close ()
## report error here
return None
DATE_FORMAT = "{:04d}-{:02d}-{:02d}"
TIME_FORMAT = "{:02d}:{:02d}:{:02d}"
class SimpleDBClient :
def __init__ (self,
hostname = "localhost",
port = 8080,
use_local_date_time = True) :
global REQUEST_URL
if not use_local_date_time :
self.get_date_time = self.get_date_time_server
self.get_date = self.get_date_server
self.get_time = self.get_time_server
self.id = 0
self.url = "http://" + hostname + ":" + str (port)
REQUEST_URL = self.url
self.post_headers = {'Content-Type': 'application/json'}
## Get server configuration
def get_configuration (self) :
request_dict = {} # No parameters for now
server_config = self.send_rpc_request ("get_configuration", request_dict)
#
if "key_separator" in server_config :
self.key_separator = server_config ["key_separator"]
if "dump_separator" in server_config :
self.dump_separator = server_config ["dump_separator"]
#
if "simpledb_available" in server_config :
return server_config ["simpledb_available"]
return True # Assume the best
## writes/rewrites table row from row_data
def write_row (self,table_name,pk_id,row_data) :
#print ("w_r:", table_name,pk)
request_dict = {
"table_name" : table_name ,
"pk_id" : pk_id ,
"row_data" : row_data
}
return self.send_rpc_request ("write_row", request_dict)
## rewrites updated table row from update_data
def rewrite_row (self,table_name,key,update_data) :
#print ("w_r:", table_name,pk)
request_dict = {
"table_name" : table_name ,
"key" : key ,
"update_data" : update_data
}
return self.send_rpc_request ("rewrite_row", request_dict)
## read row from table/key, returns None if not found
def read_row (self,table_name,key) :
request_dict = {
"table_name" : table_name ,
"key" : key
}
return self.send_rpc_request ("read_row", request_dict)
## read row column from table/key, returns None if not found
def read_columns (self,table_name,key,column_list) :
request_dict = {
"table_name" : table_name ,
"key" : key ,
"column_list" : column_list
}
return self.send_rpc_request ("read_columns", request_dict)
## read next table indexed row, or first row if key is not provided
def first_row (self,table_name,key = "") :
request_dict = {
"table_name" : table_name ,
"key" : key
}
reply = self.send_rpc_request ("first_row", request_dict)
return (reply)
## read next table indexed row, or first row if key is not provided
def next_row (self,table_name,key = "") :
request_dict = {
"table_name" : table_name ,
"key" : key
}
reply = self.send_rpc_request ("next_row", request_dict)
return (reply)
## Return True if this key is in table_name
def row_exists (self,table_name,key) :
request_dict = {
"table_name" : table_name ,
"key" : key
}
return self.send_rpc_request ("row_exists", request_dict)
## Delete row from table
def delete_row (self,table_name,key) :
request_dict = {
"table_name" : table_name ,
"key" : key
}
return self.send_rpc_request ("delete_row", request_dict)
## Returns list of keys in table
# Not too useful except for testing
def get_table_keys (self,table_name,start_key=None,end_key=None,limit=999999) :
request_dict = {
"table_name" : table_name ,
"start_key" : start_key ,
"end_key" : end_key ,
"limit" : limit
}
return self.send_rpc_request ("get_table_keys", request_dict)
## Returns list of rows in a table
def get_table_rows (self,table_name,start_key=None,end_key=None,limit=999999) :
request_dict = {
"table_name" : table_name ,
"start_key" : start_key ,
"end_key" : end_key ,
"limit" : limit
}
return self.send_rpc_request ("get_table_rows", request_dict)
## Returns list of keys/rows from a table
def get_table_items (self,table_name,start_key=None,end_key=None,limit=999999) :
request_dict = {
"table_name" : table_name ,
"start_key" : start_key ,
"end_key" : end_key ,
"limit" : limit
}
return self.send_rpc_request ("get_table_items", request_dict)
## dump_all
def dump_all (self, file_path = "db_dump.txt") :
request_dict = {
"file_path" : file_path
}
return self.send_rpc_request ("dump_all", request_dict)
## load
def load (self, file_path = "db_dump.txt") :
request_dict = {
"file_path" : file_path
}
return self.send_rpc_request ("load", request_dict)
## commit updates(s), if autocommit is not set
def commit (self) :
request_dict = {}
return self.send_rpc_request ("commit", request_dict)
def close (self) :
pass
## Utilities
def get_date_time_server (self, epoch_seconds = None) :
request_dict = {
"epoch_seconds" : epoch_seconds
}
return self.send_rpc_request ("get_date_time", request_dict)
def get_date_server (self, epoch_seconds = None) :
request_dict = {
"epoch_seconds" : epoch_seconds
}
return self.send_rpc_request ("get_date", request_dict)
def get_time_server (self, epoch_seconds = None) :
request_dict = {
"epoch_seconds" : epoch_seconds
}
return self.send_rpc_request ("get_time", request_dict)
## Utilities
def get_date_time (self, epoch_seconds = None) :
seconds = epoch_seconds
if seconds is None :
seconds = time.time ()
local_time = time.localtime (seconds)
return self.get_date (seconds) + " " + self.get_time (seconds)
def get_date (self, epoch_seconds = None) :
seconds = epoch_seconds
if seconds is None :
seconds = time.time ()
local_time = time.localtime (seconds)
return DATE_FORMAT.format (local_time[0],local_time[1],local_time[2])
def get_time (self, epoch_seconds = None) :
seconds = epoch_seconds
if seconds is None :
seconds = time.time ()
local_time = time.localtime (seconds)
return TIME_FORMAT.format (local_time[3],local_time[4],local_time[5])
def send_rpc_request (self, method, params) :
self.id += 1
rpc_dict = {
"jsonrpc" : "2.0" ,
"method" : method ,
"params" : params ,
"id" : str (self.id)
}
## Send request to server
reply = send_request (rpc_dict)
if reply is not None :
if "result" in reply :
return reply ["result"]
elif "error" in reply :
pass # Do something here?
return None
# end SimpleDBClient #
def main () :
import os
#print (os.uname())
my_db = SimpleDBClient ("127.0.0.1", 8080, use_local_date_time=True)
#
print (my_db.get_configuration ())
print ("date_time:", my_db.get_date_time ())
print ("date:", my_db.get_date ())
print ("time:", my_db.get_time ())
print ("date_time (server):", my_db.get_date_time_server ())
print ("date (server):", my_db.get_date_server ())
print ("time (server):", my_db.get_time_server ())
my_db.write_row ("customer", "customer_number" , {"customer_number" : "000100" ,
"name":"Curt" ,
"dob":19560606 ,
"occupation":"retired"})
print ("rewrite:" ,
my_db.rewrite_row ("customer", "000100" , {"location" : "Alaska"}))
print ("read_columns:" ,
my_db.read_columns ("customer", "000100" , ["name","location","bad_id"]))
my_db.write_row ("customer", "customer_number", {"customer_number" : "000500" ,
"name":"Moe" ,
"dob":19200101 ,
"occupation":"Three stooges"})
my_db.write_row ("customer", "customer_number", {"customer_number" : "010000" ,
"name":"Larry" ,
"dob":19210202 ,
"occupation":"Three stooges"})
my_db.write_row ("customer", "customer_number", {"customer_number" : "001000" ,
"name":"Curly" ,
"dob":19250303 ,
"occupation":"Three stooges"})
my_db.write_row ("invoice",
"invoice_number" ,
{"invoice_number" : "090001" ,
"customer_number" : "001000"})
my_db.write_row ("invoice_line",
["invoice_number", "line_number"] ,
{"invoice_number" : "090001" ,
"line_number" : "0001" ,
"sku" : "Snake Oil" ,
"price" : "100.00"})
my_db.write_row ("invoice_line",
["invoice_number", "line_number"] ,
{"invoice_number" : "090001" ,
"line_number" : "0002" ,
"sku" : "Aspirin" ,
"price" : "12.00"})
my_db.write_row ("log",
0 ,
["20250903122010","Error","Log error"])
my_db.write_row ("log",
0 ,
["20250904141020","Warning", "Log warning"])
#
print ("good read:", my_db.read_row ("customer", "000100")) # Good key
print ("bad read:", my_db.read_row ("customer", "000199")) # bad key
print ("all keys:", my_db.get_table_keys ("customer"))
print ("rows:", my_db.get_table_rows ("customer", "000500", "990000"))
#
#my_db.get_table_items ("customer")
row = my_db.first_row ("customer")
while row is not None :
print ("row:", row)
row = my_db.next_row ("customer", row["customer_number"])
#
row = my_db.next_row ("log")
while row is not None :
print ("row:", row)
row = my_db.next_row ("log", row[0])
#
row = my_db.next_row ("error_table")
while row is not None :
print ("row:", row)
row = my_db.next_row ("log", row[0])
#
my_db.commit ()
my_db.dump_all ()
my_db.close ()
#----------------------------------------------------
if __name__ == "__main__" :
main ()