-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
611 lines (552 loc) · 22 KB
/
utils.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import json
import logging
import sqlite3
from pandas import DataFrame
from typing import Any, TypeAlias
from re import search
import typing
from numpy import iterable
from inspect import signature
from pydantic import BaseModel
from pydantic.dataclasses import dataclass
from .models import DefaultModel
from .connection import MentoConnection
Str: TypeAlias = str
Lambda: TypeAlias = "function"
class Column:
def __init__(
self, arg: str, is_primary: bool = False, unique_columns: list[str] = None
):
"""A statement to create and recognize columns."""
match = search("(\w+)\s?\:(.+)", str(arg))
self.has_unique_check = False
self.unique_args = None
if "UniqueMatch" in str(arg):
self.unique_args = search("UniqueMatch\[(.+)\]", str(arg))[1].split("-")
self.has_unique_check = bool(self.unique_args)
if match:
column, _type = match.groups()
if search("PrimaryKey", _type):
is_primary = True
_type = search(".+?~PrimaryKey-(.+)", _type)[1]
addition = "primary key" if is_primary else ""
if unique_columns and column.lower().strip() in unique_columns:
addition = "UNIQUE"
if _type.strip() in ("int", "float"):
self.arg = f"{column} int {addition}"
else:
self.arg = f"{column} text {addition}"
else:
self.arg = f"{self.alphanum(arg)} text"
self.arg = self.arg.lower()
def alphanum(self, arg: str):
data = [letter for letter in arg if letter.isalnum()]
return "".join(data)
class PrimaryKey:
def __new__(self, _type: type) -> typing.TypeVar:
"""A PrimaryKey statement to set columns as PrimaryKey"""
type_base: str = f"{PrimaryKey.__name__}-{_type.__name__}"
return typing.TypeVar(f"{type_base}", _type, bytes)
class UniqueMatch:
def __new__(self, *args: typing.Iterable) -> typing.TypeVar:
"""A matching tool to set one or many columns as unique. (Multiple Primary Key)"""
args: typing.List[str]
arg_text = "-".join([str(arg) for arg in args])
type_base: str = f"{UniqueMatch.__name__}[{arg_text}]"
return typing.TypeVar(f"{type_base}", str, str)
class Sequence:
def __new__(self, seperators: str = ","):
type_base = f"{Sequence.__name__}[seperators='{seperators}']"
return typing.TypeVar(f"{type_base}", str, bytes)
class JsonString:
def __new__(self):
type_base = f"{JsonString.__name__}"
return typing.TypeVar(f"{type_base}", str, bytes)
class Fetch:
def __init__(self, cursor: "sqlite3.Cursor", table: str = None):
"""A fetcher can fetch datas from specified sqlite cursor."""
self.cursor = cursor
if table:
query = cursor.execute(f"SELECT * FROM {table} WHERE 0")
self.columns = list(map(lambda x: x[0], query.description))
else:
self.columns = list(map(lambda x: x[0], self.cursor.description))
def first(self, reverse: bool = False):
if reverse:
data = self.cursor.fetchall()
if data:
return data[-1]
return self.format(data)
else:
data = self.cursor.fetchone()
if not data:
return None
return self.format(data)
def all(self):
data = self.cursor.fetchall()
return self.format(data)
def format(self, values: list[tuple]) -> list[dict]:
multiple = (
True
if iterable(values)
and len(values) > 0
and iterable(values[0])
and not type(values[0]) == str
else False
)
if (
iterable(values)
and len(values) > 0
and not iterable(values[0])
and not len(self.columns) == len(values)
):
raise Exception(
"You have to give a value list has size same with column size."
)
else:
if multiple:
results = list()
for fetch_data in values:
response = dict()
for index, value in enumerate(fetch_data):
response[self.columns[index]] = value
results.append(response)
return results
else:
response = dict()
for index, value in enumerate(values):
response[self.columns[index]] = value
return response
class MentoExceptions:
def __init__(self, logging: bool = True):
self.logging = logging
self.wrong_data_model = lambda: self.auto(
"Given model and data (list[dict]) not matched with together.\nPlease check your data and model then try again."
)
def auto(self, message: str) -> "None | BaseException":
if self.logging:
logging.error(message)
else:
raise BaseException(message)
@dataclass
class AutoResponse:
def __init__(self, model: BaseModel = None, datas: list[dict] = None):
"""A recognizer can convert inputs to specified data model."""
self.status: bool = False
if model and datas:
self.model: type = model
self.datas: list[dict] = datas
self.status = (
True
if iterable(datas)
and type(datas) == list
and datas
and type(datas[0]) == dict
and datas[0]
else False
)
self.err = MentoExceptions()
if not self.status:
self.err.wrong_data_model()
self.sign: dict = self.model.__pydantic_model__.schema()
self.properties: dict = self.sign.get("properties")
self.attrs: list = sorted(list(self.properties.keys()))
self.keys: list = sorted(list(datas[0].keys()))
def get_response(self) -> list[object]:
self.models: list[self.model] = list()
if not self.status:
self.err.auto(
"Your data was wrong thats why i cant return any data response."
)
for i, data in enumerate(self.datas):
data_keys = sorted(list(data.keys()))
if not data_keys == self.attrs:
self.err.auto(
f"The dict with id {i + 1} is incorrect. Please give just ``same type`` data dicts."
)
else:
x = self.__class__()
for k, v in data.items():
if not str(k)[0].isalpha():
k = str(f"attr{k}")
setattr(x, k, v)
self.models.append(x)
return self.models
class Static:
def __init__(
self,
datas: list[dict],
model: BaseModel = None,
as_model: bool = False,
as_json: bool = False,
as_dataframe: bool = False,
) -> None:
"""A data formatting tool that converts data into desired type of output."""
self.datas = datas
self.basemodel = model
self.as_model = as_model
self.as_json = as_json
self.as_dataframe = as_dataframe
self.data = self.set()
def set(self, value: Any = None):
if self.as_model:
return self.model()
elif self.as_json:
return self.json()
elif self.as_dataframe:
return self.dataframe()
return self.datas
def model(self):
response = AutoResponse(model=self.basemodel, datas=self.datas)
return response.get_response()
def json(self):
return json.dumps(self.datas)
def dataframe(self, data_dict: dict = dict()):
if not self.datas:
return
for k in self.datas[0].keys():
data_dict[k] = [data.get(k) for data in self.datas]
if not data_dict:
return
return DataFrame(data_dict)
class Mento:
def __init__(
self,
connection: "MentoConnection" = None,
default_table: str = None,
check_model: BaseModel = None,
error_logging: bool = False,
):
"""MentoDB is powerful database engine for sqlite3. You have many options to use, specially basic things, also lambda filters, regular expressions included."""
self.connection: "MentoConnection" = connection
self.default_table: str = default_table
self.check_model: BaseModel = check_model
self.exceptions = MentoExceptions(error_logging)
def create(
self,
table: str = None,
model: BaseModel = DefaultModel,
exists_check: bool = True,
unique_columns: list = [],
):
"""Create a table with your BaseModel."""
if not table:
table = self.default_table
if not model:
model = self.check_model
parameters = list(signature(model).parameters.values())
columns = list()
for param in parameters:
column = Column(str(param), unique_columns=unique_columns)
if not column.has_unique_check:
columns.append(column.arg)
create_query = ", ".join(columns)
if exists_check:
self.connection.execute(
f"CREATE TABLE IF NOT EXISTS {table} ({create_query})"
)
else:
try:
self.connection.execute(f"CREATE TABLE {table} ({create_query})")
except:
self.drop(table)
self.create(table, model, exists_check)
def create_many(
self, datas: dict = dict(user=DefaultModel), exists_check: bool = True
):
"""Create many table with BaseModels."""
tables = list(datas.keys())
models = list(datas.values())
for i, table in enumerate(tables):
self.create(table=table, model=models[i], exists_check=exists_check)
def drop(self, table: str = None):
"""Drop table you want."""
if not table:
table = self.default_table
self.create(table, model=DefaultModel)
self.connection.execute(f"DROP TABLE {table}")
def insert(
self, table: str = None, data: dict = dict(), check_model: BaseModel = None
):
"""Insert data to current table."""
if not table:
table = self.default_table
if not check_model:
check_model = self.check_model
if check_model:
conditions = []
unique_args = []
sign = signature(check_model)
for param in sign.parameters.values():
param_check = Column(param)
if param_check.has_unique_check:
unique_args = param_check.unique_args
for arg in unique_args:
fetch = Fetch(self.connection.cursor(), table=table)
if arg not in fetch.columns:
raise BaseException("Args are not same with your table.")
value = (
f"{arg} = {data[arg]}"
if type(data[arg]) in (int, float)
else f"{arg} = '{data[arg]}'"
)
conditions.append(value)
where_query = " and ".join(conditions)
if conditions:
cursor = self.connection.execute(
f"SELECT * FROM {table} where {where_query}"
)
fetch = Fetch(cursor)
first_data = fetch.first()
if first_data:
return first_data
query = ""
index = 0
for k, v in data.items():
if not type(v) == int:
query += f"'{v}'{',' if index+1 < len(data.items()) else ''}"
else:
query += f"{v}{',' if index+1 < len(data.items()) else ''}"
index += 1
try:
self.connection.execute(f"INSERT INTO {table} VALUES ({query})")
except sqlite3.IntegrityError as e:
logging.error("This content already posted.")
def update(
self,
table: str = None,
data: dict = None,
where: dict = None,
update_all: bool = False,
):
"""Update matched or all columns."""
if not table:
table = self.default_table
if not update_all and not where:
raise BaseException("Unexpected request. Please check your inputs.")
if where:
conditions = list()
fetch = Fetch(self.connection.cursor(), table=table)
for key, value in where.items():
if key not in fetch.columns:
raise BaseException(f"Your table has no column named `{key}`")
if type(value) == int:
value = value
else:
value = f"'{value}'"
conditions.append(f"{key} = {value}")
if len(conditions) == 1:
where_statement = conditions[0]
else:
where_statement = " and ".join(conditions).strip()
if not table:
table = self.default_table
queries = list()
for k, v in data.items():
if not type(v) == int:
v = f"'{v}'"
queries.append(f"{k}={v}")
update_query = ", ".join(queries)
if update_all:
self.connection.execute(f"UPDATE {table} SET {update_query}")
else:
data = self.connection.execute(
f"UPDATE {table} SET {update_query} where {'' if not where_statement else where_statement}"
)
def select(
self,
from_table: str = None,
model: BaseModel = None,
where: dict = None,
order_by: Column = None,
limit: int = 0,
filter: Lambda = None,
regexp: dict[str, str | list[str]] = None,
select_all: bool = True,
select_column: str = None,
as_model: bool = False,
as_dataframe: bool = False,
as_json: bool = False,
):
"""Select matched or all columns as lists include Python dict or custom formats (Detailed in Tests)."""
config = dict(
model=model, as_model=as_model, as_json=as_json, as_dataframe=as_dataframe
)
if as_model and not model:
raise self.exceptions.auto(
"If you want to get models you have to specify data model."
)
additions = ""
if not from_table:
from_table = self.default_table
if order_by:
additions += f"ORDER BY {order_by}"
if limit > 0:
additions += f" LIMIT {limit}"
if where:
conditions = list()
fetch = Fetch(self.connection.cursor(), table=from_table)
for key, value in where.items():
if key not in fetch.columns:
raise self.exceptions.auto(
f"Your table has no column named `{key}`"
)
if type(value) in (int, float):
value = value
else:
value = f"'{value}'"
conditions.append(f"{key} = {value}")
where_statement = " and ".join(conditions).strip()
cursor = self.connection.execute(
f"SELECT {'*' if select_all and not select_column else select_column} FROM {from_table} where {where_statement} {additions} "
)
fetch = Fetch(cursor)
if select_all:
response = Static(fetch.all(), **config)
return response.data
response = Static(fetch.first(), **config)
return response.data
if not regexp and not filter:
query = self.connection.execute(
f"SELECT {'*' if select_all and not select_column else select_column} FROM {from_table} {additions}"
)
fetch = Fetch(query)
response = Static(fetch.all(), **config)
return response.data
else:
if filter:
if not callable(filter):
raise self.exceptions.auto(
"Filter must be lambda with one argument, also this filter is not callable."
)
else:
query = self.connection.execute(
f"SELECT * FROM {from_table} {additions}"
)
fetch = Fetch(query)
datas = fetch.all()
matches = list()
for data in datas:
filter_args = filter.__code__.co_varnames
data_index = (
filter_args[0]
if iterable(filter_args) and len(filter_args) > 0
else -1
)
if data_index == -1:
raise self.exceptions.auto(
"No argument supplied to filter. Please, specifiy column name as argument."
)
else:
if filter(data[data_index]):
matches.append(data)
response = Static(matches, **config)
return response.data
elif regexp:
query = self.connection.execute(
f"SELECT * FROM {from_table} {additions}"
)
fetch = Fetch(query)
datas = fetch.all()
column = str(list(regexp.keys())[0]).lower()
matches = list()
if iterable(datas) and type(datas) == list:
for data in datas:
if iterable(regexp[column]):
for regex in regexp[column]:
if column not in fetch.columns:
raise BaseException(
f"Current table has no column named `{column}`."
)
has_match = self.regexp(
regex,
str(
data[fetch.columns[fetch.columns.index(column)]]
),
)
if has_match:
matches.append(data)
response = Static(matches, **config)
return response.data
else:
if iterable(regexp[column]):
for regex in regexp[column]:
data = datas[fetch.columns[fetch.columns.index(column)]]
has_match = self.regexp(regex, str(data))
if has_match:
matches.append(data)
response = Static(matches, **config)
return response.data
if select_all:
fetch = Fetch(f"SELECT * FROM {from_table}")
response = Static(matches, **config)
return response.data
def delete(self, table: str, where: dict = dict(), delete_all: bool = False):
"""Delete matched or all columns."""
if delete_all:
self.connection.execute(f"DELETE FROM {table}")
else:
if where:
conditions = list()
fetch = Fetch(self.connection.cursor(), table=table)
for key, value in where.items():
if key not in fetch.columns:
raise BaseException(f"Your table has no column named `{key}`")
if type(value) in (int, float):
value = value
else:
value = f"'{value}'"
conditions.append(f"{key} = {value}")
where_statement = " and ".join(conditions).strip()
self.connection.execute(f"DELETE FROM {table} where {where_statement}")
else:
raise BaseException(
"Please add where statement or set delete_all as true to delete all rows."
)
def regexp(self, pattern: str, string: str | bytes) -> bool:
"""If pattern has a match with given string, returns True, else return False."""
match = search(pattern, str(string))
return bool(match)
@dataclass
class AutoResponse:
def __init__(self, model=None, datas: list[dict] = None):
self.status: bool = False
self.err = MentoExceptions()
if model and datas:
self.model: type = model
self.datas: list[dict] = datas
self.status = (
True
if iterable(datas)
and type(datas) == list
and datas
and type(datas[0]) == dict
and datas[0]
else False
)
if not self.status:
self.err.wrong_data_model()
self.sign: dict = self.model.__pydantic_model__.schema()
self.properties: dict = self.sign.get("properties")
self.attrs: list = sorted(list(self.properties.keys()))
self.keys: list = sorted(list(datas[0].keys()))
def get_response(self) -> list[object]:
self.models: list[self.model] = list()
if not self.status:
self.err.auto(
"Your data was wrong thats why i cant return any data response."
)
for i, data in enumerate(self.datas):
data_keys = sorted(list(data.keys()))
if not data_keys == self.attrs:
self.err.auto(
f"The dict with id {i + 1} is incorrect. Please give just ``same type`` data dicts."
)
else:
x = self.__class__()
for k, v in data.items():
if str(k[0]).isdigit():
k = str(f"w{k}")
setattr(x, k, v)
self.models.append(x)
return self.models