-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.py
476 lines (355 loc) · 14.5 KB
/
cli.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
from __future__ import print_function, unicode_literals
from PyInquirer import style_from_dict, Token, prompt, Separator
from music_library_db import *
import csv, terminaltables, functools
def make_style(color):
return style_from_dict({
Token.Separator: color,
Token.QuestionMark: '#673ab7 bold',
Token.Selected: color, # default
Token.Pointer: '#673ab7 bold',
Token.Instruction: '', # default
Token.Answer: '#f44336 bold',
Token.Question: '',
})
green_style = make_style('#008000')
red_style = make_style('#cc5454')
entities = DATABASE_DATA['entities']
operations = ["INSERT", "UPDATE", "DELETE", "SELECT", "QUIT"]
operation_choices = [{'name': operation} for operation in operations]
def make_question(type, message, name, choices):
return {'type': type,
'message': message,
'name': name,
'choices': choices}
def prompt_type(type, name, what_message, choices_names):
if len(choices_names) == 0:
raise KeyError("Empty menu")
answer = prompt([make_question(type, 'Select ' + what_message, name,
[{'name': choice_name} for choice_name in choices_names])])
return answer[name]
def prompt_list(name, what_message, choices_names):
return prompt_type('list', name, what_message, choices_names)
def prompt_entities():
return prompt_list('entity', 'an entity', [entity['name'] for entity in entities])
def get_entity_by_name(entity_name):
return next(entity for entity in entities if entity['name'] == entity_name)
def get_entity_attributes(entity_name):
return get_entity_by_name(entity_name)['attributes']
def get_names(attributes_data):
return [attribute['name'] for attribute in attributes_data]
def get_entity_attributes_names(entity_name):
return get_names(get_entity_attributes(entity_name))
def get_entity_text_attributes(entity_name):
return list(filter(lambda attr_data: attr_data['type'] == 'VARCHAR',
get_entity_attributes(entity_name)))
def get_entity_text_attributes_names(entity_name):
return get_names(get_entity_text_attributes(entity_name))
def prompt_attributes(entity_name):
return prompt_list('attribute', 'an attribute', get_entity_attributes_names(entity_name))
def prompt_text_attributes(entity_name):
return prompt_list('attribute', 'among text attributes', get_entity_text_attributes_names(entity_name))
def prompt_attributes_selection(entity_name):
return prompt_type('checkbox', 'attribute', 'the attribute(s)',
get_entity_attributes_names(entity_name))
csv_file = 'artists.csv'
json_file = 'music_library.json'
def capitalize_all_words(val):
return ' '.join([word.capitalize() for word in val.split()])
def validate_varchar(value): return len(value.split()) != 0
def validate_integer(value):
try:
int(value)
return True
except ValueError:
return False
def identity(x): return x
attribute_type_filters = {
'Artist': {
'Artist_Name': capitalize_all_words,
'Artist_Description': identity,
'Artist_Id': int
},
'Album': {
'Album_Name': capitalize_all_words,
'Album_Id': int,
'Artist_Id': int,
'Year': int
},
'Tag': {
'Tag_Name': capitalize_all_words,
'Tag_Description': identity,
'Tag_Id': int
},
'has': {
'Album_Id': int,
'Tag_Id': int
},
'Track': {
'Track_Name': capitalize_all_words,
'Track_Id': int,
'Rank': int,
'Duration': int,
'Album_Id': int
},
}
attribute_type_validators = {
'Artist': {
'Artist_Name': validate_varchar,
'Artist_Description': validate_varchar,
'Artist_Id': validate_integer
},
'Album': {
'Album_Name': validate_varchar,
'Album_Id': validate_integer,
'Artist_Id': validate_integer,
'Year': validate_integer
},
'Tag': {
'Tag_Name': validate_varchar,
'Tag_Description': validate_varchar,
'Tag_Id': validate_integer
},
'has': {
'Album_Id': validate_integer,
'Tag_Id': validate_integer
},
'Track': {
'Track_Name': validate_varchar,
'Track_Id': validate_integer,
'Rank': validate_integer,
'Duration': validate_integer,
'Album_Id': validate_integer
}
}
def make_input_for_attribute(entity_name, attribute_name):
return {
'type': 'input',
'name': attribute_name,
'message': 'Enter the ' + attribute_name,
'validate': attribute_type_validators[entity_name][attribute_name],
'filter': attribute_type_filters[entity_name][attribute_name]
}
def validate_single_word(string):
return len(string.split()) == 1
def make_input_for_attribute_single_word_key(entity_name, attribute_name):
return {
'type': 'input',
'name': attribute_name,
'message': 'Enter the ' + attribute_name,
'validate': attribute_type_validators[entity_name][attribute_name],
'filter': attribute_type_filters[entity_name][attribute_name]
}
def make_inputs_for_attributes(entity_name, attributes):
inputs = list(map(lambda attribute: make_input_for_attribute(entity_name, attribute['name']),
attributes))
return inputs
def shrink_cells(rows, length=27):
return [tuple(cell[:length]+'...' if isinstance(cell, str) and len(cell) > length
else cell
for cell in row)
for row in rows]
def print_table(entity_name, rows):
attribute_name = [tuple(i for i in get_entity_attributes_names(entity_name))]
## print(attribute_name)
rows = shrink_cells(rows)
table_wrapper = terminaltables.SingleTable(attribute_name + rows)
print(table_wrapper.table)
def print_join(entity1_name, entity2_name, rows):
attribute1_name = [i for i in get_entity_attributes_names(entity1_name)]
attribute2_name = [i for i in get_entity_attributes_names(entity2_name)]
attribute_name = [tuple(attribute1_name + attribute2_name)]
rows = shrink_cells(rows)
table_wrapper = terminaltables.SingleTable(attribute_name + rows)
print(table_wrapper.table)
def print_entity(db, entity_name):
rows = db.select_all(entity_name)
print_table(entity_name, rows)
def print_fetch_all(db):
print(db.fetch_all())
def prompt_input_attributes(entity_name):
entity_data = get_entity_by_name(entity_name)
return prompt(make_inputs_for_attributes(entity_name, entity_data['attributes']))
def perform_insert(db):
entity_name = prompt_entities()
print_entity(db, entity_name)
attributes_row = prompt_input_attributes(entity_name)
db.insert(into=entity_name, row=attributes_row)
print_entity(db, entity_name)
def perform_delete(db):
entity_name = prompt_entities()
db.delete_all(entity_name)
def make_inputs_for_range(attribute_name):
bounds = prompt([
{
'type': 'input',
'name': 'lower',
'message': 'Enter the lower bound of ' + attribute_name,
'filter': int,
'validate': validate_integer,
},
{
'type': 'input',
'name': 'upper',
'message': 'Enter the upper bound of ' + attribute_name,
'filter': int,
'validate': validate_integer,
}
])
return {attribute_name: bounds}
def make_inputs_for_str(attribute_name):
return prompt([
{
'type': 'input',
'name': attribute_name,
'message': 'Enter the ' + attribute_name,
'validate': validate_varchar,
}
])
search_key_input_makers = {
"INT": make_inputs_for_range,
"VARCHAR": make_inputs_for_str
}
def get_attribute_data(entity_name, attribute_name):
entity_data = get_entity_by_name(entity_name)
attribute_data = next(attribute
for attribute in entity_data['attributes']
if attribute['name'] == attribute_name)
return attribute_data
def prompt_attribute_search_key_input(entity_name, attribute_name):
attribute_data = get_attribute_data(entity_name, attribute_name)
attribute_type = attribute_data['type']
questions_maker = search_key_input_makers[attribute_type]
return questions_maker(attribute_name)
def perform_update(db):
entity_name = prompt_entities()
key_attributes = db.get_key(entity_name)
attributes = prompt_type('checkbox', 'attribute', 'the attribute(s) to update',
[i for i in get_entity_attributes_names(entity_name)])
if len(attributes) == 0:
raise KeyError("At least one attribute must have been selected to perform update")
# print(attributes)
key_attribute_prompt = [{
'type': 'input',
'name': key_attribute,
'message': 'Enter the ' + key_attribute + ' to specify the tuple',
'validate': attribute_type_validators[entity_name][key_attribute],
'filter': attribute_type_filters[entity_name][key_attribute]
} for key_attribute in key_attributes]
key_attribute_value = prompt(key_attribute_prompt)
# print(key_attribute_value)
attributes_keys_prompts = [make_input_for_attribute(entity_name, attribute_name)
for attribute_name in attributes]
attributes_row = prompt(attributes_keys_prompts)
# print(attributes_row)
db.update(entity_name, key_attribute_value, attributes_row)
print_entity(db, entity_name)
def make_fulltext_handler():
def get_search_data(db, prompter, searcher):
entity_name = prompt_entities()
# print(entity_name)
print_entity(db, entity_name)
attribute_name = prompt_text_attributes(entity_name)
key_questions = [prompter(entity_name, attribute_name)]
key = prompt(key_questions)[attribute_name]
search_args = {
'entity': entity_name,
'attribute': attribute_name,
'key': key
}
rows = searcher(db, search_args)
print_table(entity_name, rows)
def all_occur(db):
get_search_data(
db, make_input_for_attribute_single_word_key,
lambda db, search_args: db.fulltext_search_all_match(**search_args)
)
def one_doesnt(db):
get_search_data(
db, make_input_for_attribute,
lambda db, search_args: db.fulltext_search_one_not(**search_args)
)
modes = ("all words occur", "one word doesn't occur")
modes_handlers = {
"all words occur": all_occur,
"one word doesn't occur": one_doesnt
}
def do(db):
mode = prompt_list('modes', 'the search mode', modes)
handler = modes_handlers[mode]
handler(db)
return do
fulltext_handler = make_fulltext_handler()
def make_select_join_handler():
def do(db):
entity1_name = prompt_list('entity', 'the first entity', [entity['name'] for entity in entities])
joinable_entities = iter(join['pair'] for join in joins if entity1_name in join['pair'])
joinable_entities_flatten = functools.reduce(lambda t, s: list(t)+list(s),
joinable_entities)
entities_without_selected = [e for e in joinable_entities_flatten if e != entity1_name]
entity2_name = prompt_list('entity', 'the second entity', entities_without_selected)
join_attribute = next(join['id'] for join in joins
if join['pair'] == {entity1_name, entity2_name})
entity1_attributes_selected = prompt_type('checkbox', 'attribute',
'the ' + entity1_name + ' attribute(s) to search',
[i for i in get_entity_attributes_names(entity1_name)])
entity2_attributes_selected = prompt_type('checkbox', 'attribute',
'the ' + entity2_name + ' attribute(s) to search',
[i for i in get_entity_attributes_names(entity2_name)])
if len(entity1_attributes_selected+entity2_attributes_selected) == 0:
raise KeyError("At least one attribute must be selected to commit search")
entity1_attributes_values = [prompt_attribute_search_key_input(entity1_name, attr)
for attr in entity1_attributes_selected]
entity2_attributes_values = [prompt_attribute_search_key_input(entity2_name, attr)
for attr in entity2_attributes_selected]
# print(entity2_attributes_values, entity1_attributes_values)
rows = db.select_inner_join(entity1_name, entity2_name, join_attribute,
entity1_attributes_values, entity2_attributes_values)
print_join(entity1_name, entity2_name, rows)
return do
select_join_handler = make_select_join_handler()
def perform_select_mixin():
options = ["fulltext search", "join"]
handlers = {"fulltext search": fulltext_handler,
"join": select_join_handler}
def do(db):
option = prompt_list('option', 'the SELECT option', options)
handler = handlers[option]
return handler(db)
return do
perform_select = perform_select_mixin()
operations_performers = {
"INSERT": perform_insert,
"DELETE": perform_delete,
"UPDATE": perform_update,
"SELECT": perform_select
}
def prompt_main_menu(db):
operation_name = prompt_list('operation', 'the operation to perform', operations)
if operation_name == "QUIT":
return operation_name
performer = operations_performers[operation_name]
return performer(db)
def main(db):
try:
while prompt_main_menu(db) != "QUIT":
pass
except psycopg2.IntegrityError as error:
print(error.pgerror)
except KeyError as error:
print('ERROR: '+error.args[0])
if __name__ == '__main__':
connection_parameters = {
'user': 'postgres', 'host': 'localhost', 'password': 'py', 'database': 'music_library'
}
with MusicLibraryDatabase(**connection_parameters) as db_handle:
main(db_handle)
# entity_name = prompt_list('entity', 'an entity', [entity['name'] for entity in entities])
"""
{'type': 'list',
'message': 'Enter the attributes',
'name': 'entity',
'choices': entities_choices,
'validate': lambda answer: print(answer) or 'Sorry, try again' if len(answer) == 0 else True,
'when': lambda answer: (print(answer) and False) or answer['operation'] == "INSERT"}
"""