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 83a439e6a19 Decouple GCS ObjectStorageProvider from common-sql into
google provider (#77621)
83a439e6a19 is described below
commit 83a439e6a19c1a290979ea095bfd55afed3b6bb4
Author: Akshaykumar <[email protected]>
AuthorDate: Fri Nov 27 02:43:05 2026 +0530
Decouple GCS ObjectStorageProvider from common-sql into google provider
(#77621)
* Decouple GCS ObjectStorageProvider from common-sql into google provider
* Reuse get_field for GCS DataFusion credentials and note the S3/GCS move
in common-sql changelog
---------
Co-authored-by: Akshay <[email protected]>
---
providers/common/sql/docs/changelog.rst | 12 ++
providers/common/sql/docs/index.rst | 2 +
providers/common/sql/docs/operators.rst | 2 +-
providers/common/sql/pyproject.toml | 4 +
.../providers/common/sql/datafusion/engine.py | 28 ---
.../sql/datafusion/object_storage_provider.py | 81 ++-------
.../unit/common/sql/datafusion/test_engine.py | 129 ++-----------
.../sql/datafusion/test_object_storage_provider.py | 201 ++++++++++-----------
providers/google/docs/index.rst | 7 +-
providers/google/provider.yaml | 4 +
providers/google/pyproject.toml | 5 +
.../providers/google/cloud/datafusion/__init__.py | 17 ++
.../google/cloud/datafusion/object_storage.py | 127 +++++++++++++
.../airflow/providers/google/get_provider_info.py | 6 +
.../tests/unit/google/cloud/datafusion/__init__.py | 17 ++
.../google/cloud/datafusion/test_object_storage.py | 196 ++++++++++++++++++++
uv.lock | 18 +-
17 files changed, 547 insertions(+), 309 deletions(-)
diff --git a/providers/common/sql/docs/changelog.rst
b/providers/common/sql/docs/changelog.rst
index c91b6768a4c..e3dfaabf994 100644
--- a/providers/common/sql/docs/changelog.rst
+++ b/providers/common/sql/docs/changelog.rst
@@ -25,6 +25,18 @@
Changelog
---------
+.. note::
+ The S3 and GCS DataFusion object storage providers used by
``AnalyticsOperator`` moved out of
+ common-sql into the provider that owns the connection type. ``s3://``
sources now need
+ ``apache-airflow-providers-amazon[datafusion]`` and ``gs://`` sources need
+ ``apache-airflow-providers-google[datafusion]``; without them, resolving
the storage type raises
+ a ``ValueError`` naming the extra to install. Connection errors for these
storage types (unknown
+ connection type, unsupported or conflicting credential fields) now surface
as
+ ``ObjectStoreCreationException`` instead of ``ValueError``. Importing
``S3ObjectStorageProvider``
+ or ``GCSObjectStorageProvider`` from
+ ``airflow.providers.common.sql.datafusion.object_storage_provider`` still
works but emits
+ ``AirflowProviderDeprecationWarning``.
+
3.1.0
.....
diff --git a/providers/common/sql/docs/index.rst
b/providers/common/sql/docs/index.rst
index 8a2d38ffb71..6bcc3b4573e 100644
--- a/providers/common/sql/docs/index.rst
+++ b/providers/common/sql/docs/index.rst
@@ -127,6 +127,7 @@ Dependent package
====================================================================================================================
==================
`apache-airflow-providers-amazon
<https://airflow.apache.org/docs/apache-airflow-providers-amazon>`_
``amazon``
`apache-airflow-providers-apache-iceberg
<https://airflow.apache.org/docs/apache-airflow-providers-apache-iceberg>`_
``apache.iceberg``
+`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``
====================================================================================================================
==================
@@ -152,6 +153,7 @@ Extra Dependencies
``pyiceberg-core`` ``pyiceberg-core>=0.8.0``
``apache.iceberg`` ``apache-airflow-providers-apache-iceberg``
``amazon`` ``apache-airflow-providers-amazon>=9.38.0``
+``google`` ``apache-airflow-providers-google>=23.1.0``
==================
=======================================================================================================================================================================
Downloading official packages
diff --git a/providers/common/sql/docs/operators.rst
b/providers/common/sql/docs/operators.rst
index d2ff27b5f4b..a11da391e5b 100644
--- a/providers/common/sql/docs/operators.rst
+++ b/providers/common/sql/docs/operators.rst
@@ -343,7 +343,7 @@ The Analytics Operator is ideal for performing efficient,
high-performance analy
Supported Storage Systems
-------------------------
- S3 (requires ``apache-airflow-providers-amazon[datafusion]``)
-- GCS
+- GCS (requires ``apache-airflow-providers-google[datafusion]``)
- Azure Blob Storage
- Local File System
diff --git a/providers/common/sql/pyproject.toml
b/providers/common/sql/pyproject.toml
index b1c01c0f0e9..e1b408ea747 100644
--- a/providers/common/sql/pyproject.toml
+++ b/providers/common/sql/pyproject.toml
@@ -99,6 +99,9 @@ dependencies = [
"amazon" = [
"apache-airflow-providers-amazon>=9.38.0" # use next version
]
+"google" = [
+ "apache-airflow-providers-google>=23.1.0" # use next version
+]
[dependency-groups]
dev = [
@@ -108,6 +111,7 @@ dev = [
"apache-airflow-providers-amazon",
"apache-airflow-providers-apache-iceberg",
"apache-airflow-providers-common-compat",
+ "apache-airflow-providers-google",
"apache-airflow-providers-openlineage",
# Additional devel dependencies (do not remove this line and add extra
development dependencies)
"apache-airflow-providers-common-sql[pandas]",
diff --git
a/providers/common/sql/src/airflow/providers/common/sql/datafusion/engine.py
b/providers/common/sql/src/airflow/providers/common/sql/datafusion/engine.py
index c13d4829837..66ffb5cc499 100644
--- a/providers/common/sql/src/airflow/providers/common/sql/datafusion/engine.py
+++ b/providers/common/sql/src/airflow/providers/common/sql/datafusion/engine.py
@@ -158,14 +158,6 @@ class DataFusionEngine(LoggingMixin):
credentials: dict[str, Any] = {}
extra_config: dict[str, Any] = {}
- def _get_gcp_extra_field(extra_dejson: dict[str, Any], field_name:
str) -> Any:
- # Older Airflow connection UIs wrote custom extra fields as
- # extra__google_cloud_platform__<field_name> instead of the bare
key; GoogleBaseHook
- # still reads that legacy spelling as a fallback, so this must too.
- if field_name in extra_dejson:
- return extra_dejson[field_name]
- return
extra_dejson.get(f"extra__google_cloud_platform__{field_name}")
-
def _get_wasb_extra_field(extra_dejson: dict[str, Any], field_name:
str) -> Any:
# Older Airflow connection UIs wrote custom extra fields as
# extra__wasb__<field_name> instead of the bare key; WasbHook
still reads that
@@ -173,26 +165,6 @@ class DataFusionEngine(LoggingMixin):
return extra_dejson.get(field_name,
extra_dejson.get(f"extra__wasb__{field_name}"))
match conn.conn_type:
- case "google_cloud_platform":
- extra_dejson = conn.extra_dejson
- for unsupported_field in ("key_secret_name",
"credential_config_file", "impersonation_chain"):
- if _get_gcp_extra_field(extra_dejson, unsupported_field):
- raise ValueError(
- f"Connection field {unsupported_field!r} is not
supported for DataFusion "
- "GCS access; only key_path, keyfile_dict,
GOOGLE_APPLICATION_CREDENTIALS, or "
- "ambient credentials (gcloud ADC file / metadata
server) are used."
- )
- key_path = _get_gcp_extra_field(extra_dejson, "key_path") or
None
- keyfile_dict = _get_gcp_extra_field(extra_dejson,
"keyfile_dict") or None
- if key_path and keyfile_dict:
- raise ValueError(
- "The `keyfile_dict` and `key_path` fields are mutually
exclusive. "
- "Please provide only one value."
- )
- if not key_path and not keyfile_dict:
- key_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
- credentials = self._remove_none_values({"key_path": key_path,
"keyfile_dict": keyfile_dict})
-
case "wasb":
extra_dejson = conn.extra_dejson
for unsupported_field in (
diff --git
a/providers/common/sql/src/airflow/providers/common/sql/datafusion/object_storage_provider.py
b/providers/common/sql/src/airflow/providers/common/sql/datafusion/object_storage_provider.py
index 670c306e380..4f2f9766de5 100644
---
a/providers/common/sql/src/airflow/providers/common/sql/datafusion/object_storage_provider.py
+++
b/providers/common/sql/src/airflow/providers/common/sql/datafusion/object_storage_provider.py
@@ -16,15 +16,12 @@
# under the License.
from __future__ import annotations
-import json
import os
import re
-import tempfile
import warnings
-from pathlib import Path
from typing import Any
-from datafusion.object_store import GoogleCloud, LocalFileSystem,
MicrosoftAzure
+from datafusion.object_store import LocalFileSystem, MicrosoftAzure
from airflow.exceptions import AirflowProviderDeprecationWarning
from airflow.providers.common.compat.module_loading import import_string
@@ -32,57 +29,6 @@ from airflow.providers.common.sql.config import
ConnectionConfig, StorageType
from airflow.providers.common.sql.datafusion.base import ObjectStorageProvider
from airflow.providers.common.sql.datafusion.exceptions import
ObjectStoreCreationException
-
-class GCSObjectStorageProvider(ObjectStorageProvider):
- """GCS Object Storage Provider using DataFusion's GoogleCloud."""
-
- @property
- def get_storage_type(self) -> StorageType:
- """Return the storage type."""
- return StorageType.GCS
-
- def create_object_store(self, path: str, connection_config:
ConnectionConfig | None = None):
- """Create a GCS object store using DataFusion's GoogleCloud."""
- if connection_config is None:
- raise ValueError(f"connection_config must be provided for
{self.get_storage_type.value}")
-
- credentials = connection_config.credentials
- key_path = credentials.get("key_path")
- keyfile_dict = credentials.get("keyfile_dict")
- temp_key_path: str | None = None
-
- try:
- bucket = self.get_bucket(path)
-
- if not key_path and keyfile_dict:
- # GoogleCloud only accepts a file path, not inline JSON; safe
to delete once
- # constructed since the credentials are read only at
construction time.
- key_content = keyfile_dict if isinstance(keyfile_dict, str)
else json.dumps(keyfile_dict)
- with tempfile.NamedTemporaryFile(mode="w", suffix=".json",
delete=False) as key_file:
- key_file.write(key_content)
- temp_key_path = key_path = key_file.name
-
- if key_path is not None and not Path(key_path).is_file():
- raise FileNotFoundError(f"Service account key file not found:
{key_path}")
-
- gcs_store = GoogleCloud(bucket_name=bucket,
service_account_path=key_path)
- self.log.info("Created GCS object store for bucket %s", bucket)
-
- return gcs_store
-
- except BaseException as e:
- # A bad key file panics as pyo3_runtime.PanicException, not a
plain Exception.
- raise ObjectStoreCreationException(f"Failed to create GCS object
store: {e}")
-
- finally:
- if temp_key_path is not None:
- Path(temp_key_path).unlink(missing_ok=True)
-
- def get_scheme(self) -> str:
- """Return the scheme for GCS."""
- return "gs://"
-
-
_ABFS_URI_RE = re.compile(
r"^abfss?://(?P<container>[^@/]+)@(?P<account>[^./]+)\.(?P<host>[^/]+)(?P<path>/.*)?$"
)
@@ -201,12 +147,12 @@ class LocalObjectStorageProvider(ObjectStorageProvider):
# TODO: Add support for HTTP:
https://datafusion.apache.org/python/autoapi/datafusion/object_store/index.html
EMBEDDED_PROVIDERS: dict[StorageType, type[ObjectStorageProvider]] = {
StorageType.LOCAL: LocalObjectStorageProvider,
- StorageType.GCS: GCSObjectStorageProvider,
StorageType.AZURE: AzureObjectStorageProvider,
}
_STORAGE_TYPE_PROVIDER_HINTS: dict[str, str] = {
"s3": "apache-airflow-providers-amazon[datafusion]",
+ "gcs": "apache-airflow-providers-google[datafusion]",
}
@@ -223,6 +169,13 @@ def _get_legacy_object_storage_provider(type_key: str) ->
ObjectStorageProvider:
raise ValueError(_missing_provider_message(type_key)) from err
return S3ObjectStorageProvider()
+ if type_key == StorageType.GCS.value:
+ try:
+ from airflow.providers.google.cloud.datafusion.object_storage
import GCSObjectStorageProvider
+ except ImportError as err:
+ raise ValueError(_missing_provider_message(type_key)) from err
+ return GCSObjectStorageProvider()
+
raise ValueError(_missing_provider_message(type_key))
@@ -251,16 +204,20 @@ def get_object_storage_provider(storage_type:
StorageType) -> ObjectStorageProvi
raise ValueError(_missing_provider_message(type_key))
+_MOVED_PROVIDER_MODULES: dict[str, str] = {
+ "S3ObjectStorageProvider":
"airflow.providers.amazon.aws.datafusion.object_storage",
+ "GCSObjectStorageProvider":
"airflow.providers.google.cloud.datafusion.object_storage",
+}
+
+
def __getattr__(name: str) -> Any:
- if name == "S3ObjectStorageProvider":
+ if module_path := _MOVED_PROVIDER_MODULES.get(name):
warnings.warn(
- "Importing S3ObjectStorageProvider from "
+ f"Importing {name} from "
"airflow.providers.common.sql.datafusion.object_storage_provider
is deprecated. "
- "Import it from
airflow.providers.amazon.aws.datafusion.object_storage instead.",
+ f"Import it from {module_path} instead.",
AirflowProviderDeprecationWarning,
stacklevel=2,
)
- from airflow.providers.amazon.aws.datafusion.object_storage import
S3ObjectStorageProvider
-
- return S3ObjectStorageProvider
+ return import_string(f"{module_path}.{name}")
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git
a/providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py
b/providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py
index 613fbacff61..1c837ba88df 100644
--- a/providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py
+++ b/providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py
@@ -338,7 +338,11 @@ class TestDataFusionEngine:
assert engine.registered_tables == {"test_table": "s3://bucket/path/"}
- def test_get_connection_config_delegates_provider_owned_storage(self):
+ @pytest.mark.parametrize(
+ ("conn_id", "storage_type"),
+ [("aws_default", StorageType.S3), ("google_cloud_default",
StorageType.GCS)],
+ )
+ def test_get_connection_config_delegates_provider_owned_storage(self,
conn_id, storage_type):
"""A storage type owned by a provider package gets a bare
ConnectionConfig without fetching the connection."""
engine = DataFusionEngine()
@@ -346,10 +350,10 @@ class TestDataFusionEngine:
"airflow.providers.common.sql.datafusion.engine.BaseHook.get_connection",
autospec=True,
) as mock_get_connection:
- result = engine._get_connection_config("aws_default",
StorageType.S3)
+ result = engine._get_connection_config(conn_id, storage_type)
mock_get_connection.assert_not_called()
- assert result.conn_id == "aws_default"
+ assert result.conn_id == conn_id
assert result.credentials == {}
assert result.extra_config == {}
@@ -357,119 +361,24 @@ class TestDataFusionEngine:
"""A storage type still implemented here has its credentials resolved
by the engine."""
engine = DataFusionEngine()
mock_conn = MagicMock()
- mock_conn.conn_id = "google_cloud_default"
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {"key_path": "/path/to/key.json"}
+ mock_conn.conn_id = "wasb_default"
+ mock_conn.conn_type = "wasb"
+ mock_conn.host = None
+ mock_conn.login = "myaccount"
+ mock_conn.password = None
+ mock_conn.extra_dejson = {"sas_token": "?sv=2020-08-04&sp=rl&sig=abc"}
with patch(
"airflow.providers.common.sql.datafusion.engine.BaseHook.get_connection",
return_value=mock_conn,
):
- result = engine._get_connection_config("google_cloud_default",
StorageType.GCS)
-
- assert result.conn_id == "google_cloud_default"
- assert result.credentials == {"key_path": "/path/to/key.json"}
-
- def test_get_credentials_gcs_with_key_path(self):
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {"key_path": "/path/to/key.json"}
- engine = DataFusionEngine()
-
- credentials, extra_config = engine._get_credentials(mock_conn)
-
- assert credentials == {"key_path": "/path/to/key.json"}
- assert extra_config == {}
-
- def test_get_credentials_gcs_with_keyfile_dict(self):
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {"keyfile_dict": '{"type":
"service_account"}'}
- engine = DataFusionEngine()
-
- credentials, extra_config = engine._get_credentials(mock_conn)
-
- assert credentials == {"keyfile_dict": '{"type": "service_account"}'}
- assert extra_config == {}
-
- def test_get_credentials_gcs_without_key_path_uses_ambient_auth(self,
monkeypatch):
- monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {}
- engine = DataFusionEngine()
+ result = engine._get_connection_config("wasb_default",
StorageType.AZURE)
- credentials, extra_config = engine._get_credentials(mock_conn)
-
- assert credentials == {}
- assert extra_config == {}
-
- def
test_get_credentials_gcs_uses_google_application_credentials_env_var(self,
monkeypatch):
- monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "/env/key.json")
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {}
- engine = DataFusionEngine()
-
- credentials, extra_config = engine._get_credentials(mock_conn)
-
- assert credentials == {"key_path": "/env/key.json"}
- assert extra_config == {}
-
- def
test_get_credentials_gcs_connection_key_path_takes_priority_over_env_var(self,
monkeypatch):
- monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "/env/key.json")
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {"key_path": "/connection/key.json"}
- engine = DataFusionEngine()
-
- credentials, extra_config = engine._get_credentials(mock_conn)
-
- assert credentials == {"key_path": "/connection/key.json"}
- assert extra_config == {}
-
- def
test_get_credentials_gcs_key_path_and_keyfile_dict_mutually_exclusive(self):
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {"key_path": "/path/to/key.json",
"keyfile_dict": "{}"}
- engine = DataFusionEngine()
-
- with pytest.raises(ValueError, match="mutually exclusive"):
- engine._get_credentials(mock_conn)
-
- @pytest.mark.parametrize(
- "unsupported_field", ["key_secret_name", "credential_config_file",
"impersonation_chain"]
- )
- def test_get_credentials_gcs_rejects_unsupported_identity_fields(self,
unsupported_field):
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {unsupported_field: "some-value"}
- engine = DataFusionEngine()
-
- with pytest.raises(ValueError, match=f"{unsupported_field!r} is not
supported"):
- engine._get_credentials(mock_conn)
-
- def test_get_credentials_gcs_reads_legacy_extra_prefixed_key_path(self):
- """Older Airflow connection UIs wrote custom extra fields as
- extra__google_cloud_platform__<field>; GoogleBaseHook still reads that
spelling."""
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson = {"extra__google_cloud_platform__key_path":
"/path/to/key.json"}
- engine = DataFusionEngine()
-
- credentials, extra_config = engine._get_credentials(mock_conn)
-
- assert credentials == {"key_path": "/path/to/key.json"}
- assert extra_config == {}
-
- def
test_get_credentials_gcs_rejects_legacy_extra_prefixed_unsupported_field(self):
- mock_conn = MagicMock()
- mock_conn.conn_type = "google_cloud_platform"
- mock_conn.extra_dejson =
{"extra__google_cloud_platform__impersonation_chain": "some-chain"}
- engine = DataFusionEngine()
-
- with pytest.raises(ValueError, match="'impersonation_chain' is not
supported"):
- engine._get_credentials(mock_conn)
+ assert result.conn_id == "wasb_default"
+ assert result.credentials == {
+ "account": "myaccount",
+ "sas_query_pairs": [("sv", "2020-08-04"), ("sp", "rl"), ("sig",
"abc")],
+ }
@pytest.mark.parametrize(
("password", "extra_dejson", "expected_access_key"),
diff --git
a/providers/common/sql/tests/unit/common/sql/datafusion/test_object_storage_provider.py
b/providers/common/sql/tests/unit/common/sql/datafusion/test_object_storage_provider.py
index 03128f74e20..55988e27670 100644
---
a/providers/common/sql/tests/unit/common/sql/datafusion/test_object_storage_provider.py
+++
b/providers/common/sql/tests/unit/common/sql/datafusion/test_object_storage_provider.py
@@ -16,8 +16,6 @@
# under the License.
from __future__ import annotations
-import json
-import os
import sys
from unittest.mock import MagicMock, patch
@@ -28,93 +26,12 @@ from airflow.providers.common.sql.config import
ConnectionConfig, StorageType
from airflow.providers.common.sql.datafusion.exceptions import
ObjectStoreCreationException
from airflow.providers.common.sql.datafusion.object_storage_provider import (
AzureObjectStorageProvider,
- GCSObjectStorageProvider,
LocalObjectStorageProvider,
get_object_storage_provider,
)
-class TestGCSObjectStorageProvider:
-
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.GoogleCloud")
- def test_gcs_provider_success_with_key_path(self, mock_gcs, tmp_path):
- key_path = tmp_path / "key.json"
- key_path.write_text("{}")
- provider = GCSObjectStorageProvider()
- connection_config = ConnectionConfig(
- conn_id="google_cloud_default",
- credentials={"key_path": str(key_path)},
- )
-
- store = provider.create_object_store("gs://demo-data/path",
connection_config)
-
- mock_gcs.assert_called_once_with(bucket_name="demo-data",
service_account_path=str(key_path))
- assert store == mock_gcs.return_value
- assert provider.get_storage_type == StorageType.GCS
- assert provider.get_scheme() == "gs://"
-
-
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.GoogleCloud")
- def test_gcs_provider_success_with_keyfile_dict(self, mock_gcs):
- provider = GCSObjectStorageProvider()
- keyfile_dict = {"type": "service_account", "private_key": "fake"}
- connection_config = ConnectionConfig(
- conn_id="google_cloud_default",
- credentials={"keyfile_dict": keyfile_dict},
- )
-
- provider.create_object_store("gs://demo-data/path", connection_config)
-
- mock_gcs.assert_called_once()
- temp_path = mock_gcs.call_args.kwargs["service_account_path"]
- assert not os.path.exists(temp_path), "temp key file should be deleted
after use"
-
-
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.GoogleCloud")
- def test_gcs_provider_writes_keyfile_dict_content_before_cleanup(self,
mock_gcs):
- written_content = {}
-
- def _capture_path(*, bucket_name, service_account_path):
- with open(service_account_path) as f:
- written_content["data"] = json.load(f)
-
- mock_gcs.side_effect = _capture_path
- provider = GCSObjectStorageProvider()
- keyfile_dict = {"type": "service_account", "private_key": "fake"}
- connection_config = ConnectionConfig(
- conn_id="google_cloud_default",
- credentials={"keyfile_dict": keyfile_dict},
- )
-
- provider.create_object_store("gs://demo-data/path", connection_config)
-
- assert written_content["data"] == keyfile_dict
-
- def test_gcs_provider_failure(self):
- provider = GCSObjectStorageProvider()
- connection_config = ConnectionConfig(conn_id="google_cloud_default")
-
- with patch(
-
"airflow.providers.common.sql.datafusion.object_storage_provider.GoogleCloud",
- side_effect=Exception("Error"),
- ):
- with pytest.raises(ObjectStoreCreationException, match="Failed to
create GCS object store"):
- provider.create_object_store("gs://demo-data/path",
connection_config)
-
- def test_gcs_provider_missing_key_file_raises_clear_error(self):
- """Uses the real GoogleCloud binding, not a mock, since it's the one
that panics."""
- provider = GCSObjectStorageProvider()
- connection_config = ConnectionConfig(
- conn_id="google_cloud_default",
- credentials={"key_path": "/nonexistent/key.json"},
- )
-
- with pytest.raises(ObjectStoreCreationException, match="Failed to
create GCS object store"):
- provider.create_object_store("gs://demo-data/path",
connection_config)
-
- def test_gcs_provider_requires_connection_config(self):
- provider = GCSObjectStorageProvider()
-
- with pytest.raises(ValueError, match="connection_config must be
provided for gcs"):
- provider.create_object_store("gs://demo-data/path")
-
+class TestAzureObjectStorageProvider:
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.MicrosoftAzure")
def test_azure_provider_success(self, mock_azure):
provider = AzureObjectStorageProvider()
@@ -333,11 +250,6 @@ class TestGetObjectStorageProvider:
provider = get_object_storage_provider(StorageType.LOCAL)
assert isinstance(provider, LocalObjectStorageProvider)
- def test_returns_gcs_provider_directly(self):
- """GCS is still implemented in common-sql, so it resolves without the
registry."""
- provider = get_object_storage_provider(StorageType.GCS)
- assert isinstance(provider, GCSObjectStorageProvider)
-
def test_returns_azure_provider_directly(self):
"""Azure is still implemented in common-sql, so it resolves without
the registry."""
provider = get_object_storage_provider(StorageType.AZURE)
@@ -347,23 +259,34 @@ class TestGetObjectStorageProvider:
with pytest.raises(ValueError, match="'bogus' is not a valid
StorageType"):
get_object_storage_provider("bogus")
+ @pytest.mark.parametrize(
+ ("storage_type", "provider_class_name"),
+ [
+ (
+ StorageType.S3,
+
"airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
+ ),
+ (
+ StorageType.GCS,
+
"airflow.providers.google.cloud.datafusion.object_storage.GCSObjectStorageProvider",
+ ),
+ ],
+ )
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.import_string",
autospec=True)
@patch("airflow.providers_manager.ProvidersManager", autospec=True)
- def test_resolves_s3_via_registry(self, mock_pm_cls, mock_import_string):
+ def test_resolves_provider_owned_storage_via_registry(
+ self, mock_pm_cls, mock_import_string, storage_type,
provider_class_name
+ ):
mock_provider_cls = MagicMock()
mock_import_string.return_value = mock_provider_cls
mock_pm_cls.return_value.object_storage_providers = {
- "s3": MagicMock(
-
provider_class_name="airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
- ),
+ storage_type.value:
MagicMock(provider_class_name=provider_class_name),
}
- provider = get_object_storage_provider(StorageType.S3)
+ provider = get_object_storage_provider(storage_type)
- mock_import_string.assert_called_once_with(
-
"airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider"
- )
+ mock_import_string.assert_called_once_with(provider_class_name)
assert provider == mock_provider_cls.return_value
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.import_string",
autospec=True)
@@ -389,12 +312,19 @@ class TestGetObjectStorageProvider:
with pytest.raises(ValueError, match="No ObjectStorageProvider
registered.*Install or upgrade"):
get_object_storage_provider(StorageType.S3)
- def test_error_message_includes_install_hint_for_s3(self):
+ @pytest.mark.parametrize(
+ ("storage_type", "hint"),
+ [
+ (StorageType.S3, r"apache-airflow-providers-amazon\[datafusion\]"),
+ (StorageType.GCS,
r"apache-airflow-providers-google\[datafusion\]"),
+ ],
+ )
+ def test_error_message_includes_install_hint(self, storage_type, hint):
with patch("airflow.providers_manager.ProvidersManager",
autospec=True) as mock_pm_cls:
mock_pm_cls.return_value.object_storage_providers = {}
- with pytest.raises(ValueError,
match="apache-airflow-providers-amazon"):
- get_object_storage_provider(StorageType.S3)
+ with pytest.raises(ValueError, match=hint):
+ get_object_storage_provider(storage_type)
def test_legacy_core_resolves_s3_via_amazon_direct_import(self):
"""On an older core without the registry property, S3 resolves via a
direct amazon import."""
@@ -420,7 +350,31 @@ class TestGetObjectStorageProvider:
with pytest.raises(ValueError,
match="apache-airflow-providers-amazon"):
get_object_storage_provider(StorageType.S3)
- def test_no_amazon_imports_at_module_level(self):
+ def test_legacy_core_resolves_gcs_via_google_direct_import(self):
+ """On an older core without the registry property, GCS resolves via a
direct google import."""
+ pytest.importorskip("airflow.providers.google")
+ from airflow.providers.google.cloud.datafusion.object_storage import
GCSObjectStorageProvider
+
+ with patch("airflow.providers_manager.ProvidersManager") as
mock_pm_cls:
+ mock_pm_cls.return_value = MagicMock(spec=[])
+
+ provider = get_object_storage_provider(StorageType.GCS)
+
+ assert isinstance(provider, GCSObjectStorageProvider)
+
+ def test_legacy_core_gcs_without_google_raises_install_hint(self):
+ """On an older core without the registry and google missing, raise the
hinted ValueError."""
+ with patch("airflow.providers_manager.ProvidersManager") as
mock_pm_cls:
+ mock_pm_cls.return_value = MagicMock(spec=[])
+
+ with patch.dict(
+ sys.modules,
+ {"airflow.providers.google.cloud.datafusion.object_storage":
None},
+ ):
+ with pytest.raises(ValueError,
match="apache-airflow-providers-google"):
+ get_object_storage_provider(StorageType.GCS)
+
+ def test_no_provider_imports_at_module_level(self):
"""Verify common-sql no longer statically imports amazon provider code
at the top level."""
import airflow.providers.common.sql.datafusion.object_storage_provider
as mod
@@ -429,9 +383,9 @@ class TestGetObjectStorageProvider:
for name, obj in vars(mod).items()
if not name.startswith("_")
and hasattr(obj, "__module__")
- and "amazon" in getattr(obj, "__module__", "")
+ and any(p in getattr(obj, "__module__", "") for p in ("amazon",
"google"))
]
- assert top_level_names == [], f"Amazon symbols found at module level:
{top_level_names}"
+ assert top_level_names == [], f"Provider symbols found at module
level: {top_level_names}"
class TestS3DeprecationShim:
@@ -497,3 +451,44 @@ class TestS3DeprecationShim:
with pytest.raises(AttributeError, match="has no attribute"):
_ = mod.NonExistentClass
+
+
+class TestGCSDeprecationShim:
+ def test_old_import_path_warns_and_returns_same_class(self):
+ """Importing GCSObjectStorageProvider from the old path still works,
warns, and re-exports the class."""
+ pytest.importorskip("airflow.providers.google")
+ import airflow.providers.common.sql.datafusion.object_storage_provider
as mod
+
+ with pytest.warns(
+ AirflowProviderDeprecationWarning,
+ match="Import it from
airflow.providers.google.cloud.datafusion.object_storage",
+ ):
+ old_cls = mod.GCSObjectStorageProvider
+
+ from airflow.providers.google.cloud.datafusion.object_storage import
GCSObjectStorageProvider
+
+ assert old_cls is GCSObjectStorageProvider
+
+ def test_old_import_path_honours_explicit_credentials(self, tmp_path):
+ """The shim preserves the pre-relocation contract: explicit
credentials reach GoogleCloud."""
+ pytest.importorskip("airflow.providers.google")
+ import airflow.providers.common.sql.datafusion.object_storage_provider
as mod
+
+ with pytest.warns(
+ AirflowProviderDeprecationWarning,
+ match="Import it from
airflow.providers.google.cloud.datafusion.object_storage",
+ ):
+ cls = mod.GCSObjectStorageProvider
+
+ key_path = tmp_path / "key.json"
+ key_path.write_text("{}")
+ config = ConnectionConfig(conn_id="google_cloud_default",
credentials={"key_path": str(key_path)})
+ # Patched inline rather than via decorator: the target module only
exists when google is
+ # installed, and a decorator would resolve it before importorskip can
skip the test.
+ with patch(
+
"airflow.providers.google.cloud.datafusion.object_storage.GoogleCloud",
autospec=True
+ ) as mock_gcs:
+ store = cls().create_object_store("gs://demo-data/path",
connection_config=config)
+
+ mock_gcs.assert_called_once_with(bucket_name="demo-data",
service_account_path=str(key_path))
+ assert store == mock_gcs.return_value
diff --git a/providers/google/docs/index.rst b/providers/google/docs/index.rst
index 8a020d2dc7b..2faede7bfbb 100644
--- a/providers/google/docs/index.rst
+++ b/providers/google/docs/index.rst
@@ -246,9 +246,9 @@ Install them when installing from PyPI. For example:
pip install apache-airflow-providers-google[apache.beam]
-==================== =====================================================
+====================
===============================================================================
Extra Dependencies
-==================== =====================================================
+====================
===============================================================================
``apache.beam`` ``apache-airflow-providers-apache-beam>=6.2.2``
``cncf.kubernetes`` ``apache-airflow-providers-cncf-kubernetes>=10.25.0``
``fab`` ``apache-airflow-providers-fab>=2.0.0``
@@ -272,7 +272,8 @@ Extra Dependencies
``standard`` ``apache-airflow-providers-standard``
``common.ai`` ``apache-airflow-providers-common-ai>=0.11.0``
``common.messaging`` ``apache-airflow-providers-common-messaging>=2.0.0``
-==================== =====================================================
+``datafusion`` ``datafusion>=50.0.0,<52.0.0``,
``apache-airflow-providers-common-sql>=1.33.0``
+====================
===============================================================================
Downloading official packages
-----------------------------
diff --git a/providers/google/provider.yaml b/providers/google/provider.yaml
index b3bcd309199..ec1a4daf3c9 100644
--- a/providers/google/provider.yaml
+++ b/providers/google/provider.yaml
@@ -724,6 +724,10 @@ sensors:
filesystems:
- airflow.providers.google.cloud.fs.gcs
+object-storage-providers:
+ - storage-type: gcs
+ provider-class-name:
airflow.providers.google.cloud.datafusion.object_storage.GCSObjectStorageProvider
+
asset-uris:
- schemes: [gcp]
handler: null
diff --git a/providers/google/pyproject.toml b/providers/google/pyproject.toml
index 8e806fb2af0..be736f4b495 100644
--- a/providers/google/pyproject.toml
+++ b/providers/google/pyproject.toml
@@ -234,6 +234,10 @@ dependencies = [
"common.messaging" = [
"apache-airflow-providers-common-messaging>=2.0.0"
]
+"datafusion" = [
+ "datafusion>=50.0.0,<52.0.0",
+ "apache-airflow-providers-common-sql>=1.33.0",
+]
[dependency-groups]
dev = [
@@ -266,6 +270,7 @@ dev = [
# Additional devel dependencies (do not remove this line and add extra
development dependencies)
"apache-airflow-providers-apache-kafka",
"apache-airflow-providers-common-sql[pandas,polars]",
+ "apache-airflow-providers-google[datafusion]",
]
# To build docs:
diff --git
a/providers/google/src/airflow/providers/google/cloud/datafusion/__init__.py
b/providers/google/src/airflow/providers/google/cloud/datafusion/__init__.py
new file mode 100644
index 00000000000..21d298ede6e
--- /dev/null
+++ b/providers/google/src/airflow/providers/google/cloud/datafusion/__init__.py
@@ -0,0 +1,17 @@
+# 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
diff --git
a/providers/google/src/airflow/providers/google/cloud/datafusion/object_storage.py
b/providers/google/src/airflow/providers/google/cloud/datafusion/object_storage.py
new file mode 100644
index 00000000000..d77a76e92f5
--- /dev/null
+++
b/providers/google/src/airflow/providers/google/cloud/datafusion/object_storage.py
@@ -0,0 +1,127 @@
+# 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
+import os
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from datafusion.object_store import GoogleCloud
+
+from airflow.providers.common.compat.sdk import BaseHook
+from airflow.providers.common.sql.config import ConnectionConfig, StorageType
+from airflow.providers.common.sql.datafusion.base import ObjectStorageProvider
+from airflow.providers.common.sql.datafusion.exceptions import
ObjectStoreCreationException
+from airflow.providers.google.common.hooks.base_google import get_field
+
+_UNSUPPORTED_CONNECTION_FIELDS = ("key_secret_name", "credential_config_file",
"impersonation_chain")
+
+
+class GCSObjectStorageProvider(ObjectStorageProvider):
+ """
+ GCS Object Storage Provider using DataFusion's GoogleCloud.
+
+ ``ObjectStoragePath`` reaches ``gs://`` through
:mod:`airflow.providers.google.cloud.fs.gcs`
+ instead, which hands ``GoogleBaseHook.get_credentials()`` to gcsfs.
DataFusion's ``GoogleCloud``
+ only accepts a service account key file, so this class supports
``key_path``, ``keyfile_dict``,
+ ``GOOGLE_APPLICATION_CREDENTIALS`` and ambient credentials, and rejects
the hook's other
+ credential sources (``key_secret_name``, ``credential_config_file``,
``impersonation_chain``).
+ Keep the two in mind together when changing how a
``google_cloud_platform`` connection is read.
+ """
+
+ @property
+ def get_storage_type(self) -> StorageType:
+ """Return the storage type."""
+ return StorageType.GCS
+
+ def _credentials_from_connection(self, conn_id: str) -> dict[str, Any]:
+ """Derive GCS credentials from an Airflow connection; only
``google_cloud_platform`` connections are supported."""
+ conn = BaseHook.get_connection(conn_id)
+ if conn.conn_type != "google_cloud_platform":
+ raise ValueError(f"Unknown connection type {conn.conn_type}")
+
+ extra_dejson = conn.extra_dejson
+ for unsupported_field in _UNSUPPORTED_CONNECTION_FIELDS:
+ if get_field(extra_dejson, unsupported_field):
+ raise ValueError(
+ f"Connection field {unsupported_field!r} is not supported
for DataFusion "
+ "GCS access; only key_path, keyfile_dict,
GOOGLE_APPLICATION_CREDENTIALS, or "
+ "ambient credentials (gcloud ADC file / metadata server)
are used."
+ )
+ key_path = get_field(extra_dejson, "key_path") or None
+ keyfile_dict = get_field(extra_dejson, "keyfile_dict") or None
+ if key_path and keyfile_dict:
+ raise ValueError(
+ "The `keyfile_dict` and `key_path` fields are mutually
exclusive. "
+ "Please provide only one value."
+ )
+ if not key_path and not keyfile_dict:
+ key_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
+ credentials = {"key_path": key_path, "keyfile_dict": keyfile_dict}
+ return {k: v for k, v in credentials.items() if v is not None}
+
+ def create_object_store(self, path: str, connection_config:
ConnectionConfig | None = None):
+ """
+ Create a GCS object store using DataFusion's GoogleCloud.
+
+ Credentials supplied on ``connection_config`` take precedence. Only
when
+ ``connection_config.credentials`` is empty are they resolved from the
+ ``google_cloud_platform`` Airflow connection named by ``conn_id``.
+ """
+ if connection_config is None:
+ raise ValueError(f"connection_config must be provided for
{self.get_storage_type.value}")
+
+ credentials = connection_config.credentials
+ if not credentials:
+ credentials =
self._credentials_from_connection(connection_config.conn_id)
+
+ key_path = credentials.get("key_path")
+ keyfile_dict = credentials.get("keyfile_dict")
+ temp_key_path: str | None = None
+
+ try:
+ bucket = self.get_bucket(path)
+
+ if not key_path and keyfile_dict:
+ # GoogleCloud only accepts a file path, not inline JSON; safe
to delete once
+ # constructed since the credentials are read only at
construction time.
+ key_content = keyfile_dict if isinstance(keyfile_dict, str)
else json.dumps(keyfile_dict)
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".json",
delete=False) as key_file:
+ key_file.write(key_content)
+ temp_key_path = key_path = key_file.name
+
+ if key_path is not None and not Path(key_path).is_file():
+ raise FileNotFoundError(f"Service account key file not found:
{key_path}")
+
+ gcs_store = GoogleCloud(bucket_name=bucket,
service_account_path=key_path)
+ self.log.info("Created GCS object store for bucket %s", bucket)
+
+ return gcs_store
+
+ except BaseException as e:
+ # A bad key file panics as pyo3_runtime.PanicException, not a
plain Exception.
+ raise ObjectStoreCreationException(f"Failed to create GCS object
store: {e}")
+
+ finally:
+ if temp_key_path is not None:
+ Path(temp_key_path).unlink(missing_ok=True)
+
+ def get_scheme(self) -> str:
+ """Return the scheme for GCS."""
+ return "gs://"
diff --git a/providers/google/src/airflow/providers/google/get_provider_info.py
b/providers/google/src/airflow/providers/google/get_provider_info.py
index 6b61ccf7adf..f6b0e1cb112 100644
--- a/providers/google/src/airflow/providers/google/get_provider_info.py
+++ b/providers/google/src/airflow/providers/google/get_provider_info.py
@@ -805,6 +805,12 @@ def get_provider_info():
},
],
"filesystems": ["airflow.providers.google.cloud.fs.gcs"],
+ "object-storage-providers": [
+ {
+ "storage-type": "gcs",
+ "provider-class-name":
"airflow.providers.google.cloud.datafusion.object_storage.GCSObjectStorageProvider",
+ }
+ ],
"asset-uris": [
{"schemes": ["gcp"], "handler": None},
{
diff --git a/providers/google/tests/unit/google/cloud/datafusion/__init__.py
b/providers/google/tests/unit/google/cloud/datafusion/__init__.py
new file mode 100644
index 00000000000..21d298ede6e
--- /dev/null
+++ b/providers/google/tests/unit/google/cloud/datafusion/__init__.py
@@ -0,0 +1,17 @@
+# 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
diff --git
a/providers/google/tests/unit/google/cloud/datafusion/test_object_storage.py
b/providers/google/tests/unit/google/cloud/datafusion/test_object_storage.py
new file mode 100644
index 00000000000..67fd01fbadc
--- /dev/null
+++ b/providers/google/tests/unit/google/cloud/datafusion/test_object_storage.py
@@ -0,0 +1,196 @@
+# 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
+import os
+from unittest import mock
+
+import pytest
+
+from airflow.models import Connection
+from airflow.providers.common.sql.config import ConnectionConfig, StorageType
+from airflow.providers.common.sql.datafusion.exceptions import
ObjectStoreCreationException
+from airflow.providers.google.cloud.datafusion.object_storage import
GCSObjectStorageProvider
+
+MODULE = "airflow.providers.google.cloud.datafusion.object_storage"
+GCS_PATH = "gs://demo-data/path"
+
+
+def _gcp_connection(extra: dict | None = None, conn_type: str =
"google_cloud_platform") -> Connection:
+ return Connection(conn_id="google_cloud_default", conn_type=conn_type,
extra=json.dumps(extra or {}))
+
+
+class TestGCSObjectStorageProvider:
+ def test_storage_type_and_scheme(self):
+ provider = GCSObjectStorageProvider()
+
+ assert provider.get_storage_type == StorageType.GCS
+ assert provider.get_scheme() == "gs://"
+ assert provider.get_bucket(GCS_PATH) == "demo-data"
+
+ @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True)
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True)
+ def test_explicit_key_path_skips_connection_lookup(self, mock_gcs,
mock_get_connection, tmp_path):
+ key_path = tmp_path / "key.json"
+ key_path.write_text("{}")
+ config = ConnectionConfig(conn_id="google_cloud_default",
credentials={"key_path": str(key_path)})
+
+ store = GCSObjectStorageProvider().create_object_store(GCS_PATH,
config)
+
+ mock_get_connection.assert_not_called()
+ mock_gcs.assert_called_once_with(bucket_name="demo-data",
service_account_path=str(key_path))
+ assert store == mock_gcs.return_value
+
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True)
+ def test_keyfile_dict_written_to_temp_file_and_removed(self, mock_gcs):
+ keyfile_dict = {"type": "service_account", "private_key": "fake"}
+ written = {}
+
+ def _capture(*, bucket_name, service_account_path):
+ with open(service_account_path) as f:
+ written["data"] = json.load(f)
+
+ mock_gcs.side_effect = _capture
+ config = ConnectionConfig(conn_id="google_cloud_default",
credentials={"keyfile_dict": keyfile_dict})
+
+ GCSObjectStorageProvider().create_object_store(GCS_PATH, config)
+
+ assert written["data"] == keyfile_dict
+ assert not
os.path.exists(mock_gcs.call_args.kwargs["service_account_path"])
+
+ @pytest.mark.parametrize(
+ ("extra", "env", "expected_kwargs"),
+ [
+ pytest.param({"key_path": "KEY"}, None, {"service_account_path":
"KEY"}, id="key_path"),
+ pytest.param(
+ {"extra__google_cloud_platform__key_path": "KEY"},
+ None,
+ {"service_account_path": "KEY"},
+ id="legacy_prefixed_key_path",
+ ),
+ pytest.param({}, "KEY", {"service_account_path": "KEY"},
id="google_application_credentials"),
+ pytest.param(
+ {"key_path": "KEY"}, "/env/other.json",
{"service_account_path": "KEY"}, id="conn_over_env"
+ ),
+ pytest.param({}, None, {"service_account_path": None},
id="ambient"),
+ ],
+ )
+ @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True)
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True)
+ def test_credentials_resolved_from_connection(
+ self, mock_gcs, mock_get_connection, extra, env, expected_kwargs,
tmp_path, monkeypatch
+ ):
+ key_path = tmp_path / "key.json"
+ key_path.write_text("{}")
+ extra = {k: str(key_path) if v == "KEY" else v for k, v in
extra.items()}
+ if env is None:
+ monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
+ else:
+ monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", str(key_path)
if env == "KEY" else env)
+ mock_get_connection.return_value = _gcp_connection(extra)
+
+ GCSObjectStorageProvider().create_object_store(
+ GCS_PATH, ConnectionConfig(conn_id="google_cloud_default")
+ )
+
+ mock_get_connection.assert_called_once_with("google_cloud_default")
+ expected = {k: str(key_path) if v == "KEY" else v for k, v in
expected_kwargs.items()}
+ mock_gcs.assert_called_once_with(bucket_name="demo-data", **expected)
+
+ @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True)
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True)
+ def test_keyfile_dict_resolved_from_connection(self, mock_gcs,
mock_get_connection, monkeypatch):
+ monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
+ keyfile = '{"type": "service_account"}'
+ mock_get_connection.return_value = _gcp_connection({"keyfile_dict":
keyfile})
+ written = {}
+
+ def _capture(*, bucket_name, service_account_path):
+ with open(service_account_path) as f:
+ written["data"] = f.read()
+
+ mock_gcs.side_effect = _capture
+
+ GCSObjectStorageProvider().create_object_store(
+ GCS_PATH, ConnectionConfig(conn_id="google_cloud_default")
+ )
+
+ assert written["data"] == keyfile
+
+ @pytest.mark.parametrize(
+ ("extra", "match"),
+ [
+ pytest.param({"key_path": "/a.json", "keyfile_dict": "{}"},
"mutually exclusive", id="both_keys"),
+ pytest.param({"key_secret_name": "x"}, "'key_secret_name' is not
supported", id="secret"),
+ pytest.param(
+ {"credential_config_file": "x"}, "'credential_config_file' is
not supported", id="cfg_file"
+ ),
+ pytest.param(
+ {"impersonation_chain": "x"}, "'impersonation_chain' is not
supported", id="impersonation"
+ ),
+ pytest.param(
+ {"extra__google_cloud_platform__impersonation_chain": "x"},
+ "'impersonation_chain' is not supported",
+ id="legacy_prefixed_impersonation",
+ ),
+ ],
+ )
+ @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True)
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True)
+ def test_invalid_connection_fields_raise_value_error(self, mock_gcs,
mock_get_connection, extra, match):
+ mock_get_connection.return_value = _gcp_connection(extra)
+
+ with pytest.raises(ValueError, match=match):
+ GCSObjectStorageProvider().create_object_store(
+ GCS_PATH, ConnectionConfig(conn_id="google_cloud_default")
+ )
+
+ mock_gcs.assert_not_called()
+
+ @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True)
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True)
+ def test_non_gcp_connection_raises_unknown_connection_type(self, mock_gcs,
mock_get_connection):
+ mock_get_connection.return_value = _gcp_connection(conn_type="aws")
+
+ with pytest.raises(ValueError, match="Unknown connection type aws"):
+ GCSObjectStorageProvider().create_object_store(
+ GCS_PATH, ConnectionConfig(conn_id="google_cloud_default")
+ )
+
+ mock_gcs.assert_not_called()
+
+ def test_requires_connection_config(self):
+ with pytest.raises(ValueError, match="connection_config must be
provided for gcs"):
+ GCSObjectStorageProvider().create_object_store(GCS_PATH)
+
+ @mock.patch(f"{MODULE}.GoogleCloud", autospec=True,
side_effect=Exception("Error"))
+ def
test_store_constructor_failure_raises_object_store_creation_exception(self,
mock_gcs, tmp_path):
+ key_path = tmp_path / "key.json"
+ key_path.write_text("{}")
+ config = ConnectionConfig(conn_id="google_cloud_default",
credentials={"key_path": str(key_path)})
+
+ with pytest.raises(ObjectStoreCreationException, match="Failed to
create GCS object store"):
+ GCSObjectStorageProvider().create_object_store(GCS_PATH, config)
+
+ def test_missing_key_file_raises_object_store_creation_exception(self):
+ config = ConnectionConfig(
+ conn_id="google_cloud_default", credentials={"key_path":
"/nonexistent/key.json"}
+ )
+
+ with pytest.raises(ObjectStoreCreationException, match="Failed to
create GCS object store"):
+ GCSObjectStorageProvider().create_object_store(GCS_PATH, config)
diff --git a/uv.lock b/uv.lock
index 46b6d1004ec..1655367b65d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5309,6 +5309,9 @@ apache-iceberg = [
datafusion = [
{ name = "datafusion" },
]
+google = [
+ { name = "apache-airflow-providers-google" },
+]
openlineage = [
{ name = "apache-airflow-providers-openlineage" },
]
@@ -5335,6 +5338,7 @@ dev = [
{ name = "apache-airflow-providers-apache-iceberg" },
{ name = "apache-airflow-providers-common-compat" },
{ name = "apache-airflow-providers-common-sql", extra = ["pandas",
"polars", "sqlalchemy"] },
+ { name = "apache-airflow-providers-google" },
{ name = "apache-airflow-providers-mysql" },
{ name = "apache-airflow-providers-odbc" },
{ name = "apache-airflow-providers-openlineage" },
@@ -5354,6 +5358,7 @@ requires-dist = [
{ name = "apache-airflow-providers-amazon", marker = "extra == 'amazon'",
editable = "providers/amazon" },
{ name = "apache-airflow-providers-apache-iceberg", marker = "extra ==
'apache-iceberg'", editable = "providers/apache/iceberg" },
{ name = "apache-airflow-providers-common-compat", editable =
"providers/common/compat" },
+ { name = "apache-airflow-providers-google", marker = "extra == 'google'",
editable = "providers/google" },
{ name = "apache-airflow-providers-openlineage", marker = "extra ==
'openlineage'", editable = "providers/openlineage" },
{ name = "datafusion", marker = "extra == 'datafusion'", specifier =
">=50.0.0,<52.0.0" },
{ name = "methodtools", specifier = ">=0.4.7" },
@@ -5366,7 +5371,7 @@ requires-dist = [
{ name = "sqlalchemy", marker = "extra == 'sqlalchemy'", specifier =
">=1.4.54,!=2.1.0" },
{ name = "sqlparse", specifier = ">=0.5.1" },
]
-provides-extras = ["pandas", "openlineage", "polars", "sqlalchemy",
"datafusion", "pyiceberg-core", "apache-iceberg", "amazon"]
+provides-extras = ["pandas", "openlineage", "polars", "sqlalchemy",
"datafusion", "pyiceberg-core", "apache-iceberg", "amazon", "google"]
[package.metadata.requires-dev]
dev = [
@@ -5378,6 +5383,7 @@ dev = [
{ name = "apache-airflow-providers-common-sql", extras = ["pandas"],
editable = "providers/common/sql" },
{ name = "apache-airflow-providers-common-sql", extras = ["polars"],
editable = "providers/common/sql" },
{ name = "apache-airflow-providers-common-sql", extras = ["sqlalchemy"],
editable = "providers/common/sql" },
+ { name = "apache-airflow-providers-google", editable = "providers/google"
},
{ name = "apache-airflow-providers-mysql", editable = "providers/mysql" },
{ name = "apache-airflow-providers-odbc", editable = "providers/odbc" },
{ name = "apache-airflow-providers-openlineage", editable =
"providers/openlineage" },
@@ -6257,6 +6263,10 @@ common-ai = [
common-messaging = [
{ name = "apache-airflow-providers-common-messaging" },
]
+datafusion = [
+ { name = "apache-airflow-providers-common-sql" },
+ { name = "datafusion" },
+]
fab = [
{ name = "apache-airflow-providers-fab" },
]
@@ -6323,6 +6333,7 @@ dev = [
{ name = "apache-airflow-providers-common-messaging" },
{ name = "apache-airflow-providers-common-sql", extra = ["pandas",
"polars"] },
{ name = "apache-airflow-providers-facebook" },
+ { name = "apache-airflow-providers-google", extra = ["datafusion"] },
{ name = "apache-airflow-providers-http" },
{ name = "apache-airflow-providers-microsoft-azure" },
{ name = "apache-airflow-providers-microsoft-mssql" },
@@ -6354,6 +6365,7 @@ requires-dist = [
{ 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-common-sql", editable =
"providers/common/sql" },
+ { name = "apache-airflow-providers-common-sql", marker = "extra ==
'datafusion'", editable = "providers/common/sql" },
{ name = "apache-airflow-providers-fab", marker = "extra == 'fab'",
editable = "providers/fab" },
{ name = "apache-airflow-providers-facebook", marker = "extra ==
'facebook'", editable = "providers/facebook" },
{ name = "apache-airflow-providers-http", marker = "extra == 'http'",
editable = "providers/http" },
@@ -6372,6 +6384,7 @@ requires-dist = [
{ name = "apache-airflow-providers-trino", marker = "extra == 'trino'",
editable = "providers/trino" },
{ name = "asgiref", marker = "python_full_version < '3.14'", specifier =
">=3.5.2" },
{ name = "asgiref", marker = "python_full_version >= '3.14'", specifier =
">=3.11.1" },
+ { name = "datafusion", marker = "extra == 'datafusion'", specifier =
">=50.0.0,<52.0.0" },
{ name = "dill", specifier = ">=0.2.3" },
{ name = "gcloud-aio-auth", specifier = ">=5.2.0" },
{ name = "gcloud-aio-bigquery", specifier = ">=6.1.2" },
@@ -6450,7 +6463,7 @@ requires-dist = [
{ name = "tenacity", specifier = ">=8.3.0" },
{ name = "tqdm", specifier = ">=4.67.1" },
]
-provides-extras = ["apache-beam", "cncf-kubernetes", "fab", "leveldb",
"oracle", "facebook", "amazon", "apache-cassandra", "microsoft-azure",
"microsoft-mssql", "mongo", "mysql", "openlineage", "postgres", "presto",
"salesforce", "sftp", "ssh", "trino", "http", "standard", "common-ai",
"common-messaging"]
+provides-extras = ["apache-beam", "cncf-kubernetes", "fab", "leveldb",
"oracle", "facebook", "amazon", "apache-cassandra", "microsoft-azure",
"microsoft-mssql", "mongo", "mysql", "openlineage", "postgres", "presto",
"salesforce", "sftp", "ssh", "trino", "http", "standard", "common-ai",
"common-messaging", "datafusion"]
[package.metadata.requires-dev]
dev = [
@@ -6467,6 +6480,7 @@ dev = [
{ name = "apache-airflow-providers-common-sql", editable =
"providers/common/sql" },
{ name = "apache-airflow-providers-common-sql", extras = ["pandas",
"polars"], editable = "providers/common/sql" },
{ name = "apache-airflow-providers-facebook", editable =
"providers/facebook" },
+ { name = "apache-airflow-providers-google", extras = ["datafusion"],
editable = "providers/google" },
{ name = "apache-airflow-providers-http", editable = "providers/http" },
{ name = "apache-airflow-providers-microsoft-azure", editable =
"providers/microsoft/azure" },
{ name = "apache-airflow-providers-microsoft-mssql", editable =
"providers/microsoft/mssql" },