-
Notifications
You must be signed in to change notification settings - Fork 16.3k
Adding DatabricksSQLStatementSensor Sensor with Deferrability
#49516
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
3e3b38f
Adding mixin, Sensor, and updated Operator to create a draft PR
jroachgolf84 e45135e
Merge branch 'main' into issue-48368
jroachgolf84 bee5a9f
Merge branch 'main' into issue-48368
jroachgolf84 6a64139
Prepping to update branch
jroachgolf84 079aab9
Merge branch 'main' into issue-48368
jroachgolf84 645be4e
Adding tests for DatabricksSQLStatementSensor
jroachgolf84 241e309
Added unit tests and examples
jroachgolf84 89e6852
Merge branch 'main' into issue-48368
jroachgolf84 06416ea
Added documentation, pointed ignore tests on mixin
jroachgolf84 3156391
Merge branch 'main' into issue-48368
jroachgolf84 48b43db
Implementing changes requested in PR
jroachgolf84 2407f12
Tweaking example DAG
jroachgolf84 0105f3a
Adding validation, updating docs
jroachgolf84 d4742e9
Updated example DAG
jroachgolf84 6a99bc2
Adding test for Databricks mixins
jroachgolf84 13fde54
Updated test_project_structure.py
jroachgolf84 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
162 changes: 162 additions & 0 deletions
162
providers/databricks/src/airflow/providers/databricks/sensors/databricks.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| # | ||
| # 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 | ||
|
|
||
| from collections.abc import Sequence | ||
| from functools import cached_property | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from airflow.configuration import conf | ||
| from airflow.exceptions import AirflowException | ||
| from airflow.providers.databricks.hooks.databricks import DatabricksHook, SQLStatementState | ||
| from airflow.providers.databricks.operators.databricks import DEFER_METHOD_NAME | ||
| from airflow.providers.databricks.utils.mixins import DatabricksSQLStatementsMixin | ||
| from airflow.providers.databricks.version_compat import AIRFLOW_V_3_0_PLUS | ||
|
|
||
| if AIRFLOW_V_3_0_PLUS: | ||
| from airflow.sdk import BaseSensorOperator | ||
| else: | ||
| from airflow.sensors.base import BaseSensorOperator | ||
|
|
||
| if TYPE_CHECKING: | ||
| from airflow.utils.context import Context | ||
|
|
||
| XCOM_STATEMENT_ID_KEY = "statement_id" | ||
|
|
||
|
|
||
| class DatabricksSQLStatementsSensor(DatabricksSQLStatementsMixin, BaseSensorOperator): | ||
| """DatabricksSQLStatementsSensor.""" | ||
|
|
||
| template_fields: Sequence[str] = ( | ||
| "databricks_conn_id", | ||
| "statement", | ||
| "statement_id", | ||
| ) | ||
| template_ext: Sequence[str] = (".json-tpl",) | ||
| ui_color = "#1CB1C2" | ||
| ui_fgcolor = "#fff" | ||
|
|
||
| def __init__( | ||
| self, | ||
| warehouse_id: str, | ||
| *, | ||
| statement: str | None = None, | ||
| statement_id: str | None = None, | ||
| catalog: str | None = None, | ||
| schema: str | None = None, | ||
| parameters: list[dict[str, Any]] | None = None, | ||
| databricks_conn_id: str = "databricks_default", | ||
| polling_period_seconds: int = 30, | ||
| databricks_retry_limit: int = 3, | ||
| databricks_retry_delay: int = 1, | ||
| databricks_retry_args: dict[Any, Any] | None = None, | ||
| do_xcom_push: bool = True, | ||
| wait_for_termination: bool = True, | ||
| timeout: float = 3600, | ||
| deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), | ||
| **kwargs, | ||
| ): | ||
| # Handle the scenario where either both statement and statement_id are set/not set | ||
| if statement and statement_id: | ||
jroachgolf84 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| raise AirflowException("Cannot provide both statement and statement_id.") | ||
| if not statement and not statement_id: | ||
| raise AirflowException("One of either statement or statement_id must be provided.") | ||
|
|
||
| if not warehouse_id: | ||
| raise AirflowException("warehouse_id must be provided.") | ||
|
|
||
| super().__init__(**kwargs) | ||
|
|
||
| self.statement = statement | ||
| self.statement_id = statement_id | ||
| self.warehouse_id = warehouse_id | ||
| self.catalog = catalog | ||
| self.schema = schema | ||
| self.parameters = parameters | ||
| self.databricks_conn_id = databricks_conn_id | ||
| self.polling_period_seconds = polling_period_seconds | ||
| self.databricks_retry_limit = databricks_retry_limit | ||
| self.databricks_retry_delay = databricks_retry_delay | ||
| self.databricks_retry_args = databricks_retry_args | ||
| self.wait_for_termination = wait_for_termination | ||
| self.deferrable = deferrable | ||
| self.timeout = timeout | ||
| self.do_xcom_push = do_xcom_push | ||
|
|
||
| @cached_property | ||
| def _hook(self): | ||
| return self._get_hook(caller="DatabricksSQLStatementsSensor") | ||
|
|
||
| def _get_hook(self, caller: str) -> DatabricksHook: | ||
| return DatabricksHook( | ||
| self.databricks_conn_id, | ||
| retry_limit=self.databricks_retry_limit, | ||
| retry_delay=self.databricks_retry_delay, | ||
| retry_args=self.databricks_retry_args, | ||
| caller=caller, | ||
| ) | ||
|
|
||
| def execute(self, context: Context): | ||
| if not self.statement_id: | ||
| # Otherwise, we'll go ahead and "submit" the statement | ||
| json = { | ||
| "statement": self.statement, | ||
| "warehouse_id": self.warehouse_id, | ||
| "catalog": self.catalog, | ||
| "schema": self.schema, | ||
| "parameters": self.parameters, | ||
| "wait_timeout": "0s", | ||
| } | ||
|
|
||
| self.statement_id = self._hook.post_sql_statement(json) | ||
| self.log.info("SQL Statement submitted with statement_id: %s", self.statement_id) | ||
|
|
||
| if self.do_xcom_push and context is not None: | ||
| context["ti"].xcom_push(key=XCOM_STATEMENT_ID_KEY, value=self.statement_id) | ||
|
|
||
| # If we're not waiting for the query to complete execution, then we'll go ahead and return. However, a | ||
| # recommendation to use the DatabricksSQLStatementOperator is made in this case | ||
| if not self.wait_for_termination: | ||
| self.log.info( | ||
| "If setting wait_for_termination = False, consider using the DatabricksSQLStatementsOperator instead." | ||
| ) | ||
| return | ||
|
|
||
| if self.deferrable: | ||
| self._handle_deferrable_execution(defer_method_name=DEFER_METHOD_NAME) # type: ignore[misc] | ||
|
|
||
| def poke(self, context: Context): | ||
| """ | ||
| Handle non-deferrable Sensor execution. | ||
|
|
||
| :param context: (Context) | ||
| :return: (bool) | ||
| """ | ||
| # This is going to very closely mirror the execute_complete | ||
| statement_state: SQLStatementState = self._hook.get_sql_statement_state(self.statement_id) | ||
|
|
||
| if statement_state.is_running: | ||
| self.log.info("SQL Statement with ID %s is running", self.statement_id) | ||
| return False | ||
| if statement_state.is_successful: | ||
| self.log.info("SQL Statement with ID %s completed successfully.", self.statement_id) | ||
| return True | ||
| raise AirflowException( | ||
| f"SQL Statement with ID {statement_state} failed with error: {statement_state.error_message}" | ||
| ) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.