This is an automated email from the ASF dual-hosted git repository.
shahar1 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 590c24194f9 Add operator to edit Databricks SQL warehouses (#76504)
590c24194f9 is described below
commit 590c24194f9c397326b7b4eef5a10516e70471d1
Author: Alejandro Morgante <[email protected]>
AuthorDate: Sat Nov 21 14:56:26 2026 -0300
Add operator to edit Databricks SQL warehouses (#76504)
---
providers/databricks/docs/operators/warehouse.rst | 42 +++++++++-
.../providers/databricks/hooks/databricks.py | 13 +++
.../providers/databricks/operators/warehouse.py | 87 +++++++++++++++----
.../databricks/example_databricks_sql_warehouse.py | 39 ++++++++-
.../tests/unit/databricks/hooks/test_databricks.py | 23 +++++
.../unit/databricks/operators/test_warehouse.py | 98 +++++++++++++++++++++-
6 files changed, 278 insertions(+), 24 deletions(-)
diff --git a/providers/databricks/docs/operators/warehouse.rst
b/providers/databricks/docs/operators/warehouse.rst
index 5f6f1157fba..dc094142362 100644
--- a/providers/databricks/docs/operators/warehouse.rst
+++ b/providers/databricks/docs/operators/warehouse.rst
@@ -17,14 +17,20 @@
.. _howto/operator:DatabricksStartWarehouseOperator:
.. _howto/operator:DatabricksStopWarehouseOperator:
+.. _howto/operator:DatabricksEditWarehouseOperator:
-Databricks SQL warehouse lifecycle operators
-============================================
+Databricks SQL warehouse operators
+==================================
+
+Use these operators to start, stop, or edit an existing Databricks SQL
warehouse through the
+`Databricks SQL Warehouses API
<https://docs.databricks.com/api/workspace/warehouses>`_.
+
+Start and stop a SQL warehouse
+------------------------------
Use
:class:`~airflow.providers.databricks.operators.warehouse.DatabricksStartWarehouseOperator`
and
:class:`~airflow.providers.databricks.operators.warehouse.DatabricksStopWarehouseOperator`
-to start and stop an existing Databricks SQL warehouse through the
-`Databricks SQL Warehouses API
<https://docs.databricks.com/api/workspace/warehouses>`_.
+to start and stop an existing Databricks SQL warehouse.
Both operators require the warehouse ID and use the :ref:`Databricks connection
<howto/connection:databricks>` for authentication.
@@ -60,3 +66,31 @@ task fails.
:language: python
:start-after: [START howto_operator_databricks_stop_sql_warehouse]
:end-before: [END howto_operator_databricks_stop_sql_warehouse]
+
+Edit a SQL warehouse
+--------------------
+
+Use
:class:`~airflow.providers.databricks.operators.warehouse.DatabricksEditWarehouseOperator`
+to change the configuration of an existing warehouse. Pass its
``warehouse_id`` and a non-empty
+``json`` dictionary containing the request body for the
+`SQL Warehouses edit API
<https://docs.databricks.com/api/warehouses/v1/edit-warehouse>`_.
+For example, you can set ``cluster_size``, ``auto_stop_mins``, or ``tags``.
+Settings omitted from ``json`` retain their current values.
+
+The connection ID, warehouse ID, and nested ``json`` values support templating.
+For numeric or boolean Jinja expressions,
+set ``render_template_as_native_obj=True`` on the Dag.
+
+The operator returns ``None`` and completes when the edit request succeeds,
+without waiting for configuration changes to finish applying. Pass the
+warehouse ID explicitly to downstream tasks.
+
+If needed, follow it with
+:class:`~airflow.providers.databricks.operators.warehouse.DatabricksStartWarehouseOperator`
+to wait for warehouse availability. A ``RUNNING`` state does not guarantee
+that all configuration changes have been applied.
+
+.. exampleinclude::
/../../databricks/tests/system/databricks/example_databricks_sql_warehouse.py
+ :language: python
+ :start-after: [START howto_operator_databricks_edit_sql_warehouse]
+ :end-before: [END howto_operator_databricks_edit_sql_warehouse]
diff --git
a/providers/databricks/src/airflow/providers/databricks/hooks/databricks.py
b/providers/databricks/src/airflow/providers/databricks/hooks/databricks.py
index f21882a5763..255e00937d9 100644
--- a/providers/databricks/src/airflow/providers/databricks/hooks/databricks.py
+++ b/providers/databricks/src/airflow/providers/databricks/hooks/databricks.py
@@ -845,6 +845,19 @@ class DatabricksHook(BaseDatabricksHook):
"""
self._do_api_call(("POST",
f"{SQL_WAREHOUSES_ENDPOINT}/{warehouse_id}/stop"))
+ def edit_warehouse(self, warehouse_id: str, json: dict[str, Any]) -> None:
+ """
+ Update the configuration of a Databricks SQL warehouse.
+
+ See the `SQL Warehouses edit API
+ <https://docs.databricks.com/api/warehouses/v1/edit-warehouse>`_.
+
+ :param warehouse_id: ID of the SQL warehouse.
+ :param json: Request body for the SQL Warehouses edit API, forwarded
as provided.
+ :return: ``None`` when the request succeeds, without waiting for
configuration changes to finish.
+ """
+ self._do_api_call(("POST",
f"{SQL_WAREHOUSES_ENDPOINT}/{warehouse_id}/edit"), json)
+
def install(self, json: dict) -> None:
"""
Install libraries on the cluster.
diff --git
a/providers/databricks/src/airflow/providers/databricks/operators/warehouse.py
b/providers/databricks/src/airflow/providers/databricks/operators/warehouse.py
index 374e960e184..2a7f2fd7b20 100644
---
a/providers/databricks/src/airflow/providers/databricks/operators/warehouse.py
+++
b/providers/databricks/src/airflow/providers/databricks/operators/warehouse.py
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Operators for managing Databricks SQL warehouse lifecycle state."""
+"""Operators for managing Databricks SQL warehouses."""
from __future__ import annotations
@@ -34,7 +34,7 @@ if TYPE_CHECKING:
class _DatabricksWarehouseBaseOperator(BaseOperator):
- """Share Databricks SQL warehouse connection and polling behavior."""
+ """Share warehouse connection setup."""
template_fields: Sequence[str] = ("databricks_conn_id", "warehouse_id")
ui_color = "#1CB1C2"
@@ -45,29 +45,17 @@ class _DatabricksWarehouseBaseOperator(BaseOperator):
warehouse_id: str,
*,
databricks_conn_id: str = "databricks_default",
- wait_for_termination: bool = True,
- polling_period_seconds: int = 30,
- timeout: float = 3600,
databricks_retry_limit: int = 3,
databricks_retry_delay: int = 1,
databricks_retry_args: dict[Any, Any] | None = None,
- deferrable: bool = conf.getboolean("operators", "default_deferrable",
fallback=False),
**kwargs,
) -> None:
super().__init__(**kwargs)
self.warehouse_id = warehouse_id
self.databricks_conn_id = databricks_conn_id
- self.wait_for_termination = wait_for_termination
- self.polling_period_seconds = polling_period_seconds
- self.timeout = timeout
self.databricks_retry_limit = databricks_retry_limit
self.databricks_retry_delay = databricks_retry_delay
self.databricks_retry_args = databricks_retry_args
- self.deferrable = deferrable
- if self.deferrable:
- validate_deferrable_databricks_retry_args(
- self.databricks_retry_args, owner=self.__class__.__name__
- )
def _validate_warehouse_id(self) -> None:
if not self.warehouse_id:
@@ -83,6 +71,29 @@ class _DatabricksWarehouseBaseOperator(BaseOperator):
caller=self.__class__.__name__,
)
+
+class _DatabricksWarehouseStateOperator(_DatabricksWarehouseBaseOperator):
+ """Add state polling and deferred execution to warehouse operations that
support waiting."""
+
+ def __init__(
+ self,
+ *,
+ wait_for_termination: bool = True,
+ polling_period_seconds: int = 30,
+ timeout: float = 3600,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable",
fallback=False),
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.wait_for_termination = wait_for_termination
+ self.polling_period_seconds = polling_period_seconds
+ self.timeout = timeout
+ self.deferrable = deferrable
+ if self.deferrable:
+ validate_deferrable_databricks_retry_args(
+ self.databricks_retry_args, owner=self.__class__.__name__
+ )
+
def _wait_for_state(self, target: str) -> None:
deadline = time.monotonic() + self.timeout
last_state = "unknown"
@@ -157,7 +168,7 @@ class _DatabricksWarehouseBaseOperator(BaseOperator):
)
-class DatabricksStartWarehouseOperator(_DatabricksWarehouseBaseOperator):
+class DatabricksStartWarehouseOperator(_DatabricksWarehouseStateOperator):
"""
Start a Databricks SQL warehouse and optionally wait for it to run.
@@ -183,7 +194,7 @@ class
DatabricksStartWarehouseOperator(_DatabricksWarehouseBaseOperator):
self._wait_or_defer("RUNNING")
-class DatabricksStopWarehouseOperator(_DatabricksWarehouseBaseOperator):
+class DatabricksStopWarehouseOperator(_DatabricksWarehouseStateOperator):
"""
Stop a Databricks SQL warehouse and optionally wait for it to stop.
@@ -207,3 +218,47 @@ class
DatabricksStopWarehouseOperator(_DatabricksWarehouseBaseOperator):
if state.state != "STOPPING":
self._hook.stop_warehouse(self.warehouse_id)
self._wait_or_defer("STOPPED")
+
+
+class DatabricksEditWarehouseOperator(_DatabricksWarehouseBaseOperator):
+ """
+ Update the configuration of an existing Databricks SQL warehouse.
+
+ Return ``None`` when the edit request succeeds, without waiting for
configuration changes to finish.
+
+ :param warehouse_id: ID of the Databricks SQL warehouse. (templated)
+ :param json: Non-empty request body for the SQL Warehouses edit API, for
example,
+ ``{"cluster_size": "Small", "auto_stop_mins": 10}``. Use native
template rendering for numeric
+ or boolean Jinja expressions. (templated)
+ :param databricks_conn_id: Reference to the Databricks connection.
+ Defaults to ``databricks_default``. (templated)
+ :param databricks_retry_limit: Maximum number of attempts, including the
initial request.
+ Must be at least 1. Defaults to 3.
+ :param databricks_retry_delay: Minimum delay in seconds under the default
exponential backoff
+ strategy. Defaults to 1.
+ :param databricks_retry_args: Arguments for ``tenacity.Retrying``. A
non-empty dictionary overrides
+ the default retry configuration. Defaults to ``None``.
+ """
+
+ template_fields: Sequence[str] = ("databricks_conn_id", "warehouse_id",
"json")
+ template_fields_renderers = {"json": "json"}
+
+ def __init__(
+ self,
+ warehouse_id: str,
+ *,
+ json: dict[str, Any],
+ databricks_conn_id: str = "databricks_default",
+ **kwargs,
+ ) -> None:
+ super().__init__(warehouse_id=warehouse_id,
databricks_conn_id=databricks_conn_id, **kwargs)
+ self.json = json
+
+ def execute(self, context: Context) -> None:
+ self._validate_warehouse_id()
+ if not isinstance(self.json, dict):
+ raise TypeError("json must be a dictionary.")
+ if not self.json:
+ raise ValueError("json must contain at least one warehouse
setting.")
+ self._hook.edit_warehouse(self.warehouse_id, self.json)
+ self.log.info("Updated configuration for Databricks SQL warehouse
%s.", self.warehouse_id)
diff --git
a/providers/databricks/tests/system/databricks/example_databricks_sql_warehouse.py
b/providers/databricks/tests/system/databricks/example_databricks_sql_warehouse.py
index 81f2f5591b5..f4d22a2dafa 100644
---
a/providers/databricks/tests/system/databricks/example_databricks_sql_warehouse.py
+++
b/providers/databricks/tests/system/databricks/example_databricks_sql_warehouse.py
@@ -14,15 +14,21 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Example Dag for starting and stopping an existing Databricks SQL
warehouse."""
+"""
+Example Dag for editing, starting and stopping an existing Databricks SQL
warehouse.
+
+The original auto-stop setting is saved before editing and restored during
cleanup.
+"""
from __future__ import annotations
import os
from datetime import datetime
-from airflow.providers.common.compat.sdk import DAG
+from airflow.providers.common.compat.sdk import DAG, AirflowSkipException, task
+from airflow.providers.databricks.hooks.databricks import DatabricksHook
from airflow.providers.databricks.operators.warehouse import (
+ DatabricksEditWarehouseOperator,
DatabricksStartWarehouseOperator,
DatabricksStopWarehouseOperator,
)
@@ -36,7 +42,25 @@ with DAG(
start_date=datetime(2021, 1, 1),
tags=["example"],
catchup=False,
+ max_active_runs=1,
) as dag:
+
+ @task
+ def get_original_auto_stop_mins() -> int:
+ hook = DatabricksHook(databricks_conn_id="databricks_default")
+ return hook.get_warehouse(WAREHOUSE_ID)["auto_stop_mins"]
+
+ original_auto_stop_mins = get_original_auto_stop_mins()
+
+ # [START howto_operator_databricks_edit_sql_warehouse]
+ edit_warehouse = DatabricksEditWarehouseOperator(
+ task_id="edit_warehouse",
+ databricks_conn_id="databricks_default",
+ warehouse_id=WAREHOUSE_ID,
+ json={"auto_stop_mins": 10},
+ )
+ # [END howto_operator_databricks_edit_sql_warehouse]
+
# [START howto_operator_databricks_start_sql_warehouse]
start_warehouse = DatabricksStartWarehouseOperator(
task_id="start_warehouse",
@@ -56,7 +80,16 @@ with DAG(
)
# [END howto_operator_databricks_stop_sql_warehouse]
- start_warehouse >> stop_warehouse
+ @task(trigger_rule="all_done")
+ def restore_auto_stop_mins(auto_stop_mins: int | None) -> None:
+ if auto_stop_mins is None:
+ raise AirflowSkipException("The original auto-stop setting was not
saved.")
+ hook = DatabricksHook(databricks_conn_id="databricks_default")
+ hook.edit_warehouse(WAREHOUSE_ID, {"auto_stop_mins": auto_stop_mins})
+
+ restore_warehouse = restore_auto_stop_mins(original_auto_stop_mins)
+
+ original_auto_stop_mins >> edit_warehouse >> start_warehouse >>
stop_warehouse >> restore_warehouse
from tests_common.test_utils.watcher import watcher
diff --git
a/providers/databricks/tests/unit/databricks/hooks/test_databricks.py
b/providers/databricks/tests/unit/databricks/hooks/test_databricks.py
index b73a6990de9..28e700dca21 100644
--- a/providers/databricks/tests/unit/databricks/hooks/test_databricks.py
+++ b/providers/databricks/tests/unit/databricks/hooks/test_databricks.py
@@ -1617,6 +1617,29 @@ class
TestDatabricksHookConnSettings(TestDatabricksHookToken):
class TestWarehouseLifecycle:
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ {"name": "renamed-warehouse"},
+ {
+ "cluster_size": "Small",
+ "min_num_clusters": 1,
+ "max_num_clusters": 2,
+ "auto_stop_mins": 0,
+ "enable_photon": False,
+ "tags": {"custom_tags": [{"key": "team", "value": "data"}]},
+ },
+ ],
+ )
+ @mock.patch.object(DatabricksHook, "_do_api_call", autospec=True)
+ def test_edit_warehouse_endpoint(self, mock_do_api_call, payload):
+ mock_do_api_call.return_value = {}
+ hook = DatabricksHook()
+
+ assert hook.edit_warehouse("wh-1", payload) is None
+
+ mock_do_api_call.assert_called_once_with(hook, ("POST",
"2.0/sql/warehouses/wh-1/edit"), payload)
+
@mock.patch.object(DatabricksHook, "_do_api_call", autospec=True)
def test_get_warehouse_calls_correct_endpoint(self, mock_do_api_call):
mock_do_api_call.return_value = {"id": "wh-1", "state": "RUNNING"}
diff --git
a/providers/databricks/tests/unit/databricks/operators/test_warehouse.py
b/providers/databricks/tests/unit/databricks/operators/test_warehouse.py
index c0aa0de03b1..9d9e6c74a00 100644
--- a/providers/databricks/tests/unit/databricks/operators/test_warehouse.py
+++ b/providers/databricks/tests/unit/databricks/operators/test_warehouse.py
@@ -23,10 +23,11 @@ import pytest
import time_machine
from tenacity import stop_after_attempt, wait_incrementing
-from airflow.providers.common.compat.sdk import TaskDeferred
+from airflow.providers.common.compat.sdk import DAG, TaskDeferred
from airflow.providers.databricks.exceptions import DatabricksWarehouseError
from airflow.providers.databricks.hooks.databricks import DatabricksHook,
WarehouseState
from airflow.providers.databricks.operators.warehouse import (
+ DatabricksEditWarehouseOperator,
DatabricksStartWarehouseOperator,
DatabricksStopWarehouseOperator,
)
@@ -36,6 +37,101 @@ TASK_ID = "warehouse-lifecycle"
WAREHOUSE_ID = "wh-1"
+class TestDatabricksEditWarehouseOperator:
+
@mock.patch("airflow.providers.databricks.operators.warehouse.DatabricksHook",
autospec=True)
+ def test_execute(self, mock_hook):
+ payload = {"cluster_size": "Small", "auto_stop_mins": 0,
"enable_photon": False}
+ retry_args = {"stop": stop_after_attempt(5)}
+ operator = DatabricksEditWarehouseOperator(
+ task_id=TASK_ID,
+ warehouse_id=WAREHOUSE_ID,
+ json=payload,
+ databricks_conn_id="custom_databricks",
+ databricks_retry_limit=5,
+ databricks_retry_delay=2,
+ databricks_retry_args=retry_args,
+ )
+
+ assert operator.execute(None) is None
+
+ mock_hook.assert_called_once_with(
+ "custom_databricks",
+ retry_limit=5,
+ retry_delay=2,
+ retry_args=retry_args,
+ caller="DatabricksEditWarehouseOperator",
+ )
+ assert mock_hook.return_value.mock_calls ==
[mock.call.edit_warehouse(WAREHOUSE_ID, payload)]
+
+
@mock.patch("airflow.providers.databricks.operators.warehouse.DatabricksHook",
autospec=True)
+ def test_execute_renders_templates(self, mock_hook):
+ with DAG(dag_id="edit_warehouse", render_template_as_native_obj=True):
+ operator = DatabricksEditWarehouseOperator(
+ task_id=TASK_ID,
+ warehouse_id="{{ params.warehouse_id }}",
+ databricks_conn_id="{{ params.conn_id }}",
+ json={
+ "auto_stop_mins": "{{ params.auto_stop_mins }}",
+ "enable_photon": "{{ params.enable_photon }}",
+ "tags": {"custom_tags": [{"key": "run_date", "value": "{{
ds }}"}]},
+ },
+ )
+ operator.render_template_fields(
+ context={
+ "ds": "2026-11-04",
+ "params": {
+ "warehouse_id": WAREHOUSE_ID,
+ "conn_id": "rendered_databricks",
+ "auto_stop_mins": 0,
+ "enable_photon": False,
+ },
+ }
+ )
+
+ operator.execute(None)
+
+ assert mock_hook.call_args.args == ("rendered_databricks",)
+ mock_hook.return_value.edit_warehouse.assert_called_once_with(
+ WAREHOUSE_ID,
+ {
+ "auto_stop_mins": 0,
+ "enable_photon": False,
+ "tags": {"custom_tags": [{"key": "run_date", "value":
"2026-11-04"}]},
+ },
+ )
+
+
@mock.patch("airflow.providers.databricks.operators.warehouse.DatabricksHook",
autospec=True)
+ def test_rejects_empty_rendered_warehouse_id(self, mock_hook):
+ operator = DatabricksEditWarehouseOperator(
+ task_id=TASK_ID, warehouse_id="{{ params.warehouse_id }}",
json={"auto_stop_mins": 10}
+ )
+ operator.render_template_fields(context={"params": {"warehouse_id":
""}})
+
+ with pytest.raises(ValueError, match="warehouse_id must be provided"):
+ operator.execute(None)
+
+ mock_hook.assert_not_called()
+
+ @pytest.mark.parametrize("payload", [None, [], '{"auto_stop_mins": 10}'])
+
@mock.patch("airflow.providers.databricks.operators.warehouse.DatabricksHook",
autospec=True)
+ def test_rejects_non_dictionary_payload(self, mock_hook, payload):
+ operator = DatabricksEditWarehouseOperator(task_id=TASK_ID,
warehouse_id=WAREHOUSE_ID, json=payload)
+
+ with pytest.raises(TypeError, match="json must be a dictionary"):
+ operator.execute(None)
+
+ mock_hook.assert_not_called()
+
+
@mock.patch("airflow.providers.databricks.operators.warehouse.DatabricksHook",
autospec=True)
+ def test_rejects_empty_payload(self, mock_hook):
+ operator = DatabricksEditWarehouseOperator(task_id=TASK_ID,
warehouse_id=WAREHOUSE_ID, json={})
+
+ with pytest.raises(ValueError, match="json must contain at least one
warehouse setting"):
+ operator.execute(None)
+
+ mock_hook.assert_not_called()
+
+
class TestDatabricksStartWarehouseOperator:
@pytest.mark.parametrize(
"first_polled_state",