-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmappers_for_my_orm.py
More file actions
95 lines (74 loc) · 2.77 KB
/
mappers_for_my_orm.py
File metadata and controls
95 lines (74 loc) · 2.77 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
import sqlite3
from models import Student
connection = sqlite3.connect('patterns.sqlite')
class RecordNotFoundException(Exception):
def __init__(self, message):
super().__init__(f'Record not found: {message}')
class DbCommitException(Exception):
def __init__(self, message):
super().__init__(f'Db commit error: {message}')
class DbUpdateException(Exception):
def __init__(self, message):
super().__init__(f'Db update error: {message}')
class DbDeleteException(Exception):
def __init__(self, message):
super().__init__(f'Db delete error: {message}')
class StudentMapper:
def __init__(self, connection):
self.connection = connection
self.cursor = connection.cursor()
self.tablename = 'student'
def all(self):
statement = f'SELECT * from {self.tablename}'
self.cursor.execute(statement)
result = []
for item in self.cursor.fetchall():
id, name = item
student = Student(name)
student.id = id
result.append(student)
return result
def find_by_id(self, id):
statement = f"SELECT id, name FROM {self.tablename} WHERE id=?"
self.cursor.execute(statement, (id,))
result = self.cursor.fetchone()
if result:
return Student(*result)
else:
raise RecordNotFoundException(f'record with id={id} not found')
def insert(self, obj):
statement = f"INSERT INTO {self.tablename} (name) VALUES (?)"
self.cursor.execute(statement, (obj.name,))
try:
self.connection.commit()
except Exception as e:
raise DbCommitException(e.args)
def update(self, obj):
statement = f"UPDATE {self.tablename} SET name=? WHERE id=?"
# Где взять obj.id? Добавить в DomainModel? Или добавить когда берем объект из базы
self.cursor.execute(statement, (obj.name, obj.id))
try:
self.connection.commit()
except Exception as e:
raise DbUpdateException(e.args)
def delete(self, obj):
statement = f"DELETE FROM {self.tablename} WHERE id=?"
self.cursor.execute(statement, (obj.id,))
try:
self.connection.commit()
except Exception as e:
raise DbDeleteException(e.args)
class MapperRegistry:
mappers = {
'student': StudentMapper,
#'category': CategoryMapper
}
@staticmethod
def get_mapper(obj):
if isinstance(obj, Student):
return StudentMapper(connection)
#if isinstance(obj, Category):
#return CategoryMapper(connection)
@staticmethod
def get_current_mapper(name):
return MapperRegistry.mappers[name](connection)