|
| 1 | +""" |
| 2 | +Some helper functions for ClickHouse using clickhouse-connect. |
| 3 | +""" |
| 4 | + |
| 5 | +import os |
| 6 | +import pandas as pd |
| 7 | +from dagster import get_dagster_logger |
| 8 | +from clickhouse_connect import get_client |
| 9 | + |
| 10 | + |
| 11 | +def map_dtype(dtype) -> str: |
| 12 | + """ |
| 13 | + Map a Pandas dtype to a ClickHouse data type. |
| 14 | + """ |
| 15 | + if pd.api.types.is_integer_dtype(dtype): |
| 16 | + return "Int64" |
| 17 | + elif pd.api.types.is_float_dtype(dtype): |
| 18 | + return "Float64" |
| 19 | + elif pd.api.types.is_bool_dtype(dtype): |
| 20 | + return "UInt8" |
| 21 | + elif pd.api.types.is_datetime64_any_dtype(dtype): |
| 22 | + return "DateTime" |
| 23 | + else: |
| 24 | + return "String" |
| 25 | + |
| 26 | + |
| 27 | +def get_clickhouse_client(): |
| 28 | + """ |
| 29 | + Create a ClickHouse client using environment variables for connection parameters. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + ClickHouseClient: Configured ClickHouse client instance |
| 33 | + """ |
| 34 | + logger = get_dagster_logger() |
| 35 | + |
| 36 | + host = os.environ.get("ANOMSTACK_CLICKHOUSE_HOST", "localhost") |
| 37 | + port = int(os.environ.get("ANOMSTACK_CLICKHOUSE_PORT", "8123")) |
| 38 | + user = os.environ.get("ANOMSTACK_CLICKHOUSE_USER", "anomstack") |
| 39 | + password = os.environ.get("ANOMSTACK_CLICKHOUSE_PASSWORD", "anomstack") |
| 40 | + database = os.environ.get("ANOMSTACK_CLICKHOUSE_DATABASE", "default") |
| 41 | + |
| 42 | + logger.info(f"ClickHouse connection: {host}:{port}/{database}") |
| 43 | + |
| 44 | + return get_client( |
| 45 | + host=host, |
| 46 | + port=port, |
| 47 | + username=user, |
| 48 | + password=password, |
| 49 | + database=database |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +def read_sql_clickhouse(sql: str) -> pd.DataFrame: |
| 54 | + """ |
| 55 | + Read data from ClickHouse using an SQL query. |
| 56 | +
|
| 57 | + Args: |
| 58 | + sql (str): The SQL query to execute. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + pd.DataFrame: The result of the SQL query as a pandas DataFrame. |
| 62 | + """ |
| 63 | + client = get_clickhouse_client() |
| 64 | + result = client.query(sql) |
| 65 | + |
| 66 | + return pd.DataFrame(result.result_set, columns=result.column_names) |
| 67 | + |
| 68 | + |
| 69 | +def save_df_clickhouse(df: pd.DataFrame, table_key: str) -> pd.DataFrame: |
| 70 | + """ |
| 71 | + Save a Pandas DataFrame to ClickHouse. |
| 72 | +
|
| 73 | + Args: |
| 74 | + df (pd.DataFrame): The DataFrame to save. |
| 75 | + table_key (str): The table name to save the DataFrame as. |
| 76 | +
|
| 77 | + Returns: |
| 78 | + pd.DataFrame: The input DataFrame. |
| 79 | + """ |
| 80 | + client = get_clickhouse_client() |
| 81 | + # Convert the DataFrame to a list of rows and extract column names. |
| 82 | + data = df.values.tolist() |
| 83 | + columns = list(df.columns) |
| 84 | + |
| 85 | + try: |
| 86 | + client.insert(table=table_key, data=data, column_names=columns) |
| 87 | + except Exception as e: |
| 88 | + logger = get_dagster_logger() |
| 89 | + logger.info( |
| 90 | + f"Table {table_key} may not exist. Attempting to create table. Error: {e}" |
| 91 | + ) |
| 92 | + # Construct a CREATE TABLE statement based on the DataFrame schema. |
| 93 | + columns_defs = [] |
| 94 | + for col, dtype in df.dtypes.items(): |
| 95 | + ch_type = map_dtype(dtype) |
| 96 | + # Use backticks around column names in case of reserved words. |
| 97 | + columns_defs.append(f"`{col}` {ch_type}") |
| 98 | + columns_str = ", ".join(columns_defs) |
| 99 | + create_sql = ( |
| 100 | + f"CREATE TABLE IF NOT EXISTS {table_key} ({columns_str}) " |
| 101 | + "ENGINE = MergeTree() ORDER BY tuple()" |
| 102 | + ) |
| 103 | + client.command(create_sql) |
| 104 | + # Insert the data after creating the table. |
| 105 | + client.insert(table=table_key, data=data, column_names=columns) |
| 106 | + |
| 107 | + return df |
| 108 | + |
| 109 | + |
| 110 | +def run_sql_clickhouse(sql: str) -> None: |
| 111 | + """ |
| 112 | + Execute a non-returning SQL statement in ClickHouse. |
| 113 | +
|
| 114 | + Args: |
| 115 | + sql (str): The SQL statement to execute. |
| 116 | +
|
| 117 | + Returns: |
| 118 | + None |
| 119 | + """ |
| 120 | + client = get_clickhouse_client() |
| 121 | + try: |
| 122 | + client.command(sql) |
| 123 | + except Exception as e: |
| 124 | + logger = get_dagster_logger() |
| 125 | + logger.error(f"Error executing SQL statement in ClickHouse: {e}") |
| 126 | + raise |
0 commit comments