From ce9ed60105aa04cf91467e0c4cc3bb6283ff9fc3 Mon Sep 17 00:00:00 2001 From: Andrew Lamb Date: Thu, 26 Nov 2026 05:59:33 -0500 Subject: [PATCH 1/4] docs: replace old upgrade guides with links to the versioned docs Co-Authored-By: Claude Fable 5.2 --- datafusion/core/src/lib.rs | 54 - .../library-user-guide/upgrading/46.0.0.md | 293 +--- .../library-user-guide/upgrading/47.0.0.md | 118 +- .../library-user-guide/upgrading/48.0.0.md | 227 +-- .../library-user-guide/upgrading/48.0.1.md | 22 +- .../library-user-guide/upgrading/49.0.0.md | 205 +-- .../library-user-guide/upgrading/50.0.0.md | 313 +--- .../library-user-guide/upgrading/51.0.0.md | 255 +-- .../library-user-guide/upgrading/52.0.0.md | 652 +------ .../library-user-guide/upgrading/53.0.0.md | 534 +----- .../library-user-guide/upgrading/54.0.0.md | 875 +--------- .../library-user-guide/upgrading/55.0.0.md | 1517 +---------------- 12 files changed, 33 insertions(+), 5032 deletions(-) diff --git a/datafusion/core/src/lib.rs b/datafusion/core/src/lib.rs index 2c3dfcac966c2..04378b3d83e0f 100644 --- a/datafusion/core/src/lib.rs +++ b/datafusion/core/src/lib.rs @@ -1197,60 +1197,6 @@ doc_comment::doctest!( library_user_guide_working_with_exprs ); -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/46.0.0.md", - library_user_guide_upgrading_46_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/47.0.0.md", - library_user_guide_upgrading_47_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/48.0.0.md", - library_user_guide_upgrading_48_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/48.0.1.md", - library_user_guide_upgrading_48_0_1 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/49.0.0.md", - library_user_guide_upgrading_49_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/50.0.0.md", - library_user_guide_upgrading_50_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/51.0.0.md", - library_user_guide_upgrading_51_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/52.0.0.md", - library_user_guide_upgrading_52_0_0 -); - -#[cfg(doctest)] -doc_comment::doctest!( - "../../../docs/source/library-user-guide/upgrading/53.0.0.md", - library_user_guide_upgrading_53_0_0 -); - #[cfg(doctest)] doc_comment::doctest!( "../../../docs/source/contributor-guide/api-health.md", diff --git a/docs/source/library-user-guide/upgrading/46.0.0.md b/docs/source/library-user-guide/upgrading/46.0.0.md index d3dd02f6e38bd..65c4f89100746 100644 --- a/docs/source/library-user-guide/upgrading/46.0.0.md +++ b/docs/source/library-user-guide/upgrading/46.0.0.md @@ -4,294 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 46.0.0 Upgrade Guide -## DataFusion 46.0.0 - -### Use `invoke_with_args` instead of `invoke()` and `invoke_batch()` - -DataFusion is moving to a consistent API for invoking ScalarUDFs, -[`ScalarUDFImpl::invoke_with_args()`], and deprecating -[`ScalarUDFImpl::invoke()`], [`ScalarUDFImpl::invoke_batch()`], and [`ScalarUDFImpl::invoke_no_args()`] - -If you see errors such as the following it means the older APIs are being used: - -```text -This feature is not implemented: Function concat does not implement invoke but called -``` - -To fix this error, use [`ScalarUDFImpl::invoke_with_args()`] instead, as shown -below. See [PR 14876] for an example. - -Given existing code like this: - -```rust -# /* comment to avoid running -impl ScalarUDFImpl for SparkConcat { -... - fn invoke_batch(&self, args: &[ColumnarValue], number_rows: usize) -> Result { - if args - .iter() - .any(|arg| matches!(arg.data_type(), DataType::List(_))) - { - ArrayConcat::new().invoke_batch(args, number_rows) - } else { - ConcatFunc::new().invoke_batch(args, number_rows) - } - } -} -# */ -``` - -To - -```rust -# /* comment to avoid running -impl ScalarUDFImpl for SparkConcat { - ... - fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result { - if args - .args - .iter() - .any(|arg| matches!(arg.data_type(), DataType::List(_))) - { - ArrayConcat::new().invoke_with_args(args) - } else { - ConcatFunc::new().invoke_with_args(args) - } - } -} - # */ -``` - -[`scalarudfimpl::invoke()`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/trait.ScalarUDFImpl.html#method.invoke -[`scalarudfimpl::invoke_batch()`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/trait.ScalarUDFImpl.html#method.invoke_batch -[`scalarudfimpl::invoke_no_args()`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/trait.ScalarUDFImpl.html#method.invoke_no_args -[`scalarudfimpl::invoke_with_args()`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/trait.ScalarUDFImpl.html#method.invoke_with_args -[pr 14876]: https://github.com/apache/datafusion/pull/14876 - -### `ParquetExec`, `AvroExec`, `CsvExec`, `JsonExec` deprecated - -DataFusion 46 has a major change to how the built in DataSources are organized. -Instead of individual `ExecutionPlan`s for the different file formats they now -all use `DataSourceExec` and the format specific information is embodied in new -traits `DataSource` and `FileSource`. - -Here is more information about - -- [Design Ticket] -- Change PR [PR #14224] -- Example of an Upgrade [PR in delta-rs] - -[design ticket]: https://github.com/apache/datafusion/issues/13838 -[pr #14224]: https://github.com/apache/datafusion/pull/14224 -[pr in delta-rs]: https://github.com/delta-io/delta-rs/pull/3261 - -### Cookbook: Changes to `ParquetExecBuilder` - -Code that looks for `ParquetExec` like this will no longer work: - -```rust -# /* comment to avoid running - if let Some(parquet_exec) = plan.as_any().downcast_ref::() { - // Do something with ParquetExec here - } -# */ -``` - -Instead, with `DataSourceExec`, the same information is now on `FileScanConfig` and -`ParquetSource`. The equivalent code is - -```rust -# /* comment to avoid running -if let Some(datasource_exec) = plan.as_any().downcast_ref::() { - if let Some(scan_config) = datasource_exec.data_source().as_any().downcast_ref::() { - // FileGroups, and other information is on the FileScanConfig - // parquet - if let Some(parquet_source) = scan_config.file_source.as_any().downcast_ref::() - { - // Information on PruningPredicates and parquet options are here - } -} -# */ -``` - -### Cookbook: Changes to `ParquetExecBuilder` - -Likewise code that builds `ParquetExec` using the `ParquetExecBuilder` such as -the following must be changed: - -```rust -# /* comment to avoid running -let mut exec_plan_builder = ParquetExecBuilder::new( - FileScanConfig::new(self.log_store.object_store_url(), file_schema) - .with_projection(self.projection.cloned()) - .with_limit(self.limit) - .with_table_partition_cols(table_partition_cols), -) -.with_schema_adapter_factory(Arc::new(DeltaSchemaAdapterFactory {})) -.with_table_parquet_options(parquet_options); - -// Add filter -if let Some(predicate) = logical_filter { - if config.enable_parquet_pushdown { - exec_plan_builder = exec_plan_builder.with_predicate(predicate); - } -}; -# */ -``` - -New code should use `FileScanConfig` to build the appropriate `DataSourceExec`: - -```rust -# /* comment to avoid running -let mut file_source = ParquetSource::new(parquet_options) - .with_schema_adapter_factory(Arc::new(DeltaSchemaAdapterFactory {})); - -// Add filter -if let Some(predicate) = logical_filter { - if config.enable_parquet_pushdown { - file_source = file_source.with_predicate(predicate); - } -}; - -let file_scan_config = FileScanConfig::new( - self.log_store.object_store_url(), - file_schema, - Arc::new(file_source), -) -.with_statistics(stats) -.with_projection(self.projection.cloned()) -.with_limit(self.limit) -.with_table_partition_cols(table_partition_cols); - -// Build the actual scan like this -parquet_scan: file_scan_config.build(), -# */ -``` - -### `datafusion-cli` no longer automatically unescapes strings - -`datafusion-cli` previously would incorrectly unescape string literals (see [ticket] for more details). - -To escape `'` in SQL literals, use `''`: - -```sql -> select 'it''s escaped'; -+----------------------+ -| Utf8("it's escaped") | -+----------------------+ -| it's escaped | -+----------------------+ -1 row(s) fetched. -``` - -To include special characters (such as newlines via `\n`) you can use an `E` literal string. For example - -```sql -> select 'foo\nbar'; -+------------------+ -| Utf8("foo\nbar") | -+------------------+ -| foo\nbar | -+------------------+ -1 row(s) fetched. -Elapsed 0.005 seconds. -``` - -### Changes to array scalar function signatures - -DataFusion 46 has changed the way scalar array function signatures are -declared. Previously, functions needed to select from a list of predefined -signatures within the `ArrayFunctionSignature` enum. Now the signatures -can be defined via a `Vec` of pseudo-types, which each correspond to a -single argument. Those pseudo-types are the variants of the -`ArrayFunctionArgument` enum and are as follows: - -- `Array`: An argument of type List/LargeList/FixedSizeList. All Array - arguments must be coercible to the same type. -- `Element`: An argument that is coercible to the inner type of the `Array` - arguments. -- `Index`: An `Int64` argument. - -Each of the old variants can be converted to the new format as follows: - -`TypeSignature::ArraySignature(ArrayFunctionSignature::ArrayAndElement)`: - -```rust -# use datafusion::common::utils::ListCoercion; -# use datafusion_expr_common::signature::{ArrayFunctionArgument, ArrayFunctionSignature, TypeSignature}; - -TypeSignature::ArraySignature(ArrayFunctionSignature::Array { - arguments: vec![ArrayFunctionArgument::Array, ArrayFunctionArgument::Element], - array_coercion: Some(ListCoercion::FixedSizedListToList), -}); -``` - -`TypeSignature::ArraySignature(ArrayFunctionSignature::ElementAndArray)`: - -```rust -# use datafusion::common::utils::ListCoercion; -# use datafusion_expr_common::signature::{ArrayFunctionArgument, ArrayFunctionSignature, TypeSignature}; - -TypeSignature::ArraySignature(ArrayFunctionSignature::Array { - arguments: vec![ArrayFunctionArgument::Element, ArrayFunctionArgument::Array], - array_coercion: Some(ListCoercion::FixedSizedListToList), -}); -``` - -`TypeSignature::ArraySignature(ArrayFunctionSignature::ArrayAndIndex)`: - -```rust -# use datafusion::common::utils::ListCoercion; -# use datafusion_expr_common::signature::{ArrayFunctionArgument, ArrayFunctionSignature, TypeSignature}; - -TypeSignature::ArraySignature(ArrayFunctionSignature::Array { - arguments: vec![ArrayFunctionArgument::Array, ArrayFunctionArgument::Index], - array_coercion: None, -}); -``` - -`TypeSignature::ArraySignature(ArrayFunctionSignature::ArrayAndElementAndOptionalIndex)`: - -```rust -# use datafusion::common::utils::ListCoercion; -# use datafusion_expr_common::signature::{ArrayFunctionArgument, ArrayFunctionSignature, TypeSignature}; - -TypeSignature::OneOf(vec![ - TypeSignature::ArraySignature(ArrayFunctionSignature::Array { - arguments: vec![ArrayFunctionArgument::Array, ArrayFunctionArgument::Element], - array_coercion: None, - }), - TypeSignature::ArraySignature(ArrayFunctionSignature::Array { - arguments: vec![ - ArrayFunctionArgument::Array, - ArrayFunctionArgument::Element, - ArrayFunctionArgument::Index, - ], - array_coercion: None, - }), -]); -``` - -`TypeSignature::ArraySignature(ArrayFunctionSignature::Array)`: - -```rust -# use datafusion::common::utils::ListCoercion; -# use datafusion_expr_common::signature::{ArrayFunctionArgument, ArrayFunctionSignature, TypeSignature}; - -TypeSignature::ArraySignature(ArrayFunctionSignature::Array { - arguments: vec![ArrayFunctionArgument::Array], - array_coercion: None, -}); -``` - -Alternatively, you can switch to using one of the following functions which -take care of constructing the `TypeSignature` for you: - -- `Signature::array_and_element` -- `Signature::array_and_element_and_optional_index` -- `Signature::array_and_index` -- `Signature::array` - -[ticket]: https://github.com/apache/datafusion/issues/13286 +The upgrade guide for DataFusion 46.0.0 is in the +[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/46.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/47.0.0.md b/docs/source/library-user-guide/upgrading/47.0.0.md index 42713b2b82608..766374001fdf7 100644 --- a/docs/source/library-user-guide/upgrading/47.0.0.md +++ b/docs/source/library-user-guide/upgrading/47.0.0.md @@ -4,119 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 47.0.0 Upgrade Guide -## DataFusion 47.0.0 - -This section calls out some of the major changes in the `47.0.0` release of DataFusion. - -Here are some example upgrade PRs that demonstrate changes required when upgrading from DataFusion 46.0.0: - -- [delta-rs Upgrade to `47.0.0`](https://github.com/delta-io/delta-rs/pull/3378) -- [DataFusion Comet Upgrade to `47.0.0`](https://github.com/apache/datafusion-comet/pull/1563) -- [Sail Upgrade to `47.0.0`](https://github.com/lakehq/sail/pull/434) - -### Upgrades to `arrow-rs` and `arrow-parquet` 55.0.0 and `object_store` 0.12.0 - -Several APIs are changed in the underlying arrow and parquet libraries to use a -`u64` instead of `usize` to better support WASM (See [#7371] and [#6961]) - -Additionally `ObjectStore::list` and `ObjectStore::list_with_offset` have been changed to return `static` lifetimes (See [#6619]) - -[#6619]: https://github.com/apache/arrow-rs/pull/6619 -[#7371]: https://github.com/apache/arrow-rs/pull/7371 - -This requires converting from `usize` to `u64` occasionally as well as changes to `ObjectStore` implementations such as - -```rust -# /* comment to avoid running -impl Objectstore { - ... - // The range is now a u64 instead of usize - async fn get_range(&self, location: &Path, range: Range) -> ObjectStoreResult { - self.inner.get_range(location, range).await - } - ... - // the lifetime is now 'static instead of `_ (meaning the captured closure can't contain references) - // (this also applies to list_with_offset) - fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, ObjectStoreResult> { - self.inner.list(prefix) - } -} -# */ -``` - -The `ParquetObjectReader` has been updated to no longer require the object size -(it can be fetched using a single suffix request). See [#7334] for details - -[#7334]: https://github.com/apache/arrow-rs/pull/7334 - -Pattern in DataFusion `46.0.0`: - -```rust -# /* comment to avoid running -let meta: ObjectMeta = ...; -let reader = ParquetObjectReader::new(store, meta); -# */ -``` - -Pattern in DataFusion `47.0.0`: - -```rust -# /* comment to avoid running -let meta: ObjectMeta = ...; -let reader = ParquetObjectReader::new(store, location) - .with_file_size(meta.size); -# */ -``` - -### `DisplayFormatType::TreeRender` - -DataFusion now supports [`tree` style explain plans]. Implementations of -`Executionplan` must also provide a description in the -`DisplayFormatType::TreeRender` format. This can be the same as the existing -`DisplayFormatType::Default`. - -[`tree` style explain plans]: https://datafusion.apache.org/user-guide/sql/explain.html#tree-format-default - -### Removed Deprecated APIs - -Several APIs have been removed in this release. These were either deprecated -previously or were hard to use correctly such as the multiple different -`ScalarUDFImpl::invoke*` APIs. See [#15130], [#15123], and [#15027] for more -details. - -[#15130]: https://github.com/apache/datafusion/pull/15130 -[#15123]: https://github.com/apache/datafusion/pull/15123 -[#15027]: https://github.com/apache/datafusion/pull/15027 - -### `FileScanConfig` --> `FileScanConfigBuilder` - -Previously, `FileScanConfig::build()` directly created ExecutionPlans. In -DataFusion 47.0.0 this has been changed to use `FileScanConfigBuilder`. See -[#15352] for details. - -[#15352]: https://github.com/apache/datafusion/pull/15352 - -Pattern in DataFusion `46.0.0`: - -```rust -# /* comment to avoid running -let plan = FileScanConfig::new(url, schema, Arc::new(file_source)) - .with_statistics(stats) - ... - .build() -# */ -``` - -Pattern in DataFusion `47.0.0`: - -```rust -# /* comment to avoid running -let config = FileScanConfigBuilder::new(url, Arc::new(file_source)) - .with_statistics(stats) - ... - .build(); -let scan = DataSourceExec::from_data_source(config); -# */ -``` +The upgrade guide for DataFusion 47.0.0 is in the +[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/47.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/48.0.0.md b/docs/source/library-user-guide/upgrading/48.0.0.md index d4f7a714e20f3..80cb42776c7a7 100644 --- a/docs/source/library-user-guide/upgrading/48.0.0.md +++ b/docs/source/library-user-guide/upgrading/48.0.0.md @@ -4,228 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 48.0.0 Upgrade Guide -## DataFusion 48.0.0 - -### `Expr::Literal` has optional metadata - -The [`Expr::Literal`] variant now includes optional metadata, which allows for -carrying through Arrow field metadata to support extension types and other uses. - -This means code such as - -```rust -# /* comment to avoid running -match expr { -... - Expr::Literal(scalar) => ... -... -} -# */ -``` - -Should be updated to: - -```rust -# /* comment to avoid running -match expr { -... - Expr::Literal(scalar, _metadata) => ... -... -} -# */ -``` - -Likewise constructing `Expr::Literal` requires metadata as well. The [`lit`] function -has not changed and returns an `Expr::Literal` with no metadata. - -[`expr::literal`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html#variant.Literal -[`lit`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/fn.lit.html - -### `Expr::WindowFunction` is now `Box`ed - -`Expr::WindowFunction` is now a `Box` instead of a `WindowFunction` directly. -This change was made to reduce the size of `Expr` and improve performance when -planning queries (see [details on #16207]). - -This is a breaking change, so you will need to update your code if you match -on `Expr::WindowFunction` directly. For example, if you have code like this: - -```rust -# /* comment to avoid running -match expr { - Expr::WindowFunction(WindowFunction { - params: - WindowFunctionParams { - partition_by, - order_by, - .. - } - }) => { - // Use partition_by and order_by as needed - } - _ => { - // other expr - } -} -# */ -``` - -You will need to change it to: - -```rust -# /* comment to avoid running -match expr { - Expr::WindowFunction(window_fun) => { - let WindowFunction { - fun, - params: WindowFunctionParams { - args, - partition_by, - .. - }, - } = window_fun.as_ref(); - // Use partition_by and order_by as needed - } - _ => { - // other expr - } -} -# */ -``` - -[details on #16207]: https://github.com/apache/datafusion/pull/16207#issuecomment-2922659103 - -### The `VARCHAR` SQL type is now represented as `Utf8View` in Arrow - -The mapping of the SQL `VARCHAR` type has been changed from `Utf8` to `Utf8View` -which improves performance for many string operations. You can read more about -`Utf8View` in the [DataFusion blog post on German-style strings] - -[datafusion blog post on german-style strings]: https://datafusion.apache.org/blog/2024/09/13/string-view-german-style-strings-part-1/ - -This means that when you create a table with a `VARCHAR` column, it will now use -`Utf8View` as the underlying data type. For example: - -```sql -> CREATE TABLE my_table (my_column VARCHAR); -0 row(s) fetched. -Elapsed 0.001 seconds. - -> DESCRIBE my_table; -+-------------+-----------+-------------+ -| column_name | data_type | is_nullable | -+-------------+-----------+-------------+ -| my_column | Utf8View | YES | -+-------------+-----------+-------------+ -1 row(s) fetched. -Elapsed 0.000 seconds. -``` - -You can restore the old behavior of using `Utf8` by changing the -`datafusion.sql_parser.map_varchar_to_utf8view` configuration setting. For -example - -```sql -> set datafusion.sql_parser.map_varchar_to_utf8view = false; -0 row(s) fetched. -Elapsed 0.001 seconds. - -> CREATE TABLE my_table (my_column VARCHAR); -0 row(s) fetched. -Elapsed 0.014 seconds. - -> DESCRIBE my_table; -+-------------+-----------+-------------+ -| column_name | data_type | is_nullable | -+-------------+-----------+-------------+ -| my_column | Utf8 | YES | -+-------------+-----------+-------------+ -1 row(s) fetched. -Elapsed 0.004 seconds. -``` - -### `ListingOptions` default for `collect_stat` changed from `true` to `false` - -This makes it agree with the default for `SessionConfig`. -Most users won't be impacted by this change but if you were using `ListingOptions` directly -and relied on the default value of `collect_stat` being `true`, you will need to -explicitly set it to `true` in your code. - -```rust -# /* comment to avoid running -ListingOptions::new(Arc::new(ParquetFormat::default())) - .with_collect_stat(true) - // other options -# */ -``` - -### Processing `FieldRef` instead of `DataType` for user defined functions - -In order to support metadata handling and extension types, user defined functions are -now switching to traits which use `FieldRef` rather than a `DataType` and nullability. -This gives a single interface to both of these parameters and additionally allows -access to metadata fields, which can be used for extension types. - -To upgrade structs which implement `ScalarUDFImpl`, if you have implemented -`return_type_from_args` you need instead to implement `return_field_from_args`. -If your functions do not need to handle metadata, this should be straightforward -repackaging of the output data into a `FieldRef`. The name you specify on the -field is not important. It will be overwritten during planning. `ReturnInfo` -has been removed, so you will need to remove all references to it. - -`ScalarFunctionArgs` now contains a field called `arg_fields`. You can use this -to access the metadata associated with the columnar values during invocation. - -To upgrade user defined aggregate functions, there is now a function -`return_field` that will allow you to specify both metadata and nullability of -your function. You are not required to implement this if you do not need to -handle metadata. - -The largest change to aggregate functions happens in the accumulator arguments. -Both the `AccumulatorArgs` and `StateFieldsArgs` now contain `FieldRef` rather -than `DataType`. - -To upgrade window functions, `ExpressionArgs` now contains input fields instead -of input data types. When setting these fields, the name of the field is -not important since this gets overwritten during the planning stage. All you -should need to do is wrap your existing data types in fields with nullability -set depending on your use case. - -### Physical Expression return `Field` - -To support the changes to user defined functions processing metadata, the -`PhysicalExpr` trait, which now must specify a return `Field` based on the input -schema. To upgrade structs which implement `PhysicalExpr` you need to implement -the `return_field` function. There are numerous examples in the `physical-expr` -crate. - -### `FileFormat::supports_filters_pushdown` replaced with `FileSource::try_pushdown_filters` - -To support more general filter pushdown, the `FileFormat::supports_filters_pushdown` was replaced with -`FileSource::try_pushdown_filters`. -If you implemented a custom `FileFormat` that uses a custom `FileSource` you will need to implement -`FileSource::try_pushdown_filters`. -See `ParquetSource::try_pushdown_filters` for an example of how to implement this. - -`FileFormat::supports_filters_pushdown` has been removed. - -### `ParquetExec`, `AvroExec`, `CsvExec`, `JsonExec` Removed - -`ParquetExec`, `AvroExec`, `CsvExec`, and `JsonExec` were deprecated in -DataFusion 46 and are removed in DataFusion 48. This is sooner than the normal -process described in the [API Deprecation Guidelines] because all the tests -cover the new `DataSourceExec` rather than the older structures. As we evolve -`DataSource`, the old structures began to show signs of "bit rotting" (not -working but no one knows due to lack of test coverage). - -[api deprecation guidelines]: https://datafusion.apache.org/contributor-guide/api-health.html#deprecation-guidelines - -### `PartitionedFile` added as an argument to the `FileOpener` trait - -This is necessary to properly fix filter pushdown for filters that combine partition -columns and file columns (e.g. `day = username['dob']`). - -If you implemented a custom `FileOpener` you will need to add the `PartitionedFile` argument -but are not required to use it in any way. +The upgrade guide for DataFusion 48.0.0 is in the +[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/48.0.1.md b/docs/source/library-user-guide/upgrading/48.0.1.md index e09b67bc8010c..7e63159ddb59f 100644 --- a/docs/source/library-user-guide/upgrading/48.0.1.md +++ b/docs/source/library-user-guide/upgrading/48.0.1.md @@ -4,23 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 48.0.1 Upgrade Guide -## DataFusion 48.0.1 - -### `datafusion.execution.collect_statistics` now defaults to `true` - -The default value of the `datafusion.execution.collect_statistics` configuration -setting is now true. This change impacts users that use that value directly and relied -on its default value being `false`. - -This change also restores the default behavior of `ListingTable` to its previous. If you use it directly -you can maintain the current behavior by overriding the default value in your code. - -```rust -# /* comment to avoid running -ListingOptions::new(Arc::new(ParquetFormat::default())) - .with_collect_stat(false) - // other options -# */ -``` +The upgrade guide for DataFusion 48.0.1 is in the +[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.1.html). diff --git a/docs/source/library-user-guide/upgrading/49.0.0.md b/docs/source/library-user-guide/upgrading/49.0.0.md index db12def98718f..025e9020ff694 100644 --- a/docs/source/library-user-guide/upgrading/49.0.0.md +++ b/docs/source/library-user-guide/upgrading/49.0.0.md @@ -4,206 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 49.0.0 Upgrade Guide -## DataFusion 49.0.0 - -### `MSRV` updated to 1.85.1 - -The Minimum Supported Rust Version (MSRV) has been updated to [`1.85.1`]. See -[#16728] for details. - -[`1.85.1`]: https://releases.rs/docs/1.85.1/ -[#16728]: https://github.com/apache/datafusion/pull/16728 - -### `DataFusionError` variants are now `Box`ed - -To reduce the size of `DataFusionError`, several variants that were previously stored inline are now `Box`ed. This reduces the size of `Result` and thus stack usage and async state machine size. Please see [#16652] for more details. - -The following variants of `DataFusionError` are now boxed: - -- `ArrowError` -- `SQL` -- `SchemaError` - -This is a breaking change. Code that constructs or matches on these variants will need to be updated. - -For example, to create a `SchemaError`, instead of: - -```rust -# /* comment to avoid running -use datafusion_common::{DataFusionError, SchemaError}; -DataFusionError::SchemaError( - SchemaError::DuplicateUnqualifiedField { name: "foo".to_string() }, - Box::new(None) -) -# */ -``` - -You now need to `Box` the inner error: - -```rust -# /* comment to avoid running -use datafusion_common::{DataFusionError, SchemaError}; -DataFusionError::SchemaError( - Box::new(SchemaError::DuplicateUnqualifiedField { name: "foo".to_string() }), - Box::new(None) -) -# */ -``` - -[#16652]: https://github.com/apache/datafusion/issues/16652 - -### Metadata on Arrow Types is now represented by `FieldMetadata` - -Metadata from the Arrow `Field` is now stored using the `FieldMetadata` -structure. In prior versions it was stored as both a `HashMap` -and a `BTreeMap`. `FieldMetadata` is a easier to work with and -is more efficient. - -To create `FieldMetadata` from a `Field`: - -```rust -# /* comment to avoid running - let metadata = FieldMetadata::from(&field); -# */ -``` - -To add metadata to a `Field`, use the `add_to_field` method: - -```rust -# /* comment to avoid running -let updated_field = metadata.add_to_field(field); -# */ -``` - -See [#16317] for details. - -[#16317]: https://github.com/apache/datafusion/pull/16317 - -### New `datafusion.execution.spill_compression` configuration option - -DataFusion 49.0.0 adds support for compressing spill files when data is written to disk during spilling query execution. A new configuration option `datafusion.execution.spill_compression` controls the compression codec used. - -**Configuration:** - -- **Key**: `datafusion.execution.spill_compression` -- **Default**: `uncompressed` -- **Valid values**: `uncompressed`, `lz4_frame`, `zstd` - -**Usage:** - -```rust -# /* comment to avoid running -use datafusion::prelude::*; -use datafusion_common::config::SpillCompression; - -let config = SessionConfig::default() - .with_spill_compression(SpillCompression::Zstd); -let ctx = SessionContext::new_with_config(config); -# */ -``` - -Or via SQL: - -```sql -SET datafusion.execution.spill_compression = 'zstd'; -``` - -For more details about this configuration option, including performance trade-offs between different compression codecs, see the [Configuration Settings](../../user-guide/configs.md) documentation. - -### Deprecated `map_varchar_to_utf8view` configuration option - -See [issue #16290](https://github.com/apache/datafusion/pull/16290) for more information -The old configuration - -```text -datafusion.sql_parser.map_varchar_to_utf8view -``` - -is now **deprecated** in favor of the unified option below.\ -If you previously used this to control only `VARCHAR`→`Utf8View` mapping, please migrate to `map_string_types_to_utf8view`. - ---- - -### New `map_string_types_to_utf8view` configuration option - -To unify **all** SQL string types (`CHAR`, `VARCHAR`, `TEXT`, `STRING`) to Arrow’s zero‑copy `Utf8View`, DataFusion 49.0.0 introduces: - -- **Key**: `datafusion.sql_parser.map_string_types_to_utf8view` -- **Default**: `true` - -**Description:** - -- When **true** (default), **all** SQL string types are mapped to `Utf8View`, avoiding full‑copy UTF‑8 allocations and improving performance. -- When **false**, DataFusion falls back to the legacy `Utf8` mapping for **all** string types. - -#### Examples - -```rust -# /* comment to avoid running -// Disable Utf8View mapping for all SQL string types -let opts = datafusion::sql::planner::ParserOptions::new() - .with_map_string_types_to_utf8view(false); - -// Verify the setting is applied -assert!(!opts.map_string_types_to_utf8view); -# */ -``` - ---- - -```sql --- Disable Utf8View mapping globally -SET datafusion.sql_parser.map_string_types_to_utf8view = false; - --- Now VARCHAR, CHAR, TEXT, STRING all use Utf8 rather than Utf8View -CREATE TABLE my_table (a VARCHAR, b TEXT, c STRING); -DESCRIBE my_table; -``` - -### Deprecating `SchemaAdapterFactory` and `SchemaAdapter` - -We are moving away from converting data (using `SchemaAdapter`) to converting the expressions themselves (which is more efficient and flexible). - -See [issue #16800](https://github.com/apache/datafusion/issues/16800) for more information -The first place this change has taken place is in predicate pushdown for Parquet. -By default if you do not use a custom `SchemaAdapterFactory` we will use expression conversion instead. -If you do set a custom `SchemaAdapterFactory` we will continue to use it but emit a warning about that code path being deprecated. - -To resolve this you need to implement a custom `PhysicalExprAdapterFactory` and use that instead of a `SchemaAdapterFactory`. -See the [default values](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/custom_data_source/default_column_values.rs) for an example of how to do this. -Opting into the new APIs will set you up for future changes since we plan to expand use of `PhysicalExprAdapterFactory` to other areas of DataFusion. - -See [#16800] for details. - -[#16800]: https://github.com/apache/datafusion/issues/16800 - -### `TableParquetOptions` Updated - -The `TableParquetOptions` struct has a new `crypto` field to specify encryption -options for Parquet files. The `ParquetEncryptionOptions` implements `Default` -so you can upgrade your existing code like this: - -```rust -# /* comment to avoid running -TableParquetOptions { - global, - column_specific_options, - key_value_metadata, -} -# */ -``` - -To this: - -```rust -# /* comment to avoid running -TableParquetOptions { - global, - column_specific_options, - key_value_metadata, - crypto: Default::default(), // New crypto field -} -# */ -``` +The upgrade guide for DataFusion 49.0.0 is in the +[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/49.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/50.0.0.md b/docs/source/library-user-guide/upgrading/50.0.0.md index 29f5236dcafc2..a0d11d9dcfb11 100644 --- a/docs/source/library-user-guide/upgrading/50.0.0.md +++ b/docs/source/library-user-guide/upgrading/50.0.0.md @@ -4,314 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 50.0.0 Upgrade Guide -## DataFusion 50.0.0 - -### ListingTable automatically detects Hive Partitioned tables - -DataFusion 50.0.0 automatically infers Hive partitions when using the `ListingTableFactory` and `CREATE EXTERNAL TABLE`. Previously, -when creating a `ListingTable`, datasets that use Hive partitioning (e.g. -`/table_root/column1=value1/column2=value2/data.parquet`) would not have the Hive columns reflected in -the table's schema or data. The previous behavior can be -restored by setting the `datafusion.execution.listing_table_factory_infer_partitions` configuration option to `false`. -See [issue #17049] for more details. - -[issue #17049]: https://github.com/apache/datafusion/issues/17049 - -### `MSRV` updated to 1.86.0 - -The Minimum Supported Rust Version (MSRV) has been updated to [`1.86.0`]. -See [#17230] for details. - -[`1.86.0`]: https://releases.rs/docs/1.86.0/ -[#17230]: https://github.com/apache/datafusion/pull/17230 - -### `ScalarUDFImpl`, `AggregateUDFImpl` and `WindowUDFImpl` traits now require `PartialEq`, `Eq`, and `Hash` traits - -To address error-proneness of `ScalarUDFImpl::equals`, `AggregateUDFImpl::equals`and -`WindowUDFImpl::equals` methods and to make it easy to implement function equality correctly, -the `equals` and `hash_value` methods have been removed from `ScalarUDFImpl`, `AggregateUDFImpl` -and `WindowUDFImpl` traits. They are replaced the requirement to implement the `PartialEq`, `Eq`, -and `Hash` traits on any type implementing `ScalarUDFImpl`, `AggregateUDFImpl` or `WindowUDFImpl`. -Please see [issue #16677] for more details. - -Most of the scalar functions are stateless and have a `signature` field. These can be migrated -using regular expressions - -- search for `\#\[derive\(Debug\)\](\n *(pub )?struct \w+ \{\n *signature\: Signature\,\n *\})`, -- replace with `#[derive(Debug, PartialEq, Eq, Hash)]$1`, -- review all the changes and make sure only function structs were changed. - -[issue #16677]: https://github.com/apache/datafusion/issues/16677 - -### `AsyncScalarUDFImpl::invoke_async_with_args` returns `ColumnarValue` - -In order to enable single value optimizations and be consistent with other -user defined function APIs, the `AsyncScalarUDFImpl::invoke_async_with_args` method now -returns a `ColumnarValue` instead of a `ArrayRef`. - -To upgrade, change the return type of your implementation - -```rust -# /* comment to avoid running -impl AsyncScalarUDFImpl for AskLLM { - async fn invoke_async_with_args( - &self, - args: ScalarFunctionArgs, - _option: &ConfigOptions, - ) -> Result { - .. - return array_ref; // old code - } -} -# */ -``` - -To return a `ColumnarValue` - -```rust -# /* comment to avoid running -impl AsyncScalarUDFImpl for AskLLM { - async fn invoke_async_with_args( - &self, - args: ScalarFunctionArgs, - _option: &ConfigOptions, - ) -> Result { - .. - return ColumnarValue::from(array_ref); // new code - } -} -# */ -``` - -See [#16896](https://github.com/apache/datafusion/issues/16896) for more details. - -### `ProjectionExpr` changed from type alias to struct - -`ProjectionExpr` has been changed from a type alias to a struct with named fields to improve code clarity and maintainability. - -**Before:** - -```rust,ignore -pub type ProjectionExpr = (Arc, String); -``` - -**After:** - -```rust,ignore -#[derive(Debug, Clone)] -pub struct ProjectionExpr { - pub expr: Arc, - pub alias: String, -} -``` - -To upgrade your code: - -- Replace tuple construction `(expr, alias)` with `ProjectionExpr::new(expr, alias)` or `ProjectionExpr { expr, alias }` -- Replace tuple field access `.0` and `.1` with `.expr` and `.alias` -- Update pattern matching from `(expr, alias)` to `ProjectionExpr { expr, alias }` - -This mainly impacts use of `ProjectionExec`. - -This change was done in [#17398] - -[#17398]: https://github.com/apache/datafusion/pull/17398 - -### `SessionState`, `SessionConfig`, and `OptimizerConfig` returns `&Arc` instead of `&ConfigOptions` - -To provide broader access to `ConfigOptions` and reduce required clones, some -APIs have been changed to return a `&Arc` instead of a -`&ConfigOptions`. This allows sharing the same `ConfigOptions` across multiple -threads without needing to clone the entire `ConfigOptions` structure unless it -is modified. - -Most users will not be impacted by this change since the Rust compiler typically -automatically dereference the `Arc` when needed. However, in some cases you may -have to change your code to explicitly call `as_ref()` for example, from - -```rust -# /* comment to avoid running -let optimizer_config: &ConfigOptions = state.options(); -# */ -``` - -To - -```rust -# /* comment to avoid running -let optimizer_config: &ConfigOptions = state.options().as_ref(); -# */ -``` - -See PR [#16970](https://github.com/apache/datafusion/pull/16970) - -### API Change to `AsyncScalarUDFImpl::invoke_async_with_args` - -The `invoke_async_with_args` method of the `AsyncScalarUDFImpl` trait has been -updated to remove the `_option: &ConfigOptions` parameter to simplify the API -now that the `ConfigOptions` can be accessed through the `ScalarFunctionArgs` -parameter. - -You can change your code like this - -```rust -# /* comment to avoid running -impl AsyncScalarUDFImpl for AskLLM { - async fn invoke_async_with_args( - &self, - args: ScalarFunctionArgs, - _option: &ConfigOptions, - ) -> Result { - .. - } - ... -} -# */ -``` - -To this: - -```rust -# /* comment to avoid running - -impl AsyncScalarUDFImpl for AskLLM { - async fn invoke_async_with_args( - &self, - args: ScalarFunctionArgs, - ) -> Result { - let options = &args.config_options; - .. - } - ... -} -# */ -``` - -### Schema Rewriter Module Moved to New Crate - -The `schema_rewriter` module and its associated symbols have been moved from `datafusion_physical_expr` to a new crate `datafusion_physical_expr_adapter`. This affects the following symbols: - -- `DefaultPhysicalExprAdapter` -- `DefaultPhysicalExprAdapterFactory` -- `PhysicalExprAdapter` -- `PhysicalExprAdapterFactory` - -To upgrade, change your imports to: - -```rust -use datafusion_physical_expr_adapter::{ - DefaultPhysicalExprAdapter, DefaultPhysicalExprAdapterFactory, - PhysicalExprAdapter, PhysicalExprAdapterFactory -}; -``` - -### Upgrade to arrow `56.0.0` and parquet `56.0.0` - -This version of DataFusion upgrades the underlying Apache Arrow implementation -to version `56.0.0`. See the [release notes](https://github.com/apache/arrow-rs/releases/tag/56.0.0) -for more details. - -### Added `ExecutionPlan::reset_state` - -In order to fix a bug in DataFusion `49.0.0` where dynamic filters (currently only generated in the presence of a query such as `ORDER BY ... LIMIT ...`) -produced incorrect results in recursive queries, a new method `reset_state` has been added to the `ExecutionPlan` trait. - -Any `ExecutionPlan` that needs to maintain internal state or references to other nodes in the execution plan tree should implement this method to reset that state. -See [#17028] for more details and an example implementation for `SortExec`. - -[#17028]: https://github.com/apache/datafusion/pull/17028 - -### Nested Loop Join input sort order cannot be preserved - -The Nested Loop Join operator has been rewritten from scratch to improve performance and memory efficiency. From the micro-benchmarks: this change introduces up to 5X speed-up and uses only 1% memory in extreme cases compared to the previous implementation. - -However, the new implementation cannot preserve input sort order like the old version could. This is a fundamental design trade-off that prioritizes performance and memory efficiency over sort order preservation. - -See [#16996] for details. - -[#16996]: https://github.com/apache/datafusion/pull/16996 - -### Add `as_any()` method to `LazyBatchGenerator` - -To help with protobuf serialization, the `as_any()` method has been added to the `LazyBatchGenerator` trait. This means you will need to add `as_any()` to your implementation of `LazyBatchGenerator`: - -```rust -# /* comment to avoid running - -impl LazyBatchGenerator for MyBatchGenerator { - fn as_any(&self) -> &dyn Any { - self - } - - ... -} - -# */ -``` - -See [#17200](https://github.com/apache/datafusion/pull/17200) for details. - -### Refactored `DataSource::try_swapping_with_projection` - -We refactored `DataSource::try_swapping_with_projection` to simplify the method and minimize leakage across the ExecutionPlan <-> DataSource abstraction layer. -Reimplementation for any custom `DataSource` should be relatively straightforward, see [#17395] for more details. - -[#17395]: https://github.com/apache/datafusion/pull/17395/ - -### `FileOpenFuture` now uses `DataFusionError` instead of `ArrowError` - -The `FileOpenFuture` type alias has been updated to use `DataFusionError` instead of `ArrowError` for its error type. This change affects the `FileOpener` trait and any implementations that work with file streaming operations. - -**Before:** - -```rust,ignore -pub type FileOpenFuture = BoxFuture<'static, Result>>>; -``` - -**After:** - -```rust,ignore -pub type FileOpenFuture = BoxFuture<'static, Result>>>; -``` - -If you have custom implementations of `FileOpener` or work directly with `FileOpenFuture`, you'll need to update your error handling to use `DataFusionError` instead of `ArrowError`. The `FileStreamState` enum's `Open` variant has also been updated accordingly. See [#17397] for more details. - -[#17397]: https://github.com/apache/datafusion/pull/17397 - -### FFI user defined aggregate function signature change - -The Foreign Function Interface (FFI) signature for user defined aggregate functions -has been updated to call `return_field` instead of `return_type` on the underlying -aggregate function. This is to support metadata handling with these aggregate functions. -This change should be transparent to most users. If you have written unit tests to call -`return_type` directly, you may need to change them to calling `return_field` instead. - -This update is a breaking change to the FFI API. The current best practice when using the -FFI crate is to ensure that all libraries that are interacting are using the same -underlying Rust version. Issue [#17374] has been opened to discuss stabilization of -this interface so that these libraries can be used across different DataFusion versions. - -See [#17407] for details. - -[#17407]: https://github.com/apache/datafusion/pull/17407 -[#17374]: https://github.com/apache/datafusion/issues/17374 - -### Added `PhysicalExpr::is_volatile_node` - -We added a method to `PhysicalExpr` to mark a `PhysicalExpr` as volatile: - -```rust,ignore -impl PhysicalExpr for MyRandomExpr { - fn is_volatile_node(&self) -> bool { - true - } -} -``` - -We've shipped this with a default value of `false` to minimize breakage but we highly recommend that implementers of `PhysicalExpr` opt into a behavior, even if it is returning `false`. - -You can see more discussion and example implementations in [#17351]. - -[#17351]: https://github.com/apache/datafusion/pull/17351 +The upgrade guide for DataFusion 50.0.0 is in the +[documentation for DataFusion 50.0.0](https://datafusion.apache.org/versions/50.0.0/library-user-guide/upgrading.html#datafusion-50-0-0). diff --git a/docs/source/library-user-guide/upgrading/51.0.0.md b/docs/source/library-user-guide/upgrading/51.0.0.md index eae78f747e085..52f6c909d48bf 100644 --- a/docs/source/library-user-guide/upgrading/51.0.0.md +++ b/docs/source/library-user-guide/upgrading/51.0.0.md @@ -4,256 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 51.0.0 Upgrade Guide -## DataFusion 51.0.0 - -### `arrow` / `parquet` updated to 57.0.0 - -### Upgrade to arrow `57.0.0` and parquet `57.0.0` - -This version of DataFusion upgrades the underlying Apache Arrow implementation -to version `57.0.0`, including several dependent crates such as `prost`, -`tonic`, `pyo3`, and `substrait`. . See the [release -notes](https://github.com/apache/arrow-rs/releases/tag/57.0.0) for more details. - -### `MSRV` updated to 1.88.0 - -The Minimum Supported Rust Version (MSRV) has been updated to [`1.88.0`]. - -[`1.88.0`]: https://releases.rs/docs/1.88.0/ - -### `FunctionRegistry` exposes two additional methods - -`FunctionRegistry` exposes two additional methods `udafs` and `udwfs` which expose set of registered user defined aggregation and window function names. To upgrade implement methods returning set of registered function names: - -```diff -impl FunctionRegistry for FunctionRegistryImpl { - fn udfs(&self) -> HashSet { - self.scalar_functions.keys().cloned().collect() - } -+ fn udafs(&self) -> HashSet { -+ self.aggregate_functions.keys().cloned().collect() -+ } -+ -+ fn udwfs(&self) -> HashSet { -+ self.window_functions.keys().cloned().collect() -+ } -} -``` - -### `datafusion-proto` use `TaskContext` rather than `SessionContext` in physical plan serde methods - -There have been changes in the public API methods of `datafusion-proto` which handle physical plan serde. - -Methods like `physical_plan_from_bytes`, `parse_physical_expr` and similar, expect `TaskContext` instead of `SessionContext` - -```diff -- let plan2 = physical_plan_from_bytes(&bytes, &ctx)?; -+ let plan2 = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; -``` - -as `TaskContext` contains `RuntimeEnv` methods such as `try_into_physical_plan` will not have explicit `RuntimeEnv` parameter. - -```diff -let result_exec_plan: Arc = proto -- .try_into_physical_plan(&ctx, runtime.deref(), &composed_codec) -+. .try_into_physical_plan(&ctx.task_ctx(), &composed_codec) -``` - -`PhysicalExtensionCodec::try_decode()` expects `TaskContext` instead of `FunctionRegistry`: - -```diff -pub trait PhysicalExtensionCodec { - fn try_decode( - &self, - buf: &[u8], - inputs: &[Arc], -- registry: &dyn FunctionRegistry, -+ ctx: &TaskContext, - ) -> Result>; -``` - -See [issue #17601] for more details. - -[issue #17601]: https://github.com/apache/datafusion/issues/17601 - -### `SessionState`'s `sql_to_statement` method takes `Dialect` rather than a `str` - -The `dialect` parameter of `sql_to_statement` method defined in `datafusion::execution::session_state::SessionState` -has changed from `&str` to `&Dialect`. -`Dialect` is an enum defined in the `datafusion-common` -crate under the `config` module that provides type safety -and better validation for SQL dialect selection - -### Reorganization of `ListingTable` into `datafusion-catalog-listing` crate - -There has been a long standing request to remove features such as `ListingTable` -from the `datafusion` crate to support faster build times. The structs -`ListingOptions`, `ListingTable`, and `ListingTableConfig` are now available -within the `datafusion-catalog-listing` crate. These are re-exported in -the `datafusion` crate, so this should be a minimal impact to existing users. - -See [issue #14462] and [issue #17713] for more details. - -[issue #14462]: https://github.com/apache/datafusion/issues/14462 -[issue #17713]: https://github.com/apache/datafusion/issues/17713 - -### Reorganization of `ArrowSource` into `datafusion-datasource-arrow` crate - -To support [issue #17713] the `ArrowSource` code has been removed from -the `datafusion` core crate into it's own crate, `datafusion-datasource-arrow`. -This follows the pattern for the AVRO, CSV, JSON, and Parquet data sources. -Users may need to update their paths to account for these changes. - -See [issue #17713] for more details. - -### `FileScanConfig::projection` renamed to `FileScanConfig::projection_exprs` - -The `projection` field in `FileScanConfig` has been renamed to `projection_exprs` and its type has changed from `Option>` to `Option`. This change enables more powerful projection pushdown capabilities by supporting arbitrary physical expressions rather than just column indices. - -**Impact on direct field access:** - -If you directly access the `projection` field: - -```rust,ignore -let config: FileScanConfig = ...; -let projection = config.projection; -``` - -You should update to: - -```rust,ignore -let config: FileScanConfig = ...; -let projection_exprs = config.projection_exprs; -``` - -**Impact on builders:** - -The `FileScanConfigBuilder::with_projection()` method has been deprecated in favor of `with_projection_indices()`: - -```diff -let config = FileScanConfigBuilder::new(url, file_source) -- .with_projection(Some(vec![0, 2, 3])) -+ .with_projection_indices(Some(vec![0, 2, 3])) - .build(); -``` - -Note: `with_projection()` still works but is deprecated and will be removed in a future release. - -**What is `ProjectionExprs`?** - -`ProjectionExprs` is a new type that represents a list of physical expressions for projection. While it can be constructed from column indices (which is what `with_projection_indices` does internally), it also supports arbitrary physical expressions, enabling advanced features like expression evaluation during scanning. - -You can access column indices from `ProjectionExprs` using its methods if needed: - -```rust,ignore -let projection_exprs: ProjectionExprs = ...; -// Get the column indices if the projection only contains simple column references -let indices = projection_exprs.column_indices(); -``` - -### `DESCRIBE query` support - -`DESCRIBE query` was previously an alias for `EXPLAIN query`, which outputs the -_execution plan_ of the query. With this release, `DESCRIBE query` now outputs -the computed _schema_ of the query, consistent with the behavior of `DESCRIBE table_name`. - -### `datafusion.execution.time_zone` default configuration changed - -The default value for `datafusion.execution.time_zone` previously was a string value of `+00:00` (GMT/Zulu time). -This was changed to be an `Option` with a default of `None`. If you want to change the timezone back -to the previous value you can execute the sql: - -```sql -SET -TIMEZONE = '+00:00'; -``` - -This change was made to better support using the default timezone in scalar UDF functions such as -`now`, `current_date`, `current_time`, and `to_timestamp` among others. - -### Introduction of `TableSchema` and changes to `FileSource::with_schema()` method - -A new `TableSchema` struct has been introduced in the `datafusion-datasource` crate to better manage table schemas with partition columns. This struct helps distinguish between: - -- **File schema**: The schema of actual data files on disk -- **Partition columns**: Columns derived from directory structure (e.g., Hive-style partitioning) -- **Table schema**: The complete schema combining both file and partition columns - -As part of this change, the `FileSource::with_schema()` method signature has changed from accepting a `SchemaRef` to accepting a `TableSchema`. - -**Who is affected:** - -- Users who have implemented custom `FileSource` implementations will need to update their code -- Users who only use built-in file sources (Parquet, CSV, JSON, AVRO, Arrow) are not affected - -**Migration guide for custom `FileSource` implementations:** - -```diff - use datafusion_datasource::file::FileSource; --use arrow::datatypes::SchemaRef; -+use datafusion_datasource::TableSchema; - - impl FileSource for MyCustomSource { -- fn with_schema(&self, schema: SchemaRef) -> Arc { -+ fn with_schema(&self, schema: TableSchema) -> Arc { - Arc::new(Self { -- schema: Some(schema), -+ // Use schema.file_schema() to get the file schema without partition columns -+ schema: Some(Arc::clone(schema.file_schema())), - ..self.clone() - }) - } - } -``` - -For implementations that need access to partition columns: - -```rust,ignore -fn with_schema(&self, schema: TableSchema) -> Arc { - Arc::new(Self { - file_schema: Arc::clone(schema.file_schema()), - partition_cols: schema.table_partition_cols().clone(), - table_schema: Arc::clone(schema.table_schema()), - ..self.clone() - }) -} -``` - -**Note**: Most `FileSource` implementations only need to store the file schema (without partition columns), as shown in the first example. The second pattern of storing all three schema components is typically only needed for advanced use cases where you need access to different schema representations for different operations (e.g., ParquetSource uses the file schema for building pruning predicates but needs the table schema for filter pushdown logic). - -**Using `TableSchema` directly:** - -If you're constructing a `FileScanConfig` or working with table schemas and partition columns, you can now use `TableSchema`: - -```rust -use datafusion_datasource::TableSchema; -use arrow::datatypes::{Schema, Field, DataType}; -use std::sync::Arc; - -// Create a TableSchema with partition columns -let file_schema = Arc::new(Schema::new(vec![ - Field::new("user_id", DataType::Int64, false), - Field::new("amount", DataType::Float64, false), -])); - -let partition_cols = vec![ - Arc::new(Field::new("date", DataType::Utf8, false)), - Arc::new(Field::new("region", DataType::Utf8, false)), -]; - -let table_schema = TableSchema::new(file_schema, partition_cols); - -// Access different schema representations -let file_schema_ref = table_schema.file_schema(); // Schema without partition columns -let full_schema = table_schema.table_schema(); // Complete schema with partition columns -let partition_cols_ref = table_schema.table_partition_cols(); // Just the partition columns -``` - -### `AggregateUDFImpl::is_ordered_set_aggregate` has been renamed to `AggregateUDFImpl::supports_within_group_clause` - -This method has been renamed to better reflect the actual impact it has for aggregate UDF implementations. -The accompanying `AggregateUDF::is_ordered_set_aggregate` has also been renamed to `AggregateUDF::supports_within_group_clause`. -No functionality has been changed with regards to this method; it still refers only to permitting use of `WITHIN GROUP` -SQL syntax for the aggregate function. +The upgrade guide for DataFusion 51.0.0 is in the +[documentation for DataFusion 51.0.0](https://datafusion.apache.org/versions/51.0.0/library-user-guide/upgrading.html#datafusion-51-0-0). diff --git a/docs/source/library-user-guide/upgrading/52.0.0.md b/docs/source/library-user-guide/upgrading/52.0.0.md index 151c0e2ab408e..ee22a8b931f3c 100644 --- a/docs/source/library-user-guide/upgrading/52.0.0.md +++ b/docs/source/library-user-guide/upgrading/52.0.0.md @@ -4,653 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 52.0.0 Upgrade Guide -## DataFusion 52.0.0 - -### Changes to DFSchema API - -To permit more efficient planning, several methods on `DFSchema` have been -changed to return references to the underlying [`&FieldRef`] rather than -[`&Field`]. This allows planners to more cheaply copy the references via -`Arc::clone` rather than cloning the entire `Field` structure. - -You may need to change code to use `Arc::clone` instead of `.as_ref().clone()` -directly on the `Field`. For example: - -```diff -- let field = df_schema.field("my_column").as_ref().clone(); -+ let field = Arc::clone(df_schema.field("my_column")); -``` - -### ListingTableProvider now caches `LIST` commands - -In prior versions, `ListingTableProvider` would issue `LIST` commands to -the underlying object store each time it needed to list files for a query. -To improve performance, `ListingTableProvider` now caches the results of -`LIST` commands for the lifetime of the `ListingTableProvider` instance or -until a cache entry expires. - -Note that by default the cache has no expiration time, so if files are added or removed -from the underlying object store, the `ListingTableProvider` will not see -those changes until the `ListingTableProvider` instance is dropped and recreated. - -You can configure the maximum cache size and cache entry expiration time via configuration options: - -- `datafusion.runtime.list_files_cache_limit` - Limits the size of the cache in bytes -- `datafusion.runtime.list_files_cache_ttl` - Limits the TTL (time-to-live) of an entry in minutes and/or seconds - -Detailed configuration information can be found in the [DataFusion Runtime -Configuration](https://datafusion.apache.org/user-guide/configs.html#runtime-configuration-settings) user's guide. - -Caching can be disabled by setting the limit to 0: - -```sql -SET datafusion.runtime.list_files_cache_limit TO "0K"; -``` - -Note that the internal API has changed to use a trait `ListFilesCache` instead of a type alias. - -### `newlines_in_values` moved from `FileScanConfig` to `CsvOptions` - -The CSV-specific `newlines_in_values` configuration option has been moved from `FileScanConfig` to `CsvOptions`, as it only applies to CSV file parsing. - -**Who is affected:** - -- Users who set `newlines_in_values` via `FileScanConfigBuilder::with_newlines_in_values()` - -**Migration guide:** - -Set `newlines_in_values` in `CsvOptions` instead of on `FileScanConfigBuilder`: - -**Before:** - -```rust,ignore -let source = Arc::new(CsvSource::new(file_schema.clone())); -let config = FileScanConfigBuilder::new(object_store_url, source) - .with_newlines_in_values(true) - .build(); -``` - -**After:** - -```rust,ignore -let options = CsvOptions { - newlines_in_values: Some(true), - ..Default::default() -}; -let source = Arc::new(CsvSource::new(file_schema.clone()) - .with_csv_options(options)); -let config = FileScanConfigBuilder::new(object_store_url, source) - .build(); -``` - -### Removal of `pyarrow` feature - -The `pyarrow` feature flag has been removed. This feature has been migrated to -the `datafusion-python` repository since version `44.0.0`. - -### Refactoring of `FileSource` constructors and `FileScanConfigBuilder` to accept schemas upfront - -The way schemas are passed to file sources and scan configurations has been significantly refactored. File sources now require the schema (including partition columns) to be provided at construction time, and `FileScanConfigBuilder` no longer takes a separate schema parameter. - -**Who is affected:** - -- Users who create `FileScanConfig` or file sources (`ParquetSource`, `CsvSource`, `JsonSource`, `AvroSource`) directly -- Users who implement custom `FileFormat` implementations - -**Key changes:** - -1. **FileSource constructors now require TableSchema**: All built-in file sources now take the schema in their constructor: - - ```diff - - let source = ParquetSource::default(); - + let source = ParquetSource::new(table_schema); - ``` - -2. **FileScanConfigBuilder no longer takes schema as a parameter**: The schema is now passed via the FileSource: - - ```diff - - FileScanConfigBuilder::new(url, schema, source) - + FileScanConfigBuilder::new(url, source) - ``` - -3. **Partition columns are now part of TableSchema**: The `with_table_partition_cols()` method has been removed from `FileScanConfigBuilder`. Partition columns are now passed as part of the `TableSchema` to the FileSource constructor: - - ```diff - + let table_schema = TableSchema::new( - + file_schema, - + vec![Arc::new(Field::new("date", DataType::Utf8, false))], - + ); - + let source = ParquetSource::new(table_schema); - let config = FileScanConfigBuilder::new(url, source) - - .with_table_partition_cols(vec![Field::new("date", DataType::Utf8, false)]) - .with_file(partitioned_file) - .build(); - ``` - -4. **FileFormat::file_source() now takes TableSchema parameter**: Custom `FileFormat` implementations must be updated: - ```diff - impl FileFormat for MyFileFormat { - - fn file_source(&self) -> Arc { - + fn file_source(&self, table_schema: TableSchema) -> Arc { - - Arc::new(MyFileSource::default()) - + Arc::new(MyFileSource::new(table_schema)) - } - } - ``` - -**Migration examples:** - -For Parquet files: - -```diff -- let source = Arc::new(ParquetSource::default()); -- let config = FileScanConfigBuilder::new(url, schema, source) -+ let table_schema = TableSchema::new(schema, vec![]); -+ let source = Arc::new(ParquetSource::new(table_schema)); -+ let config = FileScanConfigBuilder::new(url, source) - .with_file(partitioned_file) - .build(); -``` - -For CSV files with partition columns: - -```diff -- let source = Arc::new(CsvSource::new(true, b',', b'"')); -- let config = FileScanConfigBuilder::new(url, file_schema, source) -- .with_table_partition_cols(vec![Field::new("year", DataType::Int32, false)]) -+ let options = CsvOptions { -+ has_header: Some(true), -+ delimiter: b',', -+ quote: b'"', -+ ..Default::default() -+ }; -+ let table_schema = TableSchema::new( -+ file_schema, -+ vec![Arc::new(Field::new("year", DataType::Int32, false))], -+ ); -+ let source = Arc::new(CsvSource::new(table_schema).with_csv_options(options)); -+ let config = FileScanConfigBuilder::new(url, source) - .build(); -``` - -### Adaptive filter representation in Parquet filter pushdown - -As of Arrow 57.1.0, DataFusion uses a new adaptive filter strategy when -evaluating pushed down filters for Parquet files. This new strategy improves -performance for certain types of queries where the results of filtering are -more efficiently represented with a bitmask rather than a selection. -See [arrow-rs #5523] for more details. - -This change only applies to the built-in Parquet data source with filter-pushdown enabled ( -which is [not yet the default behavior]). - -You can disable the new behavior by setting the -`datafusion.execution.parquet.force_filter_selections` [configuration setting] to true. - -```sql -> set datafusion.execution.parquet.force_filter_selections = true; -``` - -[arrow-rs #5523]: https://github.com/apache/arrow-rs/issues/5523 -[configuration setting]: https://datafusion.apache.org/user-guide/configs.html -[not yet the default behavior]: https://github.com/apache/datafusion/issues/3463 - -### Statistics handling moved from `FileSource` to `FileScanConfig` - -Statistics are now managed directly by `FileScanConfig` instead of being delegated to `FileSource` implementations. This simplifies the `FileSource` trait and provides more consistent statistics handling across all file formats. - -**Who is affected:** - -- Users who have implemented custom `FileSource` implementations - -**Breaking changes:** - -Two methods have been removed from the `FileSource` trait: - -- `with_statistics(&self, statistics: Statistics) -> Arc` -- `statistics(&self) -> Result` - -**Migration guide:** - -If you have a custom `FileSource` implementation, you need to: - -1. Remove the `with_statistics` method implementation -2. Remove the `statistics` method implementation -3. Remove any internal state that was storing statistics - -**Before:** - -```rust,ignore -#[derive(Clone)] -struct MyCustomSource { - table_schema: TableSchema, - projected_statistics: Option, - // other fields... -} - -impl FileSource for MyCustomSource { - fn with_statistics(&self, statistics: Statistics) -> Arc { - Arc::new(Self { - table_schema: self.table_schema.clone(), - projected_statistics: Some(statistics), - // other fields... - }) - } - - fn statistics(&self) -> Result { - Ok(self.projected_statistics.clone().unwrap_or_else(|| - Statistics::new_unknown(self.table_schema.file_schema()) - )) - } - - // other methods... -} -``` - -**After:** - -```rust,ignore -#[derive(Clone)] -struct MyCustomSource { - table_schema: TableSchema, - // projected_statistics field removed - // other fields... -} - -impl FileSource for MyCustomSource { - // with_statistics method removed - // statistics method removed - - // other methods... -} -``` - -**Accessing statistics:** - -Statistics are now accessed through `FileScanConfig` instead of `FileSource`: - -```diff -- let stats = config.file_source.statistics()?; -+ let stats = config.statistics(); -``` - -Note that `FileScanConfig::statistics()` automatically marks statistics as inexact when filters are present, ensuring correctness when filters are pushed down. - -### Partition column handling moved out of `PhysicalExprAdapter` - -Partition column replacement is now a separate preprocessing step performed before expression rewriting via `PhysicalExprAdapter`. This change provides better separation of concerns and makes the adapter more focused on schema differences rather than partition value substitution. - -**Who is affected:** - -- Users who have custom implementations of `PhysicalExprAdapterFactory` that handle partition columns -- Users who directly use the `FilePruner` API - -**Breaking changes:** - -1. `FilePruner::try_new()` signature changed: the `partition_fields` parameter has been removed since partition column handling is now done separately -2. Partition column replacement must now be done via `replace_columns_with_literals()` before expressions are passed to the adapter - -**Migration guide:** - -If you have code that creates a `FilePruner` with partition fields: - -**Before:** - -```rust,ignore -use datafusion_pruning::FilePruner; - -let pruner = FilePruner::try_new( - predicate, - file_schema, - partition_fields, // This parameter is removed - file_stats, -)?; -``` - -**After:** - -```rust,ignore -use datafusion_pruning::FilePruner; - -// Partition fields are no longer needed -let pruner = FilePruner::try_new( - predicate, - file_schema, - file_stats, -)?; -``` - -If you have custom code that relies on `PhysicalExprAdapter` to handle partition columns, you must now call `replace_columns_with_literals()` separately: - -**Before:** - -```rust,ignore -// Adapter handled partition column replacement internally -let adapted_expr = adapter.rewrite(expr)?; -``` - -**After:** - -```rust,ignore -use datafusion_physical_expr_adapter::replace_columns_with_literals; - -// Replace partition columns first -let expr_with_literals = replace_columns_with_literals(expr, &partition_values)?; -// Then apply the adapter -let adapted_expr = adapter.rewrite(expr_with_literals)?; -``` - -### `build_row_filter` signature simplified - -The `build_row_filter` function in `datafusion-datasource-parquet` has been simplified to take a single schema parameter instead of two. -The expectation is now that the filter has been adapted to the physical file schema (the arrow representation of the parquet file's schema) before being passed to this function -using a `PhysicalExprAdapter` for example. - -**Who is affected:** - -- Users who call `build_row_filter` directly - -**Breaking changes:** - -The function signature changed from: - -```rust,ignore -pub fn build_row_filter( - expr: &Arc, - physical_file_schema: &SchemaRef, - predicate_file_schema: &SchemaRef, // removed - metadata: &ParquetMetaData, - reorder_predicates: bool, - file_metrics: &ParquetFileMetrics, -) -> Result> -``` - -To: - -```rust,ignore -pub fn build_row_filter( - expr: &Arc, - file_schema: &SchemaRef, - metadata: &ParquetMetaData, - reorder_predicates: bool, - file_metrics: &ParquetFileMetrics, -) -> Result> -``` - -**Migration guide:** - -Remove the duplicate schema parameter from your call: - -```diff -- build_row_filter(&predicate, &file_schema, &file_schema, metadata, reorder, metrics) -+ build_row_filter(&predicate, &file_schema, metadata, reorder, metrics) -``` - -### Planner now requires explicit opt-in for WITHIN GROUP syntax - -The SQL planner now enforces the aggregate UDF contract more strictly: the -`WITHIN GROUP (ORDER BY ...)` syntax is accepted only if the aggregate UDAF -explicitly advertises support by returning `true` from -`AggregateUDFImpl::supports_within_group_clause()`. - -Previously the planner forwarded a `WITHIN GROUP` clause to order-sensitive -aggregates even when they did not implement ordered-set semantics, which could -cause queries such as `SUM(x) WITHIN GROUP (ORDER BY x)` to plan successfully. -This behavior was too permissive and has been changed to match PostgreSQL and -the documented semantics. - -Migration: If your UDAF intentionally implements ordered-set semantics and -wants to accept the `WITHIN GROUP` SQL syntax, update your implementation to -return `true` from `supports_within_group_clause()` and handle the ordering -semantics in your accumulator implementation. If your UDAF is merely -order-sensitive (but not an ordered-set aggregate), do not advertise -`supports_within_group_clause()` and clients should use alternative function -signatures (for example, explicit ordering as a function argument) instead. - -### `AggregateUDFImpl::supports_null_handling_clause` now defaults to `false` - -This method specifies whether an aggregate function allows `IGNORE NULLS`/`RESPECT NULLS` -during SQL parsing, with the implication it respects these configs during computation. - -Most DataFusion aggregate functions silently ignored this syntax in prior versions -as they did not make use of it and it was permitted by default. We change this so -only the few functions which do respect this clause (e.g. `array_agg`, `first_value`, -`last_value`) need to implement it. - -Custom user defined aggregate functions will also error if this syntax is used, -unless they explicitly declare support by overriding the method. - -For example, SQL parsing will now fail for queries such as this: - -```sql -SELECT median(c1) IGNORE NULLS FROM table -``` - -Instead of silently succeeding. - -### API change for `CacheAccessor` trait - -The remove API no longer requires a mutable instance - -### FFI crate updates - -Many of the structs in the `datafusion-ffi` crate have been updated to allow easier -conversion to the underlying trait types they represent. This simplifies some code -paths, but also provides an additional improvement in cases where library code goes -through a round trip via the foreign function interface. - -To update your code, suppose you have a `FFI_SchemaProvider` called `ffi_provider` -and you wish to use this as a `SchemaProvider`. In the old approach you would do -something like: - -```rust,ignore - let foreign_provider: ForeignSchemaProvider = ffi_provider.into(); - let foreign_provider = Arc::new(foreign_provider) as Arc; -``` - -This code should now be written as: - -```rust,ignore - let foreign_provider: Arc = ffi_provider.into(); - let foreign_provider = foreign_provider as Arc; -``` - -For the case of user defined functions, the updates are similar but you -may need to change the way you call the creation of the `ScalarUDF`. -Aggregate and window functions follow the same pattern. - -Previously you may write: - -```rust,ignore - let foreign_udf: ForeignScalarUDF = ffi_udf.try_into()?; - let foreign_udf: ScalarUDF = foreign_udf.into(); -``` - -Instead this should now be: - -```rust,ignore - let foreign_udf: Arc = ffi_udf.into(); - let foreign_udf = ScalarUDF::new_from_shared_impl(foreign_udf); -``` - -When creating any of the following structs, we now require the user to -provide a `TaskContextProvider` and optionally a `LogicalExtensionCodec`: - -- `FFI_CatalogListProvider` -- `FFI_CatalogProvider` -- `FFI_SchemaProvider` -- `FFI_TableProvider` -- `FFI_TableFunction` - -Each of these structs has a `new()` and a `new_with_ffi_codec()` method for -instantiation. For example, when you previously would write - -```rust,ignore - let table = Arc::new(MyTableProvider::new()); - let ffi_table = FFI_TableProvider::new(table, None); -``` - -Now you will need to provide a `TaskContextProvider`. The most common -implementation of this trait is `SessionContext`. - -```rust,ignore - let ctx = Arc::new(SessionContext::default()); - let table = Arc::new(MyTableProvider::new()); - let ffi_table = FFI_TableProvider::new(table, None, ctx, None); -``` - -The alternative function to create these structures may be more convenient -if you are doing many of these operations. A `FFI_LogicalExtensionCodec` will -store the `TaskContextProvider` as well. - -```rust,ignore - let codec = Arc::new(DefaultLogicalExtensionCodec {}); - let ctx = Arc::new(SessionContext::default()); - let ffi_codec = FFI_LogicalExtensionCodec::new(codec, None, ctx); - let table = Arc::new(MyTableProvider::new()); - let ffi_table = FFI_TableProvider::new_with_ffi_codec(table, None, ffi_codec); -``` - -Additional information about the usage of the `TaskContextProvider` can be -found in the crate README. - -Additionally, the FFI structure for Scalar UDF's no longer contains a -`return_type` call. This code was not used since the `ForeignScalarUDF` -struct implements the `return_field_from_args` instead. - -### Projection handling moved from FileScanConfig to FileSource - -Projection handling has been moved from `FileScanConfig` into `FileSource` implementations. This enables format-specific projection pushdown (e.g., Parquet can push down struct field access, Vortex can push down computed expressions into un-decoded data). - -**Who is affected:** - -- Users who have implemented custom `FileSource` implementations -- Users who use `FileScanConfigBuilder::with_projection_indices` directly - -**Breaking changes:** - -1. **`FileSource::with_projection` replaced with `try_pushdown_projection`:** - - The `with_projection(&self, config: &FileScanConfig) -> Arc` method has been removed and replaced with `try_pushdown_projection(&self, projection: &ProjectionExprs) -> Result>>`. - -2. **`FileScanConfig.projection_exprs` field removed:** - - Projections are now stored in the `FileSource` directly, not in `FileScanConfig`. - Various public helper methods that access projection information have been removed from `FileScanConfig`. - -3. **`FileScanConfigBuilder::with_projection_indices` now returns `Result`:** - - This method can now fail if the projection pushdown fails. - -4. **`FileSource::create_file_opener` now returns `Result>`:** - - Previously returned `Arc` directly. - Any `FileSource` implementation that may fail to create a `FileOpener` should now return an appropriate error. - -5. **`DataSource::try_swapping_with_projection` signature changed:** - - Parameter changed from `&[ProjectionExpr]` to `&ProjectionExprs`. - -**Migration guide:** - -If you have a custom `FileSource` implementation: - -**Before:** - -```rust,ignore -impl FileSource for MyCustomSource { - fn with_projection(&self, config: &FileScanConfig) -> Arc { - // Apply projection from config - Arc::new(Self { /* ... */ }) - } - - fn create_file_opener( - &self, - object_store: Arc, - base_config: &FileScanConfig, - partition: usize, - ) -> Arc { - Arc::new(MyOpener { /* ... */ }) - } -} -``` - -**After:** - -```rust,ignore -impl FileSource for MyCustomSource { - fn try_pushdown_projection( - &self, - projection: &ProjectionExprs, - ) -> Result>> { - // Return None if projection cannot be pushed down - // Return Some(new_source) with projection applied if it can - Ok(Some(Arc::new(Self { - projection: Some(projection.clone()), - /* ... */ - }))) - } - - fn projection(&self) -> Option<&ProjectionExprs> { - self.projection.as_ref() - } - - fn create_file_opener( - &self, - object_store: Arc, - base_config: &FileScanConfig, - partition: usize, - ) -> Result> { - Ok(Arc::new(MyOpener { /* ... */ })) - } -} -``` - -We recommend you look at [#18627](https://github.com/apache/datafusion/pull/18627) -that introduced these changes for more examples for how this was handled for the various built in file sources. - -We have added [`SplitProjection`](https://docs.rs/datafusion-datasource/latest/datafusion_datasource/projection/struct.SplitProjection.html) and [`ProjectionOpener`](https://docs.rs/datafusion-datasource/latest/datafusion_datasource/projection/struct.ProjectionOpener.html) helpers to make it easier to handle projections in your `FileSource` implementations. - -For file sources that can only handle simple column selections (not computed expressions), use the `SplitProjection` and `ProjectionOpener` helpers to split the projection into pushdownable and non-pushdownable parts: - -```rust,ignore -use datafusion_datasource::projection::{SplitProjection, ProjectionOpener}; - -// In try_pushdown_projection: -let split = SplitProjection::new(projection, self.table_schema())?; -// Use split.file_projection() for what to push down to the file format -// The ProjectionOpener wrapper will handle the rest -``` - -**For `FileScanConfigBuilder` users:** - -```diff -let config = FileScanConfigBuilder::new(url, source) -- .with_projection_indices(Some(vec![0, 2, 3])) -+ .with_projection_indices(Some(vec![0, 2, 3]))? - .build(); -``` - -### `SchemaAdapter` and `SchemaAdapterFactory` completely removed - -Following the deprecation announced in [DataFusion 49.0.0](49.0.0.md#deprecating-schemaadapterfactory-and-schemaadapter), `SchemaAdapterFactory` has been fully removed from Parquet scanning. This applies to both: - -The following symbols have been deprecated and will be removed in the next release: - -- `SchemaAdapter` trait -- `SchemaAdapterFactory` trait -- `SchemaMapper` trait -- `SchemaMapping` struct -- `DefaultSchemaAdapterFactory` struct - -These types were previously used to adapt record batch schemas during file reading. -This functionality has been replaced by `PhysicalExprAdapterFactory`, which rewrites expressions at planning time rather than transforming batches at runtime. -If you were using a custom `SchemaAdapterFactory` for schema adaptation (e.g., default column values, type coercion), you should now implement `PhysicalExprAdapterFactory` instead. -See the [default column values example](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/custom_data_source/default_column_values.rs) for how to implement a custom `PhysicalExprAdapterFactory`. - -**Migration guide:** - -If you implemented a custom `SchemaAdapterFactory`, migrate to `PhysicalExprAdapterFactory`. -See the [default column values example](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/custom_data_source/default_column_values.rs) for a complete implementation. +The upgrade guide for DataFusion 52.0.0 is in the +[documentation for DataFusion 52.0.0](https://datafusion.apache.org/versions/52.0.0/library-user-guide/upgrading.html#datafusion-52-0-0). diff --git a/docs/source/library-user-guide/upgrading/53.0.0.md b/docs/source/library-user-guide/upgrading/53.0.0.md index 7923676e29b6e..078c81ee4b91f 100644 --- a/docs/source/library-user-guide/upgrading/53.0.0.md +++ b/docs/source/library-user-guide/upgrading/53.0.0.md @@ -4,535 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 53.0.0 Upgrade Guide -## DataFusion 53.0.0 - -### Upgrade arrow/parquet to 58.0.0 and object_store to 0.13.0 - -DataFusion 53.0.0 uses `arrow` and `parquet` 58.0.0, and `object_store` 0.13.0. -This may require updates to your Cargo.toml if you have direct dependencies on -these crates. - -See the [Arrow 58.0.0 release notes] and the [object_store 0.13.0 upgrade guide] for details on breaking changes in those versions. - -[arrow 58.0.0 release notes]: https://github.com/apache/arrow-rs/releases/tag/58.0.0 -[object_store 0.13.0 upgrade guide]: https://github.com/apache/arrow-rs-object-store/blob/v0.13.0/CHANGELOG.md - -### `ExecutionPlan::statistics` removed - -The deprecated `ExecutionPlan::statistics()` method has been removed. If you -implement custom `ExecutionPlan`s, remove that method from your impl and -implement `partition_statistics()` instead. - -**Before:** - -```rust,ignore -impl ExecutionPlan for MyExec { - // ... - - fn statistics(&self) -> Result { - Ok(Statistics::new_unknown(&self.schema())) - } -} -``` - -**After:** - -```rust,ignore -impl ExecutionPlan for MyExec { - // ... - - fn partition_statistics(&self, _partition: Option) -> Result { - Ok(Statistics::new_unknown(&self.schema())) - } -} -``` - -If you do not have partition-specific statistics, return the same value for -`None` and for any partition index. - -### `ExecutionPlan::properties` now returns `&Arc` - -Now `ExecutionPlan::properties()` returns `&Arc` instead of a -reference. This make it possible to cheaply clone properties and reuse them across multiple -`ExecutionPlans`. It also makes it possible to optimize [`ExecutionPlan::with_new_children`] -to reuse properties when the children plans have not changed, which can significantly reduce -planning time for complex queries. - -[`ExecutionPlan::with_new_children`](https://docs.rs/datafusion/latest/datafusion/physical_plan/trait.ExecutionPlan.html#tymethod.with_new_children) - -To migrate, in all `ExecutionPlan` implementations, you will likely need to wrap -stored `PlanProperties` in an `Arc`: - -```diff -- cache: PlanProperties, -+ cache: Arc, - -... - -- fn properties(&self) -> &PlanProperties { -+ fn properties(&self) -> &Arc { - &self.cache - } -``` - -To improve performance of `with_new_children` for custom `ExecutionPlan` -implementations, you can use the new macro: `check_if_same_properties`. For it -to work, you need to implement the function: -`with_new_children_and_same_properties` with semantics identical to -`with_new_children`, but operating under the assumption that the properties of -the children plans have not changed. - -An example of supporting this optimization for `ProjectionExec`: - -```diff - impl ProjectionExec { -+ fn with_new_children_and_same_properties( -+ &self, -+ mut children: Vec>, -+ ) -> Self { -+ Self { -+ input: children.swap_remove(0), -+ metrics: ExecutionPlanMetricsSet::new(), -+ ..Self::clone(self) -+ } -+ } - } - - impl ExecutionPlan for ProjectionExec { - fn with_new_children( - self: Arc, - mut children: Vec>, - ) -> Result> { -+ check_if_same_properties!(self, children); - ProjectionExec::try_new( - self.projector.projection().into_iter().cloned(), - children.swap_remove(0), - ) - .map(|p| Arc::new(p) as _) - } - } -``` - -### `PlannerContext` outer query schema API now uses a stack - -`PlannerContext` no longer stores a single `outer_query_schema`. It now tracks a -stack of outer relation schemas so nested subqueries can access non-adjacent -outer relations. - -**Before:** - -```rust,ignore -let old_outer_query_schema = - planner_context.set_outer_query_schema(Some(input_schema.clone().into())); -let sub_plan = self.query_to_plan(subquery, planner_context)?; -planner_context.set_outer_query_schema(old_outer_query_schema); -``` - -**After:** - -```rust,ignore -planner_context.append_outer_query_schema(input_schema.clone().into()); -let sub_plan = self.query_to_plan(subquery, planner_context)?; -planner_context.pop_outer_query_schema(); -``` - -### `HashJoinExec::try_new` adds `null_aware` - -`HashJoinExec::try_new` now takes an extra `null_aware: bool` argument. This -flag is used for null-aware anti joins, such as plans generated for `NOT IN` -subqueries. - -Most callers should pass `false`, the previous behavior. Pass `true` only for null-aware -`JoinType::LeftAnti` joins. - -### `FileSinkConfig` adds `file_output_mode` - -`FileSinkConfig` now includes a `file_output_mode: FileOutputMode` field to control -single-file vs directory output behavior. Any code constructing `FileSinkConfig` via struct -literals must initialize this field. - -The `FileOutputMode` enum has three variants: - -- `Automatic` (default): Infer output mode from the URL (extension/trailing `/` heuristic) -- `SingleFile`: Write to a single file at the exact output path -- `Directory`: Write to a directory with generated filenames - -**Before:** - -```rust,ignore -FileSinkConfig { - // ... - file_extension: "parquet".into(), -} -``` - -**After:** - -```rust,ignore -use datafusion_datasource::file_sink_config::FileOutputMode; - -FileSinkConfig { - // ... - file_extension: "parquet".into(), - file_output_mode: FileOutputMode::Automatic, -} -``` - -### `SimplifyInfo` trait removed, `SimplifyContext` now uses builder-style API - -The `SimplifyInfo` trait has been removed and replaced with the concrete `SimplifyContext` struct. This simplifies the expression simplification API and removes the need for trait objects. - -**Who is affected:** - -- Users who implemented custom `SimplifyInfo` implementations -- Users who implemented `ScalarUDFImpl::simplify()` for custom scalar functions -- Users who directly use `SimplifyContext` or `ExprSimplifier` - -**Breaking changes:** - -1. The `SimplifyInfo` trait has been removed entirely -2. `SimplifyContext` no longer takes `&ExecutionProps` - it now uses a builder-style API with direct fields -3. `ScalarUDFImpl::simplify()` now takes `&SimplifyContext` instead of `&dyn SimplifyInfo` -4. Time-dependent function simplification (e.g., `now()`) is now optional - if `query_execution_start_time` is `None`, these functions won't be simplified - -**Migration guide:** - -If you implemented a custom `SimplifyInfo`: - -**Before:** - -```rust,ignore -impl SimplifyInfo for MySimplifyInfo { - fn is_boolean_type(&self, expr: &Expr) -> Result { ... } - fn nullable(&self, expr: &Expr) -> Result { ... } - fn execution_props(&self) -> &ExecutionProps { ... } - fn get_data_type(&self, expr: &Expr) -> Result { ... } -} -``` - -**After:** - -Use `SimplifyContext` directly with the builder-style API: - -```rust,ignore -let context = SimplifyContext::default() - .with_schema(schema) - .with_config_options(config_options) - .with_query_execution_start_time(Some(Utc::now())); // or use .with_current_time() -``` - -If you implemented `ScalarUDFImpl::simplify()`: - -**Before:** - -```rust,ignore -fn simplify( - &self, - args: Vec, - info: &dyn SimplifyInfo, -) -> Result { - let now_ts = info.execution_props().query_execution_start_time; - // ... -} -``` - -**After:** - -```rust,ignore -fn simplify( - &self, - args: Vec, - info: &SimplifyContext, -) -> Result { - // query_execution_start_time is now Option> - // Return Original if time is not set (simplification skipped) - let Some(now_ts) = info.query_execution_start_time() else { - return Ok(ExprSimplifyResult::Original(args)); - }; - // ... -} -``` - -If you created `SimplifyContext` from `ExecutionProps`: - -**Before:** - -```rust,ignore -let props = ExecutionProps::new(); -let context = SimplifyContext::new(&props).with_schema(schema); -``` - -**After:** - -```rust,ignore -let context = SimplifyContext::default() - .with_schema(schema) - .with_config_options(config_options) - .with_current_time(); // Sets query_execution_start_time to Utc::now() -``` - -See [`SimplifyContext` documentation](https://docs.rs/datafusion-expr/latest/datafusion_expr/simplify/struct.SimplifyContext.html) for more details. - -### Struct Casting Now Requires Field Name Overlap - -DataFusion's struct casting mechanism previously allowed casting between structs with differing field names if the field counts matched. This "positional fallback" behavior could silently misalign fields and cause data corruption. - -**Breaking Change:** - -Starting with DataFusion 53.0.0, struct casts now require **at least one overlapping field name** between the source and target structs. Casts without field name overlap are rejected at plan time with a clear error message. - -**Who is affected:** - -- Applications that cast between structs with no overlapping field names -- Queries that rely on positional struct field mapping (e.g., casting `struct(x, y)` to `struct(a, b)` based solely on position) -- Code that constructs or transforms struct columns programmatically - -**Migration guide:** - -If you encounter an error like: - -```text -Cannot cast struct with 2 fields to 2 fields because there is no field name overlap -``` - -You must explicitly rename or map fields to ensure at least one field name matches. Here are common patterns: - -**Example 1: Source and target field names already match (Name-based casting)** - -**Success case (field names align):** - -```sql --- source_col has schema: STRUCT --- Casting to the same field names succeeds (no-op or type validation only) -SELECT CAST(source_col AS STRUCT) FROM table1; -``` - -**Example 2: Source and target field names differ (Migration scenario)** - -**What fails now (no field name overlap):** - -```sql --- source_col has schema: STRUCT --- This FAILS because there is no field name overlap: --- ❌ SELECT CAST(source_col AS STRUCT) FROM table1; --- Error: Cannot cast struct with 2 fields to 2 fields because there is no field name overlap -``` - -**Migration options (must align names):** - -**Option A: Use struct constructor for explicit field mapping** - -```sql --- source_col has schema: STRUCT --- Use STRUCT_CONSTRUCT with explicit field names -SELECT STRUCT_CONSTRUCT( - 'x', source_col.a, - 'y', source_col.b -) AS renamed_struct FROM table1; -``` - -**Option B: Rename in the cast target to match source names** - -```sql --- source_col has schema: STRUCT --- Cast to target with matching field names -SELECT CAST(source_col AS STRUCT) FROM table1; -``` - -**Example 3: Using struct constructors in Rust API** - -If you need to map fields programmatically, build the target struct explicitly: - -```rust,ignore -// Build the target struct with explicit field names -let target_struct_type = DataType::Struct(vec![ - FieldRef::new("x", DataType::Int32), - FieldRef::new("y", DataType::Utf8), -]); - -// Use struct constructors rather than casting for field mapping -// This makes the field mapping explicit and unambiguous -// Use struct builders or row constructors that preserve your mapping logic -``` - -**Why this change:** - -1. **Safety:** Field names are now the primary contract for struct compatibility -2. **Explicitness:** Prevents silent data misalignment caused by positional assumptions -3. **Consistency:** Matches DuckDB's behavior and aligns with other SQL engines that enforce name-based matching -4. **Debuggability:** Errors now appear at plan time rather than as silent data corruption - -See [Issue #19841](https://github.com/apache/datafusion/issues/19841) and [PR #19955](https://github.com/apache/datafusion/pull/19955) for more details. - -### `FilterExec` builder methods deprecated - -The following methods on `FilterExec` have been deprecated in favor of using `FilterExecBuilder`: - -- `with_projection()` -- `with_batch_size()` - -**Who is affected:** - -- Users who create `FilterExec` instances and use these methods to configure them - -**Migration guide:** - -Use `FilterExecBuilder` instead of chaining method calls on `FilterExec`: - -**Before:** - -```rust,ignore -let filter = FilterExec::try_new(predicate, input)? - .with_projection(Some(vec![0, 2]))? - .with_batch_size(8192)?; -``` - -**After:** - -```rust,ignore -let filter = FilterExecBuilder::new(predicate, input) - .with_projection(Some(vec![0, 2])) - .with_batch_size(8192) - .build()?; -``` - -The builder pattern is more efficient as it computes properties once during `build()` rather than recomputing them for each method call. - -Note: `with_default_selectivity()` is not deprecated as it simply updates a field value and does not require the overhead of the builder pattern. - -### Protobuf conversion trait added - -A new trait, `PhysicalProtoConverterExtension`, has been added to the `datafusion-proto` -crate. This is used for controlling the process of conversion of physical plans and -expressions to and from their protobuf equivalents. The methods for conversion now -require an additional parameter. - -The primary APIs for interacting with this crate have not been modified, so most users -should not need to make any changes. If you do require this trait, you can use the -`DefaultPhysicalProtoConverter` implementation. - -For example, to convert a sort expression protobuf node you can make the following -updates: - -**Before:** - -```rust,ignore -let sort_expr = parse_physical_sort_expr( - sort_proto, - ctx, - input_schema, - codec, -); -``` - -**After:** - -```rust,ignore -let converter = DefaultPhysicalProtoConverter {}; -let sort_expr = parse_physical_sort_expr( - sort_proto, - ctx, - input_schema, - codec, - &converter -); -``` - -Similarly to convert from a physical sort expression into a protobuf node: - -**Before:** - -```rust,ignore -let sort_proto = serialize_physical_sort_expr( - sort_expr, - codec, -); -``` - -**After:** - -```rust,ignore -let converter = DefaultPhysicalProtoConverter {}; -let sort_proto = serialize_physical_sort_expr( - sort_expr, - codec, - &converter, -); -``` - -### `generate_series` and `range` table functions changed - -The `generate_series` and `range` table functions now return an empty set when the interval is invalid, instead of an error. -This behavior is consistent with systems like PostgreSQL. - -Before: - -```sql -> select * from generate_series(0, -1); -Error during planning: Start is bigger than end, but increment is positive: Cannot generate infinite series - -> select * from range(0, -1); -Error during planning: Start is bigger than end, but increment is positive: Cannot generate infinite series -``` - -Now: - -```sql -> select * from generate_series(0, -1); -+-------+ -| value | -+-------+ -+-------+ -0 row(s) fetched. - -> select * from range(0, -1); -+-------+ -| value | -+-------+ -+-------+ -0 row(s) fetched. -``` - -### `array_remove`, `array_remove_n`, `array_remove_all` now return NULL when the element argument is NULL - -Previously, calling `array_remove(array, NULL)` would attempt to match and -remove NULL entries from the array, returning the array with NULLs stripped. -Now, passing NULL as the element to remove causes the function to return NULL, -which is consistent with standard SQL NULL propagation semantics. - -The same change applies to `array_remove_n` (aliases: `list_remove_n`) and -`array_remove_all` (aliases: `list_remove_all`). - -**Who is affected:** - -- Queries that call `array_remove`, `array_remove_n`, or `array_remove_all` - with a NULL element argument (literal or column-derived). - -**Behavioral changes:** - -| Expression | Old result | New result | -| ---------------------------------------------------- | ----------------- | ---------- | -| `array_remove(make_array(1, NULL, 2), NULL)` | `[1, 2]` | `NULL` | -| `array_remove(make_array(1, NULL, 2, NULL), NULL)` | `[1, 2, NULL]` | `NULL` | -| `array_remove_n(make_array(1, 2, 2, 1, 1), NULL, 2)` | `[1, 2, 2, 1, 1]` | `NULL` | -| `array_remove_all(make_array(1, 2, 2, 1, 1), NULL)` | `[1, 2, 2, 1, 1]` | `NULL` | - -**Migration guide:** - -If your queries relied on the old behavior to strip NULLs from arrays, use -`array_remove_all` with a non-NULL sentinel or use `array_filter` instead: - -```sql --- Before (removed NULLs from array): -SELECT array_remove(make_array(1, NULL, 2), NULL); --- Old result: [1, 2] - --- After (returns NULL due to NULL propagation): -SELECT array_remove(make_array(1, NULL, 2), NULL); --- New result: NULL -``` - -See [#21011](https://github.com/apache/datafusion/issues/21011) and -[PR #21013](https://github.com/apache/datafusion/pull/21013) for details. +The upgrade guide for DataFusion 53.0.0 is in the +[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/53.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/54.0.0.md b/docs/source/library-user-guide/upgrading/54.0.0.md index 77de24cdf23c5..b8060dd70f03a 100644 --- a/docs/source/library-user-guide/upgrading/54.0.0.md +++ b/docs/source/library-user-guide/upgrading/54.0.0.md @@ -4,876 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 54.0.0 Upgrade Guide -## DataFusion 54.0.0 - -### `AggregateFunctionExpr::human_display()` now returns `Option<&str>` - -`datafusion_physical_expr::aggregate::AggregateFunctionExpr::human_display()` -now returns `Option<&str>` instead of `&str`. - -If your code read the display text directly, handle the `None` case and fall -back to `name()` when needed: - -```rust -let display = agg_expr.human_display().unwrap_or(agg_expr.name()); -``` - -### Aggregate logical-to-physical lowering helpers are deprecated - -`create_aggregate_expr_with_name_and_maybe_filter` and -`create_aggregate_expr_and_maybe_filter` are deprecated. Use -`datafusion_physical_expr::aggregate::LoweredAggregateBuilder` for new code that -lowers a logical aggregate `Expr` into an `AggregateFunctionExpr`, filter, and -order-by expressions. - -For example: - -```rust -let lowered = LoweredAggregateBuilder::new( - expr, - logical_input_schema, - physical_input_schema, - execution_props, -) -.build()?; -``` - -`LoweredAggregateBuilder` returns a `LoweredAggregate` containing the aggregate -physical expression, optional filter, and order-by expressions. - -### `Expr::unalias_nested()` preserves aliases with metadata - -`Expr::unalias_nested()` no longer removes aliases that carry non-empty -`FieldMetadata`. This preserves user-provided output field metadata. Code that -needs to remove all aliases, including aliases with metadata, should unwrap -`Expr::Alias` explicitly. - -### Physical aggregate proto display may contain encoded alias data - -`PhysicalAggregateExprNode.human_display` may now contain an internal encoded -prefix when an aggregate display has a separate output alias. DataFusion decodes -this when reading physical plans. Older readers that do not know this encoding -may show the prefix text directly in diagnostics. - -### Physical `EXPLAIN` now shows lowered aggregate execution forms - -Physical `EXPLAIN` output is intended for diagnostics and may change between -DataFusion versions. This release changes aggregate expression formatting in -physical plans to show the lowered expression executed by the engine while -keeping the visible output alias. - -Examples: - -- `count(*)` may now appear as `count(1) as count(*)` -- simplified aggregates may show the lowered implementation, such as - `min(...) as percentile_cont(...)` -- internal aggregate aliases may now show the underlying expression instead of - only the alias name - -Tests or diagnostics that compare physical `EXPLAIN` output exactly may need -to update their expected strings. - -### String/numeric comparison coercion now prefers numeric types - -Previously, comparing a numeric column with a string value (e.g., -`WHERE int_col > '100'`) coerced both sides to strings and performed a -lexicographic comparison. This produced surprising results — for example, -`5 > '100'` yielded `true` because `'5' > '1'` lexicographically, even -though `5 > 100` is `false` numerically. - -DataFusion now coerces the string side to the numeric type in comparison -contexts (`=`, `<`, `>`, `<=`, `>=`, `<>`, `IN`, `BETWEEN`, `CASE .. WHEN`, -`GREATEST`, `LEAST`). For example, `5 > '100'` will now yield `false`. - -**Who is affected:** - -- Queries that compare numeric values with string values -- Queries that use `IN` lists with mixed string and numeric types -- Queries that use `CASE expr WHEN` with mixed string and numeric types -- Queries that use `GREATEST` or `LEAST` with mixed string and numeric types - -**Behavioral changes:** - -| Expression | Old behavior | New behavior | -| ----------------------- | ------------------------------- | ------------------------------------------ | -| `int_col > '100'` | Lexicographic | Numeric | -| `float_col = '5'` | String `'5' != '5.0'` | Numeric `5.0 = 5.0` | -| `int_col = 'hello'` | String comparison, always false | Cast error | -| `str_col IN ('a', 1)` | Coerce to Utf8 | Cast error (`'a'` cannot be cast to Int64) | -| `float_col IN ('1.0')` | String `'1.0' != '1'` | Numeric `1.0 = 1.0` (correct) | -| `CASE str_col WHEN 1.0` | Coerce to Utf8 | Coerce to Float64 | -| `GREATEST(10, '9')` | Utf8 `'9'` (lexicographic) | Int64 `10` (numeric) | -| `LEAST(10, '9')` | Utf8 `10` (lexicographic) | Int64 `9` (numeric) | - -**Migration guide:** - -Most queries will produce more correct results with no changes needed. -However, queries that relied on the old string-comparison behavior may need -adjustment: - -- **Queries comparing numeric columns with non-numeric strings** (e.g., - `int_col = 'hello'` or `int_col > text_col` where `text_col` contains - non-numeric values) will now produce a cast error instead of silently - returning no rows. -- **Mixed-type `IN` lists** (e.g., `str_col IN ('a', 1)`) are now rejected. Use - consistent types for the `IN` list or add an explicit `CAST`. -- **Queries comparing integer columns with non-integer numeric string literals** (e.g., - `int_col = '99.99'`) will now produce a cast error because `'99.99'` - cannot be cast to an integer. Use a float column or adjust the literal. - -See [#15161](https://github.com/apache/datafusion/issues/15161) and -[PR #20426](https://github.com/apache/datafusion/pull/20426) for details. - -### `CastColumnExpr` removed in favor of field-aware `CastExpr` - -`datafusion_physical_expr::expressions::CastColumnExpr` has been removed; use -the field-aware `datafusion_physical_expr::expressions::CastExpr` instead. - -If your code downcasted to `CastColumnExpr`, downcast to `CastExpr` instead and -use `CastExpr::target_field()` for the output field metadata and -`CastExpr::expr()` for the input expression. To construct casts with explicit -field semantics, use `CastExpr::new_with_target_field(...)`. The type-only -`CastExpr::new(...)` and `cast(...)` helpers remain available for callers that -only have a `DataType`. - -### `comparison_coercion_numeric` removed, replaced by `comparison_coercion` - -The `comparison_coercion_numeric` function has been removed. Its behavior -(preferring numeric types for string/numeric comparisons) is now the default in -`comparison_coercion`. A new function, `type_union_coercion`, handles contexts -where string types are preferred (`UNION`, `CASE THEN/ELSE`, `NVL2`). - -**Who is affected:** - -- Crates that call `comparison_coercion_numeric` directly -- Crates that call `comparison_coercion` and relied on its old - string-preferring behavior -- Crates that call `get_coerce_type_for_case_expression` - -### `ExecutionPlan::partition_statistics` now returns `Arc` - -`ExecutionPlan::partition_statistics` now returns `Result>` instead of `Result`. This avoids cloning `Statistics` when it is shared across multiple consumers. - -**Before:** - -```rust,ignore -fn partition_statistics(&self, partition: Option) -> Result { - Ok(Statistics::new_unknown(&self.schema())) -} -``` - -**After:** - -```rust,ignore -fn partition_statistics(&self, partition: Option) -> Result> { - Ok(Arc::new(Statistics::new_unknown(&self.schema()))) -} -``` - -If you need an owned `Statistics` value (e.g. to mutate it), use `Arc::unwrap_or_clone`: - -```rust,ignore -// If you previously consumed the Statistics directly: -let stats = plan.partition_statistics(None)?; -stats.column_statistics[0].min_value = ...; - -// Now unwrap the Arc first: -let mut stats = Arc::unwrap_or_clone(plan.partition_statistics(None)?); -stats.column_statistics[0].min_value = ...; -``` - -### Remove `as_any` from `PhysicalExpr`, `ScalarUDFImpl`, `AggregateUDFImpl`, `WindowUDFImpl`, `ExecutionPlan`, `TableProvider`, `SchemaProvider`, `CatalogProvider`, `CatalogProviderList`, `TableSource`, `FileSource`, `FileFormat`, `FileFormatFactory`, `DataSource`, and `DataSink` - -Now that we have a more recent minimum version of Rust, we can take advantage of -trait upcasting. This reduces the amount of boilerplate code that -users need to implement. In your implementations of the traits listed above, -you can simply remove the `as_any` function. For example: - -```diff - impl PhysicalExpr for MyExpr { -- fn as_any(&self) -> &dyn Any { -- self -- } -- - fn data_type(&self, input_schema: &Schema) -> Result { - ... - } - - ... - } -``` - -The same change applies to all of the above traits — simply delete the -`as_any` method from each implementation. - -If you have code that is downcasting, you can drop the `.as_any()` call -and use `downcast_ref` / `is` directly on the trait object: - -```diff --let exec = plan.as_any().downcast_ref::().unwrap(); -+let exec = plan.downcast_ref::().unwrap(); -``` - -These methods work correctly whether the value is a bare reference or -behind an `Arc` (Rust auto-derefs through the `Arc`). - -> **Warning:** Do not cast an `Arc` directly to `&dyn Any`. -> Writing `(&plan as &dyn Any)` gives you an `Any` reference to the -> **`Arc` itself**, not the underlying trait object, so the downcast will -> always return `None`. Use the `downcast_ref` method above instead, or -> dereference through the `Arc` first with `plan.as_ref() as &dyn Any`. - -### `PruningStatistics::row_counts` no longer takes a `column` parameter - -The `row_counts` method on the `PruningStatistics` trait no longer takes a -`&Column` argument, since row counts are a container-level property (the same -for every column). - -**Before:** - -```rust,ignore -fn row_counts(&self, column: &Column) -> Option { - // ... -} -``` - -**After:** - -```rust,ignore -fn row_counts(&self) -> Option { - // ... -} -``` - -**Who is affected:** - -- Users who implement the `PruningStatistics` trait - -**Migration guide:** - -Remove the `column: &Column` parameter from your `row_counts` implementation -and any corresponding call sites. If your implementation was using the column -argument, note that row counts are identical for all columns in a container, so -the parameter was unnecessary. - -See [PR #21369](https://github.com/apache/datafusion/pull/21369) for details. - -### Avro API and timestamp decoding changes - -DataFusion has switched to use `arrow-avro` (see [#17861]) when reading avro files -which results in a few changes: - -- `DataFusionError::AvroError` has been removed. -- `From for DataFusionError` has been removed. -- Avro crate re-export changed: - - Before: `datafusion::apache_avro` - - After: `datafusion::arrow_avro` -- **Avro timestamp logical type interpretation changed.** Notable effects: - - Avro `timestamp-*` logical types are read as UTC timezone-aware Arrow - timestamps (`Timestamp(..., Some("+00:00"))`) - - Avro `local-timestamp-*` logical types remain timezone-naive - (`Timestamp(..., None)`) - -**Who is affected:** - -- Users matching on `DataFusionError::AvroError` -- Users importing `datafusion::apache_avro` -- Users relying on previous Avro timestamp logical type behavior - -**Migration guide:** - -- Replace `datafusion::apache_avro` imports with `datafusion::arrow_avro`. -- Update error handling code that matches on `DataFusionError::AvroError` to use - the current error surface. -- Validate timestamp handling where timezone semantics matter: - `timestamp-*` is UTC timezone-aware, while `local-timestamp-*` is - timezone-naive. - -### `lpad`, `rpad`, and `translate` now operate on Unicode codepoints instead of grapheme clusters - -Previously, `lpad`, `rpad`, and `translate` used Unicode grapheme cluster -segmentation to measure and manipulate strings. They now use Unicode codepoints, -which is consistent with the SQL standard and most other SQL implementations. It -also matches the behavior of other string-related functions in DataFusion. - -The difference is only observable for strings containing combining characters -(e.g., U+0301 COMBINING ACUTE ACCENT) or other multi-codepoint grapheme -clusters (e.g., ZWJ emoji sequences). For ASCII and most common Unicode text, -behavior is unchanged. - -### Scalar subquery execution changes - -Uncorrelated scalar subqueries (e.g. `SELECT ... WHERE x > (SELECT max(v) FROM t)`) -are now executed by a dedicated physical operator rather than being rewritten to -a join. Correlated scalar subqueries are unchanged. - -This produces two user-visible changes: - -- **Subqueries that return multiple rows now fail at runtime.** An uncorrelated - scalar subquery that returns more than one row fails with `Execution error: Scalar subquery returned more than one row`. This matches the SQL standard and - the behavior of most other SQL implementations. The previous join-based - rewrite could silently produce multi-row output. Add a `LIMIT 1` or an - aggregate to the subquery to fix such queries. -- **Plan shape changes.** Uncorrelated `Expr::ScalarSubquery` nodes now survive - into the final logical plan instead of being replaced by a join; the - corresponding physical plan contains a new `ScalarSubqueryExec` node and a - `ScalarSubqueryExpr` expression. Code that walks or transforms `LogicalPlan` / - `ExecutionPlan` trees, as well as `EXPLAIN` output, may need updating. - -### `datafusion-proto`: expression deserialization now takes a `TaskContext` - -`Serializeable::from_bytes_with_registry` is renamed to `from_bytes_with_ctx` -and takes a `&TaskContext` instead of a `&dyn FunctionRegistry`. `parse_expr`, -`parse_exprs`, and `parse_sorts` take the same change. `Expr::from_bytes` -(without a registry argument) is unchanged. - -```diff --let expr = Expr::from_bytes_with_registry(&bytes, ®istry)?; -+let expr = Expr::from_bytes_with_ctx(&bytes, ctx.task_ctx().as_ref())?; -``` - -```diff --let expr = parse_expr(&proto, ®istry, &codec)?; -+let expr = parse_expr(&proto, ctx.task_ctx().as_ref(), &codec)?; -``` - -### `datafusion-proto`: `PhysicalProtoConverterExtension` reshaped - -`PhysicalProtoConverterExtension` and the `parse_physical_*_with_converter` -helpers now take a single `&PhysicalPlanDecodeContext<'_>` that bundles the -`TaskContext` and the `PhysicalExtensionCodec`. Implementations update like -this: - -```diff - impl PhysicalProtoConverterExtension for MyConverter { - fn proto_to_execution_plan( - &self, -- ctx: &TaskContext, -- codec: &dyn PhysicalExtensionCodec, - proto: &protobuf::PhysicalPlanNode, -+ ctx: &PhysicalPlanDecodeContext<'_>, - ) -> Result> { -- proto.try_into_physical_plan_with_converter(ctx, codec, self) -+ self.default_proto_to_execution_plan(proto, ctx) - } - - fn proto_to_physical_expr( - &self, - proto: &PhysicalExprNode, -- ctx: &TaskContext, - input_schema: &Schema, -- codec: &dyn PhysicalExtensionCodec, -+ ctx: &PhysicalPlanDecodeContext<'_>, - ) -> Result> { -- parse_physical_expr_with_converter(proto, ctx, input_schema, codec, self) -+ self.default_proto_to_physical_expr(proto, input_schema, ctx) - } - } -``` - -Pull out the `TaskContext` or codec inside these methods with -`ctx.task_ctx()` and `ctx.codec()`. Construct a fresh context at an API -boundary with `PhysicalPlanDecodeContext::new(task_ctx, codec)`. - -### `ExecutionProps` has new fields - -`ExecutionProps` gained new public fields. Code that constructs it via a -struct literal, or pattern-matches it without `..`, no longer compiles. Use -`ExecutionProps::new()` and include `..` in exhaustive patterns. - -### Items in `datafusion_functions::strings` are no longer public - -`StringArrayBuilder`, `LargeStringArrayBuilder`, `StringViewArrayBuilder`, -`ColumnarValueRef`, and `append_view` have been reduced to `pub(crate)`. They -were only ever used to implement `concat` and `concat_ws` inside the crate. If -you were importing them externally, use Arrow's corresponding builders with a -caller-computed `NullBuffer`. - -[#17861]: https://github.com/apache/datafusion/pull/17861 - -### Conversion from `FileDecryptionProperties` to `ConfigFileDecryptionProperties` is now fallible - -Previously, `datafusion_common::config::ConfigFileDecryptionProperties` -implemented `From<&Arc>`. -If an error was encountered when retrieving the footer key without providing key metadata, -the error would be ignored and an empty footer key set in the result. -This could lead to obscure errors later. - -`ConfigFileDecryptionProperties` now instead implements `TryFrom<&Arc>`, -and errors retrieving the footer key will be propagated up. - -**Migration guide:** - -Replace calls to `ConfigFileDecryptionProperties::from` with `ConfigFileDecryptionProperties::try_from`, -and affected calls to `into` with `try_into`, with appropriate error handling added. - -**Before:** - -```rust,ignore -let config_decryption_properties: ConfigFileDecryptionProperties = (&decryption_properties).into(); -// or -let config_decryption_properties = ConfigFileDecryptionProperties::from(&decryption_properties); -``` - -(where `decryption_properties` is an `Arc`) - -**After:** - -```rust,ignore -let config_decryption_properties: ConfigFileDecryptionProperties = (&decryption_properties).try_into()?; -// or -let config_decryption_properties = ConfigFileDecryptionProperties::try_from(&decryption_properties)?; -``` - -See [#21602](https://github.com/apache/datafusion/issues/21602) and -[PR #21603](https://github.com/apache/datafusion/pull/21603) for details. - -### Conversion from `ConfigFileEncryptionProperties` / `ConfigFileDecryptionProperties` is now fallible - -Previously, `datafusion_common::config::ConfigFileEncryptionProperties` and -`datafusion_common::config::ConfigFileDecryptionProperties` implemented infallible -conversions into Parquet's encryption/decryption types (via `From` / `Into`). -These conversions may need to decode hex-encoded keys and other configuration values, which can fail. - -They now use `TryFrom` / `TryInto` and return a `Result`: - -- `impl TryFrom for parquet::encryption::encrypt::FileEncryptionProperties` -- `impl TryFrom for parquet::encryption::decrypt::FileDecryptionProperties` - -**Migration guide:** - -Replace `from()` / `into()` with `try_from()` / `try_into()` and handle the resulting `Result`. - -**Before:** - -```rust,ignore -let file_encryption_properties: FileEncryptionProperties = config_encryption_properties.into(); -// or -let file_decryption_properties = FileDecryptionProperties::from(config_decryption_properties); -``` - -( -where `config_encryption_properties` is a `ConfigFileEncryptionProperties` and -`config_decryption_properties` is a `ConfigFileDecryptionProperties` -) - -**After:** - -```rust,ignore -let file_encryption_properties: FileEncryptionProperties = - config_encryption_properties.try_into()?; -// or -let file_decryption_properties = - FileDecryptionProperties::try_from(config_decryption_properties)?; -``` - -See [#21974](https://github.com/apache/datafusion/issues/21974) and -[PR #21985](https://github.com/apache/datafusion/pull/21985) for details. - -### `approx_percentile_cont`, `approx_percentile_cont_with_weight`, `approx_median` now coerce to floats - -The type signatures of `approx_percentile_cont`, `approx_percentile_cont_with_weight`, and -`approx_median` now coerce integer input values to `Float64` before computing the approximation. -As a result, these functions always return a float, even when the input column is an integer type. - -**Who is affected:** - -- Queries or downstream code that relied on `approx_percentile_cont` / `approx_percentile_cont_with_weight` / - `approx_median` returning an integer type when given an integer column. - -**Migration guide:** - -If downstream code checks or relies on the return type being an integer, add an explicit -`CAST` back to the desired integer type, or update the type assertion: - -```sql --- Before (returned Int64): -SELECT approx_percentile_cont(quantity, 0.5) FROM orders; - --- After (returns Float64); cast if an integer result is required: -SELECT CAST(approx_percentile_cont(quantity, 0.5) AS BIGINT) FROM orders; -``` - -[#21074]: https://github.com/apache/datafusion/pull/21074 - -### `PartitionedFile::extensions` is now a type-keyed map - -`PartitionedFile.extensions` previously held a single -`Option>` slot, so two independent components -could not both attach data to the same file without colliding. The field -is now a `FileExtensions` (a re-export of -`datafusion_common::extensions::Extensions`), a map keyed by concrete Rust -type. Each type occupies its own slot, so multiple consumers (e.g. a -`ParquetAccessPlan` and a custom index entry) can coexist on a single -`PartitionedFile`. - -The previous `with_extensions(Arc)` builder is -deprecated (it still works, keyed by the value's dynamic `TypeId`) in -favor of a typed variant: - -```diff --let pf = PartitionedFile::new(path, size) -- .with_extensions(Arc::new(access_plan)); -+let pf = PartitionedFile::new(path, size) -+ .with_extension(access_plan); -``` - -Reading an extension no longer requires a manual downcast: - -```diff --let access_plan = partitioned_file -- .extensions -- .as_ref() -- .and_then(|ext| ext.downcast_ref::()); -+let access_plan = partitioned_file.extension::(); -``` - -The `FileExtensions` API is `insert` / `insert_arc` / `get` / `get_arc` -/ `contains` / `merge`, all generic over the concrete type `T`. Values -are stored as `Arc` so the map remains cheap to clone. - -**Who is affected:** - -- Code that constructs `PartitionedFile` and calls `.with_extensions(...)`. -- Custom `ParquetFileReaderFactory` implementations or other consumers that - read `partitioned_file.extensions` and downcast manually. - -### `arrays_zip` struct field names changed - -The `arrays_zip` (and its alias `list_zip`) scalar function now names its -output struct fields `"1"`, `"2"`, ..., `"n"` (1-indexed, matching DuckDB and -Spark) instead of `c0`, `c1`, ..., `c{n-1}`. - -**Who is affected:** - -- Queries or downstream code that references the output struct fields by name - (e.g. `arrays_zip(a, b)[1]['c0']`). Update field accessors to `'1'`, `'2'`, - etc. (e.g. `arrays_zip(a, b)[1]['1']`). - -See [PR #20886](https://github.com/apache/datafusion/pull/20886) for details. - -### `Box` and `Arc` `TreeNodeContainer` impls now require `C: Default` - -The generic `TreeNodeContainer` implementations for `Box` and `Arc` now -require `C: Default`. This change was necessary as part of optimizing tree -rewriting to reduce heap allocations. - -**Who is affected:** - -- Users that implement `TreeNodeContainer` on a custom type and wrap it in - `Box` or `Arc` when walking trees. - -**Migration guide:** - -Add a `Default` implementation to your type. The default value is used as a -temporary placeholder during query optimization, so when possible, pick a cheap, -allocation-free variant: - -```rust,ignore -impl Default for MyTreeNode { - fn default() -> Self { - MyTreeNode::Leaf // or whichever variant is cheapest to construct - } -} -``` - -### `MemoryPool` now requires `'static` (adds `Any` as a supertrait) - -To enable downcasting of `dyn MemoryPool` to concrete pool types (via -`is::()` / `downcast_ref::()`), the `MemoryPool` trait now has `Any` -as a supertrait: - -```rust,ignore -// Before -pub trait MemoryPool: Send + Sync + std::fmt::Debug + Display { ... } - -// After -pub trait MemoryPool: Any + Send + Sync + std::fmt::Debug + Display { ... } -``` - -Because `Any` is only implemented for `'static` types, this implicitly adds a -`'static` bound to every `MemoryPool` implementor. - -**Who is affected:** - -- Users who implement a custom `MemoryPool` whose type carries a lifetime - parameter or borrows state (e.g. `struct MyPool<'a> { inner: &'a State }`). - Existing implementations that are already `'static` (the common case) need - no changes. - -**Migration guide:** - -Replace borrowed references with owned handles so the pool type becomes -`'static`. The typical fix is to swap `&'a T` for `Arc` (or `Rc`, or an -owned value): - -```rust,ignore -// Before — not 'static, no longer compiles -struct MyPool<'a> { - inner: &'a SomeState, -} - -impl<'a> MemoryPool for MyPool<'a> { ... } - -// After — owned handle makes MyPool: 'static -struct MyPool { - inner: Arc, -} - -impl MemoryPool for MyPool { ... } -``` - -If the borrowed state truly cannot be made `'static`, you can wrap the -borrowed pool in a `'static` adapter that the pool consumer owns — for -example, store the underlying state in an `Arc` owned by the adapter, or -move the borrow behind an interior-mutability primitive such as `Arc>` -or `Arc>`. - -See [PR #21803](https://github.com/apache/datafusion/pull/21803) for details. - -[20047]: https://github.com/apache/datafusion/pull/20047 - -### File statistics cache is now memory-limited and managed by the `CacheManager` - -The file statistics cache used by `ListingTable` is now memory-limited and -centrally managed through the `CacheManager`. - -To configure the cache size use the `file_statistics_cache_limit` setting: - -```sql -SET datafusion.runtime.file_statistics_cache_limit = '10M' -``` - -To disable the file statistics cache, set the limit to 0. - -The file statistics cache is no longer created inside the `ListingTable`. -Instead, it is created within the `CacheManager` and must be passed to the `ListingTable`. - -**Who is affected:** - -- Users who want to limit the memory usage of the file statistics cache. -- Users who want to disable the file statistics cache. -- Users who want to create a `ListingTable` programmatically with a file statistics cache. - -**Migration guide:** - -Disable the cache by setting the configuration value to 0: - -```sql -SET datafusion.runtime.file_statistics_cache_limit = '0' -``` - -Use the file statistics cache provided by the `CacheManager` when initializing a new `ListingTable`: - -```rust,ignore -ListingTable::try_new(config)? - .with_cache(ctx.runtime_env().cache_manager.get_file_statistic_cache()) -``` - -### `UnionsToFilter` optimizer rule is now disabled by default - -The `datafusion.optimizer.enable_unions_to_filter` option now defaults to -`false`. When enabled, the rule rewrites `UNION DISTINCT` branches that read the -same source and differ only by filter predicates into a single scan with a -combined `OR` predicate: - -```sql --- Before: two separate scans -SELECT * FROM t WHERE a = 1 -UNION -SELECT * FROM t WHERE a = 2 - --- After: one scan -SELECT DISTINCT * FROM t WHERE a = 1 OR a = 2 -``` - -**Who is affected:** - -- Queries using `UNION` against the same table with different filter - conditions may benefit from enabling this rule. - -**Migration guide:** - -Enable the rule when your `UNION` queries scan the same large table -multiple times with different predicates. Avoid it when the data source handles individual equality predicates more efficiently than -a combined `OR` (e.g., index-backed sources). - -```sql -SET datafusion.optimizer.enable_unions_to_filter = true; -``` - -See [PR #21075](https://github.com/apache/datafusion/pull/21075) for more details - -### Higher-order functions and lambdas - -The changes below are related to the added support for higher-order functions -and lambdas. For more info, see [#14205], [PR #18921], [PR #21679] and -[EPIC #21172]. - -[#14205]: https://github.com/apache/datafusion/issues/14205 -[pr #18921]: https://github.com/apache/datafusion/pull/18921 -[pr #21679]: https://github.com/apache/datafusion/pull/21679 -[epic #21172]: https://github.com/apache/datafusion/issues/21172 - -#### `FunctionRegistry` exposes two additional methods - -`FunctionRegistry` exposes two additional methods, `higher_order_function` -which returns the registered higher-order function with the given name, if -any, and `higher_order_function_names` which exposes the set of registered -user defined higher-order function names. - -**Who is affected:** - -- Users who implement the `FunctionRegistry` trait - -**Migration guide:** - -Add `higher_order_function` and `higher_order_function_names` to your implementation. - -```diff -impl FunctionRegistry for FunctionRegistryImpl { - fn udfs(&self) -> HashSet { - self.scalar_functions.keys().cloned().collect() - } -+ -+ fn higher_order_function(&self, name: &str) -> Result> { -+ self.higher_order_functions -+ .get(name) -+ .cloned() -+ .ok_or_else(|| plan_datafusion_err!("Higher-order function {name} not found")) -+ } -+ -+ fn higher_order_function_names(&self) -> HashSet { -+ self.higher_order_functions.keys().cloned().collect() -+ } -} -``` - -#### `ContextProvider` exposes two additional methods - -`ContextProvider` exposes two additional methods, `get_higher_order_meta` -which returns the registered higher-order function with the given name, -if any, and `higher_order_function_names` which exposes the registered -user defined higher-order function names. - -**Who is affected:** - -- Users who implement the `ContextProvider` trait - -**Migration guide:** - -Add `get_higher_order_meta` and `higher_order_function_names` to your implementation. - -```diff -impl ContextProvider for ContextProviderImpl { - fn udfs(&self) -> HashSet { - self.scalar_functions.keys().cloned().collect() - } -+ -+ fn get_higher_order_meta(&self, name: &str) -> Option> { -+ self.higher_order_functions.get(name).cloned() -+ } -+ -+ fn higher_order_function_names(&self) -> Vec { -+ self.higher_order_functions.keys().cloned().collect() -+ } -} -``` - -#### Add `higher_order_functions()` method to `Session` - -The `higher_order_functions` method has been added to the `Session` trait, -which exposes the registered user defined higher-order functions. - -**Who is affected:** - -- Users who implement the `Session` trait - -**Migration guide:** - -Add `higher_order_functions` to your implementation. - -```diff -impl Session for MySession { - ... -+ fn higher_order_functions(&self) -> &HashMap> { -+ &self.higher_order_functions -+ } -} -``` - -#### New argument on `TaskContext::new` - -`TaskContext::new` expects a new argument, `higher_order_functions`, which is -a map of higher-order functions keyed by name. - -**Who is affected:** - -- Users who call `TaskContext::new` - -**Migration guide:** - -Provide the new argument to the function. An empty hash map is sufficient. - -```diff -+let higher_order_functions = HashMap::new(); - -TaskContext::new( - task_id, - session_id, - session_config, - scalar_functions, -+ higher_order_functions, - aggregate_functions, - window_functions, - runtime, -) -``` - -#### The `Expr` enum has three new variants - -- `HigherOrderFunction`: Call a higher-order function with a set of arguments -- `Lambda`: A Lambda expression with a set of parameters names and a body -- `LambdaVariable`: A named reference to a lambda parameter - -**Who is affected:** - -- Users who match on an `Expr` without a default branch `_ => {}` - -**Migration guide:** - -Add the new branches to the match with the logic applicable to the context. - -```diff -match expr { - Expr::Column(column) => ..., - ..., -+ Expr::HigherOrderFunction(func) => {}, -+ Expr::Lambda(lambda) => {}, -+ Expr::LambdaVariable(lambda_var) => {}, -``` - -#### The `RegisterFunction` enum has a new `HigherOrder` variant - -`RegisterFunction` now has a `HigherOrder(Arc)` variant -so user-defined higher-order functions can be registered - -**Who is affected:** - -- Users who match on a `RegisterFunction` without a default branch `_ => {}` - -**Migration guide:** - -Add the new branch to the match with the logic applicable to the context. - -```diff -match register_function { - RegisterFunction::Scalar(scalar) => {}, - RegisterFunction::Aggregate(aggregate) => {}, - RegisterFunction::Window(window) => {}, -+ RegisterFunction::HigherOrder(higher_order) => {}, - RegisterFunction::Table(name, table) => {}, -} -``` +The upgrade guide for DataFusion 54.0.0 is in the +[documentation for DataFusion 54.1.0](https://datafusion.apache.org/versions/54.1.0/library-user-guide/upgrading/54.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/55.0.0.md b/docs/source/library-user-guide/upgrading/55.0.0.md index 2e5c9a782de13..00e4847a86f0c 100644 --- a/docs/source/library-user-guide/upgrading/55.0.0.md +++ b/docs/source/library-user-guide/upgrading/55.0.0.md @@ -4,1518 +4,7 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# DataFusion 55.0.0 Upgrade Guide -## DataFusion 55.0.0 - -### Filter predicate evaluation order may differ from query text - -The logical optimizer now reorders filters so that cheap predicates (most binary -comparisons, `IS NULL`, `Between`, `InList`, etc.) evaluate before expensive -ones (`LIKE`, regex, scalar function calls, subqueries). For example, -`WHERE col LIKE '%foo%' AND col2 = 5` may evaluate `col2 = 5` before -`col LIKE '%foo%'`. - -**Evaluation order has never been guaranteed to match the order written in the -query.** The SQL standard explicitly allows implementations to evaluate operands -in any order; major engines (PostgreSQL, SQL Server, Oracle, MySQL) document the -same. Queries should not rely on left-to-right evaluation or short-circuit -semantics for `AND` or `OR`. Previous versions of DataFusion already reordered -predicates (e.g., as part of expression simplification or predicate pushdown); -the new reordering pass just increases the scenarios where the optimizer will -change predicate evaluation order. - -**Fallible-predicate patterns are particularly affected.** For example: - -```sql -WHERE s ~ '^[0-9]+$' AND CAST(s AS INT) > 0 -``` - -The intent is likely to filter non-numeric strings before the `CAST` runs, -but this depends on evaluation-order behavior the SQL standard does not -guaranteed. The new reorder makes this kind of pattern more likely to fail -at runtime if the optimizer moves the `CAST` ahead of the regex. To force -conditional evaluation, rewrite using `CASE`, which has standardized -short-circuit semantics: - -```sql -WHERE CASE WHEN s ~ '^[0-9]+$' THEN CAST(s AS INT) > 0 ELSE false END -``` - -Volatile expressions (`random()`, `now()`, etc.) are exempt — their position -in the conjunct list is preserved so the number of times they evaluate per -query does not change. - -### Map casts with nested Structs use schema-evolution rules - -Casts of a `Map` whose key or value recursively contains a `Struct` now adapt -nested Struct fields by case-sensitive name. Nullable fields added to the target -Struct are filled with `NULL`, and source-only fields are omitted. Missing -non-nullable target fields, nullable-to-non-nullable changes, and incompatible -nested types are rejected. - -Map keys define map identity. During this nested-Struct adaptation, key Struct -fields cannot be removed and primitive key type changes must preserve every -source value (for example, `Int32` to `Int64` is allowed, while `Int64` to -`Int32` is rejected). Sorted Maps also require an unchanged key type and the -same sorted flag. - -**Migration guide:** Schemas that relied on positional Struct-field matching, -key-field removal, or narrowing Map-key casts must be updated to retain -case-sensitive field names and key identity. Ordinary Maps without semantic -Struct children continue to use Arrow's normal Map cast behavior. - -### `TableProvider::scan` takes `Option<&[usize]>` for the projection - -`TableProvider::scan` and the related APIs listed below previously took the -projection as `Option<&Vec>`: - -```rust,ignore -// Before -async fn scan( - &self, - state: &dyn Session, - projection: Option<&Vec>, - filters: &[Expr], - limit: Option, -) -> Result>; - -// After -async fn scan( - &self, - state: &dyn Session, - projection: Option<&[usize]>, - filters: &[Expr], - limit: Option, -) -> Result>; -``` - -Implementations only need the signature updated. Two patterns inside a `scan` -body need adjusting, because `Option<&[usize]>` is not an `Option<&T>` over a -sized type: - -```rust,ignore -// Before // After -projection.cloned() projection.map(|p| p.to_vec()) -``` - -Callers holding an `Option>` should pass `.as_deref()` rather than -`.as_ref()`. - -The same change applies to `StreamingTableExec::try_new`, -`FilterExec::with_projection` and `batch_filter`, which took the projection in -the same shape. - -`datafusion_common::project_schema` now accepts unsized projections -(`projection: Option<&T> where T: AsRef<[usize]> + ?Sized`), so it takes both -`Option<&Vec>` and `Option<&[usize]>`; no caller changes are required. - -Besides being the more idiomatic signature, this lets -`TableProvider::scan_with_args`'s default body hand the projection straight to -`scan` instead of allocating a `Vec` that then has to be captured by the -returned future -- which is what made that method expensive to compile -(`datafusion-session` compiles ~3.3x faster as a result). - -### `DataFrame::fill_null` now borrows its arguments - -`DataFrame::fill_null` previously took its arguments by value: - -```rust,ignore -// Before -pub fn fill_null( - &self, - value: ScalarValue, - columns: Vec, -) -> Result -``` - -It now borrows them, matching the signature of the newly added -`DataFrame::fill_nan`: - -```rust,ignore -// After -pub fn fill_null( - &self, - value: &ScalarValue, - columns: &[&str], -) -> Result -``` - -This lets callers pass a borrowed `ScalarValue` and slice literals (or -`&str` column names) without first allocating owned `String`s. - -**Migration guide:** - -Borrow the value and pass a slice of `&str` instead of an owned `Vec`: - -```rust,ignore -// Before -let df = df.fill_null(ScalarValue::from(0), vec!["a".to_owned(), "c".to_owned()])?; -let df = df.fill_null(ScalarValue::from(0), vec![])?; - -// After -let df = df.fill_null(&ScalarValue::from(0), &["a", "c"])?; -let df = df.fill_null(&ScalarValue::from(0), &[])?; -``` - -### `FileScanConfig::partitioned_by_file_group` removed - -`FileScanConfig::partitioned_by_file_group` and -`FileScanConfigBuilder::with_partitioned_by_file_group(...)` have been removed. -Use `FileScanConfig::output_partitioning` and -`FileScanConfigBuilder::with_output_partitioning(...)` instead. -The corresponding -`datafusion_proto::protobuf::FileScanExecConf::partitioned_by_file_group` -field has also been removed. - -**Who is affected:** - -- Users who accessed `FileScanConfig::partitioned_by_file_group` directly. -- Users who called - `FileScanConfigBuilder::with_partitioned_by_file_group(true)`. -- Users who constructed or accessed - `datafusion_proto::protobuf::FileScanExecConf::partitioned_by_file_group`. - -**Migration guide:** - -If your file groups are organized by table partition column values, declare hash -output partitioning over those partition columns: - -```rust,ignore -use datafusion_datasource::file_scan_config::{ - FileScanConfigBuilder, output_partitioning_from_partition_fields, -}; - -let output_partitioning = output_partitioning_from_partition_fields( - source.table_schema().table_schema(), - source.table_schema().table_partition_cols(), - file_groups.len(), -); - -let config = FileScanConfigBuilder::new(object_store_url, source) - .with_file_groups(file_groups) - .with_output_partitioning(output_partitioning) - .build(); -``` - -`output_partitioning_from_partition_fields` returns -`Some(Partitioning::Hash(...))` when partition columns are present and `None` -otherwise. If you construct the partitioning manually, pass -`Some(Partitioning::Hash(partition_exprs, partition_count))` to -`with_output_partitioning(...)`. - -When constructing `FileScanExecConf`, omit `partitioned_by_file_group` and set -`output_partitioning` instead. - -### User `SpillFile` traits instead of [`RefCountedTempFile`] - -Spill file APIs now use the `datafusion_execution::SpillFile` trait instead of -the concrete [`RefCountedTempFile`] type. [`DiskManager::create_tmp_file`] now -returns `Arc`. -This change was introduced in [PR #21882], which adds pluggable spill file -backends via `SpillFile` and `TempFileFactory`. - -If your code matched on [`DiskManagerMode`], add a `DiskManagerMode::Custom(_)` -arm. - -If your code wrote directly to a [`RefCountedTempFile`] or called -[`RefCountedTempFile::update_disk_usage`], open a spill writer instead: - -```diff -- temp_file.inner().as_file().write_all(bytes)?; -- temp_file.update_disk_usage()?; -+ temp_file.open_writer()?.write_all(bytes)?; -``` - -Use `temp_file.size()` instead of [`RefCountedTempFile::current_disk_usage`]. - -[`diskmanager::create_tmp_file`]: https://docs.rs/datafusion-execution/latest/datafusion_execution/disk_manager/struct.DiskManager.html#method.create_tmp_file -[`diskmanagermode`]: https://docs.rs/datafusion-execution/latest/datafusion_execution/disk_manager/enum.DiskManagerMode.html -[`pr #21882`]: https://github.com/apache/datafusion/pull/21882 -[`refcountedtempfile`]: https://docs.rs/datafusion-execution/latest/datafusion_execution/disk_manager/struct.RefCountedTempFile.html -[`refcountedtempfile::current_disk_usage`]: https://docs.rs/datafusion-execution/latest/datafusion_execution/disk_manager/struct.RefCountedTempFile.html#method.current_disk_usage -[`refcountedtempfile::update_disk_usage`]: https://docs.rs/datafusion-execution/latest/datafusion_execution/disk_manager/struct.RefCountedTempFile.html#method.update_disk_usage - -### New `Dialect::Spark` variant - -The `Dialect` enum in `datafusion_common::config` now includes a `Spark` variant. -If you match exhaustively on `Dialect`, add a `Dialect::Spark` arm. - -### `Dialect::AVAILABLE` replaced by `Dialect::available()` - -`datafusion_common::config::Dialect::AVAILABLE` has been removed. Use -`Dialect::available()` instead. - -### `spill_record_batch_by_size` removed - -`datafusion_physical_plan::spill::spill_record_batch_by_size` has been removed. -This function was deprecated in DataFusion `46.0.0`. - -Use `datafusion_physical_plan::spill::SpillManager::spill_record_batch_by_size` -instead. - -### `CreateExternalTable` supports multiple locations - -`CREATE EXTERNAL TABLE` now accepts multiple paths in a single `LOCATION` -clause, which are read together as one table: - -```sql -CREATE EXTERNAL TABLE hits -STORED AS PARQUET -LOCATION ('file_1.parquet', 'file_2.parquet'); -``` - -To support this, the `location` field of both -`datafusion_expr::CreateExternalTable` and -`datafusion_sql::parser::CreateExternalTable` changed from a `String` to a -`Vec` named `locations`: - -```rust -// Before (54.0.0) -let location: String = create_external_table.location; - -// After (55.0.0) -let locations: Vec = create_external_table.locations; -``` - -The `CreateExternalTable::builder(name, location, file_type, schema)` -constructor is unchanged and still takes a single location; use the new -`CreateExternalTableBuilder::with_locations(Vec)` to set more than one. -All listed locations must resolve to the same schema and reside on the same -object store. A plain string literal remains a single location, so paths that -contain commas continue to work, for example `LOCATION 'path/with,comma.csv'`. - -### Decimal scalar formatting uses human-readable values - -Decimal scalar literals in `EXPLAIN` output, expression display strings, and -auto-generated column names now format the decimal value using its scale while -still showing the precision and scale. For example, a `Decimal128` literal with -stored value `1`, precision `1`, and scale `1` is now rendered as -`Decimal128(0.1,1,1)` instead of `Decimal128(Some(1),1,1)`. When formatting a -`ScalarValue` directly, it now appears as `0.1` instead of `Some(1),1,1`. - -`NULL` decimal literals were previously shown as `Decimal128(None,10,2)`; they -will now appear as `Decimal128(NULL,10,2)`. - -Query result values already used human-readable decimal formatting and are -unchanged. - -### `Coercion` supports dictionary encoding preservation - -`datafusion_expr_common::signature::Coercion` now supports optional dictionary -encoding preservation. Typed coercions materialize dictionary inputs by -default, including both `TypeSignatureClass::Native(...)` and broader classes -such as `Integer`, `Numeric`, and `Binary`. When preservation is enabled, -DataFusion instead coerces dictionary inputs to -`Dictionary(original_key_type, coerced_value_type)` instead of materializing them -to the coerced value type. - -User-defined functions can opt in by setting dictionary encoding preservation on -the relevant coercion: - -```rust -Coercion::new_exact(TypeSignatureClass::Native(logical_string())) - .with_encoding_preservation(EncodingPreservation::dictionary()) -``` - -This changes the coerced argument type passed to the function. If a function -derives its return type from that coerced argument type, code that checks exact -result types may need to update its expectations or add an explicit cast to -materialize the result. - -This changes the previous behavior of typed non-native classes such as -`Integer` and `Binary`, which retained the physical dictionary type by default. -UDFs relying on that behavior must now explicitly enable dictionary -preservation. `TypeSignatureClass::Any` is unaffected. - -### `GroupsAccumulator::merge_batch` no longer takes `opt_filter` - -The `opt_filter` argument has been removed from -`datafusion_expr_common::groups_accumulator::GroupsAccumulator::merge_batch`: - -```diff - fn merge_batch( - &mut self, - values: &[ArrayRef], - group_indices: &[usize], -- opt_filter: Option<&BooleanArray>, - total_num_groups: usize, - ) -> Result<()>; -``` - -Aggregate `FILTER` clauses only apply to raw input rows during the partial -(update) phase, so by the time intermediate states are merged there is nothing -left to filter per row. In practice `opt_filter` was always `None` here, so -removing it makes the API self-explanatory and impossible to misuse. - -**Who is affected:** - -- Anyone with a custom `GroupsAccumulator` implementation. -- Anyone calling `merge_batch` directly. - -**Migration guide:** - -Drop the `opt_filter` argument from your `merge_batch` signature and from any -call sites: - -```diff - fn merge_batch( - &mut self, - values: &[ArrayRef], - group_indices: &[usize], -- opt_filter: Option<&BooleanArray>, - total_num_groups: usize, - ) -> Result<()> { - // ... - } -``` - -```diff -- acc.merge_batch(values, group_indices, None, total_num_groups)?; -+ acc.merge_batch(values, group_indices, total_num_groups)?; -``` - -If your implementation previously inspected `opt_filter` (for example asserting -it was `None`), that code can simply be deleted. - -See [issue #22775](https://github.com/apache/datafusion/issues/22775) for details. - -### `GroupsAccumulator::convert_to_state` is now required - -`datafusion_expr_common::groups_accumulator::GroupsAccumulator::convert_to_state` -no longer provides a default implementation, and the -`GroupsAccumulator::supports_convert_to_state` capability method has been -removed. All `GroupsAccumulator` implementations must now support converting -input batches directly to intermediate aggregate state. - -**Who is affected:** - -- Users with custom `GroupsAccumulator` implementations. -- FFI providers and consumers that use `FFI_GroupsAccumulator`. - -**Migration guide:** - -Custom `GroupsAccumulator` implementations must now provide their own -`convert_to_state` implementation. - -Delete `supports_convert_to_state` implementations because `convert_to_state` -is now required: - -```diff -- fn supports_convert_to_state(&self) -> bool { -- true -- } -``` - -The `supports_convert_to_state` field has also been removed from -`datafusion_ffi::udaf::groups_accumulator::FFI_GroupsAccumulator`, changing its -ABI layout. Rebuild both FFI providers and consumers against DataFusion 55, and -do not exchange this struct with libraries built against older major versions. - -See [issue #23081](https://github.com/apache/datafusion/issues/23081) for details. - -### `is_dynamic_physical_expr` is deprecated - -`datafusion_physical_expr_common::physical_expr::is_dynamic_physical_expr` is -deprecated. It was a thin wrapper over `snapshot_generation(expr) != 0` used to -ask "does this predicate contain a dynamic filter?". - -Prefer asking the question directly against the concrete type. For a one-off -check, downcast to `DynamicFilterPhysicalExpr`: - -```rust -use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr; -use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; - -let mut is_dynamic = false; -predicate.apply(|e| { - if e.downcast_ref::().is_some() { - is_dynamic = true; - Ok(TreeNodeRecursion::Stop) - } else { - Ok(TreeNodeRecursion::Continue) - } -})?; -``` - -If you also need to know whether the dynamic filters can still change (and to be -notified when they do), use the new `DynamicFilterTracking` / -`DynamicFilterTracker` API in `datafusion_physical_expr`: - -```rust -use datafusion_physical_expr::DynamicFilterTracking; - -let tracking = DynamicFilterTracking::classify(&predicate); -if tracking.contains_dynamic_filter() { - // worth re-evaluating the predicate at runtime -} -``` - -### `PruningPredicate::try_new` is deprecated - -`datafusion_pruning::PruningPredicate::try_new` is deprecated. Use -`PruningPredicateBuilder` instead. The deprecated constructor remains available -in DataFusion 55 and preserves its existing behavior. - -```rust -// Before -let predicate = PruningPredicate::try_new(expr, schema)?; - -// After -let predicate = PruningPredicateBuilder::new() - .with_file_schema(schema) - .try_build(expr)?; -``` - -### `FilePruner::try_new` no longer builds a pruner for static predicates without statistics - -`datafusion_pruning::FilePruner::try_new` now returns `None` when the predicate -is purely static _and_ the file carries no usable column statistics, because -such a pruner can never prune anything beyond what planning already did. -Previously it returned `Some` whenever a statistics struct was present (the -"is this worth pruning?" decision lived in the Parquet opener). Files with column -statistics, and predicates that carry a dynamic filter, are unaffected. - -### `QueryPlanner` adds `Any` as a supertrait - -To enable downcasting of `dyn QueryPlanner` to concrete query planner types (via -`is::()` / `downcast_ref::()`), the `QueryPlanner` trait now has `Any` -as a supertrait: - -```diff -- pub trait QueryPlanner: Debug -+ pub trait QueryPlanner: Any + Debug -``` - -### `ExecutionPlan::partition_statistics` deprecated in favor of `statistics_from_inputs` - -`ExecutionPlan::partition_statistics` is deprecated. Statistics computation is -now split into two parts: - -- `StatisticsContext` owns the bottom-up plan-tree traversal and a per-walk - cache of memoized child statistics. Call `StatisticsContext::compute` to - obtain statistics for a plan. -- `ExecutionPlan::statistics_from_inputs` computes a node's statistics from its - children's already-resolved statistics, which the context passes in. The node - does not traverse the tree itself. - -Existing implementations of `partition_statistics` continue to work unchanged. -The default `statistics_from_inputs` delegates to the deprecated method, so no -migration is required until the deprecated method is removed. - -> **Warning:** The delegation is **one-way**: the default `statistics_from_inputs` -> calls `partition_statistics`, but the default `partition_statistics` does -> **not** call `statistics_from_inputs` — it returns `Statistics::new_unknown`. -> Nodes that override only `statistics_from_inputs` will silently return -> `Statistics::new_unknown` to any caller still using the deprecated -> `partition_statistics`. - -**Who is affected:** - -- Users who implement custom `ExecutionPlan` nodes (recommended to migrate) -- Users who call `partition_statistics` directly (recommended to switch to `StatisticsContext::compute`) - -**Migration guide:** - -For **implementations**, override `statistics_from_inputs` instead of -`partition_statistics`, plus `child_stats_requests` to declare which children to -resolve. Child statistics then arrive pre-computed in `input_stats` (one entry per -child, in `children()` order), so the node only expresses its local propagation -logic. Leaf nodes, and nodes that derive their statistics without reading children, -need neither override (the default `child_stats_requests` skips every child). - -```rust,ignore -// Before: -fn partition_statistics(&self, partition: Option) -> Result> { - let child_stats = self.input.partition_statistics(partition)?; - // ... transform child_stats ... -} - -// After: declare the child to resolve, then compute from its statistics. -fn child_stats_requests(&self, partition: Option) -> Vec { - vec![ChildStats::At(partition)] -} - -fn statistics_from_inputs( - &self, - input_stats: &[Arc], - args: &StatisticsArgs, -) -> Result> { - let child_stats = Arc::clone(&input_stats[0]); - // ... transform child_stats ... -} -``` - -> **Important:** the default `child_stats_requests` skips every child, so a node that -> reads `input_stats` must override it to declare the children it uses, or those slots -> are filled with `Statistics::new_unknown` placeholders. Request a child with -> `ChildStats::At(partition)` (`None` = overall) and omit one with `ChildStats::Skip`. -> For example, a partition-merging operator requests `ChildStats::At(None)`, and a -> broadcast join requests its build side at `None`. - -For **callers**, walk a plan through `StatisticsContext::compute`. The cache is -created with the context: - -```rust,ignore -use datafusion_physical_plan::{StatisticsArgs, StatisticsContext}; - -// Before: -let stats = plan.partition_statistics(None)?; - -// After: -let stats = StatisticsContext::new().compute(plan.as_ref(), &StatisticsArgs::new())?; -``` - -### `DdlStatement::CreateExternalTable` and `CreateFunction` are now boxed - -The two largest variants of `datafusion_expr::DdlStatement` are now -`Box`ed: - -```rust,ignore -// Before -pub enum DdlStatement { - CreateExternalTable(CreateExternalTable), - // ... - CreateFunction(CreateFunction), - // ... -} - -// After -pub enum DdlStatement { - CreateExternalTable(Box), - // ... - CreateFunction(Box), - // ... -} -``` - -`CreateExternalTable` is 312 bytes and `CreateFunction` is 288 bytes, so -without boxing they forced the entire `LogicalPlan` enum to 320 bytes -even on SELECT-only query paths that never instantiate them. Boxing -shrinks `LogicalPlan` from 320 → 176 bytes (−45%), making every -`mem::take` / `mem::swap` / `Arc` store on the planning -hot path move a smaller payload. - -**Who is affected:** - -- Users who construct `DdlStatement::CreateExternalTable(...)` or - `DdlStatement::CreateFunction(...)` from an owned struct. -- Users who pattern-match these variants and destructure the inner - struct in the same pattern (e.g. - `DdlStatement::CreateExternalTable(CreateExternalTable { name, .. })`). -- Code that consumes the inner struct out of these variants (e.g. to - pass `CreateExternalTable` by value to another function). - -**Migration guide:** - -When constructing the variants, wrap the inner struct in `Box::new`: - -```rust,ignore -// Before -let stmt = DdlStatement::CreateFunction(CreateFunction { name, args, .. }); - -// After -let stmt = DdlStatement::CreateFunction(Box::new(CreateFunction { - name, - args, - .. -})); -``` - -When pattern-matching, bind the boxed value and either access fields -through it (Rust auto-derefs the `Box`) or destructure via `.as_ref()`: - -```rust,ignore -// Before -match ddl { - DdlStatement::CreateExternalTable(CreateExternalTable { - name, location, .. - }) => { /* use name, location */ } -} - -// After — access fields through the box -match ddl { - DdlStatement::CreateExternalTable(ce) => { - let name = &ce.name; - let location = &ce.location; - /* ... */ - } -} - -// After — destructure the dereferenced struct -match ddl { - DdlStatement::CreateExternalTable(ce) => { - let CreateExternalTable { name, location, .. } = ce.as_ref(); - /* ... */ - } -} -``` - -When you need an owned `CreateExternalTable` / `CreateFunction` out of -the variant, dereference the box with `*`: - -```rust,ignore -// Before -match plan { - LogicalPlan::Ddl(DdlStatement::CreateExternalTable(cmd)) => Ok(cmd), - _ => { /* ... */ } -} - -// After -match plan { - LogicalPlan::Ddl(DdlStatement::CreateExternalTable(cmd)) => Ok(*cmd), - _ => { /* ... */ } -} -``` - -See [PR #22733](https://github.com/apache/datafusion/pull/22733) for -details, including the per-variant size breakdown and benchmark -results. - -### `ExecutionPlan::with_new_children` and `ExecutionPlan::with_new_children_and_same_properties` deprecated - -`with_new_children` and `with_new_children_and_same_properties` have been -deprecated. These methods are used to replace the child plans of an -`ExecutionPlan` while leaving the plan otherwise identical. - -`with_new_children_if_necessary` has also been deprecated in favor of -`replace_children_if_necessary` for consistency in naming. - -As noted [here](https://github.com/apache/datafusion/pull/23332#discussion_r3554897693), -while the addition of `with_new_children_and_same_properties` has the benefit -of skipping potentially expensive computation in the case that replacement children -have the same properties as the original children, it widens the API surface area -of `ExecutionPlan` in a way that could be confusing for users. - -Thus, to rectify this, we unify these methods by introducing `replace_children`. -`replace_children` solves this problem by taking `ReplaceChildrenOptions`, -which includes a `ChildrenPropertiesMode`. The mode has two variants, -`Keep` and `Recompute`, which tell `replace_children` whether plan -properties can be reused or need to be recomputed. - -This method is called from `replace_children_if_necessary`, which is the -standard entry point that should be used for replacing the children of a node. - -**Migration guide:** - -To migrate from `with_new_children` and `with_new_children_and_same_properties` -to `replace_children`, it is recommended to implement `replace_children` with -a `match` statement matching on the `ChildrenPropertiesMode`. In the case that -the properties match the children, `ChildrenPropertiesMode::Keep`, -follow the body of `with_new_children_and_same_properties`. In the case that -the properties do not match the children, `ChildrenPropertiesMode::Recompute`, -follow the body of `with_new_children`. - -For example, take a look at the implementation for `FilterExec`: - -``` - fn replace_children( - self: Arc, - mut children: Vec>, - options: ReplaceChildrenOptions, - ) -> Result> { - validate_child_count!(self, children); - match options.children_properties { - ChildrenPropertiesMode::Keep => Ok(Arc::new(Self { - input: children.swap_remove(0), - metrics: ExecutionPlanMetricsSet::new(), - ..Self::clone(&*self) - })), - ChildrenPropertiesMode::Recompute => { - let new_input = children.swap_remove(0); - FilterExecBuilder::from(&*self) - .with_input(new_input) - .build() - .map(|e| Arc::new(e) as _) - } - } - } -``` - -In the case that the options indicate the properties are the same, we can simply -swap the children without having to recompute the properties. In the other case, -we create a new node from scratch. - -To ensure that this works correctly, it is recommended that users also look -through their codebase and ensure that they use `replace_children_if_necessary` -for these changes — `replace_children_if_necessary` should be preferred over -manual use of `replace_children`, since `replace_children_if_necessary` will -call `replace_children` with the correct options filled in. - -See [PR #23903](https://github.com/apache/datafusion/pull/23903) for details. - -### `ListingOptions::target_partitions` and `collect_stat` removed - -The `target_partitions` and `collect_stat` fields on -`datafusion_catalog_listing::ListingOptions`, their builder methods -(`with_target_partitions`, `with_collect_stat`), and the -`with_session_config_options` helper have been removed. - -`ListingTable` now reads both values directly from the active `SessionConfig` -at scan time instead of from a copy snapshotted onto the table at construction -time. - -**Who is affected:** - -- Code that set `target_partitions` / `collect_stat` per table via - `ListingOptions`, or read those public fields. -- Code that relied on a `ListingTable` freezing these values at construction - time independently of the session config. The table now always reflects the - current `SessionConfig`. - -**Migration guide:** - -Configure these on the `SessionConfig` instead: - -```rust,ignore -// Before -let options = ListingOptions::new(format) - .with_target_partitions(8) - .with_collect_stat(true); - -// After -let config = SessionConfig::new() - .with_target_partitions(8) - .with_collect_statistics(true); -``` - -See [PR #22969](https://github.com/apache/datafusion/pull/22969) for details. - -### Spark map functions now reject duplicate keys by default - -The Spark-compatibility map-construction functions (`map_from_arrays`, -`map_from_entries`, `str_to_map`) now raise `[DUPLICATED_MAP_KEY]` at runtime -when constructing a map that contains duplicate keys. This matches the default -of Spark's [`spark.sql.mapKeyDedupPolicy`](https://github.com/apache/spark/blob/v4.0.0/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala#L4502-L4511). - -A new config option, `datafusion.spark.map_key_dedup_policy`, controls the -behavior: - -- `EXCEPTION` (default): raise on any duplicate key. -- `LAST_WIN`: keep the last occurrence of each duplicate key. The key stays at - its first-seen position with the value from its last occurrence (matching - Spark's `ArrayBasedMapBuilder`). - -**Who is affected:** - -- Queries calling `map_from_arrays` or `str_to_map` on data that contains - duplicate keys. Previously these functions either tolerated duplicates - silently or raised a non-configurable error. - -**Migration guide:** - -To restore lenient duplicate-key handling, set the policy to `LAST_WIN`: - -```sql -SET datafusion.spark.map_key_dedup_policy = 'LAST_WIN'; -``` - -See [PR #21720](https://github.com/apache/datafusion/pull/21720) for details. - -### Unify LRU memory-limiting caches into one generic cache - -The caches `DefaultFileMetadataCache`, `DefaultListFilesCache` and `DefaultFileStatisticsCache` -are merged into one generic implementation `DefaultCache`. The corresponding traits are now -type aliases: - -```diff -- pub trait FileStatisticsCache: CacheAccessor -- pub trait ListFilesCache: CacheAccessor -- pub trait FileMetadataCache: CacheAccessor -+ pub type FileStatisticsCache = dyn Cache; -+ pub type ListFilesCache = dyn Cache; -+ pub type FileMetadataCache = dyn Cache; -``` - -**Who is affected:** - -- Users who introduced their own implementation of `FileMetadataCache`, `ListFilesCache` or `FileStatisticsCache`. - -**Migration guide:** - -Implement the newly introduced types for your custom cache implementation. - -See [PR #22613](https://github.com/apache/datafusion/pull/22613) for details. - -### `CachedFileMetadata` now validates file schema - -The file-statistics cache remains keyed by `TableScopedPath`, but -`CachedFileMetadata` now stores a `SchemaFingerprint` of the `file_schema` used -to compute the cached statistics. Cache hits are valid only when both the file -metadata and schema fingerprint match. - -**Who is affected:** - -- Users constructing `CachedFileMetadata` values directly. - -**Migration guide:** - -- Pass `Arc::new(SchemaFingerprint::from_schema(file_schema))` to - `CachedFileMetadata::new`. -- Pass the current schema fingerprint to `CachedFileMetadata::is_valid_for`. - -See [PR #23201](https://github.com/apache/datafusion/pull/23201) for details. - -### `EmptyExecNode` and `PlaceholderRowExecNode` gained a `partitions` field - -The generated protobuf structs `EmptyExecNode` and `PlaceholderRowExecNode` -encoded only a schema, so the partition count set by `EmptyExec::with_partitions` -was silently dropped when a physical plan was serialized and deserialized: a plan -that reported `n` partitions before encoding reported `1` after. Both messages now -carry a `partitions` field that round-trips the count. - -**Who is affected:** - -- Users constructing `EmptyExecNode` or `PlaceholderRowExecNode` with an - exhaustive struct literal. - -**Migration guide:** - -Set the new field, or fill it from `Default`: - -```rust,ignore -// Before -EmptyExecNode { schema: Some(schema) } - -// After -EmptyExecNode { schema: Some(schema), partitions: 4 } -// or -EmptyExecNode { schema: Some(schema), ..Default::default() } -``` - -The wire format stays compatible in both directions. Plans encoded before this -field existed decode as a single partition, the previous default, and plans -encoded after it add a field that older readers ignore. - -See [PR #23643](https://github.com/apache/datafusion/pull/23643) for details. - -### `time ± interval` now returns a `time` instead of an `interval` - -Adding or subtracting an `interval` to/from a `time` value now returns a `time` -that wraps within the 24-hour clock, matching PostgreSQL and DuckDB. Previously -DataFusion returned an `interval`. - -```sql --- 55.0.0 onwards: returns a time -SELECT time '23:30:00' + interval '2 hours'; --- 01:30:00 -``` - -Only the sub-day portion of the interval affects the result; whole days and -months are ignored, as in PostgreSQL. The result keeps the input time's unit -(mirroring `timestamp + interval`), and any interval precision finer than that -unit is truncated -- so `time(s) + interval '1 nanosecond'` is a no-op. - -See [PR #23279](https://github.com/apache/datafusion/pull/23279) for details. - -### Physical-planning state moved to an explicit `PhysicalPlanningContext` - -The `subquery_indexes` and `subquery_results` public fields on -`datafusion_expr::execution_props::ExecutionProps` have been removed. They were -added in `54.0.0` as the channel through which the physical planner passed -uncorrelated scalar-subquery state to functions that create physical -`Arc` values from logical `Expr` values. - -The `lambda_variable_qualifier` public field and the -`with_qualified_lambda_variables` method on `ExecutionProps` have been removed -for the same reason: they carried the qualifiers of the lambda variables in -scope while `create_physical_expr` descended into a lambda body. - -That state is now carried by a dedicated -`datafusion_expr::physical_planning_context::PhysicalPlanningContext` passed explicitly -through functions and planner traits. Unlike `ExecutionProps`, which applies -throughout the planning of an entire query, this context is scoped to the -logical plan subtree currently being converted. This removes the need for the -physical planner to clone and mutate a `SessionState`, is a prerequisite for -letting the planner take `&dyn Session`, and lets `ExtensionPlanner` -implementations create physical -expressions containing scalar subqueries against the same subquery state as the -rest of the plan. - -The following functions take a new trailing -`planning_ctx: &PhysicalPlanningContext` parameter: - -- `datafusion_physical_expr::create_physical_expr` / `create_physical_exprs` -- `datafusion_physical_expr::create_physical_sort_expr` / - `create_physical_sort_exprs` / `create_physical_partitioning` -- `datafusion::physical_planner::create_window_expr` / - `create_window_expr_with_name` -- `datafusion_physical_expr::aggregate::LoweredAggregateBuilder::new` - -The planner traits changed accordingly: - -- `PhysicalPlanner::create_physical_expr` takes - `planning_ctx: &PhysicalPlanningContext` -- `ExtensionPlanner::plan_extension` and `plan_table_scan` receive - `planning_ctx: &PhysicalPlanningContext` and should forward it to - `PhysicalPlanner::create_physical_expr` when creating physical expressions - -Convenience methods such as `SessionContext::create_physical_expr` and -`SessionState::create_physical_expr` are unchanged. - -**Who is affected:** - -- Code calling the functions above: pass - `&PhysicalPlanningContext::default()` unless you are creating physical - expressions as part of a physical plan that contains uncorrelated scalar - subqueries. -- Custom `PhysicalPlanner` or `ExtensionPlanner` implementations: add the new - parameter and forward it. -- Code that read or wrote `execution_props.subquery_indexes` / - `execution_props.subquery_results`: build a `PhysicalPlanningContext` instead. -- Code that read `execution_props.lambda_variable_qualifier` or called - `ExecutionProps::with_qualified_lambda_variables`: remove that usage. Callers - that only plan a `HigherOrderFunction` are not affected -- - `create_physical_expr` populates the lambda qualifiers itself as it descends - into lambda bodies. Code that needs to read or extend the lambda - scope should use the equivalents on `PhysicalPlanningContext`: - `PhysicalPlanningContext::lambda_variable_qualifier` and - `PhysicalPlanningContext::with_qualified_lambda_variables`. - -**Migration guide:** - -When creating a physical expression outside of physical planning, pass an empty -context: - -```rust,ignore -use datafusion_expr::physical_planning_context::PhysicalPlanningContext; -use datafusion_physical_expr::create_physical_expr; - -// Before -let phys = create_physical_expr(&expr, &schema, &props)?; - -// After -let phys = create_physical_expr( - &expr, - &schema, - &props, - &PhysicalPlanningContext::default(), -)?; -``` - -For `ExtensionPlanner` implementations, accept and forward the context: - -```rust,ignore -async fn plan_extension( - &self, - planner: &dyn PhysicalPlanner, - node: &dyn UserDefinedLogicalNode, - logical_inputs: &[&LogicalPlan], - physical_inputs: &[Arc], - session: &dyn Session, - planning_ctx: &PhysicalPlanningContext, // new parameter -) -> Result>> { - for expr in node.expressions() { - // Forward the context so scalar subqueries in this node's - // expressions resolve against the plan's subquery state - planner.create_physical_expr(&expr, node.schema(), session, planning_ctx)?; - } - // ... -} -``` - -See [PR #23649](https://github.com/apache/datafusion/pull/23649) and -[PR #23989](https://github.com/apache/datafusion/pull/23989) for details. - -### Catalog, planner, and optimizer contracts moved to `datafusion-session` - -The catalog, planner, and physical optimizer contract traits now live in the -`datafusion-session` crate. This makes them available through `Session` without -downcasting to `SessionState`, including across the FFI boundary. - -The moved catalog traits are `CatalogProviderList`, `CatalogProvider`, -`SchemaProvider`, `TableProvider`, `TableProviderFactory`, and -`TableFunctionImpl`. The related `TableFunction` struct also moved. The -`datafusion-catalog` crate re-exports these items from their new location, so -paths such as `datafusion::catalog::TableProvider` and -`datafusion_catalog::CatalogProvider` continue to work unchanged. - -The moved planning and optimization traits are `QueryPlanner`, -`PhysicalPlanner`, `ExtensionPlanner`, `PhysicalOptimizerRule`, and -`PhysicalOptimizerContext`. Their previous paths also continue to work through -re-exports: - -- `datafusion::execution::context::QueryPlanner` -- `datafusion::physical_planner::{PhysicalPlanner, ExtensionPlanner}` -- `datafusion_physical_optimizer::{PhysicalOptimizerRule, PhysicalOptimizerContext}` - -The session argument for methods on `QueryPlanner`, `PhysicalPlanner`, and -`ExtensionPlanner` changed from `&SessionState` to `&dyn Session`. Custom planner -implementations should update their signatures. Planner code should use methods -on `Session` instead of downcasting it to `SessionState`. - -The `Session` trait now requires a `catalog_list` method that returns the -catalogs registered with the session: - -```rust -fn catalog_list(&self) -> Arc; -``` - -Custom `Session` implementations must add this method. Implementations that do -not expose a catalog can return the new `EmptyCatalogProviderList`: - -```rust -use std::sync::Arc; -use datafusion_session::{CatalogProviderList, EmptyCatalogProviderList}; - -fn catalog_list(&self) -> Arc { - Arc::new(EmptyCatalogProviderList) -} -``` - -`Session` gains a `query_planner` method alongside `optimize`, -`physical_optimizers`, and `statistics_registry`. All four have default -implementations, so existing `Session` implementations that do not perform -physical planning require no changes: `query_planner` defaults to the new -`UnsupportedQueryPlanner`, `optimize` returns the plan unchanged, -`physical_optimizers` returns no rules, and `statistics_registry` returns -`None`. - -A custom session that drives planning through `DefaultQueryPlanner` or -`DefaultPhysicalPlanner` must override these methods to expose its planning and -optimization behavior; the defaults will otherwise produce unoptimized plans or -fail to plan at all. The simplest approach is to delegate to a `SessionState`: - -```rust -use std::sync::Arc; -use datafusion_session::{PhysicalOptimizerRule, QueryPlanner}; - -fn query_planner(&self) -> Arc { - self.inner.query_planner() -} - -fn optimize(&self, plan: &LogicalPlan) -> Result { - self.inner.optimize(plan) -} - -fn physical_optimizers(&self) -> &[Arc] { - self.inner.physical_optimizers() -} -``` - -`ForeignSession::create_physical_plan` runs the complete planning pipeline in the -library that owns the session. `ForeignSession::query_planner`, `optimize`, and -`physical_optimizers` forward to the owning session across the FFI boundary. A -foreign query planner can also be installed on a session through the new -`datafusion_ffi::query_planner::FFI_QueryPlanner`; see that module's -documentation for how plans and extension codecs cross the boundary. - -See [PR #23703](https://github.com/apache/datafusion/pull/23703) for details on -the catalog changes. - -### `FFI_LogicalExtensionCodec::task_ctx_provider` is now private - -The `task_ctx_provider` field on -`datafusion_ffi::proto::logical_extension_codec::FFI_LogicalExtensionCodec` was -`pub` and is now crate-private, matching `FFI_PhysicalExtensionCodec`. - -**Who is affected:** - -- Code that read or cloned `FFI_LogicalExtensionCodec::task_ctx_provider` - directly. Pass the task context provider to `FFI_LogicalExtensionCodec::new` - instead, and keep your own copy if you need it elsewhere. - -### Unused `async` removed from several public functions - -Public functions that were declared `async` but never awaited anything are now -synchronous: - -- `CsvFormat::read_to_delimited_chunks_from_stream` (in - `datafusion_datasource_csv`, re-exported as - `datafusion::datasource::file_format::csv::CsvFormat`) -- `datafusion_substrait::serializer::deserialize_bytes`, which now also borrows - its input as `&[u8]` instead of taking an owned `Vec` -- `datafusion::test_util::parquet::TestParquetFile::create_scan` - -**Migration guide:** - -Remove `.await` from call sites; the compiler flags each one, since `.await` -on a non-future value does not compile: - -```rust,ignore -// Before -let stream = csv_format - .read_to_delimited_chunks_from_stream(input) - .await; -let plan = deserialize_bytes(proto_bytes).await?; - -// After -let stream = csv_format.read_to_delimited_chunks_from_stream(input); -let plan = deserialize_bytes(&proto_bytes)?; -``` - -### `MovingMin` and `MovingMax` changed to `pub(crate)` - -`MovingMin` and `MovingMax` in `datafusion_functions_aggregate::min_max` have been changed from `pub` to `pub(crate)` visibility as they are internal helper data structures for DataFusion's sliding window aggregators. - -**Who is affected:** - -- Code that directly imported `MovingMin` or `MovingMax` from `datafusion_functions_aggregate`. Standard SQL window functions (`MIN(...) OVER (...)` / `MAX(...) OVER (...)`) are unaffected. - -See [PR #23827](https://github.com/apache/datafusion/pull/23827) for details. - -### `RecursiveQuery` gained a `schema` field - -`datafusion_expr::logical_plan::RecursiveQuery` exposed the static (anchor) term's -schema to parent plans, which ignored columns that only the recursive term makes -nullable. The node now stores the schema reconciled from both terms explicitly, so -it can no longer be built with an exhaustive struct literal. - -**Who is affected:** - -- Code constructing `RecursiveQuery` with a struct literal. This change also - shipped in `54.1.0`, so the same migration applies within the `54` series. - -**Migration guide:** - -Build the node with `RecursiveQuery::try_new`, which computes the schema and -returns an error if the two terms do not have the same number of columns: - -```rust,ignore -// Before -let query = RecursiveQuery { - name, - static_term, - recursive_term, - is_distinct, -}; - -// After -let query = RecursiveQuery::try_new(name, static_term, recursive_term, is_distinct)?; -``` - -`RecursiveQueryExec::try_new` takes the reconciled schema as its second argument -for the same reason, rather than deriving it from its children. - -See [PR #22552](https://github.com/apache/datafusion/pull/22552) for details. - -### `ExecutionPlan::apply_expressions` is now a required method - -`apply_expressions` has been added as a **required** method on the `ExecutionPlan`, `FileSource`, and `DataSource` traits. Any custom implementation of -these traits must now implement `apply_expressions`. See docs on `ExecutionPlan::apply_expressions` for migration details. - -### `WindowExpr::evaluate_stateful` now takes a `WindowEvalContext` - -`WindowExpr::evaluate_stateful` (and the provided -`AggregateWindowExpr::aggregate_evaluate_stateful` method) take a new -`WindowEvalContext` argument carrying stream-level information that is shared -by all partitions: - -```rust,ignore -// Before -fn evaluate_stateful( - &self, - partition_batches: &PartitionBatches, - window_agg_state: &mut PartitionWindowAggStates, -) -> Result<()> - -// After -fn evaluate_stateful( - &self, - partition_batches: &PartitionBatches, - window_agg_state: &mut PartitionWindowAggStates, - eval_ctx: &WindowEvalContext<'_>, -) -> Result<()> -``` - -`WindowEvalContext` currently carries the most recent input row, which -previously lived in each partition's `PartitionBatchState` (see the next -section). The struct is `#[non_exhaustive]` so that fields can be added -without further signature changes: construct it with -`WindowEvalContext::default()` and set fields through its builder methods. - -**Who is affected:** - -- Implementations of the `WindowExpr` trait that override `evaluate_stateful` - must add the new parameter. -- Callers of `evaluate_stateful` or `aggregate_evaluate_stateful` must pass a - context. - -**Migration guide:** - -```rust,ignore -use datafusion_physical_expr::window::WindowEvalContext; - -// Before -window_expr.evaluate_stateful(&partition_batches, &mut window_agg_state)?; - -// After -let eval_ctx = WindowEvalContext::default() - .with_most_recent_row(most_recent_row.as_ref()); -window_expr.evaluate_stateful( - &partition_batches, - &mut window_agg_state, - &eval_ctx, -)?; -``` - -Pass `WindowEvalContext::default()` when no most-recent-row watermark is -available (for example, when the input is sorted by the partition keys and -partition ends are detected directly). - -### `PartitionBatchState::most_recent_row` removed - -The `most_recent_row` field and the `set_most_recent_row` method have been -removed from `datafusion_expr::window_state::PartitionBatchState`. The most -recent input row is a property of the whole input stream rather than -per-partition state: every partition observed the same value. It is now -tracked once by the operator driving the evaluation and passed to window -expressions through the new `WindowEvalContext` argument of -`WindowExpr::evaluate_stateful` described above. - -**Who is affected:** - -- Code that read `PartitionBatchState::most_recent_row` or called - `set_most_recent_row`, such as custom streaming window operators. - -**Migration guide:** - -Track the most recent input row once per stream (for example, a one-row -slice of the last non-empty input batch) and pass it to window expressions -via `WindowEvalContext::with_most_recent_row` instead of copying it into -each partition's state. - -### `MSRV` updated to 1.94.0 - -The Minimum Supported Rust Version (MSRV) has been updated to [`1.94.0`]. - -[`1.94.0`]: https://releases.rs/docs/1.94.0/ - -### `CachedParquetFileReader` removed; `ParquetFileReader` fields are now private - -`CachedParquetFileReader` duplicated `ParquetFileReader` and has been removed; -`ParquetFileReader`'s fields are also now private, with -`file_metrics()` and `partitioned_file()` accessors added for the two that -were previously public. - -**Who is affected:** - -- Code that names the `CachedParquetFileReader` type. -- Code that constructs a `ParquetFileReader` directly via a struct literal, or - reads/writes its fields. - -**Migration guide:** - -`ParquetFileReader::new` is no longer public; build a reader through -`ParquetFileReaderFactory::create_reader` (via `DefaultParquetFileReaderFactory` -or `CachedParquetFileReaderFactory`) instead of constructing one directly: - -```rust,ignore -// Before -let inner = ParquetObjectReader::new(Arc::clone(&store), location).with_file_size(size); -let reader = CachedParquetFileReader::new( - file_metrics, - store, - inner, - partitioned_file, - metadata_cache, - metadata_size_hint, -); - -// After -let reader = CachedParquetFileReaderFactory::new(store, metadata_cache) - .create_reader(partition_index, partitioned_file, metadata_size_hint, &metrics)?; -``` - -Replace field access with the new accessor methods: - -```rust,ignore -// Before -let bytes_scanned = reader.file_metrics.bytes_scanned.value(); -let location = &reader.partitioned_file.object_meta.location; - -// After -let bytes_scanned = reader.file_metrics().bytes_scanned.value(); -let location = &reader.partitioned_file().object_meta.location; -``` - -### `array_distance` scalar function now rejects multidimensional arrays - -`array_distance` only supports one-dimensional arrays. Previously, when given -multidimensional arrays, it computed the distance using only the first -subarray and ignored the remaining subarrays. For example: - -```sql -SELECT array_distance( - [[1, 2], [100, 100]], - [[1, 4], [0, 0]] -); -``` - -Previously, this query returned `2.0`, the distance between `[1, 2]` and -`[1, 4]`. It now returns a planning error stating that `array_distance` only -supports one-dimensional arrays. - -### `ExprType` gained a `SqlSimilarToPattern` variant - -`SIMILAR TO` with a non-literal (column- or expression-based) pattern is now -represented by a new `SqlSimilarToPattern` physical expression, so it can be -serialized. The generated `ExprType` enum on `PhysicalExprNode` gained a -matching `SqlSimilarToPattern` variant (tag 28). - -**Who is affected:** - -- Users matching exhaustively on `ExprType` (for example in a custom - physical-plan encoder/decoder). - -**Migration guide:** - -Add a `SqlSimilarToPattern` arm, or fall back to a wildcard arm: - -```rust,ignore -match expr_type { - // ... - ExprType::SqlSimilarToPattern(node) => { /* ... */ } - _ => { /* ... */ } -} -``` - -Plans encoded before this variant existed are unaffected: they never produced -this variant, so decoding is unchanged. Plans containing a dynamic -`SIMILAR TO` pattern encoded after this change fail to decode on older -readers that don't recognize the new tag. - -See [PR #23188](https://github.com/apache/datafusion/pull/23188) for details. - -### `ParquetObjectReader` / `ParquetObjectWriter` deprecated upstream - -The [`parquet` crate] deprecated [`ParquetObjectReader`] -and [`ParquetObjectWriter`] in favor of implementing -[`AsyncFileReader`] directly (see the example on the [`AsyncFileReader`] trait and -[`parquet/examples/object_store.rs`] in `arrow-rs`) or passing an -[`BufWriter`] straight to [`AsyncArrowWriter`]. - -**Who is affected:** - -- Custom [`ParquetFileReaderFactory`] implementations that construct a - [`ParquetObjectReader`] directly and now see a deprecation warning after - upgrading the `parquet` dependency. - -**Migration guide:** - -If your [`AsyncFileReader`] implementation exists mainly to read from an -[`ObjectStore`] and track metrics, consider using DataFusion's -[`ParquetFileReader`] instead of wrapping a [`ParquetObjectReader`]: - -```rust,ignore -// Before -let inner = ParquetObjectReader::new(store, location).with_file_size(size); -Ok(Box::new(MyReader { inner, file_metrics, partitioned_file })) - -// After -Ok(Box::new(ParquetFileReader { - file_metrics, - store, - metadata_size_hint, - partitioned_file, -})) -``` - -If you need custom behavior (I/O coalescing, byte caching, a dedicated I/O -runtime), implement `AsyncFileReader` directly against your `ObjectStore`, -following the pattern in [`parquet/examples/object_store.rs`] - -See [PR #24030](https://github.com/apache/datafusion/pull/24030) for details. - -### `SortProperties::and_or` replaced by `and` and `or` - -`datafusion_expr_common::sort_properties::SortProperties::and_or` has been -removed. Call `and` for `AND` and `or` for `OR`: - -```rust,ignore -// Before (54.0.0) -let props = lhs.and_or(&rhs); - -// After (55.0.0) -let props = lhs.and(&rhs); // for AND -let props = lhs.or(&rhs); // for OR -``` - -The two operators do not preserve the same sort orders. `AND` keeps an ordering -only when nulls sort after `true` (`ASC NULLS LAST` or `DESC NULLS FIRST`), and -`OR` only when nulls sort before `false` (`ASC NULLS FIRST` or -`DESC NULLS LAST`). `and_or` did not say which operator the caller meant, so it -could not be right for both. - -See [PR #24276](https://github.com/apache/datafusion/pull/24276) for details. - -[`parquet` crate]: https://crates.io/crates/parquet -[`parquetobjectreader`]: https://docs.rs/parquet/59.1.0/parquet/arrow/async_reader/struct.ParquetObjectReader.html -[`parquetobjectwriter`]: https://docs.rs/parquet/59.1.0/parquet/arrow/async_writer/struct.ParquetObjectWriter.html -[`parquetfilereader`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/parquet/struct.ParquetFileReader.html -[`parquetfilereaderfactory`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/parquet/trait.ParquetFileReaderFactory.html -[`asyncfilereader`]: https://docs.rs/parquet/59.1.0/parquet/arrow/async_reader/trait.AsyncFileReader.html -[`objectstore`]: https://docs.rs/object_store/latest/object_store/trait.ObjectStore.html -[`bufwriter`]: https://docs.rs/tokio/latest/tokio/io/struct.BufWriter.html -[`asyncarrowwriter`]: https://docs.rs/parquet/59.1.0/parquet/arrow/async_writer/struct.AsyncArrowWriter.html -[`parquet/examples/object_store.rs`]: https://github.com/apache/arrow-rs/blob/main/parquet/examples/object_store.rs - -### `datafusion-proto`: parquet options conversions are fallible - -`protobuf::ParquetOptions` and `protobuf::TableParquetOptions` validate -`writer_version` when converting into their `datafusion-common` counterparts, so -those conversions are `TryFrom` rather than `From`. - -Every other `From` / `TryFrom` conversion between DataFusion types and -`datafusion_proto::protobuf` messages is unchanged. Several impls moved to the -crate that owns their DataFusion type, but trait impls are global, so -`X::try_from(&proto)` and `proto.try_into()` still resolve with no import -changes. - -**Migration guide:** - -```rust,ignore -// Before -let opts = ParquetOptions::from(&proto_opts); -let table_opts = TableParquetOptions::from(&proto_table_opts); - -// After -let opts = ParquetOptions::try_from(&proto_opts)?; -let table_opts = TableParquetOptions::try_from(&proto_table_opts)?; -``` - -See [issue #24019](https://github.com/apache/datafusion/issues/24019) for details. - -### RANGE window frames with offsets now reject ORDER BY types without arithmetic - -A `RANGE` frame offset such as `1 PRECEDING` is measured in `ORDER BY` values -rather than in rows, so the frame bound is computed as `current_value - 1`. That -requires arithmetic on the `ORDER BY` type. For types that have no such -arithmetic -- `Utf8`, `Binary`, `Boolean`, `List` and `Null` -- such frames are -now rejected when the query is planned: - -```sql -SELECT x, COUNT(*) OVER (ORDER BY x RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) -FROM (VALUES ('a'), ('b'), ('c')) t(x) -ORDER BY x; --- Error during planning: RANGE with offset PRECEDING/FOLLOWING is not supported for ORDER BY type Utf8 -``` - -What this replaces depends on the `ORDER BY` type. Over `Utf8`, `Boolean` and -`List` keys such queries planned successfully, and in DataFusion 54 the failing -frame-bound arithmetic was silently treated as an overflow -([#22140](https://github.com/apache/datafusion/pull/22140)): the bound collapsed -to the partition edge, and the query returned results computed over that wrongly -widened frame instead of an offset window. DataFusion 53 and earlier failed -during execution with an arithmetic error. Rows whose order key value was `NULL` -never reached the arithmetic, so queries where every order key value was `NULL` -returned correct results throughout; those also now fail at planning. Over a -`Null`-typed key the offset itself failed to coerce, erroring at planning time -with `Cast error: Casting from Utf8 to Null not supported`, and binary keys were -rejected for every `RANGE` frame with the internal error quoted below -- for -those two, only the error message changes. - -Such an `ORDER BY` type is still usable with the `UNBOUNDED PRECEDING`, -`CURRENT ROW` and `UNBOUNDED FOLLOWING` bounds, which are located by comparing -`ORDER BY` values rather than by computing them. Binary order keys additionally -gained support for those bounds in this release, having previously failed with -`Internal error: Cannot run range queries on datatype: Binary`. - -**Who is affected:** - -- Queries using `offset PRECEDING` or `offset FOLLOWING` in a `RANGE` frame over - a non-numeric, non-temporal `ORDER BY` key. To count rows rather than compare - values, use a `ROWS` frame; to include everything up to the partition edge, - use `UNBOUNDED PRECEDING` or `UNBOUNDED FOLLOWING`. - -See [issue #24327](https://github.com/apache/datafusion/issues/24327) for details. +The upgrade guide for DataFusion 55.0.0 is in the +[documentation for DataFusion 55.2.0](https://datafusion.apache.org/versions/55.2.0/library-user-guide/upgrading/55.0.0.html). From 7b2d6e19aa39c2135fda812acba802e152914d9e Mon Sep 17 00:00:00 2001 From: Andrew Lamb Date: Sun, 29 Nov 2026 07:26:02 -0500 Subject: [PATCH 2/4] docs: fold the current upgrade guide into one page and redirect past guides Co-Authored-By: Claude Fable 5.2 --- docs/source/conf.py | 14 + docs/source/contributor-guide/api-health.md | 2 +- .../library-user-guide/upgrading/46.0.0.md | 10 - .../library-user-guide/upgrading/47.0.0.md | 10 - .../library-user-guide/upgrading/48.0.0.md | 10 - .../library-user-guide/upgrading/48.0.1.md | 10 - .../library-user-guide/upgrading/49.0.0.md | 10 - .../library-user-guide/upgrading/50.0.0.md | 10 - .../library-user-guide/upgrading/51.0.0.md | 10 - .../library-user-guide/upgrading/52.0.0.md | 10 - .../library-user-guide/upgrading/53.0.0.md | 10 - .../library-user-guide/upgrading/54.0.0.md | 10 - .../library-user-guide/upgrading/55.0.0.md | 10 - .../library-user-guide/upgrading/56.0.0.md | 1715 ----------------- .../upgrading/{57.0.0.md => index.md} | 22 +- .../library-user-guide/upgrading/index.rst | 23 - 16 files changed, 36 insertions(+), 1850 deletions(-) delete mode 100644 docs/source/library-user-guide/upgrading/46.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/47.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/48.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/48.0.1.md delete mode 100644 docs/source/library-user-guide/upgrading/49.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/50.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/51.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/52.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/53.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/54.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/55.0.0.md delete mode 100644 docs/source/library-user-guide/upgrading/56.0.0.md rename docs/source/library-user-guide/upgrading/{57.0.0.md => index.md} (91%) delete mode 100644 docs/source/library-user-guide/upgrading/index.rst diff --git a/docs/source/conf.py b/docs/source/conf.py index ddc212ddc1f7f..667864458f44f 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -146,4 +146,18 @@ "library-user-guide/adding-udfs": "functions/index.html", "user-guide/runtime_configs": "configs.html", "library-user-guide/upgrading": "/library-user-guide/upgrading/index.html", + "library-user-guide/upgrading/57.0.0": "index.html", + # Upgrade guides for past releases are in the versioned documentation + "library-user-guide/upgrading/56.0.0": "https://datafusion.apache.org/versions/56.0.0/library-user-guide/upgrading/56.0.0.html", + "library-user-guide/upgrading/55.0.0": "https://datafusion.apache.org/versions/55.2.0/library-user-guide/upgrading/55.0.0.html", + "library-user-guide/upgrading/54.0.0": "https://datafusion.apache.org/versions/54.1.0/library-user-guide/upgrading/54.0.0.html", + "library-user-guide/upgrading/53.0.0": "https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/53.0.0.html", + "library-user-guide/upgrading/52.0.0": "https://datafusion.apache.org/versions/52.0.0/library-user-guide/upgrading.html#datafusion-52-0-0", + "library-user-guide/upgrading/51.0.0": "https://datafusion.apache.org/versions/51.0.0/library-user-guide/upgrading.html#datafusion-51-0-0", + "library-user-guide/upgrading/50.0.0": "https://datafusion.apache.org/versions/50.0.0/library-user-guide/upgrading.html#datafusion-50-0-0", + "library-user-guide/upgrading/49.0.0": "https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/49.0.0.html", + "library-user-guide/upgrading/48.0.1": "https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.1.html", + "library-user-guide/upgrading/48.0.0": "https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.0.html", + "library-user-guide/upgrading/47.0.0": "https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/47.0.0.html", + "library-user-guide/upgrading/46.0.0": "https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/46.0.0.html", } diff --git a/docs/source/contributor-guide/api-health.md b/docs/source/contributor-guide/api-health.md index d26f25abaeb34..58cb731d139ad 100644 --- a/docs/source/contributor-guide/api-health.md +++ b/docs/source/contributor-guide/api-health.md @@ -121,7 +121,7 @@ semantics. When a change requires DataFusion users to modify their code as part of an upgrade, please consider documenting it in the version-specific [Upgrade Guide]. -[upgrade guide]: ../library-user-guide/upgrading/index.rst +[upgrade guide]: ../library-user-guide/upgrading/index.md ## Deprecation Guidelines diff --git a/docs/source/library-user-guide/upgrading/46.0.0.md b/docs/source/library-user-guide/upgrading/46.0.0.md deleted file mode 100644 index 65c4f89100746..0000000000000 --- a/docs/source/library-user-guide/upgrading/46.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 46.0.0 Upgrade Guide - -The upgrade guide for DataFusion 46.0.0 is in the -[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/46.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/47.0.0.md b/docs/source/library-user-guide/upgrading/47.0.0.md deleted file mode 100644 index 766374001fdf7..0000000000000 --- a/docs/source/library-user-guide/upgrading/47.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 47.0.0 Upgrade Guide - -The upgrade guide for DataFusion 47.0.0 is in the -[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/47.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/48.0.0.md b/docs/source/library-user-guide/upgrading/48.0.0.md deleted file mode 100644 index 80cb42776c7a7..0000000000000 --- a/docs/source/library-user-guide/upgrading/48.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 48.0.0 Upgrade Guide - -The upgrade guide for DataFusion 48.0.0 is in the -[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/48.0.1.md b/docs/source/library-user-guide/upgrading/48.0.1.md deleted file mode 100644 index 7e63159ddb59f..0000000000000 --- a/docs/source/library-user-guide/upgrading/48.0.1.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 48.0.1 Upgrade Guide - -The upgrade guide for DataFusion 48.0.1 is in the -[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.1.html). diff --git a/docs/source/library-user-guide/upgrading/49.0.0.md b/docs/source/library-user-guide/upgrading/49.0.0.md deleted file mode 100644 index 025e9020ff694..0000000000000 --- a/docs/source/library-user-guide/upgrading/49.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 49.0.0 Upgrade Guide - -The upgrade guide for DataFusion 49.0.0 is in the -[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/49.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/50.0.0.md b/docs/source/library-user-guide/upgrading/50.0.0.md deleted file mode 100644 index a0d11d9dcfb11..0000000000000 --- a/docs/source/library-user-guide/upgrading/50.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 50.0.0 Upgrade Guide - -The upgrade guide for DataFusion 50.0.0 is in the -[documentation for DataFusion 50.0.0](https://datafusion.apache.org/versions/50.0.0/library-user-guide/upgrading.html#datafusion-50-0-0). diff --git a/docs/source/library-user-guide/upgrading/51.0.0.md b/docs/source/library-user-guide/upgrading/51.0.0.md deleted file mode 100644 index 52f6c909d48bf..0000000000000 --- a/docs/source/library-user-guide/upgrading/51.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 51.0.0 Upgrade Guide - -The upgrade guide for DataFusion 51.0.0 is in the -[documentation for DataFusion 51.0.0](https://datafusion.apache.org/versions/51.0.0/library-user-guide/upgrading.html#datafusion-51-0-0). diff --git a/docs/source/library-user-guide/upgrading/52.0.0.md b/docs/source/library-user-guide/upgrading/52.0.0.md deleted file mode 100644 index ee22a8b931f3c..0000000000000 --- a/docs/source/library-user-guide/upgrading/52.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 52.0.0 Upgrade Guide - -The upgrade guide for DataFusion 52.0.0 is in the -[documentation for DataFusion 52.0.0](https://datafusion.apache.org/versions/52.0.0/library-user-guide/upgrading.html#datafusion-52-0-0). diff --git a/docs/source/library-user-guide/upgrading/53.0.0.md b/docs/source/library-user-guide/upgrading/53.0.0.md deleted file mode 100644 index 078c81ee4b91f..0000000000000 --- a/docs/source/library-user-guide/upgrading/53.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 53.0.0 Upgrade Guide - -The upgrade guide for DataFusion 53.0.0 is in the -[documentation for DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/53.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/54.0.0.md b/docs/source/library-user-guide/upgrading/54.0.0.md deleted file mode 100644 index b8060dd70f03a..0000000000000 --- a/docs/source/library-user-guide/upgrading/54.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 54.0.0 Upgrade Guide - -The upgrade guide for DataFusion 54.0.0 is in the -[documentation for DataFusion 54.1.0](https://datafusion.apache.org/versions/54.1.0/library-user-guide/upgrading/54.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/55.0.0.md b/docs/source/library-user-guide/upgrading/55.0.0.md deleted file mode 100644 index 00e4847a86f0c..0000000000000 --- a/docs/source/library-user-guide/upgrading/55.0.0.md +++ /dev/null @@ -1,10 +0,0 @@ - - -# DataFusion 55.0.0 Upgrade Guide - -The upgrade guide for DataFusion 55.0.0 is in the -[documentation for DataFusion 55.2.0](https://datafusion.apache.org/versions/55.2.0/library-user-guide/upgrading/55.0.0.html). diff --git a/docs/source/library-user-guide/upgrading/56.0.0.md b/docs/source/library-user-guide/upgrading/56.0.0.md deleted file mode 100644 index 080650e7b6247..0000000000000 --- a/docs/source/library-user-guide/upgrading/56.0.0.md +++ /dev/null @@ -1,1715 +0,0 @@ - - -# Upgrade Guides - -## DataFusion 56.0.0 - -### Session time zone now applies to mixed timestamp operations - -When `datafusion.execution.time_zone` is set, DataFusion now uses it to -interpret timezone-naive timestamps in comparisons and subtraction with -timezone-aware timestamps. This applies to binary comparisons, `IN`, -`BETWEEN`, `CASE expr WHEN`, `IN` subqueries, and `ANY` or `ALL` -comparisons. - -Previously, mixed timestamp operations did not consistently use the configured -session timezone. They could use the timezone-aware operand's timezone or -subtract raw timestamp values. The new behavior matches PostgreSQL and DuckDB. - -The default remains `None`. Without a session timezone, comparisons and -subtraction use the timezone-aware operand's timezone. Applications that set this -option need to review queries that mix timezone-aware and timezone-naive timestamps. - -### `get_coerce_type_for_list` and `get_coerce_type_for_case_when` are deprecated - -`IN` and `CASE expr WHEN` are defined in terms of `=`, and `=` now reads a -timezone-naive timestamp in `datafusion.execution.time_zone` when it is compared -against a timezone-aware one. These two functions have nowhere to take that -setting from, so the planner no longer calls them and they now return a coercion -that disagrees with the comparison operator they are defined in terms of. - -Both remain in place and behave exactly as they did in 55.0.0. To follow the -planner, fold `comparison_coercion_with_session_timezone` over the values -yourself: - -```rust -// 55.0.0 -let coerced = get_coerce_type_for_list(&expr_type, &list_types); - -// 56.0.0 -let coerced = list_types.iter().try_fold(expr_type, |left, right| { - comparison_coercion_with_session_timezone(&left, right, session_time_zone) -}); -``` - -Pass `options.execution.time_zone.as_ref().map(|tz| tz.as_str())` as -`session_time_zone`, or `None` where no session is in scope. `None` reproduces the -55.0.0 behavior, except that `NULL` -against a dictionary-encoded type coerces to the dictionary type rather than to -its value type, which is what `=` has always done. - -### `MSRV` updated to 1.95.0 - -The Minimum Supported Rust Version (MSRV) has been updated to [`1.95.0`]. - -[`1.95.0`]: https://releases.rs/docs/1.95.0/ - -### Aggregate group-clustering APIs - -`AggregateExec::input_order_mode()` has been replaced by -`AggregateExec::group_clustering_mode()`. It returns a `GroupClusteringMode`: -`None`, `Partial(indices)`, or `Full`, corresponding to the previous aggregate -modes `Linear`, `PartiallySorted(indices)`, and `Sorted`. -`AggregateExec::compute_properties` now accepts `&GroupClusteringMode` in place of -`&InputOrderMode`. - -`GroupClusteringMode` describes the input's group-clustering guarantees, which -determine when groups can be emitted during aggregation. - -In `datafusion_physical_plan::aggregates::order`, `GroupOrdering`, -`GroupOrderingPartial`, and `GroupOrderingFull` have been renamed to -`GroupClustering`, `GroupClusteringPartial`, and `GroupClusteringFull`. -`GroupClustering::try_new` accepts `&GroupClusteringMode`. - -Aggregate plans now display `group_clustering_mode=Full` or -`group_clustering_mode=Partial(indices)` instead of `ordering_mode=Sorted` or -`ordering_mode=PartiallySorted(indices)`. - -### Upgrade arrow/parquet to 60 and object_store to 0.14 - -DataFusion 56.0.0 uses `arrow` and `parquet` 60, and `object_store` 0.14. -This may require updates to your Cargo.toml if you have direct dependencies on -these crates. - -See the [Arrow 60.0.0 release notes] and the [object_store 0.14.0 changelog] for details on breaking changes in those versions. - -[arrow 60.0.0 release notes]: https://github.com/apache/arrow-rs/releases/tag/60.0.0 -[object_store 0.14.0 changelog]: https://github.com/apache/arrow-rs-object-store/blob/v0.14.2/CHANGELOG-old.md#v0140-2026-06-18 - -#### Field and schema metadata now use arrow's `Metadata` type - -Arrow 60 introduced a dedicated [`Metadata`] type for field and schema metadata -in place of `HashMap`. Following that change, several DataFusion -APIs now use `Metadata` as well, such as `DFSchema::metadata` and -`ExprSchema::metadata` return `&Metadata`. `CastExpr::target_metadata` and -`TryCastExpr::target_metadata` return `Option<&Metadata>`. - -**Migration guide:** - -```rust,ignore -// Before -let meta: &HashMap = schema.metadata(); -let field = Field::new("a", DataType::Int64, true) - .with_metadata([("k".to_string(), "v".to_string())].into()); - -// After -let meta: &Metadata = schema.metadata(); -let field = Field::new("a", DataType::Int64, true) - .with_metadata(Metadata::new().with("k", "v")); -``` - -`Metadata` supports `.get()`, `.iter()`, `.is_empty()` and `.extend()` like -`HashMap`, and converts to and from `HashMap` and -`BTreeMap` via `From`, so most call sites need only a type -change. Use `FieldMetadata::to_hashmap` where a `HashMap` is still required. - -[`metadata`]: https://docs.rs/arrow/60.0.0/arrow/datatypes/struct.Metadata.html - -### `CsvSource::newlines_in_values` is deprecated - -`CsvSource::newlines_in_values()` is deprecated starting in 56.0.0 but remains -callable with unchanged behavior. There is no replacement getter, and -`CsvSource` does not expose a `csv_options()` method. - -**Migration guide:** - -Retain the `CsvOptions` used to configure the source before passing them to -`CsvSource::with_csv_options`. Read `options.newlines_in_values.unwrap_or(false)` -to obtain the same boolean value: `None` and `Some(false)` mean false, while -`Some(true)` means true. CSV reading, repartitioning, and serialization behavior -are unchanged. - -### `ParquetAccessPlan::into_overall_row_selection` is deprecated - -`ParquetAccessPlan::into_overall_row_selection` is deprecated starting in 56.0.0. -DataFusion now keeps selections local to each row group during Parquet scanning. -The method remains available with its existing conversion and selection-length -validation behavior, so direct callers continue to work but receive a deprecation -warning. - -Users who attach a `ParquetAccessPlan` to a `PartitionedFile` for DataFusion to -read need no changes. - -For custom readers, use `ParquetAccessPlan::into_inner()` to obtain the -`RowGroupAccess` entries. Their positions are the original file row-group -indexes, and each selection uses coordinates within its own row group. When -migrating away from the deprecated method, callers must handle conversion and -selection-length validation themselves. Parquet's push decoder and async reader -accept `RowGroupSelection` values through `with_row_group_selections`; the -synchronous reader still requires `with_row_groups` and an overall -`with_row_selection`. - -### `RowGroupAccessPlanFilter::prune_by_range` takes a `RowGroupRangeAssignment` - -The new `datafusion.execution.parquet.row_group_range_assignment` option decides -which byte range of a split Parquet file reads each row group. The default, -`start_offset`, keeps the previous behavior. `midpoint` matches Apache Spark. - -`RowGroupAccessPlanFilter::prune_by_range` takes the assignment as a new -argument. Pass `RowGroupRangeAssignment::StartOffset` for the previous behavior: - -```rust,ignore -// Before -filter.prune_by_range(groups, &range); -// After -filter.prune_by_range(groups, &range, RowGroupRangeAssignment::StartOffset); -``` - -`ParquetOptions` and its generated protobuf struct gained a -`row_group_range_assignment` field. Exhaustive struct literals must set it or -use `..Default::default()`. - -### Missing Parquet null counts are treated as unknown - -DataFusion now preserves an omitted Parquet `null_count` statistic as unknown. -Previously, it assumed zero nulls, which could discard matching NULL rows in -`IS NULL` filters and `ORDER BY ... NULLS FIRST LIMIT` queries, or produce an -incorrectly high `COUNT(column)` from metadata. - -Queries over affected files may read or sort more data because these optimizations -require a known null count: - -- Pruning row groups for `IS NULL` filters. -- Computing `COUNT(column)` using only file metadata. -- Pruning row groups with a dynamic `NULLS FIRST` TopK filter. -- Eliminating a sort over nullable columns in sorted, non-overlapping files. - Such queries may now retain a full `SortExec`, even when the data has no NULLs. - -parquet-rs versions before 53.1.0 omitted zero null counts. This includes files -produced with the older parquet-rs dependency used by DataFusion releases before -42.1.0. [Arrow #6490](https://github.com/apache/arrow-rs/pull/6490) changed the -writer to record known zero counts. Files with explicit counts retain their -existing behavior. - -To identify column chunks with bounds but no null count, run this query in the -DataFusion CLI: - -```sql -SELECT row_group_id, path_in_schema -FROM parquet_metadata('data.parquet') -WHERE (stats_min IS NOT NULL OR stats_max IS NOT NULL) - AND stats_null_count IS NULL; -``` - -Rewriting affected files with a current DataFusion version, for example using -`COPY ... TO` with Parquet statistics enabled, records the missing counts and -restores optimizations that depend on them. Preserve the required data ordering -and ordering metadata when rewriting sorted files. - -### Hive null partition directories are read as NULL - -`ListingTable` now reads a partition directory named -`__HIVE_DEFAULT_PARTITION__`, for example `/table/d=__HIVE_DEFAULT_PARTITION__/`, -as a NULL partition value. This is the placeholder Hive compliant writers use for -a null partition value, and matches how Hive, Spark and Impala read it. -Previously the directory name was parsed as the partition column's type, which -failed for non-string columns and returned the literal string -`__HIVE_DEFAULT_PARTITION__` for string columns. - -The placeholder is set by the new -`datafusion.execution.listing_table_hive_default_partition_name` option, the -equivalent of Hive's `hive.exec.default.partition.name`. Setting it to the empty -string reads the directory name as the value, as before. - -Partitioned writes (`INSERT INTO` and `COPY ... PARTITIONED BY`) now reject a -partition value equal to this placeholder, since it would be read back as NULL. - -To support this, `ListingTable` now declares all partition columns as nullable, -so `DESCRIBE` and the table schema report them as nullable. - -**Who is affected:** - -- Tables with string partition columns that contain a - `__HIVE_DEFAULT_PARTITION__` directory. Its rows now have a NULL partition - value, so `WHERE col = '__HIVE_DEFAULT_PARTITION__'` no longer matches them. -- Partitioned writes of the value `__HIVE_DEFAULT_PARTITION__`, which now - return an error instead of writing a directory that reads back as NULL. -- Code that relies on `ListingTable` partition columns being non-nullable. -- Callers of `pruned_partition_list`, which can now return files with NULL - partition values. Partition fields built from its output must be nullable. -- Users constructing `ExecutionOptions` (or `ConfigOptions`) with an exhaustive - struct literal must provide the new - `listing_table_hive_default_partition_name: String` field. - -**Migration guide:** - -Select the null partition with `IS NULL`: - -```sql -SELECT * FROM t WHERE col IS NULL; -``` - -To keep reading and writing `__HIVE_DEFAULT_PARTITION__` as a literal value, -disable the mapping: - -```sql -SET datafusion.execution.listing_table_hive_default_partition_name = ''; -``` - -If your writer uses a different `hive.exec.default.partition.name`, set the -option to that name instead: - -```rust,ignore -let mut config = SessionConfig::new(); -config - .options_mut() - .execution - .listing_table_hive_default_partition_name = "MY_NULL".to_string(); -``` - -### `Timestamp(u, Some(tz)) - Timestamp(u, None)` reads the naive operand in `tz` - -Subtracting a timezone-naive timestamp from a timezone-aware one _at the same -time unit_ did not coerce at all in `55.0.0`: the naive operand was read as UTC, -which differed both from `=` on the same pair of values and from every other -pairing of time units. It now coerces like the rest, so the naive operand is -read in the aware operand's time zone: - -```sql --- ts_tz is 2024-11-01T00:00:00-04:00 (America/New_York), ts is the naive --- 2024-11-01T00:00:00; ts_tz = ts is true in both versions --- 55.0.0: 0 days 4 hours 0 mins 0.000000000 secs --- 56.0.0: 0 days 0 hours 0 mins 0.000000000 secs -SELECT ts_tz - ts FROM timestamps; -``` - -### `ForeignSession::create_physical_plan` is unsupported - -`ForeignSession::create_physical_plan` no longer forwards to the library that -owns the session. It now returns a `NotImplemented` error because forwarding can -re-enter an installed foreign planner, and the execution-plan handle returned by -the old callback cannot restore local Rust type identities for downcasting. -The original `FFI_SessionRef` callback slot remains in place for ABI compatibility -with DataFusion 55 consumers, but calling that callback returns the same error. - -The session-owning library should instead export its original planner as a -`datafusion_ffi::query_planner::FFI_QueryPlanner` before installing a foreign -planner. The foreign planner can retain and invoke that handle to receive a -serialized physical plan reconstructed with local type identities. See the -`datafusion_ffi::query_planner` module documentation for the complete delegation -pattern. `ForeignSession::query_planner`, `optimize`, and `physical_optimizers` -continue to forward to the owning session across the FFI boundary. - -### `FFI_ExecutionPlan` carries input requirements - -`FFI_ExecutionPlan` has new callbacks for `input_distribution_requirements`, -`required_input_ordering`, `maintains_input_order` and -`benefits_from_input_partitioning`, so a `ForeignExecutionPlan` now reports the -same input requirements as the plan it wraps. Previously these fell back to the -`ExecutionPlan` defaults, so physical optimizer rules running across the FFI -boundary (for example with a foreign `QueryPlanner`) could produce plans that -did not satisfy them. - -`FFI_PhysicalExpr` also has a new `eq` callback, so two `ForeignPhysicalExpr`s -wrapping equal expressions from the same library now compare equal. Previously -they compared by identity, so a foreign plan's requirements never matched its -children's partitioning or ordering on the host. - -Both structs have a new layout; rebuild FFI providers and consumers against the -same release. - -### Range partitioning supports retained samples and scaling - -`RangePartitioning::new` is deprecated. Prefer the validated -`RangePartitioning::try_new_with_samples(ordering, samples, partition_count)`. -For exact boundaries, pass `split_points.len() + 1` as the count, or keep using -the validated `try_new` constructor. Retain additional samples when future -scaling above that count is required; scaling does not create new sample values. - -`scale` returns `Option`. It returns `None` when the target -partition count is zero or exceeds the retained sample capacity; callers can -then retain the existing layout or choose another partitioning. Equality includes -retained samples; use `has_same_layout` to compare the current key ordering and -effective boundaries. - -`FFI_RangePartitioning` has a new layout; rebuild FFI consumers against the -compatible release. The generated `PhysicalRangePartitioning` protobuf struct -also gains fields, affecting exhaustive struct literals. Older protobuf payloads -remain readable, and effective split points remain available to older readers. - -### `GroupColumn` now requires `values_preserving` - -Custom implementations of the public `GroupColumn` trait must implement -`values_preserving`. This method returns selected rows without changing the stored -values or their group indices. It preserves the requested order and supports -repeated indices. - -**Migration guide:** - -Implement `values_preserving`, call -`selection.validate_num_groups(self.len())?` before reading, and return rows in -`selection.iter()` order without changing the builder state. - -### `datafusion-proto`: common option and constraint conversions are fallible - -Protobuf conversions for `CsvOptions`, `JsonOptions`, `ParquetCdcOptions`, -`Constraint`, and `Constraints` now reject integer values that do not fit -`usize`. Their infallible `From` implementations have been replaced with -`TryFrom`. The existing `TryFrom` conversions for `ParquetOptions` and -`TableParquetOptions` now also validate all `usize`-backed fields. A constraint -without a `constraint_mode` returns an error instead of panicking. - -**Migration guide:** - -```rust,ignore -// Before -let csv = CsvOptions::from(&proto_csv); -let cdc = ParquetCdcOptions::from(proto_cdc); -let constraints: Constraints = proto_constraints.into(); - -// After -let csv = CsvOptions::try_from(&proto_csv)?; -let cdc = ParquetCdcOptions::try_from(proto_cdc)?; -let constraints = Constraints::try_from(proto_constraints)?; -``` - -See [issue #24170](https://github.com/apache/datafusion/issues/24170) for details. - -### `CastExpr::cast_options` now returns `CastOptions` by value - -`CastExpr` now owns format strings decoded from protobuf, so `cast_options()` -returns a borrowing `CastOptions<'_>` value instead of `&CastOptions<'static>`. -Code that only reads the options generally needs no change. To replace only the -child, use `PhysicalExpr::with_new_children` to preserve the options and whether -the target is type-only or explicit. Use `CastExpr::with_new_expr_and_target_field` -when replacing both the child and an explicit target field. Neither method -requires a `'static` borrow of the options. - -### `ExecutionOptions` has a new `enable_nlj_coordinated_fallback` field - -`ExecutionOptions` gained a public `enable_nlj_coordinated_fallback: bool` field -(default `true`). It controls whether the memory-limited `NestedLoopJoinExec` -fallback shares per-chunk build-side state across probe partitions, which is what -lets `LEFT`, `LEFT SEMI`, `LEFT ANTI`, `LEFT MARK` and `FULL` joins spill instead -of failing with `ResourcesExhausted` when the right side has several partitions. - -**Who is affected:** - -- Users constructing `ExecutionOptions` (or `ConfigOptions`) with an exhaustive - struct literal. Reading or `SET`-ing configuration is unaffected. -- Distributed engines that run each output partition as an independent task. - The coordination assumes all probe partitions run in one process; with one - coordinator per task the shared probe-thread counter never reaches zero and the - fallback would stall. Such engines should set the flag to `false`, which keeps - the previous fail-fast behaviour for the affected join types. - -**Migration guide:** - -Set the new field, or fill it from `Default`: - -```rust,ignore -// Before -ExecutionOptions { - batch_size: 8192, - // ... every other field ... -} - -// After: set it explicitly -ExecutionOptions { - batch_size: 8192, - enable_nlj_coordinated_fallback: true, - // ... every other field ... -} - -// After: or let the remaining fields come from Default, which also keeps -// future field additions from breaking the literal -ExecutionOptions { - batch_size: 8192, - ..Default::default() -} -``` - -Distributed engines opting out: - -```rust,ignore -let mut config = SessionConfig::new(); -config.options_mut().execution.enable_nlj_coordinated_fallback = false; -``` - -### `ExecutionOptions::time_zone` is now a validated `ConfigTimeZone` - -`ExecutionOptions::time_zone` changed from `Option` to -`Option`. The value is now checked when it is set, so -`SET TIME ZONE = 'Asia/Taipei2'` fails immediately instead of on a later query. -The string is kept exactly as written (`+08` stays `+08`). - -**Who is affected:** - -- Code that reads or assigns `ExecutionOptions::time_zone` directly. -- Code that sets the value through SQL `SET` or `ConfigOptions::set` needs no - code changes, but invalid time zones are now rejected immediately. - -**Migration guide:** - -```rust,ignore -// Before -options.execution.time_zone = Some("America/Denver".to_string()); -let tz: Option = options.execution.time_zone.clone(); - -// After -options.execution.time_zone = Some("America/Denver".parse()?); -let tz: Option<&str> = options.execution.time_zone.as_ref().map(|tz| tz.as_str()); -``` - -### `ParquetOptions::coerce_int96_tz` is now a validated `ConfigTimeZone` - -`ParquetOptions::coerce_int96_tz` changed from `Option` to -`Option`, the same type as `ExecutionOptions::time_zone`. An -invalid time zone is now rejected by `SET`, by table options, and by protobuf -decoding instead of on the first Parquet read. This applies even when -`coerce_int96` is not set, where the time zone has no effect. Valid values and -the protobuf wire format are unchanged. - -**Who is affected:** - -- Code that reads or assigns `ParquetOptions::coerce_int96_tz` directly. -- Code that sets the value through SQL or `ConfigOptions::set` needs no code - changes, but invalid time zones are now rejected immediately. - -**Migration guide:** - -```rust,ignore -// Before -options.execution.parquet.coerce_int96_tz = Some("UTC".to_string()); - -// After -options.execution.parquet.coerce_int96_tz = Some("UTC".parse()?); -``` - -### `ExecutionOptions` has a new `soft_max_bytes_per_output_file` field - -`ExecutionOptions` gained a public `soft_max_bytes_per_output_file: ConfigNonZeroUsize` -field (default 4 GiB minus one byte, or 4,294,967,295 bytes). When writing -multiple output files, DataFusion starts a new file once a writer reports that -the encoded size has reached this target or the existing -`soft_max_rows_per_output_file` target has been reached. The byte limit is soft: -buffered batches, in-flight batch serialization, individual batch sizes, and -file metadata can make a completed file larger than the target. It does not -apply to single-file output. - -**Who is affected:** - -- Users constructing `ExecutionOptions` (or `ConfigOptions`) with an exhaustive - struct literal must provide the new field. -- Users writing multiple output files can set a smaller byte target to rotate - files before they reach the default size. - -**Migration guide:** - -Set the field explicitly, or fill it from `Default` as shown above. For example, -to target 128 MiB output files in Rust: - -```rust,ignore -let mut config = SessionConfig::new(); -config.options_mut().execution.soft_max_bytes_per_output_file = - ConfigNonZeroUsize::try_new(128 * 1024 * 1024)?; -``` - -The same setting can be changed with SQL: - -```sql -SET datafusion.execution.soft_max_bytes_per_output_file = 134217728; -``` - -### New field `enable_rle_to_dictionary` added to `ParquetOptions` - -`ParquetOptions` gained a new field `enable_rle_to_dictionary: bool` (default -`false`). It controls whether top-level string and binary Parquet columns with -dictionary pages are read as `Dictionary` / `Dictionary` instead of their plain type. - -`ParquetOptions` is a public struct without `#[non_exhaustive]`, so downstream -crates that construct it with an exhaustive struct literal will fail to compile -with `E0063: missing field 'enable_rle_to_dictionary'`. - -**Migration guide:** - -Add `enable_rle_to_dictionary: false` to any exhaustive `ParquetOptions { .. }` -literal, or use `..Default::default()` to future-proof against further additions: - -```rust,ignore -// Before -ParquetOptions { - enable_page_index: true, - // ... every other field ... -} - -// After: set it explicitly -ParquetOptions { - enable_page_index: true, - enable_rle_to_dictionary: false, - // ... every other field ... -} - -// After: or let remaining fields come from Default -ParquetOptions { - enable_page_index: true, - ..Default::default() -} -``` - -### `datafusion.optimizer.use_statistics_registry` is deprecated and ignored - -The `datafusion.optimizer.use_statistics_registry` config flag is deprecated and -now ignored (setting it emits a deprecation warning). The pluggable -`StatisticsRegistry` is always consulted during the single statistics walk: -providers registered on the session take effect directly. With no providers -registered the registry is a no-op, so default behavior is unchanged from the -previous default (`use_statistics_registry = false`). - -**Who is affected:** - -- Anyone who set `datafusion.optimizer.use_statistics_registry`. The setting is - still accepted (with a deprecation warning) but has no effect, and will be - removed in a future release. - -**Migration guide:** - -- Drop any `use_statistics_registry` setting. -- To use statistics providers, register them on the session with - `SessionStateBuilder::with_statistics_registry(...)`. -- To opt out, register nothing (the default). - -### Generated protobuf `JsonWriterOptions` gained a `compression_level` field - -The generated public protobuf `JsonWriterOptions` struct now carries an optional -`compression_level` so JSON sink plans preserve explicitly configured -compression levels across serialization. - -**Who is affected:** - -- Users constructing generated `JsonWriterOptions` values with an exhaustive - struct literal. - -**Migration guide:** - -Set `compression_level` explicitly, or fill it from `Default`: - -```rust,ignore -// Before -JsonWriterOptions { compression } - -// After -JsonWriterOptions { - compression, - compression_level: None, -} -// or -JsonWriterOptions { - compression, - ..Default::default() -} -``` - -The protobuf wire format remains backward compatible. - -See [PR #24945](https://github.com/apache/datafusion/pull/24945) for details. - -### Generated protobuf Parquet structs gained state fields - -The generated public protobuf `ParquetScanExecNode` struct now carries an -optional `metadata_size_hint`, and `ParquetSink` now carries optional -`sorting_columns`. These fields preserve the corresponding Parquet source and -sink settings across physical-plan serialization. - -**Who is affected:** - -- Users constructing either generated struct with an exhaustive struct literal. - -**Migration guide:** - -Add `metadata_size_hint: None` to `ParquetScanExecNode` literals and -`sorting_columns: None` to `ParquetSink` literals to retain the previous -behavior, or use `..Default::default()` for unspecified fields. - -The protobuf wire format remains backward compatible. - -See [PR #25057](https://github.com/apache/datafusion/pull/25057) for details. - -### Generated protobuf `CsvWriterOptions` changed - -The generated `CsvWriterOptions` now includes `compression_level`, -`timestamp_tz_format`, and `terminator`. Its four existing format fields changed -from `String` to `Option` to distinguish unset from explicitly empty -formats. This affects exhaustive struct literals and direct format-field access. - -Wrap existing formats in `Some` or use `None`, and initialize the new fields -(explicitly or through `Default`): - -```rust,ignore -// Before (unchanged fields omitted) -CsvWriterOptions { - date_format: "%Y-%m-%d".to_string(), - datetime_format: String::new(), - timestamp_format: String::new(), - time_format: String::new(), - // ... -} - -// After -CsvWriterOptions { - date_format: Some("%Y-%m-%d".to_string()), - datetime_format: None, - timestamp_format: None, - time_format: None, - compression_level: None, - timestamp_tz_format: None, - terminator: Vec::new(), - // ... -} -``` - -The protobuf wire format remains backward compatible. - -See [PR #25058](https://github.com/apache/datafusion/pull/25058) for details. - -### `DefaultStatisticsProvider` is deprecated - -`datafusion_physical_plan::operator_statistics::DefaultStatisticsProvider` is -deprecated. It is redundant: the statistics walk (`StatisticsContext`) falls back -to each operator's `statistics_from_inputs` when the provider chain delegates or -is empty, so a terminal "default" provider is no longer needed. It is no longer -part of `StatisticsRegistry::default_with_builtin_providers()`. - -**Migration guide:** - -- Remove `DefaultStatisticsProvider` from any custom provider chain; register no - terminal provider instead (the walk falls back on its own). - -### The bundled statistics providers are deprecated - -`StatisticsRegistry::default_with_builtin_providers()` and all the statistics -providers bundled in `datafusion_physical_plan::operator_statistics` -(`FilterStatisticsProvider`, `ProjectionStatisticsProvider`, -`PassthroughStatisticsProvider`, `AggregateStatisticsProvider`, -`JoinStatisticsProvider`, `LimitStatisticsProvider` and -`UnionStatisticsProvider`) are deprecated. They duplicate or replace the -estimation each operator already does in `statistics_from_inputs`, which is the -default. `StatisticsRegistry` remains the extension point for user-defined -providers. - -**Migration guide:** - -- Stop registering the bundled providers; with no matching provider, the - statistics walk uses the operator's own estimate. -- To keep a bundled estimation technique, implement it in a user-defined - `StatisticsProvider`. - -### `StatisticsRegistry::compute` and `compute_base` are deprecated - -Use the walk instead: - -```rust,ignore -StatisticsContext::new_with_registry(registry) - .compute_extended(plan, &StatisticsArgs::new())?; // or .compute(...) for core Statistics -``` - -### API change for `floor` and `ceil` UDF - -The output type of the `floor` and `ceil` UDFs has been changed from the exact input type to a rescaled type with the same bit width. For example, for input `Decimal32(7,2)` `floor` now returns `Decimal32(6,0)`, where the new precision is `p - s + 1`, matching Spark's behaviour. See [#24703] for more details. - -**Who is affected:** - -- Users storing query result with these UDFs in a fixed schema -- Users relying on `arrow_typeof` for these UDFs - -**Migration guide:** - -Change the expected type or wrap the expression in `CAST`. It's recommended to avoid relying on decimal's exact precision and scale. - -### `map_extract` / `element_at` return an empty list for absent keys - -`map_extract` (and its alias `element_at`) previously returned a single-element -list containing `NULL` when the key was not present in the map. It now returns -an empty list, matching the documented behavior and DuckDB. Two related cases -changed at the same time, also matching DuckDB: - -- A `NULL` map input now yields `NULL` instead of `[NULL]`. -- A `NULL` lookup key now yields `[]` instead of `[NULL]`. - -A key that is present with a `NULL` value still returns `[NULL]`, so absent -keys and `NULL` values are now distinguishable. - -**Migration guide:** - -```sql --- Before -SELECT map_extract(MAP {'a': 1}, 'missing'); -- [NULL] - --- After -SELECT map_extract(MAP {'a': 1}, 'missing'); -- [] -``` - -Expressions that assumed the result always has exactly one element, for -example by checking its length, unnesting it, or comparing it to `[NULL]`, -should treat an empty list as the absent-key case instead. - -See [issue #24981](https://github.com/apache/datafusion/issues/24981) and -[issue #24983](https://github.com/apache/datafusion/issues/24983) for details. - -### `date_bin` rejects strides that are not positive - -`date_bin` now returns an error when its stride is not greater than zero, -matching [PostgreSQL] for fixed strides. PostgreSQL does not support month -strides, and DataFusion applies the same rule to them. Negative strides were -previously accepted but did not produce well-defined bins; use the absolute -value of the stride instead. See [issue #25856] for details. - -[postgresql]: https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-BIN -[issue #25856]: https://github.com/apache/datafusion/issues/25856 - -### `log(base, value)` widens float arguments to the wider type - -`log(base, value)` previously computed in the float type of `value`, so a -wider `base` was narrowed and lost precision. Both arguments are now widened to -the wider float type, and the result has that type. An integer or decimal -`base` counts as `Float64`. - -```sql --- Before: 0.041666668 (Float32) --- After: 0.041666666517376175 (Float64) -SELECT log(arrow_cast(16777217, 'Float64'), arrow_cast(2.0, 'Float32')); -``` - -For example, `log(2, float32_col)` now returns `Float64` instead of `Float32`. - -Calls whose arguments have the same float type, and calls with a decimal -`value`, are unchanged. Wrap the call in `CAST` to keep the previous result -type. See [issue #22581] for details. - -[issue #22581]: https://github.com/apache/datafusion/issues/22581 - -### `DataFrame::from_columns` accepts `IntoIterator` - -`DataFrame::from_columns` now accepts any `IntoIterator` -instead of specifically accepting a `Vec<(&str, ArrayRef)>`. - -```rust,ignore -// Existing Vec usage continues to work -let df = DataFrame::from_columns(vec![ - ("id", id), - ("name", name), -])?; - -// Arrays can now be used directly -let df = DataFrame::from_columns([ - ("id", id), - ("name", name), -])?; -``` - -Most existing call sites using `Vec` require no changes. Code that relies on -the exact non-generic function signature of `DataFrame::from_columns` may need -to be updated to account for the new generic API. - -### Aggregate ordering state field names are now namespaced - -Ordering expressions exposed as top-level aggregate state fields now use names -derived from the aggregate name and their ordering position. - -For example: - -```text -first_value(value)[ordering_0] -``` - -is now used instead of an unqualified ordering field name such as: - -```text -timestamp@0 -``` - -This guarantees unique aggregate state field names and allows -`DFSchema::check_names()` to be enforced. - -**Who is affected:** - -Users or integrations that inspect aggregate state field names directly, -including custom UDAFs and FFI integrations. - -### Physical filter pushdown resolves columns by position - -`datafusion_physical_plan::filter_pushdown::ChildFilterDescription::from_child` -and `FilterDescription::from_children` now resolve filter columns by position -instead of looking them up by name. This prevents incorrect results when a -child schema contains duplicate column names. `from_child` requires the child -field at each referenced position to have the same name as the filter column. - -`ChildFilterDescription::from_child_with_allowed_indices` is deprecated but -preserves its previous name-based mapping to the first matching child field. -Migrate to `from_child_with_column_mapping` because name resolution is ambiguous -when the child schema contains duplicate field names. - -**Migration guide:** - -Use `from_child` (or `from_children` for multiple children) when the parent and -child schemas have matching column positions and names. When a node projects, -reorders, or renames columns, use `from_child_with_column_mapping` with an -explicit map from parent output indices to child input indices. Columns absent -from the mapping cannot be pushed down. - -For example, if the parent outputs `[a, b]` and the child outputs `[b, a]`, a -filter on `a@0` must map to child column `a@1`: - -```rust,ignore -use std::collections::{HashMap, HashSet}; -use datafusion_physical_plan::filter_pushdown::ChildFilterDescription; - -// Before: allow parent column 0 and resolve "a" by name in the child. -let description = ChildFilterDescription::from_child_with_allowed_indices( - &parent_filters, - HashSet::from([0]), - &child, -)?; - -// After: explicitly map parent column 0 to child column 1. -let description = ChildFilterDescription::from_child_with_column_mapping( - &parent_filters, - HashMap::from([(0, 1)]), - &child, -)?; -``` - -### Default `datafusion.sql_parser.recursion_limit` raised from 50 to 51 - -DataFusion now uses `sqlparser` 0.63.0, which adds recursion guards to more -parse functions (for example, data type and `INTERVAL` parsing). As a result, -the same SQL statement consumes slightly more of the parser recursion budget -than it did with previous `sqlparser` versions. In particular, every expression -now needs one additional level of depth. - -To avoid rejecting queries that previously parsed successfully, the default -value of the `datafusion.sql_parser.recursion_limit` configuration option, and -of `DFParserBuilder::with_recursion_limit`, has been raised from `50` to `51`. - -If you set `datafusion.sql_parser.recursion_limit` explicitly to a value close -to the depth of your queries, you may see `RecursionLimitExceeded` errors after -upgrading and should raise the limit accordingly. - -See [PR #25278](https://github.com/apache/datafusion/pull/25278) for details. - -### `ensure_distribution` is deprecated in favour of `ensure_distribution_with_stats` - -`datafusion_physical_optimizer::enforce_distribution::ensure_distribution` now -takes its `StatisticsContext` from the caller, so one context (and its -memoization cache) can be shared across a whole bottom-up traversal. The old -two-argument form is kept as a deprecated wrapper that allocates a fresh -context per call, which recomputes each shared subtree's statistics once per -ancestor. - -```rust,ignore -// Before -let plan = DistributionContext::new_default(plan) - .transform_up(|ctx| ensure_distribution(ctx, config)) - .data()?; - -// After: one context for the whole walk. `StatsCache` is keyed by raw plan-node -// pointers, so reset it whenever a node's plan pointer actually changed. -let stats_ctx = StatisticsContext::new(); -let plan = DistributionContext::new_default(plan) - .transform_up(|ctx| { - let before = Arc::clone(&ctx.plan); - let result = ensure_distribution_with_stats(ctx, config, &stats_ctx)?; - if !Arc::ptr_eq(&before, &result.data.plan) { - stats_ctx.reset_cache(); - } - Ok(result) - }) - .data()?; -``` - -Callers that only need the previous behaviour can keep using the deprecated -form, or pass a freshly constructed `StatisticsContext` per call. - -### Physical optimizer rules share one `StatisticsContext` per query - -`PhysicalOptimizerContext` has a new `statistics_context` method. The physical -planner returns one `StatisticsContext` for all the rules of one -`optimize_physical_plan` call, so statistics computed by one rule are reused by -later rules. The method returns `None` by default, so existing implementations -are not affected. Custom rules that compute statistics should call the new -`PhysicalOptimizerContext::compute_statistics` method in `optimize_with_context`. -It uses the shared context, or, if there is none, a new context built from the -statistics registry: - -```rust,ignore -let statistics = context.compute_statistics(&plan, &StatisticsArgs::new())?; -``` - -To pass one `StatisticsContext` down a traversal, use -`datafusion_session::with_statistics_context`, which applies the same choice. - -`AggregateStatistics`, `LimitPushdown` and the co-partitioning choice in -`EnsureRequirements` now also consult the session's statistics providers, as -`JoinSelection` already did. Sessions without registered providers (the -default) are not affected. As for operators, `Exact` statistics from a provider -must be guaranteed values: `AggregateStatistics` answers `COUNT(*)`, `MIN` and -`MAX` from them, and `LimitPushdown` removes a limit over an `Exact(0)` input. - -`datafusion_physical_optimizer::limit_pushdown::pushdown_limit_helper` and -`GlobalRequirements` are deprecated. `LimitPushdown` no longer works one node at -a time; run the `LimitPushdown` rule instead. `pushdown_limit_helper` creates a -new `StatisticsContext` on every call, without statistics providers, so its -result can differ from the rule's when providers are registered. - -### `ExecutionPlan::supports_limit_pushdown` is deprecated in favour of `limit_behavior` - -Operators now declare what a `LIMIT` on their output means for their input with -`ExecutionPlan::limit_behavior`, which returns a `LimitBehavior`: - -- `Stops` (the default): a limit above the node stays above it. -- `Limit { skip, fetch }`: the node is a limit. -- `CopyToChildren`: a limit may be copied to each child as an early-stop hint, - but must also stay above the node, which can output more rows than one child - (`UnionExec`). -- `MoveToInput`: the node outputs exactly the rows of its input, so a limit may - move below it (`ProjectionExec`). -- `Merge`: the node merges its input partitions, so it can enforce a limit with - its own fetch (`CoalescePartitionsExec`, `SortPreservingMergeExec`). Without a - fetch of its own (`ExecutionPlan::fetch`) it behaves like `MoveToInput`. -- `Window(lookahead)`: a window function node. - -`LimitPushdown`, `LimitPushPastWindows` and the sort pushdown in -`EnsureRequirements` read only `limit_behavior`. Its default is derived from -`supports_limit_pushdown` and `cardinality_effect`, so an operator that -implements `supports_limit_pushdown` keeps working: `false` maps to `Stops`; -`true` maps to `MoveToInput` when `cardinality_effect` is `Equal` and to -`CopyToChildren` otherwise. Implement `limit_behavior` instead: - -```rust,ignore -fn limit_behavior(&self) -> LimitBehavior { - LimitBehavior::MoveToInput -} -``` - -DataFusion's own operators keep returning the same `supports_limit_pushdown` -values until it is removed, so a wrapper that forwards it to its input keeps -working, but new code should call `limit_behavior`. - -Two differences for operators that still implement `supports_limit_pushdown`: - -- `LimitPushPastWindows` now pushes a window's limit below a single-input - operator that returns `true` and whose `cardinality_effect` is `Unknown` or - `LowerEqual`. Before, it stopped there. `Unknown` is the default, so this - includes a wrapper that forwards `supports_limit_pushdown` to its input and - does not override `cardinality_effect`: - - ```rust,ignore - impl ExecutionPlan for MyWrapper { - fn supports_limit_pushdown(&self) -> bool { - self.input.supports_limit_pushdown() - } - // no `cardinality_effect`: the default is `Unknown` - } - ``` - - `LimitPushdown` already moved plain limits below such an operator. - `LimitPushPastWindows` only copies the limit below and keeps it above, which - asks less of the operator, so this is safe wherever the existing - `LimitPushdown` behavior is. - -- `LimitPushdown` no longer moves a limit below an operator whose children - have more partitions in total than it outputs, such as one that combines - several inputs into one partition. Moved below, the limit would apply to each - input partition and keep too many rows. The limit now stays above the - operator, as it does above `CoalescePartitionsExec`, and is copied below as - an early-stop fetch. - -### `MergeIntoOp` requires the SQL-visible target qualifier - -`MergeIntoOp` now stores the SQL-visible target qualifier separately from the -target provider identity. This prevents an aliased target from being confused -with a source relation that uses the target table's name. - -The struct is now non-exhaustive. Replace 55.0 struct literals with -`MergeIntoOp::new`: - -```rust,ignore -// DataFusion 55.0 -let op = MergeIntoOp { on, clauses }; - -// DataFusion 56.0 -let op = MergeIntoOp::new(target_qualifier, on, clauses); -``` - -`target_qualifier` must be the relation name referenced by the MERGE expressions: -the target alias when one is present, otherwise the target table reference. -`DmlStatement::table_name` remains the provider/catalog identity. - -### `MergeIntoOpNode` protobuf literals require `target_qualifier` - -The generated `MergeIntoOpNode` type has a new optional field. Code constructing -the generated type with a struct literal must provide it: - -```rust,ignore -// DataFusion 55.0 -let node = protobuf::MergeIntoOpNode { on, clauses }; - -// DataFusion 56.0 -let node = protobuf::MergeIntoOpNode { - on, - clauses, - target_qualifier: Some(protobuf::TableReference::from(target_qualifier)), -}; -``` - -Wire compatibility is directional: - -- A 56.0 reader accepts a 55.0 payload. When `target_qualifier` is absent, it - falls back to `DmlNode.table_name`, matching the 55.0 representation. -- A 55.0 reader must not consume an alias-preserving 56.0 MERGE payload. It - ignores the unknown field but cannot preserve the qualifier required by the - expressions, which can cause resolution failure or incorrect rebinding. - -### Null-aware joins record their `NOT IN` value key count - -Multi-column `(a, b) NOT IN (SELECT x, y ...)` is now planned as a null-aware -join, which records how many of its leading equi-join keys are `NOT IN` value -keys; the keys after them are correlation scope keys. `Join` and -`HashJoinExec` have a new `null_aware_value_keys: usize` field, set with -`with_null_aware_value_keys`, and so do the generated protobuf `JoinNode` and -`HashJoinExecNode` types. - -The count defaults to `0`, unset. An unset count is accepted only for a -single-key null-aware join, the scalar `NOT IN` of earlier releases, so -existing code and 55.x plans keep working. Code that builds a multi-key -null-aware join itself must set the count, or the join fails to plan: - -```rust,ignore -let join = HashJoinExecBuilder::new(left, right, on, JoinType::LeftAnti) - .with_partition_mode(PartitionMode::CollectLeft) - .with_null_aware(true) - // `on[..2]` are the `NOT IN` value keys, any later keys scope keys. - .with_null_aware_value_keys(2) - .build()?; -``` - -A 55.x reader ignores the field and rejects a multi-key null-aware join from a -56.0 plan. - -### `FunctionalDependence` has a new `null_equality` field - -`FunctionalDependence` now records the NULL semantics its dependency holds under. -Build it with `FunctionalDependence::new(..)` and, when needed, -`.with_null_equality(NullEquality::NullEqualsNull)` instead of a struct literal. - -**Migration guide:** - -```rust,ignore -// Before -let dep = FunctionalDependence { - source_indices, - target_indices, - nullable, - mode: Dependency::Single, -}; - -// After -let dep = FunctionalDependence::new(source_indices, target_indices, nullable) - .with_mode(Dependency::Single) - .with_null_equality(NullEquality::NullEqualsNull); -``` - -### Nullable `UNIQUE` constraints no longer add or remove `GROUP BY` expressions - -`get_target_functional_dependencies` and `get_required_group_by_exprs_indices` -now ignore a functional dependency that does not hold across NULL determinant -values (see `FunctionalDependence::is_valid_across_nulls`), such as one derived -from a nullable `UNIQUE` constraint, because `GROUP BY` places all NULL keys in -a single group. - -As a result, a column that is only determined by a nullable `UNIQUE` key can no -longer be selected without appearing in the `GROUP BY`. This matches PostgreSQL, -which accepts such a query only for a `PRIMARY KEY`: - -```sql -CREATE TABLE t (x INT UNIQUE, y INT); - --- Now fails: Column in SELECT must be in GROUP BY or an aggregate function -SELECT x, y FROM t GROUP BY x; - --- Works: add `y` to the GROUP BY, aggregate it, or declare `x` NOT NULL -SELECT x, y FROM t GROUP BY x, y; -``` - -### Functional dependency helpers take field indices instead of names - -`aggregate_functional_dependencies`, `get_target_functional_dependencies`, -`get_required_group_by_exprs_indices` and `get_required_sort_exprs_indices` in -`datafusion_common` now take, for each GROUP BY or ORDER BY expression, the -index of the input field it references (`Option`) instead of its name. -Matching by name gave incorrect results, because different expressions can -have the same name: `CAST(t.pk AS INT)` is named `t.pk`, but it does not -determine the columns that `t.pk` does. - -Queries are affected too: only a column reference to the key carries its -dependencies, so a query that selects other columns while grouping by an -expression over the key is now rejected, as in PostgreSQL and DuckDB. Group by -the key column itself instead: - -```sql --- `id` is the INT PRIMARY KEY of `t` -SELECT name FROM t GROUP BY CAST(id AS BIGINT); -- now an error -SELECT name FROM t GROUP BY id; -- ok -``` - -**Migration guide:** - -Pass `None` for an expression that computes a new value. For a column -reference, `datafusion_expr::utils::passthrough_field_index` returns the index: - -```rust,ignore -// Before -let names: Vec = exprs.iter().map(|e| e.schema_name().to_string()).collect(); -let target = get_target_functional_dependencies(schema, &names); - -// After -let indices: Vec> = exprs - .iter() - .map(|e| passthrough_field_index(e, schema)) - .collect(); -let target = get_target_functional_dependencies(schema, &indices); -``` - -### `FileSource::exact_filter` controls scan equivalence properties - -`FileScanConfig` no longer derives equivalence properties (constant columns -and equal columns) from `FileSource::filter`. It uses the new -`FileSource::exact_filter` method instead. This method returns the part of the -filter that every output row satisfies. A filter that the source uses only for -pruning (for example, Parquet row group statistics when -`datafusion.execution.parquet.pushdown_filters` is `false`) lets -non-matching rows through, and equivalences derived from it gave wrong query -results. - -`exact_filter` returns `None` by default. `ParquetSource` returns the pushed-down -conjuncts when `pushdown_filters` is enabled. - -**Migration guide:** - -If your custom `FileSource` applies its filter to every row, implement -`exact_filter` to keep the equivalence properties of the scan: - -```rust,ignore -impl FileSource for MySource { - fn exact_filter(&self) -> Option> { - self.filter() - } - // ... -} -``` - -### `TableProvider::scan` takes `Option<&[usize]>` for the projection - -Update the `scan` signature in your `TableProvider` implementation. - -```rust,ignore -// Before -async fn scan( - &self, - state: &dyn Session, - projection: Option<&Vec>, - filters: &[Expr], - limit: Option, -) -> Result>; - -// After -async fn scan( - &self, - state: &dyn Session, - projection: Option<&[usize]>, - filters: &[Expr], - limit: Option, -) -> Result>; -``` - -Use `projection.map(|p| p.to_vec())` if your implementation needs an owned -`Vec`. Callers holding an `Option>` can pass `.as_deref()`. - -`StreamingTableExec::try_new` also takes `Option<&[usize]>`. - -`datafusion_common::project_schema` now accepts unsized projections -(`projection: Option<&T> where T: AsRef<[usize]> + ?Sized`), so it takes both -`Option<&Vec>` and `Option<&[usize]>`; no caller changes are required. - -Besides being the more idiomatic signature, this lets -`TableProvider::scan_with_args`'s default body hand the projection straight to -`scan` instead of allocating a `Vec` that then has to be captured by the -returned future -- which is what made that method expensive to compile -(`datafusion-session` compiles ~3.3x faster as a result). - -### `TableProvider::scan_with_args` supports skip pushdown - -The `ScanArgs` struct now carries a `skip` field (the number of rows to skip) -alongside `limit`. After updating the `scan` signature above, providers can use -the default `scan_with_args`, which forwards to `scan`. Override -`scan_with_args` to handle `skip`. - -A new `TableProvider::supports_skip_pushdown() -> bool` (default `false`) -lets a provider guarantee it honors `ScanArgs::skip` exactly — that a scan -built with `skip` omits _exactly_ the first `skip` rows it would -otherwise have produced, not just approximately. `ListingTable` overrides this -to `true` and honors `skip`. - -DataFusion's SQL/DataFrame optimizer (`push_down_limit`) now populates -`LogicalPlan::TableScan::skip` from a query's `LIMIT ... OFFSET ...` clause, -but only when the scan's source reports `supports_skip_pushdown() == true`. -In that case the skip is moved entirely into the scan and the remaining -`Limit` above it no longer re-applies it; every other provider keeps today's -behavior unchanged, with the skip always enforced above the scan. `skip` is -also reachable directly, independent of the optimizer, by constructing a -`TableScan` (for example via `LogicalPlanBuilder::scan_with_filters_fetch_skip`) -or by calling `scan_with_args` with `ScanArgs::with_skip`. - -This pushdown is also preserved end-to-end through plan serialization: -`datafusion-substrait`'s producer folds a scan's `skip` into the `FetchRel` -it emits for the wrapping `Limit` (Substrait's `ReadRel` has no field of its -own for it), and `datafusion-proto`'s `ListingTableScanNode`, `ViewTableScanNode`, -and `CustomTableScanNode` messages gained optional `fetch`/`skip` fields so a -`TableScan`'s own `fetch`/`skip` — previously silently dropped — now -round-trips exactly. - -#### Who is affected - -- Custom `TableProvider` implementations that want skip pushdown: override - `scan_with_args` to read `ScanArgs::skip()` and honor it exactly, and - override `supports_skip_pushdown` to return `true`. Once you do, - `LIMIT ... OFFSET ...` queries against that provider will have their skip pushed - into the scan automatically. -- Callers that already build a scan through `ScanArgs`/`scan_with_args` (for - example custom query planners) can now also set `skip`. - -#### API breaks - -The _public_ `TableScan` struct has one new _public_ field - `skip` and -one field whose type is changed - `statistics_requests`. The addition of `skip` -field increases the size of `TableScan` and thus the size of `LogicalPlan` enum. To keep -the size of `LogicalPlan` reasonable the type of the `TableScan::statistics_requests` -field is changed from `BTreeSet` (24 bytes) to -`Box>` (8 bytes). -The users' applications are recommended to use `TableScanBuilder` to construct new -instances of `TableScan` instead of instantiating directly `TableScan { ... }` to avoid -the API breaks. - -#### Example - -```rust,ignore -let plan = provider - .scan_with_args( - &state, - ScanArgs::default() - .with_projection(projection) - .with_filters(Some(&filters)) - .with_limit(limit) - .with_skip(skip), - ) - .await? - .into_inner(); -``` - -### Extension `ExecutionPlan`s can decode without a `PhysicalExtensionCodec` - -`ExecutionPlan::try_to_proto` let a plan serialize itself, but there was no way back: decoding an extension node always routed through `PhysicalExtensionCodec::try_decode`. `PhysicalExtensionNode` carried no type discriminator, so the codec _was_ the discriminator. `ComposedPhysicalExtensionCodec` works around that by writing the position of the encoding codec into the payload, which means the decoding side must register the same codecs in the same order, and a name collision between two independent crates is undetectable. - -`PhysicalExtensionNode` now has an optional `plan_name`, and a session can map that name to a decoder. An extension plan implements `ExtensionPlanFromProto`, which pairs the name it is dispatched by with the constructor that rebuilds it, and is registered on the session that will decode it: - -```rust,ignore -use datafusion::physical_plan::proto::{ - ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx, ExtensionPlanFromProto, -}; - -impl ExecutionPlan for MyExec { - // ... - fn try_to_proto( - &self, - ctx: &ExecutionPlanEncodeCtx<'_>, - ) -> Result> { - // `extension_node` stamps `Self::NAME` on the node, so the name on the - // wire and the registry key cannot drift apart. - Ok(Some(ctx.extension_node::( - my_payload_bytes(self)?, - self.children(), - )?)) - } - -} - -impl ExtensionPlanFromProto for MyExec { - // Namespace the name so a collision with another crate is an error at - // registration rather than a wrong decode. - const NAME: &'static str = "my-crate.MyExec"; - - fn try_from_proto( - node: &PhysicalPlanNode, - ctx: &ExecutionPlanDecodeCtx<'_>, - ) -> Result> { - let extension = expect_plan_variant!(node, PhysicalPlanType::Extension, "Extension"); - let children = ctx.decode_children(&extension.inputs)?; - // `ctx.task_ctx()` is available here, so a plan that rebuilds session - // state at decode time (a connection pool, say) can do so. - my_plan_from_bytes(&extension.node, children) - } -} - -// On every session that decodes the plan — for a distributed engine, the -// workers as well as the coordinator. -let mut config = SessionConfig::new(); -config.update_extension(MyExec::register_proto)?; -``` - -Only extension plans implement `ExtensionPlanFromProto`, and registration is the trait's provided `register_proto` method. A built-in plan has a wire variant of its own and keeps its inherent `try_from_proto`, so `FilterExec::register_proto(&mut registry)` does not compile. - -`ProtoDecoderRegistry` is shared by every kind of extension DataFusion can decode, not only plans. Its key is the trait plus the name, so a plan and an expression may use the same name, and one session carries one registry rather than one per kind. - -A session carries one registry. Each library adds its decoders to it with `SessionConfig::update_extension`, which creates the registry if there is none. Do not attach a registry with `with_extension`: it replaces the registry, so it discards the decoders that other libraries added. - -```rust,ignore -// In each library that ships extension types: -pub fn register(config: &mut SessionConfig) -> Result<()> { - config.update_extension(MyExec::register_proto) -} - -// In the application that owns the session: -let mut config = SessionConfig::new(); -shuffle_lib::register(&mut config)?; -sampling_lib::register(&mut config)?; -``` - -The libraries need to know nothing about each other, and the order they are called in does not matter. Dispatch is by name, and a real name collision is an error from `register` rather than a wrong decode later. - -A registered plan needs no `PhysicalExtensionCodec` at all, and two crates' plans coexist on one session without a `ComposedPhysicalExtensionCodec`. - -**Who is affected:** - -- Nobody is required to change anything. This is opt-in per plan type: a `PhysicalExtensionNode` with no name, or with a name the decoding session does not know, takes the `PhysicalExtensionCodec` chain exactly as before. On the binary wire format the new field is additive: old writers omit it and old readers skip it. -- The generated JSON codec is stricter than the binary one. `pbjson` rejects a field it does not know, so a named node written by a new writer cannot be read as JSON by a reader on an older DataFusion. A plan that does not opt in writes no name and is unaffected. If you serialize plans as JSON across versions, upgrade the readers before you opt a plan in. -- Users constructing `PhysicalExtensionNode` with an exhaustive struct literal must set the new `plan_name` field (`None` reproduces the previous behavior). -- Replacing a `PhysicalExtensionCodec` with a registration changes only _how_ the payload is dispatched, not what the payload is. Readers running an older DataFusion ignore `plan_name` and hand the payload to their codec, so a mixed fleet keeps working only while the bytes your `try_to_proto` writes stay decodable by the codec you removed. - -`PhysicalExtensionCodec` is not deprecated: extension `PhysicalExpr`s and UDF payloads still need it, and it remains the fallback for unmigrated plans. - -See [issue #24625](https://github.com/apache/datafusion/issues/24625) for details. - -### `LogicalPlan` has the new variant `MaterializedCte` - -`WITH x AS MATERIALIZED (...)` is planned with the new variant `LogicalPlan::MaterializedCte(MaterializedCtePlan)`. `MaterializedCtePlan` has two cases: - -- `MaterializedCtePlan::Cte` has two inputs: the body of the CTE, which is computed once, and the continuation (the query that declared the CTE). Its output is the output of the continuation. -- `MaterializedCtePlan::Scan` is a leaf. It reads the buffered output of the `MaterializedCtePlan::Cte` that has the same id. - -#### Who is affected - -- Code that has an exhaustive `match` on `LogicalPlan` must add an arm for the new variant. -- A custom optimizer rule that moves a filter, limit or projection below a node must not move it into the body of a `MaterializedCte`, because all the scans of the CTE share the body. The continuation has no such limit. - -`MaterializedCteScan::find_in` returns the scans of one CTE in a plan, also in subquery expressions. - -### `LogicalPlan::DescribeTable` is replaced by `LogicalPlan::Show` - -`SHOW TABLES`, `SHOW COLUMNS`, `SHOW CREATE TABLE`, `SHOW FUNCTIONS`, `SHOW ` and `DESCRIBE` are now all -planned as the new `LogicalPlan::Show` variant `LogicalPlan::DescribeTable` and the `DescribeTable` struct are -removed. - -**Migration guide:** - -```rust -// 55.0.0 -LogicalPlan::DescribeTable(DescribeTable { schema, output_schema }) => { ... } - -// 56.0.0 -LogicalPlan::Show(Show { kind: ShowKind::Describe { schema }, output_schema }) => { ... } -LogicalPlan::Show(_) => { ... } // other SHOW statements -``` - -### Extension `PhysicalExpr`s can decode by name instead of through a codec - -`PhysicalExtensionExprNode` has a new optional `expr_name` field. An extension expression that sets it is decoded by a decoder registered on the session, not by a `PhysicalExtensionCodec`. This is the same mechanism extension `ExecutionPlan`s use (see above), and it uses the same `ProtoDecoderRegistry`. - -**Who is affected:** nobody, unless they opt in. A node with no name, or with a name the session has no decoder for, decodes through `PhysicalExtensionCodec::try_decode_expr` as before. Binary protobuf readers skip the new field. Readers that use the optional JSON serde reject unknown fields, so they must be built after this change to read a node that has `exprName`. - -**Opting in:** - -```rust,ignore -use datafusion::execution::TaskContext; -use datafusion::physical_plan::proto::{ - ExtensionExprFromProto, PhysicalExprDecodeCtx, PhysicalExprEncodeCtx, - extension_expr_node, -}; - -impl PhysicalExpr for MyExpr { - // ... - fn try_to_proto( - &self, - ctx: &PhysicalExprEncodeCtx<'_>, - ) -> Result> { - // Writes `Self::NAME` on the node. - Ok(Some(extension_expr_node::( - ctx, - my_payload_bytes(self)?, - self.children(), - )?)) - } -} - -impl ExtensionExprFromProto for MyExpr { - // Put the crate name in the name, so that a collision is an error at registration. - const NAME: &'static str = "my_crate.MyExpr"; - - fn try_from_proto( - node: &PhysicalExprNode, - ctx: &PhysicalExprDecodeCtx<'_>, - ) -> Result> { - // The session, for example to find a UDF by name. - let task_ctx = ctx.session::(); - // ... - } -} - -let mut config = SessionConfig::new(); -config.update_extension(MyExpr::register_proto)?; -``` - -Only extension expressions can be registered. `Column::register_proto(..)` does not compile. - -If a registered decoder fails, the decode fails. It does not fall back to the codec, because the codec could decode a payload that it did not write. Changing an expression to write its own payload is therefore a wire-format change for that expression: register the type on every reader before writers start to use it. - -`PhysicalExprDecodeCtx::session::()` is new. It gives the session the decode runs under. `datafusion-proto` supplies its `TaskContext`. A custom `PhysicalExprDecode` implementation returns `None` by default. - -See [issue #24626](https://github.com/apache/datafusion/issues/24626) for details. - -### Order-preservation hooks for limit pushdown are deprecated - -A file scan that advertises an output ordering now always reads its files in -order, so `ORDER BY ... LIMIT` queries no longer depend on `LimitPushdown` -telling the scan to keep its order. Before this change, pushing the fetch of a -`SortPreservingMergeExec` into an ordered Parquet scan could return the wrong -rows, because the scan then shared files between partitions or skipped row -groups based on its limit. - -The plumbing that carried this request is deprecated and no longer used: - -- `ExecutionPlan::with_preserve_order` and `DataSource::with_preserve_order` - are never called. Built-in operators no longer override them. Overrides in - custom `ExecutionPlan` or `DataSource` implementations are now dead code, - and the compiler does not warn about them, because `#[deprecated]` on a - trait method only warns callers. -- A custom scan that advertises an output ordering must keep that order by - itself, also when a limit is pushed into it with `with_fetch`. DataFusion no - longer tells it whether the limit is order-sensitive. -- `GlobalLimitExec::required_ordering` and `LocalLimitExec::required_ordering` - always return `None`, and their `set_required_ordering` methods do nothing. - The `required_ordering` protobuf fields are no longer written and are - ignored when read. - -A plain `LIMIT` without `ORDER BY` over a table with a declared ordering now -also reads files in order, so it no longer uses file work stealing or Parquet -limit pruning. Other queries over such tables already read files in order. If -the file groups are uneven, for example a few large files next to many small -ones, a selective `WHERE ... LIMIT` can be slower than before. - -**Migration guide:** - -To keep a file scan's order, give it an output ordering -(`FileScanConfigBuilder::with_output_ordering`). To read files in group order -without declaring one, use `FileScanConfigBuilder::with_preserve_order(true)`. -Code that reads `FileScanConfig::preserve_order` to decide whether files may be -reordered should call `FileScanConfig::preserves_file_order()` instead, which -also accounts for the output ordering. - -### `LogicalPlan::map_expressions` re-derives a `Projection`'s schema - -When `LogicalPlan::map_expressions` rewrites any expression of a `Projection`, -it now derives the output schema again from the new expressions instead of -keeping the old one. See [#24281]. - -**Who is affected:** - -- Renaming rewrites, such as `unalias`, now change the returned plan's - `schema()`. -- Rewrites whose new expressions reference columns of an input that is only - installed afterwards (for example with `with_new_exprs`) now fail with a - schema error on a `Projection`. - -**Migration guide:** - -For the second case, rewrite the `Projection`'s `expr` directly instead of -through `map_expressions`, and build the projection once the new input is in -place, with `Projection::try_new`, or with `Projection::try_new_with_schema` to -keep a schema you already have. - -[#24281]: https://github.com/apache/datafusion/pull/24281 - -### `SanityCheckPlan` is deprecated and no longer in the default physical optimizer rules - -The physical planner now runs the `SanityCheckPlan` check itself on the final -plan, after every physical optimizer rule. This includes rules added with -`SessionStateBuilder::with_physical_optimizer_rule` and custom rule lists. When -the ordering or distribution requirements do not hold, the error names the rule -that broke them. `EXPLAIN VERBOSE` no longer prints a -`physical_plan after SanityCheckPlan` line. - -To upgrade, remove `SanityCheckPlan` from custom rule lists, and drop code that -looks it up in `PhysicalOptimizer::new()`. Code that runs optimizer rules -without the physical planner can call -`datafusion_physical_optimizer::sanity_checker::check_plan_tree_sanity` on the -final plan instead. - -A custom rule list that left out `SanityCheckPlan` is now checked too. A plan -whose requirements do not hold, such as a `SortMergeJoinExec` over unsorted -input, now fails to plan instead of possibly returning wrong results. - -### `AggregateUDFImpl::is_nullable` is deprecated - -`AggregateUDFImpl::is_nullable` is deprecated; set the nullability in the field -returned by `AggregateUDFImpl::return_field` instead. The compiler does not -warn about existing overrides. Keep them, consistent with `return_field`, -until the method is removed, as callers of the deprecated method still use them. - -**Migration guide:** - -```rust,ignore -// Before -fn is_nullable(&self) -> bool { - false -} - -// After -fn return_field(&self, _arg_fields: &[FieldRef]) -> Result { - Ok(Arc::new(Field::new(self.name(), DataType::Int64, false))) -} - -fn is_nullable(&self) -> bool { - false -} -``` - -See [issue #18882](https://github.com/apache/datafusion/issues/18882) for details. - -### Map casts with nested Structs use schema-evolution rules - -Casts of a `Map` whose key or value recursively contains a `Struct` now adapt -nested Struct fields by case-sensitive name. Nullable fields added to the target -Struct are filled with `NULL`, and source-only fields are omitted. Missing -non-nullable target fields, nullable-to-non-nullable changes, and incompatible -nested types are rejected. - -Map keys define map identity. During this nested-Struct adaptation, key Struct -fields cannot be removed and primitive key type changes must preserve every -source value (for example, `Int32` to `Int64` is allowed, while `Int64` to -`Int32` is rejected). Sorted Maps also require an unchanged key type and the -same sorted flag. - -**Migration guide:** Schemas that relied on positional Struct-field matching, -key-field removal, or narrowing Map-key casts must be updated to retain -case-sensitive field names and key identity. Ordinary Maps without semantic -Struct children continue to use Arrow's normal Map cast behavior. - -### `ExprType` gained a `SqlSimilarToPattern` variant - -`SIMILAR TO` with a non-literal (column- or expression-based) pattern is now -represented by a new `SqlSimilarToPattern` physical expression, so it can be -serialized. The generated `ExprType` enum on `PhysicalExprNode` gained a -matching `SqlSimilarToPattern` variant (tag 28). - -**Who is affected:** - -- Users matching exhaustively on `ExprType` (for example in a custom - physical-plan encoder/decoder). - -**Migration guide:** - -Add a `SqlSimilarToPattern` arm, or fall back to a wildcard arm: - -```rust,ignore -match expr_type { - // ... - ExprType::SqlSimilarToPattern(node) => { /* ... */ } - _ => { /* ... */ } -} -``` - -Plans encoded before this variant existed are unaffected: they never produced -this variant, so decoding is unchanged. Plans containing a dynamic -`SIMILAR TO` pattern encoded after this change fail to decode on older -readers that don't recognize the new tag. - -See [PR #23188](https://github.com/apache/datafusion/pull/23188) for details. - -### `SortProperties::and_or` replaced by `and` and `or` - -`datafusion_expr_common::sort_properties::SortProperties::and_or` has been -removed. Call `and` for `AND` and `or` for `OR`: - -```rust,ignore -// Before (55.0.0) -let props = lhs.and_or(&rhs); - -// After (56.0.0) -let props = lhs.and(&rhs); // for AND -let props = lhs.or(&rhs); // for OR -``` - -The two operators do not preserve the same sort orders. `AND` keeps an ordering -only when nulls sort after `true` (`ASC NULLS LAST` or `DESC NULLS FIRST`), and -`OR` only when nulls sort before `false` (`ASC NULLS FIRST` or -`DESC NULLS LAST`). `and_or` did not say which operator the caller meant, so it -could not be right for both. - -See [PR #24276](https://github.com/apache/datafusion/pull/24276) for details. - -### RANGE window frames with offsets now reject ORDER BY types without arithmetic - -A `RANGE` frame offset such as `1 PRECEDING` is measured in `ORDER BY` values -rather than in rows, so the frame bound is computed as `current_value - 1`. That -requires arithmetic on the `ORDER BY` type. For types that have no such -arithmetic -- `Utf8`, `Binary`, `Boolean`, `List` and `Null` -- such frames are -now rejected when the query is planned: - -```sql -SELECT x, COUNT(*) OVER (ORDER BY x RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) -FROM (VALUES ('a'), ('b'), ('c')) t(x) -ORDER BY x; --- Error during planning: RANGE with offset PRECEDING/FOLLOWING is not supported for ORDER BY type Utf8 -``` - -What this replaces depends on the `ORDER BY` type. Over `Utf8`, `Boolean` and -`List` keys such queries planned successfully, and in DataFusion 54 and 55 the failing -frame-bound arithmetic was silently treated as an overflow -([#22140](https://github.com/apache/datafusion/pull/22140)): the bound collapsed -to the partition edge, and the query returned results computed over that wrongly -widened frame instead of an offset window. DataFusion 53 and earlier failed -during execution with an arithmetic error. Rows whose order key value was `NULL` -never reached the arithmetic, so queries where every order key value was `NULL` -returned correct results throughout; those also now fail at planning. Over a -`Null`-typed key the offset itself failed to coerce, erroring at planning time -with `Cast error: Casting from Utf8 to Null not supported`, and binary keys were -rejected for every `RANGE` frame with the internal error quoted below -- for -those two, only the error message changes. - -Such an `ORDER BY` type is still usable with the `UNBOUNDED PRECEDING`, -`CURRENT ROW` and `UNBOUNDED FOLLOWING` bounds, which are located by comparing -`ORDER BY` values rather than by computing them. Binary order keys additionally -gained support for those bounds in this release, having previously failed with -`Internal error: Cannot run range queries on datatype: Binary`. - -**Who is affected:** - -- Queries using `offset PRECEDING` or `offset FOLLOWING` in a `RANGE` frame over - a non-numeric, non-temporal `ORDER BY` key. To count rows rather than compare - values, use a `ROWS` frame; to include everything up to the partition edge, - use `UNBOUNDED PRECEDING` or `UNBOUNDED FOLLOWING`. - -See [issue #24327](https://github.com/apache/datafusion/issues/24327) for details. diff --git a/docs/source/library-user-guide/upgrading/57.0.0.md b/docs/source/library-user-guide/upgrading/index.md similarity index 91% rename from docs/source/library-user-guide/upgrading/57.0.0.md rename to docs/source/library-user-guide/upgrading/index.md index 9621d51aa9f23..4870237ac2acd 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -4,7 +4,9 @@ SPDX-FileCopyrightText: See the NOTICE file distributed with this work for addit SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements --> -# Upgrade Guides +# Upgrade Guide + +For released versions, see [Past Upgrade Guides](#past-upgrade-guides). ## DataFusion 57.0.0 @@ -372,3 +374,21 @@ simplify expressions such as `col IS NULL` on them. Row values are unchanged, but schema inspection can differ: code that compares the resulting schema against a hand-written one with `nullable: true` for every field needs to be updated. + +## Past Upgrade Guides + +The upgrade guides for released versions are in the documentation for each +release: + +- [DataFusion 56.0.0](https://datafusion.apache.org/versions/56.0.0/library-user-guide/upgrading/56.0.0.html) +- [DataFusion 55.0.0](https://datafusion.apache.org/versions/55.2.0/library-user-guide/upgrading/55.0.0.html) +- [DataFusion 54.0.0](https://datafusion.apache.org/versions/54.1.0/library-user-guide/upgrading/54.0.0.html) +- [DataFusion 53.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/53.0.0.html) +- [DataFusion 52.0.0](https://datafusion.apache.org/versions/52.0.0/library-user-guide/upgrading.html#datafusion-52-0-0) +- [DataFusion 51.0.0](https://datafusion.apache.org/versions/51.0.0/library-user-guide/upgrading.html#datafusion-51-0-0) +- [DataFusion 50.0.0](https://datafusion.apache.org/versions/50.0.0/library-user-guide/upgrading.html#datafusion-50-0-0) +- [DataFusion 49.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/49.0.0.html) +- [DataFusion 48.0.1](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.1.html) +- [DataFusion 48.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/48.0.0.html) +- [DataFusion 47.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/47.0.0.html) +- [DataFusion 46.0.0](https://datafusion.apache.org/versions/53.0.0/library-user-guide/upgrading/46.0.0.html) diff --git a/docs/source/library-user-guide/upgrading/index.rst b/docs/source/library-user-guide/upgrading/index.rst deleted file mode 100644 index e3cdacc104f39..0000000000000 --- a/docs/source/library-user-guide/upgrading/index.rst +++ /dev/null @@ -1,23 +0,0 @@ -.. SPDX-License-Identifier: Apache-2.0 -.. SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership -.. SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements - -Upgrade Guides -============== - -.. toctree:: - :maxdepth: 1 - - DataFusion 57.0.0 <57.0.0> - DataFusion 56.0.0 <56.0.0> - DataFusion 55.0.0 <55.0.0> - DataFusion 54.0.0 <54.0.0> - DataFusion 53.0.0 <53.0.0> - DataFusion 52.0.0 <52.0.0> - DataFusion 51.0.0 <51.0.0> - DataFusion 50.0.0 <50.0.0> - DataFusion 49.0.0 <49.0.0> - DataFusion 48.0.1 <48.0.1> - DataFusion 48.0.0 <48.0.0> - DataFusion 47.0.0 <47.0.0> - DataFusion 46.0.0 <46.0.0> From 59d5744dfb9079982bbba9c31402890a5ff52185 Mon Sep 17 00:00:00 2001 From: Andrew Lamb Date: Sun, 29 Nov 2026 07:29:02 -0500 Subject: [PATCH 3/4] docs: reword the past upgrade guides intro Co-Authored-By: Claude Fable 5.2 --- docs/source/library-user-guide/upgrading/index.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index 4870237ac2acd..9ec1a0ee9896f 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -377,8 +377,7 @@ every field needs to be updated. ## Past Upgrade Guides -The upgrade guides for released versions are in the documentation for each -release: +The upgrade guides for released versions can be found here: - [DataFusion 56.0.0](https://datafusion.apache.org/versions/56.0.0/library-user-guide/upgrading/56.0.0.html) - [DataFusion 55.0.0](https://datafusion.apache.org/versions/55.2.0/library-user-guide/upgrading/55.0.0.html) From 02be46256d5df600ee731c304f6a847739edead2 Mon Sep 17 00:00:00 2001 From: Andrew Lamb Date: Sun, 29 Nov 2026 07:29:30 -0500 Subject: [PATCH 4/4] docs: note that the upgrade guide redirects keep old permalinks working Co-Authored-By: Claude Fable 5.2 --- docs/source/conf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/source/conf.py b/docs/source/conf.py index 667864458f44f..8cdfb4321fee9 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -148,6 +148,7 @@ "library-user-guide/upgrading": "/library-user-guide/upgrading/index.html", "library-user-guide/upgrading/57.0.0": "index.html", # Upgrade guides for past releases are in the versioned documentation + # Keep old permalinks still working "library-user-guide/upgrading/56.0.0": "https://datafusion.apache.org/versions/56.0.0/library-user-guide/upgrading/56.0.0.html", "library-user-guide/upgrading/55.0.0": "https://datafusion.apache.org/versions/55.2.0/library-user-guide/upgrading/55.0.0.html", "library-user-guide/upgrading/54.0.0": "https://datafusion.apache.org/versions/54.1.0/library-user-guide/upgrading/54.0.0.html",