Upgrade Guides#
DataFusion 57.0.0#
Note: DataFusion 57.0.0 has not been released yet. The information provided
in this section pertains to features and changes that have already been merged
to the main branch and are awaiting release in this version.
Removed temporary aggregation migration flag#
The datafusion.execution.enable_migration_aggregate flag provided a temporary
fallback during the aggregation refactor: setting it to false selected the old
implementation if users encountered a bug in the new one. As previously documented,
the flag and old implementation have now been removed after the 56.0.0 release.
See tracking issue #25902 for
background.
Remove any explicit setting of this flag from your configuration, including any
use of the ExecutionOptions::enable_migration_aggregate Rust field. No replacement
is needed. The new implementation was already enabled by default, so default query
behavior is unchanged.
ParquetSinks created by ParquetFormat no longer retain written file metadata#
ParquetSink keeps the ParquetMetaData of every file it writes so that it can
be read back with ParquetSink::written(). That is unchanged for sinks you
construct yourself. Retention can now be turned off with
ParquetSink::with_retain_written_metadata(false), and the sinks that
ParquetFormat::create_writer_physical_plan builds for COPY and INSERT do
so: nothing on that path reads the metadata, and keeping it made the memory of a
statement grow with the number of files written (see #27026). If you relied on
downcasting the sink of such a plan to call written(), construct the
ParquetSink yourself instead.
The retention setting is not part of the protobuf encoding of a ParquetSink.
A sink decoded with datafusion-proto, for example on a remote executor of a
distributed engine, is built with ParquetSink::new and retains metadata again,
even if the sink that was encoded had turned it off.
Range partitioning accepts equal split points#
datafusion_common::validate_range_split_points and the logical and physical
RangePartitioning constructors now accept equal adjacent split points.
Previously, split points had to be strictly ordered; they must now be
non-decreasing according to the supplied sort options. Equal adjacent split
points describe empty partitions. Keys equal to a repeated split point go to the
partition after its last occurrence.
Callers that relied on duplicate rejection must additionally reject adjacent points that compare equal under those sort options.
New field dictionary_read_max_distinct_values added to ParquetOptions#
ParquetOptions gained dictionary_read_max_distinct_values: Option<usize>.
Some(cap) enables dictionary inference and promotes eligible top-level string
and binary columns only when every data page is dictionary encoded and
the per-file sum of row-group cardinality upper bounds is at most cap. Missing
NDVs use the non-null row count when available and otherwise use the row count.
The cap takes precedence over enable_rle_to_dictionary. It does not demote a
dictionary type declared by a file’s embedded Arrow schema; a field that is
dictionary in one file and plain in another is still merged as plain.
Large row-group dictionaries can be slower because each output batch can retain the whole dictionary. Benchmark representative data before setting a high cap.
Exhaustive Rust and generated protobuf ParquetOptions literals must add this
field as None or use ..Default::default(). The wire format is compatible.
Substrait consumers use explicit scope context#
Add a final &SubstraitConsumerContext argument to custom relation and expression
callbacks on SubstraitConsumer. Forward it when calling conversion helpers or
consuming child relations and expressions.
Remove implementations of push_outer_schema, pop_outer_schema,
get_outer_schema, push_lambda_parameters, pop_lambda_parameters, and
lambda_variable, and remove embedded DefaultSubstraitLambdaConsumer values.
Use the context’s get_outer_schema and lambda_variable methods to resolve
outer references and lambda parameters. To enter a scope, derive a child with
context.with_outer_schema(...) or context.with_lambda_parameters(...) and pass
it to nested conversions. No pop operation is needed; the parent stays unchanged.
from_substrait_plan and from_substrait_plan_with_consumer create the root
context. For a new conversion started directly through a helper, pass
&SubstraitConsumerContext::default(). Nested conversions must receive the current
context.
Custom scoped values can be stored with context.with_extension(Arc::new(value))
and retrieved with context.get_extension::<MyScope>(). Pass the returned child
context to nested conversions. Children inherit values; replacing a value leaves
parents and siblings unchanged. The values themselves are shared through Arc.
Update logical-plan snapshots if needed: generated lambda parameter names are local to lexical scopes, so sibling lambdas may reuse names.
NULL results of set-monotonic aggregate UDFs#
A UDAF that returns SetMonotonicity::Increasing or Decreasing must return a
non-NULL result once it has seen a non-NULL input, and must not go back to NULL as
more inputs are added. Window ordering inference relies on this; see SetMonotonicity.
AggregateFunctionExpr::get_result_ordering now describes an ever-expanding
frame with NULLS FIRST. PlainAggregateWindowExpr::add_equal_orderings is
deprecated because it does not check the frame bounds or FILTER predicate;
inspect the window execution plan’s equivalence properties instead.
GroupClusteringMode::Full no longer implies sorted input#
AggregateExec can now select GroupClusteringMode::Full when the input’s
equivalence properties declare the complete GROUP BY tuple as grouped
(contiguous within each partition), even if the input is not sorted.
Full describes group contiguity only. Code that previously used
group_clustering_mode() == GroupClusteringMode::Full to infer sorted input or
output should use properties().output_ordering() on the input or aggregate
plan, respectively.
datafusion-spark moved to its own repository#
The datafusion-spark crate is now developed and released in
apache/datafusion-spark, starting
with 57.0.0. The crate name is unchanged.
datafusion-cli no longer has a --spark flag. The Spark SQL dialect is still
available without the Spark function library:
SET datafusion.sql_parser.dialect = 'spark';
SparkOptions, MapKeyDedupPolicy, and ConfigOptions::spark removed#
SparkOptions and MapKeyDedupPolicy have been removed from
datafusion_common::config, along with the ConfigOptions::spark field and the
built-in datafusion.spark.map_key_dedup_policy key. The
datafusion-spark extension now
defines SparkOptions as a ConfigExtension with the prefix spark.
SessionStateBuilder::with_spark_features() registers the extension. To
register it manually, use
SessionConfig::with_option_extension(SparkOptions::default()). Once
registered, use the new key:
SET spark.map_key_dedup_policy = 'LAST_WIN';
ParquetFileReaderFactory adds Any as a supertrait#
To enable downcasting of dyn ParquetFileReaderFactory to concrete factory
types (via is::<T>() / downcast_ref::<T>()), the
ParquetFileReaderFactory trait now has Any as a supertrait:
- pub trait ParquetFileReaderFactory: Debug + Send + Sync + 'static
+ pub trait ParquetFileReaderFactory: Any + Debug + Send + Sync
The trait already required 'static, which Any implies, so existing
implementations need no changes. ParquetSource::parquet_file_reader_factory
returns the trait object to downcast.
COPY TO ordering#
COPY TO no longer guarantees preservation of its input’s ordering. Add an
explicit ORDER BY when output order matters.
Previously, if t had an existing output ordering of ORDER BY c1, the COPY TO
statement could infer and maintain that order in the written file.
COPY (SELECT * FROM t) TO 'ordered.parquet';
Now, an explicit ORDER BY c1 clause is required to preserve this behavior. In
this case, no extra sorting is needed during execution; this is a syntax change
that aligns with the SQL specification.
COPY (SELECT * FROM t ORDER BY c1) TO 'ordered.parquet';
PARTITIONED BY column names are normalized like other identifiers#
PARTITIONED BY column names in COPY TO and CREATE EXTERNAL TABLE are now
normalized the same way as other SQL identifiers. Unquoted names are lowercased
when datafusion.sql_parser.enable_ident_normalization is enabled (the default),
and quoted names keep their exact spelling without the quotes. Previously, a
quoted name such as "'p'" kept its quotes, so it did not match the column 'p',
and an unquoted name such as P was not lowercased. See
#9714 for details.
Quote partition column names that contain uppercase letters, for example
PARTITIONED BY ("Year") for a Year=2024/ directory layout, or
COPY t TO ... PARTITIONED BY ("Year") for a source column named "Year".
The Rust fields CopyToStatement::partitioned_by and
CreateExternalTable::table_partition_cols in datafusion_sql::parser changed
from Vec<String> to Vec<Ident>. Use Ident::new("p") to build an unquoted
name, or Ident::with_quote('"', "P") to build a quoted one.
Deprecated Expr::Wildcard has been removed#
Expr::Wildcard has been deprecated since version 46.0.0, and has been removed.
For counting rows, use count_all() or count_all_window().
It has also been removed from the Protobuf and Substrait based serialization.
Statistics must have one ColumnStatistics per schema field#
Planning now fails with an error if an ExecutionPlan or StatisticsProvider
reports a different number of Statistics::column_statistics than its schema
has fields. Before, this could panic or return another column’s values.
Start from Statistics::new_unknown, or project a child’s statistics with
Statistics::project if the plan changes its columns:
let statistics = Statistics::new_unknown(&self.schema())
.with_num_rows(Precision::Exact(num_rows));
Materialized CTE scans have a projection#
MaterializedCteScan and MaterializedCteScanExec have a projection. It gives
the indexes of the columns of the CTE body that the scan outputs. None means all
the columns. OptimizeProjections uses it to remove from the body the columns
that no scan reads.
A custom optimizer rule that changes the schema of the body of a
MaterializedCte must also change the projection of every scan of that CTE,
because a scan reads the columns of the body by position. Use
MaterializedCteScan::with_body_columns to remap a scan, and
MaterializedCteScan::with_body_schema to give a scan the new types of the
columns that it reads.
The schema and projection fields of MaterializedCteScan are private, so
that the two always match. Read them with MaterializedCteScan::schema and
MaterializedCteScan::projection. Build a scan with MaterializedCteScan::new
and MaterializedCteScan::with_projection. To build a physical scan with a
projection, use MaterializedCteScanExec::with_body_projection. It returns an
error if the projection does not have one index for each column of the scan
schema.
LogicalPlan::check_invariants checks that each scan of a MaterializedCte
has the names and types of the columns that it reads from the body. The
optimizer runs this check after each rule in debug builds, so a custom rule
that does not remap the scans now fails with an error that names the rule.
Null-aware sort-merge joins add a protobuf field#
SortMergeJoinExec now supports null-aware (NOT IN) semantics for
uncorrelated, single-key LeftAnti joins without a join filter.
The existing seven-argument SortMergeJoinExec::try_new continues
to create a non-null-aware join. Enable null-aware semantics with
.with_null_aware(true)?:
let exec = SortMergeJoinExec::try_new(
left,
right,
on,
None,
JoinType::LeftAnti,
vec![SortOptions::new(false, true)], // ASC NULLS FIRST
NullEquality::NullEqualsNothing,
)?
.with_null_aware(true)?;
Both inputs must have a single partition when executed.
The generated protobuf SortMergeJoinExecNode type has a new
null_aware field. Exhaustive struct literals must initialize it;
false preserves the previous behavior:
let node = SortMergeJoinExecNode {
left,
right,
on,
join_type,
filter,
sort_options,
null_equality,
projection,
null_aware: false,
};
A binary protobuf payload without this field decodes with
null_aware = false. A 56.x reader ignores the field and executes a plain
anti join, which can return incorrect results for a null-aware plan. Upgrade
all plan readers before sending plans with null_aware = true.
aggregate_functional_dependencies is deprecated#
aggregate_functional_dependencies is deprecated; use
aggregate_functional_dependencies_with_computed_inputs instead. Its new
computed_input_indices: &[Option<Vec<usize>>] parameter lists, for each GROUP
BY expression, the input fields that a deterministic computed expression reads,
or is None for a column reference or a volatile expression. A computed
expression is determined by a key when every field it reads is, so the key
stays a key of the aggregate output. The deprecated function treats every
computed expression as not determined.
Migration guide:
// Before
let deps = aggregate_functional_dependencies(input_schema, &group_by_input_indices, aggr_schema);
// After
let deps = aggregate_functional_dependencies_with_computed_inputs(
input_schema,
&group_by_input_indices,
&computed_input_indices,
aggr_schema,
);
See issue #27112 for details.
CreateFunction argument and return types are FieldRefs#
OperateFunctionArg::data_type is replaced by OperateFunctionArg::field, and
CreateFunction::return_type by CreateFunction::return_field. Both are now
FieldRefs instead of DataTypes, so CREATE FUNCTION can declare argument
and return types that need field metadata, such as extension types
(CREATE FUNCTION f(id UUID) RETURNS UUID ...). The argument field is named
after the argument, or "" if the argument has no name. The return field has
the name "".
Migration guide:
// Before
let arg_types: Vec<DataType> = args.iter().map(|a| a.data_type.clone()).collect();
let return_type: Option<DataType> = definition.return_type;
// After
let arg_types: Vec<DataType> = args.iter().map(|a| a.field.data_type().clone()).collect();
let return_type: Option<DataType> = definition
.return_field
.map(|field| field.data_type().clone());
CreateFunction::try_new takes Option<FieldRef> for the return type.
See issue #18235 for details.
New match_columns_by_header field on CSV options#
datafusion_common::config::CsvOptions and datafusion::prelude::CsvReadOptions
have a new public field, match_columns_by_header, which maps CSV file columns
to the table schema by header name instead of by position. The protobuf
messages CsvOptions and CsvScanExecNode gained the same field.
Code that constructs these structs with an exhaustive struct literal must add
the field or use ..Default::default(). Builder methods are unaffected:
// 56.0.0
let options = CsvReadOptions {
has_header: true,
..Default::default()
};
// 57.0.0
let options = CsvReadOptions::new()
.has_header(true)
.match_columns_by_header(true);
DataFrames built from arrays derive field nullability from the data#
DataFrame::from_columns and the dataframe! macro used to mark every field
as nullable. They now mark a field as nullable only when its array may contain
nulls (Array::is_nullable); the new DataFrame::from_arrays follows the same
rule. Columns without nulls get a non-nullable schema, which lets the optimizer
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.