|
| 1 | +from collections.abc import Mapping |
| 2 | + |
| 3 | +from testgen.common.data_catalog_service import ( |
| 4 | + TAG_FIELDS, |
| 5 | + apply_column_metadata, |
| 6 | + apply_table_metadata, |
| 7 | + disable_autoflags, |
| 8 | + validate_metadata_fields, |
| 9 | +) |
| 10 | +from testgen.common.models import with_database_session |
| 11 | +from testgen.common.models.data_column import DataColumnChars |
| 12 | +from testgen.common.models.data_table import DataTable |
| 13 | +from testgen.mcp.exceptions import MCPUserError |
| 14 | +from testgen.mcp.permissions import get_project_permissions, mcp_permission |
| 15 | +from testgen.mcp.tools.common import DocGroup, resolve_table_group |
| 16 | +from testgen.mcp.tools.markdown import MdDoc |
| 17 | + |
| 18 | +_DOC_GROUP = DocGroup.MANAGE |
| 19 | + |
| 20 | +_BOOLEAN_ARGS = ("cde", "xde", "pii") |
| 21 | + |
| 22 | +# MCP argument name -> data_*_chars column name. |
| 23 | +_ARG_TO_COLUMN = {"cde": "critical_data_element", "xde": "excluded_data_element", "pii": "pii_flag"} |
| 24 | +_COLUMN_TO_ARG = {v: k for k, v in _ARG_TO_COLUMN.items()} |
| 25 | + |
| 26 | + |
| 27 | +@with_database_session |
| 28 | +@mcp_permission("disposition") |
| 29 | +def update_catalog_metadata(updates: list[dict]) -> str: |
| 30 | + """Apply metadata updates to tables and columns within table groups. |
| 31 | +
|
| 32 | + Each update targets one table, or one column within a table, and sets one or |
| 33 | + more metadata fields. Rows are processed independently: a failure on one row |
| 34 | + does not stop the others, and the response reports the outcome of every row. |
| 35 | +
|
| 36 | + Omit a field to leave it unchanged, pass null to clear it, or pass a value to set it. |
| 37 | +
|
| 38 | + Args: |
| 39 | + updates: List of per-row update specs. Each spec accepts: |
| 40 | + table_group_id: UUID of the table group, e.g. from `get_data_inventory`. |
| 41 | + table_name: Name of the target table. |
| 42 | + column_name: Name of the target column. Omit for a table-level update. |
| 43 | + description: Free-text description (max 1000 characters). |
| 44 | + cde: Whether this is a critical data element (true/false). Set at the |
| 45 | + table level to apply to all its columns unless a column overrides it. |
| 46 | + xde: Whether to exclude the column from future profiling and test |
| 47 | + generation (true/false). Columns only. |
| 48 | + pii: Whether the column contains personally identifiable information |
| 49 | + (true/false). Columns only. |
| 50 | + data_source, source_system, source_process, business_domain, |
| 51 | + stakeholder_group, transform_level, aggregation_level, data_product: |
| 52 | + Catalog tags (max 40 characters each). |
| 53 | + """ |
| 54 | + if not updates: |
| 55 | + raise MCPUserError("Provide at least one update.") |
| 56 | + |
| 57 | + perms = get_project_permissions() |
| 58 | + tg_cache: dict[str, object] = {} |
| 59 | + flag_writes: dict = {} # tg.id -> {"tg": tg, "cde": bool, "pii": bool} |
| 60 | + inheritance_notices: list[str] = [] |
| 61 | + exclusion_notices: list[str] = [] |
| 62 | + rows: list[tuple[str, str, str]] = [] |
| 63 | + |
| 64 | + for spec in updates: |
| 65 | + target = _target_label(spec) |
| 66 | + try: |
| 67 | + outcome, detail = _apply_update(spec, perms, tg_cache, flag_writes, inheritance_notices, exclusion_notices) |
| 68 | + rows.append((target, outcome, detail)) |
| 69 | + except MCPUserError as err: |
| 70 | + rows.append((target, "Failed", str(err))) |
| 71 | + |
| 72 | + autoflag_notices: list[str] = [] |
| 73 | + for entry in flag_writes.values(): |
| 74 | + disabled = disable_autoflags(entry["tg"], wrote_cde=entry["cde"], wrote_pii=entry["pii"]) |
| 75 | + for flag in disabled: |
| 76 | + autoflag_notices.append( |
| 77 | + f"Auto-disabled {flag} on table group `{entry['tg'].table_groups_name}` to preserve manual marks." |
| 78 | + ) |
| 79 | + |
| 80 | + return _render(rows, autoflag_notices + inheritance_notices + exclusion_notices) |
| 81 | + |
| 82 | + |
| 83 | +def _target_label(spec: Mapping) -> str: |
| 84 | + table = spec.get("table_name") or "?" |
| 85 | + column = spec.get("column_name") |
| 86 | + return f"{table}.{column}" if column else table |
| 87 | + |
| 88 | + |
| 89 | +def _apply_update(spec, perms, tg_cache, flag_writes, inheritance_notices, exclusion_notices) -> tuple[str, str]: |
| 90 | + if not isinstance(spec, Mapping): |
| 91 | + raise MCPUserError("Each update must be an object.") |
| 92 | + |
| 93 | + table_group_id = spec.get("table_group_id") |
| 94 | + table_name = spec.get("table_name") |
| 95 | + if not table_group_id: |
| 96 | + raise MCPUserError("table_group_id is required.") |
| 97 | + if not table_name: |
| 98 | + raise MCPUserError("table_name is required.") |
| 99 | + column_name = spec.get("column_name") |
| 100 | + is_column = column_name is not None |
| 101 | + |
| 102 | + for arg in _BOOLEAN_ARGS: |
| 103 | + if arg in spec and spec[arg] is not None and not isinstance(spec[arg], bool): |
| 104 | + raise MCPUserError(f"{arg} must be true or false.") |
| 105 | + |
| 106 | + if not is_column: |
| 107 | + if "xde" in spec: |
| 108 | + raise MCPUserError("xde applies to columns only; omit it for table-level updates.") |
| 109 | + if "pii" in spec: |
| 110 | + raise MCPUserError("pii applies to columns only; omit it for table-level updates.") |
| 111 | + |
| 112 | + tg = tg_cache.get(table_group_id) |
| 113 | + if tg is None: |
| 114 | + tg = resolve_table_group(table_group_id) |
| 115 | + tg_cache[table_group_id] = tg |
| 116 | + |
| 117 | + if "pii" in spec and not perms.has_permission("view_pii", tg.project_code): |
| 118 | + raise MCPUserError(f"Setting pii requires permission to view PII on project `{tg.project_code}`.") |
| 119 | + |
| 120 | + fields = _build_fields(spec) |
| 121 | + errors = validate_metadata_fields(fields) |
| 122 | + if errors: |
| 123 | + raise MCPUserError("; ".join(errors)) |
| 124 | + |
| 125 | + if not fields: |
| 126 | + return "Skipped", "no metadata fields provided" |
| 127 | + |
| 128 | + if is_column: |
| 129 | + target = _resolve_column(tg.id, table_name, column_name) |
| 130 | + if target is None: |
| 131 | + raise MCPUserError(f"Column `{column_name}` not found in table `{table_name}`.") |
| 132 | + else: |
| 133 | + target = _resolve_table(tg.id, table_name) |
| 134 | + if target is None: |
| 135 | + raise MCPUserError(f"Table `{table_name}` not found in this table group.") |
| 136 | + |
| 137 | + # Disable a table group's auto-detect flag only on a real change, matching the UI's confirm-to-disable |
| 138 | + # behavior. A no-op write (e.g. cde: false on an already-false column) must not silently turn it off. |
| 139 | + cde_changed = "cde" in spec and target.critical_data_element != spec["cde"] |
| 140 | + pii_changed = "pii" in spec and target.pii_flag != ("MANUAL" if spec["pii"] else None) |
| 141 | + |
| 142 | + if is_column: |
| 143 | + apply_column_metadata(target, fields) |
| 144 | + else: |
| 145 | + apply_table_metadata(target, fields) |
| 146 | + |
| 147 | + entry = flag_writes.setdefault(tg.id, {"tg": tg, "cde": False, "pii": False}) |
| 148 | + if cde_changed: |
| 149 | + entry["cde"] = True |
| 150 | + if pii_changed: |
| 151 | + entry["pii"] = True |
| 152 | + |
| 153 | + if not is_column and spec.get("cde") is True: |
| 154 | + inheritance_notices.append( |
| 155 | + f"Table-level CDE set; affects all columns of `{table_name}` unless explicitly overridden." |
| 156 | + ) |
| 157 | + if is_column and spec.get("xde") is True: |
| 158 | + exclusion_notices.append( |
| 159 | + f"Column `{table_name}.{column_name}` excluded; next profiling run and test generation will skip it." |
| 160 | + ) |
| 161 | + |
| 162 | + return "Updated", _change_summary(fields) |
| 163 | + |
| 164 | + |
| 165 | +def _build_fields(spec: Mapping) -> dict: |
| 166 | + """Translate a spec into a {data_*_chars column: value} dict (pii bool -> MANUAL/None).""" |
| 167 | + fields: dict = {} |
| 168 | + if "description" in spec: |
| 169 | + fields["description"] = spec["description"] |
| 170 | + for tag in TAG_FIELDS: |
| 171 | + if tag in spec: |
| 172 | + fields[tag] = spec[tag] |
| 173 | + if "cde" in spec: |
| 174 | + fields["critical_data_element"] = spec["cde"] |
| 175 | + if "xde" in spec: |
| 176 | + fields["excluded_data_element"] = spec["xde"] |
| 177 | + if "pii" in spec: |
| 178 | + fields["pii_flag"] = "MANUAL" if spec["pii"] else None |
| 179 | + return fields |
| 180 | + |
| 181 | + |
| 182 | +def _resolve_table(table_groups_id, table_name: str): |
| 183 | + matches = list(DataTable.select_where( |
| 184 | + DataTable.table_groups_id == table_groups_id, |
| 185 | + DataTable.table_name == table_name, |
| 186 | + )) |
| 187 | + return matches[0] if matches else None |
| 188 | + |
| 189 | + |
| 190 | +def _resolve_column(table_groups_id, table_name: str, column_name: str): |
| 191 | + matches = list(DataColumnChars.select_where( |
| 192 | + DataColumnChars.table_groups_id == table_groups_id, |
| 193 | + DataColumnChars.table_name == table_name, |
| 194 | + DataColumnChars.column_name == column_name, |
| 195 | + )) |
| 196 | + return matches[0] if matches else None |
| 197 | + |
| 198 | + |
| 199 | +def _change_summary(fields: dict) -> str: |
| 200 | + parts = [] |
| 201 | + for column, value in fields.items(): |
| 202 | + label = _COLUMN_TO_ARG.get(column, column) |
| 203 | + parts.append(f"{label} cleared" if value is None else f"{label} set") |
| 204 | + return ", ".join(parts) |
| 205 | + |
| 206 | + |
| 207 | +def _render(rows: list[tuple[str, str, str]], notices: list[str]) -> str: |
| 208 | + succeeded = sum(1 for _, outcome, _ in rows if outcome == "Updated") |
| 209 | + skipped = sum(1 for _, outcome, _ in rows if outcome == "Skipped") |
| 210 | + failed = sum(1 for _, outcome, _ in rows if outcome == "Failed") |
| 211 | + |
| 212 | + doc = MdDoc() |
| 213 | + doc.heading(1, "Catalog metadata update") |
| 214 | + doc.field("Rows attempted", len(rows)) |
| 215 | + doc.field("Updated", succeeded) |
| 216 | + doc.field("Skipped", skipped) |
| 217 | + doc.field("Failed", failed) |
| 218 | + doc.table(["Target", "Outcome", "Details"], [list(row) for row in rows], code=[0]) |
| 219 | + for notice in notices: |
| 220 | + doc.text(notice) |
| 221 | + return doc.render() |
0 commit comments