-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterface.py
More file actions
778 lines (721 loc) · 36.9 KB
/
Copy pathinterface.py
File metadata and controls
778 lines (721 loc) · 36.9 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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
from dash import Dash, html, dcc, Output, Input, State, callback_context, MATCH, ALL
import dash_bootstrap_components as dbc
from interface_components.navbar import navbar
from interface_components.accordion import accordion
from interface_components.graph_plot import GraphPlot
from db.db import Database
from db.query_list import query_template_list
from preprocessing import Graph
import pandas as pd
import psycopg2
import plotly.graph_objs as go
import feffery_markdown_components as fmc
import json
from sql_formatter.core import format_sql
from whatif import whatif_query, modify_join_order, get_modifiable_list
class Interface:
def __init__(self):
self.app = Dash(
__name__,
external_stylesheets=[dbc.themes.ZEPHYR, dbc.icons.BOOTSTRAP],
)
self.set_layout()
self.set_callbacks()
self.db = None
self.qep = None
self.qep_cost = None
self.qep_rows = None
self.modified_query = None
self.modified_qep = None
self.modified_qep_cost = None
def set_layout(self):
self.app.layout = html.Div([
navbar(),
dbc.Container([
dbc.Row([
html.H3("DBMS Query Execution Plan"),
], className="my-5"),
dbc.Row([
dbc.Col([
html.H5([
html.B("Connection")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Row([
dbc.Label("Host", html_for="host", width=3),
dbc.Col(
dbc.Input(id="host", placeholder="Enter host", type="text", value="localhost"),
width=9,
)
], className="mb-3"),
dbc.Row([
dbc.Label("Port", html_for="port", width=3),
dbc.Col(
dbc.Input(id="port", placeholder="Enter port", type="number", value=5432),
width=9,
)
], className="mb-3"),
dbc.Row([
dbc.Label("Database", html_for="dbname", width=3),
dbc.Col(
dbc.Input(id="dbname", placeholder="Enter database name", type="text",
value="TPC-H"),
width=9,
)
], className="mb-3"),
dbc.Row([
dbc.Label("User", html_for="user", width=3),
dbc.Col(
dbc.Input(id="user", placeholder="Enter user", type="text", value="postgres"),
width=9,
)
], className="mb-3"),
dbc.Row([
dbc.Label("Password", html_for="password", width=3),
dbc.Col(
dbc.Input(id="password", placeholder="Enter password", type="password", value="admin"),
width=9,
)
], className="mb-3"),
dbc.Button(["Connect", html.I(className="bi bi-database-fill-lock ms-2")], id="connect-button",
color="primary", className="my-3"),
dbc.Alert(id="connection-status", color="info", is_open=False)
], width=6),
dbc.Col([
html.H5([
html.B("Database Tables")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dcc.Loading(
id="loading-connection",
type="default",
children=[
html.P(id="table-time-taken", className="my-3"),
html.Div(
style={"maxHeight": "400px", "overflowY": "auto"},
children=[
dbc.Table(
id='table-schemas',
bordered=True,
hover=True,
responsive=True,
striped=True,
style={
"fontSize": "14px",
"padding": "2px",
"margin": "0",
"whiteSpace": "nowrap",
"overflow": "hidden",
"textOverflow": "ellipsis",
}
)
]
)
]
),
], width=6),
]),
html.Hr(),
dbc.Row([
dbc.Col([
html.H5([
html.B("SQL Query Input")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Row([
dbc.Label("Query Template", html_for="query-template", className="mb-3"),
dbc.Col(
dbc.Select(
id="query-template",
placeholder="Select a query template",
value=query_template_list[0]["value"],
options=query_template_list,
),
)
], className="mb-3"),
dbc.Row([
dbc.Label("Query", html_for="query-input", className="mb-3"),
dbc.Col(
dbc.Textarea(
id="query-input",
placeholder="Enter SQL query",
rows=7,
value=query_template_list[0]["value"]
),
),
], className="mb-3"),
dbc.Button(["Execute", html.I(className="bi bi-play-fill ms-2")], id="execute-button",
color="primary", className="my-3", disabled=True),
dbc.Alert(
id="query-status",
color="info",
is_open=False,
),
], width=6),
dbc.Col([
html.H5([
html.B("SQL Query Output")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Row([
dbc.Col(
dcc.Loading(
id="loading-query",
type="default",
children=[
html.P(id="query-time-taken", className="my-3"),
html.P(id="query-rows-count", className="my-3"),
html.Div(id="query-output", style={
"maxWidth": "100%",
"overflowX": "auto",
"maxHeight": "350px",
"overflowY": "auto"
})
]
),
),
]),
], width=6),
]),
html.Hr(),
dbc.Row([
dbc.Col([
html.H5([
html.B("QEP")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Button(["Get QEP", html.I(className="bi bi-filetype-json ms-2")], id="qep-button",
color="primary", className="my-3", disabled=True),
dbc.Alert(id="qep-status", color="info", is_open=False),
dbc.Row([
dbc.Col(
dcc.Loading(
id="loading-qep",
type="default",
children=[
html.P(id="qep-time-taken", className="my-3"),
fmc.FefferyMarkdown(
id="qep-output",
# codeTheme="coy",
codeBlockStyle={"maxHeight": "588px"},
codeStyle={"fontSize": "14px", "lineHeight": "1.5"},
),
]
),
),
], className="mb-3"),
], width=6),
dbc.Col([
html.H5([
html.B("QEP Graph")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Button(["Show QEP Graph", html.I(className="bi bi-diagram-3-fill ms-2")],
id="show-qep-graph", color="primary", className="my-3", disabled=True),
dbc.Alert(id="qep-graph-status", color="info", is_open=False),
dbc.Row([
dbc.Col(
dcc.Loading(
id="loading-qep-graph",
type="default",
children=[
html.P(id="qep-cost", className="my-3"),
html.P(id="qep-rows-estimate", className="my-3"),
html.Div(id="qep-graph", children=[
dcc.Graph(id="qep-interactive-graph", figure=go.Figure(),
style={"display": "none"}),
]),
]
),
),
], className="mb-3"),
], width=6),
]),
# Join Order Section
html.Hr(),
dbc.Row([
dbc.Col([
html.H5([
html.B("Modify Join Order")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Button(["View Join Orders", html.I(className="bi bi-search ms-2")], id="explore-join-order-btn", color="primary", className="my-3", disabled=True),
dcc.Loading(
id="loading-join-orders",
type="default",
children=[
dbc.Row(id="sortable-join-order-row"),
]
),
dbc.Row(
[
dbc.Col(
dbc.Button(["Preview Modified Join Orders", html.I(className="bi bi-eye ms-2")], id="submit-join-order-btn", color="primary", className="my-3"),
width="auto"
),
dbc.Col(
dbc.Button(["Reset Join Orders", html.I(className="bi bi-arrow-counterclockwise ms-2")], id="keep-original-query-btn", color="secondary", className="my-3"),
width="auto"
),
],
className="g-2", # Add spacing between the buttons
),
dcc.Loading(
id='loading-new-join-query',
type='default',
children=[
html.Div(id='new-join-order-query',
children=[
html.B(id='new-join-query-title', className="mt-3"),
fmc.FefferyMarkdown(
id='new-join-query-markdown',
codeTheme="atom-dark",
className="mt-3")
])
]
)
], width=12),
]),
# What-If Queries Section
html.Hr(),
dbc.Row([
dbc.Col([
html.H5([
html.B("Modify Node Type")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Row([
dbc.Col([
dbc.Row([
dbc.Label("Alternate Join Type", html_for="join-type-dropdown", width=6),
dbc.Col(
dbc.Select(
id='join-type-dropdown',
options=[
{'label': 'No modification', 'value': 'none'},
{'label': 'Hash Join', 'value': 'hash'},
{'label': 'Merge Join', 'value': 'merge'},
{'label': 'Nested Loop Join', 'value': 'nested'}
],
value='none',
),
width=6
),
]),
], className="mb-3", width=6),
dbc.Col([
dbc.Row([
dbc.Label("Alternate Scan Type", html_for="scan-type-dropdown", width=6),
dbc.Col(
dbc.Select(
id='scan-type-dropdown',
options=[
{'label': 'No modification', 'value': 'none'},
{'label': 'Sequential Scan', 'value': 'seq'},
{'label': 'Index Scan', 'value': 'index'},
{'label': 'Bitmap Scan', 'value': 'bitmap'}
],
value='none',
),
width=6
),
]),
], className="mb-3", width=6),
dbc.Col([
dbc.Row([
dbc.Label("Alternate Aggregate Type", html_for="aggregate-type-dropdown", width=6),
dbc.Col(
dbc.Select(
id='aggregate-type-dropdown',
options=[
{'label': 'No modification', 'value': 'hash'},
{'label': 'Disable Hash Aggregate', 'value': 'no_hash'}
],
value='hash',
),
width=6
),
]),
], className="mb-3", width=6),
]),
dbc.Button(["Execute Modified Query", html.I(className="bi bi-play-fill ms-2")],
id="execute-whatif-query-btn", color="primary", className="my-3", disabled=True),
dbc.Alert(id="whatif-query-status", color="info", is_open=False),
], width=12),
], className="mb-3"),
dcc.Loading(
id= 'loading-final-query',
type='default',
children=[
html.Div(id='final-query',
children= [
html.B(id='final-query-title', className="mt-3"),
# html.H5("Final SQL Query with all Settings:", className='mt-4'),
fmc.FefferyMarkdown(
id= 'final-query-markdown',
codeTheme="atom-dark",
className="my-3" )
])
]
),
dbc.Row([
dbc.Col([
html.H5([
html.B("AQP")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Row([
dbc.Col(
dcc.Loading(
id="loading-whatif-qep",
type="default",
children=[
fmc.FefferyMarkdown(
id="whatif-qep-output",
# codeTheme="coy",
codeBlockStyle={"maxHeight": "642px"},
codeStyle={"fontSize": "14px", "lineHeight": "1.5"},
),
]
),
)
], className="mb-3"),
], width=6),
dbc.Col([
html.H5([
html.B("AQP Graph")
], className="bg-light text-dark p-3 py-3 rounded-3 mb-3"),
dbc.Row([
dbc.Col(
dcc.Loading(
id="loading-whatif-qep-graph",
type="default",
children=[
html.P(id="whatif-cost", className="my-3"),
html.P(id="cost_difference", className="my-3"),
html.Div(id="whatif-qep-graph", children=[
dcc.Graph(id="updated-qep-graph", figure=go.Figure())
]),
html.Div(id="accordion-container")
]
),
)
], className="mb-3"),
], width=6),
], className="mb-5"),
dbc.Row(className="py-5"),
]),
])
def set_callbacks(self):
@self.app.callback(
Output("connection-status", "children"),
Output("connection-status", "color"),
Output("connection-status", "is_open"),
Output("table-schemas", "children"),
Output("table-time-taken", "children"),
Output("qep-button", "disabled"),
Output("execute-button", "disabled"),
Input("connect-button", "n_clicks"),
State("host", "value"),
State("port", "value"),
State("dbname", "value"),
State("user", "value"),
State("password", "value")
)
def connect_to_db(n_clicks, host, port, dbname, user, password):
if n_clicks is None:
return "", "info", False, None, "", True, True
try:
# Attempt to connect to the PostgreSQL database
self.db = Database(host, port, dbname, user, password)
self.db.connect()
# Analyze the database
result, analyze_time, error, _ = self.db.analyze()
# Query to list all tables in the connected database
tables, time_taken, error, _ = self.db.list_all_tables()
table_rows = []
time_taken = time_taken + analyze_time
for schema, table in tables:
columns = []
# Get the columns for each table
columns_result, time_taken_col, error, _ = self.db.list_columns(schema, table)
for row in columns_result:
columns.append(row[0])
time_taken += time_taken_col
# Get the exact number of rows
row_count, time_taken_row = self.db.get_rows(schema, table)
time_taken += time_taken_row
# Create a table row
table_rows.append(html.Tr([
html.Td(table),
html.Td(', '.join(columns)),
html.Td(row_count)
]))
# Define table header
table_header = [
html.Thead(html.Tr([
html.Th("Table"),
html.Th("Attributes"),
html.Th("Rows")
]))
]
# Combine header and body
table_body = [html.Tbody(table_rows)]
table_children = table_header + table_body
return ([html.I(className="bi bi-check-circle-fill me-2"), "Connected successfully! "],
"success", True, table_children, f"Time taken: {round(time_taken * 1000):,} ms", False,
False)
except psycopg2.OperationalError as e:
print(f"Connection failed: {e}")
return ([html.I(className="bi bi-x-octagon-fill me-2"), "Connection failed:",
fmc.FefferyMarkdown(markdownStr=f"```sh\n{e}\n```", codeTheme="atom-dark", className="mt-3")],
"danger", True, [], "", True, True)
@self.app.callback(
Output("query-input", "value"),
Input("query-template", "value")
)
def update_query_input(selected_template):
return selected_template
@self.app.callback(
Output("query-status", "children"),
Output("query-status", "color"),
Output("query-status", "is_open"),
Output("query-output", "children"),
Output("query-time-taken", "children"),
Output("query-rows-count", "children"),
Input("execute-button", "n_clicks"),
State("query-input", "value"),
)
def execute_query(n_clicks, query):
if n_clicks is None:
return "", "info", False, None, "", ""
try:
# Execute the query
result, time_taken, error, rows = self.db.execute_query(query)
if error:
raise psycopg2.Error(error)
# If the query returns results
if result:
df = pd.DataFrame(result, columns=[desc[0] for desc in self.db.cursor.description])
table = dbc.Table.from_dataframe(
df,
striped=True,
bordered=True,
hover=True,
style={
"fontSize": "14px",
"padding": "2px",
"margin": "0",
"whiteSpace": "nowrap",
"overflow": "hidden",
"textOverflow": "ellipsis",
}
)
return [html.I(className="bi bi-check-circle-fill me-2"),
"Query executed successfully!"], "success", True, table, f"Time taken: {round(time_taken * 1000):,} ms", f"Rows returned: {rows}"
else:
return [html.I(className="bi bi-check-circle-fill me-2"),
"Query executed successfully!"], "success", True, html.P(
"Query executed successfully!"), f"Time taken: {round(time_taken * 1000):,} ms", "No rows returned"
except psycopg2.Error as e:
# Split error message by lines and format with HTML line breaks
return [
html.I(className="bi bi-x-octagon-fill me-2"),
"Error executing query:",
fmc.FefferyMarkdown(markdownStr=f"```sh\n{str(e)}\n```", codeTheme="atom-dark", className="mt-3")
], "danger", True, None, "", ""
@self.app.callback(
Output("qep-status", "children"),
Output("qep-status", "color"),
Output("qep-status", "is_open"),
Output("qep-output", "markdownStr"),
Output("qep-time-taken", "children"),
Output("show-qep-graph", "disabled"),
Output("execute-whatif-query-btn", "disabled"),
Output("explore-join-order-btn", "disabled"),
Input("qep-button", "n_clicks"),
State("query-input", "value"),
)
def get_qep(n_clicks, query):
if n_clicks is None:
return "", "info", False, None, "", True, True, True
try:
# Get the query execution plan
self.qep, self.qep_cost, self.qep_rows, time_taken, error = self.db.get_qep(query)
if error:
raise psycopg2.Error(error)
return ([html.I(className="bi bi-check-circle-fill me-2"),
"Query execution plan generated successfully!"], "success",
True, f"```json\n{self.qep}\n```", f"Time taken: {round(time_taken * 1000):,} ms", False, False, False)
except psycopg2.Error as e:
return [html.I(className="bi bi-x-octagon-fill me-2"), "Error generating query execution plan:",
fmc.FefferyMarkdown(markdownStr=f"```sh\n{str(e)}\n```", codeTheme="atom-dark",
className="mt-3")], "danger", True, "", "", True, True
@self.app.callback(
Output("qep-graph", "children"),
Output("qep-graph-status", "children"),
Output("qep-graph-status", "color"),
Output("qep-graph-status", "is_open"),
Output("qep-cost", "children"),
Output("qep-rows-estimate", "children"),
Input("show-qep-graph", "n_clicks"),
)
def show_qep_graph(n_clicks):
if n_clicks is None:
return None, "", "info", False, "", ""
if self.qep:
qep_dict = json.loads(self.qep)
graph = Graph()
graph.parse_qep(qep_dict)
# graph.print_graph()
graph_plot = GraphPlot(graph.build_graph())
return (
dcc.Graph(id="qep-interactive-graph", figure=graph_plot.plot_graph(), style={"height": "555px"}),
[
html.I(className="bi bi-check-circle-fill me-2"),
"QEP Graph generated successfully!"
],
"success",
True,
html.Span([
"QEP Query Cost: ",
html.Strong(f'{round(self.qep_cost):,}')
]),
f'Query Planner Output Rows Estimate: {self.qep_rows:,}'
)
else:
return None, [html.I(className="bi bi-x-octagon-fill me-2"),
"No QEP available to generate graph"], "danger", True, "", ""
# To show the join order options
@self.app.callback(
Output('sortable-join-order-row', 'children'),
Output('submit-join-order-btn', 'style'),
Output("keep-original-query-btn", 'style'),
Input('explore-join-order-btn', 'n_clicks'),
State('query-input', 'value'),
)
def display_join_orders(n_clicks, query):
if n_clicks is None or n_clicks == 0:
return None, {"display": "none"}, {"display": "none"}
# Get join order from backend
join_orders = get_modifiable_list(query)
order_elements = []
count = 0
for idx, join_order in enumerate(join_orders):
badge_list = join_order.split(',')
badge_elements = []
for badge in badge_list:
badge_elements.append(
dbc.Badge(badge, className="ms-2", pill=True, color="primary")
)
# Wrap each join order in a Bootstrap Card for better UI
order_elements.append(
dbc.Col(
dbc.Card(
children=[
dbc.CardHeader(children=[
"Default Join Order: ",
*[badge for badge in badge_elements],
]),
dbc.CardBody([
html.Div([
dbc.Input(
type="text",
id={'type': 'join-order-textinput', 'index': idx},
placeholder="Relation A, Relation B, Relation C",
className="form-control",
value=join_order
),
html.Label("Modify the join order separated by commas")
], className="form-floating mb-3"),
]),
], className="card border-primary mb-3"
),
width=6
)
)
if len(order_elements) == 0:
error_message = dbc.Alert(
"Join order modification not available for this query",
color="danger", # Set the alert theme to "danger" for an error message
className="my-3"
)
self.modified_query = None
return error_message, {"display": "none"}, {"display": "none"}
return order_elements, {"display": "block"}, {"display": "block"}
@self.app.callback(
Output('new-join-query-markdown', 'markdownStr'),
Output('new-join-query-title', 'children'),
[Input('submit-join-order-btn', 'n_clicks'),
Input('keep-original-query-btn', 'n_clicks')],
State({'type': 'join-order-textinput', 'index': ALL}, 'value'),
State("query-input", "value"),
prevent_initial_call=True
)
def generate_new_sql_query(n_clicks_m, n_clicks_o, updated_orders, query):
ctx = callback_context
if not ctx:
return None, None
triggered_id = ctx.triggered[0]["prop_id"].split(".")[0]
if triggered_id == 'keep-original-query-btn' and (n_clicks_o is not None or n_clicks_o != 0):
self.modified_query = query
elif triggered_id == 'submit-join-order-btn' and n_clicks_m is not None or n_clicks_m != 0:
updated_orders = [order.split(',') for order in updated_orders]
# Remove any empty strings
updated_orders = [[item.strip() for item in order if item.strip()] for order in updated_orders]
self.modified_query = modify_join_order(query, updated_orders)
else:
return None, None
# print(format_sql(self.modified_query))
return f"```sql\n{format_sql(self.modified_query)}\n```", "Modified SQL Query:"
@self.app.callback(
Output('final-query-markdown', 'markdownStr'),
Output("whatif-query-status", "children"),
Output("whatif-query-status", "color"),
Output("whatif-query-status", "is_open"),
Output("whatif-qep-output", "markdownStr"),
Output("whatif-qep-graph", "children"),
Output("whatif-cost", "children"),
Output("cost_difference", "children"),
Output("final-query-title", "children"),
Output("accordion-container", "children"),
Input("execute-whatif-query-btn", "n_clicks"),
State("join-type-dropdown", "value"),
State("scan-type-dropdown", "value"),
State("aggregate-type-dropdown", "value"),
State("query-input", "value")
)
def execute_whatif_query(n_clicks, join_type, scan_type, aggregate_type, query):
if n_clicks is None:
return None, "", "info", False, "", "", "", "", None, None
change_order = False
if self.modified_query is not None:
query = self.modified_query
change_order = True
try:
# Send the What-If parameters and query to the backend to get the new QEP
self.modified_qep, self.modified_qep_cost, modified_qep_rows, modified_execution_time, error, new_query = whatif_query(
self.db, query, join_type, scan_type, aggregate_type, change_order)
if error:
raise Exception(error)
# Displaying Updated QEP in JSON format
qep_markdown = f"```json\n{self.modified_qep}\n```"
# Creating QEP Graph from the retrieved graph data
if self.modified_qep:
modified_qep_dict = json.loads(self.modified_qep)
modified_graph = Graph()
modified_graph.parse_qep(modified_qep_dict)
modified_graph_plot = GraphPlot(modified_graph.build_graph())
modified_qep_graph = dcc.Graph(id="updated-qep-graph", figure=modified_graph_plot.plot_graph(), style={"height": "555px"})
diff = self.qep_cost - self.modified_qep_cost
if diff == 0:
color = "info"
performance = 0
else:
performance = 100 * diff / self.qep_cost
color = "success" if performance >= 0 else "danger"
return f"```sql\n{format_sql(new_query)}\n```", [
html.I(className="bi bi-check-circle-fill me-2"), "What-If Query executed successfully!"
], "success", True, qep_markdown, modified_qep_graph, html.Span([
"AQP Query Cost: ", html.Strong(f'{round(self.modified_qep_cost):,}')
]), html.Span(f'Performance: {performance:+.4f}%', className=f'text-{color}'), "Final Modified SQL Query:", accordion()
except Exception as e:
# Handle any errors that occurred
return None, [
html.I(className="bi bi-x-octagon-fill me-2"),
"Error executing What-If query:",
fmc.FefferyMarkdown(markdownStr=f"```sh\n{str(e)}\n```", codeTheme="atom-dark",
className="mt-3")], "danger", True, "", "", "", "", None, None
def run(self):
self.app.run(debug=True)