Spaces:
Runtime error
Runtime error
File size: 8,554 Bytes
143ca8e 08d6e78 143ca8e 08d6e78 | 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 | import streamlit as st
import re
import json
st.set_page_config(page_title="Databricks Grant Object Updater", layout="wide")
st.title("Databricks Grant Object Name Changer")
st.markdown("---")
# ββ Environment β catalog mapping ββ
CATALOG_MAP = {
"dev": "uc_dev_apac_mdip_01",
"qa": "uc_qa_apac_mdip_01",
"prod": "uc_prod_apac_mdip_01",
}
# ββ Predefined 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"),
]
VIEW_GRANTS = [
("SELECT", "Team.App.MDIP.Core.Team"),
("SELECT", "svciscpkpi@pepsico.com"),
("SELECT", "Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer"),
("SELECT", "svcCViscpkrptprd@pepsico.com"),
("SELECT", "Team.App.PBNA.TDQKETSPROD.ADB"),
("SELECT", "Team.App.PBNA.TDQKETS.ADB"),
("SELECT", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader"),
("SELECT", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor"),
]
def resolve_full_name(name: str, catalog: str) -> str:
"""
Resolve a table/view identifier to a fully-qualified 3-part name.
Rules (dot-count based):
1 dot β schema.object : {catalog}.{name}
2+ dots β already a full name : swap any uc_<env>_apac_mdip_01 prefix
with the selected catalog
"""
parts = name.strip().split(".")
if len(parts) == 2:
return f"{catalog}.{name.strip()}"
elif len(parts) >= 3:
return re.sub(r'^uc_(dev|qa|prod)_apac_mdip_01', catalog, name.strip())
return name.strip()
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 build_view_grants(full_name: str) -> str:
return "\n".join(
f"GRANT {privs} ON VIEW {full_name} TO `{principal}`;"
for privs, principal in VIEW_GRANTS
)
def create_databricks_notebook(sql_statements: str, title: str) -> str:
"""Create a .ipynb notebook compatible with Databricks import."""
cells = []
cells.append({
"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)
# ββ Environment selector ββ
environment = st.selectbox(
"Select Environment:",
options=["dev", "qa", "prod"],
key="environment"
)
catalog = CATALOG_MAP[environment]
st.info(f"**Environment:** `{environment}` | **Catalog:** `{catalog}`")
st.markdown("---")
# ββ Tabs ββ
tab_tables, tab_views = st.tabs(["TABLE Grants", "VIEW Grants"])
# βββββββββββββββββββββββββββ TABLE GRANTS βββββββββββββββββββββββββββ
with tab_tables:
st.markdown("### Predefined TABLE Grant Template")
preview_table = "\n".join(
f"GRANT {p} ON TABLE <{catalog}.schema.table_name> TO `{g}`;"
for p, g in TABLE_GRANTS
)
st.code(preview_table, language="sql")
st.markdown("### Enter Table Names (one per line)")
st.caption(
"Accepted formats:\n"
"- `SCHEMA.TABLE_NAME` β auto-expands to `{catalog}.SCHEMA.TABLE_NAME`\n"
"- `uc_<env>_apac_mdip_01.SCHEMA.TABLE_NAME` β catalog is swapped to match selected env"
)
table_names_input = st.text_area(
"Table names:",
height=150,
key="table_names",
placeholder=(
f"uc_qa_apac_mdip_01.ISCP_P_DATA.AJDA_SP_TS_INVTRY_RPRT\n"
f"uc_dev_apac_mdip_01.ISCP_P_DATA.ANOTHER_TABLE"
),
)
if st.button("Generate TABLE Grant Scripts", key="btn_tables"):
if not table_names_input.strip():
st.warning("Please enter at least one table name.")
else:
table_names = [t.strip() for t in table_names_input.strip().splitlines() if t.strip()]
all_scripts = []
for name in table_names:
full_name = resolve_full_name(name, catalog)
block = f"-- ========== {full_name} ==========\n{build_table_grants(full_name)}"
all_scripts.append(block)
combined = "\n\n".join(all_scripts)
st.markdown("### Generated TABLE Grant Scripts")
st.code(combined, language="sql")
st.success(f"Generated grant scripts for {len(table_names)} table(s) in **{environment}** environment!")
st.session_state["table_combined"] = combined
if "table_combined" in st.session_state:
nb = create_databricks_notebook(st.session_state["table_combined"], "Table_Grant_Scripts")
st.download_button(
label="Download as .ipynb (Databricks Notebook)",
data=nb,
file_name="table_grant_scripts.ipynb",
mime="application/x-ipynb+json",
key="dl_tables",
)
# βββββββββββββββββββββββββββ VIEW GRANTS ββββββββββββββββββββββββββββ
with tab_views:
st.markdown("### Predefined VIEW Grant Template")
preview_view = "\n".join(
f"GRANT {p} ON VIEW <{catalog}.schema.view_name> TO `{g}`;"
for p, g in VIEW_GRANTS
)
st.code(preview_view, language="sql")
st.markdown("### Enter View Names (one per line)")
st.caption(
"Accepted formats:\n"
"- `SCHEMA.VIEW_NAME` β auto-expands to `{catalog}.SCHEMA.VIEW_NAME`\n"
"- `uc_<env>_apac_mdip_01.SCHEMA.VIEW_NAME` β catalog is swapped to match selected env"
)
view_names_input = st.text_area(
"View names:",
height=150,
key="view_names",
placeholder=(
f"uc_qa_apac_mdip_01.ISCP_P_DATA.SOME_VIEW\n"
f"uc_dev_apac_mdip_01.ISCP_P_DATA.ANOTHER_VIEW"
),
)
if st.button("Generate VIEW Grant Scripts", key="btn_views"):
if not view_names_input.strip():
st.warning("Please enter at least one view name.")
else:
view_names = [v.strip() for v in view_names_input.strip().splitlines() if v.strip()]
all_scripts = []
for name in view_names:
full_name = resolve_full_name(name, catalog)
block = f"-- ========== {full_name} ==========\n{build_view_grants(full_name)}"
all_scripts.append(block)
combined = "\n\n".join(all_scripts)
st.markdown("### Generated VIEW Grant Scripts")
st.code(combined, language="sql")
st.success(f"Generated grant scripts for {len(view_names)} view(s) in **{environment}** environment!")
st.session_state["view_combined"] = combined
if "view_combined" in st.session_state:
nb = create_databricks_notebook(st.session_state["view_combined"], "View_Grant_Scripts")
st.download_button(
label="Download as .ipynb (Databricks Notebook)",
data=nb,
file_name="view_grant_scripts.ipynb",
mime="application/x-ipynb+json",
key="dl_views",
)
|