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(""" """, unsafe_allow_html=True) st.markdown("

Databricks DDL + Grants Generator πŸš€

", unsafe_allow_html=True) st.markdown( "

" "Upload your CSV DDL file β€” get a transformed DDL notebook and auto-generated GRANT scripts in one go." "

", 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"""

✨ Transformation Complete!

Processed Tables: {len(transformed_ddls)}


""", 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", )