-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrdsdataapi.py
More file actions
337 lines (260 loc) · 8.53 KB
/
rdsdataapi.py
File metadata and controls
337 lines (260 loc) · 8.53 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
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
import numbers
import boto3
from datetime import date, datetime, time
from time import localtime
client = boto3.client("rds-data")
__all__ = [
# constants
"apilevel",
"connect",
"paramstyle",
"threadsafety",
# exceptions
"Warning",
"Error",
"InterfaceError",
"DatabaseError",
"DataError",
"OperationalError",
"IntegrityError",
"InternalError",
"ProgrammingError",
"NotSupportedError",
# connection func
"connect",
# types
]
# DBAPI 2 required constructor -- https://www.python.org/dev/peps/pep-0249/#constructors
def connect(*args, **kwargs):
return Connection(*args, **kwargs)
# DBAPI 2 required constants -- https://www.python.org/dev/peps/pep-0249/#globals
apilevel = "2.0"
threadsafety = 1 # just being safe.. miight be 3 actually!
paramstyle = "named" # seems RDS Data API uses this, regardless of mysql or postgresql
# DBAPI 2 required exceptions -- https://www.python.org/dev/peps/pep-0249/#exceptions
class Warning(Exception):
pass
class Error(Exception):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
# https://www.python.org/dev/peps/pep-0249/#connection-objects
class Connection:
def __init__(self, resource_arn, secret_arn, database):
self.resource_arn = resource_arn
self.secret_arn = secret_arn
self.database = database
self.transaction_id = None
def close(self):
pass
def commit(self):
if self.transaction_id is None:
return
client.commit_transaction(
resourceArn=self.resource_arn,
secretArn=self.secret_arn,
transactionId=self.transaction_id,
)
self.transaction_id = None
def rollback(self):
if self.transaction_id is None:
return
client.rollback_transaction(
resourceArn=self.resource_arn,
secretArn=self.secret_arn,
transactionId=self.transaction_id,
)
self.transaction_id = None
def cursor(self):
return Cursor(self)
def transaction(self):
"""
start a transaction
unless using this or cursor as a contextmanager, autocommit is used
"""
self.transaction_id = client.begin_transaction(
resourceArn=self.resource_arn,
secretArn=self.secret_arn,
database=self.database,
)["transactionId"]
# Warnings as connection peroperties
Warning = Warning
Error = Error
InterfaceError = InterfaceError
DatabaseError = DatabaseError
DataError = DataError
OperationalError = OperationalError
IntegrityError = IntegrityError
InternalError = InternalError
ProgrammingError = ProgrammingError
NotSupportedError = NotSupportedError
# https://www.python.org/dev/peps/pep-0249/#cursor-objects
class Cursor:
def __init__(self, connection):
self._connection = connection
self.arraysize = 1
self._rowcount = -1
self.result = None
@property
def connection(self):
return self._connection
@property
def description(self):
if self.result is None or "columnMetadata" not in self.result:
return None
return [
(col["name"], col["typeName"], None, None, None, None, None)
for col in self.result["columnMetadata"]
]
@property
def rowcount(self):
return self._rowcount
def close(self):
pass
def execute(self, operation, parameters=None):
if parameters is None:
parameters = {}
boto_params = dict(
sql=operation,
parameters=[
{"name": key, "value": _aws_type(value)}
for key, value in parameters.items()
],
resourceArn=self.connection.resource_arn,
secretArn=self.connection.secret_arn,
database=self.connection.database,
includeResultMetadata=True,
)
if self.connection.transaction_id is not None:
boto_params["transactionId"] = self.connection.transaction_id
try:
self.result = client.execute_statement(**boto_params)
except Exception as e:
raise self.connection.Error(e)
def executemany(self, operation, seq_of_parameters):
boto_params = dict(
sql=operation,
parameterSets=[
[
{"name": key, "value": _aws_type(value)}
for key, value in parameters.items()
]
for parameters in seq_of_parameters
],
resourceArn=self.connection.resource_arn,
secretArn=self.connection.secret_arn,
database=self.connection.database,
)
if self.connection.transaction_id is not None:
boto_params["transactionId"] = self.connection.transaction_id
try:
client.batch_execute_statement(**boto_params)
except Exception as e:
raise self.connection.Error(e)
def fetchone(self):
if self.result is None or "records" not in self.result:
raise self.connection.Error("No result to fetch!")
try:
return [_python_type(col) for col in self.result["records"].pop(0)]
except IndexError:
return None
def fetchmany(self, size=None):
if size is None:
size = self.arraysize
if self.result is None or "records" not in self.result:
raise self.connection.Error("No result to fetch!")
result = []
for _ in range(size):
try:
result.append(
[_python_type(col) for col in self.result["records"].pop(0)]
)
except IndexError:
pass
return result
def fetchall(self):
if self.result is None or "records" not in self.result:
raise self.connection.Error("No result to fetch!")
try:
return [
[_python_type(col) for col in record]
for record in self.result["records"]
]
finally:
self.result["records"] = []
def nextset(self):
raise NotSupportedError
def setinputsizes(self, sizes):
pass
def setoutputsize(self, size, column=None):
pass
# context manager use creates transactions
def __enter__(self):
self.connection.transaction()
return self
def __exit__(self, type_, value, traceback):
if type_:
self.connection.rollback()
else:
self.connection.commit()
# DBAPI 2 required types -- https://www.python.org/dev/peps/pep-0249/#type-objects-and-constructors
def Date(year, month, day):
return date(year, month, day)
def Time(hour, minute, second):
return time(hour, minute, second)
def Timestamp(year, month, day, hour, minute, second):
return DATETIME(year, month, day, hour, minute, second)
def DateFromTicks(ticks):
return Date(*localtime(ticks)[:3])
def TimeFromTicks(ticks):
return Time(*localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return Timestamp(*localtime(ticks)[:6])
def Binary(value):
return value
class DbType:
def __init__(self, *types):
self.types = types
def __eq__(self, other):
return other in self.types
class DatetimeDbType(DbType):
""" DATETIME has to both behave as `datetime.datetime` and equal to it's db_type"""
def __call__(self, *args, **kwargs):
return datetime(*args, **kwargs)
STRING = DbType("varchar", "text")
BINARY = DbType("bytea")
NUMBER = DbType("float4", "float8", "int4", "int8")
DATETIME = DatetimeDbType("timestamp")
ROWID = DbType()
# Interal utilities
def _python_type(value_dict):
if value_dict.get("isNull"):
return None
return next(iter(value_dict.values()))
def _aws_type(value):
if isinstance(value, str):
return {"stringValue": value}
if isinstance(value, bytes):
return {"blobValue": value}
if isinstance(value, bool):
return {"booleanValue": value}
if isinstance(value, float):
return {"doubleValue": value}
if isinstance(value, numbers.Integral):
return {"longValue": value}
if value is None:
return {"isNull": True}