Airflow Summit 2026 is coming August 31 - September 2 in Austin, TX. Register now to secure your spot!

Source code for airflow.providers.apache.hive.operators.hive_stats

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations

import json
import re
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, Any

from airflow.providers.apache.hive.hooks.hive import HiveMetastoreHook
from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
from airflow.providers.mysql.hooks.mysql import MySqlHook
from airflow.providers.presto.hooks.presto import PrestoHook

if TYPE_CHECKING:
    from airflow.providers.common.compat.sdk import Context

# The table, the partition columns, and the metastore columns projected in the Presto
# stats SELECT are interpolated as identifiers, which cannot be bound as SQL parameters.
# Plain word identifiers are emitted unchanged, and identifiers the caller already
# double-quoted correctly are passed through as-is (so a pre-quoted name such as
# ``"weird-col"`` is not re-escaped into ``"""weird-col"""``); anything else is
# double-quoted with embedded quotes doubled (how Presto/Trino escape identifiers).
# Kept local rather than reusing common.sql's ``Dialect.escape_word``, which needs a
# live connection and does not double embedded quotes.
_PLAIN_IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
# A fully and correctly double-quoted identifier: opening and closing quotes with every
# embedded quote doubled (e.g. ``"a""b"``). Used to detect identifiers the caller has
# already escaped so they are left untouched instead of being double-escaped.
_QUOTED_IDENT_RE = re.compile(r'"(?:[^"]|"")*"')
# One component of a qualified ``<catalog>.<schema>.<table>`` name: either a quoted
# identifier (which may itself contain dots) or a run of characters up to the next
# separating dot. Matching in that order means only the dots *outside* a quoted
# identifier separate components, so ``"my.table"`` stays a single identifier.
_QUALIFIED_NAME_PART_RE = re.compile(r'"(?:[^"]|"")*"|[^.]+')


def _quote_presto_identifier(identifier: str) -> str:
    """
    Quote a Presto/Trino identifier.

    Plain word identifiers and identifiers the caller already double-quoted
    correctly are returned unchanged; anything else is wrapped in double quotes
    with embedded quotes doubled.
    """
    if _PLAIN_IDENT_RE.fullmatch(identifier) or _QUOTED_IDENT_RE.fullmatch(identifier):
        return identifier
    return '"' + identifier.replace('"', '""') + '"'


def _quote_presto_table(table: str) -> str:
    """
    Quote a possibly qualified Presto/Trino table name.

    The name is split into components on the dots that separate catalog, schema and
    table, and each component is quoted with :func:`_quote_presto_identifier`. Dots
    inside a quoted identifier are part of the name rather than separators, so
    ``db."odd.name"`` keeps its two components instead of being split into three.
    """
    return ".".join(_quote_presto_identifier(part) for part in _QUALIFIED_NAME_PART_RE.findall(table))


