diff --git a/providers/common/ai/docs/toolsets/datafusion.rst b/providers/common/ai/docs/toolsets/datafusion.rst index 854913d8a94e..612ac5129c6a 100644 --- a/providers/common/ai/docs/toolsets/datafusion.rst +++ b/providers/common/ai/docs/toolsets/datafusion.rst @@ -37,7 +37,7 @@ querying files on object stores (S3, GCS, Azure Blob Storage, local filesystem, * - ``list_tables`` - Lists registered table names * - ``get_schema`` - - Returns a table's columns (Arrow schema) as JSON, with a ``name_contains`` + - Returns a table's columns as JSON, with a ``name_contains`` filter and a bounded summary on very wide tables (see :ref:`bounded-schema-results`) * - ``query`` diff --git a/providers/common/ai/pyproject.toml b/providers/common/ai/pyproject.toml index f7eed5450e21..ae0c3102155c 100644 --- a/providers/common/ai/pyproject.toml +++ b/providers/common/ai/pyproject.toml @@ -157,11 +157,11 @@ dependencies = [ "pyarrow>=22.0.0; python_version >= '3.14'", ] "sql" = [ - "apache-airflow-providers-common-sql>=3.1.0", + "apache-airflow-providers-common-sql>=3.1.0", # use next version "sqlglot>=30.0.0", ] "common.sql" = [ - "apache-airflow-providers-common-sql>=3.1.0" + "apache-airflow-providers-common-sql>=3.1.0" # use next version ] "langchain" = [ "langchain>=1.0.0", diff --git a/providers/common/ai/src/airflow/providers/common/ai/operators/llm_schema_compare.py b/providers/common/ai/src/airflow/providers/common/ai/operators/llm_schema_compare.py index 2d14f163121f..1c8ce1f65735 100644 --- a/providers/common/ai/src/airflow/providers/common/ai/operators/llm_schema_compare.py +++ b/providers/common/ai/src/airflow/providers/common/ai/operators/llm_schema_compare.py @@ -28,6 +28,7 @@ from airflow.providers.common.ai.operators.llm import LLMOperator from airflow.providers.common.ai.utils.prompt import describe_prompt +from airflow.providers.common.ai.utils.schema_context import format_columns_for_prompt from airflow.providers.common.ai.utils.usage import coerce_usage_limits from airflow.providers.common.compat.sdk import AirflowException, BaseHook @@ -214,7 +215,7 @@ def _introspect_db_schema(self, hook: DbApiHook, table_name: str) -> str: self.log.warning("Table %r returned no columns — it may not exist.", table_name) return "" - col_info = ", ".join(f"{c['name']} {c['type']}" for c in columns) + col_info = format_columns_for_prompt(columns) parts = [f"Columns: {col_info}"] if self.context_strategy == "full": @@ -285,11 +286,17 @@ def _df_engine(self): engine = DataFusionEngine() return engine - def _introspect_schema_from_datafusion(self, ds_config: DataSourceConfig): + def _introspect_schema_from_datafusion(self, ds_config: DataSourceConfig) -> str: self._df_engine.register_datasource(ds_config) - schema_text = self._df_engine.get_schema(ds_config.table_name) - - return f"Source: {ds_config.conn_id} \nFormat: ({ds_config.format})\nTable: {ds_config.table_name}\nColumns: {schema_text}" + columns = self._df_engine.get_table_schema(ds_config.table_name) + col_info = format_columns_for_prompt(columns) + + return ( + f"Source: {ds_config.conn_id} \n" + f"Format: ({ds_config.format})\n" + f"Table: {ds_config.table_name}\n" + f"Columns: {col_info}" + ) def _build_schema_context(self) -> str: """Collect schemas from all configured sources each clearly.""" diff --git a/providers/common/ai/src/airflow/providers/common/ai/operators/llm_sql.py b/providers/common/ai/src/airflow/providers/common/ai/operators/llm_sql.py index 8d157e02520d..c5ad52f193b1 100644 --- a/providers/common/ai/src/airflow/providers/common/ai/operators/llm_sql.py +++ b/providers/common/ai/src/airflow/providers/common/ai/operators/llm_sql.py @@ -34,6 +34,7 @@ raise AirflowOptionalProviderFeatureException(e) from airflow.providers.common.ai.operators.llm import LLMOperator +from airflow.providers.common.ai.utils.schema_context import format_columns_for_prompt from airflow.providers.common.ai.utils.usage import coerce_usage_limits from airflow.providers.common.compat.sdk import BaseHook @@ -236,7 +237,7 @@ def _introspect_schemas(self) -> str: if not columns: self.log.warning("Table %r returned no columns — it may not exist.", table) continue - col_info = ", ".join(f"{c['name']} {c['type']}" for c in columns) + col_info = format_columns_for_prompt(columns) parts.append(f"Table: {table}\nColumns: {col_info}") if not parts and self.table_names: raise ValueError( @@ -245,12 +246,13 @@ def _introspect_schemas(self) -> str: ) if self.datasource_config: - object_storage_schema = self._introspect_object_storage_schema() - parts.append(f"Table: {self.datasource_config.table_name}\nColumns: {object_storage_schema}") + object_storage_schema = self._introspect_object_storage_schema(self.datasource_config) + col_info = format_columns_for_prompt(object_storage_schema) + parts.append(f"Table: {self.datasource_config.table_name}\nColumns: {col_info}") return "\n\n".join(parts) - def _introspect_object_storage_schema(self): + def _introspect_object_storage_schema(self, ds_config: DataSourceConfig) -> list[dict[str, str]]: """Use DataFusion Engine to get the schema of object stores.""" try: from airflow.providers.common.sql.datafusion.engine import DataFusionEngine @@ -264,8 +266,8 @@ def _introspect_object_storage_schema(self): ) from e engine = DataFusionEngine() - engine.register_datasource(self.datasource_config) - return engine.get_schema(self.datasource_config.table_name) + engine.register_datasource(ds_config) + return engine.get_table_schema(ds_config.table_name) def _build_system_prompt(self, schema_info: str) -> str: """Construct the system prompt for the LLM.""" diff --git a/providers/common/ai/src/airflow/providers/common/ai/toolsets/datafusion.py b/providers/common/ai/src/airflow/providers/common/ai/toolsets/datafusion.py index b8fa3a2cf77c..7d113a9f2768 100644 --- a/providers/common/ai/src/airflow/providers/common/ai/toolsets/datafusion.py +++ b/providers/common/ai/src/airflow/providers/common/ai/toolsets/datafusion.py @@ -247,12 +247,7 @@ def _get_schema(self, table_name: str, name_contains: str | None = None) -> str: # that would not be captured there. if not engine.session_context.table_exist(table_name): return dumps_masked({"error": f"Table {table_name!r} is not available"}) - # Intentionally using session_context instead of engine.get_schema() — - # the latter returns a pre-formatted string intended for other operators, - # not a JSON-compatible format. - # TODO: refactor engine.get_schema() to return JSON and update this accordingly - table = engine.session_context.table(table_name) - columns = [{"name": f.name, "type": str(f.type)} for f in table.schema()] + columns = engine.get_table_schema(table_name) return build_schema_result( columns, max_columns=self._max_columns, diff --git a/providers/common/ai/src/airflow/providers/common/ai/utils/schema_context.py b/providers/common/ai/src/airflow/providers/common/ai/utils/schema_context.py new file mode 100644 index 000000000000..eef6e36b3175 --- /dev/null +++ b/providers/common/ai/src/airflow/providers/common/ai/utils/schema_context.py @@ -0,0 +1,24 @@ +# 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. +"""Helpers for building schema context strings for LLM operators.""" + +from __future__ import annotations + + +def format_columns_for_prompt(columns: list[dict[str, str]]) -> str: + """Format the columns type from list[dict[str, str]] to str.""" + return ", ".join(f"{c['name']} {c['type']}" for c in columns) diff --git a/providers/common/ai/tests/unit/common/ai/operators/test_llm_schema_compare.py b/providers/common/ai/tests/unit/common/ai/operators/test_llm_schema_compare.py index 51be164cc140..3acc0f2e982b 100644 --- a/providers/common/ai/tests/unit/common/ai/operators/test_llm_schema_compare.py +++ b/providers/common/ai/tests/unit/common/ai/operators/test_llm_schema_compare.py @@ -603,7 +603,8 @@ def test_introspect_basic_strategy_omits_constraints(self, db_hook): def test_introspect_schema_from_datafusion_success(self): """When a DataFusion engine is available, it should register the datasource and return schema text.""" df_mock_engine = MagicMock(spec=DataFusionEngine) - df_mock_engine.get_schema.return_value = "id int, name varchar" + mock_schema = [{"name": "id", "type": "int"}, {"name": "name", "type": "varchar"}] + df_mock_engine.get_table_schema.return_value = mock_schema ds = DataSourceConfig( conn_id="s3_conn", table_name="test_table", uri="s3://bucket/key", format="parquet" @@ -616,7 +617,7 @@ def test_introspect_schema_from_datafusion_success(self): result = op._introspect_schema_from_datafusion(ds) df_mock_engine.register_datasource.assert_called_once_with(ds) - df_mock_engine.get_schema.assert_called_once_with("test_table") + df_mock_engine.get_table_schema.assert_called_once_with("test_table") assert "Source: s3_conn" in result assert "Format: (parquet)" in result diff --git a/providers/common/ai/tests/unit/common/ai/operators/test_llm_sql.py b/providers/common/ai/tests/unit/common/ai/operators/test_llm_sql.py index 8e56ceb6d5aa..e48dcda610f7 100644 --- a/providers/common/ai/tests/unit/common/ai/operators/test_llm_sql.py +++ b/providers/common/ai/tests/unit/common/ai/operators/test_llm_sql.py @@ -116,7 +116,7 @@ def test_object_storage_error_explains_how_to_install_datafusion(self): ) try: - operator._introspect_object_storage_schema() + operator._introspect_object_storage_schema(operator.datasource_config) except AirflowOptionalProviderFeatureException as error: expected = 'pip install "apache-airflow-providers-common-sql[datafusion]"' if expected not in str(error): @@ -554,8 +554,12 @@ def test_schema_context_overrides_introspection(self): def test_introspect_object_storage_schema(self, mock_engine_cls): """_introspect_object_storage_schema registers datasource and returns schema.""" mock_engine = mock_engine_cls.return_value - schema_text = "cust_id: int64\nname: string\namount: float64" - mock_engine.get_schema.return_value = schema_text + mock_schema = [ + {"name": "cust_id", "type": "int64"}, + {"name": "name", "type": "string"}, + {"name": "amount", "type": "float64"}, + ] + mock_engine.get_table_schema.return_value = mock_schema ds_config = DataSourceConfig( conn_id="aws_default", @@ -569,11 +573,11 @@ def test_introspect_object_storage_schema(self, mock_engine_cls): llm_conn_id="my_llm", datasource_config=ds_config, ) - result = op._introspect_object_storage_schema() + result = op._introspect_object_storage_schema(ds_config) mock_engine.register_datasource.assert_called_once_with(ds_config) - mock_engine.get_schema.assert_called_once_with("sales") - assert result == schema_text + mock_engine.get_table_schema.assert_called_once_with("sales") + assert result == mock_schema @patch( "airflow.providers.common.sql.datafusion.engine.DataFusionEngine", @@ -582,8 +586,8 @@ def test_introspect_object_storage_schema(self, mock_engine_cls): def test_introspect_schemas_with_db_and_datasource_config(self, mock_engine_cls): """_introspect_schemas includes both db table and object storage schema.""" mock_engine = mock_engine_cls.return_value - object_schema = "col_a: int64\ncol_b: string" - mock_engine.get_schema.return_value = object_schema + mock_schema = [{"name": "col_a", "type": "int64"}, {"name": "col_b", "type": "string"}] + mock_engine.get_table_schema.return_value = mock_schema ds_config = DataSourceConfig( conn_id="aws_default", @@ -611,7 +615,7 @@ def test_introspect_schemas_with_db_and_datasource_config(self, mock_engine_cls) assert "Table: local_table" in result assert "id INTEGER" in result assert "Table: remote_table" in result - assert object_schema in result + assert "col_a int64, col_b string" in result @patch( "airflow.providers.common.sql.datafusion.engine.DataFusionEngine", @@ -620,7 +624,8 @@ def test_introspect_schemas_with_db_and_datasource_config(self, mock_engine_cls) def test_introspect_schemas_datasource_config_without_db_tables(self, mock_engine_cls): """_introspect_schemas works when only datasource_config is provided (no db tables).""" mock_engine = mock_engine_cls.return_value - mock_engine.get_schema.return_value = "ts: TIMESTAMP\nvalue: DOUBLE" + mock_schema = [{"name": "ts", "type": "TIMESTAMP"}, {"name": "value", "type": "DOUBLE"}] + mock_engine.get_table_schema.return_value = mock_schema ds_config = DataSourceConfig( conn_id="aws_default", @@ -643,7 +648,7 @@ def test_introspect_schemas_datasource_config_without_db_tables(self, mock_engin result = op._introspect_schemas() assert "Table: s3_data" in result - assert "ts: TIMESTAMP\nvalue: DOUBLE" in result + assert "ts TIMESTAMP, value DOUBLE" in result def test_introspect_schemas_raises_when_no_tables_and_no_datasource(self): """ValueError is raised when no db tables return schema and no datasource_config is set.""" @@ -672,7 +677,8 @@ def test_execute_with_datasource_config_and_db_tables( ): """Full execute flow with both db tables and object storage datasource.""" mock_engine = mock_engine_cls.return_value - mock_engine.get_schema.return_value = "event: TEXT\nts: TIMESTAMP" + mock_schema = [{"name": "event", "type": "TEXT"}, {"name": "ts", "type": "TIMESTAMP"}] + mock_engine.get_table_schema.return_value = mock_schema mock_agent = _make_mock_agent( "SELECT u.id, e.event FROM users u JOIN events e ON u.id = e.user_id", make_mock_run_result @@ -708,7 +714,7 @@ def test_execute_with_datasource_config_and_db_tables( instructions = mock_hook_cls.get_hook.return_value.create_agent.call_args[1]["instructions"] assert "users" in instructions assert "events" in instructions - assert "event: TEXT\nts: TIMESTAMP" in instructions + assert "event TEXT, ts TIMESTAMP" in instructions class TestLLMSQLQueryOperatorDialect: diff --git a/providers/common/ai/tests/unit/common/ai/toolsets/test_datafusion.py b/providers/common/ai/tests/unit/common/ai/toolsets/test_datafusion.py index d3f0b7e81e90..92f7183abbbf 100644 --- a/providers/common/ai/tests/unit/common/ai/toolsets/test_datafusion.py +++ b/providers/common/ai/tests/unit/common/ai/toolsets/test_datafusion.py @@ -32,6 +32,7 @@ DataFusionToolset, ) from airflow.providers.common.sql.config import DataSourceConfig +from airflow.providers.common.sql.datafusion.engine import DataFusionEngine def _make_mock_datasource_config(table_name: str = "sales_data"): @@ -48,21 +49,14 @@ def _make_mock_engine( query_result: dict[str, list] | None = None, ): """Create a mock DataFusionEngine with sensible defaults.""" - mock = MagicMock() + mock = MagicMock(spec=DataFusionEngine) tables = registered_tables or {"sales_data": "s3://bucket/sales/"} mock.registered_tables = tables mock.session_context.catalog().schema().table_names.return_value = list(tables.keys()) mock.session_context.table_exist.side_effect = lambda name: name in tables - fields = schema_fields or [("id", "Int64"), ("amount", "Float64")] - arrow_fields = [] - for name, ftype in fields: - field = MagicMock() - field.name = name - field.type = ftype - arrow_fields.append(field) - for tname in tables: - mock.session_context.table(tname).schema.return_value = arrow_fields + fields = [{"name": n, "type": t} for n, t in schema_fields or [("id", "Int64"), ("amount", "Float64")]] + mock.get_table_schema.return_value = fields mock.session_context.sql.return_value.limit.return_value.to_pydict.return_value = ( query_result diff --git a/providers/common/ai/tests/unit/common/ai/utils/test_schema_context.py b/providers/common/ai/tests/unit/common/ai/utils/test_schema_context.py new file mode 100644 index 000000000000..c66ab7d429e0 --- /dev/null +++ b/providers/common/ai/tests/unit/common/ai/utils/test_schema_context.py @@ -0,0 +1,39 @@ +# 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 pytest + +from airflow.providers.common.ai.utils.schema_context import format_columns_for_prompt + + +class TestFormatColumnsForPrompt: + @pytest.mark.parametrize( + ("columns", "expected"), + [ + pytest.param([], "", id="empty"), + pytest.param([{"name": "id", "type": "int64"}], "id int64", id="single-column"), + pytest.param( + [{"name": "id", "type": "int64"}, {"name": "n", "type": "string"}], + "id int64, n string", + id="multiple-columns", + ), + ], + ) + def test_joins_columns_with_comma(self, columns, expected): + assert format_columns_for_prompt(columns) == expected diff --git a/providers/common/sql/docs/changelog.rst b/providers/common/sql/docs/changelog.rst index e3dfaabf9949..6a270797387a 100644 --- a/providers/common/sql/docs/changelog.rst +++ b/providers/common/sql/docs/changelog.rst @@ -37,6 +37,11 @@ Changelog ``airflow.providers.common.sql.datafusion.object_storage_provider`` still works but emits ``AirflowProviderDeprecationWarning``. +.. note:: + ``DataFusionEngine.get_schema()`` is deprecated. Use the new ``DataFusionEngine.get_table_schema()``, which + returns ``list[dict[str, str]]`` (one dict per column with ``name`` and ``type`` keys, the same shape as + ``DbApiHook.get_table_schema()``) instead of the pre-formatted Arrow schema string. + 3.1.0 ..... 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 66ffb5cc4992..55c67db6bf18 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 @@ -17,12 +17,14 @@ from __future__ import annotations import os +import warnings from dataclasses import replace from typing import TYPE_CHECKING, Any from urllib.parse import parse_qsl, urlsplit from datafusion import SessionContext +from airflow.exceptions import AirflowProviderDeprecationWarning from airflow.providers.common.compat.sdk import BaseHook, Connection from airflow.providers.common.sql.config import ConnectionConfig, DataSourceConfig, StorageType from airflow.providers.common.sql.datafusion.exceptions import ( @@ -356,7 +358,28 @@ def _resolve_wasb_account(cls, host: str | None, login: str | None) -> str | Non # Azure storage account names are capped at 24 characters. return netloc.split(".", 1)[0][:24] - def get_schema(self, table_name: str): - """Get the schema of a table.""" - schema = str(self.session_context.table(table_name).schema()) - return schema + def get_table_schema(self, table_name: str) -> list[dict[str, str]]: + """ + Return column names and types for a table from its Arrow schema. + + :param table_name: Name of the table registered in the session context. + :return: List of dicts with ``name`` and ``type`` keys, the same shape as + ``DbApiHook.get_table_schema()``. + """ + table = self.session_context.table(table_name) + return [{"name": f.name, "type": str(f.type)} for f in table.schema()] + + def get_schema(self, table_name: str) -> str: + """ + Return the Arrow schema of a table as a string. + + Deprecated: use :meth:`get_table_schema`, which returns structured column metadata. + + :param table_name: Name of the table registered in the session context. + """ + warnings.warn( + "DataFusionEngine.get_schema() is deprecated. Use DataFusionEngine.get_table_schema() instead.", + AirflowProviderDeprecationWarning, + stacklevel=2, + ) + return str(self.session_context.table(table_name).schema()) 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 1c837ba88df6..4ba4cc9b094f 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 @@ -19,12 +19,14 @@ import os import tempfile from pathlib import Path +from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest -from datafusion import SessionContext +from datafusion import DataFrame, SessionContext from datafusion.object_store import LocalFileSystem +from airflow.exceptions import AirflowProviderDeprecationWarning from airflow.providers.common.sql.config import ConnectionConfig, DataSourceConfig, StorageType from airflow.providers.common.sql.datafusion.base import ObjectStorageProvider from airflow.providers.common.sql.datafusion.engine import DataFusionEngine @@ -832,44 +834,43 @@ def test_get_credentials_unknown_type(self): with pytest.raises(ValueError, match="Unknown connection type dummy"): engine._get_credentials(mock_conn) - def test_get_schema_success(self): + def test_get_table_schema_success(self): engine = DataFusionEngine() engine.df_ctx = MagicMock(spec=SessionContext) - mock_table = MagicMock() - mock_schema = MagicMock() - mock_schema.__str__ = lambda self: "id: int64, name: string" + mock_table = MagicMock(spec=DataFrame) + mock_schema = [SimpleNamespace(name="id", type="int64"), SimpleNamespace(name="name", type="string")] mock_table.schema.return_value = mock_schema engine.df_ctx.table.return_value = mock_table - result = engine.get_schema("test_table") + result = engine.get_table_schema("test_table") engine.df_ctx.table.assert_called_once_with("test_table") mock_table.schema.assert_called_once() - assert result == "id: int64, name: string" + assert result == [{"name": "id", "type": "int64"}, {"name": "name", "type": "string"}] - @patch.object(DataFusionEngine, "_get_connection_config") - def test_get_schema_with_local_csv(self, mock_get_conn): - mock_get_conn.return_value = None - - with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f: - f.write("name,age\nAlice,30\nBob,25\n") - csv_path = f.name - - try: - engine = DataFusionEngine() - datasource_config = DataSourceConfig( + @pytest.fixture + def local_csv_engine(self, tmp_path): + csv_path = tmp_path / "people.csv" + csv_path.write_text("name,age\nAlice,30\nBob,25\n") + engine = DataFusionEngine() + engine.register_datasource( + DataSourceConfig( table_name="test_csv", uri=f"file://{csv_path}", format="csv", storage_type="local", conn_id="", ) + ) + return engine - engine.register_datasource(datasource_config) + def test_get_table_schema_with_local_csv(self, local_csv_engine): + result = local_csv_engine.get_table_schema("test_csv") - result = engine.get_schema("test_csv") + assert result == [{"name": "name", "type": "string"}, {"name": "age", "type": "int64"}] - assert "name: string" in result - assert "age: int64" in result - finally: - os.unlink(csv_path) + def test_get_schema_is_deprecated_and_still_returns_the_arrow_schema_string(self, local_csv_engine): + with pytest.warns(AirflowProviderDeprecationWarning, match="Use DataFusionEngine.get_table_schema"): + result = local_csv_engine.get_schema("test_csv") + + assert result == "name: string\nage: int64"