|
| 1 | +"""Amazon Clean Rooms Module hosting read_* functions.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Any, Dict, Iterator, Optional, Union |
| 5 | + |
| 6 | +import boto3 |
| 7 | + |
| 8 | +import awswrangler.pandas as pd |
| 9 | +from awswrangler import _utils, s3 |
| 10 | +from awswrangler._sql_formatter import _process_sql_params |
| 11 | +from awswrangler.cleanrooms._utils import wait_query |
| 12 | + |
| 13 | +_logger: logging.Logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def _delete_after_iterate( |
| 17 | + dfs: Iterator[pd.DataFrame], keep_files: bool, kwargs: Dict[str, Any] |
| 18 | +) -> Iterator[pd.DataFrame]: |
| 19 | + for df in dfs: |
| 20 | + yield df |
| 21 | + if keep_files is False: |
| 22 | + s3.delete_objects(**kwargs) |
| 23 | + |
| 24 | + |
| 25 | +def read_sql_query( |
| 26 | + sql: str, |
| 27 | + membership_id: str, |
| 28 | + output_bucket: str, |
| 29 | + output_prefix: str, |
| 30 | + keep_files: bool = True, |
| 31 | + params: Optional[Dict[str, Any]] = None, |
| 32 | + chunksize: Optional[Union[int, bool]] = None, |
| 33 | + use_threads: Union[bool, int] = True, |
| 34 | + boto3_session: Optional[boto3.Session] = None, |
| 35 | + pyarrow_additional_kwargs: Optional[Dict[str, Any]] = None, |
| 36 | +) -> Union[Iterator[pd.DataFrame], pd.DataFrame]: |
| 37 | + """Execute Clean Rooms Protected SQL query and return the results as a Pandas DataFrame. |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + sql : str |
| 42 | + SQL query |
| 43 | + membership_id : str |
| 44 | + Membership ID |
| 45 | + output_bucket : str |
| 46 | + S3 output bucket name |
| 47 | + output_prefix : str |
| 48 | + S3 output prefix |
| 49 | + keep_files : bool, optional |
| 50 | + Whether files in S3 output bucket/prefix are retained. 'True' by default |
| 51 | + params : Dict[str, any], optional |
| 52 | + Dict of parameters used for constructing the SQL query. Only named parameters are supported. |
| 53 | + The dict must be in the form {'name': 'value'} and the SQL query must contain |
| 54 | + `:name`. Note that for varchar columns and similar, you must surround the value in single quotes |
| 55 | + chunksize : Union[int, bool], optional |
| 56 | + If passed, the data is split into an iterable of DataFrames (Memory friendly). |
| 57 | + If `True` an iterable of DataFrames is returned without guarantee of chunksize. |
| 58 | + If an `INTEGER` is passed, an iterable of DataFrames is returned with maximum rows |
| 59 | + equal to the received INTEGER |
| 60 | + use_threads : Union[bool, int], optional |
| 61 | + True to enable concurrent requests, False to disable multiple threads. |
| 62 | + If enabled os.cpu_count() is used as the maximum number of threads. |
| 63 | + If integer is provided, specified number is used |
| 64 | + boto3_session : boto3.Session, optional |
| 65 | + Boto3 Session. If None, the default boto3 session is used |
| 66 | + pyarrow_additional_kwargs : Optional[Dict[str, Any]] |
| 67 | + Forwarded to `to_pandas` method converting from PyArrow tables to Pandas DataFrame. |
| 68 | + Valid values include "split_blocks", "self_destruct", "ignore_metadata". |
| 69 | + e.g. pyarrow_additional_kwargs={'split_blocks': True} |
| 70 | +
|
| 71 | + Returns |
| 72 | + ------- |
| 73 | + Union[Iterator[pd.DataFrame], pd.DataFrame] |
| 74 | + Pandas DataFrame or Generator of Pandas DataFrames if chunksize is provided. |
| 75 | +
|
| 76 | + Examples |
| 77 | + -------- |
| 78 | + >>> import awswrangler as wr |
| 79 | + >>> df = wr.cleanrooms.read_sql_query( |
| 80 | + >>> sql='SELECT DISTINCT...', |
| 81 | + >>> membership_id='membership-id', |
| 82 | + >>> output_bucket='output-bucket', |
| 83 | + >>> output_prefix='output-prefix', |
| 84 | + >>> ) |
| 85 | + """ |
| 86 | + client_cleanrooms = _utils.client(service_name="cleanrooms", session=boto3_session) |
| 87 | + |
| 88 | + query_id: str = client_cleanrooms.start_protected_query( |
| 89 | + type="SQL", |
| 90 | + membershipIdentifier=membership_id, |
| 91 | + sqlParameters={"queryString": _process_sql_params(sql, params, engine_type="partiql")}, |
| 92 | + resultConfiguration={ |
| 93 | + "outputConfiguration": { |
| 94 | + "s3": { |
| 95 | + "bucket": output_bucket, |
| 96 | + "keyPrefix": output_prefix, |
| 97 | + "resultFormat": "PARQUET", |
| 98 | + } |
| 99 | + } |
| 100 | + }, |
| 101 | + )["protectedQuery"]["id"] |
| 102 | + |
| 103 | + _logger.debug("query_id: %s", query_id) |
| 104 | + path: str = wait_query(membership_id=membership_id, query_id=query_id)["protectedQuery"]["result"]["output"]["s3"][ |
| 105 | + "location" |
| 106 | + ] |
| 107 | + |
| 108 | + _logger.debug("path: %s", path) |
| 109 | + chunked: Union[bool, int] = False if chunksize is None else chunksize |
| 110 | + ret = s3.read_parquet( |
| 111 | + path=path, |
| 112 | + use_threads=use_threads, |
| 113 | + chunked=chunked, |
| 114 | + boto3_session=boto3_session, |
| 115 | + pyarrow_additional_kwargs=pyarrow_additional_kwargs, |
| 116 | + ) |
| 117 | + |
| 118 | + _logger.debug("type(ret): %s", type(ret)) |
| 119 | + kwargs: Dict[str, Any] = { |
| 120 | + "path": path, |
| 121 | + "use_threads": use_threads, |
| 122 | + "boto3_session": boto3_session, |
| 123 | + } |
| 124 | + if chunked is False: |
| 125 | + if keep_files is False: |
| 126 | + s3.delete_objects(**kwargs) |
| 127 | + return ret |
| 128 | + return _delete_after_iterate(ret, keep_files, kwargs) |
0 commit comments