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 fe75ac49523 Template SQL statements and parameters in Databricks 
operator (#76709)
fe75ac49523 is described below

commit fe75ac49523a2db634a3ff0be5df11616e45e0f9
Author: Alejandro Morgante <[email protected]>
AuthorDate: Sat Nov 21 14:49:03 2026 -0300

    Template SQL statements and parameters in Databricks operator (#76709)
---
 .../databricks/docs/operators/sql_statements.rst   | 10 +++
 .../providers/databricks/operators/databricks.py   |  7 +-
 .../example_databricks_sql_statement_parameters.py | 79 ++++++++++++++++++++++
 .../unit/databricks/operators/test_databricks.py   | 25 +++++++
 4 files changed, 118 insertions(+), 3 deletions(-)

diff --git a/providers/databricks/docs/operators/sql_statements.rst 
b/providers/databricks/docs/operators/sql_statements.rst
index 58954a06fea..7bd68d07846 100644
--- a/providers/databricks/docs/operators/sql_statements.rst
+++ b/providers/databricks/docs/operators/sql_statements.rst
@@ -50,6 +50,9 @@ but not limited to:
   (``dag_id``, ``task_id``, ``run_id``, ``try_number``, ``map_index``) is 
merged into
   ``query_tags`` automatically. Set to ``False`` to suppress these automatic 
tags.
 
+The ``statement`` and nested ``parameters`` values support Jinja templating. 
Use SQL parameter
+markers such as ``:run_date`` to bind values rendered from the Airflow context.
+
 Examples
 --------
 
@@ -60,6 +63,13 @@ An example usage of the ``DatabricksSQLStatementsOperator`` 
is as follows:
     :start-after: [START howto_operator_sql_statements]
     :end-before: [END howto_operator_sql_statements]
 
+The following example uses templated SQL and bound parameters:
+
+.. exampleinclude:: 
/../../databricks/tests/system/databricks/example_databricks_sql_statement_parameters.py
+    :language: python
+    :start-after: [START howto_operator_sql_statement_parameters]
+    :end-before: [END howto_operator_sql_statement_parameters]
+
 
 .. _howto/sensor:DatabricksSQLStatementsSensor:
 
diff --git 
a/providers/databricks/src/airflow/providers/databricks/operators/databricks.py 
b/providers/databricks/src/airflow/providers/databricks/operators/databricks.py
index b8a98ac09d6..b27b2708f26 100644
--- 
a/providers/databricks/src/airflow/providers/databricks/operators/databricks.py
+++ 
b/providers/databricks/src/airflow/providers/databricks/operators/databricks.py
@@ -1654,11 +1654,12 @@ class 
DatabricksSQLStatementsOperator(DatabricksSQLStatementsMixin, BaseOperator
         For more information on how to use this operator, take a look at the 
guide:
         :ref:`howto/operator:DatabricksSQLStatementsOperator`
 
-    :param statement: The SQL statement to execute. The statement can 
optionally be parameterized, see parameters.
+    :param statement: The SQL statement to execute. The statement can 
optionally be parameterized,
+        see parameters. (templated)
     :param warehouse_id: Warehouse upon which to execute a statement.
     :param catalog: Sets default catalog for statement execution, similar to 
USE CATALOG in SQL.
     :param schema: Sets default schema for statement execution, similar to USE 
SCHEMA in SQL.
-    :param parameters: A list of parameters to pass into a SQL statement 
containing parameter markers.
+    :param parameters: A list of parameters to pass into a SQL statement 
containing parameter markers. (templated)
 
         .. seealso::
             
https://docs.databricks.com/api/workspace/statementexecution/executestatement#parameters
@@ -1687,7 +1688,7 @@ class 
DatabricksSQLStatementsOperator(DatabricksSQLStatementsMixin, BaseOperator
     """
 
     # Used in airflow.models.BaseOperator
-    template_fields: Sequence[str] = ("databricks_conn_id", "query_tags")
+    template_fields: Sequence[str] = ("databricks_conn_id", "query_tags", 
"statement", "parameters")
     template_ext: Sequence[str] = (".json-tpl",)
     # Databricks brand color (blue) under white text
     ui_color = "#1CB1C2"
diff --git 
a/providers/databricks/tests/system/databricks/example_databricks_sql_statement_parameters.py
 
b/providers/databricks/tests/system/databricks/example_databricks_sql_statement_parameters.py
new file mode 100644
index 00000000000..02e6ea75162
--- /dev/null
+++ 
b/providers/databricks/tests/system/databricks/example_databricks_sql_statement_parameters.py
@@ -0,0 +1,79 @@
+# 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.
+"""Execute a templated SQL statement with bound parameters on an existing SQL 
warehouse."""
+
+from __future__ import annotations
+
+import os
+from datetime import datetime
+
+from airflow.providers.common.compat.sdk import DAG, task
+from airflow.providers.databricks.hooks.databricks import DatabricksHook
+from airflow.providers.databricks.operators.databricks import 
DatabricksSQLStatementsOperator
+from airflow.providers.databricks.operators.warehouse import 
DatabricksStopWarehouseOperator
+
+from tests_common.test_utils.watcher import watcher
+
+WAREHOUSE_ID = os.environ.get("WAREHOUSE_ID", "your-warehouse-id")
+
+with DAG(
+    dag_id="example_databricks_sql_statement_parameters",
+    schedule=None,
+    start_date=datetime(2021, 1, 1),
+    catchup=False,
+    tags=["example"],
+    params={"client": "airflow", "row_count": 2, "increment": 1},
+) as dag:
+    # [START howto_operator_sql_statement_parameters]
+    sql_statement = DatabricksSQLStatementsOperator(
+        task_id="sql_statement",
+        databricks_conn_id="databricks_default",
+        warehouse_id=WAREHOUSE_ID,
+        statement="""
+            SELECT :run_date AS run_date,
+                   :client AS client,
+                   :row_count + {{ params.increment }} AS total
+        """,
+        parameters=[
+            {"name": "run_date", "value": "{{ ds }}", "type": "STRING"},
+            {"name": "client", "value": "{{ params.client }}", "type": 
"STRING"},
+            {"name": "row_count", "value": "{{ params.row_count }}", "type": 
"INT"},
+        ],
+    )
+    # [END howto_operator_sql_statement_parameters]
+
+    @task
+    def validate_result(statement_id: str, run_date: str) -> None:
+        hook = DatabricksHook(databricks_conn_id="databricks_default")
+        response = hook._do_api_call(("GET", 
f"2.0/sql/statements/{statement_id}"))
+        assert response["result"]["data_array"] == [[run_date, "airflow", "3"]]
+
+    check_result = validate_result(sql_statement.output["statement_id"], "{{ 
ds }}")
+
+    stop_warehouse = DatabricksStopWarehouseOperator(
+        task_id="stop_warehouse",
+        warehouse_id=WAREHOUSE_ID,
+        trigger_rule="all_done",
+    )
+
+    sql_statement >> check_result >> stop_warehouse
+    list(dag.tasks) >> watcher()
+
+from tests_common.test_utils.system_tests import get_test_run  # noqa: E402
+
+# Needed to run the example Dag with pytest (see: 
contributing-docs/testing/system_tests.rst)
+test_run = get_test_run(dag)
diff --git 
a/providers/databricks/tests/unit/databricks/operators/test_databricks.py 
b/providers/databricks/tests/unit/databricks/operators/test_databricks.py
index f9a7e900ef9..16278ef289d 100644
--- a/providers/databricks/tests/unit/databricks/operators/test_databricks.py
+++ b/providers/databricks/tests/unit/databricks/operators/test_databricks.py
@@ -3755,6 +3755,31 @@ class TestDatabricksRunNowOperatorDurable:
 
 
 class TestDatabricksSQLStatementsOperator:
+    
@mock.patch("airflow.providers.databricks.operators.databricks.DatabricksHook", 
autospec=True)
+    def test_execute_renders_statement_and_parameters(self, mock_hook):
+        op = DatabricksSQLStatementsOperator(
+            task_id=TASK_ID,
+            statement="SELECT {{ params.expression }} WHERE event_date = 
:event_date",
+            warehouse_id=WAREHOUSE_ID,
+            parameters=[{"name": "event_date", "value": "{{ ds }}", "type": 
"DATE"}],
+            wait_for_termination=False,
+            include_airflow_query_tags=False,
+        )
+        op.render_template_fields(context={"ds": DATE, "params": 
{"expression": "COUNT(*)"}})
+
+        op.execute(None)
+
+        mock_hook.return_value.post_sql_statement.assert_called_once_with(
+            {
+                "statement": "SELECT COUNT(*) WHERE event_date = :event_date",
+                "warehouse_id": WAREHOUSE_ID,
+                "catalog": None,
+                "schema": None,
+                "parameters": [{"name": "event_date", "value": DATE, "type": 
"DATE"}],
+                "wait_timeout": "0s",
+            }
+        )
+
     def test_init(self):
         """
         Test the initializer.

Reply via email to