|
| 1 | +import argparse |
| 2 | +from pathlib import Path |
| 3 | +from tableauhyperapi import HyperProcess, Telemetry, \ |
| 4 | + Connection, CreateMode, TableDefinition, escape_name, \ |
| 5 | + escape_string_literal |
| 6 | + |
| 7 | +def convert_tde_to_hyper(tde_path: Path): |
| 8 | + # Rename path with a .hyper extension in the directory of the tde file |
| 9 | + hyper_database = tde_path.with_name(tde_path.stem + '.hyper') |
| 10 | + |
| 11 | + with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: |
| 12 | + with Connection(endpoint=hyper.endpoint, database=hyper_database, create_mode=CreateMode.CREATE_AND_REPLACE) as connection: |
| 13 | + # Schema and table for TDE file is constant |
| 14 | + schema = 'Extract' |
| 15 | + table = 'Extract' |
| 16 | + |
| 17 | + # Create the temp external table for the TDE file |
| 18 | + create_external_table_query = _get_external_table_query(str(tde_path), schema, table) |
| 19 | + connection.execute_command(create_external_table_query) |
| 20 | + |
| 21 | + # Get the name of the table created from the catalog |
| 22 | + td = connection.catalog.get_table_definition(table) |
| 23 | + |
| 24 | + # Create the schema |
| 25 | + connection.catalog.create_schema(schema) |
| 26 | + |
| 27 | + # Create the destination table in the Hyper database |
| 28 | + schema_table = f"\"{schema}\".\"{table}\"" |
| 29 | + create_table_command = f"CREATE TABLE {escape_name(schema_table)} AS SELECT * FROM {td.table_name}" |
| 30 | + |
| 31 | + # Execute |
| 32 | + connection.execute_command(create_table_command) |
| 33 | + |
| 34 | + print(f"Successfully converted {tde_path} to {hyper_database}") |
| 35 | + |
| 36 | +def _get_external_table_query(tde_file_path: str, |
| 37 | + schema: str, |
| 38 | + table: str): |
| 39 | + return f"""CREATE TEMP EXTERNAL TABLE {escape_name(table)} FOR {escape_string_literal(tde_file_path)} |
| 40 | + (WITH (FORMAT TDE, TABLE {escape_string_literal(f"{schema}.{table}")}, SANITIZE))""" |
| 41 | + |
| 42 | +if __name__ == '__main__': |
| 43 | + argparser = argparse.ArgumentParser(description="Script to convert a TDE file to a Hyper file.") |
| 44 | + argparser.add_argument("input_tde_path", type=Path, help="The input TDE file path that will be converted to a Hyper file.") |
| 45 | + args = argparser.parse_args() |
| 46 | + |
| 47 | + input_tde_path = Path(args.input_tde_path) |
| 48 | + if not input_tde_path.exists(): |
| 49 | + raise Exception(f"{input_tde_path} not found") |
| 50 | + |
| 51 | + convert_tde_to_hyper(input_tde_path) |
0 commit comments