You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "alexott (via GitHub)" <gi...@apache.org> on 2023/02/12 11:29:39 UTC
[GitHub] [airflow] alexott commented on a diff in pull request #28950: Sensor for Databricks partition and table changes
alexott commented on code in PR #28950:
URL: https://github.com/apache/airflow/pull/28950#discussion_r1103779029
##########
airflow/providers/databricks/sensors/databricks_partition.py:
##########
@@ -0,0 +1,167 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+import datetime
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.providers.databricks.utils.databricks import ParamEscaper
+from airflow.utils.context import Context
+
+
+class DatabricksPartitionSensor(DatabricksSqlSensor):
+ """Sensor to detect the existence of partitions in a Delta table.
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated).
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's extra parameters,
+ or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set
+ as HTTP headers on every request. (templated)
+ :param _catalog: An optional initial catalog to use. Requires DBR version 9.0+ (templated)
+ :param _schema: An optional initial schema to use. Requires DBR version 9.0+ (templated)
+ :param table_name: Table name to generate the SQL query.
+ :param partitions: Partitions to check, supplied via a dict.
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_one_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param partition_operator: Comparison operator for partitions.
+ """
+
+ template_fields: Sequence[str] = (
+ "databricks_conn_id",
+ "_schema",
+ "http_headers",
+ "_catalog",
+ "table_name",
+ "partitions",
+ )
+
+ def __init__(
+ self,
+ table_name: str,
+ partitions: dict,
+ partition_operator: str = "=",
+ *args,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.caller = "DatabricksPartitionSensor"
+ self.partitions = partitions
+ self.partition_operator = partition_operator
+ self.table_name = table_name
+ self.escaper = ParamEscaper()
+
+ def _get_hook(self) -> DatabricksSqlHook:
+ return DatabricksSqlHook(
+ self.databricks_conn_id,
+ self._http_path,
+ self._sql_endpoint_name,
+ self.session_config,
+ self.http_headers,
+ self._catalog,
+ self._schema,
+ self.caller,
+ **self.client_parameters,
+ **self.hook_params,
+ )
+
+ def _sql_sensor(self, sql):
+ hook = self._get_hook()
+ sql_result = hook.run(
+ sql,
+ handler=self.handler if self.do_xcom_push else None,
+ )
+ return sql_result
+
+ def _generate_partition_query(
+ self,
+ prefix: str,
+ suffix: str,
+ joiner_val: str,
+ table_name: str,
+ opts: dict[str, str] | None = None,
+ escape_key: bool = False,
+ ) -> str:
+ partition_columns = self._sql_sensor(f"DESCRIBE DETAIL {table_name}")[0][7]
+ self.log.info("table_info: %s", partition_columns)
+ if len(partition_columns) < 1:
+ raise AirflowException("Table %s does not have partitions", table_name)
+ formatted_opts = ""
+ if opts is not None and len(opts) > 0:
+ output_list = []
+ for partition_col, partition_value in self.partitions.items():
+ if escape_key:
+ partition_col = self.escaper.escape_item(partition_col)
+ if partition_col in partition_columns:
+ if isinstance(partition_value, list):
+ output_list.append(f"""{partition_col} in {tuple(partition_value)}""")
+ if isinstance(partition_value, (int, float, complex)):
+ output_list.append(
+ f"""{partition_col}{self.partition_operator}{self.escaper.escape_item(partition_value)}"""
+ )
+ if isinstance(partition_value, (str, datetime.date)):
Review Comment:
what about timestamps aka `datetime.datetime` ?
##########
airflow/providers/databricks/sensors/databricks_partition.py:
##########
@@ -0,0 +1,167 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+import datetime
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.providers.databricks.utils.databricks import ParamEscaper
+from airflow.utils.context import Context
+
+
+class DatabricksPartitionSensor(DatabricksSqlSensor):
+ """Sensor to detect the existence of partitions in a Delta table.
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated).
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's extra parameters,
+ or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set
+ as HTTP headers on every request. (templated)
+ :param _catalog: An optional initial catalog to use. Requires DBR version 9.0+ (templated)
+ :param _schema: An optional initial schema to use. Requires DBR version 9.0+ (templated)
Review Comment:
why starting with `_`? It then doesn't match other operators
##########
airflow/providers/databricks/sensors/databricks_partition.py:
##########
@@ -0,0 +1,167 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+import datetime
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.providers.databricks.utils.databricks import ParamEscaper
+from airflow.utils.context import Context
+
+
+class DatabricksPartitionSensor(DatabricksSqlSensor):
+ """Sensor to detect the existence of partitions in a Delta table.
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated).
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's extra parameters,
+ or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set
+ as HTTP headers on every request. (templated)
+ :param _catalog: An optional initial catalog to use. Requires DBR version 9.0+ (templated)
+ :param _schema: An optional initial schema to use. Requires DBR version 9.0+ (templated)
+ :param table_name: Table name to generate the SQL query.
+ :param partitions: Partitions to check, supplied via a dict.
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_one_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param partition_operator: Comparison operator for partitions.
+ """
+
+ template_fields: Sequence[str] = (
+ "databricks_conn_id",
+ "_schema",
+ "http_headers",
+ "_catalog",
+ "table_name",
+ "partitions",
+ )
+
+ def __init__(
+ self,
+ table_name: str,
+ partitions: dict,
+ partition_operator: str = "=",
+ *args,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.caller = "DatabricksPartitionSensor"
+ self.partitions = partitions
+ self.partition_operator = partition_operator
+ self.table_name = table_name
+ self.escaper = ParamEscaper()
+
+ def _get_hook(self) -> DatabricksSqlHook:
+ return DatabricksSqlHook(
+ self.databricks_conn_id,
+ self._http_path,
+ self._sql_endpoint_name,
+ self.session_config,
+ self.http_headers,
+ self._catalog,
+ self._schema,
+ self.caller,
+ **self.client_parameters,
+ **self.hook_params,
+ )
+
+ def _sql_sensor(self, sql):
+ hook = self._get_hook()
+ sql_result = hook.run(
+ sql,
+ handler=self.handler if self.do_xcom_push else None,
+ )
+ return sql_result
+
+ def _generate_partition_query(
+ self,
+ prefix: str,
+ suffix: str,
+ joiner_val: str,
+ table_name: str,
+ opts: dict[str, str] | None = None,
+ escape_key: bool = False,
+ ) -> str:
+ partition_columns = self._sql_sensor(f"DESCRIBE DETAIL {table_name}")[0][7]
+ self.log.info("table_info: %s", partition_columns)
+ if len(partition_columns) < 1:
+ raise AirflowException("Table %s does not have partitions", table_name)
+ formatted_opts = ""
+ if opts is not None and len(opts) > 0:
+ output_list = []
+ for partition_col, partition_value in self.partitions.items():
+ if escape_key:
+ partition_col = self.escaper.escape_item(partition_col)
+ if partition_col in partition_columns:
+ if isinstance(partition_value, list):
+ output_list.append(f"""{partition_col} in {tuple(partition_value)}""")
+ if isinstance(partition_value, (int, float, complex)):
+ output_list.append(
+ f"""{partition_col}{self.partition_operator}{self.escaper.escape_item(partition_value)}"""
+ )
+ if isinstance(partition_value, (str, datetime.date)):
+ output_list.append(
+ f"""{partition_col}{self.partition_operator}{self.escaper.escape_item(partition_value)}"""
+ )
+ # TODO: Check date types.
+ else:
+ raise AirflowException(
+ "Column %s not part of table partitions: %s", partition_col, partition_columns
+ )
+ self.log.debug("Formatted options: %s", formatted_opts)
+ formatted_opts = f"{prefix} {joiner_val.join(output_list)} {suffix}"
+
+ return formatted_opts.strip()
+
+ def _check_table_partitions(self) -> list:
+ _fully_qualified_table_name = str(self._catalog + "." + self._schema + "." + self.table_name)
+ self.log.debug("Table name generated from arguments: %s", _fully_qualified_table_name)
+ _joiner_val = " AND "
+ _prefix = f"SELECT 1 FROM {_fully_qualified_table_name} WHERE"
+ _suffix = " LIMIT 1"
+
+ partition_sql = self._generate_partition_query(
+ prefix=_prefix,
+ suffix=_suffix,
+ joiner_val=_joiner_val,
+ opts=self.partitions,
+ table_name=_fully_qualified_table_name,
+ escape_key=False,
+ )
+ return self._sql_sensor(partition_sql)
+
+ def _get_results(self, context: Context) -> bool:
Review Comment:
why we need context here?
##########
airflow/providers/databricks/utils/databricks.py:
##########
@@ -17,6 +17,9 @@
# under the License.
Review Comment:
Hmmm, it should be a part of `databricks-sql-connector`: https://github.com/databricks/databricks-sql-python/blob/main/src/databricks/sql/utils.py#L121
##########
airflow/providers/databricks/sensors/databricks_table_changes.py:
##########
@@ -0,0 +1,170 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.utils.context import Context
+
+
+class DatabricksTableChangesSensor(DatabricksSqlSensor):
+ """Sensor to detect changes in a Delta table.
+
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated), defaults to
+ DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's
+ extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint. If not specified, ``http_path`` must
+ be provided as described above, defaults to None
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters., defaults to None
+ :param http_headers: An optional list of (k, v) pairs
+ that will be set as HTTP headers on every request. (templated).
+ :param _catalog: An optional initial catalog to use.
+ Requires DBR version 9.0+ (templated), defaults to ""
+ :param _schema: An optional initial schema to use.
+ Requires DBR version 9.0+ (templated), defaults to "default"
+ :param table_name: Table name to generate the SQL query, defaults to ""
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_all_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param timestamp: Timestamp to check event history for a Delta table,
+ defaults to datetime.now()-timedelta(days=7)
+ :param filter operator: Operator to specify filter condition to check table changes.
+ """
+
+ template_fields: Sequence[str] = ("databricks_conn_id", "_catalog", "_schema", "table_name", "timestamp")
+
+ def __init__(
+ self,
+ table_name: str,
+ timestamp: datetime = datetime.now() - timedelta(days=7),
Review Comment:
what about making this optional? for example, I want to check changes without taking timestamp into account
##########
airflow/providers/databricks/sensors/databricks_sql.py:
##########
@@ -0,0 +1,119 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from typing import Any, Callable, Sequence
+
+from airflow.providers.common.sql.hooks.sql import fetch_all_handler
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.sensors.base import BaseSensorOperator
+from airflow.utils.context import Context
+
+
+class DatabricksSqlSensor(BaseSensorOperator):
+ """Generic SQL sensor for Databricks
+
+ :param databricks_conn_id: connection id from Airflow to databricks,
+ defaults to DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of
+ Databricks SQL Endpoint or cluster.If not specified, it should be either specified
+ in the Databricks connection's extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters.
+ Defaults to None. If not specified, it could be specified in the
+ Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set as HTTP headers on every request.
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param sql: SQL query to be executed.
Review Comment:
Not all parameters for `__init__` are documented.
##########
airflow/providers/databricks/sensors/databricks_partition.py:
##########
@@ -0,0 +1,167 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+import datetime
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.providers.databricks.utils.databricks import ParamEscaper
+from airflow.utils.context import Context
+
+
+class DatabricksPartitionSensor(DatabricksSqlSensor):
+ """Sensor to detect the existence of partitions in a Delta table.
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated).
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's extra parameters,
+ or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set
+ as HTTP headers on every request. (templated)
+ :param _catalog: An optional initial catalog to use. Requires DBR version 9.0+ (templated)
+ :param _schema: An optional initial schema to use. Requires DBR version 9.0+ (templated)
+ :param table_name: Table name to generate the SQL query.
+ :param partitions: Partitions to check, supplied via a dict.
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_one_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param partition_operator: Comparison operator for partitions.
+ """
+
+ template_fields: Sequence[str] = (
+ "databricks_conn_id",
+ "_schema",
+ "http_headers",
+ "_catalog",
+ "table_name",
+ "partitions",
+ )
+
+ def __init__(
+ self,
+ table_name: str,
+ partitions: dict,
+ partition_operator: str = "=",
+ *args,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.caller = "DatabricksPartitionSensor"
+ self.partitions = partitions
+ self.partition_operator = partition_operator
+ self.table_name = table_name
+ self.escaper = ParamEscaper()
+
+ def _get_hook(self) -> DatabricksSqlHook:
Review Comment:
This should be covered by the base class - no need to redefine it here
##########
airflow/providers/databricks/sensors/databricks_partition.py:
##########
@@ -0,0 +1,167 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+import datetime
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.providers.databricks.utils.databricks import ParamEscaper
+from airflow.utils.context import Context
+
+
+class DatabricksPartitionSensor(DatabricksSqlSensor):
+ """Sensor to detect the existence of partitions in a Delta table.
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated).
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's extra parameters,
+ or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set
+ as HTTP headers on every request. (templated)
+ :param _catalog: An optional initial catalog to use. Requires DBR version 9.0+ (templated)
+ :param _schema: An optional initial schema to use. Requires DBR version 9.0+ (templated)
+ :param table_name: Table name to generate the SQL query.
+ :param partitions: Partitions to check, supplied via a dict.
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_one_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param partition_operator: Comparison operator for partitions.
+ """
+
+ template_fields: Sequence[str] = (
+ "databricks_conn_id",
+ "_schema",
+ "http_headers",
+ "_catalog",
+ "table_name",
+ "partitions",
+ )
+
+ def __init__(
+ self,
+ table_name: str,
+ partitions: dict,
+ partition_operator: str = "=",
+ *args,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.caller = "DatabricksPartitionSensor"
+ self.partitions = partitions
+ self.partition_operator = partition_operator
+ self.table_name = table_name
+ self.escaper = ParamEscaper()
+
+ def _get_hook(self) -> DatabricksSqlHook:
+ return DatabricksSqlHook(
+ self.databricks_conn_id,
+ self._http_path,
+ self._sql_endpoint_name,
+ self.session_config,
+ self.http_headers,
+ self._catalog,
+ self._schema,
+ self.caller,
+ **self.client_parameters,
+ **self.hook_params,
+ )
+
+ def _sql_sensor(self, sql):
+ hook = self._get_hook()
+ sql_result = hook.run(
+ sql,
+ handler=self.handler if self.do_xcom_push else None,
+ )
+ return sql_result
+
+ def _generate_partition_query(
+ self,
+ prefix: str,
+ suffix: str,
+ joiner_val: str,
+ table_name: str,
+ opts: dict[str, str] | None = None,
+ escape_key: bool = False,
+ ) -> str:
+ partition_columns = self._sql_sensor(f"DESCRIBE DETAIL {table_name}")[0][7]
+ self.log.info("table_info: %s", partition_columns)
+ if len(partition_columns) < 1:
+ raise AirflowException("Table %s does not have partitions", table_name)
+ formatted_opts = ""
+ if opts is not None and len(opts) > 0:
+ output_list = []
+ for partition_col, partition_value in self.partitions.items():
+ if escape_key:
+ partition_col = self.escaper.escape_item(partition_col)
+ if partition_col in partition_columns:
+ if isinstance(partition_value, list):
+ output_list.append(f"""{partition_col} in {tuple(partition_value)}""")
+ if isinstance(partition_value, (int, float, complex)):
+ output_list.append(
+ f"""{partition_col}{self.partition_operator}{self.escaper.escape_item(partition_value)}"""
+ )
+ if isinstance(partition_value, (str, datetime.date)):
+ output_list.append(
+ f"""{partition_col}{self.partition_operator}{self.escaper.escape_item(partition_value)}"""
+ )
+ # TODO: Check date types.
+ else:
+ raise AirflowException(
+ "Column %s not part of table partitions: %s", partition_col, partition_columns
+ )
+ self.log.debug("Formatted options: %s", formatted_opts)
+ formatted_opts = f"{prefix} {joiner_val.join(output_list)} {suffix}"
+
+ return formatted_opts.strip()
+
+ def _check_table_partitions(self) -> list:
+ _fully_qualified_table_name = str(self._catalog + "." + self._schema + "." + self.table_name)
+ self.log.debug("Table name generated from arguments: %s", _fully_qualified_table_name)
+ _joiner_val = " AND "
+ _prefix = f"SELECT 1 FROM {_fully_qualified_table_name} WHERE"
+ _suffix = " LIMIT 1"
+
+ partition_sql = self._generate_partition_query(
+ prefix=_prefix,
+ suffix=_suffix,
+ joiner_val=_joiner_val,
+ opts=self.partitions,
+ table_name=_fully_qualified_table_name,
+ escape_key=False,
+ )
+ return self._sql_sensor(partition_sql)
+
+ def _get_results(self, context: Context) -> bool:
+ result = self._check_table_partitions()
+ self.log.debug("Partition sensor result: %s", result)
+ if len(result) < 1:
+ raise AirflowException("Databricks SQL partition sensor failed.")
Review Comment:
this handles lack of results differently than the generic sensor.
##########
airflow/providers/databricks/sensors/databricks_sql.py:
##########
@@ -0,0 +1,119 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from typing import Any, Callable, Sequence
+
+from airflow.providers.common.sql.hooks.sql import fetch_all_handler
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.sensors.base import BaseSensorOperator
+from airflow.utils.context import Context
+
+
+class DatabricksSqlSensor(BaseSensorOperator):
+ """Generic SQL sensor for Databricks
+
+ :param databricks_conn_id: connection id from Airflow to databricks,
+ defaults to DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of
+ Databricks SQL Endpoint or cluster.If not specified, it should be either specified
+ in the Databricks connection's extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters.
+ Defaults to None. If not specified, it could be specified in the
+ Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set as HTTP headers on every request.
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param sql: SQL query to be executed.
+ """
+
+ template_fields: Sequence[str] = (
+ "databricks_conn_id",
+ "sql",
+ "_catalog",
Review Comment:
I maybe also would make `_schema` templatized as well. Also, check consistency with other sensors
##########
airflow/providers/databricks/sensors/databricks_table_changes.py:
##########
@@ -0,0 +1,170 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.utils.context import Context
+
+
+class DatabricksTableChangesSensor(DatabricksSqlSensor):
+ """Sensor to detect changes in a Delta table.
+
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated), defaults to
+ DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's
+ extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint. If not specified, ``http_path`` must
+ be provided as described above, defaults to None
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters., defaults to None
+ :param http_headers: An optional list of (k, v) pairs
+ that will be set as HTTP headers on every request. (templated).
+ :param _catalog: An optional initial catalog to use.
+ Requires DBR version 9.0+ (templated), defaults to ""
+ :param _schema: An optional initial schema to use.
+ Requires DBR version 9.0+ (templated), defaults to "default"
Review Comment:
same here - unify names with base operator
##########
airflow/providers/databricks/sensors/databricks_sql.py:
##########
@@ -0,0 +1,119 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from typing import Any, Callable, Sequence
+
+from airflow.providers.common.sql.hooks.sql import fetch_all_handler
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.sensors.base import BaseSensorOperator
+from airflow.utils.context import Context
+
+
+class DatabricksSqlSensor(BaseSensorOperator):
+ """Generic SQL sensor for Databricks
+
+ :param databricks_conn_id: connection id from Airflow to databricks,
+ defaults to DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of
+ Databricks SQL Endpoint or cluster.If not specified, it should be either specified
+ in the Databricks connection's extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint.
+ If not specified, ``http_path`` must be provided as described above.
+ :param session_configuration: An optional dictionary of Spark session parameters.
+ Defaults to None. If not specified, it could be specified in the
+ Databricks connection's extra parameters.
+ :param http_headers: An optional list of (k, v) pairs that will be set as HTTP headers on every request.
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param sql: SQL query to be executed.
+ """
+
+ template_fields: Sequence[str] = (
+ "databricks_conn_id",
+ "sql",
+ "_catalog",
+ "http_headers",
+ )
+
+ template_ext: Sequence[str] = (".sql",)
+ template_fields_renderers = {"sql": "sql"}
+
+ def __init__(
+ self,
+ *,
+ databricks_conn_id: str = DatabricksSqlHook.default_conn_name,
+ http_path: str | None = None,
+ sql_endpoint_name: str | None = None,
+ session_configuration=None,
+ http_headers: list[tuple[str, str]] | None = None,
+ catalog: str = "hive_metastore",
+ schema: str = "default",
Review Comment:
the partition sensor documents them as `_catalog` & `_schema` - documentation there needs to be fixed
##########
airflow/providers/databricks/sensors/databricks_table_changes.py:
##########
@@ -0,0 +1,170 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.utils.context import Context
+
+
+class DatabricksTableChangesSensor(DatabricksSqlSensor):
+ """Sensor to detect changes in a Delta table.
+
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated), defaults to
+ DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's
+ extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint. If not specified, ``http_path`` must
+ be provided as described above, defaults to None
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters., defaults to None
+ :param http_headers: An optional list of (k, v) pairs
+ that will be set as HTTP headers on every request. (templated).
+ :param _catalog: An optional initial catalog to use.
+ Requires DBR version 9.0+ (templated), defaults to ""
+ :param _schema: An optional initial schema to use.
+ Requires DBR version 9.0+ (templated), defaults to "default"
+ :param table_name: Table name to generate the SQL query, defaults to ""
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_all_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param timestamp: Timestamp to check event history for a Delta table,
+ defaults to datetime.now()-timedelta(days=7)
+ :param filter operator: Operator to specify filter condition to check table changes.
+ """
+
+ template_fields: Sequence[str] = ("databricks_conn_id", "_catalog", "_schema", "table_name", "timestamp")
+
+ def __init__(
+ self,
+ table_name: str,
+ timestamp: datetime = datetime.now() - timedelta(days=7),
+ change_filter_operator: str = ">=",
+ *args,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.timestamp = timestamp
+ self.caller = "DatabricksTableChangesSensor"
+ self.change_filter_operator = change_filter_operator
+ self.table_name = table_name
+
+ def _get_hook(self) -> DatabricksSqlHook:
+ return DatabricksSqlHook(
+ self.databricks_conn_id,
+ self._http_path,
+ self._sql_endpoint_name,
+ self.session_config,
+ self.http_headers,
+ self._catalog,
+ self._schema,
+ self.caller,
+ **self.client_parameters,
+ **self.hook_params,
+ )
+
+ def _sql_sensor(self, sql):
+ hook = self._get_hook()
+ sql_result = hook.run(
+ sql,
+ handler=self.handler if self.do_xcom_push else None,
+ )
+ return sql_result
+
+ def _generate_query(
+ self,
+ prefix: str,
+ suffix: str,
+ joiner_val: str,
+ table_name: str,
+ time_range: str,
+ operation_filter: str,
+ ) -> str:
+ formatted_opts = ""
+ formatted_opts = f"{prefix} {table_name}{suffix} {joiner_val} '{time_range}'{operation_filter}"
+ self.log.debug("Formatted options: %s", formatted_opts)
+
+ return formatted_opts.strip()
+
+ @staticmethod
+ def get_previous_version(context: Context, lookup_key):
+ return context["ti"].xcom_pull(key=lookup_key, include_prior_dates=True)
+
+ @staticmethod
+ def set_version(context: Context, lookup_key, version):
+ context["ti"].xcom_push(key=lookup_key, value=version)
+
+ def get_current_table_version(self, table_name, time_range, operator):
+ _count_describe_literal = "SELECT MAX(version) AS versions FROM (DESCRIBE HISTORY"
+ _filter_predicate_literal = ") WHERE timestamp"
+ _operation_filter_literal = "AND operation NOT LIKE '%CONVERT%' AND operation NOT LIKE '%OPTIMIZE%' \
Review Comment:
could be simpler to do `operation NOT IN ('CONVERT', 'OPTIMIZE', ...)` ?
##########
airflow/providers/databricks/sensors/databricks_table_changes.py:
##########
@@ -0,0 +1,170 @@
+#
+# 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.
+#
+"""This module contains Databricks sensors."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import Sequence
+
+from airflow.exceptions import AirflowException
+from airflow.providers.databricks.hooks.databricks_sql import DatabricksSqlHook
+from airflow.providers.databricks.sensors.databricks_sql import DatabricksSqlSensor
+from airflow.utils.context import Context
+
+
+class DatabricksTableChangesSensor(DatabricksSqlSensor):
+ """Sensor to detect changes in a Delta table.
+
+
+ :param databricks_conn_id: Reference to :ref:`Databricks
+ connection id<howto/connection:databricks>` (templated), defaults to
+ DatabricksSqlHook.default_conn_name
+ :param http_path: Optional string specifying HTTP path of Databricks SQL Endpoint or cluster.
+ If not specified, it should be either specified in the Databricks connection's
+ extra parameters, or ``sql_endpoint_name`` must be specified.
+ :param sql_endpoint_name: Optional name of Databricks SQL Endpoint. If not specified, ``http_path`` must
+ be provided as described above, defaults to None
+ :param session_configuration: An optional dictionary of Spark session parameters. If not specified,
+ it could be specified in the Databricks connection's extra parameters., defaults to None
+ :param http_headers: An optional list of (k, v) pairs
+ that will be set as HTTP headers on every request. (templated).
+ :param _catalog: An optional initial catalog to use.
+ Requires DBR version 9.0+ (templated), defaults to ""
+ :param _schema: An optional initial schema to use.
+ Requires DBR version 9.0+ (templated), defaults to "default"
+ :param table_name: Table name to generate the SQL query, defaults to ""
+ :param handler: Handler for DbApiHook.run() to return results, defaults to fetch_all_handler
+ :param client_parameters: Additional parameters internal to Databricks SQL Connector parameters.
+ :param timestamp: Timestamp to check event history for a Delta table,
+ defaults to datetime.now()-timedelta(days=7)
+ :param filter operator: Operator to specify filter condition to check table changes.
+ """
+
+ template_fields: Sequence[str] = ("databricks_conn_id", "_catalog", "_schema", "table_name", "timestamp")
+
+ def __init__(
+ self,
+ table_name: str,
+ timestamp: datetime = datetime.now() - timedelta(days=7),
+ change_filter_operator: str = ">=",
+ *args,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.timestamp = timestamp
+ self.caller = "DatabricksTableChangesSensor"
+ self.change_filter_operator = change_filter_operator
+ self.table_name = table_name
+
+ def _get_hook(self) -> DatabricksSqlHook:
+ return DatabricksSqlHook(
+ self.databricks_conn_id,
+ self._http_path,
+ self._sql_endpoint_name,
+ self.session_config,
+ self.http_headers,
+ self._catalog,
+ self._schema,
+ self.caller,
+ **self.client_parameters,
+ **self.hook_params,
+ )
+
+ def _sql_sensor(self, sql):
+ hook = self._get_hook()
+ sql_result = hook.run(
+ sql,
+ handler=self.handler if self.do_xcom_push else None,
+ )
+ return sql_result
+
+ def _generate_query(
+ self,
+ prefix: str,
+ suffix: str,
+ joiner_val: str,
+ table_name: str,
+ time_range: str,
+ operation_filter: str,
+ ) -> str:
+ formatted_opts = ""
+ formatted_opts = f"{prefix} {table_name}{suffix} {joiner_val} '{time_range}'{operation_filter}"
+ self.log.debug("Formatted options: %s", formatted_opts)
+
+ return formatted_opts.strip()
+
+ @staticmethod
+ def get_previous_version(context: Context, lookup_key):
+ return context["ti"].xcom_pull(key=lookup_key, include_prior_dates=True)
+
+ @staticmethod
+ def set_version(context: Context, lookup_key, version):
+ context["ti"].xcom_push(key=lookup_key, value=version)
+
+ def get_current_table_version(self, table_name, time_range, operator):
+ _count_describe_literal = "SELECT MAX(version) AS versions FROM (DESCRIBE HISTORY"
+ _filter_predicate_literal = ") WHERE timestamp"
+ _operation_filter_literal = "AND operation NOT LIKE '%CONVERT%' AND operation NOT LIKE '%OPTIMIZE%' \
Review Comment:
Also, need to add `FSCK`. See full list here: https://docs.delta.io/latest/delta-utility.html#retrieve-delta-table-history
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org