This is an automated email from the ASF dual-hosted git repository.
dabla 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 65b2e6002d9 Add DuckDB support to the Microsoft Azure provider (#75819)
65b2e6002d9 is described below
commit 65b2e6002d92551cb3bf751428d3c627a7237259
Author: David Blain <[email protected]>
AuthorDate: Wed Nov 25 14:54:21 2026 +0100
Add DuckDB support to the Microsoft Azure provider (#75819)
* Add DuckDB support to the Microsoft Azure provider
The Amazon provider brokers an AWS connection into a DuckDB S3 secret, so a
DuckDB query reaches S3 with no credentials in the Dag. Azure storage had no
such path: reading abfss:// paths, OneLake included, meant creating the
DuckDB Azure secret by hand in every task. The new duckdb_azure connection
type does it from an ADLS connection, as an opt-in extra like on the Amazon
side.
* Read account keys and scheme-less account URLs in AzureDuckDBHook
The config strategy only read a connection string or a service principal
from the ADLS connection, so a connection holding an account key, which
AzureDataLakeStorageV2Hook accepts, was rejected. It now reads the
credentials in the order that hook does: connection_string, else a
service principal when there is a tenant_id, else the password as the
account key, turned into a connection string with the storage account.
An account_url without a scheme, which the Azure SDK accepts, gave no
storage account and also kept the host of the connection from being
used. It is parsed like a URL with a scheme now, and a URL without a
usable host falls back to the host.
With credential_chain a missing ADLS connection was ignored whatever its
id, so a mistyped azure_conn_id gave a secret without account and proxy.
Only the default adls_default may be missing now, as DuckDBHook does for
its own connection.
The duckdb_azure connection gets its own page under docs/connections,
like every other connection type of the provider, and the docs say which
ADLS auth modes each strategy reads.
---
docs/spelling_wordlist.txt | 1 +
.../azure/docs/connections/duckdb_azure.rst | 99 ++++++
providers/microsoft/azure/docs/index.rst | 2 +
.../microsoft/azure/docs/operators/duckdb.rst | 178 ++++++++++
providers/microsoft/azure/provider.yaml | 31 ++
providers/microsoft/azure/pyproject.toml | 6 +
.../providers/microsoft/azure/get_provider_info.py | 23 ++
.../providers/microsoft/azure/hooks/duckdb.py | 319 ++++++++++++++++++
.../unit/microsoft/azure/hooks/test_duckdb.py | 364 +++++++++++++++++++++
uv.lock | 8 +-
10 files changed, 1030 insertions(+), 1 deletion(-)
diff --git a/docs/spelling_wordlist.txt b/docs/spelling_wordlist.txt
index e472ea11c46..66f7aa04665 100644
--- a/docs/spelling_wordlist.txt
+++ b/docs/spelling_wordlist.txt
@@ -1252,6 +1252,7 @@ ol
Ollama
onboarded
onboarding
+OneLake
OnFailure
Oozie
OPA
diff --git a/providers/microsoft/azure/docs/connections/duckdb_azure.rst
b/providers/microsoft/azure/docs/connections/duckdb_azure.rst
new file mode 100644
index 00000000000..d4337599367
--- /dev/null
+++ b/providers/microsoft/azure/docs/connections/duckdb_azure.rst
@@ -0,0 +1,99 @@
+ .. 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.
+
+.. _howto/connection:duckdb_azure:
+
+DuckDB on Azure Connection
+==========================
+
+The DuckDB on Azure connection type is used by
+:class:`~airflow.providers.microsoft.azure.hooks.duckdb.AzureDuckDBHook` to
query data in Azure Blob
+Storage, Azure Data Lake Storage Gen2 and Microsoft Fabric OneLake with
DuckDB. See
+:doc:`../operators/duckdb` for usage.
+
+Two connections are involved:
+
+* A **DuckDB on Azure** (``duckdb_azure``) connection which configures DuckDB
itself, i.e.: *which
+ DuckDB database and with what settings*. Its id is what you pass to
+
:class:`~airflow.providers.duckdb.operators.duckdb.DuckDBExecuteQueryOperator`
as ``conn_id``, and its
+ type is also what selects
:class:`~airflow.providers.microsoft.azure.hooks.duckdb.AzureDuckDBHook`.
+* An :ref:`ADLS connection <howto/connection:adls>` says *which Azure identity
and storage account*. The
+ DuckDB connection points at it through ``azure_conn_id``, which defaults to
``adls_default``.
+
+Credentials stay in the ADLS connection. With the default
``credential_strategy`` of ``config`` the
+hook builds the DuckDB secret from them; see
:ref:`howto/operator:duckdb_azure:credentials` for the
+credentials it reads and for the other strategies.
+
+The ``duckdb_azure`` connection can be empty. Create it, name it whatever you
like, and leave every
+field blank to get an in-memory database. Pass its id to
``DuckDBExecuteQueryOperator`` as ``conn_id``;
+the operator needs the connection to exist, and with no ``conn_id`` it uses
``duckdb_default`` and the
+plain DuckDB hook, which has no Azure access. ``AzureDuckDBHook`` used on its
own defaults to
+``duckdb_azure_default``, and opens an in-memory database if that connection
does not exist.
+
+Configuring the Connection
+--------------------------
+
+Database path (optional)
+ Path to a DuckDB database file, for example ``/tmp/analytics.duckdb``.
Leave empty for an
+ in-memory database.
+
+Extra (optional)
+ A JSON object. Every parameter of ``AzureDuckDBHook`` can be set here, and
``hook_params`` on the
+ operator overrides it per task. The Azure keys are:
+
+ * ``azure_conn_id``: the ADLS connection the secret is built from.
Defaults to ``adls_default``.
+ With the ``credential_chain`` strategy the default connection may be
missing; any other id has
+ to exist.
+ * ``account_name``: the storage account of the secret. Defaults to the
account of the ADLS
+ connection: the first label of its ``account_url``, or its host.
+ * ``credential_strategy``: ``config`` (default), ``credential_chain`` or
``none``. See
+ :ref:`howto/operator:duckdb_azure:credentials`.
+ * ``credential_chain``: the providers DuckDB's credential chain consults,
for example
+ ``"managed_identity;env"``.
+ * ``transport_option_type``: the HTTP transport of the Azure SDK in
DuckDB, ``default`` or
+ ``curl``. ``curl`` resolves TLS certificate errors on Linux images whose
CA bundle is not where
+ the default transport looks.
+ * ``secret_name``: name of the DuckDB secret to create. Defaults to
``airflow_azure``.
+
+ The DuckDB engine keys, such as ``memory_limit``, ``threads`` and
``extensions``, are the same as
+ in the :doc:`DuckDB connection
<apache-airflow-providers-duckdb:connections/duckdb>`. One default
+ differs: ``autoinstall_extensions`` is ``true`` here, so missing
extensions, including ``azure``,
+ are downloaded from DuckDB's extension repository.
+
+Examples
+--------
+
+An in-memory database with explicit resource limits. The credentials, storage
account and proxy come
+from ``adls_default``:
+
+.. code-block:: json
+
+ {
+ "azure_conn_id": "adls_default",
+ "memory_limit": "2GB",
+ "threads": 4
+ }
+
+A database file, with credentials the Azure SDK inside DuckDB resolves from
the worker's environment:
+
+.. code-block:: bash
+
+ export AIRFLOW_CONN_DUCKDB_AZURE_DEFAULT='{
+ "conn_type": "duckdb_azure",
+ "host": "/tmp/analytics.duckdb",
+ "extra": {"credential_strategy": "credential_chain", "account_name":
"myaccount"}
+ }'
diff --git a/providers/microsoft/azure/docs/index.rst
b/providers/microsoft/azure/docs/index.rst
index 3d83053900b..09b8e2ca698 100644
--- a/providers/microsoft/azure/docs/index.rst
+++ b/providers/microsoft/azure/docs/index.rst
@@ -163,6 +163,7 @@ Dependent package
========================================================================================================================
====================
`apache-airflow-providers-amazon
<https://airflow.apache.org/docs/apache-airflow-providers-amazon>`_
``amazon``
`apache-airflow-providers-common-messaging
<https://airflow.apache.org/docs/apache-airflow-providers-common-messaging>`_
``common.messaging``
+`apache-airflow-providers-duckdb
<https://airflow.apache.org/docs/apache-airflow-providers-duckdb>`_
``duckdb``
`apache-airflow-providers-google
<https://airflow.apache.org/docs/apache-airflow-providers-google>`_
``google``
`apache-airflow-providers-openlineage
<https://airflow.apache.org/docs/apache-airflow-providers-openlineage>`_
``openlineage``
`apache-airflow-providers-oracle
<https://airflow.apache.org/docs/apache-airflow-providers-oracle>`_
``oracle``
@@ -189,6 +190,7 @@ Extra Dependencies
``common.messaging`` ``apache-airflow-providers-common-messaging>=2.0.0``
``google`` ``apache-airflow-providers-google``
``openlineage`` ``apache-airflow-providers-openlineage>=2.3.0``
+``duckdb`` ``apache-airflow-providers-duckdb>=0.1.0``
==================== ====================================================
Downloading official packages
diff --git a/providers/microsoft/azure/docs/operators/duckdb.rst
b/providers/microsoft/azure/docs/operators/duckdb.rst
new file mode 100644
index 00000000000..18cefa526cb
--- /dev/null
+++ b/providers/microsoft/azure/docs/operators/duckdb.rst
@@ -0,0 +1,178 @@
+ .. 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.
+
+===============
+DuckDB on Azure
+===============
+
+`DuckDB <https://duckdb.org/>`__ is an in-process analytical database. With
its ``azure`` extension it
+reads and writes Azure Blob Storage and Azure Data Lake Storage Gen2
(``az://`` and ``abfss://`` paths)
+directly, Parquet, JSON, CSV and Delta tables alike.
+
+DuckDB is not an Azure service, so the generic hook, operator and ``duckdb``
connection type live in the
+:doc:`DuckDB provider <apache-airflow-providers-duckdb:index>`. What this
provider adds is the Azure
+auth: it uses an Airflow ADLS connection to create the DuckDB secret that
grants access to the storage,
+so there is no credential wiring in the Dag. It is the Azure counterpart of
+:doc:`DuckDB on AWS <apache-airflow-providers-amazon:operators/duckdb>`.
+
+You run
:class:`~airflow.providers.duckdb.operators.duckdb.DuckDBExecuteQueryOperator`
and point it at a
+``duckdb_azure`` connection when the SQL should reach Azure storage.
+
+Prerequisite Tasks
+------------------
+
+.. include:: /operators/_partials/prerequisite_tasks.rst
+
+DuckDB support is an optional extra:
+
+.. code-block:: bash
+
+ pip install 'apache-airflow-providers-microsoft-azure[duckdb]'
+
+.. note::
+
+ Azure access needs DuckDB's ``azure`` extension. This provider installs it
if it is missing by
+ default. If your workers should not download anything at runtime, set
+ ``autoinstall_extensions=False`` and make the extension available
yourself, either in an
+ ``extension_directory`` or baked into your image.
+
+Run a DuckDB query against Azure storage
+========================================
+
+Two connections are involved: a :ref:`DuckDB on Azure connection
<howto/connection:duckdb_azure>` that
+says which DuckDB database to open and with what settings, and an
+:ref:`ADLS connection <howto/connection:adls>` that gives the Azure identity
and the storage account.
+Credentials stay in the ADLS connection. The DuckDB on Azure connection can be
empty, but the operator
+needs it to exist.
+
+Given those connections, the hook loads the ``azure`` extension and creates
the Azure secret, so the task
+supplies only SQL:
+
+.. code-block:: python
+
+ from airflow.providers.duckdb.operators.duckdb import
DuckDBExecuteQueryOperator
+
+ count_rows = DuckDBExecuteQueryOperator(
+ task_id="count_rows",
+ conn_id="duckdb_azure_default",
+ sql="SELECT COUNT(*) FROM
read_parquet('abfss://[email protected]/sales/*.parquet')",
+ )
+
+Pass the id explicitly. With no ``conn_id`` the operator uses
``duckdb_default`` and the vendor-neutral
+hook, which has no Azure access.
+
+Everything
:class:`~airflow.providers.microsoft.azure.hooks.duckdb.AzureDuckDBHook`
accepts can be set in
+the DuckDB connection ``extra``, and ``hook_params`` on the operator overrides
it per task. Set
+``memory_limit`` and ``threads`` explicitly: DuckDB otherwise sizes itself
from the resources it detects on
+the host.
+
+.. code-block:: json
+
+ {
+ "azure_conn_id": "adls_default",
+ "memory_limit": "2GB",
+ "threads": 4
+ }
+
+Microsoft Fabric OneLake works the same way: an ADLS connection whose
``account_url`` is
+``https://onelake.dfs.fabric.microsoft.com`` yields the account ``onelake``,
and DuckDB then reads paths such
+as
``abfss://<workspace>@onelake.dfs.fabric.microsoft.com/<lakehouse>/Tables/<schema>/<table>``.
+
+Using the hook directly
+=======================
+
+For work that is not a single statement (e.g. chaining several queries against
one database, or returning
+results to Python) use the hook directly. Opening one connection for several
statements also avoids paying
+connection setup and extension loading more than once per task:
+
+.. code-block:: python
+
+ from airflow.providers.microsoft.azure.hooks.duckdb import AzureDuckDBHook
+ from airflow.sdk import task
+
+
+ @task
+ def compare_regions():
+ hook = AzureDuckDBHook(azure_conn_id="adls_default")
+ with hook.get_conn() as conn:
+ conn.execute(
+ "CREATE TABLE sales AS "
+ "SELECT * FROM
read_parquet('abfss://[email protected]/sales.parquet')"
+ )
+ return conn.execute("SELECT region, SUM(revenue) FROM sales GROUP
BY region").fetchall()
+
+.. _howto/operator:duckdb_azure:credentials:
+
+How credentials reach DuckDB
+============================
+
+DuckDB does not use the Azure SDK for Python. The hook therefore issues a
``CREATE SECRET`` statement that
+tells DuckDB how to authenticate, and the ``credential_strategy`` parameter
selects how:
+
+``config`` (default)
+ Builds the secret from the credentials of the ADLS connection, read in the
order
+
:class:`~airflow.providers.microsoft.azure.hooks.data_lake.AzureDataLakeStorageV2Hook`
reads them:
+
+ * its ``connection_string`` when the extra has one (``PROVIDER config``);
+ * else an Active Directory service principal when the extra has a
``tenant_id`` (``PROVIDER
+ service_principal``), with the connection's login as client id and its
password as client secret;
+ * else the connection's password as the key of the storage account
(``PROVIDER config``, with a
+ connection string built from the storage account and the key).
+
+ An ADLS connection without credentials, which the ADLS hook resolves
through
+ ``DefaultAzureCredential``, is rejected: use ``credential_chain`` for it.
The extra's
+ ``proxies["https"]``, as the ADLS hook uses it, becomes the secret's
``HTTP_PROXY``. The credentials
+ become part of the SQL statement.
+
+``credential_chain``
+ Issues ``CREATE SECRET (TYPE azure, PROVIDER credential_chain)``, which
resolves credentials through the
+ Azure SDK inside DuckDB's ``azure`` extension: Azure CLI, managed
identity, workload identity or
+ environment variables, optionally narrowed with ``credential_chain`` (for
example
+ ``"managed_identity;env"``). Nothing secret is written into SQL text. The
default ADLS connection is
+ optional with this strategy: when it exists, it supplies the storage
account and proxy; otherwise set
+ ``account_name``. An ``azure_conn_id`` other than ``adls_default`` has to
exist. The chain does not read
+ the ``managed_identity_client_id`` or ``workload_identity_tenant_id`` of
the ADLS connection; DuckDB
+ picks the identity from the environment.
+
+``none``
+ Creates no secret. Use for a DuckDB database that never touches Azure.
+
+The storage account of the secret is ``account_name`` when it is set,
otherwise it is derived from the
+ADLS connection: the first label of its ``account_url`` (with or without a
scheme), or its host.
+
+.. code-block:: python
+
+ DuckDBExecuteQueryOperator(
+ task_id="query",
+ conn_id="duckdb_azure_default",
+ sql="SELECT COUNT(*) FROM
read_parquet('az://my-container/data.parquet')",
+ hook_params={"credential_strategy": "credential_chain",
"account_name": "myaccount"},
+ )
+
+TLS certificate errors
+======================
+
+The Azure SDK inside DuckDB looks for the CA bundle in one fixed location with
its default HTTP transport.
+On a Linux image whose bundle lives elsewhere, token requests fail with an SSL
CA certificate error. Set
+``transport_option_type`` to ``curl`` to switch to the curl transport, which
searches the usual locations.
+The hook sets it as the global ``azure_transport_option_type`` setting before
it creates the secret.
+
+Reference
+=========
+
+* `DuckDB Azure extension
<https://duckdb.org/docs/stable/core_extensions/azure>`__
+* `DuckDB secrets manager
<https://duckdb.org/docs/stable/configuration/secrets_manager>`__
diff --git a/providers/microsoft/azure/provider.yaml
b/providers/microsoft/azure/provider.yaml
index 2ed16ebf60f..654e14bbcea 100644
--- a/providers/microsoft/azure/provider.yaml
+++ b/providers/microsoft/azure/provider.yaml
@@ -231,6 +231,14 @@ integrations:
how-to-guide:
- /docs/apache-airflow-providers-microsoft-azure/operators/powerbi.rst
tags: [azure]
+ # DuckDB itself is not an Azure service: the generic hook, operator and
``duckdb`` connection type
+ # live in the ``duckdb`` provider. What lives here is only the
Azure-specific part, brokering Azure
+ # credentials into a DuckDB session configured by its own connection type
+ - integration-name: DuckDB on Azure
+ external-doc-url: https://duckdb.org/docs/stable/core_extensions/azure
+ how-to-guide:
+ - /docs/apache-airflow-providers-microsoft-azure/operators/duckdb.rst
+ tags: [azure]
operators:
- integration-name: Microsoft Azure Analysis Services
@@ -357,6 +365,9 @@ hooks:
- integration-name: Microsoft Power BI
python-modules:
- airflow.providers.microsoft.azure.hooks.powerbi
+ - integration-name: DuckDB on Azure
+ python-modules:
+ - airflow.providers.microsoft.azure.hooks.duckdb
bundles:
- integration-name: Microsoft Azure Blob Storage
@@ -1080,6 +1091,26 @@ connection-types:
label: Tenant ID
schema:
type: ["string", "null"]
+ - hook-class-name:
airflow.providers.microsoft.azure.hooks.duckdb.AzureDuckDBHook
+ hook-name: "DuckDB on Azure"
+ connection-type: duckdb_azure
+ ui-field-behaviour:
+ hidden-fields:
+ - login
+ - password
+ - port
+ - schema
+ relabeling:
+ host: Database path
+ placeholders:
+ host: /tmp/analytics.duckdb (leave empty for an in-memory database)
+ extra: |
+ {
+ "azure_conn_id": "adls_default",
+ "credential_strategy": "config",
+ "memory_limit": "2GB",
+ "threads": 4
+ }
secrets-backends:
- airflow.providers.microsoft.azure.secrets.key_vault.AzureKeyVaultBackend
diff --git a/providers/microsoft/azure/pyproject.toml
b/providers/microsoft/azure/pyproject.toml
index bac2e619928..f010d00c012 100644
--- a/providers/microsoft/azure/pyproject.toml
+++ b/providers/microsoft/azure/pyproject.toml
@@ -127,6 +127,11 @@ dependencies = [
"openlineage" = [
"apache-airflow-providers-openlineage>=2.3.0"
]
+# DuckDB support is opt-in: the duckdb wheel is around 20MB and irrelevant to
most users of this
+# provider, so it must never become a hard dependency here.
+"duckdb" = [
+ "apache-airflow-providers-duckdb>=0.1.0"
+]
[dependency-groups]
dev = [
@@ -136,6 +141,7 @@ dev = [
"apache-airflow-providers-amazon",
"apache-airflow-providers-common-compat",
"apache-airflow-providers-common-messaging",
+ "apache-airflow-providers-duckdb",
"apache-airflow-providers-google",
"apache-airflow-providers-openlineage",
"apache-airflow-providers-oracle",
diff --git
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/get_provider_info.py
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/get_provider_info.py
index dd4a470f34a..6fa5b90a18c 100644
---
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/get_provider_info.py
+++
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/get_provider_info.py
@@ -163,6 +163,12 @@ def get_provider_info():
"how-to-guide":
["/docs/apache-airflow-providers-microsoft-azure/operators/powerbi.rst"],
"tags": ["azure"],
},
+ {
+ "integration-name": "DuckDB on Azure",
+ "external-doc-url":
"https://duckdb.org/docs/stable/core_extensions/azure",
+ "how-to-guide":
["/docs/apache-airflow-providers-microsoft-azure/operators/duckdb.rst"],
+ "tags": ["azure"],
+ },
],
"operators": [
{
@@ -329,6 +335,10 @@ def get_provider_info():
"integration-name": "Microsoft Power BI",
"python-modules":
["airflow.providers.microsoft.azure.hooks.powerbi"],
},
+ {
+ "integration-name": "DuckDB on Azure",
+ "python-modules":
["airflow.providers.microsoft.azure.hooks.duckdb"],
+ },
],
"bundles": [
{
@@ -1050,6 +1060,19 @@ def get_provider_info():
},
"conn-fields": {"tenant_id": {"label": "Tenant ID", "schema":
{"type": ["string", "null"]}}},
},
+ {
+ "hook-class-name":
"airflow.providers.microsoft.azure.hooks.duckdb.AzureDuckDBHook",
+ "hook-name": "DuckDB on Azure",
+ "connection-type": "duckdb_azure",
+ "ui-field-behaviour": {
+ "hidden-fields": ["login", "password", "port", "schema"],
+ "relabeling": {"host": "Database path"},
+ "placeholders": {
+ "host": "/tmp/analytics.duckdb (leave empty for an
in-memory database)",
+ "extra": '{\n "azure_conn_id": "adls_default",\n
"credential_strategy": "config",\n "memory_limit": "2GB",\n "threads":
4\n}\n',
+ },
+ },
+ },
],
"secrets-backends":
["airflow.providers.microsoft.azure.secrets.key_vault.AzureKeyVaultBackend"],
"email-backends":
["airflow.providers.microsoft.azure.hooks.msgraph.send_email"],
diff --git
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/duckdb.py
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/duckdb.py
new file mode 100644
index 00000000000..88bf924fc78
--- /dev/null
+++
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/duckdb.py
@@ -0,0 +1,319 @@
+# 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 functools import cached_property
+from typing import TYPE_CHECKING, Any, Literal
+from urllib.parse import urlsplit
+
+from airflow.providers.common.compat.sdk import (
+ AirflowNotFoundException,
+ AirflowOptionalProviderFeatureException,
+)
+from airflow.providers.microsoft.azure.utils import get_field
+
+try:
+ from airflow.providers.duckdb.hooks.duckdb import DuckDBHook
+except ImportError:
+ raise AirflowOptionalProviderFeatureException(
+ "This feature requires the 'duckdb' provider to be installed. Install
it with: "
+ "pip install 'apache-airflow-providers-microsoft-azure[duckdb]'"
+ )
+
+if TYPE_CHECKING:
+ from duckdb import DuckDBPyConnection
+
+ from airflow.providers.common.compat.sdk import Connection
+
+CredentialStrategy = Literal["config", "credential_chain", "none"]
+
+#: Used when neither an argument nor the connection extra names an ADLS
connection.
+DEFAULT_AZURE_CONN_ID = "adls_default"
+
+
+class AzureDuckDBHook(DuckDBHook):
+ """
+ Interact with DuckDB using Azure credentials brokered by Airflow.
+
+ Extends :class:`~airflow.providers.duckdb.hooks.duckdb.DuckDBHook` with an
Azure secret built
+ from an Airflow :ref:`ADLS connection <howto/connection:adls>`, so
``read_parquet('abfss://...')``,
+ ``delta_scan('abfss://...')`` and ``COPY ... TO 'abfss://...'`` work with
no credential wiring in
+ the Dag. It is the Azure counterpart of
+ :class:`~airflow.providers.amazon.aws.hooks.duckdb.AwsDuckDBHook`.
+
+ Two credential strategies are supported:
+
+ ``config`` (the default)
+ Builds the secret from the credentials of the ADLS connection, read in
the order
+
:class:`~airflow.providers.microsoft.azure.hooks.data_lake.AzureDataLakeStorageV2Hook`
reads
+ them: its ``connection_string`` when the extra has one (``PROVIDER
config``), else an Active
+ Directory service principal when the extra has a ``tenant_id``
(``PROVIDER
+ service_principal``, with the connection's login as client id and its
password as client
+ secret), else the password as the key of the storage account
(``PROVIDER config``, with a
+ connection string built from the account and the key). A connection
without credentials is
+ rejected: use ``credential_chain`` for it. The extra's
``proxies["https"]`` becomes the
+ secret's proxy. The credentials become part of the SQL statement.
+
+ ``credential_chain``
+ Issues ``CREATE SECRET (TYPE azure, PROVIDER credential_chain)``,
which resolves credentials
+ through the Azure SDK inside DuckDB's ``azure`` extension (Azure CLI,
managed identity,
+ workload identity, environment). Nothing secret is written into SQL
text. The default ADLS
+ connection is optional then: when it exists, it supplies the storage
account and proxy. An
+ ``azure_conn_id`` other than the default has to exist. The chain does
not read the
+ connection's ``managed_identity_client_id`` or
``workload_identity_tenant_id``.
+
+ The storage account comes from ``account_name``, else from the
``account_url`` of the ADLS
+ connection's extra (``onelake`` for
``https://onelake.dfs.fabric.microsoft.com``), else from its
+ host.
+
+ This hook needs the ``azure`` extension and installs it if it is missing,
as ``AwsDuckDBHook``
+ does with ``httpfs`` and ``aws``. Set ``autoinstall_extensions=False`` to
forbid the download.
+
+ :param azure_conn_id: the ADLS connection used to reach the storage.
Defaults to ``adls_default``.
+ :param account_name: the storage account of the secret. Defaults to the
ADLS connection's.
+ :param credential_strategy: ``config``, ``credential_chain``, or ``none``
to create no secret at
+ all (for a DuckDB database that never touches Azure).
+ :param credential_chain: providers DuckDB's credential chain consults, for
example
+ ``"managed_identity;env"``. Only used with the ``credential_chain``
strategy; DuckDB's own
+ default applies when it is not set.
+ :param transport_option_type: the HTTP transport of the Azure SDK in
DuckDB (the
+ ``azure_transport_option_type`` setting): ``default`` or ``curl``.
``curl`` searches the
+ usual locations for the CA bundle, which resolves TLS certificate
errors on Linux systems
+ whose bundle is not where the default transport looks. Left unset,
DuckDB's default applies.
+ :param secret_name: name of the DuckDB secret to create.
+
+ As with :class:`~airflow.providers.duckdb.hooks.duckdb.DuckDBHook`, every
parameter may also be set
+ in the DuckDB connection ``extra``, and an explicit argument wins.
+ """
+
+ #: ``azure`` provides the ``az://``/``abfss://`` filesystems and the Azure
secret type.
+ required_extensions = ("azure",)
+
+ # A connection type is what lets DuckDBExecuteQueryOperator reach this
hook: the operator
+ # resolves the hook from the connection a Dag names.
+ conn_type = "duckdb_azure"
+ hook_name = "DuckDB on Azure"
+ default_conn_name = "duckdb_azure_default"
+
+ @classmethod
+ def get_ui_field_behaviour(cls) -> dict[str, Any]:
+ """Return custom UI field behaviour for the DuckDB on Azure
connection."""
+ return {
+ "hidden_fields": ["login", "password", "port", "schema"],
+ "relabeling": {"host": "Database path"},
+ "placeholders": {
+ "host": "/tmp/analytics.duckdb (leave empty for an in-memory
database)",
+ "extra": '{"azure_conn_id": "adls_default",
"credential_strategy": "config", '
+ '"memory_limit": "2GB", "threads": 4}',
+ },
+ }
+
+ def __init__(
+ self,
+ *args,
+ azure_conn_id: str | None = None,
+ account_name: str | None = None,
+ credential_strategy: CredentialStrategy | None = None,
+ credential_chain: str | None = None,
+ transport_option_type: Literal["default", "curl"] | None = None,
+ secret_name: str | None = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self._azure_conn_id = azure_conn_id
+ self._account_name = account_name
+ self._credential_strategy = credential_strategy
+ self._credential_chain = credential_chain
+ self._transport_option_type = transport_option_type
+ self._secret_name = secret_name
+
+ @property
+ def azure_conn_id(self) -> str:
+ return self.resolve_parameter("azure_conn_id", self._azure_conn_id,
DEFAULT_AZURE_CONN_ID)
+
+ @cached_property
+ def azure_connection(self) -> Connection:
+ """Return the ADLS connection the secret is built from."""
+ return self.get_connection(self.azure_conn_id)
+
+ @cached_property
+ def optional_azure_connection(self) -> Connection | None:
+ """
+ Return the ADLS connection, or ``None`` when the default one does not
exist.
+
+ With the ``credential_chain`` strategy the ADLS connection only
supplies the storage account
+ and proxy, so the default one may be missing. A connection named
explicitly has to exist, as
+ for the DuckDB connection itself: leaving it out would create a secret
without the account
+ and proxy the Dag author asked for.
+ """
+ try:
+ return self.azure_connection
+ except AirflowNotFoundException:
+ if self.azure_conn_id != DEFAULT_AZURE_CONN_ID:
+ raise
+ return None
+
+ @property
+ def credential_strategy(self) -> CredentialStrategy:
+ return self.resolve_parameter("credential_strategy",
self._credential_strategy, "config")
+
+ @property
+ def credential_chain(self) -> str | None:
+ return self.resolve_parameter("credential_chain",
self._credential_chain)
+
+ @property
+ def transport_option_type(self) -> str | None:
+ return self.resolve_parameter("transport_option_type",
self._transport_option_type)
+
+ @property
+ def secret_name(self) -> str:
+ return self.resolve_parameter("secret_name", self._secret_name,
"airflow_azure")
+
+ @property
+ def autoinstall_extensions(self) -> bool:
+ """
+ Default to installing missing extensions, unlike the generic hook.
+
+ Reaching for the Azure hook is a statement that the task runs against
Azure, so ``azure``
+ should just work. The generic hook cannot assume that and leaves
downloads off.
+ """
+ return bool(self.resolve_parameter("autoinstall_extensions",
self._autoinstall_extensions, True))
+
+ def get_account_name(self) -> str | None:
+ """Return the storage account of the secret."""
+ explicit = self.resolve_parameter("account_name", self._account_name)
+ if explicit:
+ return explicit
+ connection = self.optional_azure_connection
+ if connection is None:
+ return None
+ account_url = self._get_azure_field(connection, "account_url")
+ if account_url:
+ # The Azure SDK accepts an account_url without a scheme, which
urlsplit reads as a path.
+ hostname = urlsplit(account_url if "//" in account_url else
f"//{account_url}").hostname
+ if hostname:
+ return hostname.split(".", 1)[0]
+ return connection.host or None
+
+ def configure_secrets(self, conn: DuckDBPyConnection) -> None:
+ """Set the Azure transport, if one is configured, and create the
DuckDB Azure secret."""
+ transport = self.transport_option_type
+ if transport:
+ if transport not in ("default", "curl"):
+ raise ValueError(
+ f"Unknown transport_option_type {transport!r}. Expected
'default' or 'curl'."
+ )
+ # GLOBAL, not the session: DbApiHook runs statements on
conn.cursor(), a connection of
+ # its own that does not see a session setting of conn, while the
secret is
+ # database-wide already.
+ conn.execute(f"SET GLOBAL azure_transport_option_type =
'{transport}';")
+
+ strategy = self.credential_strategy
+ if strategy == "none":
+ self.log.debug("credential_strategy is 'none'; not creating a
DuckDB Azure secret.")
+ return
+
+ self._validate_identifier(self.secret_name, "secret")
+ parts = ["TYPE azure", *self._provider_clauses(strategy)]
+ self.log.info("Creating DuckDB Azure secret %r using the %r
strategy.", self.secret_name, strategy)
+ conn.execute(f"CREATE OR REPLACE SECRET {self.secret_name} ({',
'.join(parts)});")
+
+ def _provider_clauses(self, strategy: CredentialStrategy) -> list[str]:
+ if strategy == "config":
+ return [*self._config_clauses(), *self._proxy_clauses()]
+ if strategy == "credential_chain":
+ clauses = ["PROVIDER credential_chain"]
+ if self.credential_chain:
+ clauses.append(f"CHAIN '{self._quote(self.credential_chain)}'")
+ return [*clauses, *self._account_clauses(), *self._proxy_clauses()]
+ raise ValueError(
+ f"Unknown credential_strategy {strategy!r}. Expected 'config',
'credential_chain' or 'none'."
+ )
+
+ def _config_clauses(self) -> list[str]:
+ """Translate the credentials of the ADLS connection, in the order the
ADLS hook reads them."""
+ connection = self.azure_connection
+ connection_string = self._get_azure_field(connection,
"connection_string")
+ if connection_string:
+ return self._connection_string_clauses(connection_string)
+ tenant_id = self._get_azure_field(connection, "tenant_id")
+ if tenant_id:
+ return self._service_principal_clauses(tenant_id)
+ if connection.password:
+ return self._account_key_clauses(connection.password)
+ raise ValueError(
+ f"The ADLS connection {self.azure_conn_id!r} has no credentials
for the 'config' credential "
+ "strategy: it needs a connection_string, a tenant_id with a login
(client id) and a "
+ "password (client secret), or a password (account key). Use
'credential_chain' to let "
+ "the Azure SDK resolve credentials."
+ )
+
+ def _connection_string_clauses(self, connection_string: str) -> list[str]:
+ return ["PROVIDER config", f"CONNECTION_STRING
'{self._quote(connection_string)}'"]
+
+ def _account_key_clauses(self, account_key: str) -> list[str]:
+ account_name = self.get_account_name()
+ if not account_name:
+ raise ValueError(
+ f"The ADLS connection {self.azure_conn_id!r} has an account
key but no storage account. "
+ "Set its host or account_url, or account_name on the DuckDB
connection."
+ )
+ return
self._connection_string_clauses(f"AccountName={account_name};AccountKey={account_key}")
+
+ def _service_principal_clauses(self, tenant_id: str) -> list[str]:
+ connection = self.azure_connection
+ if not (connection.login and connection.password):
+ raise ValueError(
+ f"The ADLS connection {self.azure_conn_id!r} has a tenant_id
but no login (client id) "
+ "or password (client secret) for the 'config' credential
strategy."
+ )
+ return [
+ "PROVIDER service_principal",
+ f"TENANT_ID '{self._quote(tenant_id)}'",
+ f"CLIENT_ID '{self._quote(connection.login)}'",
+ f"CLIENT_SECRET '{self._quote(connection.password)}'",
+ *self._account_clauses(),
+ ]
+
+ def _account_clauses(self) -> list[str]:
+ account_name = self.get_account_name()
+ return [f"ACCOUNT_NAME '{self._quote(account_name)}'"] if account_name
else []
+
+ def _proxy_clauses(self) -> list[str]:
+ connection = self.optional_azure_connection
+ if connection is None:
+ return []
+ proxy = (connection.extra_dejson.get("proxies") or {}).get("https")
+ return [f"HTTP_PROXY '{self._quote(proxy)}'"] if proxy else []
+
+ @staticmethod
+ def _get_azure_field(connection: Connection, field_name: str) -> Any:
+ return get_field(
+ conn_id=connection.conn_id,
+ conn_type="adls",
+ extras=connection.extra_dejson,
+ field_name=field_name,
+ )
+
+ @staticmethod
+ def _quote(value: str) -> str:
+ """Escape single quotes so a value cannot break out of its SQL
literal."""
+ return value.replace("'", "''")
+
+ def get_openlineage_database_info(self, connection: Any) -> Any:
+ """Return no lineage metadata; a DuckDB database is task-local and has
no stable namespace."""
+ return None
diff --git
a/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_duckdb.py
b/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_duckdb.py
new file mode 100644
index 00000000000..8f3e9c10ae3
--- /dev/null
+++ b/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_duckdb.py
@@ -0,0 +1,364 @@
+# 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 json
+from unittest import mock
+
+import pytest
+from duckdb import DuckDBPyConnection
+
+from airflow.models.connection import Connection
+from airflow.providers.duckdb.hooks.duckdb import DuckDBHook
+from airflow.providers.duckdb.operators.duckdb import
DuckDBExecuteQueryOperator
+from airflow.providers.microsoft.azure.hooks.duckdb import AzureDuckDBHook
+
+try:
+ from airflow.sdk.exceptions import AirflowNotFoundException
+except ImportError:
+ from airflow.exceptions import AirflowNotFoundException # type:
ignore[no-redef]
+
+GET_CONNECTION =
"airflow.providers.microsoft.azure.hooks.duckdb.AzureDuckDBHook.get_connection"
+# ``spec`` rather than ``autospec``: autospec replaces the inherited
classmethod with a plain function,
+# which then receives the hook as ``conn_id``.
+GET_CONNECTION_SPEC = AzureDuckDBHook.get_connection
+
+SERVICE_PRINCIPAL = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ login="client-id",
+ password="client-secret",
+ extra=json.dumps(
+ {
+ "tenant_id": "tenant-id",
+ "account_url": "https://onelake.dfs.fabric.microsoft.com",
+ "proxies": {"https": "http://proxy:8080"},
+ }
+ ),
+)
+
+
+def connections(*available: Connection):
+ """Patch get_connection to return ``available`` by id; any other id (the
DuckDB one) is missing."""
+ by_id = {connection.conn_id: connection for connection in available}
+
+ def get_connection(conn_id):
+ if conn_id not in by_id:
+ raise AirflowNotFoundException(conn_id)
+ return by_id[conn_id]
+
+ return mock.patch(GET_CONNECTION, spec=GET_CONNECTION_SPEC,
side_effect=get_connection)
+
+
+def statements(hook: AzureDuckDBHook) -> list[str]:
+ """Run configure_secrets against a fake DuckDB connection; return the
statements it issued."""
+ conn = mock.create_autospec(DuckDBPyConnection, instance=True)
+ hook.configure_secrets(conn)
+ return [call.args[0] for call in conn.execute.call_args_list]
+
+
+def secret_statement(hook: AzureDuckDBHook) -> str:
+ issued = statements(hook)
+ return issued[-1] if issued else ""
+
+
+class TestAzureDuckDBHookConnectionType:
+ """The connection type is the integration point: it is how the generic
operator reaches this hook."""
+
+ def test_declares_its_own_connection_type(self):
+ assert AzureDuckDBHook.conn_type == "duckdb_azure"
+ assert AzureDuckDBHook.conn_type != DuckDBHook.conn_type
+ assert AzureDuckDBHook.default_conn_name == "duckdb_azure_default"
+
+ def test_reuses_the_duckdb_connection_id_attribute(self):
+ """``Connection.get_hook`` passes the conn id under this name, so it
has to keep matching."""
+ assert AzureDuckDBHook.conn_name_attr == DuckDBHook.conn_name_attr
+
+ def test_the_generic_operator_resolves_this_hook_from_the_connection(self):
+ connection = Connection(conn_id="azure_duck",
conn_type=AzureDuckDBHook.conn_type)
+ operator = DuckDBExecuteQueryOperator(task_id="t", sql="SELECT 1",
conn_id="azure_duck")
+ with (
+ mock.patch(GET_CONNECTION, spec=GET_CONNECTION_SPEC,
return_value=connection),
+ mock.patch(
+
"airflow.providers.duckdb.hooks.duckdb.DuckDBHook.get_connection",
+ spec=GET_CONNECTION_SPEC,
+ return_value=connection,
+ ),
+ ):
+ hook = operator.get_db_hook()
+
+ assert isinstance(hook, AzureDuckDBHook)
+ assert hook.get_conn_id() == "azure_duck"
+
+ def test_ui_hides_the_fields_it_does_not_use(self):
+ behaviour = AzureDuckDBHook.get_ui_field_behaviour()
+ assert set(behaviour["hidden_fields"]) == {"login", "password",
"port", "schema"}
+ assert behaviour["relabeling"] == {"host": "Database path"}
+
+
+class TestAzureDuckDBHookExtensions:
+ def test_azure_extension_is_required(self):
+ with connections():
+ assert AzureDuckDBHook().get_extensions() == ["azure"]
+
+ def test_required_extension_is_kept_when_more_are_requested(self):
+ with connections():
+ assert AzureDuckDBHook(extensions=["delta"]).get_extensions() ==
["azure", "delta"]
+
+ def test_extension_downloads_are_enabled_for_azure(self):
+ with connections():
+ assert AzureDuckDBHook().autoinstall_extensions is True
+
+ def test_extension_downloads_can_still_be_forbidden(self):
+ with connections():
+ assert
AzureDuckDBHook(autoinstall_extensions=False).autoinstall_extensions is False
+
+
+class TestAzureDuckDBHookConfigStrategy:
+ def test_config_is_the_default_and_uses_the_service_principal(self):
+ with connections(SERVICE_PRINCIPAL):
+ statement = secret_statement(AzureDuckDBHook())
+
+ assert statement == (
+ "CREATE OR REPLACE SECRET airflow_azure (TYPE azure, PROVIDER
service_principal, "
+ "TENANT_ID 'tenant-id', CLIENT_ID 'client-id', CLIENT_SECRET
'client-secret', "
+ "ACCOUNT_NAME 'onelake', HTTP_PROXY 'http://proxy:8080');"
+ )
+
+ def test_connection_string_wins_over_the_service_principal(self):
+ connection = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ login="client-id",
+ password="client-secret",
+ extra=json.dumps({"connection_string":
"AccountName=acc;AccountKey=key", "tenant_id": "t"}),
+ )
+ with connections(connection):
+ statement = secret_statement(AzureDuckDBHook())
+
+ assert "PROVIDER config, CONNECTION_STRING
'AccountName=acc;AccountKey=key'" in statement
+ assert "CLIENT_SECRET" not in statement
+
+ def test_account_falls_back_to_the_host(self):
+ connection = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ host="storageaccount",
+ login="client-id",
+ password="client-secret",
+ extra=json.dumps({"tenant_id": "tenant-id"}),
+ )
+ with connections(connection):
+ statement = secret_statement(AzureDuckDBHook())
+
+ assert "ACCOUNT_NAME 'storageaccount'" in statement
+ assert "HTTP_PROXY" not in statement
+
+ @pytest.mark.parametrize(
+ "account_url",
+ [
+ "https://storageaccount.dfs.core.windows.net",
+ "https://storageaccount.dfs.core.windows.net:443/",
+ "storageaccount.dfs.core.windows.net",
+ ],
+ )
+ def test_account_comes_from_the_account_url_with_or_without_a_scheme(self,
account_url):
+ connection = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ host="ignored",
+ extra=json.dumps({"account_url": account_url}),
+ )
+ with connections(connection):
+ assert AzureDuckDBHook().get_account_name() == "storageaccount"
+
+ def
test_account_falls_back_to_the_host_when_the_account_url_has_none(self):
+ connection = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ host="storageaccount",
+ extra=json.dumps({"account_url": "https://"}),
+ )
+ with connections(connection):
+ assert AzureDuckDBHook().get_account_name() == "storageaccount"
+
+ def test_account_name_argument_wins(self):
+ with connections(SERVICE_PRINCIPAL):
+ statement = secret_statement(AzureDuckDBHook(account_name="other"))
+
+ assert "ACCOUNT_NAME 'other'" in statement
+
+ def test_account_key_becomes_a_connection_string(self):
+ connection = Connection(
+ conn_id="adls_default", conn_type="adls", host="storageaccount",
password="account-key"
+ )
+ with connections(connection):
+ statement = secret_statement(AzureDuckDBHook())
+
+ assert statement == (
+ "CREATE OR REPLACE SECRET airflow_azure (TYPE azure, PROVIDER
config, "
+ "CONNECTION_STRING
'AccountName=storageaccount;AccountKey=account-key');"
+ )
+
+ def test_account_key_without_a_storage_account_is_rejected(self):
+ connection = Connection(conn_id="adls_default", conn_type="adls",
password="account-key")
+ with connections(connection), pytest.raises(ValueError, match="no
storage account"):
+ secret_statement(AzureDuckDBHook())
+
+ def test_tenant_without_client_credentials_is_rejected(self):
+ connection = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ password="client-secret",
+ extra=json.dumps({"tenant_id": "tenant-id"}),
+ )
+ with connections(connection), pytest.raises(ValueError, match="no
login"):
+ secret_statement(AzureDuckDBHook())
+
+ def test_missing_credentials_are_rejected(self):
+ connection = Connection(conn_id="adls_default", conn_type="adls",
host="storageaccount")
+ with connections(connection), pytest.raises(ValueError, match="has no
credentials"):
+ secret_statement(AzureDuckDBHook())
+
+ def test_quotes_in_credentials_cannot_break_out_of_the_literal(self):
+ connection = Connection(
+ conn_id="adls_default",
+ conn_type="adls",
+ login="client-id",
+ password="it's",
+ extra=json.dumps({"tenant_id": "tenant-id"}),
+ )
+ with connections(connection):
+ statement = secret_statement(AzureDuckDBHook())
+
+ assert "CLIENT_SECRET 'it''s'" in statement
+
+
+class TestAzureDuckDBHookOtherStrategies:
+ def test_credential_chain_does_not_write_credentials(self):
+ with connections(SERVICE_PRINCIPAL):
+ statement = secret_statement(
+ AzureDuckDBHook(
+ credential_strategy="credential_chain",
credential_chain="managed_identity;env"
+ )
+ )
+
+ assert statement == (
+ "CREATE OR REPLACE SECRET airflow_azure (TYPE azure, PROVIDER
credential_chain, "
+ "CHAIN 'managed_identity;env', ACCOUNT_NAME 'onelake', HTTP_PROXY
'http://proxy:8080');"
+ )
+
+ def test_credential_chain_needs_no_adls_connection(self):
+ with connections():
+ statement = secret_statement(
+ AzureDuckDBHook(credential_strategy="credential_chain",
account_name="myaccount")
+ )
+
+ assert statement == (
+ "CREATE OR REPLACE SECRET airflow_azure (TYPE azure, PROVIDER
credential_chain, "
+ "ACCOUNT_NAME 'myaccount');"
+ )
+
+ def test_credential_chain_needs_an_adls_connection_that_is_named(self):
+ hook = AzureDuckDBHook(credential_strategy="credential_chain",
azure_conn_id="lake")
+ with connections(), pytest.raises(AirflowNotFoundException):
+ secret_statement(hook)
+
+ def test_config_strategy_needs_the_adls_connection(self):
+ with connections(), pytest.raises(AirflowNotFoundException):
+ secret_statement(AzureDuckDBHook())
+
+ def test_strategy_none_creates_no_secret(self):
+ with connections():
+ assert statements(AzureDuckDBHook(credential_strategy="none")) ==
[]
+
+ def test_unknown_strategy_is_rejected(self):
+ with connections(SERVICE_PRINCIPAL), pytest.raises(ValueError,
match="Unknown credential_strategy"):
+ secret_statement(AzureDuckDBHook(credential_strategy="bogus")) #
type: ignore[arg-type]
+
+ def test_secret_name_is_validated(self):
+ with connections(SERVICE_PRINCIPAL), pytest.raises(ValueError,
match="Invalid DuckDB secret name"):
+ secret_statement(AzureDuckDBHook(secret_name="bad name; DROP"))
+
+ def test_secret_name_is_used(self):
+ with connections(SERVICE_PRINCIPAL):
+ statement = secret_statement(AzureDuckDBHook(secret_name="lake"))
+
+ assert statement.startswith("CREATE OR REPLACE SECRET lake (TYPE
azure,")
+
+
+class TestAzureDuckDBHookTransport:
+ def test_no_transport_setting_by_default(self):
+ with connections(SERVICE_PRINCIPAL):
+ issued = statements(AzureDuckDBHook())
+
+ assert len(issued) == 1
+ assert issued[0].startswith("CREATE OR REPLACE SECRET")
+
+ def test_transport_is_set_globally_before_the_secret(self):
+ with connections(SERVICE_PRINCIPAL):
+ issued = statements(AzureDuckDBHook(transport_option_type="curl"))
+
+ assert issued[0] == "SET GLOBAL azure_transport_option_type = 'curl';"
+ assert issued[1].startswith("CREATE OR REPLACE SECRET")
+
+ def test_unknown_transport_is_rejected(self):
+ with connections(SERVICE_PRINCIPAL), pytest.raises(ValueError,
match="Unknown transport_option_type"):
+ statements(AzureDuckDBHook(transport_option_type="winhttp")) #
type: ignore[arg-type]
+
+
+class TestAzureDuckDBHookConnectionOverrides:
+ """Every parameter may be set in the extra of the DuckDB connection; an
explicit argument wins."""
+
+ duckdb_connection = Connection(
+ conn_id="duckdb_azure_default",
+ conn_type="duckdb_azure",
+ extra=json.dumps(
+ {
+ "azure_conn_id": "lake",
+ "credential_strategy": "credential_chain",
+ "account_name": "fromextra",
+ "transport_option_type": "curl",
+ "secret_name": "from_extra",
+ }
+ ),
+ )
+ lake = Connection(conn_id="lake", conn_type="adls", host="lakeaccount")
+
+ def test_parameters_come_from_the_connection_extra(self):
+ with connections(self.duckdb_connection, self.lake):
+ hook = AzureDuckDBHook()
+ issued = statements(hook)
+
+ assert hook.azure_conn_id == "lake"
+ assert issued == [
+ "SET GLOBAL azure_transport_option_type = 'curl';",
+ "CREATE OR REPLACE SECRET from_extra (TYPE azure, PROVIDER
credential_chain, "
+ "ACCOUNT_NAME 'fromextra');",
+ ]
+
+ def test_explicit_argument_wins_over_the_connection_extra(self):
+ with connections(self.duckdb_connection, self.lake):
+ hook = AzureDuckDBHook(account_name="explicit",
secret_name="explicit")
+ statement = secret_statement(hook)
+
+ assert statement.startswith("CREATE OR REPLACE SECRET explicit (")
+ assert "ACCOUNT_NAME 'explicit'" in statement
+
+ def test_azure_conn_id_defaults_to_adls_default(self):
+ with connections():
+ assert AzureDuckDBHook().azure_conn_id == "adls_default"
diff --git a/uv.lock b/uv.lock
index 03a0a9ef939..43a062737f7 100644
--- a/uv.lock
+++ b/uv.lock
@@ -7038,6 +7038,9 @@ amazon = [
common-messaging = [
{ name = "apache-airflow-providers-common-messaging" },
]
+duckdb = [
+ { name = "apache-airflow-providers-duckdb" },
+]
google = [
{ name = "apache-airflow-providers-google" },
]
@@ -7058,6 +7061,7 @@ dev = [
{ name = "apache-airflow-providers-amazon" },
{ name = "apache-airflow-providers-common-compat" },
{ name = "apache-airflow-providers-common-messaging" },
+ { name = "apache-airflow-providers-duckdb" },
{ name = "apache-airflow-providers-google" },
{ name = "apache-airflow-providers-openlineage" },
{ name = "apache-airflow-providers-oracle" },
@@ -7078,6 +7082,7 @@ requires-dist = [
{ name = "apache-airflow-providers-amazon", marker = "extra == 'amazon'",
editable = "providers/amazon" },
{ name = "apache-airflow-providers-common-compat", editable =
"providers/common/compat" },
{ name = "apache-airflow-providers-common-messaging", marker = "extra ==
'common-messaging'", editable = "providers/common/messaging" },
+ { name = "apache-airflow-providers-duckdb", marker = "extra == 'duckdb'",
editable = "providers/duckdb" },
{ name = "apache-airflow-providers-google", marker = "extra == 'google'",
editable = "providers/google" },
{ name = "apache-airflow-providers-openlineage", marker = "extra ==
'openlineage'", editable = "providers/openlineage" },
{ name = "apache-airflow-providers-oracle", marker = "extra == 'oracle'",
editable = "providers/oracle" },
@@ -7113,7 +7118,7 @@ requires-dist = [
{ name = "msgraph-core", specifier = ">=1.3.3" },
{ name = "msgraphfs", specifier = ">=0.3.0" },
]
-provides-extras = ["amazon", "oracle", "sftp", "common-messaging", "google",
"openlineage"]
+provides-extras = ["amazon", "oracle", "sftp", "common-messaging", "google",
"openlineage", "duckdb"]
[package.metadata.requires-dev]
dev = [
@@ -7122,6 +7127,7 @@ dev = [
{ name = "apache-airflow-providers-amazon", editable = "providers/amazon"
},
{ name = "apache-airflow-providers-common-compat", editable =
"providers/common/compat" },
{ name = "apache-airflow-providers-common-messaging", editable =
"providers/common/messaging" },
+ { name = "apache-airflow-providers-duckdb", editable = "providers/duckdb"
},
{ name = "apache-airflow-providers-google", editable = "providers/google"
},
{ name = "apache-airflow-providers-openlineage", editable =
"providers/openlineage" },
{ name = "apache-airflow-providers-oracle", editable = "providers/oracle"
},