Spaces:
Runtime error
Runtime error
File size: 13,357 Bytes
d58ee71 91e01ff d58ee71 91e01ff | 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 | import streamlit as st
import csv
import io
import re
import json
st.set_page_config(page_title="Databricks DDL + Grants", page_icon="π", layout="wide")
st.markdown("""
<style>
.stApp {
background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
color: white;
}
header {visibility: hidden;}
h1 {
font-family: 'Inter', sans-serif;
font-weight: 800;
background: -webkit-linear-gradient(#f9d423, #ff4e50);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
margin-bottom: 1rem;
margin-top: -3rem;
}
.stButton>button {
background: linear-gradient(90deg, #ff4e50 0%, #f9d423 100%);
border: none;
border-radius: 8px;
color: white;
padding: 0.6rem 2rem;
font-size: 1.1rem;
font-weight: bold;
transition: transform 0.2s, box-shadow 0.2s;
}
.stButton>button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(255, 78, 80, 0.4);
}
.result-box {
background: rgba(255, 255, 255, 0.1);
padding: 1.5rem;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
margin-top: 1rem;
}
</style>
""", unsafe_allow_html=True)
st.markdown("<h1>Databricks DDL + Grants Generator π</h1>", unsafe_allow_html=True)
st.markdown(
"<p style='text-align: center; font-size: 1.1rem; opacity: 0.9; margin-bottom: 2rem;'>"
"Upload your CSV DDL file β get a transformed DDL notebook and auto-generated GRANT scripts in one go."
"</p>",
unsafe_allow_html=True,
)
# ββ Grant principals ββ
TABLE_GRANTS = [
("SELECT, MODIFY", "Team.App.MDIP.Core.Team"),
("SELECT, MODIFY", "svciscpkpi@pepsico.com"),
("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer"),
("SELECT, MODIFY", "svcCViscpkrptprd@pepsico.com"),
("SELECT, MODIFY", "Team.App.PBNA.TDQKETSPROD.ADB"),
("SELECT, MODIFY", "Team.App.PBNA.TDQKETS.ADB"),
("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader"),
("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor"),
]
# ββ Helpers ββ
def transform_ddl(ddl: str) -> str:
"""Apply the three standard QAβPROD transformations."""
ddl = re.sub(
r'CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS)',
'CREATE TABLE IF NOT EXISTS ',
ddl,
flags=re.IGNORECASE,
)
ddl = ddl.replace('uc_qa_apac_mdip_01', 'uc_prod_apac_mdip_01')
ddl = re.sub(r'(?i)\bUSING\s+delta\b[ \t]*\n?', '', ddl)
return ddl.strip()
def extract_table_name(ddl: str) -> str | None:
"""Pull the fully-qualified table name out of a CREATE TABLE statement."""
match = re.search(
r'CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([`\w]+(?:\.[`\w]+)+)',
ddl,
flags=re.IGNORECASE,
)
if match:
return match.group(1).replace('`', '')
return None
def build_table_grants(full_name: str) -> str:
return "\n".join(
f"GRANT {privs} ON TABLE {full_name} TO `{principal}`;"
for privs, principal in TABLE_GRANTS
)
def create_ddl_notebook(statements: list) -> str:
"""Format transformed DDLs as a Databricks .sql notebook."""
output = ["-- Databricks notebook source"]
for s in statements:
output.append(s)
output.append("-- COMMAND ----------")
if output[-1] == "-- COMMAND ----------":
output.pop()
return '\n\n'.join(output)
def create_combined_sql(ddl_statements: list, grants_sql: str) -> str:
"""Single .sql file: DDL section first, then GRANT section."""
output = ["-- Databricks notebook source"]
for s in ddl_statements:
output.append(s)
output.append("-- COMMAND ----------")
# grants section
for line in grants_sql.split('\n'):
output.append(line)
output.append("-- COMMAND ----------")
if output[-1] == "-- COMMAND ----------":
output.pop()
return '\n\n'.join(output)
def create_combined_notebook(ddl_statements: list, grants_sql: str, title: str) -> str:
"""Single .ipynb with DDL cells first, then one grant cell per table."""
cells = [
{
"cell_type": "markdown",
"metadata": {},
"source": [f"# {title}\n", "\n", "DDL statements followed by GRANT scripts.\n"],
}
]
# ββ DDL cells ββ
cells.append({
"cell_type": "markdown",
"metadata": {},
"source": ["## DDL β Create Tables\n"],
})
for stmt in ddl_statements:
lines = stmt.split('\n')
source_lines = [line + "\n" for line in lines]
if source_lines:
source_lines[-1] = source_lines[-1].rstrip("\n")
cells.append({
"cell_type": "code",
"metadata": {},
"source": source_lines,
"outputs": [],
"execution_count": None,
})
# ββ Grant cells ββ
cells.append({
"cell_type": "markdown",
"metadata": {},
"source": ["## GRANT Scripts\n"],
})
grant_blocks = re.split(r'(?=-- ==========)', grants_sql.strip())
grant_blocks = [b.strip() for b in grant_blocks if b.strip()]
for block in grant_blocks:
lines = block.split('\n')
source_lines = [line + "\n" for line in lines]
if source_lines:
source_lines[-1] = source_lines[-1].rstrip("\n")
cells.append({
"cell_type": "code",
"metadata": {},
"source": source_lines,
"outputs": [],
"execution_count": None,
})
notebook = {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"application/vnd.databricks.v1+notebook": {
"language": "sql",
"notebookName": title,
"notebookOrigID": 0,
},
"kernelspec": {"display_name": "SQL", "language": "sql", "name": "sql"},
"language_info": {"name": "sql"},
},
"cells": cells,
}
return json.dumps(notebook, indent=2)
def create_grants_notebook(sql_statements: str, title: str) -> str:
"""Format GRANT scripts as a Databricks .ipynb notebook."""
cells = [
{
"cell_type": "markdown",
"metadata": {},
"source": [f"# {title}\n", "\n", "Auto-generated GRANT scripts β run each cell or Run All.\n"],
}
]
blocks = re.split(r'(?=-- ==========)', sql_statements.strip())
blocks = [b.strip() for b in blocks if b.strip()]
for block in blocks:
lines = block.split('\n')
source_lines = [line + "\n" for line in lines]
if source_lines:
source_lines[-1] = source_lines[-1].rstrip("\n")
cells.append({
"cell_type": "code",
"metadata": {},
"source": source_lines,
"outputs": [],
"execution_count": None,
})
notebook = {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"application/vnd.databricks.v1+notebook": {
"language": "sql",
"notebookName": title,
"notebookOrigID": 0,
},
"kernelspec": {"display_name": "SQL", "language": "sql", "name": "sql"},
"language_info": {"name": "sql"},
},
"cells": cells,
}
return json.dumps(notebook, indent=2)
# ββ Upload ββ
uploaded_file = st.file_uploader("π Upload CSV DDL file", type="csv")
if uploaded_file is not None:
content = uploaded_file.getvalue().decode('utf-8')
reader = csv.reader(io.StringIO(content))
try:
next(reader) # skip header row
except StopIteration:
pass
transformed_ddls = []
table_names = []
for row in reader:
if not row:
continue
ddl = row[0].strip()
if not ddl:
continue
transformed = transform_ddl(ddl)
transformed_ddls.append(transformed)
name = extract_table_name(transformed)
if name:
table_names.append(name)
if not transformed_ddls:
st.error("β No DDL statements found in the uploaded file.")
else:
# ββ Summary banner ββ
st.markdown(f"""
<div class="result-box">
<h3 style="margin-top: 0; color: #4ADE80;">β¨ Transformation Complete!</h3>
<p style="font-size: 1.1rem;"><strong>Processed Tables:</strong> {len(transformed_ddls)}</p>
<ul style="opacity: 0.9;">
<li>βοΈ Added <code>IF NOT EXISTS</code> to all tables</li>
<li>βοΈ Switched catalog to <strong>PROD</strong> (<code>uc_prod_apac_mdip_01</code>)</li>
<li>βοΈ Cleaned redundant <code>USING delta</code> clauses</li>
<li>βοΈ Auto-generated GRANT scripts for all tables</li>
</ul>
</div>
<br>
""", unsafe_allow_html=True)
# ββββββββββββββββββββββββββββββββββββββββ
# STEP 1 β DDL Notebook
# ββββββββββββββββββββββββββββββββββββββββ
st.markdown("## π Step 1 β DDL Notebook")
st.caption("Transformed CREATE TABLE statements ready to import into Databricks.")
ddl_sql = create_ddl_notebook(transformed_ddls)
st.code(ddl_sql, language="sql")
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.download_button(
label="β¬οΈ Download DDL Notebook (.sql)",
data=ddl_sql,
file_name="PROD_DDL_Notebook.sql",
mime="text/plain",
use_container_width=True,
key="dl_ddl",
)
st.markdown("---")
# ββββββββββββββββββββββββββββββββββββββββ
# STEP 2 β Table Grant Scripts
# ββββββββββββββββββββββββββββββββββββββββ
st.markdown("## π Step 2 β Table Grant Scripts")
if not table_names:
st.warning("β οΈ Could not extract table names from the DDL statements.")
else:
st.markdown(f"**{len(table_names)} table(s) detected:**")
st.code("\n".join(table_names))
grant_blocks = [
f"-- ========== {name} ==========\n{build_table_grants(name)}"
for name in table_names
]
combined_grants = "\n\n".join(grant_blocks)
st.markdown("### Generated GRANT Statements")
st.code(combined_grants, language="sql")
nb = create_grants_notebook(combined_grants, "Table_Grant_Scripts")
col1, col2 = st.columns(2)
with col1:
st.download_button(
label="β¬οΈ Download Grants Notebook (.ipynb)",
data=nb,
file_name="table_grant_scripts.ipynb",
mime="application/x-ipynb+json",
use_container_width=True,
key="dl_grants_ipynb",
)
with col2:
st.download_button(
label="β¬οΈ Download Grants Script (.sql)",
data=combined_grants,
file_name="table_grant_scripts.sql",
mime="text/plain",
use_container_width=True,
key="dl_grants_sql",
)
st.markdown("---")
# ββββββββββββββββββββββββββββββββββββββββ
# STEP 3 β Combined DDL + Grants
# ββββββββββββββββββββββββββββββββββββββββ
st.markdown("## π¦ Step 3 β Combined DDL + Grants (Single File)")
st.caption("Everything in one file: CREATE TABLE statements first, then all GRANT scripts.")
combined_nb = create_combined_notebook(transformed_ddls, combined_grants, "DDL_And_Grants")
combined_sql = create_combined_sql(transformed_ddls, combined_grants)
col1, col2 = st.columns(2)
with col1:
st.download_button(
label="β¬οΈ Download Combined Notebook (.ipynb)",
data=combined_nb,
file_name="DDL_And_Grants.ipynb",
mime="application/x-ipynb+json",
use_container_width=True,
key="dl_combined_ipynb",
)
with col2:
st.download_button(
label="β¬οΈ Download Combined Script (.sql)",
data=combined_sql,
file_name="DDL_And_Grants.sql",
mime="text/plain",
use_container_width=True,
key="dl_combined_sql",
)
|