|
| 1 | +"""Remove dbt target fields from snapshots outside of limited list of approved fields""" |
| 2 | +import json |
| 3 | + |
| 4 | +import pandas as pd |
| 5 | +from sqlglot import exp |
| 6 | + |
| 7 | +from sqlmesh.utils.migration import index_text_type |
| 8 | + |
| 9 | + |
| 10 | +def migrate(state_sync): # type: ignore |
| 11 | + engine_adapter = state_sync.engine_adapter |
| 12 | + schema = state_sync.schema |
| 13 | + snapshots_table = "_snapshots" |
| 14 | + if schema: |
| 15 | + snapshots_table = f"{schema}.{snapshots_table}" |
| 16 | + |
| 17 | + new_snapshots = [] |
| 18 | + found_dbt_target = False |
| 19 | + for name, identifier, version, snapshot, kind_name in engine_adapter.fetchall( |
| 20 | + exp.select("name", "identifier", "version", "snapshot", "kind_name").from_(snapshots_table), |
| 21 | + quote_identifiers=True, |
| 22 | + ): |
| 23 | + parsed_snapshot = json.loads(snapshot) |
| 24 | + node = parsed_snapshot["node"] |
| 25 | + dbt_target = node.get("jinja_macros", {}).get("global_objs", {}).get("target", {}) |
| 26 | + # Double check that `target_name` exists as a field since we know that all dbt targets have `target_name` |
| 27 | + # We do this in case someone has a target macro defined that is not related to dbt |
| 28 | + if dbt_target and dbt_target.get("target_name"): |
| 29 | + found_dbt_target = True |
| 30 | + node["jinja_macros"]["global_objs"]["target"] = { |
| 31 | + "type": dbt_target.get("type", "None"), |
| 32 | + "name": dbt_target.get("name", "None"), |
| 33 | + "schema": dbt_target.get("schema", "None"), |
| 34 | + "database": dbt_target.get("database", "None"), |
| 35 | + "target_name": dbt_target["target_name"], |
| 36 | + } |
| 37 | + |
| 38 | + new_snapshots.append( |
| 39 | + { |
| 40 | + "name": name, |
| 41 | + "identifier": identifier, |
| 42 | + "version": version, |
| 43 | + "snapshot": json.dumps(parsed_snapshot), |
| 44 | + "kind_name": kind_name, |
| 45 | + } |
| 46 | + ) |
| 47 | + |
| 48 | + if found_dbt_target: |
| 49 | + engine_adapter.delete_from(snapshots_table, "TRUE") |
| 50 | + |
| 51 | + text_type = index_text_type(engine_adapter.dialect) |
| 52 | + |
| 53 | + engine_adapter.insert_append( |
| 54 | + snapshots_table, |
| 55 | + pd.DataFrame(new_snapshots), |
| 56 | + columns_to_types={ |
| 57 | + "name": exp.DataType.build(text_type), |
| 58 | + "identifier": exp.DataType.build(text_type), |
| 59 | + "version": exp.DataType.build(text_type), |
| 60 | + "snapshot": exp.DataType.build("text"), |
| 61 | + "kind_name": exp.DataType.build(text_type), |
| 62 | + }, |
| 63 | + contains_json=True, |
| 64 | + ) |
0 commit comments