Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion providers/common/ai/docs/toolsets/datafusion.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``
Expand Down
4 changes: 2 additions & 2 deletions providers/common/ai/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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:
Comment thread
kaxil marked this conversation as resolved.
Resolved
"""Format the columns type from list[dict[str, str]] to str."""
return ", ".join(f"{c['name']} {c['type']}" for c in columns)
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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."""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions providers/common/sql/docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
.....

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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())
Loading