Spaces:
Runtime error

NagaPrajwalith commited on
Commit
91e01ff
Β·
verified Β·
1 Parent(s): c786dc7

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +377 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,379 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import csv
3
+ import io
4
+ import re
5
+ import json
6
 
7
+ st.set_page_config(page_title="Databricks DDL + Grants", page_icon="πŸš€", layout="wide")
8
+
9
+ st.markdown("""
10
+ <style>
11
+ .stApp {
12
+ background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
13
+ color: white;
14
+ }
15
+ header {visibility: hidden;}
16
+ h1 {
17
+ font-family: 'Inter', sans-serif;
18
+ font-weight: 800;
19
+ background: -webkit-linear-gradient(#f9d423, #ff4e50);
20
+ -webkit-background-clip: text;
21
+ -webkit-text-fill-color: transparent;
22
+ text-align: center;
23
+ margin-bottom: 1rem;
24
+ margin-top: -3rem;
25
+ }
26
+ .stButton>button {
27
+ background: linear-gradient(90deg, #ff4e50 0%, #f9d423 100%);
28
+ border: none;
29
+ border-radius: 8px;
30
+ color: white;
31
+ padding: 0.6rem 2rem;
32
+ font-size: 1.1rem;
33
+ font-weight: bold;
34
+ transition: transform 0.2s, box-shadow 0.2s;
35
+ }
36
+ .stButton>button:hover {
37
+ transform: translateY(-2px);
38
+ box-shadow: 0 4px 15px rgba(255, 78, 80, 0.4);
39
+ }
40
+ .result-box {
41
+ background: rgba(255, 255, 255, 0.1);
42
+ padding: 1.5rem;
43
+ border-radius: 10px;
44
+ border: 1px solid rgba(255, 255, 255, 0.2);
45
+ backdrop-filter: blur(10px);
46
+ margin-top: 1rem;
47
+ }
48
+ </style>
49
+ """, unsafe_allow_html=True)
50
+
51
+ st.markdown("<h1>Databricks DDL + Grants Generator πŸš€</h1>", unsafe_allow_html=True)
52
+ st.markdown(
53
+ "<p style='text-align: center; font-size: 1.1rem; opacity: 0.9; margin-bottom: 2rem;'>"
54
+ "Upload your CSV DDL file β€” get a transformed DDL notebook and auto-generated GRANT scripts in one go."
55
+ "</p>",
56
+ unsafe_allow_html=True,
57
+ )
58
+
59
+ # ── Grant principals ──
60
+ TABLE_GRANTS = [
61
+ ("SELECT, MODIFY", "Team.App.MDIP.Core.Team"),
62
+ ("SELECT, MODIFY", "svciscpkpi@pepsico.com"),
63
+ ("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer"),
64
+ ("SELECT, MODIFY", "svcCViscpkrptprd@pepsico.com"),
65
+ ("SELECT, MODIFY", "Team.App.PBNA.TDQKETSPROD.ADB"),
66
+ ("SELECT, MODIFY", "Team.App.PBNA.TDQKETS.ADB"),
67
+ ("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader"),
68
+ ("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor"),
69
+ ]
70
+
71
+
72
+ # ── Helpers ──
73
+
74
+ def transform_ddl(ddl: str) -> str:
75
+ """Apply the three standard QA→PROD transformations."""
76
+ ddl = re.sub(
77
+ r'CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS)',
78
+ 'CREATE TABLE IF NOT EXISTS ',
79
+ ddl,
80
+ flags=re.IGNORECASE,
81
+ )
82
+ ddl = ddl.replace('uc_qa_apac_mdip_01', 'uc_prod_apac_mdip_01')
83
+ ddl = re.sub(r'(?i)\bUSING\s+delta\b[ \t]*\n?', '', ddl)
84
+ return ddl.strip()
85
+
86
+
87
+ def extract_table_name(ddl: str) -> str | None:
88
+ """Pull the fully-qualified table name out of a CREATE TABLE statement."""
89
+ match = re.search(
90
+ r'CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\w]+(?:\.[`\w]+)+)',
91
+ ddl,
92
+ flags=re.IGNORECASE,
93
+ )
94
+ if match:
95
+ return match.group(1).replace('`', '')
96
+ return None
97
+
98
+
99
+ def build_table_grants(full_name: str) -> str:
100
+ return "\n".join(
101
+ f"GRANT {privs} ON TABLE {full_name} TO `{principal}`;"
102
+ for privs, principal in TABLE_GRANTS
103
+ )
104
+
105
+
106
+ def create_ddl_notebook(statements: list) -> str:
107
+ """Format transformed DDLs as a Databricks .sql notebook."""
108
+ output = ["-- Databricks notebook source"]
109
+ for s in statements:
110
+ output.append(s)
111
+ output.append("-- COMMAND ----------")
112
+ if output[-1] == "-- COMMAND ----------":
113
+ output.pop()
114
+ return '\n\n'.join(output)
115
+
116
+
117
+ def create_combined_sql(ddl_statements: list, grants_sql: str) -> str:
118
+ """Single .sql file: DDL section first, then GRANT section."""
119
+ output = ["-- Databricks notebook source"]
120
+ for s in ddl_statements:
121
+ output.append(s)
122
+ output.append("-- COMMAND ----------")
123
+ # grants section
124
+ for line in grants_sql.split('\n'):
125
+ output.append(line)
126
+ output.append("-- COMMAND ----------")
127
+ if output[-1] == "-- COMMAND ----------":
128
+ output.pop()
129
+ return '\n\n'.join(output)
130
+
131
+
132
+ def create_combined_notebook(ddl_statements: list, grants_sql: str, title: str) -> str:
133
+ """Single .ipynb with DDL cells first, then one grant cell per table."""
134
+ cells = [
135
+ {
136
+ "cell_type": "markdown",
137
+ "metadata": {},
138
+ "source": [f"# {title}\n", "\n", "DDL statements followed by GRANT scripts.\n"],
139
+ }
140
+ ]
141
+
142
+ # ── DDL cells ──
143
+ cells.append({
144
+ "cell_type": "markdown",
145
+ "metadata": {},
146
+ "source": ["## DDL β€” Create Tables\n"],
147
+ })
148
+ for stmt in ddl_statements:
149
+ lines = stmt.split('\n')
150
+ source_lines = [line + "\n" for line in lines]
151
+ if source_lines:
152
+ source_lines[-1] = source_lines[-1].rstrip("\n")
153
+ cells.append({
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": source_lines,
157
+ "outputs": [],
158
+ "execution_count": None,
159
+ })
160
+
161
+ # ── Grant cells ──
162
+ cells.append({
163
+ "cell_type": "markdown",
164
+ "metadata": {},
165
+ "source": ["## GRANT Scripts\n"],
166
+ })
167
+ grant_blocks = re.split(r'(?=-- ==========)', grants_sql.strip())
168
+ grant_blocks = [b.strip() for b in grant_blocks if b.strip()]
169
+ for block in grant_blocks:
170
+ lines = block.split('\n')
171
+ source_lines = [line + "\n" for line in lines]
172
+ if source_lines:
173
+ source_lines[-1] = source_lines[-1].rstrip("\n")
174
+ cells.append({
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": source_lines,
178
+ "outputs": [],
179
+ "execution_count": None,
180
+ })
181
+
182
+ notebook = {
183
+ "nbformat": 4,
184
+ "nbformat_minor": 0,
185
+ "metadata": {
186
+ "application/vnd.databricks.v1+notebook": {
187
+ "language": "sql",
188
+ "notebookName": title,
189
+ "notebookOrigID": 0,
190
+ },
191
+ "kernelspec": {"display_name": "SQL", "language": "sql", "name": "sql"},
192
+ "language_info": {"name": "sql"},
193
+ },
194
+ "cells": cells,
195
+ }
196
+ return json.dumps(notebook, indent=2)
197
+
198
+
199
+ def create_grants_notebook(sql_statements: str, title: str) -> str:
200
+ """Format GRANT scripts as a Databricks .ipynb notebook."""
201
+ cells = [
202
+ {
203
+ "cell_type": "markdown",
204
+ "metadata": {},
205
+ "source": [f"# {title}\n", "\n", "Auto-generated GRANT scripts β€” run each cell or Run All.\n"],
206
+ }
207
+ ]
208
+
209
+ blocks = re.split(r'(?=-- ==========)', sql_statements.strip())
210
+ blocks = [b.strip() for b in blocks if b.strip()]
211
+
212
+ for block in blocks:
213
+ lines = block.split('\n')
214
+ source_lines = [line + "\n" for line in lines]
215
+ if source_lines:
216
+ source_lines[-1] = source_lines[-1].rstrip("\n")
217
+ cells.append({
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": source_lines,
221
+ "outputs": [],
222
+ "execution_count": None,
223
+ })
224
+
225
+ notebook = {
226
+ "nbformat": 4,
227
+ "nbformat_minor": 0,
228
+ "metadata": {
229
+ "application/vnd.databricks.v1+notebook": {
230
+ "language": "sql",
231
+ "notebookName": title,
232
+ "notebookOrigID": 0,
233
+ },
234
+ "kernelspec": {"display_name": "SQL", "language": "sql", "name": "sql"},
235
+ "language_info": {"name": "sql"},
236
+ },
237
+ "cells": cells,
238
+ }
239
+ return json.dumps(notebook, indent=2)
240
+
241
+
242
+ # ── Upload ──
243
+ uploaded_file = st.file_uploader("πŸ“‚ Upload CSV DDL file", type="csv")
244
+
245
+ if uploaded_file is not None:
246
+ content = uploaded_file.getvalue().decode('utf-8')
247
+ reader = csv.reader(io.StringIO(content))
248
+
249
+ try:
250
+ next(reader) # skip header row
251
+ except StopIteration:
252
+ pass
253
+
254
+ transformed_ddls = []
255
+ table_names = []
256
+
257
+ for row in reader:
258
+ if not row:
259
+ continue
260
+ ddl = row[0].strip()
261
+ if not ddl:
262
+ continue
263
+ transformed = transform_ddl(ddl)
264
+ transformed_ddls.append(transformed)
265
+ name = extract_table_name(transformed)
266
+ if name:
267
+ table_names.append(name)
268
+
269
+ if not transformed_ddls:
270
+ st.error("❌ No DDL statements found in the uploaded file.")
271
+ else:
272
+ # ── Summary banner ──
273
+ st.markdown(f"""
274
+ <div class="result-box">
275
+ <h3 style="margin-top: 0; color: #4ADE80;">✨ Transformation Complete!</h3>
276
+ <p style="font-size: 1.1rem;"><strong>Processed Tables:</strong> {len(transformed_ddls)}</p>
277
+ <ul style="opacity: 0.9;">
278
+ <li>βœ”οΈ Added <code>IF NOT EXISTS</code> to all tables</li>
279
+ <li>��️ Switched catalog to <strong>PROD</strong> (<code>uc_prod_apac_mdip_01</code>)</li>
280
+ <li>βœ”οΈ Cleaned redundant <code>USING delta</code> clauses</li>
281
+ <li>βœ”οΈ Auto-generated GRANT scripts for all tables</li>
282
+ </ul>
283
+ </div>
284
+ <br>
285
+ """, unsafe_allow_html=True)
286
+
287
+ # ════════════════════════════════════════
288
+ # STEP 1 β€” DDL Notebook
289
+ # ════════════════════════════════════════
290
+ st.markdown("## πŸ“„ Step 1 β€” DDL Notebook")
291
+ st.caption("Transformed CREATE TABLE statements ready to import into Databricks.")
292
+
293
+ ddl_sql = create_ddl_notebook(transformed_ddls)
294
+ st.code(ddl_sql, language="sql")
295
+
296
+ col1, col2, col3 = st.columns([1, 2, 1])
297
+ with col2:
298
+ st.download_button(
299
+ label="⬇️ Download DDL Notebook (.sql)",
300
+ data=ddl_sql,
301
+ file_name="PROD_DDL_Notebook.sql",
302
+ mime="text/plain",
303
+ use_container_width=True,
304
+ key="dl_ddl",
305
+ )
306
+
307
+ st.markdown("---")
308
+
309
+ # ════════════════════════════════════════
310
+ # STEP 2 β€” Table Grant Scripts
311
+ # ════════════════════════════════════════
312
+ st.markdown("## πŸ” Step 2 β€” Table Grant Scripts")
313
+
314
+ if not table_names:
315
+ st.warning("⚠️ Could not extract table names from the DDL statements.")
316
+ else:
317
+ st.markdown(f"**{len(table_names)} table(s) detected:**")
318
+ st.code("\n".join(table_names))
319
+
320
+ grant_blocks = [
321
+ f"-- ========== {name} ==========\n{build_table_grants(name)}"
322
+ for name in table_names
323
+ ]
324
+ combined_grants = "\n\n".join(grant_blocks)
325
+
326
+ st.markdown("### Generated GRANT Statements")
327
+ st.code(combined_grants, language="sql")
328
+
329
+ nb = create_grants_notebook(combined_grants, "Table_Grant_Scripts")
330
+ col1, col2 = st.columns(2)
331
+ with col1:
332
+ st.download_button(
333
+ label="⬇️ Download Grants Notebook (.ipynb)",
334
+ data=nb,
335
+ file_name="table_grant_scripts.ipynb",
336
+ mime="application/x-ipynb+json",
337
+ use_container_width=True,
338
+ key="dl_grants_ipynb",
339
+ )
340
+ with col2:
341
+ st.download_button(
342
+ label="⬇️ Download Grants Script (.sql)",
343
+ data=combined_grants,
344
+ file_name="table_grant_scripts.sql",
345
+ mime="text/plain",
346
+ use_container_width=True,
347
+ key="dl_grants_sql",
348
+ )
349
+
350
+ st.markdown("---")
351
+
352
+ # ════════════════════════════════════════
353
+ # STEP 3 β€” Combined DDL + Grants
354
+ # ════════════════════════════════════════
355
+ st.markdown("## πŸ“¦ Step 3 β€” Combined DDL + Grants (Single File)")
356
+ st.caption("Everything in one file: CREATE TABLE statements first, then all GRANT scripts.")
357
+
358
+ combined_nb = create_combined_notebook(transformed_ddls, combined_grants, "DDL_And_Grants")
359
+ combined_sql = create_combined_sql(transformed_ddls, combined_grants)
360
+
361
+ col1, col2 = st.columns(2)
362
+ with col1:
363
+ st.download_button(
364
+ label="⬇️ Download Combined Notebook (.ipynb)",
365
+ data=combined_nb,
366
+ file_name="DDL_And_Grants.ipynb",
367
+ mime="application/x-ipynb+json",
368
+ use_container_width=True,
369
+ key="dl_combined_ipynb",
370
+ )
371
+ with col2:
372
+ st.download_button(
373
+ label="⬇️ Download Combined Script (.sql)",
374
+ data=combined_sql,
375
+ file_name="DDL_And_Grants.sql",
376
+ mime="text/plain",
377
+ use_container_width=True,
378
+ key="dl_combined_sql",
379
+ )