odbms 0.3.2__tar.gz → 0.3.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {odbms-0.3.2/odbms.egg-info → odbms-0.3.3}/PKG-INFO +1 -1
- {odbms-0.3.2 → odbms-0.3.3}/odbms/app.py +1 -1
- odbms-0.3.3/odbms/field.py +44 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms/model.py +67 -17
- {odbms-0.3.2 → odbms-0.3.3}/odbms/orms/mongodb.py +2 -1
- {odbms-0.3.2 → odbms-0.3.3}/odbms/orms/mysqldb.py +5 -2
- {odbms-0.3.2 → odbms-0.3.3}/odbms/orms/postgresqldb.py +11 -4
- {odbms-0.3.2 → odbms-0.3.3}/odbms/orms/sqlitedb.py +4 -2
- odbms-0.3.3/odbms/validators.py +13 -0
- {odbms-0.3.2 → odbms-0.3.3/odbms.egg-info}/PKG-INFO +1 -1
- {odbms-0.3.2 → odbms-0.3.3}/odbms.egg-info/SOURCES.txt +2 -0
- {odbms-0.3.2 → odbms-0.3.3}/setup.py +1 -1
- {odbms-0.3.2 → odbms-0.3.3}/LICENSE +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/MANIFEST.in +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/README.md +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms/__init__.py +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms/database.py +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms/dbms.py +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms/orms/__init__.py +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms/orms/base.py +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms.egg-info/dependency_links.txt +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms.egg-info/requires.txt +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/odbms.egg-info/top_level.txt +0 -0
- {odbms-0.3.2 → odbms-0.3.3}/setup.cfg +0 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from typing import List, Dict, Tuple, Optional, Any, Callable, Union
|
|
2
|
+
from validators import validate_email
|
|
3
|
+
|
|
4
|
+
class Field(type):
|
|
5
|
+
def __init__(self, value: Optional[str] = None, is_unique: bool = False, validators: List[Callable] = []) -> None:
|
|
6
|
+
if value is not None:
|
|
7
|
+
self.value = value
|
|
8
|
+
else:
|
|
9
|
+
self.value = ''
|
|
10
|
+
self.is_unique = is_unique
|
|
11
|
+
self.validators = validators
|
|
12
|
+
|
|
13
|
+
def validate(self):
|
|
14
|
+
for validator in self.validators:
|
|
15
|
+
validator(self.value)
|
|
16
|
+
|
|
17
|
+
def __instancecheck__(self, instance):
|
|
18
|
+
return hasattr(instance, 'value') and hasattr(instance, 'is_unique') and hasattr(instance, 'validators')
|
|
19
|
+
|
|
20
|
+
def __new__(cls, value=None):
|
|
21
|
+
if isinstance(value, str):
|
|
22
|
+
return cls(value)
|
|
23
|
+
else:
|
|
24
|
+
return value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Email(Field):
|
|
28
|
+
def __init__(self, value: Optional[str] = None, is_unique: bool = False, validators: List[Callable] = []) -> None:
|
|
29
|
+
super().__init__(value, is_unique, validators)
|
|
30
|
+
self.is_unique = is_unique
|
|
31
|
+
self.validators = validators
|
|
32
|
+
self.validators.insert(0, validate_email)
|
|
33
|
+
self.validate()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class User:
|
|
37
|
+
def __init__(self, name: Field, email: Email, password: str) -> None:
|
|
38
|
+
self.name = name
|
|
39
|
+
self.email = email
|
|
40
|
+
self.password = password
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
new_user = User('Amos Amissah', 'theonlyamos', 'password')
|
|
44
|
+
print(type(new_user.email))
|
|
@@ -8,10 +8,10 @@ from .dbms import DBMS
|
|
|
8
8
|
|
|
9
9
|
class Model():
|
|
10
10
|
'''A model class'''
|
|
11
|
-
TABLE_NAME = ''
|
|
11
|
+
TABLE_NAME: str = ''
|
|
12
12
|
SELECTED_COLUMNS = []
|
|
13
13
|
WHERE_CLAUSE = []
|
|
14
|
-
GROUP_BY = ''
|
|
14
|
+
GROUP_BY: str = ''
|
|
15
15
|
ORDER_BY = ()
|
|
16
16
|
LIMIT = 0
|
|
17
17
|
|
|
@@ -109,6 +109,52 @@ class Model():
|
|
|
109
109
|
}
|
|
110
110
|
return type_mapping.get(attr_type, "TEXT")
|
|
111
111
|
|
|
112
|
+
@classmethod
|
|
113
|
+
def alter_table(cls, changes: dict):
|
|
114
|
+
"""
|
|
115
|
+
Alter the table structure by adding, modifying, or dropping columns.
|
|
116
|
+
|
|
117
|
+
@param changes: A dictionary mapping column names to their new data types.
|
|
118
|
+
"""
|
|
119
|
+
if DBMS.Database.dbms != 'mongodb':
|
|
120
|
+
# Fetch existing columns from the database
|
|
121
|
+
fetch_columns_sql = f"SELECT column_name FROM information_schema.columns WHERE table_name='{cls.TABLE_NAME}';"
|
|
122
|
+
existing_columns = {row['column_name'] for row in DBMS.Database.execute(fetch_columns_sql)}
|
|
123
|
+
default_columns = {'id', 'created_at', 'updated_at'}
|
|
124
|
+
# Determine columns to add or modify and columns to drop
|
|
125
|
+
specified_columns = set(changes.keys())
|
|
126
|
+
specified_columns.update(default_columns)
|
|
127
|
+
columns_to_drop = existing_columns - specified_columns
|
|
128
|
+
columns_to_add_or_modify = specified_columns - existing_columns
|
|
129
|
+
|
|
130
|
+
alter_statements = []
|
|
131
|
+
|
|
132
|
+
# Handle adding or modifying columns
|
|
133
|
+
for column, data_type in changes.items():
|
|
134
|
+
column_type = cls.get_column_type(data_type)
|
|
135
|
+
if column in columns_to_add_or_modify:
|
|
136
|
+
alter_statements.append(f"ADD COLUMN {column} {column_type}")
|
|
137
|
+
else:
|
|
138
|
+
# Modify existing column
|
|
139
|
+
if DBMS.Database.dbms in ['mysql', 'postgresql']:
|
|
140
|
+
alter_statements.append(f"ALTER COLUMN {column} TYPE {column_type}")
|
|
141
|
+
elif DBMS.Database.dbms == 'sqlite':
|
|
142
|
+
# SQLite does not support MODIFY COLUMN directly, needs table recreation
|
|
143
|
+
continue # Handle SQLite modifications separately if needed
|
|
144
|
+
|
|
145
|
+
# Handle dropping columns
|
|
146
|
+
for column in columns_to_drop:
|
|
147
|
+
if DBMS.Database.dbms in ['mysql', 'postgresql']:
|
|
148
|
+
alter_statements.append(f"DROP COLUMN {column}")
|
|
149
|
+
elif DBMS.Database.dbms == 'sqlite':
|
|
150
|
+
# SQLite does not support DROP COLUMN directly, needs table recreation
|
|
151
|
+
continue # Handle SQLite drops separately if needed
|
|
152
|
+
|
|
153
|
+
# Execute all alter statements
|
|
154
|
+
for statement in alter_statements:
|
|
155
|
+
alter_sql = f"ALTER TABLE {cls.TABLE_NAME} {statement};"
|
|
156
|
+
DBMS.Database.execute(alter_sql)
|
|
157
|
+
|
|
112
158
|
def save(self):
|
|
113
159
|
'''
|
|
114
160
|
Instance Method for saving Model instance to database
|
|
@@ -123,9 +169,9 @@ class Model():
|
|
|
123
169
|
data['updated_at'] = (datetime.now()).strftime("%a %b %d %Y %H:%M:%S")
|
|
124
170
|
del data["created_at"]
|
|
125
171
|
del data["updated_at"]
|
|
126
|
-
|
|
172
|
+
|
|
127
173
|
if isinstance(self.id, ObjectId):
|
|
128
|
-
return DBMS.Database.insert(self.TABLE_NAME,
|
|
174
|
+
return DBMS.Database.insert(self.TABLE_NAME, self.normalise(data, 'params'))
|
|
129
175
|
|
|
130
176
|
# Update the existing record in database
|
|
131
177
|
data.pop('id', None)
|
|
@@ -235,12 +281,10 @@ class Model():
|
|
|
235
281
|
@return Model instance(s)
|
|
236
282
|
'''
|
|
237
283
|
|
|
238
|
-
result = DBMS.Database.find_one(cls.TABLE_NAME, cls.normalise({'id': id}, 'params'))
|
|
239
|
-
|
|
240
|
-
if
|
|
241
|
-
|
|
242
|
-
elif isinstance(result, list) or isinstance(result, tuple):
|
|
243
|
-
return cls(*result) if len(result) else None
|
|
284
|
+
result = cls.normalise(DBMS.Database.find_one(cls.TABLE_NAME, cls.normalise({'id': id}, 'params'))) # type: ignore
|
|
285
|
+
|
|
286
|
+
return cls(**result) if len(result.keys()) else None
|
|
287
|
+
|
|
244
288
|
|
|
245
289
|
# query = 'SELECT '
|
|
246
290
|
# if cls.SELECTED_COLUMNS:
|
|
@@ -328,7 +372,7 @@ class Model():
|
|
|
328
372
|
@return List[Model]
|
|
329
373
|
'''
|
|
330
374
|
|
|
331
|
-
result = cls.normalise(DBMS.Database.find_one(cls.TABLE_NAME, cls.normalise(params, 'params'), projection))
|
|
375
|
+
result = cls.normalise(DBMS.Database.find_one(cls.TABLE_NAME, cls.normalise(params, 'params'), projection)) # type: ignore
|
|
332
376
|
|
|
333
377
|
return cls(**result) if len(result.keys()) else None
|
|
334
378
|
|
|
@@ -437,8 +481,11 @@ class Model():
|
|
|
437
481
|
|
|
438
482
|
data = self.__dict__.copy()
|
|
439
483
|
|
|
440
|
-
|
|
441
|
-
|
|
484
|
+
if isinstance(data['created_at'], datetime):
|
|
485
|
+
data['created_at'] = data['created_at'].strftime("%a %b %d %Y %H:%M:%S")
|
|
486
|
+
|
|
487
|
+
if isinstance(data['updated_at'], datetime):
|
|
488
|
+
data['updated_at'] = data['updated_at'].strftime("%a %b %d %Y %H:%M:%S")
|
|
442
489
|
|
|
443
490
|
data.pop('password', None)
|
|
444
491
|
|
|
@@ -483,16 +530,19 @@ class Model():
|
|
|
483
530
|
return normalized
|
|
484
531
|
else:
|
|
485
532
|
if optype == 'params':
|
|
486
|
-
if '
|
|
487
|
-
content['id'] = str(content['
|
|
533
|
+
if '_id' in content.keys():
|
|
534
|
+
content['id'] = str(content['_id'])
|
|
535
|
+
del content['_id']
|
|
488
536
|
for key, value in content.items():
|
|
489
|
-
if
|
|
537
|
+
if isinstance(value, ObjectId):
|
|
538
|
+
content[key] = str(value)
|
|
539
|
+
elif type(value) == list:
|
|
490
540
|
content[key] = '::'.join([str(v) for v in value])
|
|
491
|
-
|
|
492
541
|
elif type(value) == datetime:
|
|
493
542
|
content[key] = value.strftime("%a %b %d %Y %H:%M:%S")
|
|
494
543
|
elif type(value) == dict:
|
|
495
544
|
content[key] = json.dumps(value) # type: ignore
|
|
545
|
+
|
|
496
546
|
else:
|
|
497
547
|
init_signatures = inspect.signature(cls.__init__)
|
|
498
548
|
|
|
@@ -24,7 +24,8 @@ class MongoDB(ORM):
|
|
|
24
24
|
|
|
25
25
|
@staticmethod
|
|
26
26
|
def insert(collection: str, data: dict):
|
|
27
|
-
|
|
27
|
+
result = MongoDB.db[collection].insert_one(data)
|
|
28
|
+
return result.inserted_id
|
|
28
29
|
|
|
29
30
|
@staticmethod
|
|
30
31
|
def insert_many(collection: str, data: dict):
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
# @Link : link
|
|
6
6
|
# @Version : 1.0.0
|
|
7
7
|
|
|
8
|
+
import logging
|
|
8
9
|
import os
|
|
9
10
|
from mysql import connector
|
|
10
11
|
from sys import exit
|
|
@@ -64,7 +65,8 @@ class MysqlDB(ORM):
|
|
|
64
65
|
return str(MysqlDB.cursor.lastrowid)
|
|
65
66
|
|
|
66
67
|
except Exception as e:
|
|
67
|
-
|
|
68
|
+
logging.error(f"Error: {str(e)}")
|
|
69
|
+
return 0
|
|
68
70
|
|
|
69
71
|
@staticmethod
|
|
70
72
|
def update(table: str, filter: dict, data: dict):
|
|
@@ -129,7 +131,8 @@ class MysqlDB(ORM):
|
|
|
129
131
|
return MysqlDB.cursor.fetchone()
|
|
130
132
|
|
|
131
133
|
except Exception as e:
|
|
132
|
-
|
|
134
|
+
logging.error(f"Error: {str(e)}")
|
|
135
|
+
return {}
|
|
133
136
|
|
|
134
137
|
@staticmethod
|
|
135
138
|
def count(table: str, filter: dict = {}, columns: list = ['*'])-> int:
|
|
@@ -49,7 +49,7 @@ class PostgresqlDB(ORM):
|
|
|
49
49
|
|
|
50
50
|
except (Exception, psycopg2.Error) as error:
|
|
51
51
|
logging.error("Error connecting to PostgreSQL database:", error)
|
|
52
|
-
|
|
52
|
+
|
|
53
53
|
@staticmethod
|
|
54
54
|
def execute(query, params=None):
|
|
55
55
|
try:
|
|
@@ -57,11 +57,18 @@ class PostgresqlDB(ORM):
|
|
|
57
57
|
PostgresqlDB.cursor.execute(query, params)
|
|
58
58
|
else:
|
|
59
59
|
PostgresqlDB.cursor.execute(query)
|
|
60
|
-
PostgresqlDB.
|
|
61
|
-
|
|
60
|
+
if PostgresqlDB.cursor.description: # Check if description is not None
|
|
61
|
+
column_names = [desc.name for desc in PostgresqlDB.cursor.description]
|
|
62
|
+
result = [dict(zip(column_names, row)) for row in PostgresqlDB.cursor.fetchall()]
|
|
63
|
+
PostgresqlDB.db.commit()
|
|
64
|
+
return result
|
|
65
|
+
else:
|
|
66
|
+
PostgresqlDB.db.commit()
|
|
67
|
+
return [] # Return an empty list or appropriate value for queries that do not return rows
|
|
62
68
|
except (Exception, psycopg2.Error) as error:
|
|
63
69
|
logging.exception(error)
|
|
64
70
|
PostgresqlDB.db.rollback()
|
|
71
|
+
return []
|
|
65
72
|
|
|
66
73
|
@staticmethod
|
|
67
74
|
def insert(table: str, data: Dict):
|
|
@@ -77,7 +84,7 @@ class PostgresqlDB(ORM):
|
|
|
77
84
|
PostgresqlDB.db.commit()
|
|
78
85
|
new_inserts = PostgresqlDB.cursor.fetchone()
|
|
79
86
|
insert_id = new_inserts[0] if new_inserts else 0
|
|
80
|
-
return insert_id
|
|
87
|
+
return str(insert_id)
|
|
81
88
|
except (Exception, psycopg2.Error) as error:
|
|
82
89
|
print("Error inserting data:", error)
|
|
83
90
|
PostgresqlDB.db.rollback()
|
|
@@ -43,7 +43,8 @@ class SqliteDB(ORM):
|
|
|
43
43
|
return str(SqliteDB.cursor.lastrowid)
|
|
44
44
|
|
|
45
45
|
except Exception as e:
|
|
46
|
-
|
|
46
|
+
logging.error(f"Error: {str(e)}")
|
|
47
|
+
return 0
|
|
47
48
|
|
|
48
49
|
@staticmethod
|
|
49
50
|
def insert_many(tale: str, data: list[dict]):
|
|
@@ -110,7 +111,8 @@ class SqliteDB(ORM):
|
|
|
110
111
|
SqliteDB.db.commit()
|
|
111
112
|
|
|
112
113
|
resp = [x for x in SqliteDB.cursor.fetchall()]
|
|
113
|
-
|
|
114
|
+
|
|
115
|
+
return resp[0] if len(resp) else {}
|
|
114
116
|
|
|
115
117
|
except Exception as e:
|
|
116
118
|
logging.error({'status': 'Error', 'message': str(e)})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
def validate_email(email):
|
|
4
|
+
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b'
|
|
5
|
+
match = re.fullmatch(pattern, email)
|
|
6
|
+
|
|
7
|
+
if not match:
|
|
8
|
+
raise TypeError('Provide a valid email address')
|
|
9
|
+
|
|
10
|
+
return True
|
|
11
|
+
|
|
12
|
+
# print(validate_email("a._example@gmail.com.com")) # Output: True
|
|
13
|
+
# print(validate_email("invalid_email")) # Output: False
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|