Uploads a Pandas DataFrame to Redshift as a new table. The caller is responsible for deleting the table when no longer necessary. Args: redshift_data_client: Redshift Data API Service client cluster_id: Redshift Cluster Identifier workgroup: Redshift Serverless Work
(
redshift_data_client,
cluster_id: Optional[str],
workgroup: Optional[str],
database: str,
user: Optional[str],
s3_resource,
s3_path: str,
iam_role: str,
table_name: str,
df: pd.DataFrame,
)
| 212 | |
| 213 | |
| 214 | def upload_df_to_redshift( |
| 215 | redshift_data_client, |
| 216 | cluster_id: Optional[str], |
| 217 | workgroup: Optional[str], |
| 218 | database: str, |
| 219 | user: Optional[str], |
| 220 | s3_resource, |
| 221 | s3_path: str, |
| 222 | iam_role: str, |
| 223 | table_name: str, |
| 224 | df: pd.DataFrame, |
| 225 | ): |
| 226 | """Uploads a Pandas DataFrame to Redshift as a new table. |
| 227 | |
| 228 | The caller is responsible for deleting the table when no longer necessary. |
| 229 | |
| 230 | Args: |
| 231 | redshift_data_client: Redshift Data API Service client |
| 232 | cluster_id: Redshift Cluster Identifier |
| 233 | workgroup: Redshift Serverless Workgroup |
| 234 | database: Redshift Database Name |
| 235 | user: Redshift username |
| 236 | s3_resource: S3 Resource object |
| 237 | s3_path: S3 path where the Parquet file is temporarily uploaded |
| 238 | iam_role: IAM Role for Redshift to assume during the COPY command. |
| 239 | The role must grant permission to read the S3 location. |
| 240 | table_name: The name of the new Redshift table where we copy the dataframe |
| 241 | df: The Pandas DataFrame to upload |
| 242 | |
| 243 | Raises: |
| 244 | RedshiftTableNameTooLong: The specified table name is too long. |
| 245 | """ |
| 246 | |
| 247 | # Drop the index so that we dont have unnecessary columns |
| 248 | df.reset_index(drop=True, inplace=True) |
| 249 | |
| 250 | # Convert Pandas DataFrame into PyArrow table and compile the Redshift table schema. |
| 251 | # Note, if the underlying data has missing values, |
| 252 | # pandas will convert those values to np.nan if the dtypes are numerical (floats, ints, etc.) or boolean. |
| 253 | # If the dtype is 'object', then missing values are inferred as python `None`s. |
| 254 | # More details at: |
| 255 | # https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html#values-considered-missing |
| 256 | table = pa.Table.from_pandas(df) |
| 257 | upload_arrow_table_to_redshift( |
| 258 | table, |
| 259 | redshift_data_client, |
| 260 | cluster_id=cluster_id, |
| 261 | workgroup=workgroup, |
| 262 | database=database, |
| 263 | user=user, |
| 264 | s3_resource=s3_resource, |
| 265 | iam_role=iam_role, |
| 266 | s3_path=s3_path, |
| 267 | table_name=table_name, |
| 268 | ) |
| 269 | |
| 270 | |
| 271 | def delete_redshift_table( |
no test coverage detected