|
| 1 | +import os |
| 2 | +import shutil |
| 3 | +import uuid |
| 4 | + |
| 5 | +import trino |
| 6 | +import pandas as pd |
| 7 | +from sqlalchemy.engine import create_engine |
| 8 | + |
| 9 | +from .boto3_utils import upload_directory_to_s3 |
| 10 | +from .sqltypes import create_table_schema_pairs |
| 11 | + |
| 12 | +__all__ = [ |
| 13 | + "attach_trino_engine", |
| 14 | + "drop_unmanaged_table", |
| 15 | + "drop_unmanaged_data", |
| 16 | + "ingest_unmanaged_parquet", |
| 17 | + "unmanaged_parquet_tabledef", |
| 18 | +] |
| 19 | + |
| 20 | +_default_prefix = 'trino/{schema}/{table}' |
| 21 | + |
| 22 | +def _remove_trailing_slash(s): |
| 23 | + s = str(s) |
| 24 | + if len(s) == 0: return s |
| 25 | + if (s[-1] != '/'): return s |
| 26 | + return _remove_trailing_slash(s[:-1]) |
| 27 | + |
| 28 | +def _prefix(pfx, schema, table): |
| 29 | + return _remove_trailing_slash(pfx).format(schema = schema, table = table) |
| 30 | + |
| 31 | +def attach_trino_engine(env_var_prefix = 'TRINO'): |
| 32 | + sqlstring = 'trino://{user}@{host}:{port}/'.format( |
| 33 | + user = os.environ[f'{env_var_prefix}_USER'], |
| 34 | + host = os.environ[f'{env_var_prefix}_HOST'], |
| 35 | + port = os.environ[f'{env_var_prefix}_PORT'] |
| 36 | + ) |
| 37 | + sqlargs = { |
| 38 | + 'auth': trino.auth.JWTAuthentication(os.environ[f'{env_var_prefix}_PASSWD']), |
| 39 | + 'http_scheme': 'https' |
| 40 | + } |
| 41 | + engine = create_engine(sqlstring, connect_args = sqlargs) |
| 42 | + connection = engine.connect() |
| 43 | + return engine |
| 44 | + |
| 45 | +def drop_unmanaged_table(catalog, schema, table, engine, bucket, prefix=_default_prefix, verbose=False): |
| 46 | + sql = f'drop table if exists {catalog}.{schema}.{table}' |
| 47 | + qres = engine.execute(sql) |
| 48 | + dres = bucket.objects \ |
| 49 | + .filter(Prefix = f'{_prefix(prefix, schema, table)}/') \ |
| 50 | + .delete() |
| 51 | + if verbose: |
| 52 | + print(dres) |
| 53 | + return qres |
| 54 | + |
| 55 | +def drop_unmanaged_data(schema, table, bucket, prefix=_default_prefix, verbose=False): |
| 56 | + dres = bucket.objects \ |
| 57 | + .filter(Prefix = f'{_prefix(prefix, schema, table)}/') \ |
| 58 | + .delete() |
| 59 | + if verbose: print(dres) |
| 60 | + return dres |
| 61 | + |
| 62 | +def ingest_unmanaged_parquet(df, schema, table, bucket, partition_columns=[], append=True, workdir='/tmp', prefix=_default_prefix, verbose=False): |
| 63 | + if not isinstance(df, pd.DataFrame): |
| 64 | + raise ValueError("df must be a pandas DataFrame") |
| 65 | + if not isinstance(partition_columns, list): |
| 66 | + raise ValueError("partition_columns must be list of column names") |
| 67 | + |
| 68 | + s3pfx = _prefix(prefix, schema, table) |
| 69 | + |
| 70 | + if not append: |
| 71 | + dres = bucket.objects.filter(Prefix = f'{s3pfx}/').delete() |
| 72 | + if verbose: print(dres) |
| 73 | + |
| 74 | + if len(partition_columns) > 0: |
| 75 | + # tell pandas to write a directory tree, using partitions |
| 76 | + tmp = f'{workdir}/{table}' |
| 77 | + # pandas does not clean out destination directory for you: |
| 78 | + shutil.rmtree(tmp, ignore_errors=True) |
| 79 | + df.to_parquet(tmp, |
| 80 | + partition_cols=partition_columns, |
| 81 | + index=False) |
| 82 | + # upload the tree onto S3 |
| 83 | + upload_directory_to_s3(tmp, bucket, s3pfx, verbose=verbose) |
| 84 | + else: |
| 85 | + # do not use partitions: a single parquet file is created |
| 86 | + parquet = f'{uuid.uuid4().hex}.parquet' |
| 87 | + tmp = f'{workdir}/{parquet}' |
| 88 | + df.to_parquet(tmp, index=False) |
| 89 | + dst = f'{s3pfx}/{parquet}' |
| 90 | + if verbose: print(f'{tmp} --> {dst}') |
| 91 | + bucket.upload_file(tmp, dst) |
| 92 | + |
| 93 | +def unmanaged_parquet_tabledef(df, catalog, schema, table, bucket, partition_columns = [], verbose = False): |
| 94 | + if not isinstance(df, pd.DataFrame): |
| 95 | + raise ValueError("df must be a pandas DataFrame") |
| 96 | + if not isinstance(partition_columns, list): |
| 97 | + raise ValueError("partition_columns must be list of column names") |
| 98 | + |
| 99 | + columnschema = create_table_schema_pairs(df) |
| 100 | + |
| 101 | + tabledef = f"create table if not exists {catalog}.{schema}.{table} (\n" |
| 102 | + tabledef += f"{columnschema}\n" |
| 103 | + tabledef += ") with (\n format = 'parquet',\n" |
| 104 | + if len(partition_columns) > 0: |
| 105 | + tabledef += f" partitioned_by = array{partition_columns},\n" |
| 106 | + tabledef += f" external_location = 's3a://{bucket.name}/trino/{schema}/{table}/'\n)" |
| 107 | + |
| 108 | + if verbose: print(tabledef) |
| 109 | + return tabledef |
| 110 | + |
0 commit comments