[docs] class HiveStatsCollectionOperator(BaseOperator): """ Gather partition statistics and insert them into MySQL. Statistics are gathered with a dynamically generated Presto query and inserted with this format. Stats overwrite themselves if you rerun the same date/partition. .. code-block:: sql CREATE TABLE hive_stats ( ds VARCHAR(16), table_name VARCHAR(500), metric VARCHAR(200), value BIGINT ); :param metastore_conn_id: Reference to the :ref:`Hive Metastore connection id <howto/connection:hive_metastore>`. :param table: the source table, in the format ``database.table_name``. (templated) :param partition: the source partition. (templated) :param extra_exprs: dict of expression to run against the table where keys are metric names and values are Presto compatible expressions :param excluded_columns: list of columns to exclude, consider excluding blobs, large json columns, ... :param assignment_func: a function that receives a column name and a type, and returns a dict of metric names and an Presto expressions. If None is returned, the global defaults are applied. If an empty dictionary is returned, no stats are computed for that column. """
[docs] template_fields: Sequence[str] = ("table", "partition", "ds", "dttm")
[docs] ui_color = "#aff7a6"
def __init__( self, *, table: str, partition: Any, extra_exprs: dict[str, Any] | None = None, excluded_columns: list[str] | None = None, assignment_func: Callable[[str, str], dict[Any, Any] | None] | None = None, metastore_conn_id: str = "metastore_default", presto_conn_id: str = "presto_default", mysql_conn_id: str = "airflow_db", ds: str = "{{ ds }}", dttm: str = "{{ logical_date.isoformat() }}", **kwargs: Any, ) -> None: super().__init__(**kwargs)
[docs] self.table = table
[docs] self.partition = partition
[docs] self.extra_exprs = extra_exprs or {}
[docs] self.excluded_columns: list[str] = excluded_columns or []
[docs] self.metastore_conn_id = metastore_conn_id
[docs] self.presto_conn_id = presto_conn_id
[docs] self.mysql_conn_id = mysql_conn_id
[docs] self.assignment_func = assignment_func
[docs] self.ds = ds
[docs] self.dttm = dttm
[docs] def get_default_exprs(self, col: str, col_type: str) -> dict[Any, Any]: """Get default expressions.""" if col in self.excluded_columns: return {} # Quote only the interpolated identifier in the SQL value; the dict key keeps the # bare column name, which is what gets stored in the ``hive_stats.col`` column. quoted_col = _quote_presto_identifier(col) exp = {(col, "non_null"): f"COUNT({quoted_col})"} if col_type in {"double", "int", "bigint", "float"}: exp[(col, "sum")] = f"SUM({quoted_col})" exp[(col, "min")] = f"MIN({quoted_col})" exp[(col, "max")] = f"MAX({quoted_col})" exp[(col, "avg")] = f"AVG({quoted_col})" elif col_type == "boolean": exp[(col, "true")] = f"SUM(CASE WHEN {quoted_col} THEN 1 ELSE 0 END)" exp[(col, "false")] = f"SUM(CASE WHEN NOT {quoted_col} THEN 1 ELSE 0 END)" elif col_type == "string": exp[(col, "len")] = f"SUM(CAST(LENGTH({quoted_col}) AS BIGINT))" exp[(col, "approx_distinct")] = f"APPROX_DISTINCT({quoted_col})" return exp
[docs] def execute(self, context: Context) -> None: metastore = HiveMetastoreHook(metastore_conn_id=self.metastore_conn_id) table = metastore.get_table(table_name=self.table) field_types = {col.name: col.type for col in table.sd.cols} exprs: Any = {("", "count"): "COUNT(*)"} for col, col_type in list(field_types.items()): if self.assignment_func: assign_exprs = self.assignment_func(col, col_type) if assign_exprs is None: assign_exprs = self.get_default_exprs(col, col_type) else: assign_exprs = self.get_default_exprs(col, col_type) exprs.update(assign_exprs) exprs.update(self.extra_exprs) exprs_str = ",\n ".join( f"{v} AS {_quote_presto_identifier(f'{k[0]}__{k[1]}')}" for k, v in exprs.items() ) presto = PrestoHook(presto_conn_id=self.presto_conn_id) # Build the WHERE clause against the hook's declared parameter placeholder # (PrestoHook defaults to `?`; a connection may override it via the `placeholder` extra). placeholder = presto.placeholder where_clause_ = [f"{_quote_presto_identifier(k)} = {placeholder}" for k in self.partition.keys()] where_clause = " AND\n ".join(where_clause_) sql = f"SELECT {exprs_str} FROM {_quote_presto_table(self.table)} WHERE {where_clause};" self.log.info("Executing SQL check: %s", sql) row = presto.get_first(sql, parameters=tuple(self.partition.values())) self.log.info("Record: %s", row) if not row: raise AirflowException("The query returned None") part_json = json.dumps(self.partition, sort_keys=True) self.log.info("Deleting rows from previous runs if they exist") mysql = MySqlHook(self.mysql_conn_id) sql = """ SELECT 1 FROM hive_stats WHERE table_name = %s AND partition_repr = %s AND dttm = %s LIMIT 1; """ if mysql.get_records(sql, parameters=(self.table, part_json, self.dttm)): sql = """ DELETE FROM hive_stats WHERE table_name = %s AND partition_repr = %s AND dttm = %s; """ mysql.run(sql, parameters=(self.table, part_json, self.dttm)) self.log.info("Pivoting and loading cells into the Airflow db") rows = [ (self.ds, self.dttm, self.table, part_json) + (r[0][0], r[0][1], r[1]) for r in zip(exprs, row) ] mysql.insert_rows( table="hive_stats", rows=rows, target_fields=[ "ds", "dttm", "table_name", "partition_repr", "col", "metric", "value", ], )

Was this entry helpful?