-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcrud.py
More file actions
242 lines (198 loc) · 6.26 KB
/
crud.py
File metadata and controls
242 lines (198 loc) · 6.26 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
"""Low level CRUD functions, generalised for wider usage.
Functions listed here should be accessed only from other CRUD modules,
and not directly from the app.
"""
from typing import Any, List, Optional, Type, Union
from pydantic import BaseModel
from sqlalchemy.exc import (
IntegrityError,
InvalidRequestError,
OperationalError,
SQLAlchemyError,
StatementError,
)
from sqlalchemy.orm import Session
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.exc import UnmappedInstanceError
from app.database.models_v2 import Base
from app.dependencies import logger
def insert(session: Session, instance: Base) -> bool:
"""Inserts a new row into the database.
Args:
session: The database connection.
instance: The object to save.
Returns:
True if successful, otherwise returns False.
Raises:
SQLAlchemyError: If the database tables were not created.
"""
if issubclass(instance.__class__, Base):
try:
session.add(instance)
session.commit()
session.refresh(instance)
return True
except IntegrityError as e:
logger.exception(e)
return False
except OperationalError as e:
logger.exception(e)
raise SQLAlchemyError("Database tables were not created yet.")
return False
def delete(session: Session, instance: Base) -> bool:
"""Deletes a row from the database using the database model.
Args:
session: The database connection.
instance: The object to delete.
Returns:
True if successful, otherwise returns False.
"""
return delete_multiple(session, [instance])
def delete_multiple(session: Session, instances: List[Base]) -> bool:
"""Deletes a multiple rows from the database using the database models.
Args:
session: The database connection.
instances: A list of objects to delete.
Returns:
True if successful, otherwise returns False.
"""
try:
for instance in instances:
session.delete(instance)
session.commit()
return True
except InvalidRequestError:
return False
except UnmappedInstanceError:
return False
def get_by_id(
session: Session,
entity_id: int,
orm_class: Type[Base],
) -> Optional[Union[BaseModel, Base]]:
"""Returns a schema or database model by an ID.
Args:
session: The database connection.
entity_id: The entity's ID.
orm_class: The database mapped model class.
Returns:
A BaseModel or Base model, as requested, if successful,
otherwise returns None.
"""
keywords = {orm_class.id.key: entity_id}
return get_database_model_by_parameter(session, orm_class, **keywords)
def get_database_model_by_parameter(
session: Session,
orm_class: Type[Base],
**kwargs: Any,
) -> Optional[Union[BaseModel, Base]]:
"""Returns a schema or database model by a parameter.
Args:
session: The database connection.
orm_class: The database mapped model class.
**kwargs: The parameter to filter by.
Must be in the format of: key=value.
Returns:
A BaseModel or Base model, as requested, if successful,
otherwise returns None.
"""
try:
return session.query(orm_class).filter_by(**kwargs).first()
except OperationalError as e:
logger.exception(e)
return None
def get_all_database_models(
session: Session,
orm_class: Type[Base],
skip: int = 0,
limit: int = 100,
) -> List[Base]:
"""Returns all models from the database.
Args:
session: The database connection.
orm_class: The database mapped model class.
skip: The starting index.
Defaults to 0.
limit: The amount of returned items.
Defaults to 100.
Returns:
A list database models.
"""
try:
return session.query(orm_class).offset(skip).limit(limit).all()
except OperationalError as e:
logger.exception(e)
return []
def get_property(
session: Session,
entity_id: int,
column: InstrumentedAttribute,
) -> Optional[Any]:
"""Returns the value of an entity's property.
Args:
session: The database connection.
entity_id: The entity's ID.
column: The database column from where to query the data.
Returns:
The value of the entity's database column.
"""
orm_model = get_by_id(session, entity_id, column.class_)
if not orm_model:
return None
return getattr(orm_model, column.key)
def set_property(
session: Session,
entity_id: int,
column: InstrumentedAttribute,
value: Any,
) -> bool:
"""Sets a new value for an entity's property.
Args:
session: The database connection.
entity_id: The entity's ID.
column: The database column to where the data is saved.
value: The new value to set.
Returns:
True if successful, otherwise returns False.
"""
orm_model = get_by_id(session, entity_id, column.class_)
if not orm_model:
return False
setattr(orm_model, column.key, value)
try:
session.commit()
except IntegrityError:
session.rollback()
return False
except StatementError:
session.rollback()
return False
return True
def update_database_by_schema_model(
session: Session,
entity_id: int,
schema_instance: BaseModel,
orm_class: Type[Base],
) -> bool:
"""Updates the database model by extracting data from the schema object.
ID is passed as a separate parameter for instances where an ID is named
something other than "id".
Args:
session: The database connection.
entity_id: The entity's ID.
schema_instance: The schema model whose data is used for the update.
orm_class: The database mapped model class.
Returns:
True if successful, otherwise returns False.
"""
id_filter = {orm_class.id.key: entity_id}
try:
(
session.query(orm_class)
.filter_by(**id_filter)
.update(schema_instance.dict())
)
session.commit()
return True
except InvalidRequestError:
return False