-
Notifications
You must be signed in to change notification settings - Fork 0
/
abc.py
197 lines (173 loc) · 5.41 KB
/
abc.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
from __future__ import annotations
from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any, Dict, Generic, Iterable, List, Optional, Type, TypeVar
from psycopg2._psycopg import AsIs, connection
from psycopg2.extras import RealDictCursor
from constants import CHUNK_SIZE
Serialized = Dict[str, Any]
T = TypeVar("T")
@dataclass
class Serialisable(Generic[T]):
"""Abstract base for deserializing content from a request."""
__initializer = None
__init__ = None
def __new__(cls, *args, **kwargs):
try:
initializer = cls.__initializer
except AttributeError:
cls.__initializer = initializer = cls.__init__
cls.__init__ = lambda *a, **k: None
added_args = {}
for name in list(kwargs.keys()):
if name not in cls.__annotations__:
added_args[name] = kwargs.pop(name)
ret = object.__new__(cls)
initializer(ret)
for new_name, new_val in added_args.items():
setattr(ret, new_name, new_val)
return ret
@classmethod
def from_dict(cls: Type[T], d: Serialized) -> Optional[T]:
if d is not None:
return cls(**d)
def to_dict(self) -> Serialized:
d = dict()
for k, v in asdict(self).items():
if v is None:
continue
if isinstance(v, Enum):
v = v.value
elif isinstance(v, Serialisable):
v = v.to_dict()
d[k] = v
return d
def _insert(
self,
conn: connection,
table_name: str,
*returning
) -> None:
"""
:param conn:
:param table_name:
:param returning:
:return:
"""
with conn.cursor(cursor_factory=RealDictCursor) as cur:
d = tuple(self.to_dict().items())
keys = AsIs(",".join(k for k, v in d))
values = tuple(v for k, v in d)
if len(returning) == 0:
cur.execute(f"INSERT INTO {table_name} (%s) VALUES %s", (keys, values))
else:
cur.execute(
f"INSERT INTO {table_name} (%s) VALUES %s RETURNING {','.join(returning)}",
(keys, values),
)
result = cur.fetchone()
for field in returning:
setattr(self, field, result[field])
def _update(
self,
conn: connection,
table_name: str,
*key_fields
) -> None:
"""
:param conn
:param table_name
:param key_fields
:return:
"""
with conn.cursor(cursor_factory=RealDictCursor) as cur:
where_clause = []
assignment_names = []
assignment_values: List[Any] = []
for k, v in self.to_dict().items():
if k not in key_fields:
assignment_names.append("%s=%s")
assignment_values.extend((AsIs(k), v))
for field_name in key_fields:
where_clause.append(f"{field_name}=%s")
assignment_values.append(getattr(self, field_name))
statement = f"UPDATE {table_name} SET {','.join(assignment_names)} WHERE {' AND '.join(where_clause)}"
cur.execute(statement, assignment_values)
assert cur.rowcount == 1, f"Unexpectedly updated {cur.rowcount} {table_name} records"
@classmethod
def _fetch_one(
cls: Type[Serialisable],
conn: connection,
query: str,
*args: Any
) -> Optional[T]:
"""
:param conn:
:param query:
:param args:
:return:
"""
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(query, args)
result = cur.fetchone()
return cls.from_dict(result)
@classmethod
def _fetch_many(
cls: Type[Serialisable],
conn: connection,
query: str,
*args: Any
) -> Iterable[T]:
"""
:param conn:
:param query:
:param args:
:return:
"""
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(query, args)
while True:
results = cur.fetchmany(CHUNK_SIZE)
if not results:
break
for result in results:
obj = cls.from_dict(result)
if obj is not None:
yield obj
@staticmethod
def _delete_one(
conn: connection,
query: str,
*args: Any
) -> bool:
"""
:param conn:
:param query:
:param args:
:return:
"""
with conn.cursor() as cur:
cur.execute(query, args)
return True
@staticmethod
def _exists(
conn: connection,
table_name: str,
table_id_name: str,
table_id: Any
) -> bool:
"""
:param conn:
:param table_name:
:param table_id_name:
:param table_id:
:return:
"""
with conn.cursor() as cur:
# TODO: create an actual prepared statement
cur.execute(
f"select exists(select 1 from {table_name} where {table_id_name}=(%s));",
(table_id,),
)
(result,) = cur.fetchone()
return result