-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksight_bulk_update_datasets.py
300 lines (257 loc) · 13.8 KB
/
quicksight_bulk_update_datasets.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
#
# Update any Quicksight datasets with relational tables in the source schema to use the target schema.
#
# Run in dry run mode (Do this to test it)
# quicksight-bulk-update-datasets --account-id=<aws account id> --aws-profile=<aws profile name> --source-schema=<schema name> --target-schema=<schema name> --dry-run
#
# To run for real remove the "--dry-run" argument from the above command
#
# You will be prompted before each dataset is actually updated on Quicksight. To run it for all
# datasets without the prompt add the "--no-prompt" arg to the command
#
import csv
import datetime
from collections import deque
from contextlib import contextmanager
from typing_extensions import Annotated
import boto3
import pglast
import pglast.stream
import typer
from rich.highlighter import ReprHighlighter
from rich.progress import MofNCompleteColumn, BarColumn, SpinnerColumn, TextColumn, TimeRemainingColumn, Progress
from rich.table import Table
from botocore.exceptions import ClientError
app = typer.Typer()
@app.command()
def rename_schema(
account_id: Annotated[str, typer.Option("--account-id", "-a", help="The AWS account ID", show_default=False)],
source_schema: Annotated[str, typer.Option("--source-schema", "-s", help="The schema that will be renamed", show_default=False)],
target_schema: Annotated[str, typer.Option("--target-schema", "-t", help="The new name of the source schema", show_default=False)],
aws_profile: Annotated[str, typer.Option("--aws-profile", "-p", help="The profile to connect to AWS", show_default=False)] = None,
dataset_id: Annotated[str, typer.Option("--dataset-id", "-i", help="Run for the dataset with this ID only")] = None,
no_prompt: Annotated[bool, typer.Option("--no-prompt", "-n", help="Update all affected dataset without prompting the user")] = False,
dry_run: Annotated[bool, typer.Option("--dry-run", "-d", help="Do not apply changes to Quicksight")] = False,
):
"""
Update datasets that refer to the source schema to use the target schema
"""
def all_dataset_ids(client):
with Progress(SpinnerColumn(finished_text='[green]✔'), TextColumn("{task.description}")) as progress:
task = progress.add_task("Finding all datasets...", total=1)
dataset_ids = tuple(
dataset_summary['DataSetId']
for page in client.get_paginator("list_data_sets").paginate(AwsAccountId=account_id)
for dataset_summary in page.get("DataSetSummaries", [])
)
progress.update(task, advance=1, description=f'Finding all datasets... done: [bold]{len(dataset_ids)}')
return dataset_ids
def datasets(client, console, dataset_ids):
for _dataset_id in dataset_ids:
try:
response = client.describe_data_set(
AwsAccountId=account_id, DataSetId=_dataset_id
)
except ClientError as ex:
# Some datasets cannot be described in the API, e.g. manual uploads
console.print(f"⚠️ Error fetching detail for dataset {_dataset_id}: {ex.response['Error']['Message']}")
continue
yield response["DataSet"]
@contextmanager
def csv_output_report():
timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
filename = f"{timestamp}--{account_id}{'--dry-run' if dry_run else ''}.csv"
with open(filename, 'w', newline='') as f:
fieldnames = ['dataset_id', 'dataset_link', 'physical_table_id', 'type', 'source', 'target', 'error']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
yield writer
def tables_from_query(query):
statements = pglast.parse_sql(query)
if len(statements) == 0:
return []
tables = set()
node_ctenames = deque()
node_ctenames.append((statements[0](), ()))
while node_ctenames:
node, ctenames = node_ctenames.popleft()
if node.get("withClause", None) is not None:
if node["withClause"]["recursive"]:
ctenames += tuple((cte["ctename"] for cte in node["withClause"]["ctes"]))
for cte in node["withClause"]["ctes"]:
node_ctenames.append((cte, ctenames))
else:
for cte in node["withClause"]["ctes"]:
node_ctenames.append((cte, ctenames))
ctenames += (cte["ctename"],)
if node.get("@", None) == "RangeVar" and (
node["schemaname"] is not None or node["relname"] not in ctenames
):
tables.add((node["schemaname"] or "public", node["relname"]))
for node_type, node_value in node.items():
if node_type == "withClause":
continue
for nested_node in node_value if isinstance(node_value, tuple) else (node_value,):
if isinstance(nested_node, dict):
node_ctenames.append((nested_node, ctenames))
return sorted(list(tables))
def rename_schema(query, source, target):
# Strongly based on tables_from_query, but that is based on iterating over the "dict" form
# of the parsed query. But to re-serialize, we need the object form. Could probably be
# simplified to only use the object form
statements = pglast.parse_sql(query)
if len(statements) > 1:
raise Exception("Multiple statements are not supported")
if len(statements) == 0:
return []
node_ctenames = deque()
node_ctenames.append((statements[0], ()))
while node_ctenames:
node, ctenames = node_ctenames.popleft()
node_dict = node()
if node_dict.get("withClause", None) is not None:
if node_dict["withClause"]["recursive"]:
ctenames += tuple((cte.ctename for cte in node.withClause.ctes))
for cte in node.withClause.ctes:
node_ctenames.append((cte, ctenames))
else:
for cte in node.withClause.ctes:
node_ctenames.append((cte, ctenames))
ctenames += (cte.ctename,)
if node_dict.get("@", None) == "RangeVar" and (
node_dict["schemaname"] is not None or node_dict["relname"] not in ctenames
) and (node.schemaname or "public") == source:
node.schemaname = target
if (node_dict.get("@", None) == "ColumnRef" and
len(node.fields) == 3 and
node.fields[0].sval == source
):
node.fields[0].sval = target
for node_type in node:
node_value = getattr(node, node_type)
if node_type == "withClause":
continue
for nested_node in node_value if isinstance(node_value, tuple) else (node_value,):
if isinstance(nested_node, pglast.ast.Node):
node_ctenames.append((nested_node, ctenames))
return pglast.stream.IndentedStream(
comments=pglast._extract_comments(query),
comma_at_eoln=True,
)(statements[0])
def modify_dataset_dict_if_needed(console, dataset):
for physical_table_id, physical_table in dataset.get("PhysicalTableMap", {}).items():
dataset_link = f"https://eu-west-2.quicksight.aws.amazon.com/sn/data-sets/{dataset['DataSetId']}"
if "RelationalTable" in physical_table:
table = physical_table["RelationalTable"]
if table["Schema"] == source_schema:
grid = Table.grid(padding=(0, 1))
grid.add_column(justify="left")
grid.add_column(justify="left")
grid.add_row(f"[green]✔[/green] RelationalTable", ReprHighlighter()(f"{(table['Schema'], table['Name'])} ➜ {(target_schema, table['Name'])}"))
console.print(grid, highlight=True)
table["Schema"] = target_schema
yield {
'dataset_id': dataset['DataSetId'],
'dataset_link': dataset_link,
'physical_table_id': physical_table_id,
'type': 'table',
'source': source_schema,
'target': target_schema,
'error': '',
}
if "CustomSql" in physical_table:
original_sql = physical_table["CustomSql"]["SqlQuery"]
try:
tables = tables_from_query(physical_table["CustomSql"]["SqlQuery"])
except Exception as e:
console.print(f"⚠️ Unable to parse query in {dataset['DataSetId']}")
yield {
'dataset_id': dataset['DataSetId'],
'dataset_link': dataset_link,
'physical_table_id': physical_table_id,
'type': 'sql',
'source': original_sql,
'target': '',
'error': f'Unable to parse query: {e}',
}
continue
if any(schema == source_schema for schema, table in tables):
renamed_sql = rename_schema(original_sql, source_schema, target_schema)
new_tables = tables_from_query(renamed_sql)
grid = Table.grid(padding=(0, 1))
grid.add_column(justify="left")
grid.add_column(justify="left")
innerGrid = Table.grid(padding=(0, 1))
innerGrid.add_column(justify="left")
innerGrid.add_column(justify="left")
for old, new in zip(tables, new_tables):
innerGrid.add_row(ReprHighlighter()(f'{old}'), '➜', ReprHighlighter()(f'{new}'))
grid.add_row(f"[green]✔[/green] CustomSql ", innerGrid)
console.print(grid, highlight=True)
no_original = any(schema == source_schema for schema, table in new_tables) == False
any_target = any(schema == target_schema for schema, table in new_tables) == True
original_tables_to_be_unchanged = set((schema, table) for schema, table in tables if schema not in (source_schema, target_schema))
new_tables_to_be_unchanged = set((schema, table) for schema, table in new_tables if schema not in (source_schema, target_schema))
assert no_original
assert any_target
assert original_tables_to_be_unchanged == new_tables_to_be_unchanged
physical_table["CustomSql"]["SqlQuery"] = renamed_sql
yield {
'dataset_id': dataset['DataSetId'],
'dataset_link': dataset_link,
'physical_table_id': physical_table_id,
'type': 'sql',
'source': original_sql,
'target': rename_schema(original_sql, source_schema, target_schema),
'error': '',
}
session_opts = {'profile_name': aws_profile} if aws_profile is not None else {}
session = boto3.Session(**session_opts)
client = session.client("quicksight")
dataset_ids = \
(dataset_id,) if dataset_id is not None else \
all_dataset_ids(client)
updated = 0
with \
csv_output_report() as writer, \
Progress(
SpinnerColumn(finished_text='[green]✔'),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
MofNCompleteColumn(),
'[bright_yellow]Updated: {task.fields[updated]}',
TimeRemainingColumn(),
) as progress:
task = progress.add_task(("[green]\\[DRY RUN][/green] " if dry_run else "") + 'Updating datasets...', total=len(dataset_ids), updated=0)
for dataset in datasets(client, progress.console, dataset_ids):
dataset_changes = tuple(modify_dataset_dict_if_needed(progress.console, dataset))
non_errored_changes = [not dataset_change['error'] for dataset_change in dataset_changes]
if non_errored_changes and not dry_run:
if not no_prompt:
input("Press enter to update the dataset on Quicksight")
try:
client.update_data_set(
AwsAccountId=account_id,
**{
x: v
for x, v in dataset.items()
if x
not in [
"Arn",
"CreatedTime",
"LastUpdatedTime",
"OutputColumns",
"ConsumedSpiceCapacityInBytes",
]
},
)
except Exception as e:
progress.console.print(f"⚠️ Failed to update dataset: {e}")
for dataset_change in dataset_changes:
dataset_change['error'] = f'Failed to update dataset: {e}'
for dataset_change in dataset_changes:
writer.writerow(dataset_change)
non_errored_changes_post_update = [not dataset_change['error'] for dataset_change in dataset_changes]
updated += 1 if non_errored_changes_post_update else 0
progress.advance(task)
progress.update(task, updated=updated)