|
| 1 | +"""Replace snapshot model_kind_name enum with value.""" |
| 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 | + |
| 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 | + corrected_kind_name = None |
| 24 | + parsed_snapshot = json.loads(snapshot) |
| 25 | + if "kind" in parsed_snapshot["node"]: |
| 26 | + corrected_kind_name = parsed_snapshot["node"]["kind"].get("name") |
| 27 | + |
| 28 | + new_snapshots.append( |
| 29 | + { |
| 30 | + "name": name, |
| 31 | + "identifier": identifier, |
| 32 | + "version": version, |
| 33 | + "snapshot": snapshot, |
| 34 | + "kind_name": corrected_kind_name, |
| 35 | + } |
| 36 | + ) |
| 37 | + |
| 38 | + if new_snapshots: |
| 39 | + engine_adapter.delete_from(snapshots_table, "TRUE") |
| 40 | + |
| 41 | + text_type = index_text_type(engine_adapter.dialect) |
| 42 | + |
| 43 | + engine_adapter.insert_append( |
| 44 | + snapshots_table, |
| 45 | + pd.DataFrame(new_snapshots), |
| 46 | + columns_to_types={ |
| 47 | + "name": exp.DataType.build(text_type), |
| 48 | + "identifier": exp.DataType.build(text_type), |
| 49 | + "version": exp.DataType.build(text_type), |
| 50 | + "snapshot": exp.DataType.build("text"), |
| 51 | + "kind_name": exp.DataType.build("text"), |
| 52 | + }, |
| 53 | + contains_json=True, |
| 54 | + ) |
0 commit comments