-
Notifications
You must be signed in to change notification settings - Fork 707
/
Copy pathrds.py
513 lines (421 loc) · 16.8 KB
/
rds.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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""RDS Data API Connector."""
from __future__ import annotations
import datetime as dt
import logging
import time
import uuid
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
import boto3
from typing_extensions import Literal
import awswrangler.pandas as pd
from awswrangler import _data_types, _databases, _utils, exceptions
from awswrangler._sql_utils import identifier
from awswrangler.data_api import _connector
if TYPE_CHECKING:
from mypy_boto3_rds_data.client import BotocoreClientError # type: ignore[attr-defined]
from mypy_boto3_rds_data.type_defs import BatchExecuteStatementResponseTypeDef, ExecuteStatementResponseTypeDef
_logger = logging.getLogger(__name__)
_ExecuteStatementResponseType = TypeVar(
"_ExecuteStatementResponseType", "ExecuteStatementResponseTypeDef", "BatchExecuteStatementResponseTypeDef"
)
class RdsDataApi(_connector.DataApiConnector):
"""Provides access to the RDS Data API.
Parameters
----------
resource_arn
ARN for the RDS resource.
database
Target database name.
secret_arn
The ARN for the secret to be used for authentication.
sleep
Number of seconds to sleep between connection attempts to paused clusters - defaults to 0.5.
backoff
Factor by which to increase the sleep between connection attempts to paused clusters - defaults to 1.0.
retries
Maximum number of connection attempts to paused clusters - defaults to 10.
boto3_session
The default boto3 session will be used if **boto3_session** is ``None``.
"""
def __init__(
self,
resource_arn: str,
database: str,
secret_arn: str = "",
sleep: float = 0.5,
backoff: float = 1.0,
retries: int = 30,
boto3_session: boto3.Session | None = None,
) -> None:
super().__init__()
self.client = _utils.client(service_name="rds-data", session=boto3_session)
self.resource_arn = resource_arn
self.database = database
self.secret_arn = secret_arn
self.wait_config = _connector.WaitConfig(sleep, backoff, retries)
self.results: dict[str, "ExecuteStatementResponseTypeDef" | "BatchExecuteStatementResponseTypeDef"] = {}
def close(self) -> None:
"""Close underlying endpoint connections."""
self.client.close()
def begin_transaction(self, database: str | None = None, schema: str | None = None) -> str:
"""Start an SQL transaction."""
if database is None:
database = self.database
kwargs = {}
if database:
kwargs["database"] = database
if schema:
kwargs["schema"] = schema
response = self.client.begin_transaction(
resourceArn=self.resource_arn,
secretArn=self.secret_arn,
**kwargs,
)
return response["transactionId"]
def commit_transaction(self, transaction_id: str) -> str:
"""Commit an SQL transaction."""
response = self.client.commit_transaction(
resourceArn=self.resource_arn,
secretArn=self.secret_arn,
transactionId=transaction_id,
)
return response["transactionStatus"]
def rollback_transaction(self, transaction_id: str) -> str:
"""Roll back an SQL transaction."""
response = self.client.rollback_transaction(
resourceArn=self.resource_arn,
secretArn=self.secret_arn,
transactionId=transaction_id,
)
return response["transactionStatus"]
def _execute_with_retry(
self,
sql: str,
function: Callable[[str], _ExecuteStatementResponseType],
) -> str:
sleep: float = self.wait_config.sleep
total_tries: int = 0
total_sleep: float = 0
response: _ExecuteStatementResponseType | None = None
last_exception: "BotocoreClientError" | None = None
while total_tries < self.wait_config.retries:
try:
response = function(sql)
_logger.debug(
"Response received after %s tries and sleeping for a total of %s seconds", total_tries, total_sleep
)
break
except self.client.exceptions.BadRequestException as exception:
last_exception = exception
total_sleep += sleep
_logger.debug("BadRequestException occurred: %s", exception)
_logger.debug(
"Cluster may be paused - sleeping for %s seconds for a total of %s before retrying",
sleep,
total_sleep,
)
time.sleep(sleep)
total_tries += 1
sleep *= self.wait_config.backoff
if response is None:
_logger.exception("Maximum BadRequestException retries reached for query %s", sql)
raise last_exception # type: ignore[misc]
request_id: str = uuid.uuid4().hex
self.results[request_id] = response
return request_id
def _execute_statement(
self,
sql: str,
database: str | None = None,
transaction_id: str | None = None,
parameters: list[dict[str, Any]] | None = None,
) -> str:
if database is None:
database = self.database
additional_kwargs: dict[str, Any] = {}
if transaction_id:
additional_kwargs["transactionId"] = transaction_id
if parameters:
additional_kwargs["parameters"] = parameters
def function(sql: str) -> "ExecuteStatementResponseTypeDef":
return self.client.execute_statement(
resourceArn=self.resource_arn,
database=database,
sql=sql,
secretArn=self.secret_arn,
includeResultMetadata=True,
**additional_kwargs,
)
return self._execute_with_retry(sql=sql, function=function)
def _batch_execute_statement(
self,
sql: str | list[str],
database: str | None = None,
transaction_id: str | None = None,
parameter_sets: list[list[dict[str, Any]]] | None = None,
) -> str:
if isinstance(sql, list):
raise exceptions.InvalidArgumentType("`sql` parameter cannot be list.")
if database is None:
database = self.database
additional_kwargs: dict[str, Any] = {}
if transaction_id:
additional_kwargs["transactionId"] = transaction_id
if parameter_sets:
additional_kwargs["parameterSets"] = parameter_sets
def function(sql: str) -> "BatchExecuteStatementResponseTypeDef":
return self.client.batch_execute_statement(
resourceArn=self.resource_arn,
database=database,
sql=sql,
secretArn=self.secret_arn,
**additional_kwargs,
)
return self._execute_with_retry(sql=sql, function=function)
def _get_statement_result(self, request_id: str) -> pd.DataFrame:
try:
result = cast("ExecuteStatementResponseTypeDef", self.results.pop(request_id))
except KeyError as exception:
raise KeyError(f"Request {request_id} not found in results {self.results}") from exception
if "records" not in result:
return pd.DataFrame()
rows: list[list[Any]] = []
column_types = [col.get("typeName") for col in result["columnMetadata"]]
for record in result["records"]:
row: list[Any] = [
_connector.DataApiConnector._get_column_value(column, col_type) # type: ignore[arg-type]
for column, col_type in zip(record, column_types)
]
rows.append(row)
column_names: list[str] = [column["name"] for column in result["columnMetadata"]]
dataframe = pd.DataFrame(rows, columns=column_names)
return dataframe
def connect(
resource_arn: str, database: str, secret_arn: str = "", boto3_session: boto3.Session | None = None, **kwargs: Any
) -> RdsDataApi:
"""Create a RDS Data API connection.
Parameters
----------
resource_arn
ARN for the RDS resource.
database
Target database name.
secret_arn
The ARN for the secret to be used for authentication.
boto3_session
The default boto3 session will be used if **boto3_session** is ``None``.
**kwargs
Any additional kwargs are passed to the underlying RdsDataApi class.
Returns
-------
A RdsDataApi connection instance that can be used with `wr.rds.data_api.read_sql_query`.
"""
return RdsDataApi(resource_arn, database, secret_arn=secret_arn, boto3_session=boto3_session, **kwargs)
def read_sql_query(
sql: str, con: RdsDataApi, database: str | None = None, parameters: list[dict[str, Any]] | None = None
) -> pd.DataFrame:
"""Run an SQL query on an RdsDataApi connection and return the result as a DataFrame.
Parameters
----------
sql
SQL query to run.
con
A RdsDataApi connection instance
database
Database to run query on - defaults to the database specified by `con`.
parameters
A list of named parameters e.g. [{"name": "col", "value": {"stringValue": "val1"}}].
Returns
-------
A Pandas DataFrame containing the query results.
Examples
--------
>>> import awswrangler as wr
>>> df = wr.data_api.rds.read_sql_query(
>>> sql="SELECT * FROM public.my_table",
>>> con=con,
>>> )
>>> import awswrangler as wr
>>> df = wr.data_api.rds.read_sql_query(
>>> sql="SELECT * FROM public.my_table WHERE col = :name",
>>> con=con,
>>> parameters=[
>>> {"name": "col1", "value": {"stringValue": "val1"}}
>>> ],
>>> )
"""
return con.execute(sql, database=database, parameters=parameters)
def _drop_table(con: RdsDataApi, table: str, database: str, transaction_id: str, sql_mode: str) -> None:
sql = f"DROP TABLE IF EXISTS {identifier(table, sql_mode=sql_mode)}"
_logger.debug("Drop table query:\n%s", sql)
con.execute(sql, database=database, transaction_id=transaction_id)
def _does_table_exist(con: RdsDataApi, table: str, database: str, transaction_id: str) -> bool:
res = con.execute(
"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = :table",
parameters=[
{
"name": "table",
"value": {"stringValue": table},
},
],
)
return not res.empty
def _create_table(
df: pd.DataFrame,
con: RdsDataApi,
table: str,
database: str,
transaction_id: str,
mode: str,
index: bool,
dtype: dict[str, str] | None,
varchar_lengths: dict[str, int] | None,
sql_mode: str,
) -> None:
if mode == "overwrite":
_drop_table(con=con, table=table, database=database, transaction_id=transaction_id, sql_mode=sql_mode)
elif _does_table_exist(con=con, table=table, database=database, transaction_id=transaction_id):
return
mysql_types: dict[str, str] = _data_types.database_types_from_pandas(
df=df,
index=index,
dtype=dtype,
varchar_lengths_default="TEXT",
varchar_lengths=varchar_lengths,
converter_func=_data_types.pyarrow2mysql,
)
cols_str: str = "".join([f"{identifier(k, sql_mode=sql_mode)} {v},\n" for k, v in mysql_types.items()])[:-2]
sql = f"CREATE TABLE IF NOT EXISTS {identifier(table, sql_mode=sql_mode)} (\n{cols_str})"
_logger.debug("Create table query:\n%s", sql)
con.execute(sql, database=database, transaction_id=transaction_id)
def _create_value_dict( # noqa: PLR0911
value: Any,
) -> tuple[dict[str, Any], str | None]:
if value is None or pd.isnull(value):
return {"isNull": True}, None
if isinstance(value, bool):
return {"booleanValue": value}, None
if isinstance(value, int):
return {"longValue": value}, None
if isinstance(value, float):
return {"doubleValue": value}, None
if isinstance(value, str):
return {"stringValue": value}, None
if isinstance(value, bytes):
return {"blobValue": value}, None
if isinstance(value, dt.datetime):
return {"stringValue": str(value)}, "TIMESTAMP"
if isinstance(value, dt.date):
return {"stringValue": str(value)}, "DATE"
if isinstance(value, dt.time):
return {"stringValue": str(value)}, "TIME"
if isinstance(value, Decimal):
return {"stringValue": str(value)}, "DECIMAL"
if isinstance(value, uuid.UUID):
return {"stringValue": str(value)}, "UUID"
raise exceptions.InvalidArgumentType(f"Value {value} not supported.")
def _generate_parameters(columns: list[str], values: list[Any]) -> list[dict[str, Any]]:
parameter_list = []
for col, value in zip(columns, values):
value, type_hint = _create_value_dict(value) # noqa: PLW2901
parameter = {
"name": col,
"value": value,
}
if type_hint:
parameter["typeHint"] = type_hint
parameter_list.append(parameter)
return parameter_list
def _generate_parameter_sets(df: pd.DataFrame) -> list[list[dict[str, Any]]]:
parameter_sets = []
columns = df.columns.tolist()
for values in df.values.tolist():
parameter_sets.append(_generate_parameters(columns, values))
return parameter_sets
def to_sql(
df: pd.DataFrame,
con: RdsDataApi,
table: str,
database: str,
mode: Literal["append", "overwrite"] = "append",
index: bool = False,
dtype: dict[str, str] | None = None,
varchar_lengths: dict[str, int] | None = None,
use_column_names: bool = False,
chunksize: int = 200,
sql_mode: str = "mysql",
) -> None:
"""
Insert data using an SQL query on a Data API connection.
Parameters
----------
df
`Pandas DataFrame <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_
con
A RdsDataApi connection instance
database
Database to run query on - defaults to the database specified by `con`.
table
Table name
mode
`append` (inserts new records into table), `overwrite` (drops table and recreates)
index
True to store the DataFrame index as a column in the table,
otherwise False to ignore it.
dtype
Dictionary of columns names and MySQL types to be casted.
Useful when you have columns with undetermined or mixed data types.
(e.g. ```{'col name': 'TEXT', 'col2 name': 'FLOAT'}```)
varchar_lengths
Dict of VARCHAR length by columns. (e.g. ```{"col1": 10, "col5": 200}```).
use_column_names
If set to True, will use the column names of the DataFrame for generating the INSERT SQL Query.
E.g. If the DataFrame has two columns `col1` and `col3` and `use_column_names` is True, data will only be
inserted into the database columns `col1` and `col3`.
chunksize
Number of rows which are inserted with each SQL query. Defaults to inserting 200 rows per query.
sql_mode
"mysql" for default MySQL identifiers (backticks) or "ansi" for ANSI-compatible identifiers (double quotes).
"""
if df.empty is True:
raise exceptions.EmptyDataFrame("DataFrame cannot be empty.")
_databases.validate_mode(mode=mode, allowed_modes=["append", "overwrite"])
transaction_id: str | None = None
try:
transaction_id = con.begin_transaction(database=database)
_create_table(
df=df,
con=con,
table=table,
database=database,
transaction_id=transaction_id,
mode=mode,
index=index,
dtype=dtype,
varchar_lengths=varchar_lengths,
sql_mode=sql_mode,
)
if index:
df = df.reset_index(level=df.index.names)
if use_column_names:
insertion_columns = "(" + ", ".join([f"{identifier(col, sql_mode=sql_mode)}" for col in df.columns]) + ")"
else:
insertion_columns = ""
placeholders = ", ".join([f":{col}" for col in df.columns])
sql = f"INSERT INTO {identifier(table, sql_mode=sql_mode)} {insertion_columns} VALUES ({placeholders})"
parameter_sets = _generate_parameter_sets(df)
for parameter_sets_chunk in _utils.chunkify(parameter_sets, max_length=chunksize):
con.batch_execute(
sql=sql,
database=database,
transaction_id=transaction_id,
parameter_sets=parameter_sets_chunk,
)
except Exception as ex:
if transaction_id:
con.rollback_transaction(transaction_id=transaction_id)
_logger.error(ex)
raise
else:
con.commit_transaction(transaction_id=transaction_id)