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 89e7490b780 Add deferrable mode to InfluxDB 3 Operator (#71976)
89e7490b780 is described below
commit 89e7490b7804c31efe8998d80685a0cee86ed7f4
Author: Subhramit Basu <[email protected]>
AuthorDate: Tue Sep 22 10:17:34 2026 +0530
Add deferrable mode to InfluxDB 3 Operator (#71976)
---
providers/influxdb/README.rst | 13 ++--
providers/influxdb/docs/index.rst | 13 ++--
providers/influxdb/docs/operators/index.rst | 22 ++++++
providers/influxdb/provider.yaml | 5 ++
providers/influxdb/pyproject.toml | 7 +-
.../providers/influxdb/get_provider_info.py | 6 ++
.../airflow/providers/influxdb/hooks/influxdb3.py | 34 ++++++++-
.../providers/influxdb/operators/influxdb3.py | 39 +++++++++--
.../providers/influxdb/triggers/__init__.py | 16 +++++
.../providers/influxdb/triggers/influxdb3.py | 78 +++++++++++++++++++++
.../src/airflow/providers/influxdb/utils.py | 30 ++++++++
.../tests/system/influxdb/example_influxdb3.py | 11 ++-
.../tests/unit/influxdb/hooks/test_influxdb3.py | 50 +++++++++++--
.../unit/influxdb/operators/test_influxdb3.py | 79 ++++++++++++++++++++-
.../influxdb/tests/unit/influxdb/test_utils.py | 35 ++++++++++
.../tests/unit/influxdb/triggers/__init__.py | 16 +++++
.../tests/unit/influxdb/triggers/test_influxdb3.py | 81 ++++++++++++++++++++++
uv.lock | 7 +-
18 files changed, 515 insertions(+), 27 deletions(-)
diff --git a/providers/influxdb/README.rst b/providers/influxdb/README.rst
index 45317984fe1..d344c9cec16 100644
--- a/providers/influxdb/README.rst
+++ b/providers/influxdb/README.rst
@@ -50,15 +50,18 @@ The package supports the following python versions:
3.10,3.11,3.12,3.13,3.14
Requirements
------------
-========================================== ==================
+==========================================
=================================================================
PIP package Version required
-========================================== ==================
+==========================================
=================================================================
``apache-airflow`` ``>=2.11.0``
-``apache-airflow-providers-common-compat`` ``>=1.8.0``
+``apache-airflow-providers-common-compat`` ``>=1.17.0``
+``pandas`` ``>=2.1.2; python_version <
"3.13"``
+``pandas`` ``>=2.2.3; python_version >=
"3.13" and python_version < "3.14"``
+``pandas`` ``>=2.3.3; python_version >=
"3.14"``
``influxdb-client`` ``>=1.19.0``
-``influxdb3-python`` ``>=0.7.0``
+``influxdb3-python`` ``>=0.12.0``
``requests`` ``>=2.32.0,<3``
-========================================== ==================
+==========================================
=================================================================
The changelog for the provider package can be found in the
`changelog
<https://airflow.apache.org/docs/apache-airflow-providers-influxdb/2.11.1/changelog.html>`_.
diff --git a/providers/influxdb/docs/index.rst
b/providers/influxdb/docs/index.rst
index c132c22c1df..c2f8f50f149 100644
--- a/providers/influxdb/docs/index.rst
+++ b/providers/influxdb/docs/index.rst
@@ -98,15 +98,18 @@ Requirements
The minimum Apache Airflow version supported by this provider distribution is
``2.11.0``.
-========================================== ==================
+==========================================
=================================================================
PIP package Version required
-========================================== ==================
+==========================================
=================================================================
``apache-airflow`` ``>=2.11.0``
-``apache-airflow-providers-common-compat`` ``>=1.8.0``
+``apache-airflow-providers-common-compat`` ``>=1.17.0``
+``pandas`` ``>=2.1.2; python_version <
"3.13"``
+``pandas`` ``>=2.2.3; python_version >=
"3.13" and python_version < "3.14"``
+``pandas`` ``>=2.3.3; python_version >=
"3.14"``
``influxdb-client`` ``>=1.19.0``
-``influxdb3-python`` ``>=0.7.0``
+``influxdb3-python`` ``>=0.12.0``
``requests`` ``>=2.32.0,<3``
-========================================== ==================
+==========================================
=================================================================
Downloading official packages
-----------------------------
diff --git a/providers/influxdb/docs/operators/index.rst
b/providers/influxdb/docs/operators/index.rst
index 8f0eeff1271..b768097edd0 100644
--- a/providers/influxdb/docs/operators/index.rst
+++ b/providers/influxdb/docs/operators/index.rst
@@ -46,3 +46,25 @@ Example usage:
:language: python
:start-after: [START howto_operator_influxdb3]
:end-before: [END howto_operator_influxdb3]
+
+Deferrable mode
+^^^^^^^^^^^^^^^
+
+Set ``deferrable=True`` to release the worker slot while the query runs. The
task is resumed by the
+:class:`~airflow.providers.influxdb.triggers.influxdb3.InfluxDB3QueryTrigger`
once results are ready.
+
+.. exampleinclude:: /../../influxdb/tests/system/influxdb/example_influxdb3.py
+ :language: python
+ :start-after: [START howto_operator_influxdb3_deferrable]
+ :end-before: [END howto_operator_influxdb3_deferrable]
+
+.. note::
+
+ This implementation follows the upstream ``influxdb3-python`` client,
which documents querying
+ through the `Flight client
<https://influxdb3-python.readthedocs.io/en/latest/>`__ and exposes
+ `query_async()
<https://influxdb3-python.readthedocs.io/en/latest/api_reference/>`__ for
+ asynchronous query execution.
+
+ Results still travel back through XCom, so deferring is most useful for
long-running queries
+ with small-to-moderate result sets. For very large extracts, keep using
+ :class:`~airflow.providers.influxdb.hooks.influxdb3.InfluxDB3Hook` from a
Python task.
diff --git a/providers/influxdb/provider.yaml b/providers/influxdb/provider.yaml
index 0c9bd8efab8..83c69c3e71a 100644
--- a/providers/influxdb/provider.yaml
+++ b/providers/influxdb/provider.yaml
@@ -91,6 +91,11 @@ operators:
python-modules:
- airflow.providers.influxdb.operators.influxdb3
+triggers:
+ - integration-name: InfluxDB 3
+ python-modules:
+ - airflow.providers.influxdb.triggers.influxdb3
+
connection-types:
- hook-class-name: airflow.providers.influxdb.hooks.influxdb.InfluxDBHook
hook-name: "Influxdb"
diff --git a/providers/influxdb/pyproject.toml
b/providers/influxdb/pyproject.toml
index 1fec096cbfe..6f699a4974f 100644
--- a/providers/influxdb/pyproject.toml
+++ b/providers/influxdb/pyproject.toml
@@ -60,9 +60,12 @@ requires-python = ">=3.10"
# After you modify the dependencies, and rebuild your Breeze CI image with
``breeze ci-image build``
dependencies = [
"apache-airflow>=2.11.0",
- "apache-airflow-providers-common-compat>=1.8.0",
+ "apache-airflow-providers-common-compat>=1.17.0",
+ 'pandas>=2.1.2; python_version <"3.13"',
+ 'pandas>=2.2.3; python_version >="3.13" and python_version <"3.14"',
+ 'pandas>=2.3.3; python_version >="3.14"',
"influxdb-client>=1.19.0",
- "influxdb3-python>=0.7.0",
+ "influxdb3-python>=0.12.0",
"requests>=2.32.0,<3",
]
diff --git
a/providers/influxdb/src/airflow/providers/influxdb/get_provider_info.py
b/providers/influxdb/src/airflow/providers/influxdb/get_provider_info.py
index f8334178029..0b2011da40f 100644
--- a/providers/influxdb/src/airflow/providers/influxdb/get_provider_info.py
+++ b/providers/influxdb/src/airflow/providers/influxdb/get_provider_info.py
@@ -56,6 +56,12 @@ def get_provider_info():
"python-modules":
["airflow.providers.influxdb.operators.influxdb3"],
},
],
+ "triggers": [
+ {
+ "integration-name": "InfluxDB 3",
+ "python-modules":
["airflow.providers.influxdb.triggers.influxdb3"],
+ }
+ ],
"connection-types": [
{
"hook-class-name":
"airflow.providers.influxdb.hooks.influxdb.InfluxDBHook",
diff --git
a/providers/influxdb/src/airflow/providers/influxdb/hooks/influxdb3.py
b/providers/influxdb/src/airflow/providers/influxdb/hooks/influxdb3.py
index 0659e056813..1f1a3e7efa5 100644
--- a/providers/influxdb/src/airflow/providers/influxdb/hooks/influxdb3.py
+++ b/providers/influxdb/src/airflow/providers/influxdb/hooks/influxdb3.py
@@ -41,12 +41,13 @@ except ImportError:
InfluxDBClient3 = None # type: ignore[assignment, misc]
Point = None # type: ignore[assignment, misc]
+from airflow.providers.common.compat.connection import get_async_connection
from airflow.providers.common.compat.sdk import BaseHook
if TYPE_CHECKING:
import pandas as pd
- from airflow.models import Connection
+ from airflow.providers.common.compat.sdk import Connection
class InfluxDB3Hook(BaseHook):
@@ -148,7 +149,14 @@ class InfluxDB3Hook(BaseHook):
- Connection password field (as fallback for token)
- Connection extras JSON (for manual configuration)
"""
- self.connection = self.get_connection(self.influxdb3_conn_id)
+ return self._create_client(self.get_connection(self.influxdb3_conn_id))
+
+ async def aget_conn(self) -> InfluxDBClient3:
+ """Initiate a new InfluxDB 3.x connection asynchronously."""
+ return self._create_client(await
get_async_connection(self.influxdb3_conn_id, hook=self))
+
+ def _create_client(self, connection: Connection) -> InfluxDBClient3:
+ self.connection = connection
self.extras = self.connection.extra_dejson.copy()
self.uri = self.get_uri(self.connection)
@@ -205,6 +213,28 @@ class InfluxDB3Hook(BaseHook):
return result
+ async def query_async(self, query: str) -> pd.DataFrame:
+ """
+ Run a SQL query from the triggerer and return results as a pandas
DataFrame.
+
+ :param query: SQL query string
+ :return: pandas DataFrame with query results
+ """
+ client = await self.aget_conn()
+ import pandas as pd
+
+ # InfluxDB 3 does not expose a submit-then-poll query API, so this
coroutine
+ # resolves only after the full result stream has been read.
+ result = await client.query_async(query=query, language="sql",
mode="pandas")
+
+ if not isinstance(result, pd.DataFrame):
+ raise ValueError(
+ f"Query did not return a DataFrame. "
+ f"Result type:
{type(result).__module__}.{type(result).__name__}"
+ )
+
+ return result
+
def write(
self,
measurement: str,
diff --git
a/providers/influxdb/src/airflow/providers/influxdb/operators/influxdb3.py
b/providers/influxdb/src/airflow/providers/influxdb/operators/influxdb3.py
index f863a057906..1fd8adc1114 100644
--- a/providers/influxdb/src/airflow/providers/influxdb/operators/influxdb3.py
+++ b/providers/influxdb/src/airflow/providers/influxdb/operators/influxdb3.py
@@ -19,12 +19,13 @@
from __future__ import annotations
-import json
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
-from airflow.providers.common.compat.sdk import BaseOperator
+from airflow.providers.common.compat.sdk import BaseOperator, conf
from airflow.providers.influxdb.hooks.influxdb3 import InfluxDB3Hook
+from airflow.providers.influxdb.triggers.influxdb3 import InfluxDB3QueryTrigger
+from airflow.providers.influxdb.utils import _convert_dataframe_to_records
if TYPE_CHECKING:
from airflow.sdk.definitions.context import Context
@@ -40,6 +41,10 @@ class InfluxDB3Operator(BaseOperator):
:param sql: The SQL query to be executed
:param influxdb3_conn_id: Reference to :ref:`InfluxDB 3 connection id
<howto/connection:influxdb3>`.
+ :param deferrable: Run the query from the triggerer so the worker slot is
released while the
+ query runs. This is most useful for long-running queries that return
small-to-moderate
+ result sets because the full result still flows back through XCom.
Defaults to the
+ ``operators.default_deferrable`` configuration (``False`` if unset).
"""
template_fields: Sequence[str] = ("sql",)
@@ -49,11 +54,13 @@ class InfluxDB3Operator(BaseOperator):
*,
sql: str,
influxdb3_conn_id: str = "influxdb3_default",
+ deferrable: bool = conf.getboolean("operators", "default_deferrable",
fallback=False),
**kwargs,
) -> None:
super().__init__(**kwargs)
self.influxdb3_conn_id = influxdb3_conn_id
self.sql = sql
+ self.deferrable = deferrable
def execute(self, context: Context) -> list[dict[str, Any]]:
"""
@@ -63,10 +70,34 @@ class InfluxDB3Operator(BaseOperator):
:return: List of dictionaries representing query results
"""
self.log.info("Executing SQL query: %s", self.sql)
+
+ if self.deferrable:
+ self.defer(
+ timeout=self.execution_timeout,
+ trigger=InfluxDB3QueryTrigger(
+ sql=self.sql,
+ influxdb3_conn_id=self.influxdb3_conn_id,
+ ),
+ method_name="execute_complete",
+ )
+
hook = InfluxDB3Hook(conn_id=self.influxdb3_conn_id)
result = hook.query(self.sql)
self.log.info("Query executed successfully. Rows returned: %d",
len(result))
+ return _convert_dataframe_to_records(result)
+
+ def execute_complete(self, context: Context, event: dict[str, Any] | None
= None) -> list[dict[str, Any]]:
+ """Return the query results produced by
:class:`InfluxDB3QueryTrigger`."""
+ if event is None:
+ raise RuntimeError("InfluxDB 3 query did not return an event")
+
+ status = event.get("status")
+ if status == "error":
+ raise RuntimeError(event.get("message", "InfluxDB 3 query failed"))
+ if status != "success":
+ raise RuntimeError(f"InfluxDB 3 query returned unexpected status:
{status!r}")
- json_str = result.to_json(orient="records", date_format="iso")
- return json.loads(json_str)
+ records = event["records"]
+ self.log.info("Query executed successfully. Rows returned: %d",
len(records))
+ return records
diff --git
a/providers/influxdb/src/airflow/providers/influxdb/triggers/__init__.py
b/providers/influxdb/src/airflow/providers/influxdb/triggers/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ b/providers/influxdb/src/airflow/providers/influxdb/triggers/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git
a/providers/influxdb/src/airflow/providers/influxdb/triggers/influxdb3.py
b/providers/influxdb/src/airflow/providers/influxdb/triggers/influxdb3.py
new file mode 100644
index 00000000000..f9bf999fca2
--- /dev/null
+++ b/providers/influxdb/src/airflow/providers/influxdb/triggers/influxdb3.py
@@ -0,0 +1,78 @@
+# 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.
+"""Trigger for running InfluxDB 3.x SQL queries from the triggerer."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import TYPE_CHECKING, Any
+
+from airflow.providers.influxdb.hooks.influxdb3 import InfluxDB3Hook
+from airflow.providers.influxdb.utils import _convert_dataframe_to_records
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator
+
+
+class InfluxDB3QueryTrigger(BaseTrigger):
+ """
+ Run a SQL query against InfluxDB 3.x without occupying a worker slot.
+
+ InfluxDB 3 executes queries over a single Apache Arrow Flight stream:
there is no
+ server-side job to submit and then poll for completion, and therefore no
query state
+ and no poll interval. The trigger instead awaits the query coroutine once
and emits a
+ single event when the stream has been fully read.
+
+ ``influxdb3-python`` implements ``query_async`` by running the blocking
Flight calls in
+ the event loop's default executor, so concurrency in the triggerer is
bounded by that
+ thread pool rather than by native async IO. This is a limitation of the
upstream client,
+ not of this trigger.
+
+ :param sql: The SQL query to be executed.
+ :param influxdb3_conn_id: Reference to :ref:`InfluxDB 3 connection id
<howto/connection:influxdb3>`.
+ """
+
+ def __init__(
+ self,
+ sql: str,
+ influxdb3_conn_id: str = "influxdb3_default",
+ ) -> None:
+ super().__init__()
+ self.sql = sql
+ self.influxdb3_conn_id = influxdb3_conn_id
+
+ def serialize(self) -> tuple[str, dict[str, Any]]:
+ return (
+
"airflow.providers.influxdb.triggers.influxdb3.InfluxDB3QueryTrigger",
+ {
+ "sql": self.sql,
+ "influxdb3_conn_id": self.influxdb3_conn_id,
+ },
+ )
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ hook = InfluxDB3Hook(conn_id=self.influxdb3_conn_id)
+ try:
+ dataframe = await hook.query_async(self.sql)
+ records = await asyncio.to_thread(_convert_dataframe_to_records,
dataframe)
+ except Exception as error:
+ self.log.exception("InfluxDB 3 query failed in trigger")
+ yield TriggerEvent({"status": "error", "message": str(error)})
+ return
+
+ yield TriggerEvent({"status": "success", "records": records})
diff --git a/providers/influxdb/src/airflow/providers/influxdb/utils.py
b/providers/influxdb/src/airflow/providers/influxdb/utils.py
new file mode 100644
index 00000000000..79abb8d6ee2
--- /dev/null
+++ b/providers/influxdb/src/airflow/providers/influxdb/utils.py
@@ -0,0 +1,30 @@
+# 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.
+"""Internal helpers shared across the InfluxDB provider."""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ import pandas as pd
+
+
+def _convert_dataframe_to_records(dataframe: pd.DataFrame) -> list[dict[str,
Any]]:
+ """Convert a query result DataFrame into a JSON-serializable list of
dictionaries."""
+ return json.loads(dataframe.to_json(orient="records", date_format="iso"))
diff --git a/providers/influxdb/tests/system/influxdb/example_influxdb3.py
b/providers/influxdb/tests/system/influxdb/example_influxdb3.py
index 10dc16a5023..ef8029e58b9 100644
--- a/providers/influxdb/tests/system/influxdb/example_influxdb3.py
+++ b/providers/influxdb/tests/system/influxdb/example_influxdb3.py
@@ -57,6 +57,15 @@ query_task = InfluxDB3Operator(
)
# [END howto_operator_influxdb3]
+# [START howto_operator_influxdb3_deferrable]
+deferrable_query_task = InfluxDB3Operator(
+ task_id="query_data_deferrable",
+ sql="""SELECT * FROM "temperature" WHERE time > now() - INTERVAL '1
hour'""",
+ influxdb3_conn_id="influxdb3_default",
+ deferrable=True,
+)
+# [END howto_operator_influxdb3_deferrable]
+
ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID")
DAG_ID = "influxdb3_example_dag"
@@ -68,7 +77,7 @@ with DAG(
tags=["example", "influxdb3"],
) as dag:
write_task = write_to_influxdb3()
- write_task >> query_task
+ write_task >> [query_task, deferrable_query_task]
from tests_common.test_utils.watcher import watcher
diff --git a/providers/influxdb/tests/unit/influxdb/hooks/test_influxdb3.py
b/providers/influxdb/tests/unit/influxdb/hooks/test_influxdb3.py
index afc7a3e1164..6332bb88e9b 100644
--- a/providers/influxdb/tests/unit/influxdb/hooks/test_influxdb3.py
+++ b/providers/influxdb/tests/unit/influxdb/hooks/test_influxdb3.py
@@ -18,6 +18,7 @@ from __future__ import annotations
from unittest import mock
+import pandas as pd
import pytest
from airflow.models import Connection
@@ -52,6 +53,21 @@ class TestInfluxDB3Hook:
assert self.influxdb3_hook.get_client is not None
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.influxdb.hooks.influxdb3.InfluxDBClient3")
+
@mock.patch("airflow.providers.influxdb.hooks.influxdb3.get_async_connection")
+ async def test_aget_conn(self, get_async_connection, influx_db_client_3):
+ """Test async connection to InfluxDB 3.x."""
+ get_async_connection.return_value = self.connection
+
+ await self.influxdb3_hook.aget_conn()
+
+ assert self.influxdb3_hook.uri == "https://localhost:8086"
+ get_async_connection.assert_awaited_once_with("influxdb3_default",
hook=self.influxdb3_hook)
+ influx_db_client_3.assert_called_once_with(
+ host="https://localhost:8086", token="123456789",
database="test_db", org="test_org"
+ )
+
def test_get_conn_missing_database(self):
"""Test that InfluxDB 3.x requires database parameter."""
extra = {}
@@ -68,9 +84,7 @@ class TestInfluxDB3Hook:
def test_query(self):
"""Test query with InfluxDB 3.x."""
- pd = pytest.importorskip("pandas")
-
- self.influxdb3_hook.client = mock.Mock()
+ self.influxdb3_hook.client = mock.Mock(spec_set=["query"])
mock_df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
self.influxdb3_hook.client.query = mock.Mock(return_value=mock_df)
self.influxdb3_hook.get_conn =
mock.Mock(return_value=self.influxdb3_hook.client)
@@ -85,9 +99,37 @@ class TestInfluxDB3Hook:
assert isinstance(result, pd.DataFrame)
assert len(result) == 2
+ @pytest.mark.asyncio
+ async def test_query_async(self):
+ """Test async query with InfluxDB 3.x."""
+ self.influxdb3_hook.client = mock.Mock(spec_set=["query_async"])
+ mock_df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
+ self.influxdb3_hook.client.query_async =
mock.AsyncMock(return_value=mock_df)
+ self.influxdb3_hook.aget_conn =
mock.AsyncMock(return_value=self.influxdb3_hook.client)
+
+ influxdb_query = 'SELECT "duration" FROM "pyexample"'
+ result = await self.influxdb3_hook.query_async(influxdb_query)
+
+ self.influxdb3_hook.aget_conn.assert_awaited_once_with()
+ self.influxdb3_hook.client.query_async.assert_awaited_once_with(
+ query=influxdb_query, language="sql", mode="pandas"
+ )
+ assert isinstance(result, pd.DataFrame)
+ assert result.equals(mock_df)
+
+ @pytest.mark.asyncio
+ async def test_query_async_requires_dataframe_result(self):
+ """Async query results must resolve to a pandas DataFrame."""
+ self.influxdb3_hook.client = mock.Mock(spec_set=["query_async"])
+ self.influxdb3_hook.client.query_async =
mock.AsyncMock(return_value=[{"col1": 1}])
+ self.influxdb3_hook.aget_conn =
mock.AsyncMock(return_value=self.influxdb3_hook.client)
+
+ with pytest.raises(ValueError, match="did not return a DataFrame"):
+ await self.influxdb3_hook.query_async('SELECT "duration" FROM
"pyexample"')
+
def test_write(self):
"""Test write with InfluxDB 3.x."""
- self.influxdb3_hook.client = mock.Mock()
+ self.influxdb3_hook.client = mock.Mock(spec_set=["write"])
self.influxdb3_hook.client.write = mock.Mock()
self.influxdb3_hook.get_conn =
mock.Mock(return_value=self.influxdb3_hook.client)
diff --git a/providers/influxdb/tests/unit/influxdb/operators/test_influxdb3.py
b/providers/influxdb/tests/unit/influxdb/operators/test_influxdb3.py
index d67028ad03a..f29b38fc5d6 100644
--- a/providers/influxdb/tests/unit/influxdb/operators/test_influxdb3.py
+++ b/providers/influxdb/tests/unit/influxdb/operators/test_influxdb3.py
@@ -16,11 +16,15 @@
# under the License.
from __future__ import annotations
+from datetime import timedelta
from unittest import mock
+import pandas as pd
import pytest
+from airflow.exceptions import TaskDeferred
from airflow.providers.influxdb.operators.influxdb3 import InfluxDB3Operator
+from airflow.providers.influxdb.triggers.influxdb3 import InfluxDB3QueryTrigger
class TestInfluxDB3Operator:
@@ -36,13 +40,12 @@ class TestInfluxDB3Operator:
assert self.operator.sql == 'SELECT "duration" FROM "pyexample"'
assert self.operator.influxdb3_conn_id == "influxdb3_default"
assert "sql" in self.operator.template_fields
+ assert self.operator.deferrable is False
- @mock.patch("airflow.providers.influxdb.operators.influxdb3.InfluxDB3Hook")
+
@mock.patch("airflow.providers.influxdb.operators.influxdb3.InfluxDB3Hook",
autospec=True)
def test_execute(self, mock_hook_class):
"""Test operator execution."""
- pd = pytest.importorskip("pandas")
-
mock_hook = mock.Mock()
mock_df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
mock_hook.query.return_value = mock_df
@@ -57,3 +60,73 @@ class TestInfluxDB3Operator:
assert isinstance(result[0], dict)
assert "col1" in result[0]
assert "col2" in result[0]
+
+
@mock.patch("airflow.providers.influxdb.operators.influxdb3.InfluxDB3Hook",
autospec=True)
+ def test_execute_deferrable_defers(self, mock_hook_class):
+ """In deferrable mode the operator defers instead of running the query
on the worker."""
+ operator = InfluxDB3Operator(
+ task_id="test_task_deferrable",
+ sql='SELECT "duration" FROM "pyexample"',
+ influxdb3_conn_id="influxdb3_default",
+ deferrable=True,
+ execution_timeout=timedelta(minutes=7),
+ )
+
+ with pytest.raises(TaskDeferred) as exc:
+ operator.execute(context={})
+
+ assert isinstance(exc.value.trigger, InfluxDB3QueryTrigger)
+ assert exc.value.trigger.sql == 'SELECT "duration" FROM "pyexample"'
+ assert exc.value.trigger.influxdb3_conn_id == "influxdb3_default"
+ assert exc.value.timeout == timedelta(minutes=7)
+ assert exc.value.method_name == "execute_complete"
+ mock_hook_class.assert_not_called()
+
+ def test_execute_complete_success(self):
+ """execute_complete returns the records carried by the trigger
event."""
+ operator = InfluxDB3Operator(
+ task_id="test_task_complete",
+ sql='SELECT "duration" FROM "pyexample"',
+ deferrable=True,
+ )
+ records = [{"col1": 1, "col2": 3}]
+
+ result = operator.execute_complete(context={}, event={"status":
"success", "records": records})
+
+ assert result == records
+
+ @pytest.mark.parametrize(
+ ("event", "match"),
+ [
+ pytest.param({"status": "error", "message": "boom"}, "boom",
id="error-with-message"),
+ pytest.param({"status": "error"}, "InfluxDB 3 query failed",
id="error-without-message"),
+ ],
+ )
+ def test_execute_complete_error(self, event, match):
+ """execute_complete surfaces trigger-reported failures as runtime
errors."""
+ operator = InfluxDB3Operator(
+ task_id="test_task_complete_error",
+ sql='SELECT "duration" FROM "pyexample"',
+ deferrable=True,
+ )
+
+ with pytest.raises(RuntimeError, match=match):
+ operator.execute_complete(context={}, event=event)
+
+ @pytest.mark.parametrize(
+ ("event", "match"),
+ [
+ pytest.param(None, "did not return an event", id="missing-event"),
+ pytest.param({"status": "cancelled"}, "unexpected status",
id="unexpected-status"),
+ ],
+ )
+ def test_execute_complete_invalid_event(self, event, match):
+ """execute_complete rejects missing or unexpected trigger events."""
+ operator = InfluxDB3Operator(
+ task_id="test_task_complete_invalid_event",
+ sql='SELECT "duration" FROM "pyexample"',
+ deferrable=True,
+ )
+
+ with pytest.raises(RuntimeError, match=match):
+ operator.execute_complete(context={}, event=event)
diff --git a/providers/influxdb/tests/unit/influxdb/test_utils.py
b/providers/influxdb/tests/unit/influxdb/test_utils.py
new file mode 100644
index 00000000000..270474453b1
--- /dev/null
+++ b/providers/influxdb/tests/unit/influxdb/test_utils.py
@@ -0,0 +1,35 @@
+# 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 pandas as pd
+
+from airflow.providers.influxdb.utils import _convert_dataframe_to_records
+
+
+def test_convert_dataframe_to_records_serializes_rows_and_timestamps():
+ dataframe = pd.DataFrame(
+ {
+ "col1": [1, 2],
+ "timestamp": pd.to_datetime(["2024-01-01T00:00:00Z",
"2024-01-02T03:04:05Z"], utc=True),
+ }
+ )
+
+ assert _convert_dataframe_to_records(dataframe) == [
+ {"col1": 1, "timestamp": "2024-01-01T00:00:00.000Z"},
+ {"col1": 2, "timestamp": "2024-01-02T03:04:05.000Z"},
+ ]
diff --git a/providers/influxdb/tests/unit/influxdb/triggers/__init__.py
b/providers/influxdb/tests/unit/influxdb/triggers/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ b/providers/influxdb/tests/unit/influxdb/triggers/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git a/providers/influxdb/tests/unit/influxdb/triggers/test_influxdb3.py
b/providers/influxdb/tests/unit/influxdb/triggers/test_influxdb3.py
new file mode 100644
index 00000000000..18669c504cf
--- /dev/null
+++ b/providers/influxdb/tests/unit/influxdb/triggers/test_influxdb3.py
@@ -0,0 +1,81 @@
+# 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 asyncio
+from unittest import mock
+
+import pandas as pd
+import pytest
+
+from airflow.providers.influxdb.triggers.influxdb3 import InfluxDB3QueryTrigger
+from airflow.triggers.base import TriggerEvent
+
+SQL = 'SELECT "duration" FROM "pyexample"'
+CONN_ID = "test_influxdb3_conn"
+
+
+class TestInfluxDB3QueryTrigger:
+ def test_serialization(self):
+ """Trigger serializes its constructor arguments."""
+ trigger = InfluxDB3QueryTrigger(sql=SQL, influxdb3_conn_id=CONN_ID)
+ classpath, kwargs = trigger.serialize()
+
+ assert classpath ==
"airflow.providers.influxdb.triggers.influxdb3.InfluxDB3QueryTrigger"
+ assert kwargs == {"sql": SQL, "influxdb3_conn_id": CONN_ID}
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.influxdb.triggers.influxdb3.InfluxDB3Hook",
autospec=True)
+ async def test_run_success(self, mock_hook_class):
+ """A completed query emits a single success event carrying
JSON-serializable records."""
+ dataframe = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
+ records = [{"col1": 1, "col2": 3}, {"col1": 2, "col2": 4}]
+ mock_hook = mock_hook_class.return_value
+ mock_hook.query_async = mock.AsyncMock(return_value=dataframe)
+
+ trigger = InfluxDB3QueryTrigger(sql=SQL)
+ events = [event async for event in trigger.run()]
+
+ mock_hook_class.assert_called_once_with(conn_id="influxdb3_default")
+ mock_hook.query_async.assert_awaited_once_with(SQL)
+ assert events == [TriggerEvent({"status": "success", "records":
records})]
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.influxdb.triggers.influxdb3.InfluxDB3Hook",
autospec=True)
+ async def test_run_failure(self, mock_hook_class):
+ """A failing query is reported as an event, not raised out of the
triggerer."""
+ mock_hook = mock_hook_class.return_value
+ mock_hook.query_async = mock.AsyncMock(side_effect=ValueError("boom"))
+
+ trigger = InfluxDB3QueryTrigger(sql=SQL)
+ events = [event async for event in trigger.run()]
+
+ mock_hook_class.assert_called_once_with(conn_id="influxdb3_default")
+ mock_hook.query_async.assert_awaited_once_with(SQL)
+ assert events == [TriggerEvent({"status": "error", "message": "boom"})]
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.influxdb.triggers.influxdb3.InfluxDB3Hook",
autospec=True)
+ async def test_run_propagates_cancellation(self, mock_hook_class):
+ """Trigger cancellation propagates instead of being converted into an
error event."""
+ mock_hook = mock_hook_class.return_value
+ mock_hook.query_async =
mock.AsyncMock(side_effect=asyncio.CancelledError())
+
+ trigger = InfluxDB3QueryTrigger(sql=SQL)
+
+ with pytest.raises(asyncio.CancelledError):
+ await anext(trigger.run())
diff --git a/uv.lock b/uv.lock
index 844b80ccbc8..a47f2392617 100644
--- a/uv.lock
+++ b/uv.lock
@@ -6369,6 +6369,8 @@ dependencies = [
{ name = "apache-airflow-providers-common-compat" },
{ name = "influxdb-client" },
{ name = "influxdb3-python" },
+ { name = "pandas", version = "2.3.3", source = { registry =
"https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
+ { name = "pandas", version = "3.0.5", source = { registry =
"https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
{ name = "requests" },
]
@@ -6388,7 +6390,10 @@ requires-dist = [
{ name = "apache-airflow", editable = "." },
{ name = "apache-airflow-providers-common-compat", editable =
"providers/common/compat" },
{ name = "influxdb-client", specifier = ">=1.19.0" },
- { name = "influxdb3-python", specifier = ">=0.7.0" },
+ { name = "influxdb3-python", specifier = ">=0.12.0" },
+ { name = "pandas", marker = "python_full_version == '3.13.*'", specifier =
">=2.2.3" },
+ { name = "pandas", marker = "python_full_version < '3.13'", specifier =
">=2.1.2" },
+ { name = "pandas", marker = "python_full_version >= '3.14'", specifier =
">=2.3.3" },
{ name = "requests", specifier = ">=2.32.0,<3" },
]